Merge sk/features-on-rynth-main (synced with rynth/main) into feat/mini-remote-drawer
Co-authored-by: Cursor <cursoragent@cursor.com> # Conflicts: # Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs
This commit is contained in:
commit
4f2168da36
160 changed files with 15447 additions and 2566 deletions
37
Changelog/2026-10-08-merge-rynth-main-into-pr2.md
Normal file
37
Changelog/2026-10-08-merge-rynth-main-into-pr2.md
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
# 2026-10-08 - Merge rynth/main (2026.10.6.1 .. 2026.10.8.1) into sk/features-on-rynth-main
|
||||
|
||||
Brings PR #2 up to date with rynth/main so it merges cleanly. No new features.
|
||||
|
||||
## Where rynth/main already had the same feature, rynth/main's version wins
|
||||
|
||||
- **Install paths.** `Plugins/Shared/RynthInstallPaths.cs` (read-only, byte-identical with
|
||||
RynthCore's copy) replaces PR #2's `Shared/RynthInstallPaths.cs`. RynthAi and the Monster
|
||||
Editor now link the shared file.
|
||||
- **Item info.** rynth/main's `/ra iteminfo` (one Mag-style chat line, item info on select,
|
||||
skips RynthAi's own selections) replaces PR #2's Mag-Tools port. Removed:
|
||||
`ItemInfo/MagItemDescriber.cs`, `MagItemInfoSettings.cs`, `MagItemInfoTables.cs`,
|
||||
`LegacyUi/LegacyItemInfoUi.cs`, `RynthAiItemInfo.cs`, the Item Info window, the click
|
||||
trigger, the `iteminfo` remote action and `SpellDatabase.TryGetSpellMeta`. `/ra ii` stays as
|
||||
a short alias. The richer options can come back later as a follow-up on top of
|
||||
rynth/main's version.
|
||||
- **Pet essence refills.** rynth/main's "server said full" trust and refill-loop parking
|
||||
(`OnServerSaidFull`, `RefillLooping`) replace PR #2's equivalents. PR #2's extra stays: with
|
||||
summon-on-empty (pyreal-refill charm) on, an essence that still reports empty is parked.
|
||||
- **Object filing.** rynth/main's `FileTypedObject` / `WhoHas` (other players' wielded gear is
|
||||
not ours or loot) replaces PR #2's `PlaceTypedObject`.
|
||||
- **Spell metadata.** rynth/main's `_spellMeta` (category, power) and `_idsByCategory`.
|
||||
- **Monster Editor.** rynth/main's `Category` / `MatchExpression`; PR #2's
|
||||
`PreferredAmmoItemId` and `Clone()` stay, and `Clone()` / `CopyCombatSettingsFrom` now copy
|
||||
`UseWall` (and `Clone()` the extra fields).
|
||||
|
||||
## Kept from both sides
|
||||
|
||||
- Chat: `OnChatLocalFeatures` (PR #2) and the hazard chat check (rynth/main).
|
||||
- Monster Editor JSON: the UB seed type (PR #2), case-insensitive reads (rynth/main).
|
||||
- Host tests: `AttributeRaiserTests` (PR #2) and rynth/main's new suites.
|
||||
|
||||
## Checks
|
||||
|
||||
- Release builds: RynthAi, Monster Editor, Loot Editor, RynthAiTests.
|
||||
- RynthAiHostTests: 558 passed, 4 known; the 1 failure is the map-bake check that needs the
|
||||
real dats (fails the same way without this merge).
|
||||
|
|
@ -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,
|
||||
|
|
@ -47,7 +49,9 @@ public enum StringValueKey
|
|||
|
||||
/// <summary>
|
||||
/// STypeFloat keys used with TryGetObjectDoubleProperty / WorldObjectCache.GetDoubleProperty.
|
||||
/// Values match Chorizite's STypeFloat sequential enum.
|
||||
/// Values match ACE's PropertyFloat and Chorizite's STypeFloat (UNDEF = 0). WeaponOffense and
|
||||
/// DamageMod were 61/62 until 2026-10-05 (61 is EconRecoveryInterval), so a native "damage
|
||||
/// percent" loot rule read the weapon's attack mod; PowerLevel/AccuracyLevel were 86/87.
|
||||
/// </summary>
|
||||
public enum DoubleValueKey
|
||||
{
|
||||
|
|
@ -57,10 +61,10 @@ public enum DoubleValueKey
|
|||
MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised
|
||||
WeaponDefense = 29,
|
||||
UseRadius = 54,
|
||||
WeaponOffense = 61,
|
||||
DamageMod = 62,
|
||||
PowerLevel = 86,
|
||||
AccuracyLevel = 87,
|
||||
WeaponOffense = 62,
|
||||
DamageMod = 63,
|
||||
PowerLevel = 92,
|
||||
AccuracyLevel = 93,
|
||||
}
|
||||
|
||||
// ── Combat mode int constants (matches acclient.exe CM_Combat enum) ────────
|
||||
|
|
@ -117,13 +121,34 @@ 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);
|
||||
|
||||
// Decal's synthetic keys that are a plain int property (MaxDamage = Damage 44, Coverage =
|
||||
// ClothingPriority 4, ...) read as that property, from the overlay or live. The icon and
|
||||
// spell ones are data ids: WorldObjectCache.GetIntProperty answers them.
|
||||
uint decalStype = WorldObjectCache.DecalIntStype(unchecked((uint)key));
|
||||
if (decalStype != 0)
|
||||
return Values(unchecked((int)decalStype), 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)
|
||||
|
|
|
|||
|
|
@ -158,6 +158,15 @@ public class BuffManager : IDisposable
|
|||
private readonly Dictionary<int, DateTime> _buffFailCooldownUntil = new();
|
||||
private const double BuffFailCooldownSec = 120.0;
|
||||
|
||||
// A vital spell LEVEL the server refused for missing components (Revitalize, Heal, Stamina
|
||||
// to Mana...): that level is passed over for NoComponentsLevelSec and the next lower level
|
||||
// with components is cast instead. It used to park the whole family, then retry the same
|
||||
// top level the character had no components for (2026-10-08).
|
||||
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
|
||||
private const double NoComponentsLevelSec = 600.0;
|
||||
private bool LevelLacksComponents(int spellId)
|
||||
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && DateTime.Now < until;
|
||||
|
||||
// Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil
|
||||
// (which catches chat-explicit hard rejects). This catches the /god case:
|
||||
// skill is Trained → IsSkillUsable says yes → BuildDynamicBuffList includes
|
||||
|
|
@ -328,6 +337,16 @@ public class BuffManager : IDisposable
|
|||
// stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield
|
||||
// the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never
|
||||
// loop forever; on exhaustion the buff family is parked and the bot fights unbuffed.
|
||||
// Switch like a player (2026-10-06): a use of the wand goes through ClientUISystem::UseObject,
|
||||
// the client's double-click, which puts the weapon in hand away by itself (ACE's
|
||||
// DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items
|
||||
// automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it,
|
||||
// then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't
|
||||
// got the wand into the hand in WieldResolveTimeoutMs, this session moves the weapon first.
|
||||
private bool _directWandSwapFailed;
|
||||
// The swap gate's claim count when the wand's use went out: a later claim means another swap
|
||||
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
|
||||
private long _pendingWieldClaim;
|
||||
private int _bowDequipPendingId;
|
||||
private DateTime _bowDequipAt = DateTime.MinValue;
|
||||
private int _bowDequipAttempts;
|
||||
|
|
@ -466,6 +485,27 @@ public class BuffManager : IDisposable
|
|||
{ AcSkillType.Summoning, "Summoning Mastery" },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The prots and banes the Buffing settings let the player untick (LegacyUiSettings.DisabledBuffs),
|
||||
/// paired by element for the two-column grid: (buff base name, label). Armor Self and
|
||||
/// Impenetrability head the columns. The cast order stays BuildDynamicBuffList's.
|
||||
/// </summary>
|
||||
internal static readonly (string Buff, string Label)[] ToggleProtections =
|
||||
{
|
||||
("Armor Self", "Armor"), ("Fire Protection Self", "Fire"), ("Cold Protection Self", "Cold"),
|
||||
("Acid Protection Self", "Acid"), ("Lightning Protection Self", "Lightning"),
|
||||
("Blade Protection Self", "Blade"), ("Piercing Protection Self", "Piercing"),
|
||||
("Bludgeoning Protection Self", "Bludgeoning"),
|
||||
};
|
||||
|
||||
internal static readonly (string Buff, string Label)[] ToggleBanes =
|
||||
{
|
||||
("Impenetrability", "Impenetrability"), ("Flame Bane", "Flame"), ("Frost Bane", "Frost"),
|
||||
("Acid Bane", "Acid"), ("Lightning Bane", "Lightning"),
|
||||
("Blade Bane", "Blade"), ("Piercing Bane", "Piercing"),
|
||||
("Bludgeoning Bane", "Bludgeoning"),
|
||||
};
|
||||
|
||||
public BuffManager(RynthCoreHost host, LegacyUiSettings settings, SpellManager spellManager, PlayerVitalsCache vitals)
|
||||
{
|
||||
_host = host;
|
||||
|
|
@ -1117,6 +1157,18 @@ public class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no kit, potion,
|
||||
// wand, stance change or cast while the server hasn't answered the last one (its UseDone;
|
||||
// a buff's enchantment lands before that). Heals keep their priority (ActionPacer's heal
|
||||
// rules). And not while RynthAi still has the character running: the arbiter's stop goes
|
||||
// out this tick, the cast the next one (a stop mid-windup disturbs the cast).
|
||||
if (!PacerAllows(out string paceWhy))
|
||||
{
|
||||
LastBuffSkipReason = "server answering the last action: " + paceWhy;
|
||||
Hold("server answering the last action", paceWhy);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't issue a cast while the previous cast GESTURE is still animating.
|
||||
// CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast
|
||||
// gate). AC refuses a cast issued mid-gesture with a server-driven
|
||||
|
|
@ -1135,6 +1187,7 @@ public class BuffManager : IDisposable
|
|||
// everything else still waits for the count to drop.
|
||||
bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
|
||||
bool busyHolds = BusyCount > 0
|
||||
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
|
||||
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
|
||||
if (!gateOpen || busyHolds)
|
||||
{
|
||||
|
|
@ -1157,6 +1210,14 @@ public class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// Health floor: no buff while health is under a heal line that nothing could heal
|
||||
// (Drakkon, 2026-10-06 04:51: recasting Swift Killer at 19% health, dead 10 s later).
|
||||
if (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct))
|
||||
{
|
||||
Hold("health under a heal line");
|
||||
return;
|
||||
}
|
||||
|
||||
// Mana floor: no buff while mana is under Get Mana At. CheckVitals above already tried
|
||||
// Stamina to Mana and a mana potion; when neither could run (stamina too low, none
|
||||
// carried) buffing used to carry on and run mana to 0. Wait for it instead.
|
||||
|
|
@ -1392,7 +1453,7 @@ public class BuffManager : IDisposable
|
|||
bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
|
||||
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
|
||||
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
|
||||
int stamThreshold = inCombat ? _settings.RestamAt : _settings.TopOffStam;
|
||||
int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
|
||||
|
||||
// A flag is set only when something was actually done about the vital.
|
||||
// WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so
|
||||
|
|
@ -1409,6 +1470,16 @@ public class BuffManager : IDisposable
|
|||
if (!healed) { _vitalWhy = ""; healed = AttemptVitalCast("Heal Self"); }
|
||||
string spellWhy = _vitalWhy;
|
||||
if (!healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); }
|
||||
// Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all
|
||||
// (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later).
|
||||
if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal))
|
||||
{
|
||||
string potionWhy = _vitalWhy;
|
||||
_vitalWhy = "";
|
||||
healed = AttemptHealthKitUse(ignoreMinSuccess: true);
|
||||
if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %.");
|
||||
else _vitalWhy = potionWhy;
|
||||
}
|
||||
if (healed)
|
||||
{
|
||||
_isHealingSelf = true;
|
||||
|
|
@ -1438,16 +1509,54 @@ public class BuffManager : IDisposable
|
|||
}
|
||||
// Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits
|
||||
// and cast Revitalize/Robustification instead, because stamina never looked for a kit.
|
||||
if (curStamPct < stamThreshold && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self")
|
||||
|| AttemptPotion("StaminaPotion", "Stamina")))
|
||||
// Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon
|
||||
// for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina
|
||||
// potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize
|
||||
// on top of it. In Magic stance (a caster) Revitalize stays first.
|
||||
bool potionFirst = CurrentCombatMode != CombatMode.Magic;
|
||||
if (curStamPct < stamThreshold)
|
||||
{
|
||||
_isRechargingStamina = true;
|
||||
return true;
|
||||
bool potionJustDrunk = potionFirst && _settings.UsePotions
|
||||
&& (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500
|
||||
&& HasListedPotion("StaminaPotion", "Stamina");
|
||||
if (!potionJustDrunk
|
||||
&& (AttemptStaminaKitUse()
|
||||
|| (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
|
||||
|| AttemptVitalCast("Revitalize Self")
|
||||
|| AttemptPotion("StaminaPotion", "Stamina")))
|
||||
{
|
||||
_isRechargingStamina = true;
|
||||
if (_restamRun) _restamRunCasts++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina
|
||||
// reaches Re-stam To; one Revitalize often doesn't get far. Capped so a recharge that
|
||||
// never gains can't loop: it ends after RestamRunMaxCasts.
|
||||
private bool _restamRun;
|
||||
private int _restamRunCasts;
|
||||
internal const int RestamRunMaxCasts = 4;
|
||||
|
||||
/// <summary>The stamina % to recharge under now (see the fields above).</summary>
|
||||
internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts)
|
||||
{
|
||||
if (!inCombat) { run = false; return s.TopOffStam; }
|
||||
if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; }
|
||||
if (stamPct < s.RestamAt)
|
||||
{
|
||||
if (!run) { run = true; casts = 0; }
|
||||
}
|
||||
else if (stamPct >= s.RestamTo || casts >= RestamRunMaxCasts)
|
||||
{
|
||||
run = false;
|
||||
}
|
||||
return run ? s.RestamTo : s.RestamAt;
|
||||
}
|
||||
|
||||
/// <summary>True when Stamina To Health At / Min Stamina allow Stamina to Health Self now.</summary>
|
||||
internal static bool StaminaToHealthAllowed(LegacyUiSettings s, int healthPct, int staminaPct)
|
||||
=> s.StaminaToHealthAt > 0 && healthPct <= s.StaminaToHealthAt && staminaPct > s.StaminaToHealthMinStamina;
|
||||
|
|
@ -1485,6 +1594,7 @@ public class BuffManager : IDisposable
|
|||
if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return;
|
||||
if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return;
|
||||
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return;
|
||||
if (!ActionPacer.MayStart(_host, "Buff", HealNeed.Emergency, out _)) return;
|
||||
if (AttemptHealthKitUse() || AttemptPotion("HealthPotion"))
|
||||
{
|
||||
_lastPendingEmergencyHealAt = DateTime.Now;
|
||||
|
|
@ -1540,7 +1650,19 @@ public class BuffManager : IDisposable
|
|||
_healWaitKind = "server finishing the last cast";
|
||||
return true;
|
||||
}
|
||||
int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic);
|
||||
int spellId = _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic, LevelLacksComponents);
|
||||
// A heal with nothing known at the allowed tiers: the lowest known tier above them.
|
||||
// Vitae can drop Life Magic under a tier line while only higher tiers are known.
|
||||
if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self")
|
||||
{
|
||||
spellId = _spellManager.GetSelfSpellIdAboveAllowedTier(baseName, AcSkillType.LifeMagic);
|
||||
if (spellId != 0 && (DateTime.Now - _lastAboveTierLog).TotalSeconds >= 30)
|
||||
{
|
||||
_lastAboveTierLog = DateTime.Now;
|
||||
_host.Log($"[RynthAi] Vitals: no '{baseName}' at the tiers Life Magic allows now; " +
|
||||
$"trying {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} (may fizzle).");
|
||||
}
|
||||
}
|
||||
if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers");
|
||||
// Parked after a hard server refusal (see OnChatWindowText) — the same
|
||||
// per-family cooldown the buff selectors honour.
|
||||
|
|
@ -1566,7 +1688,8 @@ public class BuffManager : IDisposable
|
|||
_pendingSpellId = spellId;
|
||||
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
|
||||
_pendingVitalLabel = VitalLabel(baseName);
|
||||
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
|
||||
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff",
|
||||
SpellTableStub.GetById(spellId)?.Name ?? baseName);
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
if (!castOk)
|
||||
{
|
||||
|
|
@ -1589,7 +1712,21 @@ public class BuffManager : IDisposable
|
|||
/// Drinks the first potion of <paramref name="types"/> from the Items panel.
|
||||
/// "Stamina" is the older name for stamina potions. Off with UsePotions.
|
||||
/// </summary>
|
||||
private bool AttemptPotion(params string[] types)
|
||||
private bool AttemptPotion(params string[] types) => AttemptPotion(false, types);
|
||||
|
||||
/// <summary>A potion of one of <paramref name="types"/> listed in Consumables and in the pack.</summary>
|
||||
private bool HasListedPotion(params string[] types)
|
||||
{
|
||||
if (_worldObjectCache == null) return false;
|
||||
foreach (var rule in _settings.ConsumableRules)
|
||||
if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) >= 0
|
||||
&& _worldObjectCache[rule.Id] != null)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="listedOnly"/>: only the Consumables list, not any potion in the pack.</summary>
|
||||
private bool AttemptPotion(bool listedOnly, params string[] types)
|
||||
{
|
||||
if (!_settings.UsePotions || _worldObjectCache == null) return VitalNo("Use Potions is off");
|
||||
if ((DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago");
|
||||
|
|
@ -1605,6 +1742,7 @@ public class BuffManager : IDisposable
|
|||
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
|
||||
return true;
|
||||
}
|
||||
if (listedOnly) return VitalNo("none listed in Consumables");
|
||||
// Nothing on the Items panel: anything in the pack of that kind (Field Rations
|
||||
// weren't used unless someone added them by hand, 2026-09-29).
|
||||
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
|
||||
|
|
@ -1726,7 +1864,9 @@ public class BuffManager : IDisposable
|
|||
}
|
||||
private DateTime _lastPotionAt = DateTime.MinValue;
|
||||
|
||||
private bool AttemptHealthKitUse()
|
||||
private DateTime _lastAboveTierLog = DateTime.MinValue;
|
||||
|
||||
private bool AttemptHealthKitUse(bool ignoreMinSuccess = false)
|
||||
{
|
||||
if (_worldObjectCache == null) return false;
|
||||
// VTank's kit options: skip kits in magic mode unless allowed; optionally
|
||||
|
|
@ -1745,10 +1885,10 @@ public class BuffManager : IDisposable
|
|||
if (KitRetryWait(out string kitWait)) return VitalNo(kitWait);
|
||||
// Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it.
|
||||
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
|
||||
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
|
||||
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit");
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
_healWaitKind = "peace mode for the kit";
|
||||
return true; // use the kit next tick, once in peace mode
|
||||
|
|
@ -1781,7 +1921,7 @@ public class BuffManager : IDisposable
|
|||
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false;
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit");
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
return true; // use the kit next tick, once in peace mode
|
||||
}
|
||||
|
|
@ -2102,7 +2242,7 @@ public class BuffManager : IDisposable
|
|||
// buffed when it wasn't and never retried the known tier.
|
||||
|
||||
if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)");
|
||||
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
|
||||
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName);
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
if (castOk) NoteCastIssued(spellId);
|
||||
if (castOk && buffFamily != 0 && spellInfo != null)
|
||||
|
|
@ -2997,6 +3137,12 @@ public class BuffManager : IDisposable
|
|||
final.AddRange(step5_LifeAndItem);
|
||||
final.AddRange(step6_WeaponAuras);
|
||||
final.AddRange(step7_ArmorBanes);
|
||||
|
||||
// Buffs the player unticked (Buffing settings: prots and banes) leave the list here, so
|
||||
// the cast loop never casts them and NeedsAnyBuff never waits on them: a skipped buff
|
||||
// can't hold the bot in Buffing.
|
||||
if (_settings.DisabledBuffs.Count > 0)
|
||||
final.RemoveAll(_settings.IsBuffDisabled);
|
||||
return final;
|
||||
}
|
||||
|
||||
|
|
@ -3206,7 +3352,15 @@ public class BuffManager : IDisposable
|
|||
if (_pendingSpellId != 0)
|
||||
{
|
||||
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
|
||||
if (pendingSpell != null)
|
||||
bool noCompsVital = _pendingSpellId == _pendingVitalSpellId
|
||||
&& (lower.Contains("components") || lower.Contains("missing some required"));
|
||||
if (pendingSpell != null && noCompsVital)
|
||||
{
|
||||
// A vital spell: pass over this level only; the next lower one goes next.
|
||||
_noComponentsUntil[_pendingSpellId] = DateTime.Now.AddSeconds(NoComponentsLevelSec);
|
||||
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
|
||||
}
|
||||
else if (pendingSpell != null)
|
||||
{
|
||||
if (IsItemEnchantment(pendingSpell.Name))
|
||||
{
|
||||
|
|
@ -3364,6 +3518,50 @@ public class BuffManager : IDisposable
|
|||
_onCastResolved?.Invoke($"cast '{spellName}'");
|
||||
}
|
||||
|
||||
/// <summary>What a heal needs from the pacing now: none, a heal line, or Emergency Heal At.</summary>
|
||||
internal HealNeed HealNeedNow()
|
||||
{
|
||||
if (_vitals.MaxHealth <= 0) return HealNeed.None;
|
||||
int hp = _vitals.HealthPct;
|
||||
int emergencyAt = _settings.EmergencyHealAt;
|
||||
if (emergencyAt > 0 && hp <= emergencyAt) return HealNeed.Emergency;
|
||||
return HealthUnderAnyLine(hp, _vitals.StaminaPct) ? HealNeed.Heal : HealNeed.None;
|
||||
}
|
||||
|
||||
/// <summary>Times the vitals/buff step waited for the server's answer (tests, status).</summary>
|
||||
internal int PacerHolds { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The pacing gate of the vitals/buff step (see HeartbeatCore): false while the server is still
|
||||
/// answering the last action (ActionPacer.MayStart, with the heal rules) or while RynthAi still
|
||||
/// has the character running (the arbiter's stop goes out first).
|
||||
/// </summary>
|
||||
private bool _pacerLetHealAhead;
|
||||
|
||||
private bool PacerAllows(out string why)
|
||||
{
|
||||
why = "";
|
||||
_pacerLetHealAhead = false;
|
||||
if (!ActionPacer.Enabled) return true;
|
||||
if (MoveAudit.OwnMovementActive)
|
||||
{
|
||||
why = "the character is still moving (the stop goes out first)";
|
||||
PacerHolds++;
|
||||
return false;
|
||||
}
|
||||
HealNeed need = HealNeedNow();
|
||||
bool outstanding = ActionPacer.Current(_host) != null;
|
||||
if (ActionPacer.MayStart(_host, "Buff", need, out why))
|
||||
{
|
||||
// A heal let ahead of an unanswered action: the busy count still counts that action,
|
||||
// so the busy gate below must not hold the heal again.
|
||||
_pacerLetHealAhead = outstanding && need != HealNeed.None;
|
||||
return true;
|
||||
}
|
||||
PacerHolds++;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Record that a cast just went out, so the next one waits for the
|
||||
/// server to report the action finished rather than a blind interval.</summary>
|
||||
private void NoteCastIssued(int spellId)
|
||||
|
|
@ -3491,6 +3689,7 @@ public class BuffManager : IDisposable
|
|||
var held = _cast.Open;
|
||||
string name = held?.Name ?? "?";
|
||||
double secs = _cast.HeldSeconds;
|
||||
FlightRecorderSignal.Dump(_host, $"held cast nudge: '{name}' {secs:0.0} s");
|
||||
if (!_host.HasSetAutoRun)
|
||||
{
|
||||
_host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation, but this engine has no SetAutoRun: no nudge.");
|
||||
|
|
@ -3740,9 +3939,9 @@ public class BuffManager : IDisposable
|
|||
// _lastBuffStanceAttempt), while buffing held the bot.
|
||||
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
|
||||
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs)
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
NoteStanceRequest();
|
||||
_lastBuffStanceAttempt = DateTime.Now;
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
|
|
@ -3801,6 +4000,20 @@ public class BuffManager : IDisposable
|
|||
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
|
||||
return false;
|
||||
|
||||
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
|
||||
{
|
||||
_pendingWieldId = 0; // another swap since ours: not a failed wield
|
||||
return false;
|
||||
}
|
||||
int stillInHand = _directWandSwapFailed ? 0 : FindWieldedNonWandWeapon(wandId);
|
||||
if (stillInHand != 0 && IsWieldedLive(stillInHand))
|
||||
{
|
||||
_directWandSwapFailed = true;
|
||||
_pendingWieldId = 0;
|
||||
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
|
||||
"from now on the weapon goes into a pack first");
|
||||
return false;
|
||||
}
|
||||
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
|
||||
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
|
||||
_pendingWieldId = 0;
|
||||
|
|
@ -3838,7 +4051,7 @@ public class BuffManager : IDisposable
|
|||
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
|
||||
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
|
||||
int bowId = FindWieldedNonWandWeapon(wandId);
|
||||
if (bowId != 0)
|
||||
if (bowId != 0 && (_directWandSwapFailed || !IsWieldedLive(bowId))) // else the use swaps (see _directWandSwapFailed)
|
||||
{
|
||||
if (_bowDequipPendingId == bowId
|
||||
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
|
||||
|
|
@ -3861,6 +4074,7 @@ public class BuffManager : IDisposable
|
|||
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
|
||||
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
|
||||
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
|
||||
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
|
||||
_bowDequipPendingId = bowId;
|
||||
_bowDequipAt = now;
|
||||
_lastCastAttempt = now;
|
||||
|
|
@ -3870,8 +4084,9 @@ public class BuffManager : IDisposable
|
|||
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
|
||||
}
|
||||
|
||||
_host.UseFor((uint)wandId, "Buff", "buffing: wield the wand");
|
||||
_host.UseFor((uint)wandId, "Buff", bowId != 0 && !_directWandSwapFailed ? "buffing: switch to the wand" : "buffing: wield the wand");
|
||||
NoteStanceRequest();
|
||||
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
|
||||
_pendingWieldId = wandId;
|
||||
_pendingWieldAt = now;
|
||||
_lastCastAttempt = now;
|
||||
|
|
@ -3924,9 +4139,9 @@ public class BuffManager : IDisposable
|
|||
if (shift > 5) shift = 5;
|
||||
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
|
||||
if (gateMs > 30000) gateMs = 30000; // cap at 30s
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs)
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
NoteStanceRequest();
|
||||
_lastBuffStanceAttempt = DateTime.Now;
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
|
|
|
|||
|
|
@ -156,6 +156,8 @@ internal sealed class CastTracker
|
|||
private void Close(Cast c, string kind)
|
||||
{
|
||||
c.Done = true;
|
||||
// The server is in the cast's recoil now: one heal may be queued behind it (ActionPacer).
|
||||
RynthCore.Plugin.Shared.ActionPacer.NoteCastResult();
|
||||
DateTime now = Now;
|
||||
string nudged = c.Nudged ? " (after the movement nudge)" : "";
|
||||
if (c.HasIncantation)
|
||||
|
|
|
|||
|
|
@ -220,6 +220,7 @@ public partial class CombatManager
|
|||
var wo = _worldFilter[wielded.Id];
|
||||
int amount = Math.Max(1, wo?.Values(LongValueKey.StackCount, 1) ?? 1); // the whole stack, not one arrow
|
||||
_host.MoveItemInternal(unchecked((uint)wielded.Id), unchecked((uint)packId), 0, amount);
|
||||
_weaponSwapGate?.NoteMove(wielded.Id, wieldedNow: true);
|
||||
_ammoDequipPendingId = wielded.Id;
|
||||
_ammoDequipAt = now;
|
||||
_ammoDequipTries++;
|
||||
|
|
|
|||
|
|
@ -285,6 +285,7 @@ public partial class CombatManager
|
|||
if (!gateHeld && _weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-offhand-dequip")) return OffPrep.Busy;
|
||||
|
||||
_host.MoveItemInternal(unchecked((uint)offId), unchecked((uint)packId), 0, 1);
|
||||
_weaponSwapGate?.NoteMove(offId, wieldedNow: true);
|
||||
_offDequipPendingId = offId;
|
||||
_offDequipAt = now;
|
||||
_offDequipTries++;
|
||||
|
|
@ -379,6 +380,7 @@ public partial class CombatManager
|
|||
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
|
||||
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
|
||||
OffhandTracker.Sent(plan.Id, _offSwapFrom, now);
|
||||
_weaponSwapGate?.NoteMove(plan.Id, wieldedNow: false);
|
||||
_offSwapFrom = 0;
|
||||
_lastEquipTime = now;
|
||||
if (plan.Id != _stowedOffhandId) _stowedOffhandId = 0; // a listed one replaces what was taken off
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
126
Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs
Normal file
126
Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// The one "time since our last kill" clock (2026-10-06). Read by the meta expression
|
||||
/// secondssincelastkill[], the "No Kills Within Minutes" meta condition and the status feed's
|
||||
/// secsSinceLastKill.
|
||||
///
|
||||
/// A kill is ACE's KillerNotification (GameEvent 0x01AD), which the server sends only to the
|
||||
/// killer: RynthAiPlugin.OnKillNotification is the only caller of <see cref="RecordKill"/>.
|
||||
/// Death messages in chat ("X died", a fellow's kill) never count.
|
||||
///
|
||||
/// Before the first kill this session the clock counts from the last macro start, or, if the
|
||||
/// macro hasn't been started since login, from login (a plugin load or hot reload counts as a
|
||||
/// login), so a meta can still act on "no kills at all". After that it counts from the later of
|
||||
/// the last kill and the last macro start: restarting the macro starts the count again.
|
||||
///
|
||||
/// Monotonic (Environment.TickCount64, not the wall clock). Writers are the plugin pump thread;
|
||||
/// the status feed reads from its poll thread, so every field is read and written with Interlocked.
|
||||
/// </summary>
|
||||
internal sealed class KillClock
|
||||
{
|
||||
private const long None = long.MinValue;
|
||||
|
||||
private readonly Func<long> _nowMs;
|
||||
private long _sessionStartMs;
|
||||
private long _macroStartMs = None;
|
||||
private long _lastKillMs = None;
|
||||
private int _macroWasRunning;
|
||||
|
||||
/// <param name="nowMs">Monotonic milliseconds; tests pass a fake clock.</param>
|
||||
public KillClock(Func<long>? nowMs = null)
|
||||
{
|
||||
_nowMs = nowMs ?? (static () => Environment.TickCount64);
|
||||
_sessionStartMs = _nowMs();
|
||||
}
|
||||
|
||||
/// <summary>Asked on every read, so a macro start is seen before the first condition after it.
|
||||
/// The plugin also calls <see cref="ObserveMacro"/> every tick.</summary>
|
||||
public Func<bool>? MacroRunning { get; set; }
|
||||
|
||||
/// <summary>Login (and plugin load): no kill yet, the clock counts from now. A macro that is
|
||||
/// already on (start macro on login) counts as started now.</summary>
|
||||
public void SessionStarted()
|
||||
{
|
||||
Interlocked.Exchange(ref _sessionStartMs, _nowMs());
|
||||
Interlocked.Exchange(ref _macroStartMs, None);
|
||||
Interlocked.Exchange(ref _lastKillMs, None);
|
||||
Interlocked.Exchange(ref _macroWasRunning, 0);
|
||||
Observe();
|
||||
}
|
||||
|
||||
/// <summary>Notes a macro start (off to on). Safe to call any number of times.</summary>
|
||||
public void ObserveMacro(bool running)
|
||||
{
|
||||
int prev = Interlocked.Exchange(ref _macroWasRunning, running ? 1 : 0);
|
||||
if (running && prev == 0)
|
||||
Interlocked.Exchange(ref _macroStartMs, _nowMs());
|
||||
}
|
||||
|
||||
/// <summary>We killed something (KillerNotification only).</summary>
|
||||
public void RecordKill() => Interlocked.Exchange(ref _lastKillMs, _nowMs());
|
||||
|
||||
/// <summary>True once we have a kill this session.</summary>
|
||||
public bool HasKill => Interlocked.Read(ref _lastKillMs) != None;
|
||||
|
||||
/// <summary>What the clock counts from: "kill", "macro start" or "login".</summary>
|
||||
public string Since
|
||||
{
|
||||
get
|
||||
{
|
||||
Observe();
|
||||
long kill = Interlocked.Read(ref _lastKillMs), macro = Interlocked.Read(ref _macroStartMs);
|
||||
if (kill != None && kill >= macro) return "kill";
|
||||
return macro != None ? "macro start" : "login";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Milliseconds since our last kill (before the first: since the macro start, or login). Never negative.</summary>
|
||||
public long ElapsedMs()
|
||||
{
|
||||
Observe();
|
||||
// The later of the last kill and the last macro start: a restart after a long pause
|
||||
// starts the count again (Tom, 2026-10-06), so "no kills in 10 min" doesn't fire at once.
|
||||
long from = Math.Max(Interlocked.Read(ref _lastKillMs), Interlocked.Read(ref _macroStartMs));
|
||||
if (from == None) from = Interlocked.Read(ref _sessionStartMs);
|
||||
return Math.Max(0, _nowMs() - from);
|
||||
}
|
||||
|
||||
/// <summary>Whole seconds for secondssincelastkill[].</summary>
|
||||
public long SecondsSinceLastKill() => ElapsedMs() / 1000;
|
||||
|
||||
/// <summary>Whole seconds since an actual kill, or -1 before the first (the status feed's value).</summary>
|
||||
public int SecondsSinceKillOnly()
|
||||
{
|
||||
long kill = Interlocked.Read(ref _lastKillMs);
|
||||
if (kill == None) return -1;
|
||||
return (int)Math.Clamp((_nowMs() - kill) / 1000, 0, int.MaxValue);
|
||||
}
|
||||
|
||||
/// <summary>"No Kills Within Minutes": true when nothing was killed for at least
|
||||
/// <paramref name="minutes"/> minutes (decimals allowed: 0.5 = 30 s).</summary>
|
||||
public bool NoKillsFor(double minutes) => ElapsedMs() >= minutes * 60_000.0;
|
||||
|
||||
/// <summary>The condition's value as typed in the editor or the .af file: minutes, decimals
|
||||
/// allowed ("5", "2.5"; a comma decimal is accepted too). False for empty, negative or not a number.</summary>
|
||||
public static bool TryParseMinutes(string? text, out double minutes)
|
||||
{
|
||||
minutes = 0;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string t = text.Trim().Replace(',', '.');
|
||||
if (!double.TryParse(t, System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out double m)) return false;
|
||||
if (double.IsNaN(m) || double.IsInfinity(m) || m < 0) return false;
|
||||
minutes = m;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Observe()
|
||||
{
|
||||
Func<bool>? probe = MacroRunning;
|
||||
if (probe != null) ObserveMacro(probe());
|
||||
}
|
||||
}
|
||||
|
|
@ -223,7 +223,7 @@ public class MissileCraftingManager
|
|||
_combinesCompleted = 0;
|
||||
_allCombinesDone = false;
|
||||
|
||||
try { _host.ChangeCombatMode(CombatMode.NonCombat); } catch { }
|
||||
try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { }
|
||||
|
||||
var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList();
|
||||
var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList();
|
||||
|
|
|
|||
|
|
@ -60,13 +60,15 @@ internal sealed class PetManager
|
|||
// get parked so we advance to the next configured essence instead of looping.
|
||||
private readonly Dictionary<int, long> _deviceCooldownUntil = new();
|
||||
|
||||
// Essences the server just confirmed full ("You add the spirit…" / "…already full"). Until a
|
||||
// summon reports "not enough charges", their Structure read is not trusted: the cached value
|
||||
// can still be the empty 0 from the last appraisal, which re-issued the refill in a loop
|
||||
// (spirit use → peace mode → clap) on 2026-10-04.
|
||||
private readonly Dictionary<int, long> _confirmedFullUntil = new();
|
||||
// Refills issued per essence inside RefillLoopWindowMs; a third one parks the essence.
|
||||
private readonly Dictionary<int, (int Count, long WindowStart)> _refillAttempts = new();
|
||||
// The server's word over a stale Structure read (2026-10-05). A read
|
||||
// can say 0 while the server holds a full essence; the server then answers a refill with
|
||||
// "already full" (or refills it and the read still lags), and deciding from the read alone
|
||||
// re-issued the refill every think tick: peace mode and a clap each time, a spirit each time
|
||||
// the refill was real. Essence -> until when its read of 0 is not believed; cleared when a
|
||||
// summon reports "not enough charges".
|
||||
private readonly Dictionary<int, long> _serverSaidFullUntil = new();
|
||||
// Refills issued per essence: how many since the window opened, and when it opened.
|
||||
private readonly Dictionary<int, (int Count, long Since)> _refills = new();
|
||||
|
||||
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
|
||||
// by name; it is never itself a summon device.
|
||||
|
|
@ -77,15 +79,17 @@ internal sealed class PetManager
|
|||
private const long AssumeActiveAfterSummonMs = 10_000;
|
||||
private const long DeviceFailCooldownMs = 30_000;
|
||||
private const long DeviceNoSpiritCooldownMs = 15_000;
|
||||
private const long ConfirmedFullTrustMs = 30 * 60_000;
|
||||
private const long RefillLoopWindowMs = 120_000;
|
||||
private const int RefillLoopMaxAttempts = 2;
|
||||
private const long RefillLoopParkMs = 300_000;
|
||||
private const long ServerSaidFullTrustMs = 30 * 60_000;
|
||||
private const long RefillWindowMs = 120_000; // two refills inside this and the
|
||||
private const int RefillsPerWindow = 2; // essence still reads empty:
|
||||
private const long RefillLoopParkMs = 300_000; // park it this long
|
||||
|
||||
private string _playerName = string.Empty;
|
||||
private long _playerNameAt;
|
||||
|
||||
private static long NowMs => Environment.TickCount64;
|
||||
/// <summary>Clock (ms); tests replace it.</summary>
|
||||
internal static Func<long> Clock { get; set; } = static () => Environment.TickCount64;
|
||||
private static long NowMs => Clock();
|
||||
|
||||
/// <summary>
|
||||
/// Optional ILT Hub hook: when it returns true an EMPTY essence is used anyway, because
|
||||
|
|
@ -190,8 +194,8 @@ internal sealed class PetManager
|
|||
// Drop to Idle; the next think tick reads Structure==0 and refills it.
|
||||
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
|
||||
_confirmedFullUntil.Remove(_activeDeviceId); // really empty now — a refill is due
|
||||
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
|
||||
_serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again
|
||||
// The server-side pyreal refill didn't happen (charm off / no pyreals):
|
||||
// park the essence so the empty-summon path can't spin on it.
|
||||
if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0)
|
||||
|
|
@ -205,21 +209,13 @@ internal sealed class PetManager
|
|||
if (_state == PetState.Refilling)
|
||||
{
|
||||
// "You add the spirit to the essence." (success) / "This essence is
|
||||
// already full." (our Structure read was stale — also done).
|
||||
// already full." (our Structure read was stale — also done). Either way the
|
||||
// essence is full now, whatever its read says until the next update.
|
||||
bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase);
|
||||
bool full = text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
|
||||
bool full = !added && text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
|
||||
if (added || full)
|
||||
{
|
||||
int device = _activeDeviceId;
|
||||
if (device != 0)
|
||||
{
|
||||
_confirmedFullUntil[device] = NowMs + ConfirmedFullTrustMs;
|
||||
// Refresh the cached Structure so the roster / HUD and later reads agree.
|
||||
if (_host.HasRequestId) _host.RequestId(unchecked((uint)device));
|
||||
}
|
||||
RynthLog.Write(LogCat.Pets, added
|
||||
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)device:X8}, server confirmed)."
|
||||
: $"[RynthAi] Pet: essence 0x{(uint)device:X8} is already full; charge read was stale.");
|
||||
OnServerSaidFull(_activeDeviceId, added);
|
||||
GoIdle();
|
||||
}
|
||||
}
|
||||
|
|
@ -258,12 +254,11 @@ internal sealed class PetManager
|
|||
|
||||
int charges = ReadCharges(deviceId); // -1 = unreadable
|
||||
|
||||
// The server said this essence is full since the read went stale — summon from it.
|
||||
if (charges == 0 && _confirmedFullUntil.TryGetValue(deviceId, out long trustUntil))
|
||||
{
|
||||
if (now < trustUntil) charges = -1;
|
||||
else _confirmedFullUntil.Remove(deviceId);
|
||||
}
|
||||
// The server called this essence full after the read last changed: the 0 is stale.
|
||||
// Summon as for an unreadable one (an empty essence is refused harmlessly, and that
|
||||
// "not enough charges" ends the trust).
|
||||
if (charges == 0 && ServerSaidFull(deviceId, now))
|
||||
charges = -1;
|
||||
|
||||
if (charges != 0)
|
||||
{
|
||||
|
|
@ -285,13 +280,13 @@ internal sealed class PetManager
|
|||
if (_settings.PetAutoRefill)
|
||||
{
|
||||
int spiritId = FindEncapsulatedSpirit();
|
||||
if (spiritId != 0)
|
||||
if (spiritId != 0 && !RefillLooping(deviceId, now))
|
||||
{
|
||||
if (RefillLoopDetected(deviceId, now))
|
||||
continue;
|
||||
IssueRefill(deviceId, spiritId);
|
||||
return;
|
||||
}
|
||||
if (spiritId != 0)
|
||||
continue; // parked by RefillLooping; try the next essence
|
||||
}
|
||||
|
||||
// Out of charges and no spirit (or refill off): park this essence
|
||||
|
|
@ -323,34 +318,54 @@ internal sealed class PetManager
|
|||
_activeDeviceId = deviceId;
|
||||
_activeSpiritId = spiritId;
|
||||
_actionIssuedAt = NowMs;
|
||||
RecordRefillAttempt(deviceId, _actionIssuedAt);
|
||||
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
|
||||
CountRefill(deviceId, _actionIssuedAt);
|
||||
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
|
||||
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
|
||||
}
|
||||
|
||||
/// <summary>Counts refills per essence inside <see cref="RefillLoopWindowMs"/>.</summary>
|
||||
private void RecordRefillAttempt(int deviceId, long now)
|
||||
/// <summary>
|
||||
/// The server said the essence is full ("You add the spirit..." / "...already full"): its
|
||||
/// read of 0 is not believed for a while, and it is re-identified so the read catches up.
|
||||
/// </summary>
|
||||
private void OnServerSaidFull(int deviceId, bool refilled)
|
||||
{
|
||||
if (_refillAttempts.TryGetValue(deviceId, out var a) && now - a.WindowStart < RefillLoopWindowMs)
|
||||
_refillAttempts[deviceId] = (a.Count + 1, a.WindowStart);
|
||||
if (deviceId == 0) return;
|
||||
_serverSaidFullUntil[deviceId] = NowMs + ServerSaidFullTrustMs;
|
||||
if (_host.HasRequestId) _host.RequestId(unchecked((uint)deviceId));
|
||||
_host.Log(refilled
|
||||
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)deviceId:X8}, server confirmed)."
|
||||
: $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} is already full (its charge read was stale); summoning from it.");
|
||||
}
|
||||
|
||||
private bool ServerSaidFull(int deviceId, long now)
|
||||
{
|
||||
if (!_serverSaidFullUntil.TryGetValue(deviceId, out long until)) return false;
|
||||
if (now < until) return true;
|
||||
_serverSaidFullUntil.Remove(deviceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void CountRefill(int deviceId, long now)
|
||||
{
|
||||
if (_refills.TryGetValue(deviceId, out var r) && now - r.Since < RefillWindowMs)
|
||||
_refills[deviceId] = (r.Count + 1, r.Since);
|
||||
else
|
||||
_refillAttempts[deviceId] = (1, now);
|
||||
_refills[deviceId] = (1, now);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True (and the essence parked) when it was already refilled <see cref="RefillLoopMaxAttempts"/>
|
||||
/// times in the window without becoming usable — the charge read is stale or the refill is
|
||||
/// failing, and repeating it only burns spirits and forces peace mode.
|
||||
/// True, and the essence parked, when it was refilled <see cref="RefillsPerWindow"/> times
|
||||
/// inside <see cref="RefillWindowMs"/> and still reads empty: another refill would only cost
|
||||
/// a spirit and force peace mode again. An essence holds dozens of summons, so two real
|
||||
/// refills that close together don't happen.
|
||||
/// </summary>
|
||||
private bool RefillLoopDetected(int deviceId, long now)
|
||||
private bool RefillLooping(int deviceId, long now)
|
||||
{
|
||||
if (!_refillAttempts.TryGetValue(deviceId, out var a) || now - a.WindowStart >= RefillLoopWindowMs)
|
||||
return false;
|
||||
if (a.Count < RefillLoopMaxAttempts)
|
||||
if (!_refills.TryGetValue(deviceId, out var r) || now - r.Since >= RefillWindowMs || r.Count < RefillsPerWindow)
|
||||
return false;
|
||||
_refills.Remove(deviceId);
|
||||
_deviceCooldownUntil[deviceId] = now + RefillLoopParkMs;
|
||||
_refillAttempts.Remove(deviceId);
|
||||
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} refilled {a.Count}x in {(now - a.WindowStart) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
|
||||
_host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} was refilled {r.Count}x in {(now - r.Since) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,11 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
public static class SpellDatabase
|
||||
{
|
||||
private static readonly Dictionary<int, string> _spellNames = new();
|
||||
// Family + difficulty (power) per spell id, from SpellData.txt columns 3 and 7.
|
||||
// Used by the Mag-style item info spell filter (cantrip / aura tiers).
|
||||
private static readonly Dictionary<int, (int Family, int Difficulty)> _spellMeta = new();
|
||||
// The data's category (ACE SpellCategory, column 3) and power (difficulty, column 7) per id,
|
||||
// and the ids of each category. Read for wall spells (2026-10-08): they have no tier in their
|
||||
// names ("Slithering Flames"), so a wall is found by its category and ranked by its power.
|
||||
private static readonly Dictionary<int, (int Category, int Power)> _spellMeta = new();
|
||||
private static readonly Dictionary<int, List<int>> _idsByCategory = new();
|
||||
private static bool _loaded = false;
|
||||
|
||||
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
|
||||
|
|
@ -42,6 +44,7 @@ public static class SpellDatabase
|
|||
{
|
||||
_spellNames.Clear();
|
||||
_spellMeta.Clear();
|
||||
_idsByCategory.Clear();
|
||||
_loaded = false;
|
||||
|
||||
try
|
||||
|
|
@ -65,10 +68,14 @@ public static class SpellDatabase
|
|||
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
|
||||
{
|
||||
_spellNames[spellId] = columns[1].Trim();
|
||||
if (columns.Length >= 7
|
||||
&& int.TryParse(columns[2].Trim(), out int family)
|
||||
&& int.TryParse(columns[6].Trim(), out int difficulty))
|
||||
_spellMeta[spellId] = (family, difficulty);
|
||||
if (columns.Length >= 7 && int.TryParse(columns[2].Trim(), out int category)
|
||||
&& int.TryParse(columns[6].Trim(), out int power))
|
||||
{
|
||||
_spellMeta[spellId] = (category, power);
|
||||
if (!_idsByCategory.TryGetValue(category, out List<int>? ids))
|
||||
_idsByCategory[category] = ids = new List<int>();
|
||||
ids.Add(spellId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -87,20 +94,6 @@ public static class SpellDatabase
|
|||
return $"Unknown Spell ({spellId})";
|
||||
}
|
||||
|
||||
/// <summary>Spell family and difficulty (power). False when the spell isn't in SpellData.txt.</summary>
|
||||
public static bool TryGetSpellMeta(int spellId, out int family, out int difficulty)
|
||||
{
|
||||
if (_spellMeta.TryGetValue(spellId, out var meta))
|
||||
{
|
||||
family = meta.Family;
|
||||
difficulty = meta.Difficulty;
|
||||
return true;
|
||||
}
|
||||
family = 0;
|
||||
difficulty = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>True when the spell id is in the embedded table or the built-in recall list.</summary>
|
||||
public static bool HasSpell(int spellId) =>
|
||||
_spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
|
||||
|
|
@ -121,6 +114,30 @@ public static class SpellDatabase
|
|||
return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
|
||||
}
|
||||
|
||||
/// <summary>The spell's category (ACE SpellCategory) and power from the data; false when the
|
||||
/// spell isn't in it.</summary>
|
||||
public static bool TryGetCategoryAndPower(int spellId, out int category, out int power)
|
||||
{
|
||||
if (_spellMeta.TryGetValue(spellId, out var m)) { category = m.Category; power = m.Power; return true; }
|
||||
category = 0; power = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Every spell id of a category (ACE SpellCategory), in data order.</summary>
|
||||
public static IReadOnlyList<int> IdsInCategory(int category)
|
||||
=> _idsByCategory.TryGetValue(category, out List<int>? ids) ? ids : Array.Empty<int>();
|
||||
|
||||
/// <summary>
|
||||
/// A spell's level by ACE's server formula (Spell.Level): the highest level whose minimum power
|
||||
/// it reaches, 1/50/100/150/200/250/300/400 for levels 1-8 (SpellFormula.MinPower). The tiered
|
||||
/// war lines have exactly those powers (Flame Bolt V 200, the tier-7 lore 300, Incantations
|
||||
/// 400; blasts +25), so it is the same tier limit the other shapes use. 0 = no power.
|
||||
/// </summary>
|
||||
public static int LevelFromPower(int power) => power switch
|
||||
{
|
||||
>= 400 => 8, >= 300 => 7, >= 250 => 6, >= 200 => 5, >= 150 => 4, >= 100 => 3, >= 50 => 2, >= 1 => 1, _ => 0,
|
||||
};
|
||||
|
||||
/// <summary>Builds a name→id reverse map for SpellManager initialisation.</summary>
|
||||
public static Dictionary<string, int> BuildNameToIdMap()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -174,7 +174,29 @@ public class SpellManager
|
|||
_ => "I"
|
||||
};
|
||||
|
||||
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill)
|
||||
/// <summary>
|
||||
/// The LOWEST known tier of <paramref name="baseSpellName"/> above the buff tier the skill
|
||||
/// allows, 0 when none. For heals when nothing at or under the allowed tier is known: vitae
|
||||
/// can drop Life Magic under a tier line while the character only knows higher tiers, and a
|
||||
/// heal that may fizzle beats none (Drakkon died twice, 2026-10-06).
|
||||
/// </summary>
|
||||
public int GetSelfSpellIdAboveAllowedTier(string baseSpellName, AcSkillType magicSkill)
|
||||
{
|
||||
RefreshKnownSpells();
|
||||
int maxTier = GetHighestBuffSpellTier(magicSkill);
|
||||
string cleanBase = baseSpellName.Replace(" Self", "").Trim();
|
||||
BaseNameAliases.TryGetValue(cleanBase, out string? alias);
|
||||
for (int tier = maxTier + 1; tier <= 8; tier++)
|
||||
{
|
||||
if (TryGetTierId(cleanBase, tier, out int id)) return id;
|
||||
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <param name="skip">Levels to pass over (a level the server refused for missing components):
|
||||
/// the next lower known level is returned instead.</param>
|
||||
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill, Func<int, bool>? skip = null)
|
||||
{
|
||||
RefreshKnownSpells(); // keep the authoritative inventory current (throttled)
|
||||
|
||||
|
|
@ -187,8 +209,8 @@ public class SpellManager
|
|||
|
||||
for (int tier = maxTier; tier >= 1; tier--)
|
||||
{
|
||||
if (TryGetTierId(cleanBase, tier, out int id)) return id;
|
||||
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
|
||||
if (TryGetTierId(cleanBase, tier, out int id) && (skip == null || !skip(id))) return id;
|
||||
if (alias != null && TryGetTierId(alias, tier, out int idAlias) && (skip == null || !skip(idAlias))) return idAlias;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
/// they didn't know about each other, so cross-subsystem swaps still raced.
|
||||
///
|
||||
/// This gate is a single shared instance both managers consult: a swap is only
|
||||
/// allowed if no other swap has been issued within MinIntervalMs. The loser
|
||||
/// yields and retries on a later tick. Spell casts and non-weapon item actions
|
||||
/// allowed once the last one is done on the server (or MinIntervalMs has passed).
|
||||
/// The loser yields and retries on a later tick. Spell casts and non-weapon item actions
|
||||
/// (loot moves, corpse opens) do NOT go through here.
|
||||
/// </summary>
|
||||
public sealed class WeaponSwapGate
|
||||
|
|
@ -24,37 +24,84 @@ public sealed class WeaponSwapGate
|
|||
private readonly object _lock = new();
|
||||
private long _lastSwapTickMs = long.MinValue / 4;
|
||||
private string _lastSwapBy = "";
|
||||
private int _movingId;
|
||||
private long _claims;
|
||||
|
||||
/// <summary>Swaps claimed so far: a caller can tell whether another swap went out after its own.</summary>
|
||||
public long Claims { get { lock (_lock) { return _claims; } } }
|
||||
|
||||
/// <summary>
|
||||
/// Minimum milliseconds between two weapon swaps. ~3s comfortably covers
|
||||
/// AC's equip + stance-change settle (matches the existing 3000ms cast
|
||||
/// equip-gate in CombatManager) so a swap fully resolves before the next.
|
||||
/// The longest one swap holds the next: a swap the server's answer can't be seen for (or
|
||||
/// with no <see cref="ServerIdle"/>) waits this long, as before 2026-10-06.
|
||||
/// </summary>
|
||||
public int MinIntervalMs { get; set; } = 3000;
|
||||
|
||||
/// <summary>
|
||||
/// Atomically claim the swap slot. Returns true (recording the swap) when
|
||||
/// no swap has occurred within MinIntervalMs; false when the caller must
|
||||
/// wait. Only mutates state when it returns true, so a denied caller never
|
||||
/// Swap speed (2026-10-06): the next swap may go once the last one is done on the server,
|
||||
/// after at least this long. A weapon change takes up to three steps (a shield or arrows
|
||||
/// into the pack, the weapon, the off hand); at a flat 3 s per step it took 6-9 s.
|
||||
/// </summary>
|
||||
public int FloorMs { get; set; } = 400;
|
||||
|
||||
/// <summary>True when no use or cast is waiting for the server's answer (ActionPacer).</summary>
|
||||
public Func<bool>? ServerIdle { get; set; }
|
||||
|
||||
/// <summary>Reads whether the character wields an item (for a noted move, <see cref="NoteMove"/>).</summary>
|
||||
public Func<int, bool>? IsWielded { get; set; }
|
||||
|
||||
public Func<long> NowMs { get; set; } = () => Environment.TickCount64;
|
||||
|
||||
/// <summary>
|
||||
/// Atomically claim the swap slot. Returns true (recording the swap) when the last swap is
|
||||
/// done on the server (see <see cref="FloorMs"/>) or MinIntervalMs has passed; false when
|
||||
/// the caller must wait. Only mutates state when it returns true, so a denied caller never
|
||||
/// "wastes" the slot.
|
||||
/// </summary>
|
||||
public bool TryBeginSwap(string requestedBy)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
long now = NowMs();
|
||||
lock (_lock)
|
||||
{
|
||||
if (now - _lastSwapTickMs < MinIntervalMs)
|
||||
long since = now - _lastSwapTickMs;
|
||||
if (since < MinIntervalMs && !LastSwapDone(since))
|
||||
return false;
|
||||
_lastSwapTickMs = now;
|
||||
_lastSwapBy = requestedBy ?? "";
|
||||
_movingId = 0;
|
||||
_claims++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The claimed swap moved <paramref name="itemId"/> into or out of a hand without a use (a
|
||||
/// pack move or a slot wield): the next swap waits the full MinIntervalMs, as before.
|
||||
/// Drakkon 2026-10-06 13:58: the wand went out 1.3 s after the axe's pack move (the axe read
|
||||
/// out of hand) and the server then held the first cast open until a relog. The server's
|
||||
/// unwield motion outlasts the item move, and nothing tells us when it ends.
|
||||
/// </summary>
|
||||
public void NoteMove(int itemId, bool wieldedNow)
|
||||
{
|
||||
lock (_lock) _movingId = itemId;
|
||||
}
|
||||
|
||||
private bool LastSwapDone(long since)
|
||||
{
|
||||
if (since < FloorMs || ServerIdle == null || IsWielded == null) return false;
|
||||
try
|
||||
{
|
||||
return _movingId == 0 && ServerIdle();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Milliseconds since the last successful swap (diagnostics).</summary>
|
||||
public long MsSinceLastSwap
|
||||
{
|
||||
get { lock (_lock) { return Environment.TickCount64 - _lastSwapTickMs; } }
|
||||
get { lock (_lock) { return NowMs() - _lastSwapTickMs; } }
|
||||
}
|
||||
|
||||
/// <summary>Who last claimed a swap (diagnostics).</summary>
|
||||
|
|
|
|||
|
|
@ -43,6 +43,12 @@ public class WorldObjectCache
|
|||
private readonly HashSet<int> _landscape = new(); // has physics position
|
||||
private readonly HashSet<int> _inventory = new(); // no physics position
|
||||
private readonly Dictionary<int, float> _healthRatios = new(); // last known health ratio per object (0-1)
|
||||
// Ids whose ratio is an estimate from our own damage lines (a ring, wall or chain spell's other
|
||||
// targets: the server sends health only for the selected target). A real health update replaces
|
||||
// the estimate and takes the id out of this set.
|
||||
private readonly HashSet<int> _estimatedHealth = new();
|
||||
/// <summary>The lowest an estimate goes: 0 means dead to every reader, and only the server says that.</summary>
|
||||
internal const float EstimatedHealthFloor = 0.01f;
|
||||
|
||||
// OnCreateObject IDs pending classification
|
||||
private readonly Queue<uint> _pending = new();
|
||||
|
|
@ -199,6 +205,7 @@ public class WorldObjectCache
|
|||
_creatures.Remove(sid);
|
||||
_landscape.Remove(sid);
|
||||
_healthRatios.Remove(sid);
|
||||
_estimatedHealth.Remove(sid);
|
||||
_classifyRetry.Remove(id);
|
||||
_slowRetry.Remove(id);
|
||||
_reclassifySkipState.Remove(id);
|
||||
|
|
@ -234,6 +241,37 @@ public class WorldObjectCache
|
|||
return _healthRatios.TryGetValue(id, out float v) ? v : -1f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lowers a creature's health by our own hit when the server sends it no health of its own: the
|
||||
/// other targets of a ring, wall or chain spell (ACE pushes health only for the selected target).
|
||||
/// <paramref name="fraction"/> is damage / max health, or 0 when the max is unknown, which only
|
||||
/// marks the creature as hurt (0.99). Never goes to 0 (dead is the server's call: the kill
|
||||
/// notice, a health update or the corpse) and never raises a known value. A real health update
|
||||
/// overwrites the estimate.
|
||||
/// </summary>
|
||||
public void ApplyDamageEstimate(int id, double fraction)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_playerId != 0 && unchecked((uint)id) == _playerId) return;
|
||||
float cur = _healthRatios.TryGetValue(id, out float v) ? v : 1f;
|
||||
if (cur <= 0f) return;
|
||||
float next = fraction > 0
|
||||
? (float)Math.Max(EstimatedHealthFloor, cur - fraction)
|
||||
: Math.Min(cur, 0.99f);
|
||||
if (next >= cur && _healthRatios.ContainsKey(id)) return;
|
||||
_healthRatios[id] = next;
|
||||
_estimatedHealth.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="id"/>'s health ratio is our estimate rather than the server's.</summary>
|
||||
public bool IsHealthEstimated(int id)
|
||||
{
|
||||
lock (_gate)
|
||||
return _estimatedHealth.Contains(id);
|
||||
}
|
||||
|
||||
public void OnUpdateHealth(uint id, float healthRatio)
|
||||
{
|
||||
lock (_gate)
|
||||
|
|
@ -243,6 +281,7 @@ public class WorldObjectCache
|
|||
|
||||
int sid = (int)id;
|
||||
_healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f);
|
||||
_estimatedHealth.Remove(sid); // the server's number replaces any estimate
|
||||
|
||||
if (!_creatures.Add(sid))
|
||||
return; // creature already known — ratio updated above, nothing more to do
|
||||
|
|
@ -601,13 +640,16 @@ public class WorldObjectCache
|
|||
return;
|
||||
}
|
||||
|
||||
// Non-creature with a known type: classify it by its ItemType flags and place it
|
||||
// by ownership. Only weapons/armor/casters/containers were accepted here before,
|
||||
// so keys, gems, spell components, food and misc fell through to Unknown
|
||||
// landscape (never inventory) and ReclassifyUnknownDynamics re-probed them
|
||||
// every 2 s forever.
|
||||
// Non-creature with a position and a known item type: equipped gear, a ground
|
||||
// drop, a chest. It gets the class its type gives and is filed by who has it
|
||||
// (FileTypedObject). Only weapons, armor, casters and containers were taken
|
||||
// here before, all into the inventory: keys, gems, comps, food and the like
|
||||
// stayed Unknown landscape and were re-probed every 2 s for good, and other
|
||||
// players' wielded gear and ground-dropped weapons counted as ours
|
||||
// (2026-10-05). A static object that isn't a chest or a lifestone returns
|
||||
// false and stays Unknown scenery below, hazard check included.
|
||||
AcObjectClass typedCls = ClassifyItem(uid, typeFlags);
|
||||
if (typedCls != AcObjectClass.Unknown && PlaceTypedObject(uid, id, name, typedCls, typeFlags))
|
||||
if (typedCls != AcObjectClass.Unknown && FileTypedObject(uid, id, name, typedCls, typeFlags))
|
||||
return;
|
||||
}
|
||||
else if (uid >= 0x80000000u)
|
||||
|
|
@ -657,83 +699,77 @@ public class WorldObjectCache
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Places a positioned, non-creature object whose ItemType resolved to a real class.
|
||||
/// Must be called under <see cref="_gate"/>.
|
||||
/// <list type="bullet">
|
||||
/// <item>Portals / lifestones → landscape with their real class.</item>
|
||||
/// <item>Dynamic objects owned by the player (wielded, in the main pack, or in a side pack) → inventory.</item>
|
||||
/// <item>Other dynamic objects (ground drops, corpse / chest contents) → landscape with the item class.</item>
|
||||
/// <item>Ownership unreadable → gear-like types go to inventory, the rest to landscape.</item>
|
||||
/// <item>Static non-fixture, non-container objects (doors, signs) → returns false; the caller keeps them Unknown scenery.</item>
|
||||
/// </list>
|
||||
/// Returns true when the object was placed and recorded in <see cref="_byId"/>.
|
||||
/// </summary>
|
||||
private bool PlaceTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
|
||||
{
|
||||
bool isFixture = cls is AcObjectClass.Portal or AcObjectClass.Lifestone;
|
||||
bool isDynamic = uid >= 0x80000000u;
|
||||
private const uint ItemTypeGear = ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer;
|
||||
|
||||
bool toInventory;
|
||||
if (isFixture)
|
||||
private enum Holder { Unknown, Player, OtherWielder, OtherContainer, Nobody }
|
||||
|
||||
/// <summary>
|
||||
/// Who has the object: the player (wielded, in the main pack, or in a side pack), another
|
||||
/// wielder (other players' and NPCs' gear), another container (a corpse, a chest), or
|
||||
/// nobody (it lies on the ground). Unknown when the player isn't known yet or the engine
|
||||
/// can't read the object's ownership. Caller holds _gate.
|
||||
/// </summary>
|
||||
private Holder WhoHas(int id)
|
||||
{
|
||||
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
|
||||
return Holder.Unknown;
|
||||
uint container = unchecked((uint)containerId), wielder = unchecked((uint)wielderId);
|
||||
if (wielder == _playerId || container == _playerId) return Holder.Player;
|
||||
if (wielder != 0) return Holder.OtherWielder;
|
||||
if (container == 0) return Holder.Nobody;
|
||||
// Side packs sit in the main pack (AC has no deeper nesting).
|
||||
return TryGetOwnership(containerId, out int outer, out _, out _) && unchecked((uint)outer) == _playerId
|
||||
? Holder.Player : Holder.OtherContainer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Files a positioned non-creature whose item type gave it a real class. Caller holds _gate.
|
||||
/// <list type="bullet">
|
||||
/// <item>A lifestone: landscape.</item>
|
||||
/// <item>Another static object: a chest goes on the landscape; anything else returns false
|
||||
/// and the caller keeps it Unknown scenery (doors, signs, static hotspots).</item>
|
||||
/// <item>A dynamic object the player has: inventory. One another player or an NPC wields:
|
||||
/// neither list (known by id only), so it is not ours, not a ground item on the radar and
|
||||
/// not something a meta can pick up. In another container or loose on the ground: landscape.</item>
|
||||
/// <item>Ownership unreadable: gear goes to the inventory as before, the rest to the landscape.</item>
|
||||
/// </list>
|
||||
/// A non-gear object that lands on the landscape gets the hazard check it had as Unknown
|
||||
/// (a hotspot spawned with a dynamic id and a Misc type is still a hazard).
|
||||
/// </summary>
|
||||
private bool FileTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
|
||||
{
|
||||
bool gear = (typeFlags & ItemTypeGear) != 0;
|
||||
bool toInventory, toLandscape;
|
||||
if (cls == AcObjectClass.Lifestone)
|
||||
{
|
||||
toInventory = false;
|
||||
toLandscape = true;
|
||||
}
|
||||
else if (!isDynamic)
|
||||
else if (uid < 0x80000000u)
|
||||
{
|
||||
// Chests are static containers; other static objects stay Unknown scenery.
|
||||
if ((typeFlags & ItemTypeContainer) == 0)
|
||||
return false;
|
||||
if ((typeFlags & ItemTypeContainer) == 0) return false;
|
||||
toInventory = false;
|
||||
toLandscape = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
bool owned = IsOwnedByPlayer(id, out bool ownershipKnown);
|
||||
toInventory = ownershipKnown
|
||||
? owned
|
||||
: (typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0;
|
||||
Holder holder = WhoHas(id);
|
||||
toInventory = holder == Holder.Player || (holder == Holder.Unknown && gear);
|
||||
toLandscape = !toInventory && holder != Holder.OtherWielder;
|
||||
}
|
||||
|
||||
_classifyRetry.Remove(uid);
|
||||
_reclassifySkipState.Remove(uid);
|
||||
if (toInventory)
|
||||
{
|
||||
if (_inventory.Add(id)) _inventoryDirty = true;
|
||||
_landscape.Remove(id);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_inventory.Remove(id)) _inventoryDirty = true;
|
||||
_landscape.Add(id);
|
||||
}
|
||||
if (toInventory) { if (_inventory.Add(id)) _inventoryDirty = true; }
|
||||
else if (_inventory.Remove(id)) _inventoryDirty = true;
|
||||
if (toLandscape) _landscape.Add(id);
|
||||
else _landscape.Remove(id);
|
||||
_byId[id] = Make(id, name, cls);
|
||||
TraceClassify(uid, name.Length > 0, true, true, typeFlags, toInventory ? $"typed->{cls}(inv)" : $"typed->{cls}(land)");
|
||||
if (toLandscape && !gear)
|
||||
MaybeRegisterHazard(uid, name);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the object is wielded by the player, sits in the player's main pack, or sits in
|
||||
/// a side pack whose container is the player. <paramref name="known"/> is false when the
|
||||
/// player id isn't set yet or the ownership read failed.
|
||||
/// </summary>
|
||||
private bool IsOwnedByPlayer(int id, out bool known)
|
||||
{
|
||||
known = false;
|
||||
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
|
||||
return false;
|
||||
|
||||
known = true;
|
||||
uint container = unchecked((uint)containerId);
|
||||
uint wielder = unchecked((uint)wielderId);
|
||||
if (wielder == _playerId || container == _playerId)
|
||||
return true;
|
||||
|
||||
// One level of nesting covers side packs (AC doesn't allow packs inside packs).
|
||||
return container != 0
|
||||
&& TryGetOwnership(containerId, out int outer, out _, out _)
|
||||
&& unchecked((uint)outer) == _playerId;
|
||||
}
|
||||
|
||||
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
|
||||
private const uint BfCorpse = 0x2000;
|
||||
|
||||
|
|
@ -799,7 +835,7 @@ public class WorldObjectCache
|
|||
List<int>? toPromote = null;
|
||||
List<int>? toCorpse = null;
|
||||
List<(int id, string name, AcObjectClass cls)>? statics = null;
|
||||
List<(int Id, uint Flags)>? toType = null; // Unknowns whose ItemType is now a real item class
|
||||
List<(int Id, uint Flags)>? typed = null; // Unknowns whose item type now gives a class
|
||||
foreach (int id in _landscape)
|
||||
{
|
||||
uint uid = unchecked((uint)id);
|
||||
|
|
@ -829,7 +865,11 @@ public class WorldObjectCache
|
|||
// Bounded to Monster/Unknown so we don't name-query every ground
|
||||
// item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X")
|
||||
// so a live mob cannot be misread as a corpse.
|
||||
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown)
|
||||
// Container too: a corpse typed before its name or flag was readable is filed as a
|
||||
// landscape Container by FileTypedObject (it used to go to the inventory, which the
|
||||
// inventory pass below re-checks).
|
||||
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown
|
||||
|| wo.ObjectClass == AcObjectClass.Container)
|
||||
&& ((_host.TryGetObjectName(uid, out string maybeCorpse) && IsCorpseName(maybeCorpse))
|
||||
|| HasCorpseFlag(uid)))
|
||||
{
|
||||
|
|
@ -854,11 +894,11 @@ public class WorldObjectCache
|
|||
isCreature = true;
|
||||
if (!isCreature)
|
||||
{
|
||||
// Type known now (or arrived late): place it as a real item instead of
|
||||
// re-probing it every pass. Applied after the loop: placing mutates _landscape.
|
||||
// Its type arrived after it was classified: file it as the item it is instead
|
||||
// of probing it again every pass. Done after the loop (filing edits _landscape).
|
||||
if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown)
|
||||
{
|
||||
(toType ??= new()).Add((id, typeFlags));
|
||||
(typed ??= new()).Add((id, typeFlags));
|
||||
continue;
|
||||
}
|
||||
DiagLogReclassifySkip(uid, wo.Name);
|
||||
|
|
@ -914,27 +954,27 @@ public class WorldObjectCache
|
|||
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse");
|
||||
}
|
||||
|
||||
if (toType != null)
|
||||
if (typed != null)
|
||||
{
|
||||
int placed = 0, toInv = 0;
|
||||
foreach (var (id, flags) in toType)
|
||||
int filed = 0, intoInventory = 0;
|
||||
foreach (var (id, flags) in typed)
|
||||
{
|
||||
if (!_byId.TryGetValue(id, out var wo)) continue;
|
||||
uint uid = unchecked((uint)id);
|
||||
// An Unknown result would be re-queued every pass, so leave it to the skip diag.
|
||||
AcObjectClass cls = ClassifyItem(uid, flags);
|
||||
if (cls == AcObjectClass.Unknown || !PlaceTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
|
||||
placed++;
|
||||
if (_inventory.Contains(id)) toInv++;
|
||||
if (cls == AcObjectClass.Unknown || !FileTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
|
||||
filed++;
|
||||
if (_inventory.Contains(id)) intoInventory++;
|
||||
}
|
||||
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {placed} Unknown object(s) as items ({toInv} into inventory)");
|
||||
if (filed > 0)
|
||||
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {filed} Unknown object(s) as items ({intoInventory} into the inventory)");
|
||||
}
|
||||
|
||||
// DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted
|
||||
// this pass. Confirms ReclassifyUnknownDynamics is running and engine signals
|
||||
// keep failing for the stuck uids (vs. them never reaching _landscape at all).
|
||||
if (toPromote == null
|
||||
&& toType == null
|
||||
&& typed == null
|
||||
&& _reclassifySkipState.Count > 0
|
||||
&& _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries)
|
||||
{
|
||||
|
|
@ -1096,10 +1136,64 @@ public class WorldObjectCache
|
|||
uint uid = unchecked((uint)id);
|
||||
if (stype == DecalTypeKey)
|
||||
return _host.HasGetObjectWcid && _host.TryGetObjectWcid(uid, out uint wcid) ? unchecked((int)wcid) : defaultValue;
|
||||
if ((stype & 0xFFFFFF00u) == DecalTypeKey)
|
||||
return GetDecalLongKey(uid, stype, defaultValue);
|
||||
if (!_host.HasGetObjectIntProperty) return defaultValue;
|
||||
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decal's other synthetic LongValueKeys (0x0D000001-0x0D00002A, Decal.Adapter's numbering),
|
||||
/// read as the game property each one is. VTank profiles use them: LootSnobV4 has 336 rules on
|
||||
/// MaxDamage and 109 on Coverage. They were read as STypeInt ids, which no object has, so
|
||||
/// they were always 0 and those rules never matched (until 2026-10-07). Icons are the
|
||||
/// portal.dat index without its 0x06000000 base, as Decal gives them. Keys with no property
|
||||
/// here (landblock, monarch, physics flags, spell counts) answer the default.
|
||||
/// </summary>
|
||||
private int GetDecalLongKey(uint uid, uint key, int defaultValue)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case 0x0D000001: return DecalIcon(uid, 8, defaultValue); // Icon
|
||||
case 0x0D000008: { uint s = GetDataIdProperty(unchecked((int)uid), 28); return s != 0 ? unchecked((int)s) : defaultValue; } // AssociatedSpell
|
||||
case 0x0D000029: return DecalIcon(uid, 50, defaultValue); // IconOverlay
|
||||
case 0x0D00002A: return DecalIcon(uid, 52, defaultValue); // IconUnderlay
|
||||
}
|
||||
uint stype = DecalIntStype(key);
|
||||
if (stype == 0 || !_host.HasGetObjectIntProperty) return defaultValue;
|
||||
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>The STypeInt a Decal synthetic long key is, or 0 (not an int property).</summary>
|
||||
public static uint DecalIntStype(uint key) => key switch
|
||||
{
|
||||
0x0D000004 => 6, // ItemSlots -> ItemsCapacity
|
||||
0x0D000005 => 7, // PackSlots -> ContainersCapacity
|
||||
0x0D000006 => 12, // StackCount -> StackSize
|
||||
0x0D000007 => 11, // StackMax -> MaxStackSize
|
||||
0x0D00000B => 10, // WieldingSlot -> CurrentWieldedLocation
|
||||
0x0D00000D => 4, // Coverage -> ClothingPriority
|
||||
0x0D00000E => 9, // EquipableSlots -> ValidLocations
|
||||
0x0D00000F => 51, // EquipType -> CombatUse
|
||||
0x0D000010 => 18, // IconOutline -> UiEffects
|
||||
0x0D000011 => 50, // MissileType -> AmmoType
|
||||
0x0D000012 => 16, // UsageMask -> ItemUseable
|
||||
0x0D000014 => 152, // HookMask -> HookItemType
|
||||
0x0D000015 => 151, // HookType
|
||||
0x0D00001A => 1, // Category -> ItemType
|
||||
0x0D00001F => 49, // WeapSpeed -> WeaponTime
|
||||
0x0D000020 => 48, // EquipSkill -> WeaponSkill
|
||||
0x0D000021 => 45, // DamageType
|
||||
0x0D000022 => 44, // MaxDamage -> Damage (the appraisal's weapon profile)
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
private int DecalIcon(uint uid, uint did, int defaultValue)
|
||||
{
|
||||
uint v = GetDataIdProperty(unchecked((int)uid), did);
|
||||
return v != 0 ? unchecked((int)(v & 0x00FFFFFFu)) : defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read an STypeDID property (e.g. a scroll's Spell 28 from its CreateObject header).
|
||||
/// 0 if the API is unavailable or the property is not set.
|
||||
|
|
@ -1753,6 +1847,24 @@ public class WorldObjectCache
|
|||
get { lock (_gate) return _hazardVersion; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A dungeon cell the character took hotspot damage in ("You suffer 32 damage from acid!"):
|
||||
/// registered and persisted like a sighted hazard, so the patrol reroutes around it now and
|
||||
/// on every later visit. Outdoor cells (a 24 m land cell) are never registered. True when new.
|
||||
/// </summary>
|
||||
public bool RegisterDamageHazardCell(uint cellId, string source)
|
||||
{
|
||||
if (cellId == 0 || (cellId & 0xFFFF) < 0x0100) return false;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_hazardCells.Add(cellId)) return false;
|
||||
_hazardVersion++;
|
||||
}
|
||||
DungeonHazardStore.Append(cellId >> 16, cellId);
|
||||
_host.Log($"[Hazard] took {source} damage in cell 0x{cellId:X8} (persisted)");
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool IsHazardCell(uint cellId)
|
||||
{
|
||||
lock (_gate)
|
||||
|
|
|
|||
|
|
@ -97,6 +97,10 @@ public sealed partial class RynthAiPlugin
|
|||
private bool _currentLootItemMovePending;
|
||||
private bool _corpseAutorunActive;
|
||||
private int _currentLootItemMoveAttempts;
|
||||
private long _currentLootItemStillSince;
|
||||
private long _currentLootItemLeftAt;
|
||||
private bool _currentLootItemSawAnim;
|
||||
private long _pickupAnimSince;
|
||||
private string _currentLootItemActionLabel = string.Empty;
|
||||
private string _currentLootItemName = string.Empty;
|
||||
private bool _currentLootItemIsSalvage;
|
||||
|
|
@ -104,7 +108,9 @@ public sealed partial class RynthAiPlugin
|
|||
private long _corpseIdsRequestedAt;
|
||||
private bool _corpseApproachTurnsActive;
|
||||
|
||||
private static long CorpseNowMs => Environment.TickCount64;
|
||||
/// <summary>The loot clock (ms); the host tests replace it to run minutes of looting at once.</summary>
|
||||
internal static Func<long> CorpseClock = static () => Environment.TickCount64;
|
||||
private static long CorpseNowMs => CorpseClock();
|
||||
private void LootDiag(string message)
|
||||
{
|
||||
Log(message);
|
||||
|
|
@ -142,8 +148,49 @@ public sealed partial class RynthAiPlugin
|
|||
// busy-zero churn) paced the whole loot grind, and the 2026-06-12 09:33
|
||||
// storm of them latched the variant-2 stance/item deadlock.
|
||||
private const long BUSY_TIMEOUT_COMBAT_URGENT_MS = 5_000;
|
||||
// The engine's count is the one owner (2026-10-06; analysis by Silentkelpie, re-implemented
|
||||
// here): this mirror is fed by the engine's busy events, and the engine now sends one for
|
||||
// every UseDone and every reset it does, so the two agree except for events still on their
|
||||
// way. A disagreement that lasts BusyMirrorFollowMs is settled the engine's way; the old
|
||||
// 5/10 s mirror reset below is only for an engine without GetBusyState.
|
||||
private const long BusyMirrorFollowMs = 1_500;
|
||||
private long _busyMismatchSince;
|
||||
private long _lastBusyFollowLogAt;
|
||||
private int _busyFollowsSinceLog;
|
||||
|
||||
private bool FollowEngineBusyCount()
|
||||
{
|
||||
if (!Host.HasGetBusyState) return false;
|
||||
int engine;
|
||||
try { engine = Host.GetBusyState(); } catch { return false; }
|
||||
long now = CorpseNowMs;
|
||||
if (engine == _busyCount) { _busyMismatchSince = 0; return true; }
|
||||
if (_busyMismatchSince == 0) { _busyMismatchSince = now; return true; }
|
||||
if (now - _busyMismatchSince < BusyMirrorFollowMs) return true;
|
||||
int was = _busyCount;
|
||||
_busyMismatchSince = 0;
|
||||
_busyCount = Math.Max(0, engine);
|
||||
_busyCountLastIncrementAt = 0;
|
||||
_busyCountBecamePositiveAt = _busyCount > 0 ? now : 0;
|
||||
if (_combatManager != null) _combatManager.BusyCount = _busyCount;
|
||||
if (_buffManager != null) _buffManager.BusyCount = _busyCount;
|
||||
_busyFollowsSinceLog++;
|
||||
if (now - _lastBusyFollowLogAt >= 10_000)
|
||||
{
|
||||
Log($"[RynthAi] Busy mirror {was} -> {_busyCount}: following the engine's count ({_busyFollowsSinceLog} in the last {(now - _lastBusyFollowLogAt) / 1000.0:0} s; the client's count is never cleared by RynthAi).");
|
||||
_lastBusyFollowLogAt = now;
|
||||
_busyFollowsSinceLog = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void CheckBusyTimeout()
|
||||
{
|
||||
if (FollowEngineBusyCount())
|
||||
{
|
||||
PruneCorpseCollections();
|
||||
return;
|
||||
}
|
||||
if (_busyCount > 0 && _busyCountBecamePositiveAt != 0)
|
||||
{
|
||||
long elapsed = CorpseNowMs - _busyCountBecamePositiveAt;
|
||||
|
|
@ -176,10 +223,17 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (elapsed > threshold)
|
||||
{
|
||||
Log($"[RynthAi] Busy count stuck at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}) — force-clearing.");
|
||||
// Reset pending loot item BEFORE zeroing AC's m_cBusy. If we have an
|
||||
// in-flight UseObject, ForceResetBusyCount zeros m_cBusy under it; the
|
||||
// retry in TickPendingCorpsePickup would then hit a freed AC object and crash.
|
||||
// Our mirror only (2026-10-06). AC's m_cBusy is +1 per action the client sends and
|
||||
// -1 per server UseDone (ClientUISystem::Handle_Item::UseDone, inline - which is why
|
||||
// this mirror, fed by the Increment/Decrement hooks, never saw the decrement and
|
||||
// looked "stuck"). Force-clearing AC's count here zeroed the count of actions the
|
||||
// server had not answered yet (each later UseDone then drove it negative: ~190
|
||||
// repairs an hour in the 10-05/10-06 logs) and let the next action out on top of
|
||||
// them. The pacing waits on the server's answers now (ActionPacer); the client's
|
||||
// own count is left to the client and the engine.
|
||||
bool serverWaiting = RynthCore.Plugin.Shared.ActionPacer.Current(Host) != null;
|
||||
Log($"[RynthAi] Busy mirror at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}" +
|
||||
$"{(serverWaiting ? ", a server action is still unanswered" : "")}) — resetting the mirror only (the client's count is left alone).");
|
||||
ResetCurrentLootItem();
|
||||
_corpseIdsRequested = false;
|
||||
_lastLootActionAt = CorpseNowMs;
|
||||
|
|
@ -188,7 +242,6 @@ public sealed partial class RynthAiPlugin
|
|||
_busyCountBecamePositiveAt = 0;
|
||||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -350,6 +403,13 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
|
||||
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
|
||||
_lootWedgeAnnounced = false;
|
||||
if (_useCheckJumpAt != 0)
|
||||
{
|
||||
Log($"[RynthAi] Use check: 0x{objectId:X8} opened {CorpseNowMs - _useCheckJumpAt} ms after the use check's jump - the jump cleared the server's stuck turn.");
|
||||
_useCheckJumpAt = 0;
|
||||
}
|
||||
ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs);
|
||||
if (switchedTarget)
|
||||
LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}.");
|
||||
|
||||
|
|
@ -476,7 +536,12 @@ public sealed partial class RynthAiPlugin
|
|||
// timeouts). Stop firing opens into a dead client until the halt window
|
||||
// elapses — hammering it can't recover a server-side lock, only a relog
|
||||
// can. Navigation/combat (non-item-action) still run elsewhere.
|
||||
if (CorpseNowMs < _lootHaltUntil)
|
||||
// The use-refusal watch first: it reads the server's answers to our opens, and while it
|
||||
// has decided the server refuses every use (Stuck) no corpse is claimed or opened until
|
||||
// its back-off ends.
|
||||
long haltNow = CorpseNowMs;
|
||||
TickUseRefusalWatch(haltNow);
|
||||
if (haltNow < _lootHaltUntil || _useRefusals.HoldsOpens(haltNow))
|
||||
return;
|
||||
|
||||
// ── Buffing: halt loot work but retain target so looting resumes immediately ──
|
||||
|
|
@ -622,6 +687,29 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
// An open goes out only once the arbiter has given Looting the tick. A corpse claimed on
|
||||
// the tick a fight ended (Combat still owned it) used to be opened at once, and the
|
||||
// arbiter's nav stop (StopCompletely) and Combat's idle peace-mode swap followed 3-30 ms
|
||||
// later. On ACE both cancel the server's walk/turn to the corpse - a mode change runs
|
||||
// HandleActionCancelAttack -> cancel_moveto - so that open could only fail (2026-10-06
|
||||
// 06:18:44, the first failed open of the day's stall). One tick later the stop goes
|
||||
// out first (PauseNavigationForCorpse) and the open after it.
|
||||
if (_activity != BotActivity.Looting)
|
||||
return;
|
||||
|
||||
// One server action at a time (2026-10-06, ActionPacer): no open while the server is still
|
||||
// answering another action - a kit, a cast, a stance change, or the last open itself (a
|
||||
// re-sent open restarts the server's walk and fails the first one's callback). The claim's
|
||||
// 12 s timeout keeps running (the longest wait here is the 5 s limit on an open).
|
||||
if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out _))
|
||||
return;
|
||||
// The last corpse's close is not answered yet (CloseGroundContainer, ~40 ms): a use now makes
|
||||
// the client send its own NoLongerViewingContents for that corpse too (flight recorder
|
||||
// 2026-10-06 07:57:09.801: the engine's close, then the client's, beside the next use).
|
||||
if (_closeSentFor != 0 && _closeSentFor != _targetCorpseId && now - _closeSentAt < CloseAnswerWaitMs
|
||||
&& Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == _closeSentFor)
|
||||
return;
|
||||
|
||||
// Farther than reach: just use the corpse. The server walks the character to it and turns
|
||||
// it (as a player's double-click does); steering there ourselves looked awkward and
|
||||
// turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that
|
||||
|
|
@ -634,8 +722,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (_lastCorpseOpenAttemptAt == 0 || now - _lastCorpseOpenAttemptAt >= walkMs)
|
||||
{
|
||||
if (_busyCount > 0 && now - _lastCorpseOpenAttemptAt < OpenBusyWaitMaxMs) return;
|
||||
AttemptOpenCorpse(_targetCorpseId);
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
if (AttemptOpenCorpse(_targetCorpseId))
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
@ -660,8 +748,8 @@ public sealed partial class RynthAiPlugin
|
|||
return; // busy — hold the open briefly
|
||||
}
|
||||
_corpseOpenBusyWaitSince = 0;
|
||||
AttemptOpenCorpse(_targetCorpseId);
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
if (AttemptOpenCorpse(_targetCorpseId))
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1208,7 +1296,9 @@ public sealed partial class RynthAiPlugin
|
|||
pendingDataCount++;
|
||||
continue;
|
||||
}
|
||||
// Still nameless well past the window — skip this item.
|
||||
// Still nameless well past the window — skip this item (and say so: it used to
|
||||
// leave nothing in the log, so a missed item couldn't be traced).
|
||||
LootDiag($"[LootEval] 0x{(uint)item.Id:X8} on 0x{(uint)corpseId:X8} still has no name after the wait (value={item.Values(19, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)}) -> left");
|
||||
_processedCorpseItems.Add(item.Id);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -1248,7 +1338,7 @@ public sealed partial class RynthAiPlugin
|
|||
// once the assess window expires, so an unappraised item can match a
|
||||
// rule it should not. If keeps correlate with appraised=False, that
|
||||
// is the cause.
|
||||
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
|
||||
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
|
||||
(classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : "leave"));
|
||||
|
||||
if (classified)
|
||||
|
|
@ -1306,8 +1396,14 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
// The last pickup's bend-down still plays: the engine holds a move sent now until
|
||||
// it ends, so wait and send it then.
|
||||
if (PickupAnimating(CorpseNowMs))
|
||||
return;
|
||||
|
||||
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
|
||||
_currentLootItemId = firstMatchId;
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId));
|
||||
Host.SelectItem(unchecked((uint)firstMatchId));
|
||||
LootDiag($"[RynthAi] Corpse loot: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}.");
|
||||
|
||||
|
|
@ -1377,6 +1473,42 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s).</summary>
|
||||
internal const long PickupAnimMaxMs = 3000;
|
||||
|
||||
/// <summary>After the item leaves the corpse: how long to wait for its bend-down to start.</summary>
|
||||
internal const long PickupSettleMs = 1000;
|
||||
|
||||
/// <summary>Off the corpse but not seen in the inventory: counted after this anyway.</summary>
|
||||
internal const long PickupArriveMaxMs = 4000;
|
||||
|
||||
/// <summary>The container is the character or a pack it carries.</summary>
|
||||
private bool InPlayerInventory(int containerId)
|
||||
{
|
||||
if (containerId == 0 || _playerId == 0 || _objectCache == null) return false;
|
||||
int player = unchecked((int)_playerId);
|
||||
return containerId == player || _objectCache.GetContainerId(containerId) == player;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The character still has motions queued (the engine's cast gate, GetCastBusyState):
|
||||
/// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a
|
||||
/// stuck queue can't stop looting, and on an engine without the gate.
|
||||
/// </summary>
|
||||
private bool PickupAnimating(long now)
|
||||
{
|
||||
bool busy;
|
||||
try { busy = Host.HasGetCastBusyState && Host.GetCastBusyState() != 0; } catch { busy = false; }
|
||||
if (!busy)
|
||||
{
|
||||
_pickupAnimSince = 0;
|
||||
return false;
|
||||
}
|
||||
if (_pickupAnimSince == 0)
|
||||
_pickupAnimSince = now;
|
||||
return now - _pickupAnimSince < PickupAnimMaxMs;
|
||||
}
|
||||
|
||||
private void TickPendingCorpsePickup(LegacyUiSettings settings)
|
||||
{
|
||||
if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0)
|
||||
|
|
@ -1390,10 +1522,24 @@ public sealed partial class RynthAiPlugin
|
|||
int currentContainer = currentItem?.Container ?? 0;
|
||||
bool stillVisibleOnCorpse = IsCorpseItemVisible(_openedContainerId, _currentLootItemId);
|
||||
|
||||
// Check every tick — confirm immediately as soon as the item leaves the corpse.
|
||||
// Don't gate this on a timer; the timer only applies to the RETRY path below.
|
||||
// Watch for this pickup's bend-down (the server plays it once the move reaches it).
|
||||
bool animating = PickupAnimating(now);
|
||||
if (animating) _currentLootItemSawAnim = true;
|
||||
|
||||
// Off the corpse is not done yet: confirming then closed the corpse while the pickup was
|
||||
// still under way, and the character picked the last item up after the corpse closed
|
||||
// (2026-10-07). It counts once the item shows up in the inventory (the main pack, a side
|
||||
// pack, or merged into a stack already there: the picked object is gone) and its
|
||||
// bend-down has played out. Off the corpse but never seen in the inventory: counted
|
||||
// after PickupArriveMaxMs anyway, so looting can't stall on it.
|
||||
if (currentItem == null || !stillVisibleOnCorpse || (currentContainer != 0 && currentContainer != _openedContainerId))
|
||||
{
|
||||
if (_currentLootItemLeftAt == 0) _currentLootItemLeftAt = now;
|
||||
bool inInventory = currentItem == null || InPlayerInventory(currentContainer);
|
||||
long since = now - _currentLootItemLeftAt;
|
||||
bool settled = !animating && (_currentLootItemSawAnim || since >= PickupSettleMs);
|
||||
if (!(inInventory && settled) && since < PickupArriveMaxMs)
|
||||
return;
|
||||
ConfirmCurrentLootItemMoved(
|
||||
now,
|
||||
currentItem == null
|
||||
|
|
@ -1404,9 +1550,20 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
// Item still on corpse — wait before retrying the UseObject.
|
||||
// Item still on corpse — wait before retrying the UseObject. The window counts from
|
||||
// when the character is still: while a pickup animation plays the engine holds the
|
||||
// move, and a retry timed from the send gave up on items whose move had not gone
|
||||
// out yet (2026-10-07: moves ran ~2.2 s late, 3 tries at 0.5 s skipped the item).
|
||||
if (PickupAnimating(now))
|
||||
{
|
||||
_currentLootItemStillSince = 0;
|
||||
return;
|
||||
}
|
||||
if (_currentLootItemStillSince == 0)
|
||||
_currentLootItemStillSince = now;
|
||||
long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs);
|
||||
if (now - _currentLootItemMoveRequestedAt < verifyWindowMs)
|
||||
long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince);
|
||||
if (now - windowStart < verifyWindowMs)
|
||||
return;
|
||||
|
||||
if (_currentLootItemMoveAttempts >= 3)
|
||||
|
|
@ -1421,6 +1578,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (_busyCount > 0)
|
||||
return; // Client is busy — don't queue retry
|
||||
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId));
|
||||
Host.SelectItem(unchecked((uint)_currentLootItemId));
|
||||
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
|
||||
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
|
||||
|
|
@ -1555,6 +1713,11 @@ public sealed partial class RynthAiPlugin
|
|||
if (!settings.IsMacroRunning || !settings.EnableLooting)
|
||||
return false;
|
||||
|
||||
// The server refuses every use (UseRefusalWatch, Stuck): no loot work until the back-off
|
||||
// ends, so the arbiter lets nav and combat run on instead of standing at the corpses.
|
||||
if (_openedContainerId == 0 && _useRefusals.HoldsOpens(CorpseNowMs))
|
||||
return false;
|
||||
|
||||
// Already committed to a body, or mid-loot with the container open.
|
||||
if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive)
|
||||
{
|
||||
|
|
@ -2002,10 +2165,6 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (_manaStoneManager == null) return false;
|
||||
if (!Host.HasGetObjectIntProperty) return false;
|
||||
// ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps
|
||||
// one (and its pending-drain count skips them, so the quota never filled): every
|
||||
// high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05.
|
||||
if (ManaStoneManager.IsWandLike(item)) return false;
|
||||
|
||||
int threshold = settings.ManaTapMinMana;
|
||||
if (threshold <= 0) return false;
|
||||
|
|
@ -2220,6 +2379,9 @@ public sealed partial class RynthAiPlugin
|
|||
_currentLootItemMovePending = false;
|
||||
_currentLootItemMoveRequestedAt = 0;
|
||||
_currentLootItemMoveAttempts = 0;
|
||||
_currentLootItemStillSince = 0;
|
||||
_currentLootItemLeftAt = 0;
|
||||
_currentLootItemSawAnim = false;
|
||||
_currentLootItemActionLabel = string.Empty;
|
||||
_currentLootItemName = string.Empty;
|
||||
_currentLootItemIsSalvage = false;
|
||||
|
|
@ -2306,13 +2468,187 @@ public sealed partial class RynthAiPlugin
|
|||
// or a corpse the bot never reached?).
|
||||
private int _lastOpenAttemptCorpseId;
|
||||
|
||||
private void AttemptOpenCorpse(int corpseId)
|
||||
/// <summary>Sends one open. False when the use-refusal watch acted instead (nothing sent).</summary>
|
||||
private bool AttemptOpenCorpse(int corpseId)
|
||||
{
|
||||
long now = CorpseNowMs;
|
||||
bool watch = Host.HasUseDoneSeq;
|
||||
if (watch)
|
||||
{
|
||||
// The previous open, answered with nothing opened, is judged before this one goes out:
|
||||
// a clean stop or a back-off must not land right after a fresh use (it would cancel it).
|
||||
var verdict = _useRefusals.SettleBeforeOpen(now);
|
||||
if (verdict != UseRefusalWatch.Verdict.None)
|
||||
{
|
||||
ApplyUseRefusalVerdict(verdict, now);
|
||||
return false;
|
||||
}
|
||||
|
||||
// The back-off is over and this is the probe: jump first (clears the server's stuck
|
||||
// animation queue, see UseRefusalWatch), send the probe after the pause.
|
||||
if (_useRefusals.TakeProbeJump(now) && TryUseCheckJump(now, "before the probe"))
|
||||
{
|
||||
_lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
_corpseTargetSince = now;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_lastOpenAttemptCorpseId = corpseId;
|
||||
StopCorpseMovement();
|
||||
int seqBefore = watch ? Host.GetUseDoneSeq() : 0;
|
||||
Host.SelectItem(unchecked((uint)corpseId));
|
||||
Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
|
||||
bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
|
||||
if (watch && sent)
|
||||
_useRefusals.OnOpenSent(corpseId, now, seqBefore);
|
||||
LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Server refuses every use (2026-10-06; Loot/UseRefusalWatch.cs) ─────────────────────
|
||||
private readonly UseRefusalWatch _useRefusals = new();
|
||||
private bool _useStuckAnnounced;
|
||||
private bool _lootWedgeAnnounced;
|
||||
|
||||
/// <summary>Every tick while looting runs: the server's answers to our opens.</summary>
|
||||
private void TickUseRefusalWatch(long now)
|
||||
{
|
||||
if (!Host.HasUseDoneSeq)
|
||||
return;
|
||||
int seq = Host.GetUseDoneSeq();
|
||||
bool haveErr = Host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq;
|
||||
ApplyUseRefusalVerdict(_useRefusals.OnTick(now, seq, err, haveErr), now);
|
||||
}
|
||||
|
||||
private void ApplyUseRefusalVerdict(UseRefusalWatch.Verdict verdict, long now)
|
||||
{
|
||||
switch (verdict)
|
||||
{
|
||||
case UseRefusalWatch.Verdict.CleanStopAndRetry:
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened");
|
||||
Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a jump, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try.");
|
||||
Host.SetAutoRunBy("Loot/UseCheck", false);
|
||||
if (Host.HasStopCompletely)
|
||||
Host.StopCompletelyBy("Loot/UseCheck");
|
||||
_corpseAutorunActive = false;
|
||||
_corpseApproachTurnsActive = false;
|
||||
// The jump is the fix (see UseRefusalWatch): it empties the server's animation
|
||||
// queues and cancels the stuck turn; the retry then gets a fresh server turn.
|
||||
bool jumped = TryUseCheckJump(now, "for the retry");
|
||||
// Without a jump: face the corpse for the retry. Since 2026-10-04 the bot leaves the
|
||||
// turn to the server; if the server can't turn the character any more, a corpse already
|
||||
// in front may still open (mid-stall, 06:28:19, a use by hand with the macro off
|
||||
// opened one - the only open in those 13 minutes; whether it was faced isn't logged).
|
||||
if (!jumped && _targetCorpseId != 0 && Host.HasTurnToHeading
|
||||
&& TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _)
|
||||
&& faceErr > 2.0)
|
||||
{
|
||||
Host.TurnToHeadingBy("Loot/UseCheck", (float)faceDeg);
|
||||
Log($"[RynthAi] Use check: facing 0x{(uint)_targetCorpseId:X8} ({faceErr:0} deg off) for the retry.");
|
||||
}
|
||||
_lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
|
||||
_lastCorpseOpenAttemptAt = 0; // the retry goes out as soon as the pause ends
|
||||
if (_targetCorpseId != 0)
|
||||
_corpseTargetSince = now; // and gets a full corpse timeout
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.DropCorpse:
|
||||
{
|
||||
int id = _useRefusals.LastRefusedCorpse;
|
||||
Log($"[RynthAi] Use check: corpse 0x{(uint)id:X8} is answered but never opens - giving up on it; the next corpse tells whether every use is refused.");
|
||||
if (id != 0 && _targetCorpseId == id && _openedContainerId == 0)
|
||||
AbandonCurrentCorpse(now, "refused");
|
||||
else if (id != 0)
|
||||
_corpseCooldownUntil[id] = now + NeverOpenedAbandonRetryMs;
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.Stuck:
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "use check: server refuses every use");
|
||||
Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}.");
|
||||
_useCheckJumpAt = 0;
|
||||
if (!_useStuckAnnounced)
|
||||
{
|
||||
_useStuckAnnounced = true;
|
||||
ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every few minutes.");
|
||||
}
|
||||
ResetCorpseTarget();
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.StillStuck:
|
||||
Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 60_000} min.");
|
||||
_useCheckJumpAt = 0;
|
||||
ResetCorpseTarget();
|
||||
break;
|
||||
case UseRefusalWatch.Verdict.Recovered:
|
||||
Log("[RynthAi] Use check: a corpse opened - uses work again, looting resumes.");
|
||||
if (_useStuckAnnounced)
|
||||
ChatLine("[RynthAi] Objects open again; looting is back on.");
|
||||
_useStuckAnnounced = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When the use check last jumped (0 = not since the last open).</summary>
|
||||
private long _useCheckJumpAt;
|
||||
|
||||
/// <summary>
|
||||
/// One jump in place for the use check. On ACE the jump (0xF61B, the keyboard path: TapJump)
|
||||
/// is the only in-world action that empties the server's animation queues for the character
|
||||
/// (Player.HandleActionJump: RemoveLinkAnimations drains MotionTableManager.PendingAnimations,
|
||||
/// MotionInterp.PendingMotions.Clear(), IsAnimating = false) and it cancels the stuck walk/turn
|
||||
/// (GameActionJump -> StopExistingMoveToChains2). JumpNonAutonomous (0xF7C9) is not used: ACE
|
||||
/// has no handler for it. Not while the pacer has an action out (a jump in Magic stance fails a
|
||||
/// cast on the server).
|
||||
/// </summary>
|
||||
private bool TryUseCheckJump(long now, string why)
|
||||
{
|
||||
if (!Host.HasTapJump)
|
||||
return false;
|
||||
if (ActionPacer.Outstanding(Host, out var pending) && pending != null)
|
||||
{
|
||||
Log($"[RynthAi] Use check: no jump {why} - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)}.");
|
||||
return false;
|
||||
}
|
||||
Host.SetAutoRunBy("Loot/UseCheck", false);
|
||||
bool ok = Host.TapJump();
|
||||
if (ok)
|
||||
_useCheckJumpAt = now;
|
||||
Log($"[RynthAi] Use check: jump {why} (clears the server's stuck animation queue; a relog was the only other fix) ok={ok}.");
|
||||
return ok;
|
||||
}
|
||||
|
||||
private string RefusedList() =>
|
||||
string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}"));
|
||||
|
||||
// The arbiter's wantLoot of the current tick (HasLootWork), for LootHoldsIdlePeace.
|
||||
private bool _lastWantLoot;
|
||||
|
||||
/// <summary>
|
||||
/// CombatManager's idle peace-mode swap waits while looting has work: a corpse to claim, a
|
||||
/// claimed or open corpse, or a door/corpse use the server is still answering. On ACE a
|
||||
/// combat-mode change cancels the server's walk/turn to a used corpse (HandleActionCancelAttack
|
||||
/// -> cancel_moveto), so the swap that went out 3 ms after the 06:18:44 open (2026-10-06) made
|
||||
/// it fail; and between kills in a busy spawn it flipped peace/war every few seconds. Opening a
|
||||
/// corpse needs no peace mode; the swap happens once looting is done.
|
||||
/// </summary>
|
||||
private bool LootHoldsIdlePeace() =>
|
||||
_targetCorpseId != 0
|
||||
|| _openedContainerId != 0
|
||||
|| _lastWantLoot
|
||||
|| RynthCore.Plugin.Shared.UseAudit.WorldUseInFlight(Host, out _);
|
||||
|
||||
/// <summary>A fresh session (logout/login): a relog is what clears a server that refuses uses.</summary>
|
||||
private void ResetUseRefusalState()
|
||||
{
|
||||
_useRefusals.Reset();
|
||||
_useCheckJumpAt = 0;
|
||||
_useStuckAnnounced = false;
|
||||
_lootWedgeAnnounced = false;
|
||||
_consecutiveLootTimeouts = 0;
|
||||
_lootHaltUntil = 0;
|
||||
}
|
||||
|
||||
private void SyncCorpseContainerState()
|
||||
|
|
@ -2551,6 +2887,11 @@ public sealed partial class RynthAiPlugin
|
|||
/// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing
|
||||
/// (the server closes the corpse when the next one is opened, as before).
|
||||
/// </summary>
|
||||
// The last close sent, until the server's CloseGroundContainer answers it (see TickCorpseOpening).
|
||||
private int _closeSentFor;
|
||||
private long _closeSentAt;
|
||||
private const long CloseAnswerWaitMs = 500;
|
||||
|
||||
private void CloseCorpseContainer(int corpseId, string why)
|
||||
{
|
||||
if (corpseId == 0 || !Host.HasCloseContainer)
|
||||
|
|
@ -2562,7 +2903,11 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
|
||||
if (Host.CloseContainer(unchecked((uint)corpseId)))
|
||||
{
|
||||
_closeSentFor = corpseId;
|
||||
_closeSentAt = CorpseNowMs;
|
||||
LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why}).");
|
||||
}
|
||||
else
|
||||
LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why}).");
|
||||
}
|
||||
|
|
@ -2592,7 +2937,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
long ageMs = _corpseTargetSince != 0 ? now - _corpseTargetSince : 0;
|
||||
LootDiag($"[RynthAi] Corpse loot: abandoning corpse 0x{(uint)corpseId:X8} after {ageMs}ms ({reason}).");
|
||||
ChatLine($"[RynthAi] Corpse timeout: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
|
||||
ChatLine($"[RynthAi] Corpse {(reason == "refused" ? "refuses to open" : "timeout")}: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
|
||||
|
||||
// Only a corpse we actually OPENED earns the completed mark (30-min
|
||||
// do-not-touch — its loot is permanently skipped). A never-opened
|
||||
|
|
@ -2664,13 +3009,19 @@ public sealed partial class RynthAiPlugin
|
|||
/// </summary>
|
||||
private void HandleLootWedge(long now)
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "loot wedge");
|
||||
_lootHaltUntil = now + LootWedgeHaltMs;
|
||||
_consecutiveLootTimeouts = 0; // re-arm; if still wedged it trips again after the halt
|
||||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
// Peace only when not already in it (2026-10-06): an unneeded request went to the server as
|
||||
// a raw 0x53 anyway, and on ACE a mode change cancels whatever walk/turn is pending. Not
|
||||
// while a server action is unanswered either (ChangeCombatModeFor holds it then).
|
||||
Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset");
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// No ForceResetBusyCount (2026-10-06): AC's busy count is the count of actions the server
|
||||
// has not answered; zeroing it fixed nothing here (the lock is the server's or the
|
||||
// client's item-request gates below) and let the next action out on top of them.
|
||||
// The lock is client-side: AC's pending-item-request slot or attacking
|
||||
// flag (see the engine's ClientActionGates). Open both now.
|
||||
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions");
|
||||
|
|
@ -2680,7 +3031,12 @@ public sealed partial class RynthAiPlugin
|
|||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
|
||||
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
|
||||
// Once per stall (until a corpse opens): 2026-10-06 it fired 11 times in 13 minutes.
|
||||
if (!_lootWedgeAnnounced)
|
||||
{
|
||||
_lootWedgeAnnounced = true;
|
||||
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
|
||||
}
|
||||
Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired.");
|
||||
}
|
||||
|
||||
|
|
@ -2716,6 +3072,10 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine($"[RynthAi] Corpse ranges: max={ConvertMetersToYards(maxMeters):F1} yd / {maxMeters:F1} m, min={ConvertMetersToYards(minMeters):F1} yd / {minMeters:F1} m");
|
||||
uint rawOpen = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
|
||||
ChatLine($"[RynthAi] Corpse state: target=0x{(uint)_targetCorpseId:X8}, corpse-open=0x{(uint)_openedContainerId:X8}, raw-open=0x{rawOpen:X8}, busy={_busyCount}, inv-update={(_openedContainerInventoryObservedAt != 0 ? 1 : 0)}, completed={_completedCorpses.Count}");
|
||||
long infoNow = CorpseNowMs;
|
||||
ChatLine($"[RynthAi] Use check: {_useRefusals.State}, {_useRefusals.Refusals} refused open(s) since the last open"
|
||||
+ (_useRefusals.HoldsOpens(infoNow) ? $", looting paused {(_useRefusals.BackoffUntil - infoNow) / 1000}s more (the server refuses uses; a relog fixes it)" : "")
|
||||
+ (Host.HasUseDoneSeq ? "" : " (this engine can't report the server's answers: the check is off)"));
|
||||
|
||||
if (TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters))
|
||||
ChatLine($"[RynthAi] Nearest corpse: {corpse!.Name} (0x{(uint)corpse.Id:X8}) at {ConvertMetersToYards(distanceMeters):F1} yd / {distanceMeters:F1} m");
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
|
|||
/// </summary>
|
||||
internal sealed class CreatureProfileStore
|
||||
{
|
||||
internal const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
|
||||
internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
|
||||
private const string FileName = "creatures.json";
|
||||
|
||||
private readonly object _lock = new();
|
||||
|
|
|
|||
|
|
@ -283,7 +283,7 @@ internal static class CreatureWeakness
|
|||
}
|
||||
|
||||
/// <summary>The on-disk copy of the weakness table next to RynthAi (optional; the DLL has one built in).</summary>
|
||||
internal const string WeaknessFile = @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json";
|
||||
internal static readonly string WeaknessFile = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Data", "creature_weakness.json");
|
||||
|
||||
// JSON keys → Elements index (the table spells Lightning "electric").
|
||||
private static readonly (string Key, int Index)[] JsonKeys =
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
internal static class DungeonHazardStore
|
||||
{
|
||||
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
|
||||
private static readonly string Folder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"DungeonHazards");
|
||||
// Settable so the host tests point it at their scratch folder.
|
||||
internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "DungeonHazards");
|
||||
|
||||
private static string PathFor(uint landblockKey)
|
||||
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
internal static class DungeonHazardSurfaces
|
||||
{
|
||||
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
|
||||
private static readonly string Folder = RynthInstallPaths.RynthAiDir;
|
||||
private static readonly string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir;
|
||||
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
|
||||
|
||||
private static readonly object _gate = new();
|
||||
|
|
|
|||
28
Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs
Normal file
28
Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
using System;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Asks the engine's flight recorder (RynthCore Net/FlightRecorder.cs, 2026-10-06) to write its
|
||||
/// buffer: the last minutes of client/server messages and engine markers. Called where RynthAi
|
||||
/// notices a stall (LOOT WEDGE, the use-refusal check, a held-cast nudge), so the dump holds
|
||||
/// the message sequence that led into it. The engine writes at most one automatic dump per
|
||||
/// 10 minutes, so calling this often is harmless. Uses the plugin-command broker (API v64)
|
||||
/// with a name the engine reserves; an engine without the recorder finds no such plugin and
|
||||
/// nothing happens. Never throws.
|
||||
/// </summary>
|
||||
internal static class FlightRecorderSignal
|
||||
{
|
||||
public const string Target = "RynthCore.FlightRecorder";
|
||||
|
||||
public static void Dump(RynthCoreHost host, string reason)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (host.HasSendPluginCommand)
|
||||
host.SendPluginCommand(Target, "dump", "RynthAi " + reason);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
308
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs
Normal file
308
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>One item's appraisal values, as <see cref="ItemInfoText"/> reads them.</summary>
|
||||
internal interface IItemInfoSource
|
||||
{
|
||||
/// <summary>The name the client shows ("" when unknown).</summary>
|
||||
string Name { get; }
|
||||
bool TryInt(uint key, out int value);
|
||||
bool TryFloat(uint key, out double value);
|
||||
/// <summary>The item's spells (empty when none or not appraised).</summary>
|
||||
IReadOnlyList<int> SpellIds { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra iteminfo's text: one item on one chat line, in the spirit of Mag-Tools' item info
|
||||
/// (name, type, set, armor, ratings, damage and mods, imbues, slayer, tinks, spells by name,
|
||||
/// wield and activation requirements, craft, material, value and burden). A field the
|
||||
/// appraisal doesn't carry is left out. Pure: no host calls, so the host tests feed it a
|
||||
/// fake source.
|
||||
/// </summary>
|
||||
internal static class ItemInfoText
|
||||
{
|
||||
// STypeInt (AC / ACE PropertyInt numbering; the names in Meta/PropertyNames.cs).
|
||||
internal const uint IntItemType = 1, IntEncumbrance = 5, IntStackSize = 12, IntRareId = 17, IntValue = 19,
|
||||
IntArmorLevel = 28, IntBonded = 33, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48,
|
||||
IntWeaponTime = 49, IntWorkmanship = 105, IntSpellcraft = 106, IntCurMana = 107, IntMaxMana = 108,
|
||||
IntItemDifficulty = 109, IntAllegianceRankLimit = 110, IntAttuned = 114, IntSkillLevelLimit = 115,
|
||||
IntMaterial = 131, IntWieldReq = 158, IntWieldSkill = 159, IntWieldDiff = 160, IntSlayerType = 166,
|
||||
IntTinks = 171, IntImbued = 179, IntElementalBonus = 204, IntSetId = 265, IntWieldReq2 = 270,
|
||||
IntWieldSkill2 = 271, IntWieldDiff2 = 272, IntItemMaxLevel = 319;
|
||||
|
||||
// STypeFloat (ACE PropertyFloat numbering).
|
||||
internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63,
|
||||
FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152;
|
||||
|
||||
/// <summary>Gear ratings (STypeInt 370-389) and their short tags, in print order.</summary>
|
||||
internal static readonly (uint Key, string Tag)[] Ratings =
|
||||
{
|
||||
(370, "D"), (371, "DR"), (372, "C"), (373, "CR"), (374, "CD"), (375, "CDR"),
|
||||
(376, "HB"), (379, "Vit"), (377, "NR"), (378, "LR"), (388, "OP"), (389, "OPR"),
|
||||
(383, "PvP D"), (384, "PvP DR"),
|
||||
};
|
||||
|
||||
// ItemType flags (STypeInt 1), most specific first.
|
||||
private static readonly (uint Flag, string Name)[] Types =
|
||||
{
|
||||
(0x00040000, "Promissory Note"), (0x00080000, "Mana Stone"), (0x00001000, "Spell Component"),
|
||||
(0x00000800, "Gem"), (0x00004000, "Key"), (0x40000000, "Salvage"), (0x20000000, "Tinkering Tool"),
|
||||
(0x00000200, "Container"), (0x00008000, "Caster"), (0x00000100, "Missile Weapon"),
|
||||
(0x00000001, "Melee Weapon"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
|
||||
(0x00000020, "Food"), (0x00000040, "Money"), (0x00002000, "Writable"), (0x00000080, "Misc"),
|
||||
};
|
||||
|
||||
// ImbuedEffect flags (STypeInt 179).
|
||||
private static readonly (uint Flag, string Name)[] Imbues =
|
||||
{
|
||||
(0x0001, "Critical Strike"), (0x0002, "Crippling Blow"), (0x0004, "Armor Rending"),
|
||||
(0x0008, "Slash Rending"), (0x0010, "Pierce Rending"), (0x0020, "Bludgeon Rending"),
|
||||
(0x0040, "Acid Rending"), (0x0080, "Cold Rending"), (0x0100, "Lightning Rending"),
|
||||
(0x0200, "Fire Rending"), (0x0400, "Melee Defense"), (0x0800, "Missile Defense"),
|
||||
(0x1000, "Magic Defense"), (0x4000, "Nether Rending"),
|
||||
};
|
||||
|
||||
// Equipment sets (STypeInt 265) whose ids are certain: the loot armor sets and Aetheria.
|
||||
private static readonly Dictionary<int, string> Sets = new()
|
||||
{
|
||||
[13] = "Soldier's", [14] = "Adept's", [15] = "Archer's", [16] = "Defender's", [17] = "Tinker's",
|
||||
[18] = "Crafter's", [19] = "Hearty", [20] = "Dexterous", [21] = "Wise", [22] = "Swift",
|
||||
[23] = "Hardened", [24] = "Reinforced", [25] = "Interlocking", [26] = "Flame Proof",
|
||||
[27] = "Acid Proof", [28] = "Cold Proof", [29] = "Lightning Proof",
|
||||
[35] = "Aetheria: Defense", [36] = "Aetheria: Destruction", [37] = "Aetheria: Fury",
|
||||
[38] = "Aetheria: Growth", [39] = "Aetheria: Vigor",
|
||||
};
|
||||
|
||||
// Attributes and vitals for attribute/vital wield requirements (ACE PropertyAttribute / PropertyAttribute2nd).
|
||||
private static readonly string[] Attributes = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
|
||||
private static readonly string[] Vitals = { "", "Max Health", "Health", "Max Stamina", "Stamina", "Max Mana", "Mana" };
|
||||
|
||||
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
||||
|
||||
/// <summary>
|
||||
/// The item on one line. <paramref name="spellName"/> names a spell id (the plugin's
|
||||
/// spell table). <paramref name="identified"/> false adds a note that the server never
|
||||
/// answered the ID, so only what the client already knew is shown.
|
||||
/// </summary>
|
||||
public static string Describe(IItemInfoSource item, Func<int, string> spellName, bool identified = true)
|
||||
{
|
||||
var parts = new List<string>(24);
|
||||
int type = Int(item, IntItemType);
|
||||
|
||||
// Name, with the material in front the way the game names loot ("Gold Ring").
|
||||
string name = item.Name.Trim();
|
||||
int material = Int(item, IntMaterial);
|
||||
string full = WeaponNames.Full(name, material);
|
||||
if (full.Length == 0) full = "(unnamed item)";
|
||||
string typeName = TypeName(type);
|
||||
int stack = Int(item, IntStackSize);
|
||||
var head = new StringBuilder(full);
|
||||
if (stack > 1) head.Append(" x").Append(stack.ToString("N0", Inv));
|
||||
if (typeName.Length > 0) head.Append(" (").Append(typeName).Append(')');
|
||||
parts.Add(head.ToString());
|
||||
|
||||
if (Int(item, IntSetId) is int set and > 0)
|
||||
parts.Add((Sets.TryGetValue(set, out string? setName) ? setName : "Set " + set) + " Set");
|
||||
|
||||
if (item.TryInt(IntArmorLevel, out int al) && (al > 0 || (type & 0x2) != 0))
|
||||
parts.Add("AL " + al.ToString(Inv));
|
||||
|
||||
string ratings = RatingText(item);
|
||||
if (ratings.Length > 0) parts.Add(ratings);
|
||||
|
||||
AddWeapon(item, type, parts);
|
||||
|
||||
string imbues = ImbueText(Int(item, IntImbued));
|
||||
if (imbues.Length > 0) parts.Add(imbues);
|
||||
|
||||
if (Int(item, IntSlayerType) is int slayer and > 0)
|
||||
parts.Add(CreatureTypeNames.Name(slayer) + " Slayer");
|
||||
|
||||
if (item.TryInt(IntTinks, out int tinks) && tinks > 0)
|
||||
parts.Add("Tinks " + tinks.ToString(Inv));
|
||||
|
||||
string spells = SpellText(item.SpellIds, spellName);
|
||||
if (spells.Length > 0) parts.Add(spells);
|
||||
|
||||
string wield = WieldText(item, IntWieldReq, IntWieldSkill, IntWieldDiff);
|
||||
if (wield.Length > 0) parts.Add(wield);
|
||||
string wield2 = WieldText(item, IntWieldReq2, IntWieldSkill2, IntWieldDiff2);
|
||||
if (wield2.Length > 0) parts.Add(wield2);
|
||||
|
||||
if (Int(item, IntSkillLevelLimit) is int skillLimit and > 0) parts.Add("Skill " + skillLimit.ToString(Inv) + " to activate");
|
||||
if (Int(item, IntAllegianceRankLimit) is int rank and > 0) parts.Add("Rank " + rank.ToString(Inv));
|
||||
if (Int(item, IntItemDifficulty) is int diff and > 0) parts.Add("Diff " + diff.ToString(Inv));
|
||||
if (Int(item, IntSpellcraft) is int spellcraft and > 0) parts.Add("Spellcraft " + spellcraft.ToString(Inv));
|
||||
if (item.TryInt(IntMaxMana, out int maxMana) && maxMana > 0)
|
||||
parts.Add("Mana " + (item.TryInt(IntCurMana, out int cur) ? cur.ToString(Inv) + "/" : "") + maxMana.ToString(Inv));
|
||||
if (Int(item, IntItemMaxLevel) is int maxLevel and > 0) parts.Add("Max Level " + maxLevel.ToString(Inv));
|
||||
|
||||
if (item.TryInt(IntWorkmanship, out int craft) && craft > 0) parts.Add("Craft " + craft.ToString(Inv));
|
||||
string matName = WeaponNames.Material(material);
|
||||
if (matName.Length > 0) parts.Add("Mat " + matName);
|
||||
|
||||
if (Int(item, IntBonded) == 1) parts.Add("Bonded");
|
||||
if (Int(item, IntAttuned) == 1) parts.Add("Attuned");
|
||||
if (Int(item, IntRareId) is int rare and > 0) parts.Add("Rare #" + rare.ToString(Inv));
|
||||
|
||||
if (item.TryInt(IntValue, out int value)) parts.Add("Value " + value.ToString("N0", Inv));
|
||||
if (item.TryInt(IntEncumbrance, out int burden)) parts.Add("BU " + burden.ToString("N0", Inv));
|
||||
|
||||
if (!identified) parts.Add("(not identified: no reply from the server)");
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
private static int Int(IItemInfoSource item, uint key) => item.TryInt(key, out int v) ? v : 0;
|
||||
|
||||
/// <summary>The item's kind from its ItemType flags ("" when none is set).</summary>
|
||||
internal static string TypeName(int itemType)
|
||||
{
|
||||
uint t = unchecked((uint)itemType);
|
||||
foreach (var (flag, n) in Types)
|
||||
if ((t & flag) != 0) return n;
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>"[D3 CD2 CDR1]" for the gear ratings that are set; "" for none.</summary>
|
||||
internal static string RatingText(IItemInfoSource item)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var (key, tag) in Ratings)
|
||||
{
|
||||
if (!item.TryInt(key, out int r) || r <= 0) continue;
|
||||
sb.Append(sb.Length == 0 ? "[" : " ").Append(tag).Append(r.ToString(Inv));
|
||||
}
|
||||
return sb.Length == 0 ? "" : sb.Append(']').ToString();
|
||||
}
|
||||
|
||||
private static void AddWeapon(IItemInfoSource item, int type, List<string> parts)
|
||||
{
|
||||
uint t = unchecked((uint)type);
|
||||
bool melee = (t & 0x1) != 0, missile = (t & 0x100) != 0, caster = (t & 0x8000) != 0;
|
||||
bool weapon = melee || missile || caster;
|
||||
|
||||
if (Int(item, IntWeaponSkill) is int skill and > 0 && weapon)
|
||||
parts.Add(SkillName(skill));
|
||||
|
||||
int dmgType = Int(item, IntDamageType);
|
||||
if (item.TryInt(IntDamage, out int max) && max > 0)
|
||||
{
|
||||
string dmg = "Dmg " + max.ToString(Inv);
|
||||
if (item.TryFloat(FloatDamageVariance, out double variance) && variance > 0 && variance < 1)
|
||||
{
|
||||
int min = (int)Math.Round(max * (1.0 - variance), MidpointRounding.AwayFromZero);
|
||||
dmg = $"Dmg {min.ToString(Inv)}-{max.ToString(Inv)}";
|
||||
}
|
||||
string element = DamageTypeName(dmgType);
|
||||
if (element.Length > 0) dmg += " " + element;
|
||||
parts.Add(dmg);
|
||||
}
|
||||
else if (weapon && dmgType > 0)
|
||||
{
|
||||
string element = DamageTypeName(dmgType);
|
||||
if (element.Length > 0) parts.Add(element);
|
||||
}
|
||||
if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg");
|
||||
if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv));
|
||||
|
||||
// Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too.
|
||||
var mods = new List<string>(6);
|
||||
AddPercent(item, FloatWeaponOffense, "atk", mods, weapon);
|
||||
if (missile) AddPercent(item, FloatDamageMod, "dmg", mods, true);
|
||||
if (caster) AddPercent(item, FloatElementalDamage, "vs monsters", mods, true);
|
||||
AddPercent(item, FloatMeleeDefense, "md", mods, weapon);
|
||||
AddPercent(item, FloatMissileDefense, "mid", mods, weapon);
|
||||
AddPercent(item, FloatMagicDefense, "mgd", mods, weapon);
|
||||
AddPercent(item, FloatManaConversion, "mana c", mods, true);
|
||||
if (mods.Count > 0) parts.Add("(" + string.Join(", ", mods) + ")");
|
||||
}
|
||||
|
||||
private static void AddPercent(IItemInfoSource item, uint key, string label, List<string> mods, bool allowed)
|
||||
{
|
||||
if (!allowed || !item.TryFloat(key, out double v) || double.IsNaN(v)) return;
|
||||
// Multipliers (attack, defense, damage) are stored as 1.xx; mana conversion as 0.xx.
|
||||
double pct = key == FloatManaConversion ? v * 100.0 : (v - 1.0) * 100.0;
|
||||
int rounded = (int)Math.Round(pct, MidpointRounding.AwayFromZero);
|
||||
if (rounded == 0) return;
|
||||
mods.Add((rounded > 0 ? "+" : "") + rounded.ToString(Inv) + "% " + label);
|
||||
}
|
||||
|
||||
/// <summary>"Crippling Blow, Fire Rending" for the imbue flags; "" for none.</summary>
|
||||
internal static string ImbueText(int flags)
|
||||
{
|
||||
if (flags == 0) return "";
|
||||
uint f = unchecked((uint)flags);
|
||||
var names = new List<string>(2);
|
||||
foreach (var (flag, n) in Imbues)
|
||||
if ((f & flag) != 0) names.Add(n);
|
||||
return string.Join(", ", names);
|
||||
}
|
||||
|
||||
/// <summary>"Spells: A, B, C" by name, in the item's order, each once; "" for none.</summary>
|
||||
internal static string SpellText(IReadOnlyList<int> spellIds, Func<int, string> spellName)
|
||||
{
|
||||
if (spellIds.Count == 0) return "";
|
||||
var seen = new HashSet<int>();
|
||||
var names = new List<string>(spellIds.Count);
|
||||
foreach (int id in spellIds)
|
||||
{
|
||||
if (id <= 0 || !seen.Add(id)) continue;
|
||||
string n = spellName(id);
|
||||
names.Add(string.IsNullOrWhiteSpace(n) ? "spell " + id.ToString(Inv) : n);
|
||||
}
|
||||
return names.Count == 0 ? "" : "Spells: " + string.Join(", ", names);
|
||||
}
|
||||
|
||||
/// <summary>One wield requirement ("Wield Lvl 180", "Heavy Weapons 375 to wield"); "" for none.</summary>
|
||||
internal static string WieldText(IItemInfoSource item, uint reqKey, uint skillKey, uint diffKey)
|
||||
{
|
||||
int req = Int(item, reqKey);
|
||||
if (req <= 0) return "";
|
||||
int skill = Int(item, skillKey);
|
||||
int diff = Int(item, diffKey);
|
||||
string d = diff.ToString(Inv);
|
||||
return req switch
|
||||
{
|
||||
1 => $"{SkillName(skill)} {d} to wield",
|
||||
2 => $"Base {SkillName(skill)} {d} to wield",
|
||||
3 => $"{Pick(Attributes, skill, "Attribute")} {d} to wield",
|
||||
4 => $"Base {Pick(Attributes, skill, "Attribute")} {d} to wield",
|
||||
5 => $"{Pick(Vitals, skill, "Vital")} {d} to wield",
|
||||
6 => $"Base {Pick(Vitals, skill, "Vital")} {d} to wield",
|
||||
7 => $"Wield Lvl {d}",
|
||||
8 => $"{(diff >= 3 ? "Specialized" : "Trained")} {SkillName(skill)} to wield",
|
||||
12 => $"Heritage {d} to wield",
|
||||
_ => $"Wield requirement {req.ToString(Inv)} ({skill.ToString(Inv)}, {d})",
|
||||
};
|
||||
}
|
||||
|
||||
private static string Pick(string[] names, int i, string fallback) =>
|
||||
i > 0 && i < names.Length ? names[i] : $"{fallback} {i.ToString(Inv)}";
|
||||
|
||||
/// <summary>AC's skill name for a skill id ("skill N" when unknown).</summary>
|
||||
internal static string SkillName(int id)
|
||||
{
|
||||
foreach (var (sid, n) in LootRuleText.Skills)
|
||||
if (sid == id) return n;
|
||||
return "skill " + id.ToString(Inv);
|
||||
}
|
||||
|
||||
/// <summary>The damage type's name ("Slashing/Piercing" etc.); "" for none.</summary>
|
||||
internal static string DamageTypeName(int flags)
|
||||
{
|
||||
if (flags <= 0) return "";
|
||||
foreach (var (id, n) in LootRuleText.DamageTypes)
|
||||
if (id == flags) return n;
|
||||
// Other combinations: the single flags joined.
|
||||
var names = new List<string>(3);
|
||||
foreach (var (id, n) in LootRuleText.DamageTypes)
|
||||
if (id > 0 && (id & (id - 1)) == 0 && (flags & id) != 0) names.Add(n);
|
||||
return string.Join("/", names);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,673 +0,0 @@
|
|||
// 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,
|
||||
// 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
|
||||
// [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270
|
||||
// Spells: Legendary Blood Thirst
|
||||
//
|
||||
// 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
|
||||
// STypeInt/STypeFloat/STypeString id — not Decal's remapped LongValueKey/DoubleValueKey numbers).
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RynthCore.Loot;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>Property reads for one item. Implemented over the live object cache (see
|
||||
/// <see cref="CacheItemPropertySource"/>); a missing property returns false / empty.</summary>
|
||||
internal interface IItemPropertySource
|
||||
{
|
||||
string Name { get; }
|
||||
AcObjectClass ObjectClass { get; }
|
||||
bool TryGetInt(uint stype, out int value);
|
||||
bool TryGetDouble(uint stype, out double value);
|
||||
string GetString(uint stype);
|
||||
/// <summary>Spell ids on the item (inscribed + cantrips), unsorted.</summary>
|
||||
IReadOnlyList<int> SpellIds { get; }
|
||||
}
|
||||
|
||||
/// <summary>Per-call output options, snapshotted from <see cref="MagItemInfoSettings"/>.</summary>
|
||||
internal readonly record struct MagItemInfoOptions(
|
||||
MagItemInfoField Hidden, int HiddenRatings, bool ShowValueAndBurden, bool AllSpells, int MaxListedSpells)
|
||||
{
|
||||
/// <summary>Everything shown, Mag spell filter — used when no settings are loaded yet.</summary>
|
||||
public static readonly MagItemInfoOptions Default = new(MagItemInfoField.None, 0, false, false, 26);
|
||||
|
||||
public static MagItemInfoOptions From(MagItemInfoSettings? s) => s == null
|
||||
? Default
|
||||
: new((MagItemInfoField)s.HiddenFields, s.HiddenRatings, s.ShowValueAndBurden,
|
||||
s.SpellMode == MagItemInfoSettings.SpellModeAll, s.MaxListedSpells);
|
||||
|
||||
public bool Shows(MagItemInfoField f) => (Hidden & f) == 0;
|
||||
}
|
||||
|
||||
/// <summary>Which pet-style line a field lands on (<see cref="MagItemDescription.ToPetLines"/>).</summary>
|
||||
internal enum MagItemSection
|
||||
{
|
||||
/// <summary>Line 1 after the name: set, AL, tinks, applied, craft, keyring.</summary>
|
||||
Identity,
|
||||
/// <summary>Line 2: imbues, slayer, damage, attack/defense/mana-conversion, protections.</summary>
|
||||
Combat,
|
||||
/// <summary>Line 3 lead: the "[D 3, CD 2]" cluster.</summary>
|
||||
Ratings,
|
||||
/// <summary>Line 3 tail: wield / activation / difficulty, value and burden.</summary>
|
||||
Requirements,
|
||||
/// <summary>Line 4: spell names.</summary>
|
||||
Spells,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One described item: the title plus fields tagged with their section, kept in Mag print order
|
||||
/// so <see cref="ToOneLine"/> reproduces the classic line exactly.
|
||||
/// </summary>
|
||||
internal sealed class MagItemDescription
|
||||
{
|
||||
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
|
||||
public string Title = string.Empty;
|
||||
public readonly List<(MagItemSection Section, string Text)> Segments = new();
|
||||
|
||||
public void Add(MagItemSection section, string text)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(text)) Segments.Add((section, text));
|
||||
}
|
||||
|
||||
/// <summary>Classic Mag one-liner: title, then every field comma-separated.</summary>
|
||||
public string ToOneLine()
|
||||
{
|
||||
var sb = new StringBuilder(Title, 256);
|
||||
foreach (var (_, text) in Segments) sb.Append(", ").Append(text);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are
|
||||
/// dropped so plain armor stays short.
|
||||
/// </summary>
|
||||
public List<string> ToPetLines()
|
||||
{
|
||||
var lines = new List<string>(4);
|
||||
|
||||
var identity = new StringBuilder(Title);
|
||||
foreach (string t in Section(MagItemSection.Identity)) identity.Append(", ").Append(t);
|
||||
lines.Add(identity.ToString());
|
||||
|
||||
string combat = string.Join(", ", Section(MagItemSection.Combat));
|
||||
if (combat.Length > 0) lines.Add(combat);
|
||||
|
||||
// Like the pet roster's third line: ratings first, then the rest two-space separated.
|
||||
var tail = new List<string>(2);
|
||||
string ratings = string.Join(", ", Section(MagItemSection.Ratings));
|
||||
if (ratings.Length > 0) tail.Add(ratings);
|
||||
string reqs = string.Join(", ", Section(MagItemSection.Requirements));
|
||||
if (reqs.Length > 0) tail.Add(reqs);
|
||||
if (tail.Count > 0) lines.Add(string.Join(" ", tail));
|
||||
|
||||
var spells = Section(MagItemSection.Spells);
|
||||
if (spells.Count > 0)
|
||||
{
|
||||
// The verbose list is a single pre-labelled "Spells: a; b" segment.
|
||||
lines.Add(spells.Count == 1 && spells[0].StartsWith("Spells:", StringComparison.Ordinal)
|
||||
? spells[0]
|
||||
: "Spells: " + string.Join(", ", spells));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private List<string> Section(MagItemSection section)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (var (s, text) in Segments)
|
||||
if (s == section) list.Add(text);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds the Mag-style item info line.</summary>
|
||||
internal static class MagItemDescriber
|
||||
{
|
||||
// ── ACE PropertyInt ids ──────────────────────────────────────────────────
|
||||
private const uint IntBurden = 5; // EncumbranceVal
|
||||
private const uint IntValue = 19;
|
||||
private const uint IntArmorLevel = 28;
|
||||
private const uint IntResistMagic = 36; // >= 9999 = unenchantable
|
||||
private const uint IntMaxDamage = 44; // Damage
|
||||
private const uint IntDamageType = 45;
|
||||
private const uint IntAttackType = 47;
|
||||
private const uint IntStructure = 92; // keyring uses remaining
|
||||
private const uint IntWorkmanship = 105;
|
||||
private const uint IntItemDifficulty = 109; // arcane lore requirement ("Diff")
|
||||
private const uint IntActivationLevel = 115; // ItemSkillLevelLimit
|
||||
private const uint IntMaterial = 131;
|
||||
private const uint IntWieldReq = 158;
|
||||
private const uint IntWieldSkill = 159;
|
||||
private const uint IntWieldValue = 160;
|
||||
private const uint IntSlayerCreature = 166;
|
||||
private const uint IntNumItemsInMaterial = 170; // salvage: workmanship = 105 / 170
|
||||
private const uint IntTinks = 171;
|
||||
private const uint IntActivationSkill = 176; // AppraisalItemSkill
|
||||
private const uint IntImbued = 179; // ImbuedEffect (+ 303..306 for 2..5)
|
||||
private const uint IntNumKeys = 193;
|
||||
private const uint IntElementalBonus = 204;
|
||||
private const uint IntEquipmentSet = 265;
|
||||
private const uint IntWieldReq2 = 270;
|
||||
private const uint IntWieldSkill2 = 271;
|
||||
private const uint IntWieldValue2 = 272;
|
||||
private const uint IntWeaponType = 353; // mastery
|
||||
private const uint IntUseRequiresSkill = 366;
|
||||
private const uint IntUseRequiresSkillLvl = 367;
|
||||
private const uint IntUseRequiresSpec = 368;
|
||||
private const uint IntUseRequiresLevel = 369;
|
||||
private const uint IntSplitArrows = 9031; // ACECustom SplitArrowCount
|
||||
|
||||
// ── ACE PropertyFloat ids ────────────────────────────────────────────────
|
||||
private const uint FloatArmorVsSlash = 13; // 13..19 = Slash/Pierce/Bludgeon/Cold/Fire/Acid/Electric
|
||||
private const uint FloatVariance = 22;
|
||||
private const uint FloatMaxVelocity = 26;
|
||||
private const uint FloatMeleeDefense = 29; // WeaponDefense
|
||||
private const uint FloatAttack = 62; // WeaponOffense
|
||||
private const uint FloatDamageMod = 63;
|
||||
private const uint FloatCritMultiplier = 136;
|
||||
private const uint FloatManaConversion = 144;
|
||||
private const uint FloatCritFrequency = 147;
|
||||
private const uint FloatMissileDefense = 149;
|
||||
private const uint FloatMagicDefense = 150;
|
||||
private const uint FloatVsMonsters = 152; // ElementalDamageMod
|
||||
private const uint FloatIgnoreArmor = 155; // armor cleaving
|
||||
|
||||
// ── ACE PropertyString ids ───────────────────────────────────────────────
|
||||
private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids
|
||||
|
||||
/// <summary>Gear ratings are small (1..~50). Anything above is a wrong key leaking through.</summary>
|
||||
private const int MaxPlausibleRating = 200;
|
||||
|
||||
/// <summary>Class-specific fields (ub-IT ItemIdentifyFieldSet). Generic fields print for every class.</summary>
|
||||
[Flags]
|
||||
private enum Field
|
||||
{
|
||||
None = 0,
|
||||
DamageType = 1 << 0,
|
||||
CritStats = 1 << 1,
|
||||
Splits = 1 << 2,
|
||||
Cleaves = 1 << 3,
|
||||
Slayer = 1 << 4,
|
||||
Range = 1 << 5,
|
||||
Damage = 1 << 6,
|
||||
AttackBonus = 1 << 7,
|
||||
MeleeDefense = 1 << 8,
|
||||
MissileDefense = 1 << 9,
|
||||
MagicDefense = 1 << 10,
|
||||
ManaConversion = 1 << 11,
|
||||
ArmorCleave = 1 << 12,
|
||||
WeaponDefenses = MeleeDefense | MissileDefense | MagicDefense,
|
||||
}
|
||||
|
||||
private static Field FieldsFor(AcObjectClass cls) => cls switch
|
||||
{
|
||||
AcObjectClass.MissileWeapon => Field.DamageType | Field.CritStats | Field.Splits | Field.Cleaves
|
||||
| Field.Slayer | Field.Range | Field.Damage | Field.WeaponDefenses
|
||||
| Field.ArmorCleave,
|
||||
AcObjectClass.MeleeWeapon => Field.DamageType | Field.CritStats | Field.Cleaves | Field.Slayer
|
||||
| Field.Damage | Field.AttackBonus | Field.WeaponDefenses
|
||||
| Field.ArmorCleave,
|
||||
AcObjectClass.WandStaffOrb => Field.DamageType | Field.CritStats | Field.Slayer | Field.Damage
|
||||
| Field.WeaponDefenses | Field.ManaConversion,
|
||||
AcObjectClass.Jewelry => Field.None,
|
||||
// Armor / clothing / misc: keep Mag's generic bonus lines (shields roll %md etc.).
|
||||
_ => Field.AttackBonus | Field.WeaponDefenses | Field.ManaConversion,
|
||||
};
|
||||
|
||||
/// <summary>Full Mag-style line for one item (name first, comma-separated fields).</summary>
|
||||
public static string Describe(IItemPropertySource item, MagItemInfoOptions options)
|
||||
=> Build(item, options).ToOneLine();
|
||||
|
||||
/// <summary>Reads every enabled field once, tagged by section (one-line or pet-style output).</summary>
|
||||
public static MagItemDescription Build(IItemPropertySource item, MagItemInfoOptions options)
|
||||
{
|
||||
var d = new MagItemDescription();
|
||||
var sb = new StringBuilder(128); // title only
|
||||
AcObjectClass cls = item.ObjectClass;
|
||||
Field fields = FieldsFor(cls);
|
||||
bool Has(Field f) => (fields & f) == f;
|
||||
bool Show(MagItemInfoField f) => options.Shows(f);
|
||||
|
||||
int Int(uint id) => item.TryGetInt(id, out int v) ? v : 0;
|
||||
double Dbl(uint id, double fallback) => item.TryGetDouble(id, out double v) ? v : fallback;
|
||||
|
||||
// ── Name: "[Material ]Name (DamageType Mastery)" ────────────────────────
|
||||
int material = Int(IntMaterial);
|
||||
if (material > 0 && Show(MagItemInfoField.Material))
|
||||
{
|
||||
string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}";
|
||||
// Loot names usually omit the material; don't double it when the name already starts with it.
|
||||
if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase))
|
||||
sb.Append(matName).Append(' ');
|
||||
}
|
||||
sb.Append(item.Name);
|
||||
|
||||
if (Has(Field.DamageType) && Show(MagItemInfoField.TypeMastery))
|
||||
{
|
||||
string dmgType = MagItemInfoTables.DamageTypeName(Int(IntDamageType));
|
||||
int mastery = Int(IntWeaponType);
|
||||
string masteryName = mastery > 0
|
||||
? (MagItemInfoTables.Masteries.TryGetValue(mastery, out string? mn) ? mn : $"Unknown mastery {mastery}")
|
||||
: string.Empty;
|
||||
string inner = $"{dmgType} {masteryName}".Trim();
|
||||
if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')');
|
||||
}
|
||||
d.Title = sb.ToString();
|
||||
|
||||
const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements;
|
||||
string I(int v) => v.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
// ── Set ─────────────────────────────────────────────────────────────────
|
||||
int set = Int(IntEquipmentSet);
|
||||
if (set > 0 && Show(MagItemInfoField.Set))
|
||||
d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
|
||||
|
||||
// ── Armor level ─────────────────────────────────────────────────────────
|
||||
int al = Int(IntArmorLevel);
|
||||
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al));
|
||||
|
||||
// ── 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)));
|
||||
|
||||
if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0)
|
||||
d.Add(Cbt, "AC");
|
||||
|
||||
if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats))
|
||||
{
|
||||
double critMult = Dbl(FloatCritMultiplier, 0);
|
||||
if (critMult > 0) d.Add(Cbt, $"CritMult ({Fmt(critMult)})");
|
||||
double critFreq = Dbl(FloatCritFrequency, 0);
|
||||
if (critFreq > 0) d.Add(Cbt, $"CritFreq ({Fmt(critFreq)})");
|
||||
}
|
||||
|
||||
if (Has(Field.Splits) && Show(MagItemInfoField.Splits))
|
||||
{
|
||||
int splits = Int(IntSplitArrows);
|
||||
if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})");
|
||||
}
|
||||
|
||||
if (Has(Field.Range) && Show(MagItemInfoField.Range))
|
||||
{
|
||||
int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0));
|
||||
if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd");
|
||||
}
|
||||
|
||||
if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike))
|
||||
{
|
||||
int attackType = Int(IntAttackType);
|
||||
int mastery = Int(IntWeaponType);
|
||||
bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0);
|
||||
if (cleaving) d.Add(Cbt, "Cleaving");
|
||||
else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike");
|
||||
else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)");
|
||||
}
|
||||
|
||||
// ── Slayer ──────────────────────────────────────────────────────────────
|
||||
if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer))
|
||||
{
|
||||
string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature));
|
||||
if (slayer != null) d.Add(Cbt, slayer + " Slayer");
|
||||
}
|
||||
|
||||
// ── Tinks + applied materials (TinkerLog) ──────────────────────────────
|
||||
int tinks = Int(IntTinks);
|
||||
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks));
|
||||
if (Show(MagItemInfoField.Applied))
|
||||
{
|
||||
string applied = FormatTinkerLog(item.GetString(StringTinkerLog));
|
||||
if (applied.Length > 0) d.Add(Id, "Applied: " + applied);
|
||||
}
|
||||
|
||||
// ── Damage ──────────────────────────────────────────────────────────────
|
||||
if (Has(Field.Damage) && Show(MagItemInfoField.Damage))
|
||||
AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus),
|
||||
Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1));
|
||||
|
||||
// ── Attack / defense / mana conversion percents ───────────────────────
|
||||
bool defenses = Show(MagItemInfoField.Defenses);
|
||||
if (Has(Field.AttackBonus) && Show(MagItemInfoField.Attack)) AddPercent(d, Dbl(FloatAttack, 1), "%a", 0);
|
||||
if (Has(Field.MeleeDefense) && defenses) AddPercent(d, Dbl(FloatMeleeDefense, 1), "%md", 0);
|
||||
if (Has(Field.MagicDefense) && defenses) AddPercent(d, Dbl(FloatMagicDefense, 1), "%mgc.d", 1);
|
||||
if (Has(Field.MissileDefense) && defenses) AddPercent(d, Dbl(FloatMissileDefense, 1), "%msl.d", 1);
|
||||
if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion))
|
||||
{
|
||||
double mc = Dbl(FloatManaConversion, 0);
|
||||
if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
|
||||
}
|
||||
|
||||
// ── Spells ──────────────────────────────────────────────────────────────
|
||||
bool unenchantable = Int(IntResistMagic) >= 9999;
|
||||
if (Show(MagItemInfoField.Spells))
|
||||
AddSpells(d, item.SpellIds, unenchantable, options.AllSpells, options.MaxListedSpells);
|
||||
|
||||
// ── Requirements ────────────────────────────────────────────────────────
|
||||
if (Show(MagItemInfoField.Wield))
|
||||
{
|
||||
AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue));
|
||||
AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2));
|
||||
}
|
||||
|
||||
if (Show(MagItemInfoField.Activation))
|
||||
{
|
||||
int useLevel = Int(IntUseRequiresLevel);
|
||||
if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel));
|
||||
|
||||
// "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it.
|
||||
int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel);
|
||||
if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel))
|
||||
d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
|
||||
|
||||
// Summoning essences / gems.
|
||||
int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec);
|
||||
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}");
|
||||
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
|
||||
}
|
||||
|
||||
int diff = Int(IntItemDifficulty);
|
||||
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff));
|
||||
|
||||
// ── Workmanship ─────────────────────────────────────────────────────────
|
||||
int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0;
|
||||
if (cls == AcObjectClass.Salvage)
|
||||
{
|
||||
int items = Int(IntNumItemsInMaterial);
|
||||
if (work > 0)
|
||||
{
|
||||
double avg = items > 0 ? (double)work / items : work;
|
||||
d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked
|
||||
{
|
||||
d.Add(Id, "Craft " + I(work));
|
||||
}
|
||||
|
||||
// ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ─────────────
|
||||
if (cls == AcObjectClass.Armor && unenchantable && Show(MagItemInfoField.Protections))
|
||||
{
|
||||
var prot = new StringBuilder("[");
|
||||
for (uint i = 0; i < 7; i++)
|
||||
{
|
||||
if (i > 0) prot.Append('/');
|
||||
prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture));
|
||||
}
|
||||
d.Add(Cbt, prot.Append(']').ToString());
|
||||
}
|
||||
|
||||
if (options.ShowValueAndBurden)
|
||||
{
|
||||
int value = Int(IntValue);
|
||||
if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
|
||||
int burden = Int(IntBurden);
|
||||
if (burden > 0) d.Add(Req, "BU " + I(burden));
|
||||
}
|
||||
|
||||
// ── Ratings ─────────────────────────────────────────────────────────────
|
||||
if (Show(MagItemInfoField.Ratings))
|
||||
d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings));
|
||||
|
||||
if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring)
|
||||
&& item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
d.Add(Id, "Keys: " + I(Int(IntNumKeys)));
|
||||
d.Add(Id, "Uses: " + I(Int(IntStructure)));
|
||||
}
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether
|
||||
/// rend); empty when no known bit is set.</summary>
|
||||
private static string ImbueLabels(int mask)
|
||||
{
|
||||
if (mask == 0) return string.Empty;
|
||||
var sb = new StringBuilder();
|
||||
void Flag(int bit, string label)
|
||||
{
|
||||
if ((mask & bit) == 0) return;
|
||||
if (sb.Length > 0) sb.Append(' ');
|
||||
sb.Append(label);
|
||||
}
|
||||
Flag(0x0001, "CS");
|
||||
Flag(0x0002, "CB");
|
||||
Flag(0x0004, "AR");
|
||||
Flag(0x0008, "SlashRend");
|
||||
Flag(0x0010, "PierceRend");
|
||||
Flag(0x0020, "BludgeRend");
|
||||
Flag(0x0040, "AcidRend");
|
||||
Flag(0x0080, "FrostRend");
|
||||
Flag(0x0100, "LightRend");
|
||||
Flag(0x0200, "FireRend");
|
||||
Flag(0x4000, "NetherRend");
|
||||
Flag(0x0400, "MeleeImbue");
|
||||
Flag(0x0800, "MissileImbue");
|
||||
Flag(0x1000, "MagicImbue");
|
||||
Flag(0x2000, "Hematited");
|
||||
Flag(0x20000000, "MagicAbsorb");
|
||||
return sb.ToString(); // only unknown bits → empty → field skipped
|
||||
}
|
||||
|
||||
/// <summary>Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line).</summary>
|
||||
private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance,
|
||||
int elemBonus, double dmgMod, double vsMonsters)
|
||||
{
|
||||
const MagItemSection Cbt = MagItemSection.Combat;
|
||||
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);
|
||||
}
|
||||
if (variance > 0)
|
||||
d.Add(Cbt, Math.Round(variance, 2).ToString(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%).
|
||||
if (dmgMod > 0 && dmgMod != 1)
|
||||
d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
|
||||
if (vsMonsters > 0 && vsMonsters != 1)
|
||||
d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
|
||||
}
|
||||
|
||||
/// <summary>Mag "18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>"Wield Lvl 180" for a level requirement, else "Heavy Weapons 375".</summary>
|
||||
private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value)
|
||||
{
|
||||
if (value <= 0) return;
|
||||
string v = value.ToString(CultureInfo.InvariantCulture);
|
||||
d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level
|
||||
? "Wield Lvl " + v
|
||||
: SkillName(skillOrAttr) + " " + v);
|
||||
}
|
||||
|
||||
private static string SkillName(int skill) =>
|
||||
MagItemInfoTables.Skills.TryGetValue(skill, out string? name) ? name : $"Skill {skill}";
|
||||
|
||||
/// <summary>
|
||||
/// Mag-Tools spell filter (ub-IT applies it to every item): keep cantrip Impen, Augmented
|
||||
/// (trinket) spells, banes/Impen only on unenchantable gear, level 7+ weapon auras, and
|
||||
/// named high-tier spells (cantrips); drop I–VI, level-7 lore buffs and Incantations.
|
||||
/// Verbose lists every spell (capped) for troubleshooting.
|
||||
/// </summary>
|
||||
private static void AddSpells(MagItemDescription d, IReadOnlyList<int> spellIds, bool unenchantable,
|
||||
bool verbose, int maxVerbose)
|
||||
{
|
||||
if (spellIds.Count == 0) return;
|
||||
var ids = new List<int>(spellIds);
|
||||
ids.Sort();
|
||||
ids.Reverse(); // Mag lists highest spell id first
|
||||
|
||||
var seen = new HashSet<int>();
|
||||
var verboseList = verbose ? new StringBuilder() : null;
|
||||
int shown = 0, skippedVerbose = 0;
|
||||
foreach (int id in ids)
|
||||
{
|
||||
if (!seen.Add(id)) continue;
|
||||
bool known = SpellDatabase.HasSpell(id);
|
||||
if (verboseList != null)
|
||||
{
|
||||
// Verbose is the troubleshooting view: list ids SpellData.txt doesn't know too.
|
||||
if (shown >= maxVerbose) { skippedVerbose++; continue; }
|
||||
verboseList.Append(shown == 0 ? "Spells: " : "; ")
|
||||
.Append(known ? SpellDatabase.GetSpellName(id) : $"Spell {id}");
|
||||
shown++;
|
||||
continue;
|
||||
}
|
||||
if (!known) continue;
|
||||
string name = SpellDatabase.GetSpellName(id);
|
||||
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
|
||||
if (ShouldShowSpell(name, family, difficulty, unenchantable))
|
||||
d.Add(MagItemSection.Spells, name);
|
||||
}
|
||||
if (verboseList == null || verboseList.Length == 0) return;
|
||||
if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)");
|
||||
d.Add(MagItemSection.Spells, verboseList.ToString());
|
||||
}
|
||||
|
||||
private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable)
|
||||
{
|
||||
if (name.Contains("Minor Impenetrability") || name.Contains("Major Impenetrability")
|
||||
|| name.Contains("Epic Impenetrability") || name.Contains("Legendary Impenetrability"))
|
||||
return true;
|
||||
if (name.Contains("Augmented"))
|
||||
return true;
|
||||
|
||||
// Banes / Impen / Brogard's: only meaningful on unenchantable gear (loot armor
|
||||
// already reflects them in AL and protections).
|
||||
bool baneLike = name.Contains(" Bane") || name.Contains("Impen") || name.StartsWith("Brogard", StringComparison.Ordinal);
|
||||
if (baneLike) return unenchantable;
|
||||
|
||||
// Weapon auras (Elysa's Sight .. Swift Killer, Hermetic Link, Vision of the Hunter):
|
||||
// level 7 (300) and 8+ (400+) only.
|
||||
if ((family >= 152 && family <= 158) || family == 195 || family == 325)
|
||||
return difficulty == 300 || difficulty >= 400;
|
||||
|
||||
if (name.EndsWith(" I") || name.EndsWith(" II") || name.EndsWith(" III")
|
||||
|| name.EndsWith(" IV") || name.EndsWith(" V") || name.EndsWith(" VI"))
|
||||
return false;
|
||||
if (difficulty == 300) return false; // level-7 lore buffs (Might of the Lugians …)
|
||||
if (name.Contains("Incantation")) return false;
|
||||
return true; // cantrips: Legendary Strength, Epic Defender …
|
||||
}
|
||||
|
||||
/// <summary>Rating cluster "[D 11, C 8, CD 4]" from ACE Gear* ratings 370–389
|
||||
/// (<see cref="MagItemInfoCatalog.Ratings"/>); bit i of <paramref name="hiddenMask"/> skips rating i.</summary>
|
||||
private static string RatingsCluster(IItemPropertySource item, int hiddenMask)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
var ratings = MagItemInfoCatalog.Ratings;
|
||||
for (int i = 0; i < ratings.Length; i++)
|
||||
{
|
||||
if ((hiddenMask & (1 << i)) != 0) continue;
|
||||
if (!item.TryGetInt(ratings[i].StatId, out int v) || v <= 0 || v > MaxPlausibleRating) continue;
|
||||
sb.Append(sb.Length == 0 ? "[" : ", ").Append(ratings[i].Tag).Append(' ')
|
||||
.Append(v.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
return sb.Length > 0 ? sb.Append(']').ToString() : string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>ACECustom TinkerLog CSV ("64,64,46") → "Steel x2, White Quartz".</summary>
|
||||
private static string FormatTinkerLog(string csv)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(csv)) return string.Empty;
|
||||
var order = new List<int>();
|
||||
var counts = new Dictionary<int, int>();
|
||||
foreach (string raw in csv.Split(','))
|
||||
{
|
||||
if (!int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) || id <= 0)
|
||||
continue;
|
||||
if (counts.TryGetValue(id, out int c)) counts[id] = c + 1;
|
||||
else { counts[id] = 1; order.Add(id); }
|
||||
}
|
||||
var sb = new StringBuilder();
|
||||
foreach (int id in order)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append(", ");
|
||||
sb.Append(MagItemInfoTables.Materials.TryGetValue(id, out string? name) ? name : $"material {id}");
|
||||
if (counts[id] > 1) sb.Append(" x").Append(counts[id]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Max ballistic range (45° arc, v²/g) in yards; 0 when velocity is missing.</summary>
|
||||
private static int MissileRangeYards(double velocity)
|
||||
{
|
||||
if (double.IsNaN(velocity) || velocity <= 0) return 0;
|
||||
double meters = velocity * velocity / 9.8;
|
||||
return (int)Math.Round(meters * 1.0936133);
|
||||
}
|
||||
|
||||
private static string Fmt(double v) => Math.Round(v, 2).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary><see cref="IItemPropertySource"/> over the live client object (RynthCore host reads).</summary>
|
||||
internal sealed class CacheItemPropertySource : IItemPropertySource
|
||||
{
|
||||
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
|
||||
private readonly uint _id;
|
||||
private IReadOnlyList<int>? _spells;
|
||||
|
||||
public CacheItemPropertySource(RynthCore.PluginSdk.RynthCoreHost host, WorldObject wo)
|
||||
{
|
||||
_host = host;
|
||||
_id = unchecked((uint)wo.Id);
|
||||
Name = wo.Name;
|
||||
ObjectClass = wo.ObjectClass;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public AcObjectClass ObjectClass { get; }
|
||||
|
||||
public bool TryGetInt(uint stype, out int value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, stype, out value);
|
||||
}
|
||||
|
||||
public bool TryGetDouble(uint stype, out double value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(_id, stype, out value);
|
||||
}
|
||||
|
||||
public string GetString(uint stype) =>
|
||||
_host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(_id, stype, out string? v) && v != null
|
||||
? v
|
||||
: string.Empty;
|
||||
|
||||
public IReadOnlyList<int> SpellIds => _spells ??= ReadSpells();
|
||||
|
||||
private IReadOnlyList<int> ReadSpells()
|
||||
{
|
||||
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
|
||||
uint[] buf = new uint[128];
|
||||
int n = _host.GetObjectSpellIds(_id, buf, buf.Length);
|
||||
if (n <= 0) return Array.Empty<int>();
|
||||
int take = Math.Min(n, buf.Length);
|
||||
var list = new List<int>(take);
|
||||
for (int i = 0; i < take; i++) list.Add(unchecked((int)buf[i]));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,251 +0,0 @@
|
|||
// MagItemInfoSettings.cs — user options for the Mag-style item info line (/ra iteminfo).
|
||||
//
|
||||
// Stored per character inside LegacyUiSettings.ItemInfoSettings. Field visibility is kept as a
|
||||
// *hidden* bitmask so any field added in a later release shows by default for existing profiles.
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>Toggleable sections of the item info line (bit set in HiddenFields = not printed).</summary>
|
||||
[Flags]
|
||||
public enum MagItemInfoField
|
||||
{
|
||||
None = 0,
|
||||
Material = 1 << 0,
|
||||
TypeMastery = 1 << 1,
|
||||
Set = 1 << 2,
|
||||
ArmorLevel = 1 << 3,
|
||||
Imbues = 1 << 4,
|
||||
ArmorCleave = 1 << 5,
|
||||
CritStats = 1 << 6,
|
||||
Splits = 1 << 7,
|
||||
Range = 1 << 8,
|
||||
CleaveMultiStrike = 1 << 9,
|
||||
Slayer = 1 << 10,
|
||||
Tinks = 1 << 11,
|
||||
Applied = 1 << 12,
|
||||
Damage = 1 << 13,
|
||||
Attack = 1 << 14,
|
||||
Defenses = 1 << 15,
|
||||
ManaConversion = 1 << 16,
|
||||
Spells = 1 << 17,
|
||||
Wield = 1 << 18,
|
||||
Activation = 1 << 19,
|
||||
Difficulty = 1 << 20,
|
||||
Craft = 1 << 21,
|
||||
Protections = 1 << 22,
|
||||
Ratings = 1 << 23,
|
||||
Keyring = 1 << 24,
|
||||
}
|
||||
|
||||
/// <summary>Persisted item-info options (JSON fields; see RynthAiJsonContext IncludeFields).</summary>
|
||||
public sealed class MagItemInfoSettings
|
||||
{
|
||||
/// <summary>Spell list modes for <see cref="SpellMode"/>.</summary>
|
||||
public const int SpellModeMag = 0, SpellModeAll = 1;
|
||||
/// <summary>Mouse triggers for <see cref="ClickTrigger"/>.</summary>
|
||||
public const int ClickOff = 0, ClickLeft = 1, ClickRight = 2;
|
||||
/// <summary>Output layouts for <see cref="Layout"/>.</summary>
|
||||
public const int LayoutOneLine = 0, LayoutPetLines = 1;
|
||||
/// <summary><see cref="DetailChatType"/> value meaning "use <see cref="ChatType"/>".</summary>
|
||||
public const int SameAsHeader = -1;
|
||||
|
||||
// ── When to print ────────────────────────────────────────────────────────
|
||||
/// <summary>Print automatically when an item is selected.</summary>
|
||||
public bool OnSelect;
|
||||
/// <summary>
|
||||
/// Print the selected item after a left (<see cref="ClickLeft"/>) or right (<see cref="ClickRight"/>)
|
||||
/// click in the game world / inventory — also re-prints an item that was already selected.
|
||||
/// </summary>
|
||||
public int ClickTrigger = ClickOff;
|
||||
/// <summary>On-select class filters (manual /ra iteminfo ignores them).</summary>
|
||||
public bool OnSelectWeapons = true;
|
||||
public bool OnSelectArmor = true;
|
||||
public bool OnSelectJewelry = true;
|
||||
public bool OnSelectOther = true;
|
||||
/// <summary>Seconds to wait for an ID before printing partial data.</summary>
|
||||
public float IdTimeoutSec = 3f;
|
||||
|
||||
// ── What to print ────────────────────────────────────────────────────────
|
||||
/// <summary><see cref="MagItemInfoField"/> bits that are NOT printed.</summary>
|
||||
public int HiddenFields;
|
||||
/// <summary>Bit i set = <see cref="MagItemInfoCatalog.Ratings"/>[i] not printed.</summary>
|
||||
public int HiddenRatings;
|
||||
/// <summary>Append ", Value N, BU N".</summary>
|
||||
public bool ShowValueAndBurden;
|
||||
/// <summary><see cref="SpellModeMag"/> (Mag filter) or <see cref="SpellModeAll"/>.</summary>
|
||||
public int SpellMode = SpellModeMag;
|
||||
/// <summary>Cap for the "all spells" list.</summary>
|
||||
public int MaxListedSpells = 26;
|
||||
|
||||
// ── How to print ─────────────────────────────────────────────────────────
|
||||
/// <summary><see cref="LayoutPetLines"/> (pet-roster style lines) or <see cref="LayoutOneLine"/> (Mag one-liner).</summary>
|
||||
public int Layout = LayoutPetLines;
|
||||
/// <summary>AC chat type passed to WriteToChat (selects the chat colour / window).</summary>
|
||||
public int ChatType = 1;
|
||||
/// <summary>Chat type for pet-style lines 2+, or <see cref="SameAsHeader"/>.</summary>
|
||||
public int DetailChatType = SameAsHeader;
|
||||
/// <summary>Text put in front of every line.</summary>
|
||||
public string Prefix = "[RynthAi] ";
|
||||
|
||||
/// <summary>Item Info settings window open.</summary>
|
||||
public bool ShowWindow;
|
||||
|
||||
public bool IsHidden(MagItemInfoField f) => (HiddenFields & (int)f) != 0;
|
||||
|
||||
public void SetHidden(MagItemInfoField f, bool hidden) =>
|
||||
HiddenFields = hidden ? HiddenFields | (int)f : HiddenFields & ~(int)f;
|
||||
|
||||
public bool IsRatingHidden(int index) => (HiddenRatings & (1 << index)) != 0;
|
||||
|
||||
public void SetRatingHidden(int index, bool hidden) =>
|
||||
HiddenRatings = hidden ? HiddenRatings | (1 << index) : HiddenRatings & ~(1 << index);
|
||||
|
||||
/// <summary>Clamp values a hand-edited or older profile could carry out of range.</summary>
|
||||
public void Sanitize()
|
||||
{
|
||||
if (float.IsNaN(IdTimeoutSec) || IdTimeoutSec < 0.5f) IdTimeoutSec = 0.5f;
|
||||
if (IdTimeoutSec > 15f) IdTimeoutSec = 15f;
|
||||
if (SpellMode is not (SpellModeMag or SpellModeAll)) SpellMode = SpellModeMag;
|
||||
MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64);
|
||||
if (ChatType < 0 || ChatType > 31) ChatType = 1;
|
||||
if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader;
|
||||
if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff;
|
||||
if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines;
|
||||
Prefix ??= string.Empty;
|
||||
if (Prefix.Length > 32) Prefix = Prefix[..32];
|
||||
}
|
||||
|
||||
/// <summary>Back to first-run defaults (window stays open).</summary>
|
||||
public void ResetToDefaults()
|
||||
{
|
||||
var d = new MagItemInfoSettings();
|
||||
OnSelect = d.OnSelect;
|
||||
ClickTrigger = d.ClickTrigger;
|
||||
Layout = d.Layout;
|
||||
DetailChatType = d.DetailChatType;
|
||||
OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor;
|
||||
OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther;
|
||||
IdTimeoutSec = d.IdTimeoutSec;
|
||||
HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings;
|
||||
ShowValueAndBurden = d.ShowValueAndBurden;
|
||||
SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells;
|
||||
ChatType = d.ChatType; Prefix = d.Prefix;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Labels for the settings window and the /ra iteminfo field|rating commands.</summary>
|
||||
public static class MagItemInfoCatalog
|
||||
{
|
||||
public readonly record struct FieldInfo(MagItemInfoField Field, string Label, string Example);
|
||||
public readonly record struct RatingInfo(uint StatId, string Tag, string Name);
|
||||
|
||||
/// <summary>In print order.</summary>
|
||||
public static readonly FieldInfo[] Fields =
|
||||
{
|
||||
new(MagItemInfoField.Material, "Material", "Gold Ornate Long Sword"),
|
||||
new(MagItemInfoField.TypeMastery, "Damage type / mastery","(Slash Sword)"),
|
||||
new(MagItemInfoField.Set, "Equipment set", "Noble Relic Set"),
|
||||
new(MagItemInfoField.ArmorLevel, "Armor level", "AL 650"),
|
||||
new(MagItemInfoField.Imbues, "Imbues", "CS, AR, FireRend"),
|
||||
new(MagItemInfoField.ArmorCleave, "Armor cleaving", "AC"),
|
||||
new(MagItemInfoField.CritStats, "Crit mult / freq", "CritMult (1.5), CritFreq (0.15)"),
|
||||
new(MagItemInfoField.Splits, "Split arrows", "Splits (2)"),
|
||||
new(MagItemInfoField.Range, "Missile range", "Range 120yd"),
|
||||
new(MagItemInfoField.CleaveMultiStrike, "Cleaving / Multi-Strike", "Cleaving"),
|
||||
new(MagItemInfoField.Slayer, "Slayer", "Undead Slayer"),
|
||||
new(MagItemInfoField.Tinks, "Tinks", "Tinks 4"),
|
||||
new(MagItemInfoField.Applied, "Applied materials", "Applied: Steel x2"),
|
||||
new(MagItemInfoField.Damage, "Damage", "152.48-236, 0.35v, +18, +10%"),
|
||||
new(MagItemInfoField.Attack, "Attack bonus", "+18%a"),
|
||||
new(MagItemInfoField.Defenses, "Defense bonuses", "12%md, 1.5%mgc.d, 1%msl.d"),
|
||||
new(MagItemInfoField.ManaConversion, "Mana conversion", "6%mc"),
|
||||
new(MagItemInfoField.Spells, "Spells", "Legendary Blood Thirst"),
|
||||
new(MagItemInfoField.Wield, "Wield requirements", "Wield Lvl 180, Heavy Weapons 375"),
|
||||
new(MagItemInfoField.Activation, "Activation / use reqs","Lvl 50, Melee Defense 300 to Activate"),
|
||||
new(MagItemInfoField.Difficulty, "Arcane difficulty", "Diff 270"),
|
||||
new(MagItemInfoField.Craft, "Craft / salvage work", "Craft 8"),
|
||||
new(MagItemInfoField.Protections, "Protections (unenchantable armor)", "[1.0/0.8/1.2/...]"),
|
||||
new(MagItemInfoField.Ratings, "Ratings", "[D 3, CD 2]"),
|
||||
new(MagItemInfoField.Keyring, "Keyring keys / uses", "Keys: 3, Uses: 25"),
|
||||
};
|
||||
|
||||
/// <summary>ACE gear ratings (PropertyInt 370–389) in Mag print order.</summary>
|
||||
public static readonly RatingInfo[] Ratings =
|
||||
{
|
||||
new(370, "D", "Damage"),
|
||||
new(371, "DR", "Damage Resist"),
|
||||
new(372, "C", "Crit"),
|
||||
new(374, "CD", "Crit Damage"),
|
||||
new(373, "CR", "Crit Resist"),
|
||||
new(375, "CDR", "Crit Damage Resist"),
|
||||
new(376, "HB", "Healing Boost"),
|
||||
new(379, "V", "Vitality"),
|
||||
new(377, "NR", "Nether Resist"),
|
||||
new(378, "LR", "Life Resist"),
|
||||
new(383, "PKD", "PK Damage"),
|
||||
new(384, "PKDR", "PK Damage Resist"),
|
||||
new(388, "OP", "Overpower"),
|
||||
new(389, "OPR", "Overpower Resist"),
|
||||
};
|
||||
|
||||
/// <summary>Labels for <see cref="MagItemInfoSettings.ClickTrigger"/>, indexed by value.</summary>
|
||||
public static readonly string[] ClickTriggers = { "Off", "Left mouse click", "Right mouse click" };
|
||||
|
||||
/// <summary>Labels for <see cref="MagItemInfoSettings.Layout"/>, indexed by value.</summary>
|
||||
public static readonly string[] Layouts = { "One line (Mag-Tools)", "Pet-style lines" };
|
||||
|
||||
/// <summary>Common AC chat types for the colour picker (value passed to WriteToChat).</summary>
|
||||
public static readonly (int Type, string Label)[] ChatTypes =
|
||||
{
|
||||
(0, "0 - Broadcast"),
|
||||
(1, "1 - RynthAi default"),
|
||||
(2, "2 - Speech"),
|
||||
(3, "3 - Tell"),
|
||||
(4, "4 - Outgoing tell"),
|
||||
(5, "5 - System"),
|
||||
(6, "6 - Combat"),
|
||||
(7, "7 - Magic"),
|
||||
(8, "8 - Channels"),
|
||||
(10, "10 - Social"),
|
||||
(12, "12 - Emote"),
|
||||
(13, "13 - Advancement"),
|
||||
(15, "15 - Help"),
|
||||
(16, "16 - Appraisal"),
|
||||
(17, "17 - Spellcasting"),
|
||||
(18, "18 - Allegiance"),
|
||||
(19, "19 - Fellowship"),
|
||||
(21, "21 - Combat (enemy)"),
|
||||
(22, "22 - Combat (self)"),
|
||||
(24, "24 - Craft"),
|
||||
(25, "25 - Salvaging"),
|
||||
};
|
||||
|
||||
/// <summary>Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery").</summary>
|
||||
public static bool TryFindField(string key, out MagItemInfoField field)
|
||||
{
|
||||
foreach (var f in Fields)
|
||||
{
|
||||
if (f.Field.ToString().Equals(key, StringComparison.OrdinalIgnoreCase)
|
||||
|| f.Label.Replace(" ", string.Empty).StartsWith(key, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
field = f.Field;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
field = MagItemInfoField.None;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Rating index by tag ("CD") or name ("critdamage"), case-insensitive.</summary>
|
||||
public static int FindRating(string key)
|
||||
{
|
||||
for (int i = 0; i < Ratings.Length; i++)
|
||||
{
|
||||
if (Ratings[i].Tag.Equals(key, StringComparison.OrdinalIgnoreCase)
|
||||
|| Ratings[i].Name.Replace(" ", string.Empty).Equals(key, StringComparison.OrdinalIgnoreCase))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
// MagItemInfoTables.cs — name tables for the Mag-style item info line (MagItemDescriber).
|
||||
// Skill / mastery / set / material names follow UtilityBelt ub-IT (Lib/ItemInfoHelper/Dictionaries.cs,
|
||||
// itself from Mag-Tools / Alinco / VTank). Slayer names use the full ACE CreatureType enum instead of
|
||||
// ub-IT's 17-entry subset so every slayer resolves.
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
internal static class MagItemInfoTables
|
||||
{
|
||||
/// <summary>Skill id → name (wield / activation / summoning requirements).</summary>
|
||||
public static readonly Dictionary<int, string> Skills = new()
|
||||
{
|
||||
{ 0x01, "Axe" }, { 0x02, "Bow" }, { 0x03, "Crossbow" }, { 0x04, "Dagger" }, { 0x05, "Mace" },
|
||||
{ 0x06, "Melee Defense" }, { 0x07, "Missile Defense" }, { 0x08, "Sling" }, { 0x09, "Spear" },
|
||||
{ 0x0A, "Staff" }, { 0x0B, "Sword" }, { 0x0C, "Thrown Weapons" }, { 0x0D, "Unarmed Combat" },
|
||||
{ 0x0E, "Arcane Lore" }, { 0x0F, "Magic Defense" }, { 0x10, "Mana Conversion" },
|
||||
{ 0x12, "Item Tinkering" }, { 0x13, "Assess Person" }, { 0x14, "Deception" }, { 0x15, "Healing" },
|
||||
{ 0x16, "Jump" }, { 0x17, "Lockpick" }, { 0x18, "Run" }, { 0x1B, "Assess Creature" },
|
||||
{ 0x1C, "Weapon Tinkering" }, { 0x1D, "Armor Tinkering" }, { 0x1E, "Magic Item Tinkering" },
|
||||
{ 0x1F, "Creature Enchantment" }, { 0x20, "Item Enchantment" }, { 0x21, "Life Magic" },
|
||||
{ 0x22, "War Magic" }, { 0x23, "Leadership" }, { 0x24, "Loyalty" }, { 0x25, "Fletching" },
|
||||
{ 0x26, "Alchemy" }, { 0x27, "Cooking" }, { 0x28, "Salvaging" }, { 0x29, "Two Handed Combat" },
|
||||
{ 0x2A, "Gearcraft" }, { 0x2B, "Void" }, { 0x2C, "Heavy Weapons" }, { 0x2D, "Light Weapons" },
|
||||
{ 0x2E, "Finesse Weapons" }, { 0x2F, "Missile Weapons" }, { 0x30, "Shield" }, { 0x31, "Dual Wield" },
|
||||
{ 0x32, "Recklessness" }, { 0x33, "Sneak Attack" }, { 0x34, "Dirty Fighting" }, { 0x35, "Challenge" },
|
||||
{ 0x36, "Summoning" },
|
||||
};
|
||||
|
||||
/// <summary>ACE PropertyInt.WeaponType (353) → mastery name.</summary>
|
||||
public static readonly Dictionary<int, string> Masteries = new()
|
||||
{
|
||||
{ 1, "Unarmed Weapon" }, { 2, "Sword" }, { 3, "Axe" }, { 4, "Mace" }, { 5, "Spear" }, { 6, "Dagger" },
|
||||
{ 7, "Staff" }, { 8, "Bow" }, { 9, "Crossbow" }, { 10, "Thrown" }, { 11, "Two Handed Combat" }, { 12, "Wand" },
|
||||
};
|
||||
|
||||
/// <summary>ACE PropertyInt.MaterialType (131) → material name.</summary>
|
||||
public static readonly Dictionary<int, string> Materials = new()
|
||||
{
|
||||
{ 1, "Ceramic" }, { 2, "Porcelain" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" }, { 7, "Velvet" },
|
||||
{ 8, "Wool" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" }, { 13, "Aquamarine" },
|
||||
{ 14, "Azurite" }, { 15, "Bag of Abyssal-Touched" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
|
||||
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" },
|
||||
{ 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" },
|
||||
{ 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
|
||||
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" },
|
||||
{ 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smokey Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" },
|
||||
{ 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" },
|
||||
{ 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" },
|
||||
{ 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" },
|
||||
{ 55, "Reed Shark Hide" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" },
|
||||
{ 61, "Iron" }, { 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 66, "Alabaster" },
|
||||
{ 67, "Granite" }, { 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" },
|
||||
{ 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
|
||||
};
|
||||
|
||||
/// <summary>ACE PropertyInt.EquipmentSetId (265) → set name.</summary>
|
||||
public static readonly Dictionary<int, string> EquipmentSets = BuildSets();
|
||||
|
||||
/// <summary>ACE CreatureType enum, index = value (0..101). Used for SlayerCreatureType (166).</summary>
|
||||
private static readonly string[] CreatureTypes =
|
||||
{
|
||||
"Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker",
|
||||
"Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo",
|
||||
"Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus",
|
||||
"Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman",
|
||||
"Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny",
|
||||
"Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion",
|
||||
"Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun",
|
||||
"Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental",
|
||||
"Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken",
|
||||
"Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", "Target",
|
||||
"Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", "Remoran", "Swarm",
|
||||
"Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", "Paradox Olthoi", "Harvest",
|
||||
"Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", "Gear Knight", "Gurog", "A'nekshay",
|
||||
};
|
||||
|
||||
/// <summary>Slayer creature name, or null for 0 / unknown values.</summary>
|
||||
public static string? CreatureTypeName(int value) =>
|
||||
value > 0 && value < CreatureTypes.Length ? CreatureTypes[value] : null;
|
||||
|
||||
/// <summary>
|
||||
/// ACE DamageType flags (45) → "Slash", "Slash/Pierce", "Lightning" … Empty when no known bit is set.
|
||||
/// </summary>
|
||||
public static string DamageTypeName(int flags)
|
||||
{
|
||||
if (flags <= 0) return string.Empty;
|
||||
var sb = new StringBuilder();
|
||||
void Add(int bit, string name)
|
||||
{
|
||||
if ((flags & bit) == 0) return;
|
||||
if (sb.Length > 0) sb.Append('/');
|
||||
sb.Append(name);
|
||||
}
|
||||
Add(0x001, "Slash");
|
||||
Add(0x002, "Pierce");
|
||||
Add(0x004, "Bludgeon");
|
||||
Add(0x008, "Cold");
|
||||
Add(0x010, "Fire");
|
||||
Add(0x020, "Acid");
|
||||
Add(0x040, "Lightning");
|
||||
Add(0x400, "Nether");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static Dictionary<int, string> BuildSets()
|
||||
{
|
||||
var d = new Dictionary<int, string>
|
||||
{
|
||||
{ 2, "Test" }, { 4, "Carraida's Benediction" }, { 5, "Noble Relic Set" }, { 6, "Ancient Relic Set" },
|
||||
{ 7, "Relic Alduressa Set" }, { 8, "Shou-jen Set" }, { 9, "Empyrean Rings Set" },
|
||||
{ 10, "Arm, Mind, Heart Set" }, { 11, "Coat of the Perfect Light Set" },
|
||||
{ 12, "Leggings of Perfect Light Set" }, { 13, "Soldier's Set" }, { 14, "Adept's Set" },
|
||||
{ 15, "Archer's Set" }, { 16, "Defender's Set" }, { 17, "Tinker's Set" }, { 18, "Crafter's Set" },
|
||||
{ 19, "Hearty Set" }, { 20, "Dexterous Set" }, { 21, "Wise Set" }, { 22, "Swift Set" },
|
||||
{ 23, "Hardened Set" }, { 24, "Reinforced Set" }, { 25, "Interlocking Set" },
|
||||
{ 26, "Flame Proof Set" }, { 27, "Acid Proof Set" }, { 28, "Cold Proof Set" },
|
||||
{ 29, "Lightning Proof Set" }, { 30, "Dedication Set" }, { 31, "Gladiatorial Clothing Set" },
|
||||
{ 32, "Ceremonial Clothing" }, { 33, "Protective Clothing" }, { 34, "Noobie Armor" },
|
||||
{ 35, "Sigil of Defense" }, { 36, "Sigil of Destruction" }, { 37, "Sigil of Fury" },
|
||||
{ 38, "Sigil of Growth" }, { 39, "Sigil of Vigor" }, { 40, "Heroic Protector Set" },
|
||||
{ 41, "Heroic Destroyer Set" }, { 42, "Olthoi Armor D Red" }, { 43, "Olthoi Armor C Rat" },
|
||||
{ 44, "Olthoi Armor C Red" }, { 45, "Olthoi Armor D Rat" }, { 46, "Upgraded Relic Alduressa Set" },
|
||||
{ 47, "Upgraded Ancient Relic Set" }, { 48, "Upgraded Noble Relic Set" },
|
||||
{ 49, "Weave of Alchemy" }, { 50, "Weave of Arcane Lore" }, { 51, "Weave of Armor Tinkering" },
|
||||
{ 52, "Weave of Assess Person" }, { 53, "Weave of Light Weapons" }, { 54, "Weave of Missile Weapons" },
|
||||
{ 55, "Weave of Cooking" }, { 56, "Weave of Creature Enchantment" }, { 57, "Weave of Missile Weapons" },
|
||||
{ 58, "Weave of Finesse" }, { 59, "Weave of Deception" }, { 60, "Weave of Fletching" },
|
||||
{ 61, "Weave of Healing" }, { 62, "Weave of Item Enchantment" }, { 63, "Weave of Item Tinkering" },
|
||||
{ 64, "Weave of Leadership" }, { 65, "Weave of Life Magic" }, { 66, "Weave of Loyalty" },
|
||||
{ 67, "Weave of Light Weapons" }, { 68, "Weave of Magic Defense" },
|
||||
{ 69, "Weave of Magic Item Tinkering" }, { 70, "Weave of Mana Conversion" },
|
||||
{ 71, "Weave of Melee Defense" }, { 72, "Weave of Missile Defense" }, { 73, "Weave of Salvaging" },
|
||||
{ 74, "Weave of Light Weapons" }, { 75, "Weave of Light Weapons" }, { 76, "Weave of Heavy Weapons" },
|
||||
{ 77, "Weave of Missile Weapons" }, { 78, "Weave of Two Handed Combat" }, { 79, "Weave of Light Weapons" },
|
||||
{ 80, "Weave of Void Magic" }, { 81, "Weave of War Magic" }, { 82, "Weave of Weapon Tinkering" },
|
||||
{ 83, "Weave of Assess Creature" }, { 84, "Weave of Dirty Fighting" }, { 85, "Weave of Dual Wield" },
|
||||
{ 86, "Weave of Recklessness" }, { 87, "Weave of Shield" }, { 88, "Weave of Sneak Attack" },
|
||||
{ 89, "Ninja_New" }, { 90, "Weave of Summoning" }, { 91, "Shrouded Soul" }, { 92, "Darkened Mind" },
|
||||
{ 93, "Clouded Spirit" }, { 130, "Shimmering Shadows" }, { 131, "Brown Society Locket" },
|
||||
{ 132, "Yellow Society Locket" }, { 133, "Red Society Band" }, { 134, "Green Society Band" },
|
||||
{ 135, "Purple Society Band" }, { 136, "Blue Society Band" }, { 137, "Gauntlet Garb" },
|
||||
{ 138, "Paragon" }, { 139, "Paragon" }, { 140, "Paragon" },
|
||||
};
|
||||
|
||||
// 94..129: Minor / Major / Blackfire × Stinging / Sparking / Smoldering / Shivering ×
|
||||
// Shrouded Soul / Darkened Mind / Clouded Spirit (same order as the VTank set list).
|
||||
string[] tiers = { "Minor", "Major", "Blackfire" };
|
||||
string[] souls = { "Shrouded Soul", "Darkened Mind", "Clouded Spirit" };
|
||||
string[] elements = { "Stinging", "Sparking", "Smoldering", "Shivering" };
|
||||
int id = 94;
|
||||
foreach (string tier in tiers)
|
||||
foreach (string soul in souls)
|
||||
foreach (string element in elements)
|
||||
d[id++] = $"{tier} {element} {soul}";
|
||||
return d;
|
||||
}
|
||||
}
|
||||
27
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs
Normal file
27
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Items RynthAi selects by itself (the looter picking an item up, a meta's selectitem), so the
|
||||
/// selection-change handler can tell them from the player's own clicks: Item Info on select
|
||||
/// prints only for the player's. <see cref="Mark"/> goes right before Host.SelectItem.
|
||||
/// </summary>
|
||||
internal static class SelfSelect
|
||||
{
|
||||
/// <summary>A selection change this soon after <see cref="Mark"/>, for the same id, is ours.</summary>
|
||||
internal const long WindowMs = 2000;
|
||||
|
||||
internal static Func<long> Clock = () => Environment.TickCount64;
|
||||
|
||||
private static uint _id;
|
||||
private static long _at;
|
||||
|
||||
internal static void Mark(uint id)
|
||||
{
|
||||
_at = Clock();
|
||||
_id = id;
|
||||
}
|
||||
|
||||
internal static bool IsOurs(uint id) => id != 0 && id == _id && Clock() - _at <= WindowMs;
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
private string? _serverNamesEdit;
|
||||
|
||||
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
||||
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
|
||||
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
||||
|
||||
public LegacyAdvancedSettingsUi(LegacyUiSettings settings)
|
||||
|
|
@ -214,6 +215,14 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>One cell of the Protections and Banes grid: ticked = cast it.</summary>
|
||||
private void BuffToggle((string Buff, string Label) toggle)
|
||||
{
|
||||
bool on = !_settings.IsBuffDisabled(toggle.Buff);
|
||||
if (ImGui.Checkbox($"{toggle.Label}##buff_{toggle.Buff}", ref on))
|
||||
_settings.SetBuffEnabled(toggle.Buff, on);
|
||||
}
|
||||
|
||||
private void RenderTabContent(int tabIndex)
|
||||
{
|
||||
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
|
||||
|
|
@ -295,6 +304,9 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
|
||||
ImGui.Checkbox("Escape Acid and Lava", ref _settings.EscapeHazards);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose.");
|
||||
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
|
||||
|
||||
ImGui.Separator();
|
||||
|
|
@ -430,6 +442,9 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.SetNextItemWidth(120);
|
||||
ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100);
|
||||
ImGui.SetNextItemWidth(120);
|
||||
ImGui.SliderInt("Re-stam To", ref _settings.RestamTo, 0, 100);
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before.");
|
||||
ImGui.SetNextItemWidth(120);
|
||||
ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100);
|
||||
|
||||
ImGui.Spacing();
|
||||
|
|
@ -527,12 +542,12 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
"Below 200ms may cause fizzles or dropped casts on laggy servers.");
|
||||
|
||||
ImGui.SetNextItemWidth(180);
|
||||
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 250, 5000);
|
||||
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Delay between offensive (war/void) COMBAT casts only.\n" +
|
||||
"Spacing casts ~1-2s (1500ms default) stops back-to-back\n" +
|
||||
"\"You're too busy!\" refusals that drop casts and cost kills.\n" +
|
||||
"Least time between offensive (war/void) COMBAT casts at one target.\n" +
|
||||
"The next cast also waits until the last one is finished (the server's\n" +
|
||||
"answer and the casting animation), so 0 = cast again as soon as it is.\n" +
|
||||
"Does NOT affect buffing speed.");
|
||||
|
||||
ImGui.Spacing();
|
||||
|
|
@ -546,6 +561,12 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.InputInt("Min Blast Targets", ref _settings.MinBlastTargets);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.");
|
||||
ImGui.InputInt("Wall Range (0 = off)", ref _settings.WallRange);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Monster rules with Wall on cast their element's wall spell when enough monsters\n" +
|
||||
"are within this many yards in the wall's path toward the target.\n" +
|
||||
"The character turns to face the target first. 0 = no walls.");
|
||||
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
|
|
@ -599,7 +620,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
|
||||
_settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Follow stops this close to its leader; the nav marker ring shows it.");
|
||||
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Up to 2 nav walks right up to each point before turning (tight dungeons); bigger values round corners. Follow stops this close to its leader; the nav marker ring shows it.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Text("Nav Marker Display");
|
||||
|
|
@ -619,6 +640,11 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Checkbox("Show Terrain Passability", ref _settings.ShowTerrainPassability);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Highlight impassable terrain triangles in red.");
|
||||
ImGui.SetNextItemWidth(160);
|
||||
ImGui.Combo("Waypoint Labels", ref _settings.NavLabelMode, NavLabelModeNames, NavLabelModeNames.Length);
|
||||
ImGui.Checkbox("Guide Line", ref _settings.NavGuideLine);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("A line from your character to the waypoint nav is heading for.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
|
|
@ -689,7 +715,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.InputFloat("Lookahead (yd)", ref _settings.NavLookaheadYards, 0.5f, 1f, "%.1f");
|
||||
if (_settings.NavLookaheadYards < 0f) _settings.NavLookaheadYards = 0f;
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
|
||||
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to round corners. The nav point reach limits it to 2 yd per yard of reach over 1 yd (no rounding up to a 2 yd reach), never more than this. 0 = off (aim straight at each waypoint).");
|
||||
|
||||
ImGui.SetNextItemWidth(80);
|
||||
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
|
||||
|
|
@ -753,6 +779,31 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
"For servers with buff augments, where your own cast is stronger or\n" +
|
||||
"lasts longer. On by default: on retail it costs a few extra casts.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
ImGui.Text("Protections and Banes");
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Untick a protection or bane to stop the bot casting it.\n" +
|
||||
"Unticked buffs are skipped and never hold the bot in Buffing.\n" +
|
||||
"All on by default.");
|
||||
if (ImGui.BeginTable("##protsBanes", 2, ImGuiTableFlags.SizingStretchSame))
|
||||
{
|
||||
ImGui.TableSetupColumn("Protections");
|
||||
ImGui.TableSetupColumn("Banes");
|
||||
ImGui.TableHeadersRow();
|
||||
int rows = Math.Max(BuffManager.ToggleProtections.Length, BuffManager.ToggleBanes.Length);
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
ImGui.TableNextRow();
|
||||
ImGui.TableSetColumnIndex(0);
|
||||
if (i < BuffManager.ToggleProtections.Length) BuffToggle(BuffManager.ToggleProtections[i]);
|
||||
ImGui.TableSetColumnIndex(1);
|
||||
if (i < BuffManager.ToggleBanes.Length) BuffToggle(BuffManager.ToggleBanes[i]);
|
||||
}
|
||||
ImGui.EndTable();
|
||||
}
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
|
||||
|
|
@ -802,6 +853,9 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
|
||||
ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoOnSelect);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Selecting an item prints its details to chat (/ra iteminfo).");
|
||||
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");
|
||||
|
|
|
|||
|
|
@ -60,16 +60,16 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
// escaped the snapshot poll's reverse-P/Invoke boundary it fail-fasted the
|
||||
// NativeAOT runtime. Copy-under-lock on read; lock the Clear+AddRange swap.
|
||||
private readonly object _profileListsLock = new();
|
||||
private readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
private readonly string _lootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
private readonly string _metaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
private readonly string _navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
private readonly string _lootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
private readonly string _metaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
// Profiles are kept per server: SettingsProfiles\<server>\<character> and
|
||||
// MonsterProfiles\<server>\<character>.json, the server being the world name
|
||||
// the server sends at login. Before 2026-09-28 every server shared
|
||||
// SettingsProfiles\ACEmulator, so the same character name on two servers
|
||||
// shared one profile; that folder is still used when no name is known.
|
||||
private const string ProfilesBase = @"C:\Games\RynthSuite\RynthAi\SettingsProfiles";
|
||||
private const string MonstersBase = @"C:\Games\RynthSuite\RynthAi\MonsterProfiles";
|
||||
private static readonly string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
|
||||
private static readonly string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles");
|
||||
private const string LegacyServerFolder = "ACEmulator";
|
||||
private string _serverFolder = LegacyServerFolder;
|
||||
private string _settingsRoot => Path.Combine(ProfilesBase, _serverFolder);
|
||||
|
|
@ -113,7 +113,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
private DateTime _sessionStartUtc = DateTime.UtcNow;
|
||||
private long _sessionKills; // Interlocked: incremented on the pump thread, read in the snapshot
|
||||
private double _killsPerHour;
|
||||
private long _lastKillTicks; // DateTime.UtcNow.Ticks of the last kill (0 = none yet this session)
|
||||
/// <summary>The plugin's kill clock (secsSinceLastKill); set once at plugin init.</summary>
|
||||
internal KillClock? KillClock { get; set; }
|
||||
// volatile: written on the pump thread (SetFreeSlots/SetComponentCounts), read on the snapshot-poll
|
||||
// thread (BuildSnapshotJson). x86 int writes are atomic but give no visibility guarantee — without
|
||||
// volatile the reader can see a stale value indefinitely. (_sessionKills uses Interlocked for the same reason.)
|
||||
|
|
@ -950,6 +951,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
|
||||
TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec,
|
||||
GiveQueueIntervalMs = s.GiveQueueIntervalMs,
|
||||
T11ItemAugsOverride = s.T11ItemAugsOverride,
|
||||
// Recharge
|
||||
HealAt = s.HealAt,
|
||||
UsePotions = s.UsePotions,
|
||||
|
|
@ -966,6 +968,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
StopLootingWhenPackFull = s.StopLootingWhenPackFull,
|
||||
StopMacroWhenPackFull = s.StopMacroWhenPackFull,
|
||||
RestamAt = s.RestamAt,
|
||||
RestamTo = s.RestamTo,
|
||||
GetManaAt = s.GetManaAt,
|
||||
TopOffHP = s.TopOffHP,
|
||||
TopOffStam = s.TopOffStam,
|
||||
|
|
@ -989,6 +992,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
MinRingTargets = s.MinRingTargets,
|
||||
BlastRange = s.BlastRange,
|
||||
MinBlastTargets = s.MinBlastTargets,
|
||||
WallRange = s.WallRange,
|
||||
MinWallTargets = s.MinWallTargets,
|
||||
MinSkillLevelTier1 = s.MinSkillLevelTier1,
|
||||
MinSkillLevelTier2 = s.MinSkillLevelTier2,
|
||||
MinSkillLevelTier3 = s.MinSkillLevelTier3,
|
||||
|
|
@ -1012,6 +1017,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
NavHeightOffset = s.NavHeightOffset,
|
||||
NavSlopeSink = s.NavSlopeSink,
|
||||
ShowTerrainPassability = s.ShowTerrainPassability,
|
||||
NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode),
|
||||
NavGuideLine = s.NavGuideLine,
|
||||
OpenDoors = s.OpenDoors,
|
||||
OpenDoorRange = s.OpenDoorRange,
|
||||
AutoUnlockDoors = s.AutoUnlockDoors,
|
||||
|
|
@ -1037,6 +1044,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
|
||||
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
|
||||
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
|
||||
DisabledBuffs = new List<string>(s.DisabledBuffs),
|
||||
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
|
||||
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
|
||||
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
|
||||
|
|
@ -1058,7 +1066,9 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
LootJumpHeight = s.LootJumpHeight,
|
||||
LootOwnership = s.LootOwnership,
|
||||
LootOwnCorpse = s.LootOwnCorpse,
|
||||
EscapeHazards = s.EscapeHazards,
|
||||
TravelToOwnCorpse = s.TravelToOwnCorpse,
|
||||
ItemInfoOnSelect = s.ItemInfoOnSelect,
|
||||
EnableAutostack = s.EnableAutostack,
|
||||
ReadUnknownScrolls = s.ReadUnknownScrolls,
|
||||
EnableCombineSalvage = s.EnableCombineSalvage,
|
||||
|
|
@ -1091,7 +1101,6 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
OffhandDefault = s.OffhandDefault,
|
||||
PreferDualWield = s.PreferDualWield,
|
||||
EnableGroundLoot = s.EnableGroundLoot,
|
||||
ItemInfoOnSelect = s.ItemInfoSettings.OnSelect,
|
||||
// Diagnostics (per PC, RynthLog)
|
||||
DiagDebugToChat = RynthLog.DebugToChat,
|
||||
DiagFileLogAll = RynthLog.FileLogAll,
|
||||
|
|
@ -1163,6 +1172,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
|
||||
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
|
||||
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
|
||||
s.T11ItemAugsOverride = p.T11ItemAugsOverride ?? -1;
|
||||
// Recharge
|
||||
s.HealAt = p.HealAt;
|
||||
s.UsePotions = p.UsePotions;
|
||||
|
|
@ -1179,6 +1189,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
s.StopLootingWhenPackFull = p.StopLootingWhenPackFull;
|
||||
s.StopMacroWhenPackFull = p.StopMacroWhenPackFull;
|
||||
s.RestamAt = p.RestamAt;
|
||||
s.RestamTo = p.RestamTo ?? 0;
|
||||
s.GetManaAt = p.GetManaAt;
|
||||
s.TopOffHP = p.TopOffHP;
|
||||
s.TopOffStam = p.TopOffStam;
|
||||
|
|
@ -1197,11 +1208,13 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
s.PetMinMonsters = p.PetMinMonsters;
|
||||
// Spell Combat
|
||||
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
|
||||
s.AttackSpellIntervalMs = p.AttackSpellIntervalMs;
|
||||
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
|
||||
s.CastDispelSelf = p.CastDispelSelf;
|
||||
s.MinRingTargets = p.MinRingTargets;
|
||||
s.BlastRange = p.BlastRange;
|
||||
s.MinBlastTargets = p.MinBlastTargets;
|
||||
if (p.WallRange is int wallRange) s.WallRange = wallRange; // null = an engine without walls
|
||||
if (p.MinWallTargets is int minWall) s.MinWallTargets = minWall;
|
||||
s.MinSkillLevelTier1 = p.MinSkillLevelTier1;
|
||||
s.MinSkillLevelTier2 = p.MinSkillLevelTier2;
|
||||
s.MinSkillLevelTier3 = p.MinSkillLevelTier3;
|
||||
|
|
@ -1225,6 +1238,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
s.NavHeightOffset = p.NavHeightOffset;
|
||||
s.NavSlopeSink = p.NavSlopeSink;
|
||||
s.ShowTerrainPassability = p.ShowTerrainPassability;
|
||||
if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode);
|
||||
if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine;
|
||||
s.OpenDoors = p.OpenDoors;
|
||||
s.OpenDoorRange = p.OpenDoorRange;
|
||||
s.AutoUnlockDoors = p.AutoUnlockDoors;
|
||||
|
|
@ -1250,6 +1265,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
|
||||
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
|
||||
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
|
||||
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
|
||||
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
|
||||
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
|
||||
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
|
||||
|
|
@ -1267,8 +1283,10 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
s.LootJumpEnabled = p.LootJumpEnabled;
|
||||
s.LootJumpHeight = p.LootJumpHeight;
|
||||
s.LootOwnership = p.LootOwnership;
|
||||
if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged
|
||||
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
|
||||
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
|
||||
if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged
|
||||
s.EnableAutostack = p.EnableAutostack;
|
||||
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
|
||||
s.EnableCombineSalvage = p.EnableCombineSalvage;
|
||||
|
|
@ -1302,7 +1320,6 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
if (p.OffhandDefault is string od && OffhandRules.TryParse(od, out var odMode)) s.OffhandDefault = OffhandRules.SettingValue(odMode);
|
||||
if (p.PreferDualWield is bool pdw) s.PreferDualWield = pdw;
|
||||
s.EnableGroundLoot = p.EnableGroundLoot;
|
||||
s.ItemInfoSettings.OnSelect = p.ItemInfoOnSelect;
|
||||
// Diagnostics: each setter rewrites diagnostics.json, so only touch what changed.
|
||||
if (p.DiagDebugToChat != RynthLog.DebugToChat) RynthLog.DebugToChat = p.DiagDebugToChat;
|
||||
if (p.DiagFileLogAll != RynthLog.FileLogAll) RynthLog.FileLogAll = p.DiagFileLogAll;
|
||||
|
|
@ -1640,6 +1657,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.StopLootingWhenPackFull = tmp.StopLootingWhenPackFull;
|
||||
dst.StopMacroWhenPackFull = tmp.StopMacroWhenPackFull;
|
||||
dst.RestamAt = tmp.RestamAt;
|
||||
dst.RestamTo = tmp.RestamTo;
|
||||
dst.GetManaAt = tmp.GetManaAt;
|
||||
dst.TopOffHP = tmp.TopOffHP;
|
||||
dst.TopOffStam = tmp.TopOffStam;
|
||||
|
|
@ -1654,6 +1672,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.MinRingTargets = tmp.MinRingTargets;
|
||||
dst.BlastRange = tmp.BlastRange;
|
||||
dst.MinBlastTargets = tmp.MinBlastTargets;
|
||||
dst.WallRange = tmp.WallRange;
|
||||
dst.MinWallTargets = tmp.MinWallTargets;
|
||||
dst.FollowNavMin = tmp.FollowNavMin;
|
||||
dst.NavRingThickness = tmp.NavRingThickness;
|
||||
dst.NavLineThickness = tmp.NavLineThickness;
|
||||
|
|
@ -1675,13 +1695,16 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
|
||||
dst.LootOwnership = tmp.LootOwnership;
|
||||
dst.LootOwnCorpse = tmp.LootOwnCorpse;
|
||||
dst.EscapeHazards = tmp.EscapeHazards;
|
||||
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
|
||||
dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect;
|
||||
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
|
||||
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
|
||||
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
|
||||
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
|
||||
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
|
||||
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
|
||||
dst.DisabledBuffs = tmp.DisabledBuffs;
|
||||
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
||||
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
|
||||
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
|
||||
|
|
@ -1780,7 +1803,10 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.FeatureServerNames = tmp.FeatureServerNames ?? new(IltHub.ServerFeatureGate.DefaultServerNames);
|
||||
dst.ForceServerFeatures = tmp.ForceServerFeatures;
|
||||
dst.ShowTerrainPassability = tmp.ShowTerrainPassability;
|
||||
dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode);
|
||||
dst.NavGuideLine = tmp.NavGuideLine;
|
||||
dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs;
|
||||
dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride;
|
||||
dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs;
|
||||
dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs;
|
||||
dst.EmbeddedNavs = tmp.EmbeddedNavs;
|
||||
|
|
@ -1912,15 +1938,13 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
{
|
||||
_sessionStartUtc = DateTime.UtcNow;
|
||||
System.Threading.Interlocked.Exchange(ref _sessionKills, 0);
|
||||
System.Threading.Interlocked.Exchange(ref _lastKillTicks, 0);
|
||||
}
|
||||
|
||||
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour
|
||||
/// and the "time since last kill" liveness signal.
|
||||
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour.
|
||||
/// The "time since last kill" signal is the plugin's KillClock.
|
||||
public void RecordKill()
|
||||
{
|
||||
System.Threading.Interlocked.Increment(ref _sessionKills);
|
||||
System.Threading.Interlocked.Exchange(ref _lastKillTicks, DateTime.UtcNow.Ticks);
|
||||
}
|
||||
|
||||
/// Pushed from the plugin tick (it owns the inventory cache) — main-pack empty slots. -1 = unknown.
|
||||
|
|
@ -2108,6 +2132,43 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
_selectedNavIdx = sel;
|
||||
}
|
||||
|
||||
private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp;
|
||||
private long _nextNavFolderCheckMs;
|
||||
|
||||
/// <summary>
|
||||
/// Lists a folder again when it changed since the last look (a file added, removed or renamed:
|
||||
/// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings
|
||||
/// profile saved), so its picker shows it without a relog or a reload. NavProfiles since
|
||||
/// 2026-10; LootProfiles, MetaFiles and the character's settings profiles since 2026-10-08
|
||||
/// (a loot profile copied in didn't show until a hot reload). One folder time check each every
|
||||
/// 3 s. Plugin tick.
|
||||
/// </summary>
|
||||
public void TickNavFolder()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextNavFolderCheckMs) return;
|
||||
_nextNavFolderCheckMs = now + 3000;
|
||||
if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles();
|
||||
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
|
||||
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
|
||||
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="folder"/>'s write time moved since the last call (never on
|
||||
/// the first look, which only records it: the lists were built at load).</summary>
|
||||
private static bool FolderChanged(string? folder, ref DateTime stamp)
|
||||
{
|
||||
try
|
||||
{
|
||||
DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue;
|
||||
if (now == stamp) return false;
|
||||
bool first = stamp == default;
|
||||
stamp = now;
|
||||
return !first;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>Save button and /ra nav save [name]. Returns the chat line.</summary>
|
||||
public string SaveRoute(string? name)
|
||||
{
|
||||
|
|
@ -2563,11 +2624,8 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
// (kill counter + inventory cache); the rest of the player stats are engine top-level.
|
||||
AppendFloat(sb, "killsPerHour", (float)_killsPerHour); sb.Append(',');
|
||||
AppendInt(sb, "sessionKills", (int)System.Threading.Interlocked.Read(ref _sessionKills)); sb.Append(',');
|
||||
long lastKillTicks = System.Threading.Interlocked.Read(ref _lastKillTicks);
|
||||
int secsSinceLastKill = lastKillTicks == 0
|
||||
? -1
|
||||
: (int)Math.Clamp((DateTime.UtcNow - new DateTime(lastKillTicks, DateTimeKind.Utc)).TotalSeconds, 0, int.MaxValue);
|
||||
AppendInt(sb, "secsSinceLastKill", secsSinceLastKill); sb.Append(',');
|
||||
// -1 before the first kill this session (the plugin's KillClock, reset at login).
|
||||
AppendInt(sb, "secsSinceLastKill", KillClock?.SecondsSinceKillOnly() ?? -1); sb.Append(',');
|
||||
AppendInt(sb, "freeSlots", _freeSlots); sb.Append(',');
|
||||
// D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning).
|
||||
AppendInt(sb, "scanTotal", _scanTotal); sb.Append(',');
|
||||
|
|
@ -2776,7 +2834,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
|
||||
// ── Meta bridge ───────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
|
||||
// Result of the last set_source, reported in BuildMetaJson (under MetaRulesLock).
|
||||
private long _metaApplySeq;
|
||||
|
|
@ -3037,11 +3095,10 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
break;
|
||||
|
||||
case "update_rule":
|
||||
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
|
||||
{
|
||||
_settings.MetaRules[cmd.Index] = DtoToMetaRule(cmd.Rule);
|
||||
// The engine's editor saves every change (2026-10-05): keep the running rule's
|
||||
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
|
||||
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule)))
|
||||
TryAutoSaveMetaCmd();
|
||||
}
|
||||
break;
|
||||
|
||||
case "delete_rule":
|
||||
|
|
@ -3072,7 +3129,9 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
case "duplicate_rule":
|
||||
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
|
||||
{
|
||||
_settings.MetaRules.Insert(cmd.Index + 1, DtoToMetaRule(cmd.Rule));
|
||||
var copy = DtoToMetaRule(cmd.Rule);
|
||||
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
|
||||
_settings.MetaRules.Insert(cmd.Index + 1, copy);
|
||||
TryAutoSaveMetaCmd();
|
||||
}
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -1,295 +0,0 @@
|
|||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
/// <summary>
|
||||
/// "RynthAi Item Info" window: every option of the Mag-style item info line (/ra iteminfo) with
|
||||
/// a live preview of the selected item. Edits go straight into
|
||||
/// <see cref="LegacyUiSettings.ItemInfoSettings"/> and are saved by the dashboard autosave.
|
||||
/// Opened from Advanced Settings → Display or with /ra iteminfo settings.
|
||||
/// </summary>
|
||||
internal sealed class LegacyItemInfoUi
|
||||
{
|
||||
private readonly LegacyUiSettings _settings;
|
||||
|
||||
// Supplied by RynthAiPlugin (it owns the host + object cache).
|
||||
private Func<string?>? _describeSelected; // selected item's line (no prefix) or null when nothing is selected
|
||||
private Action? _printSelected; // same path as /ra iteminfo (requests an ID when needed)
|
||||
private Action<int>? _testChatType; // prints a sample line with the given chat type
|
||||
|
||||
// Preview is rebuilt on a timer or when an output option changes, not every frame.
|
||||
private const long PreviewRefreshMs = 500;
|
||||
private string? _previewText;
|
||||
private long _previewAt;
|
||||
private MagItemInfoOptions _previewOptions;
|
||||
|
||||
private static readonly Vector4 ExampleColor = new(0.60f, 0.66f, 0.74f, 1f);
|
||||
|
||||
public LegacyItemInfoUi(LegacyUiSettings settings) => _settings = settings;
|
||||
|
||||
public void SetHooks(Func<string?> describeSelected, Action printSelected, Action<int> testChatType)
|
||||
{
|
||||
_describeSelected = describeSelected;
|
||||
_printSelected = printSelected;
|
||||
_testChatType = testChatType;
|
||||
}
|
||||
|
||||
public void Render()
|
||||
{
|
||||
// Re-read every frame: loading a character profile replaces the settings object.
|
||||
MagItemInfoSettings s = _settings.ItemInfoSettings;
|
||||
if (!s.ShowWindow) return;
|
||||
|
||||
ImGui.SetNextWindowSize(new Vector2(560, 600), ImGuiCond.FirstUseEver);
|
||||
if (ImGui.Begin("RynthAi Item Info##ItemInfoSettings", ref s.ShowWindow))
|
||||
{
|
||||
RenderPreview(s);
|
||||
RenderWhen(s);
|
||||
RenderFields(s);
|
||||
RenderSpellsAndRatings(s);
|
||||
RenderChat(s);
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
if (ImGui.Button("Reset all to defaults##ii"))
|
||||
{
|
||||
s.ResetToDefaults();
|
||||
_previewAt = 0;
|
||||
}
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Close##ii")) s.ShowWindow = false;
|
||||
}
|
||||
ImGui.End();
|
||||
}
|
||||
|
||||
// ── Preview ──────────────────────────────────────────────────────────────
|
||||
|
||||
private void RenderPreview(MagItemInfoSettings s)
|
||||
{
|
||||
if (!ImGui.CollapsingHeader("Preview (selected item)##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
|
||||
|
||||
var options = MagItemInfoOptions.From(s);
|
||||
long now = Environment.TickCount64;
|
||||
if (_describeSelected != null && (now - _previewAt >= PreviewRefreshMs || options != _previewOptions))
|
||||
{
|
||||
try { _previewText = _describeSelected(); }
|
||||
catch (Exception ex) { _previewText = "Preview failed: " + ex.Message; }
|
||||
_previewAt = now;
|
||||
_previewOptions = options;
|
||||
}
|
||||
|
||||
// Pet-style output is up to four lines plus wrapping.
|
||||
float previewHeight = s.Layout == MagItemInfoSettings.LayoutPetLines ? 110 : 70;
|
||||
ImGui.BeginChild("iiPreview", new Vector2(0, previewHeight), ImGuiChildFlags.Borders);
|
||||
if (string.IsNullOrEmpty(_previewText))
|
||||
ImGui.TextDisabled("Select an item to preview its info line.");
|
||||
else
|
||||
ImGui.TextWrapped(s.Prefix + _previewText);
|
||||
ImGui.EndChild();
|
||||
|
||||
if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke();
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Same as /ra iteminfo: IDs the selected item first when needed.");
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Refresh##iiRefresh")) _previewAt = 0;
|
||||
}
|
||||
|
||||
// ── When to print ────────────────────────────────────────────────────────
|
||||
|
||||
private static void RenderWhen(MagItemInfoSettings s)
|
||||
{
|
||||
if (!ImGui.CollapsingHeader("When to print##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
|
||||
|
||||
ImGui.Checkbox("Describe items when selected##iiOnSel", ref s.OnSelect);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Print the info every time the selection changes to an item.\n/ra iteminfo always works, whatever is set here.");
|
||||
|
||||
RenderClickTrigger(s, "##iiClick");
|
||||
|
||||
ImGui.Text("Item types:");
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Which items the select / click triggers describe.\n/ra iteminfo and Print to chat ignore these.");
|
||||
ImGui.Indent();
|
||||
ImGui.BeginDisabled(!s.OnSelect && s.ClickTrigger == MagItemInfoSettings.ClickOff);
|
||||
ImGui.Checkbox("Weapons##iiSelW", ref s.OnSelectWeapons); ImGui.SameLine();
|
||||
ImGui.Checkbox("Armor & clothing##iiSelA", ref s.OnSelectArmor); ImGui.SameLine();
|
||||
ImGui.Checkbox("Jewelry##iiSelJ", ref s.OnSelectJewelry); ImGui.SameLine();
|
||||
ImGui.Checkbox("Other items##iiSelO", ref s.OnSelectOther);
|
||||
ImGui.EndDisabled();
|
||||
ImGui.Unindent();
|
||||
|
||||
ImGui.SetNextItemWidth(200);
|
||||
if (ImGui.SliderFloat("ID wait (seconds)##iiTimeout", ref s.IdTimeoutSec, 0.5f, 15f, "%.1f s"))
|
||||
s.Sanitize();
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("How long to wait for an unidentified item's appraisal\nbefore printing what is already known.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "ID on click" combo (Off / Left / Right). Shared with Advanced Settings → Display, so
|
||||
/// <paramref name="idSuffix"/> keeps the ImGui ids unique per window.
|
||||
/// </summary>
|
||||
public static void RenderClickTrigger(MagItemInfoSettings s, string idSuffix)
|
||||
{
|
||||
ImGui.SetNextItemWidth(200);
|
||||
if (ImGui.Combo("ID + print on click" + idSuffix, ref s.ClickTrigger,
|
||||
MagItemInfoCatalog.ClickTriggers, MagItemInfoCatalog.ClickTriggers.Length))
|
||||
s.Sanitize();
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Clicking an item in the world or your packs IDs it and prints its info,\n" +
|
||||
"even when it was already selected. Clicks on RynthCore windows, drags and\n" +
|
||||
"held-button camera turns are ignored.\n" +
|
||||
"Right click prints whatever item is selected after the click: if your client\n" +
|
||||
"doesn't select on right click, left-click to select, then right-click to print.\n" +
|
||||
"Needs the ImGui overlay enabled.");
|
||||
}
|
||||
|
||||
/// <summary>Layout combo (pet-style lines / one line). Shared with Advanced Settings → Display.</summary>
|
||||
public static void RenderLayout(MagItemInfoSettings s, string idSuffix)
|
||||
{
|
||||
ImGui.SetNextItemWidth(200);
|
||||
if (ImGui.Combo("Layout" + idSuffix, ref s.Layout, MagItemInfoCatalog.Layouts, MagItemInfoCatalog.Layouts.Length))
|
||||
s.Sanitize();
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(
|
||||
"Pet-style lines (like the ILT Hub pet roster):\n" +
|
||||
" 1 Name (type mastery), set, AL, tinks, applied, craft\n" +
|
||||
" 2 imbues, slayer, damage, variance, %a / %md / %mc\n" +
|
||||
" 3 [ratings] wield / activation / diff, value\n" +
|
||||
" 4 Spells: …\n" +
|
||||
"One line: the classic Mag-Tools single line.");
|
||||
}
|
||||
|
||||
// ── Field toggles ────────────────────────────────────────────────────────
|
||||
|
||||
private void RenderFields(MagItemInfoSettings s)
|
||||
{
|
||||
if (!ImGui.CollapsingHeader("Fields##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
|
||||
|
||||
if (ImGui.SmallButton("All on##iiFields")) s.HiddenFields = 0;
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("All off##iiFields"))
|
||||
{
|
||||
foreach (var f in MagItemInfoCatalog.Fields) s.SetHidden(f.Field, true);
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.TextDisabled("(the item name is always printed)");
|
||||
|
||||
if (ImGui.BeginTable("iiFieldTable", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
|
||||
{
|
||||
ImGui.TableSetupColumn("Field", ImGuiTableColumnFlags.WidthStretch, 0.45f);
|
||||
ImGui.TableSetupColumn("Example", ImGuiTableColumnFlags.WidthStretch, 0.55f);
|
||||
foreach (var f in MagItemInfoCatalog.Fields)
|
||||
{
|
||||
ImGui.TableNextRow();
|
||||
ImGui.TableNextColumn();
|
||||
bool shown = !s.IsHidden(f.Field);
|
||||
if (ImGui.Checkbox($"{f.Label}##iiF{(int)f.Field}", ref shown))
|
||||
s.SetHidden(f.Field, !shown);
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.TextColored(ExampleColor, f.Example);
|
||||
}
|
||||
ImGui.TableNextRow();
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.Checkbox("Value & burden##iiValBu", ref s.ShowValueAndBurden);
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.TextColored(ExampleColor, "Value 12,500, BU 220");
|
||||
ImGui.EndTable();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Spells + per-rating toggles ──────────────────────────────────────────
|
||||
|
||||
private static void RenderSpellsAndRatings(MagItemInfoSettings s)
|
||||
{
|
||||
if (!ImGui.CollapsingHeader("Spells & ratings##ii")) return;
|
||||
|
||||
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Spells));
|
||||
ImGui.Text("Spell list:");
|
||||
ImGui.SameLine();
|
||||
ImGui.RadioButton("Mag filter##iiSpMag", ref s.SpellMode, MagItemInfoSettings.SpellModeMag);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Cantrips, level 7+ weapon auras, Augmented spells,\nand Impen/banes only on unenchantable gear.");
|
||||
ImGui.SameLine();
|
||||
ImGui.RadioButton("All spells##iiSpAll", ref s.SpellMode, MagItemInfoSettings.SpellModeAll);
|
||||
if (s.SpellMode == MagItemInfoSettings.SpellModeAll)
|
||||
{
|
||||
ImGui.SetNextItemWidth(200);
|
||||
if (ImGui.SliderInt("Max spells listed##iiSpMax", ref s.MaxListedSpells, 1, 64))
|
||||
s.Sanitize();
|
||||
}
|
||||
ImGui.EndDisabled();
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Ratings));
|
||||
ImGui.Text("Ratings shown:");
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("All##iiRat")) s.HiddenRatings = 0;
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("None##iiRat")) s.HiddenRatings = (1 << MagItemInfoCatalog.Ratings.Length) - 1;
|
||||
if (ImGui.BeginTable("iiRatingTable", 3))
|
||||
{
|
||||
var ratings = MagItemInfoCatalog.Ratings;
|
||||
for (int i = 0; i < ratings.Length; i++)
|
||||
{
|
||||
ImGui.TableNextColumn();
|
||||
bool shown = !s.IsRatingHidden(i);
|
||||
if (ImGui.Checkbox($"{ratings[i].Tag} - {ratings[i].Name}##iiR{i}", ref shown))
|
||||
s.SetRatingHidden(i, !shown);
|
||||
}
|
||||
ImGui.EndTable();
|
||||
}
|
||||
ImGui.EndDisabled();
|
||||
}
|
||||
|
||||
// ── Chat output ──────────────────────────────────────────────────────────
|
||||
|
||||
private void RenderChat(MagItemInfoSettings s)
|
||||
{
|
||||
if (!ImGui.CollapsingHeader("Chat output##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
|
||||
|
||||
RenderLayout(s, "##iiLayout");
|
||||
|
||||
ChatTypeCombo("Chat type / colour##iiChat", ref s.ChatType, allowSameAsHeader: false);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Test##iiChatTest")) _testChatType?.Invoke(s.ChatType);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Print a sample line with this chat type to see its colour.");
|
||||
|
||||
// Pet-style only: the roster draws its detail lines in a second colour.
|
||||
ImGui.BeginDisabled(s.Layout != MagItemInfoSettings.LayoutPetLines);
|
||||
ChatTypeCombo("Detail lines colour##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Test##iiChatDetailTest"))
|
||||
_testChatType?.Invoke(s.DetailChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.DetailChatType);
|
||||
ImGui.EndDisabled();
|
||||
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above).");
|
||||
|
||||
ImGui.SetNextItemWidth(220);
|
||||
ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Text put in front of every item info line (may be empty).");
|
||||
}
|
||||
|
||||
/// <summary>Chat type picker; <paramref name="allowSameAsHeader"/> adds the "same as name line" entry (-1).</summary>
|
||||
private static void ChatTypeCombo(string label, ref int chatType, bool allowSameAsHeader)
|
||||
{
|
||||
const string SameLabel = "Same as name line";
|
||||
string current = chatType == MagItemInfoSettings.SameAsHeader ? SameLabel : $"{chatType}";
|
||||
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
|
||||
if (type == chatType) { current = name; break; }
|
||||
|
||||
ImGui.SetNextItemWidth(220);
|
||||
if (!ImGui.BeginCombo(label, current)) return;
|
||||
if (allowSameAsHeader && ImGui.Selectable(SameLabel, chatType == MagItemInfoSettings.SameAsHeader))
|
||||
chatType = MagItemInfoSettings.SameAsHeader;
|
||||
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
|
||||
if (ImGui.Selectable(name, type == chatType)) chatType = type;
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
}
|
||||
|
|
@ -47,7 +47,7 @@ internal sealed class LegacyMetaUi
|
|||
private string _statusMessage = "";
|
||||
private DateTime _statusTime = DateTime.MinValue;
|
||||
|
||||
private static readonly string MetaFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
|
||||
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
|
||||
/// <summary>Warnings from the most recent LoadMacroFile, so the Avalonia
|
||||
/// bridge can surface them too (it doesn't see the LoadedMeta).</summary>
|
||||
|
|
@ -699,6 +699,9 @@ internal sealed class LegacyMetaUi
|
|||
case MetaConditionType.VitaePHE:
|
||||
condHint = "Vitae penalty % (e.g. 5)";
|
||||
break;
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
condHint = "Minutes without a kill (e.g. 5 or 2.5)";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -143,7 +143,7 @@ internal sealed class LegacyNavigationUi
|
|||
|
||||
for (int ri = 0; ri < ids.Length; ri++)
|
||||
{
|
||||
string name = $"Spell {ids[ri]}";
|
||||
string name = NavPoint.RecallName(ids[ri]);
|
||||
if (ImGui.Selectable($"{name} ({ids[ri]})"))
|
||||
{
|
||||
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ public sealed class LegacyUiSettings
|
|||
public float NavResumeTurnAngle = 10f;
|
||||
public float NavDeadZone = 4f;
|
||||
public float NavSweepMult = 2.5f;
|
||||
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
|
||||
public float NavLookaheadYards = 4.0f; // most the aim point is blended toward the next waypoint (0 = off); the nav point reach scales it down (NavigationEngine.CornerLookaheadYards)
|
||||
public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point)
|
||||
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
|
||||
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
|
||||
|
|
@ -82,10 +82,6 @@ public sealed class LegacyUiSettings
|
|||
|
||||
public bool ShowTargetStaminaMana;
|
||||
|
||||
/// <summary>Mag-style item info (/ra iteminfo): on-select, per-field visibility, chat type, prefix.
|
||||
/// Edited in the "RynthAi Item Info" window.</summary>
|
||||
public RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoSettings ItemInfoSettings = new();
|
||||
|
||||
public bool EnableMissileCrafting = true;
|
||||
public int MissileCraftAmmoThreshold = 1000;
|
||||
|
||||
|
|
@ -137,6 +133,11 @@ public sealed class LegacyUiSettings
|
|||
public bool StopLootingWhenPackFull = true;
|
||||
public bool StopMacroWhenPackFull = false;
|
||||
public int RestamAt = 30;
|
||||
/// <summary>
|
||||
/// In combat, once stamina drops under Re-stam At, keep recharging until it reaches this %
|
||||
/// (one Revitalize often doesn't get far). 0, or not above Re-stam At = one recharge, as before.
|
||||
/// </summary>
|
||||
public int RestamTo = 0;
|
||||
public int GetManaAt = 40;
|
||||
public int TopOffHP = 95;
|
||||
public int TopOffStam = 95;
|
||||
|
|
@ -160,6 +161,12 @@ public sealed class LegacyUiSettings
|
|||
// degrees) toward the target; otherwise its other shape. 0 = off: Blast is just a shape.
|
||||
public int BlastRange = 0;
|
||||
public int MinBlastTargets = 3;
|
||||
// Wall spells (2026-10-08): with WallRange > 0, a rule with Wall on casts its element's wall
|
||||
// (Slithering Flames, Os' Wall...) when MinWallTargets monsters are within WallRange in the
|
||||
// wall's path toward the target, turning to face the target first (a wall flies along the
|
||||
// caster's facing). Below a due ring, above a due blast. 0 = off: no walls at all.
|
||||
public int WallRange = 0;
|
||||
public int MinWallTargets = 3;
|
||||
// Nav point reach (VTank "Follow/Nav Min Distance"), yards: how close nav gets to each
|
||||
// nav point before moving on to the next, and how close Follow gets to its leader.
|
||||
// Metas set it as FollowNavMin (yards) or VTank's NavCloseStopRange (landblock units,
|
||||
|
|
@ -175,6 +182,11 @@ public sealed class LegacyUiSettings
|
|||
public float NavHeightOffset = 0.05f;
|
||||
public float NavSlopeSink = 1.5f;
|
||||
public bool ShowTerrainPassability = true;
|
||||
// Nav3D extras, both off by default: labels over the route's waypoints (NavLabelModes:
|
||||
// 0 off, 1 numbers, 2 numbers and what happens there) and a line from the character to
|
||||
// the waypoint nav is heading for.
|
||||
public int NavLabelMode;
|
||||
public bool NavGuideLine;
|
||||
public double MaxMonRange = 12.0;
|
||||
public bool SummonPets;
|
||||
public int CustomPetRange = 5;
|
||||
|
|
@ -200,10 +212,22 @@ public sealed class LegacyUiSettings
|
|||
/// </summary>
|
||||
public bool LootOwnCorpse = true;
|
||||
/// <summary>
|
||||
/// Out of acid or lava at once (RynthAiPlugin.HazardEscape.cs): the first hotspot hit stops
|
||||
/// everything and walks back out, and the spot becomes a hazard the patrol avoids. On by
|
||||
/// default (2026-10-07); off for characters that walk through acid on purpose (then the spot
|
||||
/// isn't learned either). A profile saved before this setting loads it as on.
|
||||
/// </summary>
|
||||
public bool EscapeHazards = true;
|
||||
/// <summary>
|
||||
/// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight
|
||||
/// on the way as usual, recover the corpse, then carry on. Off by default.
|
||||
/// </summary>
|
||||
public bool TravelToOwnCorpse;
|
||||
/// <summary>
|
||||
/// Selecting an item prints its details to chat (/ra iteminfo, Mag-Tools style),
|
||||
/// identifying it first when needed. Items RynthAi selects itself are skipped. On by default.
|
||||
/// </summary>
|
||||
public bool ItemInfoOnSelect = true;
|
||||
public bool LootOnlyRareCorpses;
|
||||
/// <summary>Also pick up loose ground items that match the loot profile, within the corpse max range.</summary>
|
||||
public bool EnableGroundLoot;
|
||||
|
|
@ -232,6 +256,35 @@ public sealed class LegacyUiSettings
|
|||
/// as on for good (the behaviour before 2026-10-05).
|
||||
/// </summary>
|
||||
public bool CastBuffsOverItemBuffs = true;
|
||||
/// <summary>
|
||||
/// Buff base names the player unticked in Buffing settings (the Protections and Banes grid,
|
||||
/// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and
|
||||
/// never waited on. Empty = every buff on, which is also what a profile saved before this
|
||||
/// setting existed loads as. Replaced, not edited in place (SetBuffEnabled), so a reader
|
||||
/// holding the old list never sees it change under it.
|
||||
/// </summary>
|
||||
public List<string> DisabledBuffs
|
||||
{
|
||||
get => _disabledBuffs;
|
||||
set => _disabledBuffs = value ?? new List<string>();
|
||||
}
|
||||
private List<string> _disabledBuffs = new();
|
||||
|
||||
public bool IsBuffDisabled(string buffBaseName)
|
||||
{
|
||||
foreach (string b in _disabledBuffs)
|
||||
if (string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SetBuffEnabled(string buffBaseName, bool enabled)
|
||||
{
|
||||
if (enabled == !IsBuffDisabled(buffBaseName)) return;
|
||||
var next = new List<string>(_disabledBuffs);
|
||||
if (enabled) next.RemoveAll(b => string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase));
|
||||
else next.Add(buffBaseName);
|
||||
_disabledBuffs = next;
|
||||
}
|
||||
public bool StartMacroOnLogin;
|
||||
public bool PatrolOnLogin;
|
||||
/// <summary>
|
||||
|
|
@ -276,6 +329,13 @@ public sealed class LegacyUiSettings
|
|||
|
||||
public int GiveQueueIntervalMs = 150;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int T11ItemAugsOverride = -1;
|
||||
|
||||
public int SpellCastIntervalMs = 400;
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -630,6 +690,10 @@ public sealed class MonsterRule
|
|||
/// <summary>Blast spells (Flame Blast, Frost Blast...: a spread of projectiles). Off in files
|
||||
/// from before 2026-10-03. Wins over Bolt when both are on; see CombatManager.PickBaseShape.</summary>
|
||||
public bool UseBlast { get; set; }
|
||||
/// <summary>Wall spells (Slithering Flames, Os' Wall...: a row of projectiles flying straight
|
||||
/// ahead). An override like the ring, cast only with Wall Range on and enough monsters in the
|
||||
/// wall's path; a wall-only rule casts Bolt between walls. Off in files from before 2026-10-08.</summary>
|
||||
public bool UseWall { get; set; }
|
||||
public string ExVuln { get; set; } = "None";
|
||||
/// <summary>The off hand for this rule: 0 = the global setting (OffhandDefault), 1 Auto,
|
||||
/// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed
|
||||
|
|
@ -823,6 +887,7 @@ public sealed class SettingsBridgePayload
|
|||
public int BlacklistCastSettleMs { get; set; } = -1;
|
||||
public int TargetNoProgressTimeoutSec { get; set; }
|
||||
public int GiveQueueIntervalMs { get; set; }
|
||||
public int? T11ItemAugsOverride { get; set; }
|
||||
|
||||
// Recharge
|
||||
public int HealAt { get; set; }
|
||||
|
|
@ -840,6 +905,7 @@ public sealed class SettingsBridgePayload
|
|||
public bool StopLootingWhenPackFull { get; set; }
|
||||
public bool StopMacroWhenPackFull { get; set; }
|
||||
public int RestamAt { get; set; }
|
||||
public int? RestamTo { get; set; }
|
||||
public int GetManaAt { get; set; }
|
||||
public int TopOffHP { get; set; }
|
||||
public int TopOffStam { get; set; }
|
||||
|
|
@ -860,11 +926,16 @@ public sealed class SettingsBridgePayload
|
|||
|
||||
// Spell Combat
|
||||
public int SpellCastIntervalMs { get; set; }
|
||||
public int AttackSpellIntervalMs { get; set; }
|
||||
// Nullable since 0 became a real value (2026-10-08): a file without it keeps the default.
|
||||
public int? AttackSpellIntervalMs { get; set; }
|
||||
public bool CastDispelSelf { get; set; }
|
||||
public int MinRingTargets { get; set; }
|
||||
public int BlastRange { get; set; }
|
||||
public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default
|
||||
// Walls (2026-10-08): null = sent by an engine without the Wall Range control, which then
|
||||
// leaves the plugin's own values alone (a profile's or a meta's) instead of zeroing them.
|
||||
public int? WallRange { get; set; }
|
||||
public int? MinWallTargets { get; set; }
|
||||
public int MinSkillLevelTier1 { get; set; }
|
||||
public int MinSkillLevelTier2 { get; set; }
|
||||
public int MinSkillLevelTier3 { get; set; }
|
||||
|
|
@ -890,6 +961,9 @@ public sealed class SettingsBridgePayload
|
|||
public float NavHeightOffset { get; set; }
|
||||
public float NavSlopeSink { get; set; }
|
||||
public bool ShowTerrainPassability { get; set; }
|
||||
// Absent from an older engine: -1 / null keep the plugin's value.
|
||||
public int NavLabelMode { get; set; } = -1;
|
||||
public bool? NavGuideLine { get; set; }
|
||||
public bool OpenDoors { get; set; }
|
||||
public float OpenDoorRange { get; set; }
|
||||
public bool AutoUnlockDoors { get; set; }
|
||||
|
|
@ -918,6 +992,8 @@ public sealed class SettingsBridgePayload
|
|||
// Nullable: an engine that predates the setting doesn't send it, and a save from its
|
||||
// Settings face must leave the setting alone rather than force it either way.
|
||||
public bool? CastBuffsOverItemBuffs { get; set; }
|
||||
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
|
||||
public List<string>? DisabledBuffs { get; set; }
|
||||
public int BuffMinSkillLevelTier1 { get; set; }
|
||||
public int BuffMinSkillLevelTier2 { get; set; }
|
||||
public int BuffMinSkillLevelTier3 { get; set; }
|
||||
|
|
@ -943,7 +1019,9 @@ public sealed class SettingsBridgePayload
|
|||
// Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them,
|
||||
// and its save must leave them alone.
|
||||
public bool? LootOwnCorpse { get; set; }
|
||||
public bool? EscapeHazards { get; set; }
|
||||
public bool? TravelToOwnCorpse { get; set; }
|
||||
public bool? ItemInfoOnSelect { get; set; }
|
||||
public bool EnableAutostack { get; set; }
|
||||
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
|
||||
public bool EnableCombineSalvage { get; set; }
|
||||
|
|
@ -980,8 +1058,6 @@ public sealed class SettingsBridgePayload
|
|||
|
||||
// Ground loot (GroundLootController; also /ra groundloot on|off).
|
||||
public bool EnableGroundLoot { get; set; }
|
||||
// Item info: describe an item in chat when it is selected (/ra iteminfo onselect).
|
||||
public bool ItemInfoOnSelect { get; set; }
|
||||
|
||||
// Diagnostics. Stored per PC in Logs\Diagnostics\diagnostics.json (RynthLog), not in
|
||||
// the character profile; applied only when a value differs, so a save of other
|
||||
|
|
@ -1030,7 +1106,11 @@ public enum MetaConditionType
|
|||
MainManaLE,
|
||||
MainManaPHE,
|
||||
MainStamLE,
|
||||
VitaePHE
|
||||
VitaePHE,
|
||||
/// <summary>RynthAi only (2026-10-06): no kill for at least N minutes (ConditionData = minutes,
|
||||
/// decimals allowed). Appended last: the value is the wire / JSON number, and an older RynthAi
|
||||
/// that reads it treats the unknown number (and the .af keyword NoKillsInMins) as never true.</summary>
|
||||
NoKillsWithinMinutes
|
||||
}
|
||||
|
||||
public enum MetaActionType
|
||||
|
|
|
|||
|
|
@ -74,12 +74,24 @@ public sealed class NavPoint
|
|||
/// </summary>
|
||||
public bool Doorway { get; set; }
|
||||
|
||||
/// <summary>"Lifestone Recall": a recall step by its spell's name (it showed "Spell 1635",
|
||||
/// 2026-10-08); the id when the spell table doesn't know it.</summary>
|
||||
internal static string RecallName(int spellId)
|
||||
{
|
||||
string? name = SpellNameLookup?.Invoke(spellId);
|
||||
return string.IsNullOrEmpty(name) ? $"Spell {spellId}" : name;
|
||||
}
|
||||
|
||||
/// <summary>The spell table's name for an id; RynthAi sets it (this file is also compiled into
|
||||
/// tools without the spell table, which keep "Spell N").</summary>
|
||||
internal static Func<int, string?>? SpellNameLookup { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Type switch
|
||||
{
|
||||
NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}",
|
||||
NavPointType.Recall => $"[Recall] Spell {SpellId}",
|
||||
NavPointType.Recall => $"[Recall] {RecallName(SpellId)}",
|
||||
NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0:F1}s",
|
||||
NavPointType.Chat => $"[Chat] {ChatCommand}",
|
||||
NavPointType.OpenVendor => $"[Vendor] {TargetName}",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ namespace RynthCore.Plugin.RynthAi.Loot;
|
|||
/// </summary>
|
||||
internal sealed class LootEditorBridge
|
||||
{
|
||||
public const string LootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
public static readonly string LootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
|
||||
private readonly object _sync = new();
|
||||
private readonly LootEditSession _session = new();
|
||||
|
|
@ -182,8 +182,10 @@ internal sealed class LootEditorBridge
|
|||
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
|
||||
d.ItemId = id;
|
||||
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
|
||||
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like);
|
||||
d.IncludeT11 = req.IncludeT11;
|
||||
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
|
||||
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
|
||||
d.IsT11 = facts.T11?.IsT11 == true;
|
||||
d.ItemName = facts.Name;
|
||||
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
|
||||
d.Stackable = facts.Stackable;
|
||||
|
|
@ -207,6 +209,7 @@ internal sealed class LootEditorBridge
|
|||
Action = req.Action == 0 ? null : (VTankLootAction)req.Action,
|
||||
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
|
||||
RuleName = req.RuleName,
|
||||
IncludeT11 = req.IncludeT11,
|
||||
};
|
||||
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
|
||||
if (draft == null) return Refuse(d, error);
|
||||
|
|
@ -336,8 +339,11 @@ internal sealed class LootItemHooks
|
|||
{
|
||||
/// <summary>The item selected in the game, or 0.</summary>
|
||||
public Func<uint> SelectedItemId { get; set; } = () => 0;
|
||||
/// <summary>The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified).</summary>
|
||||
public Func<uint, bool, LootItemFacts?> Facts { get; set; } = (_, _) => null;
|
||||
/// <summary>
|
||||
/// The item's facts from the object cache, or null. The bools: "items like this" and
|
||||
/// "include T11 attributes"; either asks for an ID when the item isn't identified.
|
||||
/// </summary>
|
||||
public Func<uint, bool, bool, LootItemFacts?> Facts { get; set; } = (_, _, _) => null;
|
||||
/// <summary>The first rule of the .utl profile that matches the item now, or -1.</summary>
|
||||
public Func<uint, VTankLootProfile, int> FirstMatchUtl { get; set; } = (_, _) => -1;
|
||||
/// <summary>The first rule of the native profile that matches the item now, or -1.</summary>
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ public static class LootEvaluator
|
|||
|
||||
private static double EvalMinDamage(WorldObject item)
|
||||
{
|
||||
int maxDamage = item.Values(54, 0); // STypeInt MAX_DAMAGE
|
||||
int maxDamage = item.Values(44, 0); // Damage, the weapon profile's max (was 54, WeaponEncumbrance, until 2026-10-07)
|
||||
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
|
||||
return maxDamage - variance * maxDamage;
|
||||
}
|
||||
|
|
|
|||
116
Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs
Normal file
116
Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Loot.T11;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
/// <summary>
|
||||
/// T11 (tier 11+ ACECustom) loot support for <see cref="WorldObject.Values(int, int)"/>:
|
||||
/// answers the virtual T11 keys (<see cref="T11Keys"/>) 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.
|
||||
/// </summary>
|
||||
internal static class T11ItemSupport
|
||||
{
|
||||
/// <summary>The logged-in character's T11 wield counters.</summary>
|
||||
public static T11PlayerAugs Player { get; } = new();
|
||||
|
||||
private static readonly T11AugReportParser AugParser = new();
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Dictionary<int, Entry> 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;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="name"/> carries the server's T11 drop prefix.</summary>
|
||||
public static bool HasT11Name(string? name)
|
||||
=> !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>The parsed T11 view of <paramref name="item"/> (<see cref="T11ItemInfo.None"/> for other items).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A virtual T11 key's value, or <paramref name="defaultValue"/> for an unused id.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The value a T11 appraisal stripped for a retail key (158/159/160, 370-379), else
|
||||
/// <paramref name="fallback"/>. Only T11-named items are parsed, so other items pay a
|
||||
/// string compare.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Feeds a chat line to the "/aug" reader. Returns true when a counter changed.</summary>
|
||||
public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player);
|
||||
|
||||
/// <summary>Applies the saved item-aug override (-1 = automatic). Cheap; called every tick.</summary>
|
||||
public static void SyncOverride(int itemAugsOverride)
|
||||
=> Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null;
|
||||
|
||||
/// <summary>Drops the cached parse of a deleted object.</summary>
|
||||
public static void Forget(int objectId)
|
||||
{
|
||||
lock (Gate) Parsed.Remove(objectId);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the character's counters and every cached item (logout).</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
Player.Clear();
|
||||
lock (Gate) Parsed.Clear();
|
||||
}
|
||||
}
|
||||
213
Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
Normal file
213
Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
// ============================================================================
|
||||
// RynthAi - Loot/UseRefusalWatch.cs
|
||||
// Notices when the server answers every corpse open but nothing opens.
|
||||
//
|
||||
// Why (2026-10-06, Drakkon on DreamWeave): from 06:18:44 every use of a corpse
|
||||
// or door got the server's "use done" (UseDone, no error) about one round trip
|
||||
// after it was sent, and nothing opened. Fighting, healing kits and spells kept
|
||||
// working. Macro off, walking, jumping and /rc unlockactions changed nothing; a
|
||||
// relog fixed it at once, for the very same corpses. The bot hammered corpses
|
||||
// for 13 minutes: 33 abandons, 11 "LOOT WEDGE" resets, a chat line each.
|
||||
//
|
||||
// What this does: each corpse open is remembered with the server's UseDone
|
||||
// count at the time. A UseDone that arrives after it with no error, with no
|
||||
// corpse opening within AnswerGraceMs, is a refusal. A successful open of any
|
||||
// corpse clears everything.
|
||||
// - RefusalsBeforeRetry refusals in a row: stop all movement once, pause a
|
||||
// moment, try once more (CleanStopAndRetry).
|
||||
// - The retry refused too, with refusals on two different corpses since the
|
||||
// last open: the server refuses every use. Say so once and back off
|
||||
// (Stuck), then try one corpse every BackoffMs (doubling, capped). Each
|
||||
// probe that is refused again is StillStuck (log only); one that opens is
|
||||
// Recovered.
|
||||
// - The retry refused but only one corpse has ever refused: that corpse can't
|
||||
// be opened (its loot rights, say). Give up on it (DropCorpse); the next
|
||||
// corpse's first refusal decides.
|
||||
//
|
||||
// A UseDone with an error (0x1D "too busy", ...) says nothing either way, and
|
||||
// an open the server never answers is left to the corpse timeout as before.
|
||||
// No game calls here: the controller acts on the verdicts.
|
||||
//
|
||||
// The jump (2026-10-06 afternoon): the stuck state is the server's animation
|
||||
// bookkeeping for the character (ACE: MotionInterp.PendingMotions/IsAnimating
|
||||
// and the MotionTableManager queue never drain, so the server's turn to the
|
||||
// corpse never starts and the use's callback never runs). Besides leaving the
|
||||
// world, the only thing on ACE that empties those queues is the player's jump
|
||||
// (Player.HandleActionJump: RemoveLinkAnimations drains the motion table queue,
|
||||
// PendingMotions.Clear, IsAnimating = false; the jump also cancels the pending
|
||||
// walk/turn). So the controller jumps at the clean stop, and once more before
|
||||
// each probe after a back-off (TakeProbeJump).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
internal sealed class UseRefusalWatch
|
||||
{
|
||||
/// <summary>After the server's answer, a corpse that opens does so within a few frames.</summary>
|
||||
public const long AnswerGraceMs = 1500;
|
||||
/// <summary>An open the server hasn't answered after this long is forgotten (the corpse timeout handles it).</summary>
|
||||
public const long UnansweredForgetMs = 15_000;
|
||||
public const int RefusalsBeforeRetry = 3;
|
||||
/// <summary>The pause after the clean stop, before the one retry.</summary>
|
||||
public const long CleanStopPauseMs = 1500;
|
||||
public const long FirstBackoffMs = 5 * 60_000;
|
||||
public const long MaxBackoffMs = 20 * 60_000;
|
||||
|
||||
public enum Phase { Normal, Retrying, Stuck }
|
||||
|
||||
public enum Verdict
|
||||
{
|
||||
None,
|
||||
/// <summary>Several refusals in a row: stop all movement, pause CleanStopPauseMs, try once more.</summary>
|
||||
CleanStopAndRetry,
|
||||
/// <summary>The retry was refused but only this corpse ever refused: give up on it.</summary>
|
||||
DropCorpse,
|
||||
/// <summary>The server refuses every use: tell the player once, back off until BackoffUntil.</summary>
|
||||
Stuck,
|
||||
/// <summary>A probe after the back-off was refused too: back off again (longer), quietly.</summary>
|
||||
StillStuck,
|
||||
/// <summary>A corpse opened after Stuck: uses work again.</summary>
|
||||
Recovered,
|
||||
}
|
||||
|
||||
public Phase State { get; private set; } = Phase.Normal;
|
||||
public int Refusals { get; private set; }
|
||||
public long BackoffUntil { get; private set; }
|
||||
public long BackoffMs { get; private set; }
|
||||
/// <summary>The corpses refused since the last successful open.</summary>
|
||||
public IReadOnlyCollection<int> RefusedCorpses => _refused;
|
||||
/// <summary>The corpse of the last refusal (what a verdict is about).</summary>
|
||||
public int LastRefusedCorpse { get; private set; }
|
||||
|
||||
private readonly HashSet<int> _refused = new();
|
||||
private bool _probeJumpTaken;
|
||||
private bool _pending;
|
||||
private int _pendingId;
|
||||
private long _sentAt;
|
||||
private int _seqAtSend;
|
||||
private long _answeredAt;
|
||||
|
||||
/// <summary>While Stuck: no opens until the back-off ends (then one probe).</summary>
|
||||
public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil;
|
||||
|
||||
/// <summary>The back-off is over and the probe is next: true once per back-off, meaning
|
||||
/// "jump first, then send the probe after the pause".</summary>
|
||||
public bool TakeProbeJump(long now)
|
||||
{
|
||||
if (State != Phase.Stuck || now < BackoffUntil || _probeJumpTaken)
|
||||
return false;
|
||||
_probeJumpTaken = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Call before sending the next open: the previous one, answered with nothing opened,
|
||||
/// counts as refused now (the next attempt came before its grace ran out). A verdict other than
|
||||
/// None means: act on it and don't send this open.</summary>
|
||||
public Verdict SettleBeforeOpen(long now)
|
||||
{
|
||||
if (!_pending || _answeredAt == 0)
|
||||
return Verdict.None;
|
||||
_pending = false;
|
||||
return Refused(_pendingId, now);
|
||||
}
|
||||
|
||||
/// <summary>An open of <paramref name="corpseId"/> went out; <paramref name="useDoneSeq"/> is the
|
||||
/// server UseDone count read just before it was sent.</summary>
|
||||
public void OnOpenSent(int corpseId, long now, int useDoneSeq)
|
||||
{
|
||||
_pending = true;
|
||||
_pendingId = corpseId;
|
||||
_sentAt = now;
|
||||
_seqAtSend = useDoneSeq;
|
||||
_answeredAt = 0;
|
||||
}
|
||||
|
||||
/// <summary>Every tick: <paramref name="useDoneSeq"/> is the server UseDone count now,
|
||||
/// <paramref name="lastError"/> the error of the latest one when the engine can say
|
||||
/// (<paramref name="haveLastError"/>).</summary>
|
||||
public Verdict OnTick(long now, int useDoneSeq, uint lastError, bool haveLastError)
|
||||
{
|
||||
if (!_pending)
|
||||
return Verdict.None;
|
||||
|
||||
if (_answeredAt == 0)
|
||||
{
|
||||
if (useDoneSeq != _seqAtSend)
|
||||
{
|
||||
if (haveLastError && lastError != 0)
|
||||
{
|
||||
_pending = false; // "too busy" or another error: says nothing about refusals
|
||||
return Verdict.None;
|
||||
}
|
||||
_answeredAt = now;
|
||||
}
|
||||
else if (now - _sentAt >= UnansweredForgetMs)
|
||||
{
|
||||
_pending = false;
|
||||
}
|
||||
return Verdict.None;
|
||||
}
|
||||
|
||||
if (now - _answeredAt < AnswerGraceMs)
|
||||
return Verdict.None;
|
||||
|
||||
_pending = false;
|
||||
return Refused(_pendingId, now);
|
||||
}
|
||||
|
||||
/// <summary>A corpse opened (the server sent its contents): uses work.</summary>
|
||||
public Verdict OnOpened(long now)
|
||||
{
|
||||
bool wasStuck = State == Phase.Stuck;
|
||||
Reset();
|
||||
return wasStuck ? Verdict.Recovered : Verdict.None;
|
||||
}
|
||||
|
||||
/// <summary>Back to normal: a relog, a login, a successful open.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
State = Phase.Normal;
|
||||
Refusals = 0;
|
||||
BackoffUntil = 0;
|
||||
BackoffMs = 0;
|
||||
LastRefusedCorpse = 0;
|
||||
_refused.Clear();
|
||||
_probeJumpTaken = false;
|
||||
_pending = false;
|
||||
_answeredAt = 0;
|
||||
}
|
||||
|
||||
private Verdict Refused(int corpseId, long now)
|
||||
{
|
||||
_refused.Add(corpseId);
|
||||
LastRefusedCorpse = corpseId;
|
||||
Refusals++;
|
||||
|
||||
switch (State)
|
||||
{
|
||||
case Phase.Normal:
|
||||
if (Refusals < RefusalsBeforeRetry)
|
||||
return Verdict.None;
|
||||
State = Phase.Retrying;
|
||||
return Verdict.CleanStopAndRetry;
|
||||
|
||||
case Phase.Retrying:
|
||||
if (_refused.Count < 2)
|
||||
return Verdict.DropCorpse; // stay Retrying: the next corpse's refusal decides
|
||||
State = Phase.Stuck;
|
||||
BackoffMs = FirstBackoffMs;
|
||||
BackoffUntil = now + BackoffMs;
|
||||
_probeJumpTaken = false;
|
||||
return Verdict.Stuck;
|
||||
|
||||
default: // Stuck: a probe after the back-off
|
||||
BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2));
|
||||
BackoffUntil = now + BackoffMs;
|
||||
_probeJumpTaken = false;
|
||||
return Verdict.StillStuck;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -194,8 +194,8 @@ public static class VTankLootEvaluator
|
|||
VTankNodeTypes.StringValueMatch => MatchStringValue(item, d),
|
||||
VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val,
|
||||
VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
|
||||
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) <= val,
|
||||
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
|
||||
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) <= val,
|
||||
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val,
|
||||
VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally
|
||||
VTankNodeTypes.ObjectClass => ScrollLearner.ClassMatches(item, ReadInt(d, 0)), // Scroll (42) also matches scroll Books
|
||||
VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0),
|
||||
|
|
@ -216,8 +216,8 @@ public static class VTankLootEvaluator
|
|||
VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, d),
|
||||
VTankNodeTypes.BuffedMissileDamageGE => MatchBuffedMissileDamageGE(item, d),
|
||||
VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
|
||||
VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
|
||||
VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(54, 0) >= ReadDouble(d, 0),
|
||||
VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val,
|
||||
VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(44, 0) >= ReadDouble(d, 0),
|
||||
VTankNodeTypes.TotalRatingsGE => MatchTotalRatingsGE(item, d),
|
||||
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false, // not implemented
|
||||
VTankNodeTypes.DisabledRule => MatchDisabledRule(d),
|
||||
|
|
@ -278,7 +278,7 @@ public static class VTankLootEvaluator
|
|||
private static bool MatchMinDamageGE(WorldObject item, IList<string> d)
|
||||
{
|
||||
double threshold = ReadDouble(d, 0);
|
||||
int maxDamage = item.Values(54, 0);
|
||||
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
|
||||
if (maxDamage == 0) return false;
|
||||
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
|
||||
double minDamage = maxDamage - (variance * maxDamage);
|
||||
|
|
@ -310,7 +310,7 @@ public static class VTankLootEvaluator
|
|||
private static bool MatchBuffedMedianDamageGE(WorldObject item, IList<string> d)
|
||||
{
|
||||
double threshold = ReadDouble(d, 0);
|
||||
int maxDamage = item.Values(54, 0);
|
||||
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
|
||||
if (maxDamage == 0) return false;
|
||||
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
|
||||
double minDamage = maxDamage - (variance * maxDamage);
|
||||
|
|
@ -320,7 +320,7 @@ public static class VTankLootEvaluator
|
|||
private static bool MatchBuffedMissileDamageGE(WorldObject item, IList<string> d)
|
||||
{
|
||||
double threshold = ReadDouble(d, 0);
|
||||
int maxDamage = item.Values(54, 0);
|
||||
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
|
||||
if (maxDamage == 0) return false;
|
||||
double elemBonus = item.Values((DoubleValueKey)152, 1.0);
|
||||
if (elemBonus < 1.0) elemBonus = 1.0;
|
||||
|
|
@ -356,4 +356,24 @@ public static class VTankLootEvaluator
|
|||
private static (double Val, int Key) Double(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
|
||||
// Buffed long/double helpers store value as double in slot 0 (matching VTank's "Read" of doubles).
|
||||
private static (double Val, int Key) DoubleKey(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
|
||||
|
||||
// A double key as the STypeFloat it reads. VTank files the appraisal's armor and weapon
|
||||
// profiles under Decal's 0x0A0000xx keys (uTank2 LootPlugins.DoubleValueKey), which no
|
||||
// object property has: read raw they were always 0, so LootSnob's "AttackBonus >=" rules
|
||||
// never matched (until 2026-10-05). Range (0x0A00000D) and the physics keys stay unmapped.
|
||||
private static DoubleValueKey FloatKey(int key) => unchecked((uint)key) switch
|
||||
{
|
||||
0x0A000000 => (DoubleValueKey)13, // SlashProt → ArmorModVsSlash
|
||||
0x0A000001 => (DoubleValueKey)14, // PierceProt → ArmorModVsPierce
|
||||
0x0A000002 => (DoubleValueKey)15, // BludgeonProt → ArmorModVsBludgeon
|
||||
0x0A000003 => (DoubleValueKey)18, // AcidProt → ArmorModVsAcid
|
||||
0x0A000004 => (DoubleValueKey)19, // LightningProt → ArmorModVsElectric
|
||||
0x0A000005 => (DoubleValueKey)17, // FireProt → ArmorModVsFire
|
||||
0x0A000006 => (DoubleValueKey)16, // ColdProt → ArmorModVsCold
|
||||
0x0A000009 => (DoubleValueKey)280, // SalvageWorkmanship → the engine's workmanship read (as wobjectgetdoubleprop)
|
||||
0x0A00000B => DoubleValueKey.DamageVariance, // Variance
|
||||
0x0A00000C => DoubleValueKey.WeaponOffense, // AttackBonus
|
||||
0x0A00000E => DoubleValueKey.DamageMod, // DamageBonus
|
||||
_ => (DoubleValueKey)key,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -289,7 +289,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; }
|
||||
|
||||
Host.ChangeCombatMode(cm);
|
||||
Host.ChangeCombatModeFor(cm, "Command", "/mt combat", force: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -379,7 +379,7 @@ public sealed partial class RynthAiPlugin
|
|||
targetId = Host.GetPlayerId();
|
||||
}
|
||||
|
||||
Host.CastSpell(targetId, spellId);
|
||||
Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -110,8 +110,11 @@ internal sealed class ManaStoneManager
|
|||
// off or the macro is stopped must leave the set too.
|
||||
PruneLootedForTap(NowMs);
|
||||
|
||||
// An Eternal Mana Charge refills gear for free, so it works with tapping off too.
|
||||
if (!_settings.EnableManaTapping && !HasEternalCharge()) { Reset(); return; }
|
||||
// Refilling worn gear from a charged stone (or a free Eternal charge) works with tapping
|
||||
// off too; only draining loot into empty stones needs tapping on. It used to need tapping
|
||||
// on for any refill, so charged stones and bought Mana Charges were never used with it
|
||||
// off (2026-10-08).
|
||||
if (!_settings.EnableManaTapping && !HasChargedRefillStone()) { Reset(); return; }
|
||||
if (!_settings.IsMacroRunning) { Reset(); return; }
|
||||
|
||||
long now = NowMs;
|
||||
|
|
@ -418,7 +421,6 @@ internal sealed class ManaStoneManager
|
|||
if (item == null) continue;
|
||||
if (IsManaStone(item)) continue;
|
||||
if (!IsOwnedByPlayer(item, playerId)) continue;
|
||||
if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget
|
||||
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
|
||||
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
|
||||
&& wield != 0) continue;
|
||||
|
|
@ -488,12 +490,23 @@ internal sealed class ManaStoneManager
|
|||
if (hasRule) return false; // explicit rules → match by name only
|
||||
if (!_settings.EnableManaTapping) return false; // no rules → auto-detect only when tapping is on
|
||||
|
||||
if (item.ObjectClass == AcObjectClass.ManaStone) return true;
|
||||
return !string.IsNullOrEmpty(item.Name)
|
||||
&& (item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase)
|
||||
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase));
|
||||
// Only the ordinary tapping stones and mana charges. Retail also has special stones
|
||||
// (Aligned, Aetheria, Unstable, Enchanted, Adjanite Mana Stone) that are not for
|
||||
// draining or recharging: an Aligned Mana Stone was used on a wand (2026-10-08). A
|
||||
// special stone is only touched when a ManaStone consumable rule names it.
|
||||
if (string.IsNullOrEmpty(item.Name))
|
||||
return item.ObjectClass == AcObjectClass.ManaStone; // unnamed yet: the class decides (looting)
|
||||
return OrdinaryStoneNames.Contains(item.Name)
|
||||
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>The retail tapping stones (ACE world data names), smallest to largest.</summary>
|
||||
internal static readonly HashSet<string> OrdinaryStoneNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone",
|
||||
"Greater Mana Stone", "Major Mana Stone",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// An unlimited mana charge (Eternal Mana Charge: 10,000 mana, never used up). Always
|
||||
/// "charged", never an empty stone to drain into, and preferred for refilling gear.
|
||||
|
|
@ -501,6 +514,35 @@ internal sealed class ManaStoneManager
|
|||
private static bool IsEternal(WorldObject item) =>
|
||||
!string.IsNullOrEmpty(item.Name) && item.Name.StartsWith("Eternal Mana", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// A stone that may refill worn gear when charged: what <see cref="IsManaStone"/> takes, but
|
||||
/// with tapping off as well (no rules: the ordinary stones and mana charges; with ManaStone
|
||||
/// rules: the named ones).
|
||||
/// </summary>
|
||||
internal bool IsRefillStone(WorldObject item)
|
||||
{
|
||||
if (IsManaStone(item)) return true;
|
||||
if (_settings.EnableManaTapping || string.IsNullOrEmpty(item.Name)) return false;
|
||||
foreach (var rule in _settings.ConsumableRules)
|
||||
if (rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(rule.Name))
|
||||
return false; // rules decide (IsManaStone already said no)
|
||||
return OrdinaryStoneNames.Contains(item.Name)
|
||||
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// FindChargedStone walks every known object; with tapping off it gates the whole tick, so
|
||||
// the answer is kept for a few seconds.
|
||||
private long _chargedCheckAt;
|
||||
private bool _chargedCached;
|
||||
private bool HasChargedRefillStone()
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now - _chargedCheckAt < 5000) return _chargedCached;
|
||||
_chargedCheckAt = now;
|
||||
_chargedCached = HasEternalCharge() || FindChargedStone() != 0;
|
||||
return _chargedCached;
|
||||
}
|
||||
|
||||
private bool HasEternalCharge()
|
||||
{
|
||||
int playerId = unchecked((int)_host.GetPlayerId());
|
||||
|
|
@ -609,7 +651,7 @@ internal sealed class ManaStoneManager
|
|||
|
||||
foreach (var item in _objectCache.AllKnownObjects())
|
||||
{
|
||||
if (!IsManaStone(item)) continue;
|
||||
if (!IsRefillStone(item)) continue;
|
||||
if (!IsOwnedByPlayer(item, playerId)) continue;
|
||||
|
||||
// Skip stones that timed out on use-on-player recently.
|
||||
|
|
@ -618,7 +660,6 @@ internal sealed class ManaStoneManager
|
|||
|
||||
// Eternal: always charged (its mana often can't be read), never used up — first choice.
|
||||
if (IsEternal(item)) return item.Id;
|
||||
if (!_settings.EnableManaTapping) continue; // tapping off: only the free charge
|
||||
|
||||
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
|
||||
continue;
|
||||
|
|
@ -649,13 +690,9 @@ internal sealed class ManaStoneManager
|
|||
if (IsManaStone(item)) continue;
|
||||
if (!IsOwnedByPlayer(item, playerId)) continue;
|
||||
|
||||
// Never tap a casting implement (wand/staff/orb). ACE refuses to
|
||||
// drain mana out of these into a stone, so the tap can never complete
|
||||
// and the loop spins forever (each attempt cancels movement + bumps
|
||||
// busy). This is most often the character's OWN casting wand mis-read
|
||||
// as a loose item — WieldedSlot can read 0 from a stale cache, so the
|
||||
// equipped-skip below misses it. Mirrors CombatManager.IsWandObject.
|
||||
if (IsWandLike(item)) continue;
|
||||
// Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses
|
||||
// retained items). Only items looted for Mana Tap are candidates, and the wielded /
|
||||
// listed-item / loot-kept checks below protect the character's own casters.
|
||||
|
||||
// Skip items that recently failed to drain.
|
||||
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
|
||||
|
|
@ -682,11 +719,9 @@ internal sealed class ManaStoneManager
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for casting implements (wand/staff/orb). ACE will not drain mana out
|
||||
/// of these into a mana stone, so they must never be selected as a tap target
|
||||
/// — otherwise the tap can never complete and loops forever. ObjectClass alone
|
||||
/// is unreliable for unappraised items, so we fall back to the name, matching
|
||||
/// CombatManager/BuffManager.IsWandObject.
|
||||
/// True for casting implements (wand/staff/orb). They drain like any other item;
|
||||
/// this is only a classifier. ObjectClass alone is unreliable for unappraised items,
|
||||
/// so we fall back to the name, matching CombatManager/BuffManager.IsWandObject.
|
||||
/// </summary>
|
||||
internal static bool IsWandLike(WorldObject item)
|
||||
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ internal static class DungeonMapBake
|
|||
private const int MaxDim = 8192; // the agent refuses bigger rasters
|
||||
|
||||
/// <summary>Where plans go. A test points this at its own folder.</summary>
|
||||
internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
internal static string CacheDir { get; set; } = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps");
|
||||
|
||||
// Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours).
|
||||
private static uint Argb(float r, float g, float b, float a) =>
|
||||
|
|
|
|||
|
|
@ -476,6 +476,8 @@ internal static class AfFileParser
|
|||
case MetaConditionType.MainManaPHE:
|
||||
case MetaConditionType.MainStamLE:
|
||||
case MetaConditionType.VitaePHE:
|
||||
// RynthAi only: NoKillsInMins 5 (minutes, decimals allowed).
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
// These use bare numbers (no braces): e.g. MainSlotsLE 4, BlockE F6820033
|
||||
rule.ConditionData = ExtractBareOrBrace(rest);
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -139,6 +139,9 @@ internal static class AfFileWriter
|
|||
case MetaConditionType.MainManaPHE:
|
||||
case MetaConditionType.MainStamLE:
|
||||
case MetaConditionType.VitaePHE:
|
||||
// RynthAi only (NoKillsInMins 5): metaf can't compile it to a .met, and an older
|
||||
// RynthAi loads it as Never with an "unknown condition keyword" warning.
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
// Bare values (no braces): MainSlotsLE 4, MainHealthLE 50
|
||||
writer.Write($"{keyword} {data}");
|
||||
break;
|
||||
|
|
@ -341,7 +344,7 @@ internal static class AfFileWriter
|
|||
5543 => "Neftet Recall",
|
||||
6321 => "Rynthid Recall",
|
||||
6322 => "Viridian Rise Recall",
|
||||
_ => $"Spell {spellId}"
|
||||
_ => NavPoint.RecallName(spellId)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ internal sealed class ExpressionEngine
|
|||
// The three data paths are settable only so offline tests can point them at a scratch
|
||||
// folder before anything reads or writes them; the plugin never changes them.
|
||||
internal static string ItemGiverDir { get; set; }
|
||||
= Path.Combine(@"C:\Games\RynthSuite\RynthAi", "ItemGiver");
|
||||
= Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
|
||||
|
||||
/// <summary>Millisecond tick for delayexec and the var-flush throttle. Tests swap it for a
|
||||
/// fake clock; the plugin never changes it.</summary>
|
||||
|
|
@ -107,8 +107,8 @@ internal sealed class ExpressionEngine
|
|||
private long _lastVarFlushMs;
|
||||
private string? _pvarPathCached;
|
||||
private const long VarFlushIntervalMs = 2000;
|
||||
internal static string PvarsDir { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars");
|
||||
internal static string GvarsPath { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt");
|
||||
internal static string PvarsDir { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "pvars");
|
||||
internal static string GvarsPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "gvars.txt");
|
||||
private Dictionary<string, (Func<string> Get, Action<string> Set)>? _settingsMap;
|
||||
|
||||
public IReadOnlyDictionary<string, string> Variables => _variables;
|
||||
|
|
@ -156,6 +156,11 @@ internal sealed class ExpressionEngine
|
|||
private CreatureProfileStore? _creatureStore;
|
||||
public void SetCreatureStore(CreatureProfileStore? store) => _creatureStore = store;
|
||||
|
||||
// secondssincelastkill[]: the plugin's kill clock. Null (not wired) reads as 0, i.e.
|
||||
// "just killed", so a "no kills for a while" test never holds by mistake.
|
||||
private KillClock? _killClock;
|
||||
public void SetKillClock(KillClock? clock) => _killClock = clock;
|
||||
|
||||
// ── Backward-compat shim ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Executes an expression for its side effects. Always returns true.</summary>
|
||||
|
|
@ -327,6 +332,8 @@ internal sealed class ExpressionEngine
|
|||
"getdatetimelocal" => DateTime.Now.ToString(A(0)),
|
||||
"getdatetimeutc" => DateTime.UtcNow.ToString(A(0)),
|
||||
"getunixtime" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
// Whole seconds since our last kill; before the first, since the macro start (or login).
|
||||
"secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture),
|
||||
|
||||
// ── World object queries ──────────────────────────────────────────
|
||||
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
|
||||
|
|
@ -342,7 +349,8 @@ internal sealed class ExpressionEngine
|
|||
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)),
|
||||
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)),
|
||||
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)),
|
||||
"wobjectfindalllandscapebytemplatetype" => EvalWobjectFindAllLandscapeByTemplateType(A(0)),
|
||||
"wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)),
|
||||
"wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)),
|
||||
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)),
|
||||
"wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)),
|
||||
"wobjectgetselection" => EvalWobjectGetSelection(),
|
||||
|
|
@ -1635,6 +1643,24 @@ internal sealed class ExpressionEngine
|
|||
return NewList(items);
|
||||
}
|
||||
|
||||
private string EvalWobjectFindAllLandscapeByObjectClass(string arg)
|
||||
{
|
||||
if (_worldObjectCache == null) return "[]";
|
||||
if (!int.TryParse(arg.Trim(), out int targetClass)) return "[]";
|
||||
|
||||
var items = new List<string>();
|
||||
var seen = new System.Collections.Generic.HashSet<int>();
|
||||
void Check(WorldObject wo)
|
||||
{
|
||||
if (!seen.Add(wo.Id)) return;
|
||||
if (ResolveEffectiveObjectClass(wo) == targetClass)
|
||||
items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name));
|
||||
}
|
||||
foreach (var wo in _worldObjectCache.GetLandscapeObjects()) Check(wo);
|
||||
foreach (var wo in _worldObjectCache.GetLandscape()) Check(wo);
|
||||
return NewList(items);
|
||||
}
|
||||
|
||||
private string EvalWobjectFindAllLandscapeByTemplateType(string arg)
|
||||
{
|
||||
if (_worldObjectCache == null || !_host.HasGetObjectWcid) return "[]";
|
||||
|
|
@ -2412,8 +2438,8 @@ internal sealed class ExpressionEngine
|
|||
{
|
||||
if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0";
|
||||
if (!_host.HasSelectItem) return "0";
|
||||
_host.SelectItem(uid);
|
||||
return "0";
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid);
|
||||
return _host.SelectItem(uid) ? "1" : "0";
|
||||
}
|
||||
|
||||
private string EvalActionTryUseItem(string arg)
|
||||
|
|
@ -2440,7 +2466,7 @@ internal sealed class ExpressionEngine
|
|||
|
||||
if (!EnsureMagicModeForCast()) return "0";
|
||||
|
||||
_host.CastSpell(targetId, spellId);
|
||||
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
|
||||
return "1";
|
||||
}
|
||||
|
||||
|
|
@ -2486,7 +2512,7 @@ internal sealed class ExpressionEngine
|
|||
if (!_host.HasGetCurrentCombatMode)
|
||||
{
|
||||
// Can't read mode — best-effort flip and bail.
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -2509,7 +2535,7 @@ internal sealed class ExpressionEngine
|
|||
if (wandId == 0 || !_host.HasUseObject)
|
||||
{
|
||||
// No wand (or no UseObject) — try bare-handed magic.
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -2613,7 +2639,7 @@ internal sealed class ExpressionEngine
|
|||
if (_host.HasChangeCombatMode
|
||||
&& (now - _castStanceLastFlipAt).TotalMilliseconds > CastStanceFlipGateMs)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
_host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
_castStanceLastFlipAt = now;
|
||||
}
|
||||
return false;
|
||||
|
|
@ -2717,7 +2743,7 @@ internal sealed class ExpressionEngine
|
|||
if (targetId == 0) targetId = _host.GetPlayerId();
|
||||
if (targetId == 0) return "2";
|
||||
|
||||
_host.CastSpell(targetId, spellId);
|
||||
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
|
||||
return "1";
|
||||
}
|
||||
|
||||
|
|
@ -2867,7 +2893,11 @@ internal sealed class ExpressionEngine
|
|||
_ => 0,
|
||||
};
|
||||
if (mode == 0) return "0";
|
||||
return _host.ChangeCombatMode(mode) ? "1" : "0";
|
||||
if (!_host.HasChangeCombatMode) return "0";
|
||||
int seq = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
bool ok = _host.ChangeCombatMode(mode);
|
||||
if (ok) ActionPacer.Begin(_host, PacedKind.CombatMode, 0, ActionPacer.ModeName(mode), "RynthAi/Meta (asked)", seq, mode);
|
||||
return ok ? "1" : "0";
|
||||
}
|
||||
|
||||
private string EvalGetBusyState()
|
||||
|
|
@ -3306,7 +3336,9 @@ internal sealed class ExpressionEngine
|
|||
["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0),
|
||||
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
|
||||
["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0),
|
||||
["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0),
|
||||
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
|
||||
["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0),
|
||||
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
|
||||
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
|
||||
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
|
||||
|
|
@ -3325,8 +3357,11 @@ internal sealed class ExpressionEngine
|
|||
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
|
||||
["BlastRange"] = (() => I(s.BlastRange), v => { if (int.TryParse(v, out int i)) s.BlastRange = i; }),
|
||||
["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }),
|
||||
["WallRange"] = (() => I(s.WallRange), v => { if (int.TryParse(v, out int i)) s.WallRange = i; }),
|
||||
["MinWallTargets"] = (() => I(s.MinWallTargets), v => { if (int.TryParse(v, out int i)) s.MinWallTargets = i; }),
|
||||
["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }),
|
||||
["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }),
|
||||
["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }),
|
||||
["GetManaAt"] = (() => I(s.GetManaAt), v => { if (int.TryParse(v, out int i)) s.GetManaAt = i; }),
|
||||
["TopOffHP"] = (() => I(s.TopOffHP), v => { if (int.TryParse(v, out int i)) s.TopOffHP = i; }),
|
||||
["TopOffStam"] = (() => I(s.TopOffStam), v => { if (int.TryParse(v, out int i)) s.TopOffStam = i; }),
|
||||
|
|
@ -3371,6 +3406,8 @@ internal sealed class ExpressionEngine
|
|||
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
|
||||
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
|
||||
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),
|
||||
["NavLabelMode"] = (() => I(s.NavLabelMode), v => { if (int.TryParse(v, out int i)) s.NavLabelMode = NavLabelModes.Clamp(i); }),
|
||||
["NavGuideLine"] = (() => B(s.NavGuideLine), v => s.NavGuideLine = ToDouble(v) != 0),
|
||||
["CurrentNavPath"] = (() => s.CurrentNavPath, v => s.CurrentNavPath = v),
|
||||
["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v),
|
||||
["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v),
|
||||
|
|
|
|||
|
|
@ -728,6 +728,19 @@ getunixtime[]
|
|||
Example: setvar[t, getunixtime[]] → snapshot a timestamp
|
||||
Example: getunixtime[] - getvar[t] > 60 → true if 60s have elapsed
|
||||
|
||||
secondssincelastkill[]
|
||||
Returns the whole number of seconds since your character's last kill.
|
||||
Only kills credited to you count (the server's "you killed it" notice);
|
||||
deaths you only see in chat, and your fellows' kills, do not.
|
||||
Before your first kill this session it counts from when the macro was last
|
||||
started, or from login (or a RynthAi reload) if the macro hasn't been started
|
||||
since, so a meta can still react when nothing has been killed at all.
|
||||
After a kill it is always the time since that kill, also across a macro stop/start.
|
||||
The meta condition "No Kills Within Minutes" (.af: NoKillsInMins 5) uses the same clock.
|
||||
Test in chat: /ra mexec secondssincelastkill[]
|
||||
Example: secondssincelastkill[] → e.g. "42"
|
||||
Example: secondssincelastkill[] >= 300 → true after 5 minutes without a kill
|
||||
|
||||
getaccounthash[]
|
||||
Returns a lowercase MD5 hex string of the current account name.
|
||||
Returns "" (empty string) if the account name is not yet available.
|
||||
|
|
|
|||
|
|
@ -145,6 +145,15 @@ internal sealed class MetaManager
|
|||
_expressions?.SetCreatureStore(store);
|
||||
}
|
||||
|
||||
// The plugin's kill clock (secondssincelastkill[], No Kills Within Minutes). Without one
|
||||
// (never in the plugin) the condition is false and the function says 0: fail closed.
|
||||
private KillClock? _killClock;
|
||||
public void SetKillClock(KillClock? clock)
|
||||
{
|
||||
_killClock = clock;
|
||||
_expressions?.SetKillClock(clock);
|
||||
}
|
||||
|
||||
public void SetPlayerId(uint id)
|
||||
{
|
||||
_playerId = id;
|
||||
|
|
@ -201,6 +210,7 @@ internal sealed class MetaManager
|
|||
engine.SetQuestTracker(_questTracker);
|
||||
engine.SetSettings(_settings);
|
||||
engine.SetCreatureStore(_creatureStore);
|
||||
engine.SetKillClock(_killClock);
|
||||
return engine;
|
||||
}
|
||||
|
||||
|
|
@ -728,6 +738,14 @@ internal sealed class MetaManager
|
|||
case MetaConditionType.NeedToBuff:
|
||||
return _buffManager != null && _buffManager.NeedsAnyBuff();
|
||||
|
||||
// ── No kills within N minutes (RynthAi only) ──────────────────────
|
||||
// The secondssincelastkill[] clock: our last kill (KillerNotification), or before
|
||||
// the first one the last macro start / login. Bad or missing minutes never hold.
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
return _killClock != null
|
||||
&& KillClock.TryParseMinutes(rule.ConditionData, out double noKillMins)
|
||||
&& _killClock.NoKillsFor(noKillMins);
|
||||
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -893,7 +911,7 @@ internal sealed class MetaManager
|
|||
}
|
||||
|
||||
// Fallback: a standalone .nav file in NavProfiles.
|
||||
string navFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"NavProfiles");
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
string fullPath = Path.Combine(navFolder, routeName + ".nav");
|
||||
if (File.Exists(fullPath))
|
||||
{
|
||||
|
|
@ -1092,7 +1110,7 @@ internal sealed class MetaManager
|
|||
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string name = string.Join(" ", parts, 3, parts.Length - 3);
|
||||
string metaDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
|
||||
string metaDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
string afPath = Path.Combine(metaDir, name + ".af");
|
||||
string metPath = Path.Combine(metaDir, name + ".met");
|
||||
|
||||
|
|
@ -1156,7 +1174,7 @@ internal sealed class MetaManager
|
|||
string path = name;
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
string stem = name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
|
||||
? name : name + ".utl";
|
||||
string candidate = Path.Combine(folder, stem);
|
||||
|
|
|
|||
52
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs
Normal file
52
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Meta;
|
||||
|
||||
/// <summary>
|
||||
/// How a rule edited in the Meta panel replaces the running one (update_rule / duplicate_rule).
|
||||
///
|
||||
/// The engine's Meta editor saves every change on its own since 2026-10-05 (debounced), so an
|
||||
/// update must not disturb a meta that is running:
|
||||
/// - the rule keeps its runtime latch (HasFired) and LastFiredAt. A fresh MetaRule had
|
||||
/// HasFired = false, so every save of a rule in the current state fired it again
|
||||
/// (an IF Always DO EmbedNav rule restarted its route from point 0 on each save);
|
||||
/// - the panel's DTO has no CallReturnState (CallState's return state) or ChatColors
|
||||
/// (ChatCapture's chat types), so an update used to drop both from VTank-imported rules.
|
||||
/// They are kept while the rule still has that action / condition.
|
||||
/// Nothing here touches the current state, the state clocks, the watchdog or the call stack.
|
||||
/// </summary>
|
||||
internal static class MetaRuleEdits
|
||||
{
|
||||
/// <summary>Puts <paramref name="edited"/> at <paramref name="index"/>, keeping the old rule's
|
||||
/// runtime latch and the fields the panel can't send. False when the index is out of range.</summary>
|
||||
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited)
|
||||
{
|
||||
if (index < 0 || index >= rules.Count) return false;
|
||||
MetaRule old = rules[index];
|
||||
KeepHidden(old, edited);
|
||||
edited.HasFired = old.HasFired;
|
||||
edited.LastFiredAt = old.LastFiredAt;
|
||||
rules[index] = edited;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Copies CallReturnState / ChatColors from <paramref name="from"/> into an edited copy
|
||||
/// that still has the same action / condition and carries none of its own; children by position.</summary>
|
||||
public static void KeepHidden(MetaRule from, MetaRule to)
|
||||
{
|
||||
if (to.Action == MetaActionType.CallMetaState && from.Action == MetaActionType.CallMetaState
|
||||
&& string.IsNullOrEmpty(to.CallReturnState))
|
||||
to.CallReturnState = from.CallReturnState;
|
||||
if (to.Condition == MetaConditionType.ChatMessageCapture && from.Condition == MetaConditionType.ChatMessageCapture
|
||||
&& string.IsNullOrEmpty(to.ChatColors))
|
||||
to.ChatColors = from.ChatColors;
|
||||
|
||||
if (from.Children != null && to.Children != null)
|
||||
for (int i = 0; i < from.Children.Count && i < to.Children.Count; i++)
|
||||
KeepHidden(from.Children[i], to.Children[i]);
|
||||
if (from.ActionChildren != null && to.ActionChildren != null)
|
||||
for (int i = 0; i < from.ActionChildren.Count && i < to.ActionChildren.Count; i++)
|
||||
KeepHidden(from.ActionChildren[i], to.ActionChildren[i]);
|
||||
}
|
||||
}
|
||||
|
|
@ -72,6 +72,8 @@ internal static class MetaSchema
|
|||
new(MetaConditionType.MainManaPHE, "MainManaPHE", "Main Mana % >="),
|
||||
new(MetaConditionType.MainStamLE, "MainStamLE", "Main Stam <="),
|
||||
new(MetaConditionType.VitaePHE, "VitaePHE", "Vitae % >="),
|
||||
// RynthAi only: VTank and metaf have no such condition (see AfFileWriter).
|
||||
new(MetaConditionType.NoKillsWithinMinutes, "NoKillsInMins", "No Kills Within Minutes"),
|
||||
};
|
||||
|
||||
// Index == (int)MetaActionType.
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Numerics;
|
|||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
|
|
@ -253,6 +254,13 @@ internal sealed class NavMarkerRenderer
|
|||
int n = route.Points.Count;
|
||||
bool circular = route.RouteType == NavRouteType.Circular;
|
||||
|
||||
// ── Waypoint labels and guide line (both off by default) ─────
|
||||
// Worked out from the route here, on the plugin tick, into an immutable frame; the
|
||||
// emit steps read only that frame. The guide goes in first so the route's lines can't
|
||||
// crowd it out of the engine's line buffer; the labels go in last (pass 4).
|
||||
NavOverlayFrame overlay = BuildOverlay(route, px, py, pz, playerNS, playerEW, heightOffset);
|
||||
NavOverlay.EmitGuide(overlay, _sink ??= new HostNav3DSink(_host), lineThick);
|
||||
|
||||
// ── Pass 1: Submit rings ─────────────────────────────────────
|
||||
// Arrays are indexed by window slot k (0..count), not absolute route
|
||||
// index — the absolute index can run far past count on a long route.
|
||||
|
|
@ -343,6 +351,68 @@ internal sealed class NavMarkerRenderer
|
|||
_host.Nav3DAddRing(pwx, pwy, pwz, ringRadius, ringThick * 1.4f, ColorPortal3D);
|
||||
_host.Nav3DAddLine(px, pwy, py, pwx, pwy, pwz, lineThick, ColorPortal3D);
|
||||
}
|
||||
|
||||
// ── Pass 4: waypoint labels (filled strokes, Nav3D triangles) ─
|
||||
if (overlay.Labels.Count > 0 && _host.HasNav3DTriangle)
|
||||
NavOverlay.EmitLabels(overlay, _sink);
|
||||
}
|
||||
|
||||
// ── Labels and guide line ────────────────────────────────────────
|
||||
private NavOverlay.RouteText? _labelText;
|
||||
private INav3DSink? _sink;
|
||||
|
||||
/// <summary>
|
||||
/// The tick's labels and guide line from the route and the two settings (Navigation ▸
|
||||
/// Waypoint Labels / Guide Line). Plugin tick only; returns an immutable frame.
|
||||
/// </summary>
|
||||
internal NavOverlayFrame BuildOverlay(NavRouteParser route, float px, float py, float pz,
|
||||
double playerNS, double playerEW, float heightOffset)
|
||||
{
|
||||
int mode = NavLabelModes.Clamp(_settings.NavLabelMode);
|
||||
bool guideOn = _settings.NavGuideLine;
|
||||
if (mode == NavLabelModes.Off && !guideOn)
|
||||
{
|
||||
_labelText = null;
|
||||
return NavOverlayFrame.Empty;
|
||||
}
|
||||
|
||||
var points = route.Points;
|
||||
int n = points.Count;
|
||||
NavOverlay.RouteText? text = null;
|
||||
if (mode != NavLabelModes.Off)
|
||||
{
|
||||
// Rebuilt only when the route, its length or the mode change (an edit in place keeps
|
||||
// the count: the Nav panel's edits replace the route or change its length).
|
||||
text = _labelText;
|
||||
if (text == null || !ReferenceEquals(text.Route, route) || text.Count != n || text.Mode != mode)
|
||||
_labelText = text = NavOverlay.BuildText(route, points, mode, SpellDatabase.GetSpellNameOrId);
|
||||
}
|
||||
else _labelText = null;
|
||||
|
||||
int active = _settings.ActiveNavIndex;
|
||||
bool guide = guideOn && active >= 0 && active < n && HasGroundCoords(points[active].Type);
|
||||
|
||||
(float X, float Y, float Z) WorldOf(int i)
|
||||
{
|
||||
var pt = points[i];
|
||||
return (px + (float)((pt.EW - playerEW) * 240.0),
|
||||
ResolveMarkerWorldY(route, i, heightOffset),
|
||||
py + (float)((pt.NS - playerNS) * 240.0));
|
||||
}
|
||||
|
||||
// D3D frame: X = EW, Y = height, Z = NS; the player's height is pose z.
|
||||
return NavOverlay.BuildFrame(text, guide, active, WorldOf, px, pz, py, heightOffset);
|
||||
}
|
||||
|
||||
/// <summary>The engine's Nav3D buffer.</summary>
|
||||
private sealed class HostNav3DSink : INav3DSink
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
public HostNav3DSink(RynthCoreHost host) => _host = host;
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
=> _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb);
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb)
|
||||
=> _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb);
|
||||
}
|
||||
|
||||
private void PrepareFloorCache(NavRouteParser route)
|
||||
|
|
|
|||
234
Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs
Normal file
234
Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>Settings ▸ Navigation ▸ "Waypoint Labels" (LegacyUiSettings.NavLabelMode).</summary>
|
||||
internal static class NavLabelModes
|
||||
{
|
||||
public const int Off = 0, Numbers = 1, Names = 2;
|
||||
public static int Clamp(int mode) => mode is >= Off and <= Names ? mode : Off;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One tick's waypoint labels and guide line, worked out from the route on the plugin tick and
|
||||
/// then never changed: the emit step reads only this, never the route's lists. Positions are in
|
||||
/// the Nav3D frame NavMarkerRenderer uses (X = east metres, Y = height, Z = north metres, in
|
||||
/// the player's landblock).
|
||||
/// </summary>
|
||||
internal sealed class NavOverlayFrame
|
||||
{
|
||||
public static readonly NavOverlayFrame Empty = new(Array.Empty<NavLabel>(), null, 0f, 0f, 0f);
|
||||
|
||||
public NavOverlayFrame(NavLabel[] labels, NavGuide? guide, float playerX, float playerY, float playerZ)
|
||||
{
|
||||
Labels = labels;
|
||||
Guide = guide;
|
||||
PlayerX = playerX;
|
||||
PlayerY = playerY;
|
||||
PlayerZ = playerZ;
|
||||
}
|
||||
|
||||
public IReadOnlyList<NavLabel> Labels { get; }
|
||||
public NavGuide? Guide { get; }
|
||||
public float PlayerX { get; }
|
||||
public float PlayerY { get; }
|
||||
public float PlayerZ { get; }
|
||||
}
|
||||
|
||||
/// <summary>One text line over a waypoint. Row 0 sits just above the ring; higher rows stack above it.</summary>
|
||||
internal sealed record NavLabel(float X, float Y, float Z, string Text, int Row, uint Color);
|
||||
|
||||
/// <summary>The line from the character's feet to the waypoint nav is heading for.</summary>
|
||||
internal sealed record NavGuide(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint Color);
|
||||
|
||||
/// <summary>
|
||||
/// Waypoint labels (numbers, or numbers and what happens there) and the guide line for the Nav3D
|
||||
/// markers (Silentkelpie's rynth PR #1 idea, done on our pump-thread Nav3D path). Both are off by
|
||||
/// default. Labels are drawn as filled strokes (Nav3D triangles) on an upright plane turned toward
|
||||
/// the character, sized up with distance so far labels stay readable; the guide is one Nav3D line.
|
||||
/// </summary>
|
||||
internal static class NavOverlay
|
||||
{
|
||||
/// <summary>Labels further than this from the character are left out (metres).</summary>
|
||||
public const float LabelRange = 60f;
|
||||
/// <summary>At most this many label lines a tick, nearest first (the active point's always first).</summary>
|
||||
public const int MaxLabelLines = 24;
|
||||
/// <summary>At most this many action lines stacked over one point.</summary>
|
||||
public const int MaxActionLines = 3;
|
||||
/// <summary>Triangle budget for all labels together (the engine keeps 8192 a tick for every plugin).</summary>
|
||||
public const int MaxLabelTriangles = 1600;
|
||||
public const int MaxLabelChars = 22;
|
||||
|
||||
public const uint LabelColor = 0xFFE6FFFF; // near white, a cyan touch like the rings
|
||||
public const uint ActiveLabelColor = 0xFFFF6A6A;
|
||||
public const uint ActionLabelColor = 0xFFFFC040;
|
||||
public const uint GuideColor = 0xFFFFD21E;
|
||||
|
||||
private const float GuideLift = 0.05f;
|
||||
private const float MaxGuideLength = 500f;
|
||||
|
||||
// ── Text per route (rebuilt when the route or the mode changes) ──────
|
||||
|
||||
/// <summary>
|
||||
/// Label text for every route point, built once per route and mode: <c>Own[i]</c> for a point
|
||||
/// with ground coordinates (null otherwise), and the action lines ("13 RECALL ...") hung on
|
||||
/// the ground point before them (the point where nav does them).
|
||||
/// </summary>
|
||||
internal sealed class RouteText
|
||||
{
|
||||
public readonly object Route;
|
||||
public readonly int Count, Mode;
|
||||
public readonly string?[] Own;
|
||||
public readonly string[]?[] Actions;
|
||||
|
||||
public RouteText(object route, int count, int mode, string?[] own, string[]?[] actions)
|
||||
{
|
||||
Route = route; Count = count; Mode = mode; Own = own; Actions = actions;
|
||||
}
|
||||
}
|
||||
|
||||
public static RouteText BuildText(object route, IReadOnlyList<NavPoint> points, int mode, Func<int, string> spellName)
|
||||
{
|
||||
int n = points.Count;
|
||||
var own = new string?[n];
|
||||
var actions = new string[]?[n];
|
||||
var pending = new List<string>();
|
||||
int lastGround = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
NavPoint p = points[i];
|
||||
if (HasGroundCoords(p.Type))
|
||||
{
|
||||
own[i] = mode == NavLabelModes.Names ? Fit(GroundName(i, p)) : i.ToString();
|
||||
lastGround = i;
|
||||
continue;
|
||||
}
|
||||
if (mode != NavLabelModes.Names || lastGround < 0) continue;
|
||||
var list = actions[lastGround] ??= Array.Empty<string>();
|
||||
if (list.Length < MaxActionLines)
|
||||
actions[lastGround] = Append(list, Fit(ActionName(i, p, spellName)));
|
||||
else if (list.Length == MaxActionLines)
|
||||
actions[lastGround] = Append(list, "...");
|
||||
}
|
||||
return new RouteText(route, n, mode, own, actions);
|
||||
}
|
||||
|
||||
private static string[] Append(string[] a, string s)
|
||||
{
|
||||
var b = new string[a.Length + 1];
|
||||
Array.Copy(a, b, a.Length);
|
||||
b[a.Length] = s;
|
||||
return b;
|
||||
}
|
||||
|
||||
private static bool HasGroundCoords(NavPointType t) => NavRouteParser.IsPlainWaypoint(t) || t == NavPointType.Jump;
|
||||
|
||||
private static string GroundName(int i, NavPoint p) => p.Type switch
|
||||
{
|
||||
NavPointType.Checkpoint => $"{i} CHECKPOINT",
|
||||
NavPointType.Jump => $"{i} JUMP",
|
||||
_ => i.ToString(),
|
||||
};
|
||||
|
||||
private static string ActionName(int i, NavPoint p, Func<int, string> spellName) => p.Type switch
|
||||
{
|
||||
NavPointType.Recall => $"{i} {spellName(p.SpellId)}",
|
||||
NavPointType.Pause => $"{i} PAUSE {Math.Max(0, p.PauseTimeMs) / 1000.0:0.#}S",
|
||||
NavPointType.Chat => $"{i} CHAT {p.ChatCommand}",
|
||||
NavPointType.OpenVendor => $"{i} VENDOR {p.TargetName}",
|
||||
NavPointType.PortalNPC => $"{i} PORTAL {p.TargetName}",
|
||||
NavPointType.Npc => $"{i} NPC {p.TargetName}",
|
||||
_ => $"{i} {p.Type}",
|
||||
};
|
||||
|
||||
private static string Fit(string s)
|
||||
{
|
||||
s = s.Trim().ToUpperInvariant();
|
||||
return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s;
|
||||
}
|
||||
|
||||
// ── The frame (plugin tick) ───────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Builds the tick's overlay from <paramref name="text"/> (null: no labels) and the waypoints'
|
||||
/// positions (<paramref name="worldOf"/>, only asked for points that have ground coordinates).
|
||||
/// <paramref name="active"/> is the point nav is heading for; <paramref name="guide"/> draws the
|
||||
/// line to it (the caller passes false when that point has no ground coordinates). Plugin tick only.
|
||||
/// </summary>
|
||||
public static NavOverlayFrame BuildFrame(RouteText? text, bool guide, int active,
|
||||
Func<int, (float X, float Y, float Z)> worldOf, float playerX, float playerY, float playerZ, float lift)
|
||||
{
|
||||
NavGuide? g = null;
|
||||
if (guide && active >= 0)
|
||||
{
|
||||
var (ax, ay, az) = worldOf(active);
|
||||
float dx = ax - playerX, dz = az - playerZ;
|
||||
if (dx * dx + dz * dz <= MaxGuideLength * MaxGuideLength)
|
||||
g = new NavGuide(playerX, playerY + lift + GuideLift, playerZ, ax, ay, az, GuideColor);
|
||||
}
|
||||
|
||||
if (text == null || text.Mode == NavLabelModes.Off)
|
||||
return g == null ? NavOverlayFrame.Empty : new NavOverlayFrame(Array.Empty<NavLabel>(), g, playerX, playerY, playerZ);
|
||||
|
||||
// Ground points in range, nearest first; the active point first of all.
|
||||
var near = new List<(float D2, int I, float X, float Y, float Z)>();
|
||||
float range2 = LabelRange * LabelRange;
|
||||
for (int i = 0; i < text.Count; i++)
|
||||
{
|
||||
if (text.Own[i] == null) continue;
|
||||
var (x, y, z) = worldOf(i);
|
||||
float dx = x - playerX, dz = z - playerZ;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
if (d2 > range2) continue;
|
||||
near.Add((i == active ? -1f : d2, i, x, y, z));
|
||||
}
|
||||
near.Sort((a, b) => a.D2.CompareTo(b.D2));
|
||||
|
||||
var labels = new List<NavLabel>(Math.Min(MaxLabelLines, near.Count * 2));
|
||||
foreach (var (_, i, x, y, z) in near)
|
||||
{
|
||||
if (labels.Count >= MaxLabelLines) break;
|
||||
labels.Add(new NavLabel(x, y, z, text.Own[i]!, 0, i == active ? ActiveLabelColor : LabelColor));
|
||||
string[]? acts = text.Actions[i];
|
||||
if (acts == null) continue;
|
||||
for (int k = 0; k < acts.Length && labels.Count < MaxLabelLines; k++)
|
||||
labels.Add(new NavLabel(x, y, z, acts[k], k + 1, ActionLabelColor));
|
||||
}
|
||||
return new NavOverlayFrame(labels.ToArray(), g, playerX, playerY, playerZ);
|
||||
}
|
||||
|
||||
// ── Emit (plugin tick, into the Nav3D buffer) ──────────────────────
|
||||
|
||||
/// <summary>The guide line, if the frame has one: submitted before the route's lines so a full line buffer never drops it.</summary>
|
||||
public static void EmitGuide(NavOverlayFrame frame, INav3DSink sink, float thickness)
|
||||
{
|
||||
NavGuide? g = frame.Guide;
|
||||
if (g != null)
|
||||
sink.Line(g.X1, g.Y1, g.Z1, g.X2, g.Y2, g.Z2, thickness, g.Color);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Each label as filled strokes (triangles). Returns the number of triangles used (at most
|
||||
/// <see cref="MaxLabelTriangles"/>).
|
||||
/// </summary>
|
||||
public static int EmitLabels(NavOverlayFrame frame, INav3DSink sink)
|
||||
{
|
||||
int tris = 0;
|
||||
foreach (NavLabel l in frame.Labels)
|
||||
{
|
||||
if (!EmitLabel(l, frame.PlayerX, frame.PlayerZ, sink, ref tris)) break;
|
||||
}
|
||||
return tris;
|
||||
}
|
||||
|
||||
/// <summary>The line height (m) for a label this far from the character.</summary>
|
||||
internal static float LineHeight(float distance) => Nav3DText.LineHeight(distance);
|
||||
|
||||
// The text itself is drawn by the shared Nav3DText (Plugins/Shared/Nav3DText.cs), which
|
||||
// RynthNav's path markers use too.
|
||||
private static bool EmitLabel(NavLabel l, float playerX, float playerZ, INav3DSink sink, ref int tris)
|
||||
=> Nav3DText.Emit(l.X, l.Y, l.Z, l.Text, l.Row, l.Color, playerX, playerZ, sink, ref tris, MaxLabelTriangles);
|
||||
}
|
||||
|
|
@ -75,7 +75,16 @@ internal sealed class NavigationEngine
|
|||
private bool _inPause;
|
||||
private int _pauseIdx = -1; // the Pause waypoint _pauseUntil belongs to
|
||||
private long _pauseUntil;
|
||||
private double _prevDist = double.MaxValue;
|
||||
// Closest the character has come to the current waypoint since it became the target (or
|
||||
// since a pause / escape / teleport reset it). It used to hold only the previous tick's
|
||||
// distance, so a "sweep pass" needed the distance to grow 0.3 yd in ONE 33 ms tick (over
|
||||
// 9 yd/s straight away from the point): just past a point the distance grows slowly, the
|
||||
// pass was never seen, and nav turned round and walked back to the point (2026-10-05).
|
||||
private double _closestDist = double.MaxValue;
|
||||
// Where the character stood when it started on the current waypoint (NaN = take it on the
|
||||
// next steering tick). With the waypoint it gives the way the route arrives at the point,
|
||||
// for the pass-through rule (PassedThrough).
|
||||
private double _legStartNs = double.NaN, _legStartEw = double.NaN;
|
||||
|
||||
// ── Portal/Recall state machine ──────────────────────────────────────────
|
||||
private enum PortalState
|
||||
|
|
@ -147,7 +156,7 @@ internal sealed class NavigationEngine
|
|||
public int Doorways;
|
||||
public long StartedAt;
|
||||
public long DeadlineAt;
|
||||
public double PrevDist = double.MaxValue;
|
||||
public double ClosestDist = double.MaxValue; // closest to the current detour point so far
|
||||
public bool Paused; // nav was stopped (combat, loot, buff, door) mid-detour
|
||||
public long PausedAt;
|
||||
public double PausedNs = double.NaN, PausedEw = double.NaN;
|
||||
|
|
@ -244,10 +253,39 @@ internal sealed class NavigationEngine
|
|||
private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards;
|
||||
private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult);
|
||||
|
||||
// Lookahead: within this distance of a waypoint, blend the aim point toward
|
||||
// the next one so corners are cut smoothly. 0 = off (aim straight at each
|
||||
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
|
||||
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
|
||||
// Lookahead (corner rounding): within this distance of a waypoint, blend the aim point
|
||||
// toward the next one so corners are rounded. It used to be the Lookahead setting alone
|
||||
// (4 yd), whatever the nav point reach: at a 1 yd reach the aim was already 75% of the way
|
||||
// down the next leg when the character got to 1 yd, so it cut the corner, never got within
|
||||
// the reach, and ran into the wall at the corner (2026-10-05). Now the reach decides how
|
||||
// much rounding there is: none at or under CornerRoundFreeReachYd, then CornerRoundPerReachYd
|
||||
// per yard of reach above it, never more than the Lookahead setting (Advanced > Navigation >
|
||||
// Steering; 0 = off). Blending only matters where it starts outside the reach, so there is
|
||||
// none up to a 2 yd reach (the 1.5 yd default gives 1 yd, inside it); it reaches the 4 yd
|
||||
// setting at a 3 yd reach, so 3-5 yd round corners as before. Doorway points never blend.
|
||||
internal const double CornerRoundFreeReachYd = 1.0, CornerRoundPerReachYd = 2.0;
|
||||
internal static double CornerLookaheadYards(double lookaheadSetting, double reachYd)
|
||||
=> Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting));
|
||||
private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards);
|
||||
|
||||
// Pass-through: a plain waypoint the character has gone past (it is beyond the point along
|
||||
// the way it came, and no farther to the side than the sweep radius) counts as reached,
|
||||
// so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the
|
||||
// point is behind the character: a corner cut toward the next point never qualifies.
|
||||
// Doorway points keep their own tight reach and sweep and never use it.
|
||||
private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction
|
||||
private bool PassedThrough(NavPoint pt, double ns, double ew)
|
||||
{
|
||||
if (pt.Doorway || double.IsNaN(_legStartNs)) return false;
|
||||
double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0;
|
||||
double len = Math.Sqrt(ux * ux + uy * uy);
|
||||
if (len < PassMinLegYd) return false;
|
||||
ux /= len; uy /= len;
|
||||
double ax = (ns - pt.NS) * 240.0, ay = (ew - pt.EW) * 240.0;
|
||||
double along = ax * ux + ay * uy;
|
||||
double side = Math.Abs(ax * uy - ay * ux);
|
||||
return along > 0.0 && side <= SweepFor(pt);
|
||||
}
|
||||
|
||||
|
||||
// Mode 0 heading servo: cap the heading change we command per tick so the
|
||||
|
|
@ -411,7 +449,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
_lastRoute = route;
|
||||
_inPause = false;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_linearDir = 1;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
|
|
@ -462,7 +500,7 @@ internal sealed class NavigationEngine
|
|||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
_watchdogNext = Now + (long)WatchdogMs;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_globalSettling = false;
|
||||
ResetRecovery("teleported");
|
||||
}
|
||||
|
|
@ -582,7 +620,7 @@ internal sealed class NavigationEngine
|
|||
if (dist < ReachFor(pt))
|
||||
{
|
||||
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing");
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
// Advance before the jump: the Jumper pauses nav and later restores what it
|
||||
// saw, so jumping first turned a finished Once route back on (re-run from [0]).
|
||||
|
|
@ -591,17 +629,33 @@ internal sealed class NavigationEngine
|
|||
return;
|
||||
}
|
||||
|
||||
// Closest-approach detection — prevents circling.
|
||||
// Matches old NavigationManager exactly.
|
||||
if (_prevDist < SweepFor(pt) && dist > _prevDist + 0.3)
|
||||
// First tick on this waypoint (or after a pause / escape / teleport): remember where
|
||||
// the approach starts, for the pass-through rule.
|
||||
if (_closestDist == double.MaxValue) { _legStartNs = ns; _legStartEw = ew; }
|
||||
|
||||
// Went past it: the point is behind, close enough to the side. Counts as reached
|
||||
// instead of turning round to walk back to it.
|
||||
if (PassedThrough(pt, ns, ew))
|
||||
{
|
||||
_host.Log($"Nav: sweep-pass [{idx}] prev={_prevDist:F1} now={dist:F1}yd → advancing");
|
||||
_prevDist = double.MaxValue;
|
||||
_host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
}
|
||||
_prevDist = dist;
|
||||
|
||||
// Closest-approach detection — prevents circling: within the sweep radius, then
|
||||
// 0.3 yd farther out than the closest it came.
|
||||
if (_closestDist < SweepFor(pt) && dist > _closestDist + 0.3)
|
||||
{
|
||||
_host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
}
|
||||
_closestDist = Math.Min(_closestDist, dist);
|
||||
|
||||
SteerToWaypoint(idx, pt, route, ns, ew, dist);
|
||||
}
|
||||
|
|
@ -622,7 +676,7 @@ internal sealed class NavigationEngine
|
|||
// closest-approach reading from before the pause says nothing about where we
|
||||
// are now; kept, the first tick back reads the displacement as a sweep-pass
|
||||
// and advances past a waypoint that was never reached.
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_stopRequestedAt = long.MaxValue;
|
||||
// A detour survives the pause: it re-plans on the way back if the pause
|
||||
// moved us. Whatever moved us, being far off the route afterwards is not
|
||||
|
|
@ -689,7 +743,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
_host.Log($"Nav: macro start — {how} waypoint [{best}] ({Math.Sqrt(Sq(route.Points[best].NS - ns) + Sq(route.Points[best].EW - ew)) * 240.0:F0}yd) instead of [{cur}]");
|
||||
_settings.ActiveNavIndex = best;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_stuckCount = 0;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
|
|
@ -747,7 +801,7 @@ internal sealed class NavigationEngine
|
|||
_linearDir = 1;
|
||||
_stuckCount = 0;
|
||||
_recoveryKind = RecoveryKind.Jump;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
_hasGoodHeading = false;
|
||||
|
|
@ -1146,7 +1200,7 @@ internal sealed class NavigationEngine
|
|||
private void Advance(NavRouteParser route)
|
||||
{
|
||||
int oldIdx = _settings.ActiveNavIndex;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_portalState = PortalState.None;
|
||||
// Reaching a waypoint is progress: the next snag gets a fresh detour budget.
|
||||
_detourAttempts = 0;
|
||||
|
|
@ -1238,7 +1292,7 @@ internal sealed class NavigationEngine
|
|||
/// current route's iteration direction. Used by the dense-waypoint
|
||||
/// skip loop in <see cref="Advance"/>. Mirrors the single-step logic
|
||||
/// in the main switch; factored out so the skip loop can call it
|
||||
/// without re-clearing _prevDist / _portalState.
|
||||
/// without re-clearing _closestDist / _portalState.
|
||||
/// </summary>
|
||||
private void AdvanceOneIndex(NavRouteParser route)
|
||||
{
|
||||
|
|
@ -1352,7 +1406,7 @@ internal sealed class NavigationEngine
|
|||
private void HoldAtCampRoute(int idx, double dist, NavRouteParser route)
|
||||
{
|
||||
if (_isMovingForward || _isTurning) StopMovement();
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
if (!_campHoldAnnounced)
|
||||
{
|
||||
|
|
@ -1448,7 +1502,7 @@ internal sealed class NavigationEngine
|
|||
_host.Log($"Nav: no player id — cannot fire recall {pt.SpellId}");
|
||||
return;
|
||||
}
|
||||
_host.CastSpell(target, pt.SpellId);
|
||||
_host.CastSpellFor(target, pt.SpellId, "Nav", $"recall spell {pt.SpellId}");
|
||||
_host.Log($"Nav: CastSpell(recall {pt.SpellId}) on player 0x{target:X8}");
|
||||
}
|
||||
|
||||
|
|
@ -1707,7 +1761,7 @@ internal sealed class NavigationEngine
|
|||
// teleport happened but wasn't seen, or the route stays on this side).
|
||||
if (NextWalkTargetBeyond(route, _settings.ActiveNavIndex, OffTrackYards, out int farIdx, out double farYd))
|
||||
{
|
||||
string what = pt.Type == NavPointType.Recall ? $"the recall (spell {pt.SpellId})" : $"the portal '{pt.TargetName}'";
|
||||
string what = pt.Type == NavPointType.Recall ? $"the recall ({NavPoint.RecallName(pt.SpellId)})" : $"the portal '{pt.TargetName}'";
|
||||
string msg = $"Nav: {what} didn't teleport within {ActionTimeoutMs / 1000:F0}s, and the next waypoint [{farIdx}] is {farYd:F0}yd away - navigation stopped.";
|
||||
_host.Log(msg);
|
||||
_host.WriteToChat(msg, 1);
|
||||
|
|
@ -2229,7 +2283,7 @@ internal sealed class NavigationEngine
|
|||
// The escape moves us off the approach line, so the closest-approach
|
||||
// tracker's last reading is meaningless — reset it or the next steer
|
||||
// tick reads the retreat as a sweep-pass and advances the index.
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════════════
|
||||
|
|
@ -2577,7 +2631,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
StopMovement();
|
||||
_inRecovery = false;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_settings.NavIsStuck = true;
|
||||
return true;
|
||||
}
|
||||
|
|
@ -2604,7 +2658,7 @@ internal sealed class NavigationEngine
|
|||
+ $"reached {Math.Min(d.Index, d.Points.Count)}/{d.Points.Count}, door requests {d.DoorRequestCount}, re-plans {d.Replans}, "
|
||||
+ $"{(Now - d.StartedAt) / 1000.0:F1}s - result: {result}");
|
||||
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
if (!_inRecovery) _settings.NavIsStuck = false;
|
||||
}
|
||||
|
||||
|
|
@ -2635,7 +2689,7 @@ internal sealed class NavigationEngine
|
|||
// against the deadline; if the pause moved us, plan again from here.
|
||||
d.Paused = false;
|
||||
d.DeadlineAt += Now - d.PausedAt;
|
||||
d.PrevDist = double.MaxValue;
|
||||
d.ClosestDist = double.MaxValue;
|
||||
double moved = double.IsNaN(d.PausedNs) ? 0.0 : NavYd(ns - d.PausedNs, ew - d.PausedEw);
|
||||
if (moved > DetourReplanMovedYd && !ReplanDetour(route, d, moved)) return;
|
||||
}
|
||||
|
|
@ -2650,10 +2704,10 @@ internal sealed class NavigationEngine
|
|||
|
||||
var p = d.Points[d.Index];
|
||||
double dist = NavYd(p.NS - ns, p.EW - ew);
|
||||
if (dist < ReachFor(p) || (d.PrevDist < SweepFor(p) && dist > d.PrevDist + 0.3))
|
||||
if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3))
|
||||
{
|
||||
d.Index++;
|
||||
d.PrevDist = double.MaxValue;
|
||||
d.ClosestDist = double.MaxValue;
|
||||
if (d.Index >= d.Points.Count)
|
||||
{
|
||||
// Back on the route: resume at the rejoin waypoint; normal nav walks the last leg.
|
||||
|
|
@ -2662,7 +2716,7 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
return;
|
||||
}
|
||||
d.PrevDist = dist;
|
||||
d.ClosestDist = Math.Min(d.ClosestDist, dist);
|
||||
|
||||
// Aim point: blend toward the following point near arrival, but less than the
|
||||
// route does (doorways are narrow).
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ internal sealed class RadarWallRenderer
|
|||
private readonly bool[] _inside = new bool[MaxPolyVerts];
|
||||
|
||||
private static readonly string ExploredDir =
|
||||
System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"ExploredDungeons");
|
||||
System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ExploredDungeons");
|
||||
|
||||
public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ 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 <n|auto>|refresh|item] — T11 loot: wield counters, aug override, parsed item");
|
||||
ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style");
|
||||
ChatLine("[RynthAi] /ra mexec <expr> — evaluate meta expression");
|
||||
ChatLine("[RynthAi] /ra listvars — show session variables");
|
||||
ChatLine("[RynthAi] /ra listpvars — show persistent variables");
|
||||
|
|
@ -68,6 +70,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
|
||||
ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)");
|
||||
ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics");
|
||||
ChatLine("[RynthAi] /ra pace — what the server is still answering (one action at a time)");
|
||||
ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop");
|
||||
ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted");
|
||||
ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow");
|
||||
|
|
@ -240,7 +243,7 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
bool ok = Host.CastSpell(_currentTargetId, spellId);
|
||||
bool ok = Host.CastSpellFor(_currentTargetId, spellId, "Command", $"spell {spellId} (/ra cast)", asked: true);
|
||||
ChatLine($"[RynthAi] CastSpell(target=0x{_currentTargetId:X8}, spell={spellId}) => {ok}");
|
||||
}
|
||||
|
||||
|
|
@ -1600,8 +1603,12 @@ public sealed partial class RynthAiPlugin
|
|||
if (inUse) ReloadLootProfileInUse(d.TargetPath);
|
||||
}
|
||||
|
||||
/// <summary>What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache.</summary>
|
||||
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like)
|
||||
/// <summary>
|
||||
/// What a loot rule can be built from: the item's name, class, stack, key properties and
|
||||
/// T11 reading, from the object cache. <paramref name="like"/> adds its spells;
|
||||
/// <paramref name="t11"/> asks for an ID when a T11 item's text hasn't arrived.
|
||||
/// </summary>
|
||||
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11)
|
||||
{
|
||||
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
|
||||
if (wo == null) return null;
|
||||
|
|
@ -1631,6 +1638,10 @@ public sealed partial class RynthAiPlugin
|
|||
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
|
||||
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
|
||||
}
|
||||
// Always read (a cached parse), so the popup knows whether the T11 option applies.
|
||||
f.T11 = Loot.T11ItemSupport.Get(wo);
|
||||
// T11 tier, grade and modifiers are appraisal text: ask for it, so the next preview has them.
|
||||
if (t11 && f.T11.IsT11 && !f.T11.HasText && Host.HasRequestId) Host.RequestId(itemId);
|
||||
return f;
|
||||
}
|
||||
|
||||
|
|
@ -1653,17 +1664,18 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for
|
||||
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview]: a rule for
|
||||
/// the selected item, straight into the loot profile in use (the defaults: exact
|
||||
/// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep).
|
||||
/// t11 also requires the item's T11 attributes.
|
||||
/// </summary>
|
||||
private void HandleLootCommand(string[] parts)
|
||||
{
|
||||
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
|
||||
if (sub != "add")
|
||||
{
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use");
|
||||
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing.");
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use");
|
||||
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing.");
|
||||
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor.");
|
||||
return;
|
||||
}
|
||||
|
|
@ -1683,6 +1695,7 @@ public sealed partial class RynthAiPlugin
|
|||
case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break;
|
||||
case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break;
|
||||
case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break;
|
||||
case "t11": req.IncludeT11 = true; break;
|
||||
case "preview":
|
||||
case "?": preview = true; break;
|
||||
default:
|
||||
|
|
@ -1692,7 +1705,7 @@ public sealed partial class RynthAiPlugin
|
|||
req.KeepCount = n;
|
||||
break;
|
||||
}
|
||||
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview.");
|
||||
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like, t11 or preview.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
@ -2148,6 +2161,8 @@ public sealed partial class RynthAiPlugin
|
|||
private void HandleClearBusyCommand()
|
||||
{
|
||||
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
// You asked for it: forget what the pacing waits on too (ActionPacer).
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra clearbusy");
|
||||
if (Host.HasForceResetBusyCount)
|
||||
Host.ForceResetBusyCount();
|
||||
if (Host.HasStopCompletely)
|
||||
|
|
@ -2171,9 +2186,10 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
ChatLine("[RynthAi] PANIC — full AC state reset");
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra panic");
|
||||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true);
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Command");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// The item-action lock itself is not the busy count: AC refuses every use,
|
||||
|
|
@ -2612,7 +2628,7 @@ public sealed partial class RynthAiPlugin
|
|||
string playerPart = argStr.Substring(toIdx + 4).Trim();
|
||||
|
||||
// Resolve profile path — bare name resolved from ItemGiver dir, .utl extension added if needed
|
||||
const string itemGiverDir = @"C:\Games\RynthSuite\RynthAi\ItemGiver";
|
||||
string itemGiverDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
|
||||
string profilePath = System.IO.Path.IsPathRooted(profileArg)
|
||||
? profileArg
|
||||
: System.IO.Path.Combine(itemGiverDir, profileArg);
|
||||
|
|
@ -2873,6 +2889,11 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
settings.IsMacroRunning = true;
|
||||
// The patrol picked its own start (the first waypoint in sight). Starting the macro
|
||||
// here must not also trigger the macro-start "nearest waypoint" pick on the next
|
||||
// tick: on a loop that is often a waypoint near the END (it comes back to the start),
|
||||
// so the bot walked there, back to waypoint 0, and only then on (2026-10-08).
|
||||
_macroWasRunning = true;
|
||||
}
|
||||
settings.CurrentNavPath = string.Empty;
|
||||
settings.CurrentRoute = route;
|
||||
|
|
@ -2975,7 +2996,7 @@ public sealed partial class RynthAiPlugin
|
|||
sb.Append("\"routes\":[");
|
||||
try
|
||||
{
|
||||
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
if (System.IO.Directory.Exists(navFolder))
|
||||
{
|
||||
var files = System.IO.Directory.GetFiles(navFolder, "*.nav");
|
||||
|
|
|
|||
|
|
@ -1,381 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// /ra iteminfo — Mag-style item info (ratings, damage, spells, slayer, imbues …) as one line or
|
||||
/// as pet-roster style lines, printed on demand, on select or on a left/right mouse click;
|
||||
/// ported from UtilityBelt ub-IT / Mag-Tools ItemInfo. Partial class of RynthAiPlugin.
|
||||
///
|
||||
/// /ra iteminfo describe the selected item (IDs it first when needed)
|
||||
/// /ra iteminfo on|off describe every item you select
|
||||
/// /ra iteminfo settings open/close the Item Info settings window
|
||||
/// /ra iteminfo fields list fields and ratings with their on/off state
|
||||
/// /ra iteminfo field <name> on|off show/hide one field (ratings, slayer, spells, …)
|
||||
/// /ra iteminfo rating <tag> on|off show/hide one rating (D, CD, CDR, …)
|
||||
/// /ra iteminfo value on|off append value + burden
|
||||
/// /ra iteminfo verbose on|off list every spell instead of Mag's filter
|
||||
/// /ra iteminfo click left|right|off print the selected item after a mouse click
|
||||
/// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner
|
||||
/// /ra iteminfo reset restore defaults
|
||||
/// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi).
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
// One pending describe at a time: the newest request replaces the previous one.
|
||||
private int _itemInfoPendingId;
|
||||
private long _itemInfoPendingSince;
|
||||
|
||||
// Automatic triggers (select + click) can both fire for one click; the same item inside
|
||||
// this window prints once.
|
||||
private const long AutoDedupeMs = 1500;
|
||||
private int _itemInfoLastAutoId;
|
||||
private long _itemInfoLastAutoAt;
|
||||
|
||||
// Click trigger. A press counts as a click only if it started outside every overlay window,
|
||||
// was released within ClickMaxHoldMs and moved at most ClickMaxMovePx — so item drags and
|
||||
// right-button mouse-look never print. The client updates the selection after it handles
|
||||
// the click, so the selection is read ClickSettleMs after the release, on the tick thread.
|
||||
private const long ClickMaxHoldMs = 600;
|
||||
private const float ClickMaxMovePx = 6f;
|
||||
private const long ClickSettleMs = 150;
|
||||
private bool _iiClickPrevDown;
|
||||
private bool _iiClickArmed;
|
||||
private long _iiClickPressAt;
|
||||
private Vector2 _iiClickPressPos;
|
||||
private long _iiClickResolveAt; // TickCount64 to read the selection at; 0 = none (Interlocked)
|
||||
|
||||
/// <summary>Character settings when loaded, else null (commands then use defaults / refuse edits).</summary>
|
||||
private MagItemInfoSettings? ItemInfoSettings => _dashboard?.Settings.ItemInfoSettings;
|
||||
|
||||
private void HandleItemInfoCommand(string[] parts)
|
||||
{
|
||||
var s = ItemInfoSettings;
|
||||
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
|
||||
string arg3 = parts.Length >= 4 ? parts[3] : string.Empty;
|
||||
string arg4 = parts.Length >= 5 ? parts[4] : string.Empty;
|
||||
|
||||
if (sub.Length == 0)
|
||||
{
|
||||
PrintSelectedItemInfo();
|
||||
return;
|
||||
}
|
||||
if (s == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
|
||||
|
||||
switch (sub)
|
||||
{
|
||||
case "settings":
|
||||
case "gui":
|
||||
case "window":
|
||||
s.ShowWindow = !s.ShowWindow;
|
||||
ChatLine($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}.");
|
||||
return;
|
||||
|
||||
case "value":
|
||||
if (ParseOnOff(arg3) is bool v) s.ShowValueAndBurden = v;
|
||||
ChatLine($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}");
|
||||
return;
|
||||
|
||||
case "verbose":
|
||||
if (ParseOnOff(arg3) is bool all)
|
||||
s.SpellMode = all ? MagItemInfoSettings.SpellModeAll : MagItemInfoSettings.SpellModeMag;
|
||||
ChatLine($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}");
|
||||
return;
|
||||
|
||||
case "field":
|
||||
if (!MagItemInfoCatalog.TryFindField(arg3, out MagItemInfoField field))
|
||||
{
|
||||
ChatLine($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them.");
|
||||
return;
|
||||
}
|
||||
if (ParseOnOff(arg4) is bool fieldOn) s.SetHidden(field, !fieldOn);
|
||||
ChatLine($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}");
|
||||
return;
|
||||
|
||||
case "rating":
|
||||
int r = MagItemInfoCatalog.FindRating(arg3);
|
||||
if (r < 0)
|
||||
{
|
||||
ChatLine($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them.");
|
||||
return;
|
||||
}
|
||||
if (ParseOnOff(arg4) is bool ratingOn) s.SetRatingHidden(r, !ratingOn);
|
||||
var rating = MagItemInfoCatalog.Ratings[r];
|
||||
ChatLine($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}");
|
||||
return;
|
||||
|
||||
case "fields":
|
||||
ListItemInfoFields(s);
|
||||
return;
|
||||
|
||||
case "click":
|
||||
switch (arg3.ToLowerInvariant())
|
||||
{
|
||||
case "left": case "l": s.ClickTrigger = MagItemInfoSettings.ClickLeft; break;
|
||||
case "right": case "r": s.ClickTrigger = MagItemInfoSettings.ClickRight; break;
|
||||
case "off": case "none": s.ClickTrigger = MagItemInfoSettings.ClickOff; break;
|
||||
case "": break;
|
||||
default:
|
||||
ChatLine("[RynthAi] Usage: /ra iteminfo click left|right|off");
|
||||
return;
|
||||
}
|
||||
ChatLine($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}");
|
||||
return;
|
||||
|
||||
case "layout":
|
||||
switch (arg3.ToLowerInvariant())
|
||||
{
|
||||
case "pet": case "pets": case "lines": s.Layout = MagItemInfoSettings.LayoutPetLines; break;
|
||||
case "line": case "mag": case "one": s.Layout = MagItemInfoSettings.LayoutOneLine; break;
|
||||
case "": break;
|
||||
default:
|
||||
ChatLine("[RynthAi] Usage: /ra iteminfo layout pet|line");
|
||||
return;
|
||||
}
|
||||
ChatLine($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}");
|
||||
return;
|
||||
|
||||
case "reset":
|
||||
s.ResetToDefaults();
|
||||
ChatLine("[RynthAi] Item info settings reset to defaults.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ParseOnOff(sub) is bool onSelect)
|
||||
{
|
||||
s.OnSelect = onSelect;
|
||||
ChatLine($"[RynthAi] Item info on select: {OnOff(onSelect)}");
|
||||
return;
|
||||
}
|
||||
ChatLine("[RynthAi] Usage: /ra iteminfo [on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
|
||||
}
|
||||
|
||||
private static string OnOff(bool on) => on ? "ON" : "OFF";
|
||||
|
||||
/// <summary>"/ra iteminfo fields" — current state of every field and rating.</summary>
|
||||
private void ListItemInfoFields(MagItemInfoSettings s)
|
||||
{
|
||||
var sb = new StringBuilder("[RynthAi] Fields: ");
|
||||
bool first = true;
|
||||
foreach (var f in MagItemInfoCatalog.Fields)
|
||||
{
|
||||
if (!first) sb.Append(", ");
|
||||
sb.Append(f.Field).Append(s.IsHidden(f.Field) ? " off" : " on");
|
||||
first = false;
|
||||
}
|
||||
ChatLine(sb.ToString());
|
||||
|
||||
sb.Clear().Append("[RynthAi] Ratings: ");
|
||||
var ratings = MagItemInfoCatalog.Ratings;
|
||||
for (int i = 0; i < ratings.Length; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(", ");
|
||||
sb.Append(ratings[i].Tag).Append(s.IsRatingHidden(i) ? " off" : " on");
|
||||
}
|
||||
ChatLine(sb.ToString());
|
||||
}
|
||||
|
||||
/// <summary>/ra iteminfo and the window's "Print to chat" button.</summary>
|
||||
private void PrintSelectedItemInfo()
|
||||
{
|
||||
if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; }
|
||||
uint selected = Host.GetSelectedItemId();
|
||||
if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; }
|
||||
QueueItemInfo(unchecked((int)selected), requestId: true);
|
||||
}
|
||||
|
||||
/// <summary>On-select class filters from the Item Info window.</summary>
|
||||
private static bool ItemInfoWantsClass(MagItemInfoSettings s, AcObjectClass cls) => cls switch
|
||||
{
|
||||
AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb => s.OnSelectWeapons,
|
||||
AcObjectClass.Armor or AcObjectClass.Clothing => s.OnSelectArmor,
|
||||
AcObjectClass.Jewelry => s.OnSelectJewelry,
|
||||
_ => s.OnSelectOther,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describe <paramref name="itemId"/> now if its appraisal is cached, otherwise (optionally)
|
||||
/// request an ID and print from <see cref="TickItemInfo"/> once it lands or times out.
|
||||
/// </summary>
|
||||
internal void QueueItemInfo(int itemId, bool requestId)
|
||||
{
|
||||
if (itemId == 0) return;
|
||||
uint uid = unchecked((uint)itemId);
|
||||
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(uid))
|
||||
{
|
||||
_itemInfoPendingId = 0;
|
||||
PrintItemInfo(itemId, identified: true);
|
||||
return;
|
||||
}
|
||||
if (requestId && Host.HasRequestId) Host.RequestId(uid);
|
||||
_itemInfoPendingId = itemId;
|
||||
_itemInfoPendingSince = Environment.TickCount64;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select / click triggers: <see cref="QueueItemInfo"/> unless the same item was queued
|
||||
/// automatically within <see cref="AutoDedupeMs"/> (one click can raise both triggers).
|
||||
/// </summary>
|
||||
internal void QueueAutoItemInfo(int itemId, bool requestId)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) return;
|
||||
_itemInfoLastAutoId = itemId;
|
||||
_itemInfoLastAutoAt = now;
|
||||
QueueItemInfo(itemId, requestId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Render-thread click watcher (OnRender / OnRenderOverlay, ImGui context current). The ImGui
|
||||
/// backend sees every mouse message on the game window, including the ones the game handles,
|
||||
/// so the raw button state is edge-detected here; the selection is resolved in
|
||||
/// <see cref="TickItemInfo"/>.
|
||||
/// </summary>
|
||||
private void DetectItemInfoClick()
|
||||
{
|
||||
int trigger = ItemInfoSettings?.ClickTrigger ?? MagItemInfoSettings.ClickOff;
|
||||
int button = trigger switch
|
||||
{
|
||||
MagItemInfoSettings.ClickLeft => 0,
|
||||
MagItemInfoSettings.ClickRight => 1,
|
||||
_ => -1,
|
||||
};
|
||||
if (button < 0)
|
||||
{
|
||||
_iiClickPrevDown = false;
|
||||
_iiClickArmed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
bool down = io.MouseDown[button];
|
||||
long now = Environment.TickCount64;
|
||||
|
||||
if (down && !_iiClickPrevDown)
|
||||
{
|
||||
// A press on an overlay window belongs to the overlay, not to an item in the game.
|
||||
_iiClickArmed = !io.WantCaptureMouse;
|
||||
_iiClickPressAt = now;
|
||||
_iiClickPressPos = io.MousePos;
|
||||
}
|
||||
else if (down && _iiClickArmed)
|
||||
{
|
||||
bool held = now - _iiClickPressAt > ClickMaxHoldMs;
|
||||
bool moved = Vector2.DistanceSquared(io.MousePos, _iiClickPressPos) > ClickMaxMovePx * ClickMaxMovePx;
|
||||
if (held || moved) _iiClickArmed = false; // drag or mouse-look, not a click
|
||||
}
|
||||
else if (!down && _iiClickPrevDown && _iiClickArmed)
|
||||
{
|
||||
_iiClickArmed = false;
|
||||
Interlocked.Exchange(ref _iiClickResolveAt, now + ClickSettleMs);
|
||||
}
|
||||
_iiClickPrevDown = down;
|
||||
}
|
||||
|
||||
/// <summary>Tick-thread half of the click trigger: describe whatever item the click selected.</summary>
|
||||
private void ResolveItemInfoClick()
|
||||
{
|
||||
long at = Interlocked.Read(ref _iiClickResolveAt);
|
||||
if (at == 0 || Environment.TickCount64 < at) return;
|
||||
if (Interlocked.CompareExchange(ref _iiClickResolveAt, 0, at) != at) return;
|
||||
|
||||
var s = ItemInfoSettings;
|
||||
if (s == null || s.ClickTrigger == MagItemInfoSettings.ClickOff || !Host.HasGetSelectedItemId) return;
|
||||
uint selected = Host.GetSelectedItemId();
|
||||
if (selected == 0) return;
|
||||
|
||||
int id = unchecked((int)selected);
|
||||
WorldObject? obj = _objectCache?[id];
|
||||
if (obj == null || !IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) return;
|
||||
QueueAutoItemInfo(id, requestId: true);
|
||||
}
|
||||
|
||||
/// <summary>Plugin-tick poll for a pending describe (no appraisal-arrived event in the SDK).</summary>
|
||||
private void TickItemInfo()
|
||||
{
|
||||
ResolveItemInfoClick();
|
||||
|
||||
int id = _itemInfoPendingId;
|
||||
if (id == 0) return;
|
||||
bool ready = Host.HasAppraisalData(unchecked((uint)id));
|
||||
long timeoutMs = (long)((ItemInfoSettings?.IdTimeoutSec ?? 3f) * 1000f);
|
||||
bool timedOut = Environment.TickCount64 - _itemInfoPendingSince > timeoutMs;
|
||||
if (!ready && !timedOut) return;
|
||||
_itemInfoPendingId = 0;
|
||||
PrintItemInfo(id, identified: ready);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the output lines (no prefix / indent) in the configured layout, or returns null
|
||||
/// with <paramref name="error"/> set. The one-line layout returns a single line.
|
||||
/// </summary>
|
||||
private List<string>? BuildItemInfoLines(int itemId, out string? error)
|
||||
{
|
||||
error = null;
|
||||
WorldObject? wo = _objectCache?[itemId];
|
||||
if (wo == null) { error = $"Item 0x{(uint)itemId:X8} is not in the object cache."; return null; }
|
||||
try
|
||||
{
|
||||
var s = ItemInfoSettings;
|
||||
MagItemDescription d = MagItemDescriber.Build(new CacheItemPropertySource(Host, wo), MagItemInfoOptions.From(s));
|
||||
return (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine
|
||||
? new List<string> { d.ToOneLine() }
|
||||
: d.ToPetLines();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Exception(LogCat.General, ex, $"item info 0x{(uint)itemId:X8}");
|
||||
error = $"Item info failed for {wo.Name}: {ex.Message}";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chat output. Pet-style: line 1 carries the prefix in <see cref="MagItemInfoSettings.ChatType"/>,
|
||||
/// later lines are indented like the pet roster and use <see cref="MagItemInfoSettings.DetailChatType"/>.
|
||||
/// </summary>
|
||||
private void PrintItemInfo(int itemId, bool identified)
|
||||
{
|
||||
List<string>? lines = BuildItemInfoLines(itemId, out string? error);
|
||||
if (lines == null || lines.Count == 0) { ChatLine("[RynthAi] " + error); return; }
|
||||
if (!identified) lines[0] += " (not identified — stats may be incomplete)";
|
||||
|
||||
var s = ItemInfoSettings;
|
||||
string prefix = s?.Prefix ?? "[RynthAi] ";
|
||||
int headerType = s?.ChatType ?? 1;
|
||||
int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType;
|
||||
|
||||
Host.WriteToChat(prefix + lines[0], headerType);
|
||||
for (int i = 1; i < lines.Count; i++)
|
||||
Host.WriteToChat(prefix + " " + lines[i], detailType);
|
||||
}
|
||||
|
||||
/// <summary>Item Info window preview: the selected item's lines, or null when nothing is selected.</summary>
|
||||
private string? DescribeSelectedItemForPreview()
|
||||
{
|
||||
if (!Host.HasGetSelectedItemId) return null;
|
||||
uint selected = Host.GetSelectedItemId();
|
||||
if (selected == 0) return null;
|
||||
int id = unchecked((int)selected);
|
||||
List<string>? lines = BuildItemInfoLines(id, out string? error);
|
||||
if (lines == null || lines.Count == 0) return error;
|
||||
if (Host.HasHasAppraisalData && !Host.HasAppraisalData(selected))
|
||||
lines[0] += " (not identified yet — Print to chat IDs it)";
|
||||
// The window adds the prefix to the first line; indent the rest like chat.
|
||||
return string.Join("\n ", lines);
|
||||
}
|
||||
|
||||
/// <summary>Item Info window "Test" button: sample line in the chosen chat type.</summary>
|
||||
private void TestItemInfoChatType(int chatType)
|
||||
{
|
||||
string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi] ";
|
||||
Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType);
|
||||
}
|
||||
}
|
||||
323
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs
Normal file
323
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Out of the acid at once. A hotspot (an acid or lava pool, ACE's Hotspot) hurts every couple of
|
||||
/// seconds while you stand in it and says so: "You suffer 32 damage from acid!". On 2026-10-07
|
||||
/// Drakkon died twice that way in an hour: the patrol (once after a reload, once after a fight)
|
||||
/// left him in a pool the hazard list didn't know, and topping up with healing kits held him there
|
||||
/// - every kit stopped him, the acid matched each kit, and the kits ran his stamina out.
|
||||
///
|
||||
/// Now the first hotspot hit, while the macro runs, stops everything (combat, buffs, healing,
|
||||
/// looting, the route, the meta: OnTick returns here, like the death hold) and walks the character
|
||||
/// back out along its own footsteps (the positions it just came through, so a path it could walk)
|
||||
/// to where it stood just before the hit. It hands back once it got there and no hit came
|
||||
/// for HazardQuietMs. A dungeon cell it was hurt in is a hazard from then on (persisted), so the
|
||||
/// patrol reroutes around it now and on later visits.
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The escape clock (ms); host tests replace it.</summary>
|
||||
internal static Func<long> HazardClock = static () => Environment.TickCount64;
|
||||
|
||||
/// <summary>No hit for this long = out of it (hotspots hit about every 2.5-3.5 s).</summary>
|
||||
internal const long HazardQuietMs = 4000;
|
||||
/// <summary>An escape that hasn't got out by then gives the tick back (and says so).</summary>
|
||||
internal const long HazardEscapeMaxMs = 20000;
|
||||
private const long HazardTrailSampleMs = 250;
|
||||
private const int HazardTrailSize = 80; // 20 s of positions
|
||||
private const double HazardArriveMeters = 0.6;
|
||||
/// <summary>A footstep on the way counts as passed this close (the target needs HazardArriveMeters).</summary>
|
||||
private const double HazardStepMeters = 1.0;
|
||||
private const double HazardMinBackMeters = 2.5;
|
||||
/// <summary>A trail point this long before the first hit is taken as outside the pool.</summary>
|
||||
private const long HazardBeforeHitMs = 750;
|
||||
|
||||
private static readonly Regex HotspotDamageRx = new(
|
||||
@"^You suffer (\d+) (?:points of )?damage from (?:the )?([A-Za-z][A-Za-z ]*?)[.!]*$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly (long At, uint Cell, float X, float Y)[] _hazardTrail = new (long, uint, float, float)[HazardTrailSize];
|
||||
private int _hazardTrailHead;
|
||||
private int _hazardTrailCount;
|
||||
private long _hazardTrailLastAt;
|
||||
|
||||
private long _hazardLastHitAt;
|
||||
private long _hazardFirstHitAt;
|
||||
private long _hazardEscapeSince; // 0 = not escaping
|
||||
private long _hazardArrivedAt; // 0 = still running to the target
|
||||
private bool _hazardHasTarget;
|
||||
private uint _hazardTargetCell;
|
||||
private float _hazardTargetX, _hazardTargetY;
|
||||
private long _hazardTargetAt; // the trail time of the target (older = further back)
|
||||
/// <summary>The footsteps back to the target, newest first; the last one is the target.</summary>
|
||||
private readonly System.Collections.Generic.List<(uint Cell, float X, float Y)> _hazardPath = new();
|
||||
private int _hazardPathIdx;
|
||||
private bool _hazardRunning;
|
||||
private long _hazardRunBeatAt;
|
||||
private string _hazardSource = "";
|
||||
|
||||
/// <summary>True while the escape owns the character.</summary>
|
||||
internal bool HazardEscaping => _hazardEscapeSince != 0;
|
||||
|
||||
/// <summary>"You suffer 32 damage from acid!" -> 32, "acid". Broadcast text only.</summary>
|
||||
internal static bool TryParseHotspotDamage(string? text, out int amount, out string source)
|
||||
{
|
||||
amount = 0;
|
||||
source = "";
|
||||
if (string.IsNullOrEmpty(text)) return false;
|
||||
Match m = HotspotDamageRx.Match(text.Trim());
|
||||
if (!m.Success || !int.TryParse(m.Groups[1].Value, out amount)) return false;
|
||||
source = m.Groups[2].Value.Trim().ToLowerInvariant();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Chat hook: a hotspot hit starts (or pushes on) the escape.</summary>
|
||||
internal void NoteHotspotChat(string? text, int chatType)
|
||||
{
|
||||
if (chatType != 0 || !TryParseHotspotDamage(text, out int amount, out string source)) return;
|
||||
// Off (Escape Acid and Lava): neither the escape nor the learning - a character that walks
|
||||
// through acid on purpose doesn't want the patrol rerouted around it either.
|
||||
if (_dashboard?.Settings is { EscapeHazards: false }) return;
|
||||
long now = HazardClock();
|
||||
bool fresh = _hazardLastHitAt == 0 || now - _hazardLastHitAt > HazardQuietMs;
|
||||
if (fresh) _hazardFirstHitAt = now;
|
||||
_hazardLastHitAt = now;
|
||||
_hazardSource = source;
|
||||
|
||||
if (Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _))
|
||||
_objectCache?.RegisterDamageHazardCell(cell, source);
|
||||
|
||||
if (_dashboard?.Settings is not { IsMacroRunning: true }) return;
|
||||
if (!HazardEscaping)
|
||||
{
|
||||
StartHazardEscape(now, amount);
|
||||
return;
|
||||
}
|
||||
// Got to the target and still hurt: the pool reaches further back. Go further.
|
||||
if (_hazardArrivedAt != 0 || !_hazardHasTarget)
|
||||
{
|
||||
_hazardArrivedAt = 0;
|
||||
if (!PickHazardTarget(now, olderThan: _hazardHasTarget ? _hazardTargetAt : _hazardFirstHitAt - HazardBeforeHitMs + 1))
|
||||
Log("[RynthAi] Hazard: still taking damage and no older spot to run back to; running on.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every tick: where the character stood (not while escaping, nor dead).</summary>
|
||||
internal void RecordHazardTrail()
|
||||
{
|
||||
if (HazardEscaping) return;
|
||||
long now = HazardClock();
|
||||
if (now - _hazardTrailLastAt < HazardTrailSampleMs) return;
|
||||
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0)
|
||||
return;
|
||||
_hazardTrailLastAt = now;
|
||||
_hazardTrail[_hazardTrailHead] = (now, cell, x, y);
|
||||
_hazardTrailHead = (_hazardTrailHead + 1) % HazardTrailSize;
|
||||
if (_hazardTrailCount < HazardTrailSize) _hazardTrailCount++;
|
||||
}
|
||||
|
||||
private void StartHazardEscape(long now, int amount)
|
||||
{
|
||||
_hazardEscapeSince = now;
|
||||
_hazardArrivedAt = 0;
|
||||
_hazardRunning = false;
|
||||
PickHazardTarget(now, olderThan: _hazardFirstHitAt - HazardBeforeHitMs + 1);
|
||||
Log($"[RynthAi] Hazard: took {amount} {_hazardSource} damage - stopping everything and moving out"
|
||||
+ (_hazardHasTarget ? $" (back to ({_hazardTargetX:0.0}, {_hazardTargetY:0.0}))." : " (no earlier spot known: running back the way it faces)."));
|
||||
try { Host.WriteToChat($"[RynthAi] Standing in {_hazardSource} - stopping everything to move out.", 1); } catch { }
|
||||
|
||||
try { if (Host.HasCancelAttack) Host.CancelAttack(); } catch { }
|
||||
_combatManager?.ReleaseHeldTurn();
|
||||
_navigationEngine?.Stop();
|
||||
try { StopCorpseMovement(); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The newest trail point older than <paramref name="olderThan"/>, in this landblock, at least
|
||||
/// HazardMinBackMeters away, preferring one outside a known hazard cell. False = none; then
|
||||
/// the escape runs straight back from where it faces.
|
||||
/// </summary>
|
||||
private bool PickHazardTarget(long now, long olderThan)
|
||||
{
|
||||
_hazardHasTarget = false;
|
||||
if (!Host.TryGetPlayerPose(out uint cell, out float px, out float py, out _, out float qw, out _, out _, out float qz))
|
||||
return false;
|
||||
|
||||
int fallback = -1;
|
||||
for (int k = 1; k <= _hazardTrailCount; k++)
|
||||
{
|
||||
int i = (_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize;
|
||||
var p = _hazardTrail[i];
|
||||
if (p.At >= olderThan || (p.Cell >> 16) != (cell >> 16)) continue;
|
||||
double d = Math.Sqrt((p.X - px) * (p.X - px) + (p.Y - py) * (p.Y - py));
|
||||
if (d < HazardMinBackMeters) continue;
|
||||
if (_objectCache?.IsHazardCell(p.Cell) == true)
|
||||
{
|
||||
if (fallback < 0) fallback = i;
|
||||
continue;
|
||||
}
|
||||
SetHazardTarget(p);
|
||||
return true;
|
||||
}
|
||||
if (fallback >= 0)
|
||||
{
|
||||
SetHazardTarget(_hazardTrail[fallback]);
|
||||
return true;
|
||||
}
|
||||
|
||||
// No trail (fresh login, or it all lies in the pool): 4 m straight back from the facing.
|
||||
double yawDeg = ((-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI)) % 360.0 + 720.0) % 360.0;
|
||||
double back = (yawDeg + 180.0) * Math.PI / 180.0;
|
||||
SetHazardTarget((olderThan - 1, cell, (float)(px + 4.0 * Math.Sin(back)), (float)(py + 4.0 * Math.Cos(back))));
|
||||
return false;
|
||||
}
|
||||
|
||||
private void SetHazardTarget((long At, uint Cell, float X, float Y) p)
|
||||
{
|
||||
_hazardHasTarget = true;
|
||||
_hazardTargetAt = p.At;
|
||||
_hazardTargetCell = p.Cell;
|
||||
_hazardTargetX = p.X;
|
||||
_hazardTargetY = p.Y;
|
||||
|
||||
// The footsteps from now back to the target, newest first, thinned to about 1 m apart:
|
||||
// the way it came in is a way it can walk out (no straight line through a wall).
|
||||
_hazardPath.Clear();
|
||||
_hazardPathIdx = 0;
|
||||
float lx = float.NaN, ly = float.NaN;
|
||||
for (int k = 1; k <= _hazardTrailCount; k++)
|
||||
{
|
||||
var t = _hazardTrail[(_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize];
|
||||
if (t.At <= p.At) break;
|
||||
if ((t.Cell >> 16) != (p.Cell >> 16)) continue;
|
||||
if (!float.IsNaN(lx) && (t.X - lx) * (t.X - lx) + (t.Y - ly) * (t.Y - ly) < 1.0f) continue;
|
||||
_hazardPath.Add((t.Cell, t.X, t.Y));
|
||||
lx = t.X; ly = t.Y;
|
||||
}
|
||||
_hazardPath.Add((p.Cell, p.X, p.Y));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called in OnTick right after the death hold. True = the escape owns this tick: nothing else
|
||||
/// runs (no buffs, healing kits, combat, looting, route or meta).
|
||||
/// </summary>
|
||||
internal bool HoldForHazardEscape()
|
||||
{
|
||||
if (!HazardEscaping) return false;
|
||||
long now = HazardClock();
|
||||
|
||||
if (_dashboard?.Settings is { EscapeHazards: false })
|
||||
{
|
||||
EndHazardEscape("Escape Acid and Lava was turned off");
|
||||
return false;
|
||||
}
|
||||
if (_dashboard?.Settings is not { IsMacroRunning: true })
|
||||
{
|
||||
EndHazardEscape("the macro was stopped");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Died, recalled or portalled meanwhile: the target is somewhere else now.
|
||||
if (_hazardHasTarget && Host.TryGetPlayerPose(out uint cellNow, out _, out _, out _, out _, out _, out _, out _)
|
||||
&& (cellNow >> 16) != (_hazardTargetCell >> 16))
|
||||
{
|
||||
EndHazardEscape("left the area");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool quiet = now - _hazardLastHitAt >= HazardQuietMs;
|
||||
if (now - _hazardEscapeSince > HazardEscapeMaxMs && quiet)
|
||||
{
|
||||
EndHazardEscape("no hit for a while");
|
||||
return false;
|
||||
}
|
||||
if (now - _hazardEscapeSince > HazardEscapeMaxMs * 2)
|
||||
{
|
||||
EndHazardEscape($"still hurt after {HazardEscapeMaxMs * 2 / 1000} s - giving the tick back");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_hazardArrivedAt == 0 && _hazardHasTarget)
|
||||
RunToHazardTarget(now);
|
||||
if (_hazardArrivedAt != 0 && quiet)
|
||||
{
|
||||
EndHazardEscape("out of it");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void RunToHazardTarget(long now)
|
||||
{
|
||||
if (!Host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _))
|
||||
return;
|
||||
// Skip to just past the furthest footstep already reached (it may have been carried
|
||||
// along, or started near the end); the last one is the target.
|
||||
for (int j = _hazardPath.Count - 1; j >= _hazardPathIdx; j--)
|
||||
{
|
||||
var r = _hazardPath[j];
|
||||
double rd = Math.Sqrt((r.X - px) * (r.X - px) + (r.Y - py) * (r.Y - py));
|
||||
if (rd <= (j == _hazardPath.Count - 1 ? HazardArriveMeters : HazardStepMeters))
|
||||
{
|
||||
_hazardPathIdx = j + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
double dx = 0, dy = 0;
|
||||
if (_hazardPathIdx < _hazardPath.Count)
|
||||
{
|
||||
var w = _hazardPath[_hazardPathIdx];
|
||||
dx = w.X - px; dy = w.Y - py;
|
||||
}
|
||||
if (_hazardPathIdx >= _hazardPath.Count)
|
||||
{
|
||||
_hazardArrivedAt = now;
|
||||
StopHazardRun();
|
||||
return;
|
||||
}
|
||||
double desired = Math.Atan2(dx, dy) * (180.0 / Math.PI);
|
||||
if (desired < 0) desired += 360.0;
|
||||
bool aligned = _navigationEngine?.ServoToward(desired) ?? TurnDirect(desired);
|
||||
if (!aligned)
|
||||
{
|
||||
if (_hazardRunning) StopHazardRun();
|
||||
return;
|
||||
}
|
||||
if (!_hazardRunning || now - _hazardRunBeatAt >= 500)
|
||||
{
|
||||
Host.SetAutoRunBy("Hazard", true);
|
||||
_hazardRunning = true;
|
||||
_hazardRunBeatAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TurnDirect(double desired)
|
||||
{
|
||||
if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Hazard", (float)desired);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void StopHazardRun()
|
||||
{
|
||||
if (!_hazardRunning) return;
|
||||
_hazardRunning = false;
|
||||
Host.SetAutoRunBy("Hazard", false);
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Hazard");
|
||||
}
|
||||
|
||||
private void EndHazardEscape(string why)
|
||||
{
|
||||
StopHazardRun();
|
||||
Log($"[RynthAi] Hazard: {why} after {(HazardClock() - _hazardEscapeSince) / 1000.0:0.0} s - resuming.");
|
||||
_hazardEscapeSince = 0;
|
||||
_hazardArrivedAt = 0;
|
||||
_hazardHasTarget = false;
|
||||
_hazardPath.Clear();
|
||||
_hazardTrailCount = 0; // the old trail runs through the pool
|
||||
_navigationEngine?.ResumeFromNearestWaypoint();
|
||||
}
|
||||
}
|
||||
189
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs
Normal file
189
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// /ra iteminfo [name]: a selected (or named) item's details on one chat line, Mag-Tools
|
||||
/// style (ItemInfo/ItemInfoText). An item the client hasn't appraised is identified first
|
||||
/// and printed when the appraisal arrives, or after <see cref="ItemInfoTimeoutMs"/> with
|
||||
/// what the client has. Partial class of RynthAiPlugin.
|
||||
///
|
||||
/// Threads: the command only queues its argument; <see cref="TickItemInfo"/> on the plugin
|
||||
/// tick does every host read, the ID request and the print. Nothing is drawn.
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const long ItemInfoTimeoutMs = 5000;
|
||||
|
||||
/// <summary>Test seam: the clock the ID timeout runs on.</summary>
|
||||
internal static Func<long> ItemInfoClock = () => Environment.TickCount64;
|
||||
|
||||
private readonly ConcurrentQueue<string> _itemInfoRequests = new();
|
||||
// One item waiting for its appraisal at a time (tick thread only); a newer request replaces it.
|
||||
private uint _itemInfoPendingId;
|
||||
private long _itemInfoDeadline;
|
||||
|
||||
/// <summary>/ra iteminfo [item name]. Queued for the next tick.</summary>
|
||||
private void HandleItemInfoCommand(string[] parts)
|
||||
{
|
||||
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
|
||||
if (arg.Equals("help", StringComparison.OrdinalIgnoreCase) || arg == "?")
|
||||
{
|
||||
ChatLine("[RynthAi] /ra iteminfo - the selected item's details (identifies it first when needed).");
|
||||
ChatLine("[RynthAi] /ra iteminfo <name> - the first item in your inventory with that name (else one whose name contains it).");
|
||||
return;
|
||||
}
|
||||
if (_itemInfoRequests.Count < 8) _itemInfoRequests.Enqueue(arg);
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: starts queued requests, prints an item once its ID lands or times out.</summary>
|
||||
private void TickItemInfo()
|
||||
{
|
||||
while (_itemInfoRequests.TryDequeue(out string? arg))
|
||||
StartItemInfo(arg);
|
||||
|
||||
uint selected = System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, 0);
|
||||
if (selected != 0)
|
||||
StartItemInfoFor(selected, quiet: true);
|
||||
|
||||
uint pending = _itemInfoPendingId;
|
||||
if (pending == 0) return;
|
||||
bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(pending);
|
||||
if (appraised || ItemInfoClock() >= _itemInfoDeadline)
|
||||
{
|
||||
_itemInfoPendingId = 0;
|
||||
PrintItemInfo(pending, identified: appraised);
|
||||
}
|
||||
}
|
||||
|
||||
private void StartItemInfo(string arg)
|
||||
{
|
||||
uint id;
|
||||
if (arg.Length == 0)
|
||||
{
|
||||
id = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
if (id == 0)
|
||||
{
|
||||
ChatLine("[RynthAi] Item info: nothing selected. Select an item, or /ra iteminfo <name>.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
id = FindInventoryItemByName(arg);
|
||||
if (id == 0)
|
||||
{
|
||||
ChatLine($"[RynthAi] Item info: no \"{arg}\" in your inventory.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
StartItemInfoFor(id, quiet: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prints <paramref name="id"/> now when it's appraised, else asks for its ID and prints when
|
||||
/// it lands. <paramref name="quiet"/> (Item Info On Select): no "identifying" chatter.
|
||||
/// </summary>
|
||||
private void StartItemInfoFor(uint id, bool quiet)
|
||||
{
|
||||
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(id))
|
||||
{
|
||||
if (_itemInfoPendingId == id) _itemInfoPendingId = 0;
|
||||
PrintItemInfo(id, identified: true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!quiet && _itemInfoPendingId != 0 && _itemInfoPendingId != id)
|
||||
ChatLine($"[RynthAi] Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}.");
|
||||
if (Host.HasRequestId) Host.RequestId(id);
|
||||
_itemInfoPendingId = id;
|
||||
_itemInfoDeadline = ItemInfoClock() + ItemInfoTimeoutMs;
|
||||
if (!quiet) ChatLine($"[RynthAi] Item info: identifying {ObjectNameOr(id)}...");
|
||||
}
|
||||
|
||||
// Item Info On Select: the item the player just selected, for the next tick (0 = none).
|
||||
private uint _itemInfoSelectId;
|
||||
|
||||
/// <summary>
|
||||
/// Selection change (OnSelectedTargetChange): queues Item Info for an item the player
|
||||
/// selected. Skips non-items and RynthAi's own selections (the looter, metas).
|
||||
/// </summary>
|
||||
private void QueueItemInfoOnSelect(uint id, WorldObject? obj)
|
||||
{
|
||||
if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return;
|
||||
if (obj == null || !IsLootableClass(obj.ObjectClass)) return;
|
||||
if (SelfSelect.IsOurs(id)) return;
|
||||
System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An inventory item (carried or worn) whose name is <paramref name="name"/>, ignoring case;
|
||||
/// else the first whose name contains it. 0 when none.
|
||||
/// </summary>
|
||||
private uint FindInventoryItemByName(string name)
|
||||
{
|
||||
if (_objectCache == null) return 0;
|
||||
uint partial = 0;
|
||||
foreach (WorldObject wo in _objectCache.GetInventory())
|
||||
{
|
||||
if (wo.Name.Length == 0) continue;
|
||||
if (wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id);
|
||||
if (partial == 0 && wo.Name.Contains(name, StringComparison.OrdinalIgnoreCase)) partial = unchecked((uint)wo.Id);
|
||||
}
|
||||
return partial;
|
||||
}
|
||||
|
||||
private string ObjectNameOr(uint id) =>
|
||||
Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}";
|
||||
|
||||
private void PrintItemInfo(uint id, bool identified)
|
||||
{
|
||||
var source = new HostItemInfoSource(Host, id);
|
||||
ChatLine("[RynthAi] " + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified));
|
||||
}
|
||||
|
||||
/// <summary>The live appraisal through the host (tick thread).</summary>
|
||||
private sealed class HostItemInfoSource : IItemInfoSource
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly uint _id;
|
||||
|
||||
public HostItemInfoSource(RynthCoreHost host, uint id)
|
||||
{
|
||||
_host = host;
|
||||
_id = id;
|
||||
Name = host.TryGetObjectName(id, out string n) ? n : string.Empty;
|
||||
SpellIds = ReadSpells(host, id);
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public IReadOnlyList<int> SpellIds { get; }
|
||||
|
||||
public bool TryInt(uint key, out int value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, key, out value);
|
||||
}
|
||||
|
||||
public bool TryFloat(uint key, out double value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.TryGetObjectDoubleProperty(_id, key, out value);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<int> ReadSpells(RynthCoreHost host, uint id)
|
||||
{
|
||||
if (!host.HasGetObjectSpellIds) return Array.Empty<int>();
|
||||
var buf = new uint[64];
|
||||
int n = host.GetObjectSpellIds(id, buf, buf.Length);
|
||||
if (n <= 0) return Array.Empty<int>();
|
||||
var list = new List<int>(n);
|
||||
for (int i = 0; i < n && i < buf.Length; i++) list.Add(unchecked((int)buf[i]));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -21,7 +21,6 @@ public sealed partial class RynthAiPlugin
|
|||
private Huds.HudIconCache? _hudIcons;
|
||||
private Translate.ChatTranslator? _translator;
|
||||
private Translate.TranslateUi? _translateUi;
|
||||
private LegacyItemInfoUi? _itemInfoUi;
|
||||
private CreatureData.UbMobSeedStore? _mobSeedStore;
|
||||
|
||||
// One-time overlay diagnostics (render thread only).
|
||||
|
|
@ -117,15 +116,6 @@ public sealed partial class RynthAiPlugin
|
|||
var huds = _huds;
|
||||
_iltHub.MiniRemoteCommand = mode => "[ILT Hub] " + huds.HandleCommand("remote", mode);
|
||||
_iltHub.MiniRemoteVisible = () => huds.MiniRemoteActive;
|
||||
EnsureItemInfoUi();
|
||||
}
|
||||
|
||||
/// <summary>Item Info window, created once settings exist.</summary>
|
||||
private void EnsureItemInfoUi()
|
||||
{
|
||||
if (_dashboard == null || _itemInfoUi != null) return;
|
||||
_itemInfoUi = new LegacyItemInfoUi(_dashboard.Settings);
|
||||
_itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType);
|
||||
}
|
||||
|
||||
/// <summary>Pump-thread work for the ported features. Safe before login (each call is null-checked).</summary>
|
||||
|
|
@ -160,7 +150,6 @@ public sealed partial class RynthAiPlugin
|
|||
try { _huds?.OnLogout(); }
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); }
|
||||
_huds = null;
|
||||
_itemInfoUi = null;
|
||||
ResetGroundLoot(clearCaches: true);
|
||||
if (!disposeTranslator) return;
|
||||
try { _translator?.Dispose(); }
|
||||
|
|
@ -205,9 +194,7 @@ public sealed partial class RynthAiPlugin
|
|||
ImGui.SetCurrentContext(Host.ImGuiContext);
|
||||
try
|
||||
{
|
||||
DetectItemInfoClick();
|
||||
_navOverlay?.Render();
|
||||
_itemInfoUi?.Render();
|
||||
_iltHub?.Render();
|
||||
_huds?.Render();
|
||||
RenderTranslateWindow();
|
||||
|
|
@ -249,14 +236,12 @@ public sealed partial class RynthAiPlugin
|
|||
ImGui.SetCurrentContext(Host.ImGuiContext);
|
||||
try
|
||||
{
|
||||
DetectItemInfoClick();
|
||||
int pushedColors = LegacyDashboardRenderer.PushDashboardStyle();
|
||||
try { _iltHub?.Render(); }
|
||||
finally { ImGui.PopStyleColor(pushedColors); }
|
||||
_huds?.Render();
|
||||
RenderTranslateWindow();
|
||||
_navOverlay?.Render();
|
||||
_itemInfoUi?.Render();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
|
|||
68
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
Normal file
68
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// ============================================================================
|
||||
// RynthAi's side of the action pacing (Plugins/Shared/ActionPacer.cs, 2026-10-06).
|
||||
// Every use / use-on RynthAi sends is recorded as the server action it waits on;
|
||||
// casts and mode changes record themselves (CastSpellFor / ChangeCombatModeFor).
|
||||
// The managers that only see a busy count (inventory, salvage, mana stones, pets)
|
||||
// get PacedBusy: the count, plus one while a server action is unanswered.
|
||||
// ============================================================================
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>UseAudit.AfterSend: a use or use-on went out - record it as the action the server is answering.</summary>
|
||||
private static void RecordUseForPacing(RynthCoreHost host, UseAudit.SentUse use)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The salvage panel (a UST use) opens on the client; the server answered only 7 of 18
|
||||
// of them with a UseDone in the 10-05/10-06 logs, so it is not waited on.
|
||||
if (use.Subsystem == "Salvage" || use.What.Contains("'Ust'", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
PacedKind kind;
|
||||
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
|
||||
if (use.TargetId != 0)
|
||||
{
|
||||
// Something on a target: on yourself (kit, stone, food) it is an item use; on a
|
||||
// door/corpse or anything else in the world the server walks there first.
|
||||
kind = use.TargetId == player
|
||||
? PacedKind.ItemUse
|
||||
: ActionPacer.ClassifyUse(host, use.TargetId, use.DoorOrCorpse);
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = ActionPacer.ClassifyUse(host, use.ObjectId, use.DoorOrCorpse);
|
||||
}
|
||||
string who = "RynthAi/" + use.Subsystem + (use.Kind == UseKind.Asked ? " (asked)" : "");
|
||||
ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The busy count the item managers gate on (inventory, salvage, mana stones, pets): our mirror of
|
||||
/// AC's count, plus one while a server action is unanswered so they don't start one on top of it.
|
||||
/// </summary>
|
||||
private int PacedBusy
|
||||
{
|
||||
get
|
||||
{
|
||||
int busy = _busyCount;
|
||||
if (ActionPacer.Enabled
|
||||
&& (ActionPacer.Current(Host) != null || ActionPacer.GestureHolds(Host, "Items", HealNeed.None, out _)))
|
||||
busy++; // an unanswered server action, or the character still animating (a pack move of a wielded item, a stone, a summon would start on top)
|
||||
return busy;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/ra pace: what the pacing is waiting on, and its counters.</summary>
|
||||
private void HandlePaceCommand()
|
||||
{
|
||||
foreach (string line in ActionPacer.DescribeLines(Host))
|
||||
ChatLine("[RynthAi] " + line);
|
||||
ChatLine($"[RynthAi] Busy mirror {_busyCount} (shadow resets only; the client's count is never force-cleared by RynthAi now)");
|
||||
}
|
||||
}
|
||||
|
|
@ -131,6 +131,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// Give queue — drained one item per tick with a cooldown (interval comes from settings)
|
||||
private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new();
|
||||
private DateTime _lastGiveAt = DateTime.MinValue;
|
||||
// The give the server hasn't answered yet (0 = none): the next one waits for it.
|
||||
private uint _giveInFlightId, _giveInFlightTarget;
|
||||
private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries;
|
||||
private long _giveInFlightAt;
|
||||
private const long GiveConfirmMs = 3000;
|
||||
private const int GiveMaxTries = 2;
|
||||
private RynthCore.Loot.LootProfile? _nativeLootProfile;
|
||||
private string _nativeLootProfilePath = string.Empty;
|
||||
private DateTime _nativeLootProfileTime = DateTime.MinValue;
|
||||
|
|
@ -168,11 +174,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module.
|
||||
ImGuiNativeBinding.Ensure();
|
||||
_dashboard = new LegacyDashboardRenderer(Host);
|
||||
_killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true;
|
||||
_dashboard.KillClock = _killClock;
|
||||
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
|
||||
// each, and no automatic door/corpse use while the macro is off.
|
||||
RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true);
|
||||
// Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs).
|
||||
RynthCore.Plugin.Shared.MoveAudit.Reset();
|
||||
// A door/corpse use the server is still answering holds RynthAi's own moves and turns
|
||||
// (moving would cancel the server's walk/turn to it; 2026-10-06).
|
||||
RynthCore.Plugin.Shared.UseAudit.TrackWorldUses = true;
|
||||
// One server action at a time (Plugins/Shared/ActionPacer.cs, 2026-10-06): every use,
|
||||
// use-on, cast and combat-mode change waits for the server's answer to the last one.
|
||||
RynthCore.Plugin.Shared.ActionPacer.Reset();
|
||||
RynthCore.Plugin.Shared.ActionPacer.Enabled = true;
|
||||
RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing;
|
||||
_objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login
|
||||
// Items we use (or use something on) get re-identified before a meta reads them.
|
||||
// ObjectUsed is a static event and Shutdown never unsubscribes: when the engine
|
||||
|
|
@ -220,6 +236,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_dashboard = null;
|
||||
// Don't let the static audit hold this instance once it's gone (a reused module).
|
||||
RynthCore.Plugin.Shared.UseAudit.MacroOn = static () => false;
|
||||
RynthCore.Plugin.Shared.UseAudit.AfterSend = null;
|
||||
RynthCore.Plugin.Shared.ActionPacer.Enabled = false;
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown");
|
||||
|
||||
// Give the heap back. When a changed RynthAi is deployed, the engine loads
|
||||
// it as a new copy and this one is abandoned for good (a NativeAOT DLL can't
|
||||
|
|
@ -252,6 +271,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
Log("RynthAi: logout — tearing down session.");
|
||||
try { _dashboard?.SaveSettings(); } catch { }
|
||||
Loot.T11ItemSupport.Reset();
|
||||
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
|
||||
ClearInGameMarker();
|
||||
TeardownSession();
|
||||
|
|
@ -352,6 +372,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private void TeardownSession()
|
||||
{
|
||||
ObjectChangeTracker.Clear();
|
||||
// The server drops whatever it was doing for this character at logout.
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("logout");
|
||||
_navigationEngine?.Stop();
|
||||
_navigationEngine = null;
|
||||
// The dungeon cell graph is a static single-landblock cache; nothing may outlive the session.
|
||||
|
|
@ -372,6 +394,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
_combatManager?.Dispose();
|
||||
_combatManager = null;
|
||||
// A relog is what clears a server that refuses every use: start the next session clean.
|
||||
ResetUseRefusalState();
|
||||
Log($"RynthAi: TeardownSession — RadarWallFlush={tFlushMs} ms, RaycastDispose={tRayMs} ms");
|
||||
_fellowshipTracker?.Dispose();
|
||||
_fellowshipTracker = null;
|
||||
|
|
@ -460,10 +484,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_loginCompletedAt = DateTime.Now;
|
||||
_loginComplete = true;
|
||||
_killClock.SessionStarted();
|
||||
_dashboard.OnLoginComplete();
|
||||
_dashboard.ChatSubmitHandler = HandleRynthChatSubmit;
|
||||
EnsureTranslator();
|
||||
EnsureItemInfoUi();
|
||||
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
|
||||
{
|
||||
ChatSubmit = HandleRynthChatSubmit,
|
||||
|
|
@ -578,6 +602,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// other (the collision behind "you can only move or use one item at a
|
||||
// time" and the object-teardown AV).
|
||||
_weaponSwapGate ??= new WeaponSwapGate();
|
||||
// The next swap goes once the server is done with the last one (not a flat 3 s).
|
||||
_weaponSwapGate.ServerIdle = () => RynthCore.Plugin.Shared.ActionPacer.Enabled && RynthCore.Plugin.Shared.ActionPacer.Current(Host) == null;
|
||||
_weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id));
|
||||
|
||||
_buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals);
|
||||
_inGameMarkerSet = false;
|
||||
|
|
@ -618,6 +645,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
|
||||
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
|
||||
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
|
||||
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
|
||||
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
|
||||
if (_buffManager != null)
|
||||
|
|
@ -658,6 +686,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_metaManager.SetQuestTracker(_questTracker);
|
||||
if (_buffManager != null) _metaManager.SetBuffManager(_buffManager);
|
||||
_metaManager.SetCreatureStore(_creatureStore);
|
||||
_metaManager.SetKillClock(_killClock);
|
||||
if (_dashboard != null)
|
||||
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
|
||||
|
||||
|
|
@ -665,6 +694,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
_inventoryManager = new InventoryManager(Host, _dashboard.Settings, _objectCache);
|
||||
_manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache);
|
||||
LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name
|
||||
_manaStoneManager.IsLootKept = IsKeptByLootProfile;
|
||||
_petManager = new PetManager(Host, _dashboard.Settings, _objectCache, _combatManager, _charSkills);
|
||||
_combatManager.SummonOut = () => _petManager?.CurrentSummon();
|
||||
|
|
@ -720,6 +750,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// decides whether nav runs at all. One edge-detect replaces the cascade.
|
||||
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
|
||||
private bool _macroWasRunning; // edge: release held turns when the macro stops
|
||||
|
||||
// Time since our last kill (KillerNotification only): secondssincelastkill[], the
|
||||
// No Kills Within Minutes meta condition and the status feed. Counts from login / plugin
|
||||
// load, then from each macro start, until the first kill.
|
||||
private readonly KillClock _killClock = new();
|
||||
internal KillClock Kills => _killClock;
|
||||
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
|
||||
private bool _navStopIssued;
|
||||
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
|
||||
|
|
@ -755,8 +791,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_navStopIssued = true;
|
||||
_navStoppedFor = owner;
|
||||
|
||||
bool ownMovement = RynthCore.Plugin.Shared.MoveAudit.OwnMovementActive; // before nav's own stops clear it
|
||||
_navigationEngine?.Stop();
|
||||
if (Host.HasStopCompletely)
|
||||
// A StopCompletely only when RynthAi itself has the character moving (2026-10-06): with
|
||||
// nothing of ours moving it is one more movement packet on the server's motion - 116 in 46
|
||||
// minutes on 10-06, on every change of activity - and it cut off movement another plugin
|
||||
// (RynthNav, RynthLua) had just started (analysis by Silentkelpie). RynthNav's travel is
|
||||
// stopped by its own command (TickOwnCorpseTravel). Without the pacing, as before.
|
||||
if (Host.HasStopCompletely
|
||||
&& (!RynthCore.Plugin.Shared.ActionPacer.Enabled || ownMovement))
|
||||
Host.StopCompletelyBy("Arbiter");
|
||||
|
||||
// Combat taking the tick invalidates any in-progress door interaction.
|
||||
|
|
@ -867,9 +910,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
break;
|
||||
case "trace":
|
||||
case "logs":
|
||||
case "iteminfo":
|
||||
// Settings panel buttons (Diagnostics tab, Item Info options); value carries the
|
||||
// same arguments as "/ra trace|logs|iteminfo ...".
|
||||
// Settings panel buttons (Diagnostics tab); value carries the same arguments as
|
||||
// "/ra trace|logs ...".
|
||||
{
|
||||
var args = new List<string> { "/ra", action.ToLowerInvariant() };
|
||||
args.AddRange(value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
|
|
@ -878,7 +920,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
case "trace": HandleTraceCommand(parts); break;
|
||||
case "logs": HandleLogsCommand(parts); break;
|
||||
case "iteminfo": HandleItemInfoCommand(parts); break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
|
@ -905,19 +946,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
|
||||
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
|
||||
["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100),
|
||||
["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
|
||||
["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100),
|
||||
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
|
||||
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
|
||||
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
|
||||
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
|
||||
["PetMinMonsters"] = (1, 20),
|
||||
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (250, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100),
|
||||
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
|
||||
["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500),
|
||||
["MinSkillLevelTier5"] = (1, 500), ["MinSkillLevelTier6"] = (1, 500), ["MinSkillLevelTier7"] = (1, 500), ["MinSkillLevelTier8"] = (1, 500),
|
||||
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
|
||||
["CorpseApproachRangeMax"] = (0.5, 50), ["CorpseApproachRangeMin"] = (0.5, 20),
|
||||
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
|
||||
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
|
||||
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["NavLabelMode"] = (0, 2), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
|
||||
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
|
||||
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
|
||||
["NavOffTrackYards"] = (160, 1000), ["NavMaxDetourAttempts"] = (1, 10),
|
||||
|
|
@ -1435,11 +1476,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// to run only inside the legacy dashboard's Render(), which the engine no
|
||||
// longer calls, so edits waited for the next login. A flag check when idle.
|
||||
_dashboard?.TickMonsterReload();
|
||||
// A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it.
|
||||
_dashboard?.TickNavFolder();
|
||||
_questTracker?.Tick();
|
||||
TickLocalFeatures();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
|
||||
DrainGiveQueue();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
|
||||
if (_loginComplete) TickItemInfo();
|
||||
Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1);
|
||||
_jumper?.Tick();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
|
||||
|
||||
|
|
@ -1513,6 +1558,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// finally below still submits the nav markers.
|
||||
if (HoldForDeath())
|
||||
return;
|
||||
// Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs).
|
||||
RecordHazardTrail();
|
||||
if (HoldForHazardEscape())
|
||||
return;
|
||||
|
||||
if (diag) Host.Log("[RynthAi] OnTick: before CheckBusyTimeout");
|
||||
CheckBusyTimeout();
|
||||
|
|
@ -1565,6 +1614,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (!_macroWasRunning && settings.IsMacroRunning)
|
||||
_navigationEngine?.ResumeFromNearestWaypoint();
|
||||
_macroWasRunning = settings.IsMacroRunning;
|
||||
_killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile
|
||||
|
||||
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
|
||||
{
|
||||
|
|
@ -1667,6 +1717,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_combatEndedAt = nowMs;
|
||||
|
||||
bool wantLoot = HasLootWork(settings, nowMs);
|
||||
_lastWantLoot = wantLoot;
|
||||
bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy;
|
||||
bool routeLoaded = settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0;
|
||||
|
||||
|
|
@ -1813,7 +1864,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
&& _openedContainerId == 0
|
||||
&& _targetCorpseId == 0)
|
||||
{
|
||||
_inventoryManager.OnHeartbeat(_busyCount);
|
||||
_inventoryManager.OnHeartbeat(PacedBusy);
|
||||
}
|
||||
|
||||
// Status feed: main-pack empty slots (cache-based, off-thread-safe). Throttled to
|
||||
|
|
@ -1886,7 +1937,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// combine work while a threat is up so it doesn't contend with
|
||||
// combat over SelectItem; it resumes the moment the threat clears.
|
||||
if (inventorySettled && !combatThreat)
|
||||
_salvageManager?.OnTick(_busyCount);
|
||||
_salvageManager?.OnTick(PacedBusy);
|
||||
if (diag) Host.Log("[RynthAi] OnTick: before manaStoneManager");
|
||||
|
||||
// STEP 4: the salvage gap-fill that used to pin/release
|
||||
|
|
@ -1899,8 +1950,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// decision from scratch every tick.
|
||||
|
||||
// Mana stone tapping — runs after salvage, independent of looting state.
|
||||
_manaStoneManager?.OnHeartbeat(_busyCount);
|
||||
_petManager?.OnHeartbeat(_busyCount);
|
||||
_manaStoneManager?.OnHeartbeat(PacedBusy);
|
||||
_petManager?.OnHeartbeat(PacedBusy);
|
||||
if (diag) Host.Log("[RynthAi] OnTick: before combatManager");
|
||||
|
||||
// Missile crafting runs before combat — blocks everything while active.
|
||||
|
|
@ -2041,18 +2092,14 @@ 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))
|
||||
{
|
||||
if (_lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass))
|
||||
InspectLootRuleForItem(sid, quiet: true);
|
||||
var itemInfo = _dashboard?.Settings.ItemInfoSettings;
|
||||
if (itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass))
|
||||
QueueAutoItemInfo(sid, requestId: false);
|
||||
}
|
||||
QueueItemInfoOnSelect(currentTargetId, obj);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2078,6 +2125,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (mmEat) eat = 1;
|
||||
else _dashboard?.PushChatLine(text, chatType);
|
||||
OnChatLocalFeatures(text, chatType, ref eat);
|
||||
try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); }
|
||||
_buffManager?.OnChatWindowText(text, chatType);
|
||||
_manaStoneManager?.OnChatWindowText(text);
|
||||
_petManager?.OnChatWindowText(text);
|
||||
|
|
@ -2087,6 +2135,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.
|
||||
try { Loot.T11ItemSupport.OnChat(text); }
|
||||
catch (Exception ex) { Log("RynthAi: T11 /aug parse failed: " + ex.Message); }
|
||||
CheckChatForSafetyStops(text);
|
||||
try { OnOwnCorpseChat(text); } catch { }
|
||||
}
|
||||
|
|
@ -2098,6 +2149,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
public override void OnKillNotification(string? deathMessage)
|
||||
{
|
||||
if (string.IsNullOrEmpty(deathMessage)) return;
|
||||
_killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone
|
||||
_combatManager?.OnKillNotification(deathMessage);
|
||||
_dashboard?.RecordKill(); // feeds the kills/hour session stat
|
||||
try { _iltHub?.RecordKill(); }
|
||||
|
|
@ -2120,6 +2172,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)
|
||||
|
|
@ -3052,13 +3105,48 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
int count = _pendingGives.Count;
|
||||
_pendingGives.Clear();
|
||||
_giveInFlightId = 0;
|
||||
ChatLine(count > 0
|
||||
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
|
||||
: "[RynthAi] Give queue is already empty.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One give at a time, each after the server has taken the last: the item has left the
|
||||
/// inventory (or its stack shrank, for part of a stack). The queue used to send a give
|
||||
/// every 150 ms; the server takes one give at a time and answers the rest "too busy",
|
||||
/// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no
|
||||
/// answer in GiveConfirmMs is sent once more, then skipped.
|
||||
/// </summary>
|
||||
private void DrainGiveQueue()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (_giveInFlightId != 0)
|
||||
{
|
||||
if (GiveLanded())
|
||||
{
|
||||
_giveInFlightId = 0;
|
||||
_lastGiveAt = DateTime.UtcNow;
|
||||
if (_pendingGives.Count == 0)
|
||||
ChatLine("[RynthAi] Give queue complete.");
|
||||
}
|
||||
else if (now - _giveInFlightAt < GiveConfirmMs)
|
||||
return;
|
||||
else if (_giveInFlightTries < GiveMaxTries)
|
||||
{
|
||||
GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack);
|
||||
_giveInFlightTries++;
|
||||
_giveInFlightAt = now;
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
|
||||
_giveInFlightId = 0;
|
||||
if (_pendingGives.Count == 0) return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_pendingGives.Count == 0) return;
|
||||
int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150;
|
||||
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
|
||||
|
|
@ -3069,9 +3157,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
|
||||
GiveItem(itemId, targetId, stackSize, whole);
|
||||
_lastGiveAt = DateTime.UtcNow;
|
||||
_giveInFlightId = itemId;
|
||||
_giveInFlightTarget = targetId;
|
||||
_giveInFlightAmount = stackSize;
|
||||
_giveInFlightStack = whole;
|
||||
_giveInFlightTries = 1;
|
||||
_giveInFlightAt = now;
|
||||
}
|
||||
|
||||
if (_pendingGives.Count == 0)
|
||||
ChatLine("[RynthAi] Give queue complete.");
|
||||
/// <summary>The in-flight give went through: the item left the inventory, or part of its stack did.</summary>
|
||||
private bool GiveLanded()
|
||||
{
|
||||
if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true;
|
||||
if (!InPlayerInventory(wo.Container)) return true;
|
||||
return _giveInFlightAmount < _giveInFlightStack
|
||||
&& Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -3120,7 +3220,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "listpvars": HandleListPvarsCommand(); break;
|
||||
case "listgvars": HandleListGvarsCommand(); break;
|
||||
case "dumpprops": HandleDumpPropsCommand(parts); break;
|
||||
case "iteminfo": HandleItemInfoCommand(parts); break;
|
||||
case "version": HandleVersionCommand(); break;
|
||||
case "t11": HandleT11Command(parts); break;
|
||||
case "wielded": HandleWieldedCommand(); break;
|
||||
case "scan": HandleScanCommand(); break;
|
||||
case "buildinfo": HandleBuildInfoCommand(); break;
|
||||
|
|
@ -3148,7 +3250,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "miniremote": HandleHudCommand(cmd, parts.Length > 2 ? parts[2] : string.Empty); break;
|
||||
case "translate":
|
||||
case "tr": HandleTranslateCommand(parts); break;
|
||||
case "iteminfo":
|
||||
case "ii": HandleItemInfoCommand(parts); break;
|
||||
case "groundloot": HandleGroundLootCommand(parts); break;
|
||||
case "addnavpt": HandleAddNavPointCommand(); break;
|
||||
|
|
@ -3172,6 +3273,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
|
||||
case "loot": HandleLootCommand(parts); break;
|
||||
case "corpseinfo": HandleCorpseInfoCommand(); break;
|
||||
case "pace": HandlePaceCommand(); break;
|
||||
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
|
||||
case "corpseopen": HandleCorpseOpenCommand(); break;
|
||||
case "owncorpse":
|
||||
|
|
|
|||
124
Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs
Normal file
124
Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// /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.
|
||||
/// </summary>
|
||||
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 <n|auto> | refresh | item [0xId]]");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The counters the "T11: Can Wield" loot key compares wield gates against.</summary>
|
||||
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 <n>.");
|
||||
}
|
||||
|
||||
/// <summary>/ra t11 augs <n|auto>: saves the item-aug override (-1 = read from /aug).</summary>
|
||||
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|auto> (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.");
|
||||
}
|
||||
|
||||
/// <summary>/ra t11 item [0xId]: the parsed T11 text of an item (selected item by default).</summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -29,8 +29,6 @@
|
|||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver used by the ILT Hub, diagnostics, and chat translator. -->
|
||||
<Compile Include="..\..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- UB damage-insights seed schema, shared with the Monster Editor importer. -->
|
||||
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
|
||||
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
|
||||
|
|
@ -39,10 +37,16 @@
|
|||
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
|
||||
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
|
||||
<!-- Reading our hits out of the combat log (victim + amount); RynthTracker reads the same lines. -->
|
||||
<Compile Include="..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Movement calls logged with the subsystem that sent them (stuck-cast diagnosis, 2026-10-05). -->
|
||||
<Compile Include="..\Shared\MoveAudit.cs" Link="Shared\MoveAudit.cs" />
|
||||
<!-- One server action at a time, paced on the server's answers (stuck use/cast, 2026-10-06). -->
|
||||
<Compile Include="..\Shared\ActionPacer.cs" Link="Shared\ActionPacer.cs" />
|
||||
<!-- Text in the world on the Nav3D buffer (waypoint labels; RynthNav's path markers use it too). -->
|
||||
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -97,4 +101,9 @@
|
|||
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ namespace RynthCore.Plugin.RynthAi.Trade;
|
|||
/// </summary>
|
||||
internal sealed class AutoTradeManager
|
||||
{
|
||||
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoTrade";
|
||||
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoTrade");
|
||||
public const string ProfileSubfolder = "AutoTrade";
|
||||
public const string AutoAcceptListFileName = "autoAcceptList.json";
|
||||
public const uint RequiredApiVersion = 72;
|
||||
|
|
|
|||
|
|
@ -170,7 +170,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
string n = name.Trim().Trim('"');
|
||||
if (File.Exists(n)) return n;
|
||||
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
|
||||
{
|
||||
string p = Path.Combine(folder, cand);
|
||||
|
|
@ -236,7 +236,7 @@ public sealed partial class RynthAiPlugin
|
|||
int sp = args.IndexOf(' ');
|
||||
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
|
||||
file = file.Trim('"');
|
||||
if (!Path.IsPathRooted(file)) file = Path.Combine(@"C:\Games\RynthSuite\RynthAi", file);
|
||||
if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file);
|
||||
if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; }
|
||||
try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); }
|
||||
catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); }
|
||||
|
|
@ -352,7 +352,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
|
||||
return;
|
||||
}
|
||||
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]);
|
||||
string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]);
|
||||
if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav";
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ namespace RynthCore.Plugin.RynthAi.Vendor;
|
|||
/// </summary>
|
||||
internal sealed class AutoVendorManager
|
||||
{
|
||||
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
|
||||
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor");
|
||||
public const string ProfileSubfolder = "AutoVendor";
|
||||
|
||||
private const long BailMs = 60_000; // UB bailTimer
|
||||
|
|
@ -76,6 +76,7 @@ internal sealed class AutoVendorManager
|
|||
private long _nextPollAt;
|
||||
private int _failures;
|
||||
private readonly HashSet<uint> _sessionSkip = new(); // items the engine refused to sell
|
||||
private readonly HashSet<string> _sellSkipLogged = new(StringComparer.OrdinalIgnoreCase); // names logged as held back this session
|
||||
|
||||
private readonly List<uint> _idQueue = new();
|
||||
private readonly Dictionary<uint, (int Attempts, long LastAt)> _idState = new();
|
||||
|
|
@ -457,6 +458,7 @@ internal sealed class AutoVendorManager
|
|||
_profilePath = path;
|
||||
_failures = 0;
|
||||
_sessionSkip.Clear();
|
||||
_sellSkipLogged.Clear();
|
||||
_bailAt = Now();
|
||||
_nextActionAt = 0;
|
||||
_host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)");
|
||||
|
|
@ -853,14 +855,36 @@ internal sealed class AutoVendorManager
|
|||
SafetyFacts safety = ReadSafety(wo, player);
|
||||
string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack);
|
||||
if (unsafeWhy != null && heldBack == null)
|
||||
{
|
||||
if (!_sellSkipLogged.Contains(wo.Name))
|
||||
{
|
||||
ProfileVerdict uv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
|
||||
// "Not identified" is usually just not yet (the IDs are on their way): only a
|
||||
// certain Sell match is worth a line.
|
||||
if (uv.Rule?.Action == VTankLootAction.Sell && uv.Certain && _sellSkipLogged.Add(wo.Name))
|
||||
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{uv.RuleName}'): {unsafeWhy}.");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
uint type = ItemType(wo);
|
||||
int stack = StackOf(wo);
|
||||
bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
|
||||
int unitValue = stack > 1 ? safety.Value / stack : safety.Value;
|
||||
if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue))
|
||||
{
|
||||
// A Sell rule wanted it and the vendor won't take it: say why, once per name a
|
||||
// session (peas not sold at Aun Amanaualuan, 2026-10-07, with nothing logged).
|
||||
if (heldBack == null && !_sellSkipLogged.Contains(wo.Name))
|
||||
{
|
||||
ProfileVerdict sv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
|
||||
if (sv.Rule?.Action == VTankLootAction.Sell && sv.Certain && _sellSkipLogged.Add(wo.Name))
|
||||
_host.Log(!v.Buys(type)
|
||||
? $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): this vendor doesn't buy {AutoVendorPlanner.CategoryName(type)} (item type 0x{type:X}, vendor buys 0x{v.ItemTypes:X})."
|
||||
: $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): worth {unitValue:n0} each, this vendor pays for items up to {v.MaxValue:n0}.");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
ItemFacts f = InventoryFacts(wo, safety.Appraised);
|
||||
ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx));
|
||||
|
|
@ -876,6 +900,8 @@ internal sealed class AutoVendorManager
|
|||
{
|
||||
if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell)
|
||||
heldBack.Add($"{wo.Name} - {sd.Reason}");
|
||||
else if (heldBack == null && verdict.Rule?.Action == VTankLootAction.Sell && _sellSkipLogged.Add(wo.Name))
|
||||
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}': {sd.Reason}.");
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -254,7 +254,9 @@ internal static class AutoVendorPlanner
|
|||
if (f.IsRare) return "rare";
|
||||
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
|
||||
if (f.Attuned != 0) return "attuned";
|
||||
if (f.Bonded != 0) return "bonded";
|
||||
// Not Bonded: on ACE it only decides what a death keeps (PropertyInt.Bonded, Player_Death);
|
||||
// it never stops a sale. Peas, trade notes and salvage bags are bonded so a death keeps
|
||||
// them, and AutoVendor held them all back (2026-10-07). Quest items are not sellable anyway.
|
||||
if (f.Retained) return "retained";
|
||||
if (f.TimesTinkered > 0) return "tinkered";
|
||||
if (f.Imbued != 0) return "imbued";
|
||||
|
|
|
|||
|
|
@ -44,4 +44,9 @@
|
|||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ namespace RynthCore.Plugin.RynthLua;
|
|||
/// </summary>
|
||||
internal static class RynthLuaPaths
|
||||
{
|
||||
/// <summary>RynthLua's folder: Scripts\, Data\, settings.json, editor.lua.</summary>
|
||||
public static string Root { get; set; } = @"C:\Games\RynthSuite\RynthLua";
|
||||
/// <summary>RynthLua's folder: Scripts\, Data\, settings.json, editor.lua (<SuiteDir>\RynthLua, C:\Games\RynthSuite\RynthLua by default).</summary>
|
||||
public static string Root { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthLua");
|
||||
|
||||
/// <summary>Where scripts lived while Lua was part of RynthAi (copied over once, then left alone).</summary>
|
||||
public static string LegacyScripts { get; set; } = @"C:\Games\RynthSuite\RynthAi\LuaScripts";
|
||||
public static string LegacyScripts { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LuaScripts");
|
||||
|
||||
public static string Scripts => Path.Combine(Root, "Scripts");
|
||||
public static string Data => Path.Combine(Root, "Data");
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ internal sealed class AtlasLocation
|
|||
// A portal's destination.
|
||||
public bool HasDest, DestOnMap;
|
||||
public double DestNs, DestEw;
|
||||
public string DestName = "", DestPlace = "";
|
||||
public string DestName = "", DestPlace = "", DestCell = "";
|
||||
public int MinLevel, MaxLevel;
|
||||
public bool Quest, Closed;
|
||||
}
|
||||
|
|
@ -92,6 +92,7 @@ internal sealed class Atlas
|
|||
l.DestOnMap = TryNum(d, "ns", out l.DestNs) & TryNum(d, "ew", out l.DestEw);
|
||||
l.DestName = Str(d, "name");
|
||||
l.DestPlace = Str(d, "place");
|
||||
l.DestCell = Str(d, "cell");
|
||||
}
|
||||
locs.Add(l);
|
||||
}
|
||||
|
|
@ -110,6 +111,36 @@ internal sealed class Atlas
|
|||
|
||||
public AtlasLocation? ById(int id) => _byId.TryGetValue(id, out var l) ? l : null;
|
||||
|
||||
/// <summary>
|
||||
/// Landblocks that are dungeons: places (and portal destinations) the Atlas has in "dungeon"
|
||||
/// cells, less any landblock with places on the map. A dungeon's nav_XXXX.tile holds only that
|
||||
/// landblock's surface (a flat sheet; RynthNav.Baker leaves dungeon cells out), so it isn't
|
||||
/// a navmesh for walking inside the dungeon.
|
||||
/// </summary>
|
||||
public HashSet<uint> DungeonLandblocks()
|
||||
{
|
||||
var dungeon = new HashSet<uint>();
|
||||
var map = new HashSet<uint>();
|
||||
foreach (AtlasLocation l in Locations)
|
||||
{
|
||||
if (TryLandblock(l.Cell, out uint lb))
|
||||
{
|
||||
if (l.OnMap) map.Add(lb);
|
||||
else if (l.Place.Equals("dungeon", StringComparison.Ordinal)) dungeon.Add(lb);
|
||||
}
|
||||
if (l.HasDest && !l.DestOnMap && l.DestPlace.Equals("dungeon", StringComparison.Ordinal) && TryLandblock(l.DestCell, out uint dlb))
|
||||
dungeon.Add(dlb);
|
||||
}
|
||||
dungeon.ExceptWith(map);
|
||||
return dungeon;
|
||||
}
|
||||
|
||||
private static bool TryLandblock(string cell, out uint lb)
|
||||
{
|
||||
lb = 0;
|
||||
return cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb);
|
||||
}
|
||||
|
||||
// ── Search ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>How well <paramref name="name"/> matches <paramref name="q"/> (lower case): 0 = not at all.</summary>
|
||||
|
|
|
|||
203
Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs
Normal file
203
Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// "Save as nav route": a planned trip as a RynthAi nav route (uTank2 NAV 1.2, the VTank format
|
||||
/// RynthAi reads and writes; RynthAi's own NavRouteParser, linked in, does the writing), so RynthAi
|
||||
/// can load it from NavProfiles and run it. Route type Once.
|
||||
///
|
||||
/// a walk step its path's waypoints (Point), thinned (TripPathBuilder.Thin): not every
|
||||
/// navmesh corner, a point at least every 60 yd on straight ground
|
||||
/// a portal step the walk up to PortalStopShort yd before the entrance, then a Portal step
|
||||
/// (VTank "Portal", type 6) naming the portal object, at the entrance: RynthAi
|
||||
/// uses it by name (the nearest one) and walks the last yards itself
|
||||
/// a recall spell a Recall step (type 2) with the spell id, cast where the trip stands
|
||||
/// a command recall (@lifestone, @house recall...): a Chat step with the command, then a Pause
|
||||
/// of CommandRecallPauseMs (RynthAi doesn't wait for a chat command's teleport)
|
||||
/// the Town Network the walk inside (townnet.json) as waypoints, then a Portal step for the exit
|
||||
/// a dungeon goto ends with the Portal step into the dungeon's entrance portal
|
||||
/// A step it can't write (a recall the plan doesn't know, a Town Network walk townnet.json doesn't
|
||||
/// have) stops the route there: what comes before is kept, and the reason is given.
|
||||
/// Host-free: the route tests convert made-up trips and read the file back with RynthAi's reader.
|
||||
/// </summary>
|
||||
internal static class NavRouteExport
|
||||
{
|
||||
/// <summary>The walk to a portal stops this far short of its entrance (the Portal step walks the rest).</summary>
|
||||
public const double PortalStopShort = 5.0;
|
||||
/// <summary>Inside the Town Network the stored walk ends at the exit portal: stop this far short.</summary>
|
||||
public const double HubStopShort = 2.0;
|
||||
/// <summary>After a command recall's chat step: wait this long for its teleport (ms).</summary>
|
||||
public const int CommandRecallPauseMs = 20000;
|
||||
/// <summary>VTank's object class for a portal (the Portal step's second trailer line).</summary>
|
||||
public const int PortalObjectClass = 14;
|
||||
|
||||
public sealed class Result
|
||||
{
|
||||
public NavRouteParser Route = new() { RouteType = NavRouteType.Once };
|
||||
/// <summary>The step (0-based) the route stops at, short of the trip's end; -1 = the whole trip.</summary>
|
||||
public int StoppedAt = -1;
|
||||
public string StopReason = "";
|
||||
public int Waypoints, Portals, Recalls, Chats;
|
||||
}
|
||||
|
||||
/// <summary>The trip as nav points (see the class notes). <paramref name="path"/> must be this trip's.</summary>
|
||||
public static Result Convert(PlannedTrip trip, TripPath path, TownNet? net)
|
||||
{
|
||||
var r = new Result();
|
||||
if (path.TripId != trip.Id) { r.StoppedAt = 0; r.StopReason = "the path was worked out for another trip"; return r; }
|
||||
WorldPt here = trip.Start; // where action steps happen when nothing better is known
|
||||
double lastH = double.IsNaN(trip.Start.H) ? 0 : trip.Start.H;
|
||||
|
||||
void Stop(int i, string why) { r.StoppedAt = i; r.StopReason = $"step {i + 1}: {why}"; }
|
||||
void AddPoint(WorldPt p)
|
||||
{
|
||||
if (!double.IsNaN(p.H)) lastH = p.H;
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = p.Ns, EW = p.Ew, Z = lastH / 240.0 });
|
||||
r.Waypoints++;
|
||||
here = p;
|
||||
}
|
||||
void AddPortal(string name, WorldPt at)
|
||||
{
|
||||
if (!double.IsNaN(at.H)) lastH = at.H;
|
||||
double ns = at.Ns, ew = at.Ew, z = lastH / 240.0;
|
||||
r.Route.Points.Add(new NavPoint
|
||||
{
|
||||
Type = NavPointType.PortalNPC, NS = ns, EW = ew, Z = z,
|
||||
TargetName = name, ObjectClass = PortalObjectClass, IsTie = true,
|
||||
PortalExitNS = ns, PortalExitEW = ew, PortalExitZ = z,
|
||||
});
|
||||
r.Portals++;
|
||||
}
|
||||
void Land(RouteStep s)
|
||||
{
|
||||
if (!double.IsNaN(s.LandNs)) here = WorldPt.FromMap(s.LandNs, s.LandEw, double.NaN);
|
||||
}
|
||||
|
||||
for (int i = 0; i < trip.Count; i++)
|
||||
{
|
||||
RouteStep s = trip.Steps[i];
|
||||
if (s.UseRecall)
|
||||
{
|
||||
TripRecall? rec = trip.RecallOf(i);
|
||||
if (rec is not TripRecall o) { Stop(i, $"the recall {s.Label} isn't one the plan knows how to cast"); return r; }
|
||||
WorldPt at = trip.Point[i] ?? here;
|
||||
double z = (double.IsNaN(at.H) ? lastH : at.H) / 240.0;
|
||||
if (o.SpellId != 0)
|
||||
{
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Recall, NS = at.Ns, EW = at.Ew, Z = z, SpellId = o.SpellId });
|
||||
r.Recalls++;
|
||||
}
|
||||
else if (o.Command.Length > 0)
|
||||
{
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Chat, NS = at.Ns, EW = at.Ew, Z = z, ChatCommand = o.Command });
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Pause, NS = at.Ns, EW = at.Ew, Z = z, PauseTimeMs = CommandRecallPauseMs });
|
||||
r.Chats++;
|
||||
}
|
||||
else { Stop(i, $"{o.Name} has neither a spell nor a command"); return r; }
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
WorldPt[]? inside = path.Hub[i];
|
||||
WorldPt? exit = PlannedTrip.HubExitPoint(net, s);
|
||||
if (inside == null || exit == null || net == null)
|
||||
{
|
||||
trip.HubWalk(i, net, out string why);
|
||||
Stop(i, $"the walk inside the Town Network isn't known ({(why.Length > 0 ? why : "no townnet.json")})");
|
||||
return r;
|
||||
}
|
||||
List<WorldPt> walk = TripPathBuilder.StopShort(inside, HubStopShort);
|
||||
for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]);
|
||||
AddPortal(net.Exits[s.HubExit].Name, exit.Value);
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
WorldPt[]? pts = path.Walks[i];
|
||||
if (pts == null || pts.Length == 0)
|
||||
{
|
||||
if (trip.WalkFrom[i] == null) { Stop(i, "it starts where the plan has no map position (inside a dungeon)"); return r; }
|
||||
Stop(i, "its walk wasn't worked out");
|
||||
return r;
|
||||
}
|
||||
if (s.UsePortal)
|
||||
{
|
||||
List<WorldPt> walk = TripPathBuilder.StopShort(pts, PortalStopShort);
|
||||
for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]);
|
||||
WorldPt at = trip.Point[i] is WorldPt p ? p with { H = pts[^1].H } : pts[^1];
|
||||
string name = trip.PortalName(i);
|
||||
if (name.Length == 0) { Stop(i, "the portal has no name to look for"); return r; }
|
||||
AddPortal(name, at);
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
for (int k = 1; k < pts.Length; k++) AddPoint(pts[k]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── The file ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A nav file name from what was typed: trimmed, without ".nav". "" with <paramref name="error"/>
|
||||
/// when it can't be one (empty, characters a file name can't have, a path).
|
||||
/// </summary>
|
||||
public static string FileName(string typed, out string error)
|
||||
{
|
||||
error = "";
|
||||
string n = (typed ?? "").Trim();
|
||||
if (n.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) n = n[..^4].TrimEnd();
|
||||
if (n.Length == 0) { error = "give the route a name"; return ""; }
|
||||
if (n.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || n.Contains("..") || n.Length > 100)
|
||||
{ error = $"'{typed}' can't be used as a file name"; return ""; }
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>A file name made from a place's name (characters a file can't have become spaces).</summary>
|
||||
public static string SafeName(string text)
|
||||
{
|
||||
var chars = (text ?? "").ToCharArray();
|
||||
char[] bad = Path.GetInvalidFileNameChars();
|
||||
for (int i = 0; i < chars.Length; i++) if (Array.IndexOf(bad, chars[i]) >= 0) chars[i] = ' ';
|
||||
string s = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
return s.Length > 60 ? s[..60].TrimEnd() : s;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="route"/> to <folder>\<name>.nav. An existing file is only replaced
|
||||
/// with <paramref name="overwrite"/>; otherwise nothing is written and false comes back with
|
||||
/// <paramref name="exists"/> set. Written to a temporary file first, then moved into place.
|
||||
/// </summary>
|
||||
public static bool Save(string folder, string name, NavRouteParser route, bool overwrite, out string path, out bool exists, out string error)
|
||||
{
|
||||
error = "";
|
||||
path = Path.Combine(folder, name + ".nav");
|
||||
exists = File.Exists(path);
|
||||
if (exists && !overwrite) return false;
|
||||
string tmp = path + ".tmp";
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllLines(tmp, route.ToLines());
|
||||
File.Move(tmp, path, overwrite);
|
||||
return true;
|
||||
}
|
||||
catch (IOException) when (!overwrite && File.Exists(path))
|
||||
{
|
||||
exists = true; // made by someone else in the meantime
|
||||
try { File.Delete(tmp); } catch { }
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
try { File.Delete(tmp); } catch { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
295
Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs
Normal file
295
Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
internal enum MarkKind : byte { Waypoint, Portal, Recall, Town, Goal }
|
||||
|
||||
/// <summary>One marker on the ground: a waypoint of a walk, or where a step happens.</summary>
|
||||
internal readonly record struct Mark(WorldPt P, MarkKind Kind, string Label, int Step, bool LineToNext);
|
||||
|
||||
/// <summary>
|
||||
/// A trip's markers, built on the tick from the trip and its path and then never changed: the
|
||||
/// Nav3D emit reads only this (never the plan, the route or the walker's state).
|
||||
/// </summary>
|
||||
internal sealed class MarkerSnapshot
|
||||
{
|
||||
public static readonly MarkerSnapshot Empty = new(0, false, Array.Empty<Mark>());
|
||||
|
||||
public readonly int TripId;
|
||||
/// <summary>Built with the trip's path (waypoints and lines), not just the steps' points.</summary>
|
||||
public readonly bool HasPath;
|
||||
public readonly Mark[] Marks;
|
||||
|
||||
public MarkerSnapshot(int tripId, bool hasPath, Mark[] marks) { TripId = tripId; HasPath = hasPath; Marks = marks; }
|
||||
|
||||
/// <summary>The first marker of step <paramref name="step"/>, or -1.</summary>
|
||||
public int FirstOfStep(int step)
|
||||
{
|
||||
for (int i = 0; i < Marks.Length; i++) if (Marks[i].Step == step) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>The last marker of step <paramref name="step"/>, or -1.</summary>
|
||||
public int LastOfStep(int step)
|
||||
{
|
||||
for (int i = Marks.Length - 1; i >= 0; i--) if (Marks[i].Step == step) return i;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the markers go: the engine's Nav3D buffer in the game, a recorder in the tests.</summary>
|
||||
internal interface IMarkerSink : INav3DSink
|
||||
{
|
||||
void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb);
|
||||
}
|
||||
|
||||
/// <summary>What the emit needs to know about this tick (all plain values, taken on the tick).</summary>
|
||||
internal readonly record struct MarkerView(
|
||||
double Px, double Py, double Pz, // the character: world east, north, height
|
||||
int Next, // the marker the walk is heading for (-1: none, a plan only)
|
||||
bool Labels, bool Guide);
|
||||
|
||||
/// <summary>
|
||||
/// RynthNav's path markers: the planned trip drawn on the ground the way RynthAi draws its nav
|
||||
/// routes (rings at the waypoints, lines between them, on the engine's Nav3D buffer), with the
|
||||
/// place each step happens (a portal, a recall, the Town Network, the goal) in its own colour and,
|
||||
/// optionally, a label (Plugins/Shared/Nav3DText) and a guide line from your feet to the next
|
||||
/// waypoint. Host-free: the route tests build and emit these into a recorder.
|
||||
/// </summary>
|
||||
internal static class PathMarkers
|
||||
{
|
||||
public const double WaypointRange = 160.0; // waypoints this close (yards) are drawn
|
||||
public const double StepRange = 400.0; // a step's own marker, this close
|
||||
public const double LabelRange = 90.0;
|
||||
public const double MaxGuideUnits = 500.0;
|
||||
public const double NextReach = 4.0; // the next waypoint counts as reached this close
|
||||
public const int MaxWaypointRings = 40;
|
||||
public const int MaxStepRings = 8;
|
||||
public const int MaxLines = 90;
|
||||
public const int MaxLabelTriangles = 900; // the engine keeps 8192 a tick for every plugin
|
||||
public const int MaxLabelChars = 22;
|
||||
|
||||
public const uint WaypointColor = 0xFF40D973, LineColor = 0xFF2FB863, NextColor = 0xFFFF4444,
|
||||
PortalColor = 0xFFBF4DFF, RecallColor = 0xFFFFC040, TownColor = 0xFF2EC4C4, GoalColor = 0xFFFFD24D,
|
||||
GuideColor = 0xFFFFD21E;
|
||||
|
||||
private const float WaypointRadius = 0.9f, StepRadius = 1.8f, RingThick = 0.12f, LineThick = 0.08f, Lift = 0.1f;
|
||||
|
||||
// ── Build (tick) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The markers for <paramref name="trip"/>: with its <paramref name="path"/> (same trip), every
|
||||
/// walk's waypoints joined by lines and each step's own marker; without it (still being worked
|
||||
/// out, or none to be had), only the steps' markers.
|
||||
/// </summary>
|
||||
public static MarkerSnapshot Build(PlannedTrip trip, TripPath? path, TownNet? net)
|
||||
{
|
||||
if (path != null && path.TripId != trip.Id) path = null;
|
||||
var marks = new List<Mark>();
|
||||
int n = trip.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
RouteStep s = trip.Steps[i];
|
||||
bool last = i == n - 1;
|
||||
if (s.UseRecall)
|
||||
{
|
||||
if (trip.Point[i] is WorldPt at)
|
||||
marks.Add(new Mark(at, MarkKind.Recall, Fit("RECALL " + (trip.RecallOf(i)?.Name ?? s.Label)), i, false));
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
WorldPt? exit = PlannedTrip.HubExitPoint(net, s);
|
||||
WorldPt[]? inside = path?.Hub[i];
|
||||
if (inside != null)
|
||||
foreach (WorldPt p in inside)
|
||||
{
|
||||
if (exit is WorldPt e && p.FlatDistance(e) < 2.0) continue;
|
||||
Add(marks, new Mark(p, MarkKind.Waypoint, "", i, true));
|
||||
}
|
||||
WorldPt? at = exit ?? (inside is { Length: > 0 } ? inside[^1] : null);
|
||||
string where = net != null && s.HubExit >= 0 && s.HubExit < net.Exits.Count ? net.Exits[s.HubExit].Where : s.Label;
|
||||
if (at is WorldPt a) marks.Add(new Mark(a, MarkKind.Town, Fit("PORTAL TO " + where), i, false));
|
||||
continue;
|
||||
}
|
||||
if (trip.Point[i] is not WorldPt to) continue;
|
||||
WorldPt[]? walk = path?.Walks[i];
|
||||
if (walk != null)
|
||||
for (int k = 0; k < walk.Length - 1; k++)
|
||||
Add(marks, new Mark(walk[k], MarkKind.Waypoint, "", i, true));
|
||||
if (walk is { Length: > 0 }) to = to with { H = walk[^1].H };
|
||||
Mark end;
|
||||
if (s.UsePortal)
|
||||
{
|
||||
bool intoHub = i + 1 < n && trip.Steps[i + 1].IsHub;
|
||||
string label = intoHub ? "TOWN NETWORK"
|
||||
: last && trip.EndsInEntrance ? "ENTER " + trip.EnterName
|
||||
: "PORTAL " + s.Label;
|
||||
end = new Mark(to, intoHub ? MarkKind.Town : MarkKind.Portal, Fit(label), i, false);
|
||||
}
|
||||
else if (last) end = new Mark(to, MarkKind.Goal, Fit(trip.Goal.Length > 0 ? trip.Goal : "ARRIVE"), i, false);
|
||||
else end = new Mark(to, MarkKind.Waypoint, "", i, walk != null);
|
||||
Add(marks, end);
|
||||
}
|
||||
return new MarkerSnapshot(trip.Id, path != null, marks.ToArray());
|
||||
}
|
||||
|
||||
// A leg starts where the last one ended: the same point once. A step's own marker takes the
|
||||
// place of a waypoint under it (the line before it then runs into the step's marker).
|
||||
private static void Add(List<Mark> marks, Mark m)
|
||||
{
|
||||
if (marks.Count > 0 && marks[^1].P.FlatDistance(m.P) < 1.0)
|
||||
{
|
||||
Mark prev = marks[^1];
|
||||
if (m.Kind == MarkKind.Waypoint)
|
||||
{
|
||||
if (m.LineToNext && !prev.LineToNext && prev.Kind == MarkKind.Waypoint) marks[^1] = prev with { LineToNext = true };
|
||||
return;
|
||||
}
|
||||
if (prev.Kind == MarkKind.Waypoint) marks.RemoveAt(marks.Count - 1);
|
||||
}
|
||||
marks.Add(m);
|
||||
}
|
||||
|
||||
private static string Fit(string s)
|
||||
{
|
||||
s = s.Trim().ToUpperInvariant();
|
||||
return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s;
|
||||
}
|
||||
|
||||
// ── The next waypoint (tick) ─────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The marker the walk on step <paramref name="step"/> heads for next, carried on from
|
||||
/// <paramref name="idx"/> (last tick's): it moves on when the character is within
|
||||
/// <see cref="NextReach"/> of it, or is already nearer the stretch after it than the one before
|
||||
/// it (a re-plan or a cut corner). Never moves back within a step. -1 when the step has no markers.
|
||||
/// </summary>
|
||||
public static int Advance(MarkerSnapshot s, int idx, int step, double px, double py)
|
||||
{
|
||||
Mark[] m = s.Marks;
|
||||
int first = s.FirstOfStep(step), lastOfStep = s.LastOfStep(step);
|
||||
if (first < 0) return -1;
|
||||
if (idx < first || idx > lastOfStep) idx = first;
|
||||
var me = new WorldPt(px, py, 0);
|
||||
while (idx < lastOfStep)
|
||||
{
|
||||
if (m[idx].P.FlatDistance(me) < NextReach) { idx++; continue; }
|
||||
WorldPt before = idx > first ? m[idx - 1].P : m[idx].P;
|
||||
double toBefore = idx > first ? PlannedTrip.SegmentDistance(me, before, m[idx].P) : double.MaxValue;
|
||||
double toAfter = PlannedTrip.SegmentDistance(me, m[idx].P, m[idx + 1].P, out double t);
|
||||
if (toAfter + 1.0 < toBefore && t > 0.05) { idx++; continue; }
|
||||
break;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
/// <summary>The marker nearest the character (a plan only: where the guide line points), or -1.</summary>
|
||||
public static int Nearest(MarkerSnapshot s, double px, double py)
|
||||
{
|
||||
int best = -1;
|
||||
double bestD = MaxGuideUnits;
|
||||
var me = new WorldPt(px, py, 0);
|
||||
for (int i = 0; i < s.Marks.Length; i++)
|
||||
{
|
||||
double d = s.Marks[i].P.FlatDistance(me);
|
||||
if (d < bestD) { bestD = d; best = i; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── Emit (tick, into the Nav3D buffer) ───────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Submits the markers near the character: rings (waypoints within <see cref="WaypointRange"/>,
|
||||
/// at most <see cref="MaxWaypointRings"/> nearest; steps' markers within <see cref="StepRange"/>),
|
||||
/// lines between neighbouring waypoints, the guide line first (so a full line buffer never drops
|
||||
/// it) and the labels last. Positions go in the Nav3D frame: the character's landblock, X = east
|
||||
/// metres, Y = height, Z = north metres. Returns the number of rings drawn.
|
||||
/// </summary>
|
||||
public static int Emit(MarkerSnapshot s, in MarkerView v, IMarkerSink sink)
|
||||
{
|
||||
Mark[] m = s.Marks;
|
||||
if (m.Length == 0) return 0;
|
||||
double baseX = Math.Floor(v.Px / 192.0) * 192.0, baseY = Math.Floor(v.Py / 192.0) * 192.0;
|
||||
float px = (float)(v.Px - baseX), py = (float)(v.Py - baseY), pz = (float)v.Pz;
|
||||
var me = new WorldPt(v.Px, v.Py, v.Pz);
|
||||
|
||||
// Which markers: steps' own within StepRange, waypoints within WaypointRange (the nearest).
|
||||
var dist = new double[m.Length];
|
||||
var drawn = new bool[m.Length];
|
||||
var waypoints = new List<int>();
|
||||
int steps = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
dist[i] = m[i].P.FlatDistance(me);
|
||||
if (m[i].Kind == MarkKind.Waypoint) { if (dist[i] <= WaypointRange) waypoints.Add(i); }
|
||||
else if (dist[i] <= StepRange && steps < MaxStepRings) { drawn[i] = true; steps++; }
|
||||
}
|
||||
if (waypoints.Count > MaxWaypointRings) waypoints.Sort((a, b) => dist[a].CompareTo(dist[b]));
|
||||
for (int k = 0; k < waypoints.Count && k < MaxWaypointRings; k++) drawn[waypoints[k]] = true;
|
||||
if (v.Next >= 0 && v.Next < m.Length && dist[v.Next] <= StepRange) drawn[v.Next] = true;
|
||||
|
||||
(float X, float Y, float Z) Local(WorldPt p) =>
|
||||
((float)(p.X - baseX), (double.IsNaN(p.H) ? pz : (float)p.H) + Lift, (float)(p.Y - baseY));
|
||||
|
||||
// Guide line: to the next waypoint (a walk), else the nearest marker (a plan).
|
||||
if (v.Guide)
|
||||
{
|
||||
int g = v.Next >= 0 && v.Next < m.Length ? v.Next : Nearest(s, v.Px, v.Py);
|
||||
if (g >= 0 && dist[g] <= MaxGuideUnits)
|
||||
{
|
||||
var (gx, gy, gz) = Local(m[g].P);
|
||||
sink.Line(px, pz + Lift + 0.05f, py, gx, gy, gz, LineThick, GuideColor);
|
||||
}
|
||||
}
|
||||
|
||||
int rings = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
if (!drawn[i]) continue;
|
||||
var (x, y, z) = Local(m[i].P);
|
||||
bool next = i == v.Next;
|
||||
bool step = m[i].Kind != MarkKind.Waypoint;
|
||||
uint color = next ? NextColor : ColorOf(m[i].Kind);
|
||||
sink.Ring(x, y, z, step ? StepRadius : next ? WaypointRadius * 1.2f : WaypointRadius, step || next ? RingThick * 1.4f : RingThick, color);
|
||||
rings++;
|
||||
}
|
||||
|
||||
int lines = 0;
|
||||
for (int i = 0; i + 1 < m.Length && lines < MaxLines; i++)
|
||||
{
|
||||
if (!m[i].LineToNext) continue;
|
||||
// A line when either end is drawn and the other isn't far off.
|
||||
if (!(drawn[i] || drawn[i + 1]) || Math.Min(dist[i], dist[i + 1]) > WaypointRange) continue;
|
||||
var (ax, ay, az) = Local(m[i].P);
|
||||
var (bx, by, bz) = Local(m[i + 1].P);
|
||||
sink.Line(ax, ay, az, bx, by, bz, LineThick, LineColor);
|
||||
lines++;
|
||||
}
|
||||
|
||||
if (v.Labels)
|
||||
{
|
||||
int tris = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
if (!drawn[i] || m[i].Label.Length == 0 || dist[i] > LabelRange) continue;
|
||||
var (x, y, z) = Local(m[i].P);
|
||||
if (!Nav3DText.Emit(x, y, z, m[i].Label, 0, ColorOf(m[i].Kind), px, py, sink, ref tris, MaxLabelTriangles)) break;
|
||||
}
|
||||
}
|
||||
return rings;
|
||||
}
|
||||
|
||||
public static uint ColorOf(MarkKind k) => k switch
|
||||
{
|
||||
MarkKind.Portal => PortalColor,
|
||||
MarkKind.Recall => RecallColor,
|
||||
MarkKind.Town => TownColor,
|
||||
MarkKind.Goal => GoalColor,
|
||||
_ => WaypointColor,
|
||||
};
|
||||
}
|
||||
|
|
@ -8,7 +8,11 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// Where a character's personal recalls land. The client is never told (the server keeps
|
||||
// a character's lifestone, ties, last portal and house), so RynthNav learns them from what
|
||||
// it sees: the server's messages ("You have attuned your spirit to this Lifestone.", "X is
|
||||
// recalling home.") and the teleport that follows. Saved per character in
|
||||
// recalling home.") and the teleport that follows, and a teleport right after your own spell
|
||||
// words (a recall cast by hand: RecallPlanner.GuessHandCast). ACE sends a character neither
|
||||
// its tie positions (PlayerDescription carries only LastOutsideDeath) nor the tied portals'
|
||||
// data ids (LinkedPortalOne/Two aren't SendOnLogin and change silently), so a tie made
|
||||
// before RynthNav was there is learned on the first cast of its recall. Saved per character in
|
||||
// NavData\recalls.txt. No host calls: the offline tests compile this file.
|
||||
// (GoArrow kept the same kind of per-character recall list; Digero 2006, Virindi 2011, MIT.)
|
||||
|
||||
|
|
@ -61,6 +65,9 @@ internal enum RecallEvent
|
|||
RecallingHometown,
|
||||
/// <summary>"Name is recalling to the marketplace." (lands in a dungeon: never used for routes).</summary>
|
||||
RecallingMarketplace,
|
||||
/// <summary>"You say, "Zojak Ququ"" on the spellcasting channel: you started casting a spell
|
||||
/// (a recall cast by hand teleports a few seconds later).</summary>
|
||||
OwnSpellWords,
|
||||
}
|
||||
|
||||
internal sealed class RecallMemory
|
||||
|
|
@ -108,15 +115,21 @@ internal sealed class RecallMemory
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>ChatMessageType.Spellcasting: the words a caster speaks (yours: "You say, "...").</summary>
|
||||
public const int ChatTypeSpellcasting = 17;
|
||||
|
||||
/// <summary>
|
||||
/// Reads a chat line (the server's own wording, ACE's Player_Location / Lifestone /
|
||||
/// WorldObject_Magic). <paramref name="playerName"/> picks out your own "is recalling"
|
||||
/// lines from other players' nearby.
|
||||
/// lines from other players' nearby. <paramref name="chatType"/> tells your spell words
|
||||
/// (Spellcasting, 17) from something you typed in local chat (Speech, 2).
|
||||
/// </summary>
|
||||
public static RecallEvent Classify(string? text, string? playerName)
|
||||
public static RecallEvent Classify(string? text, string? playerName, int chatType = -1)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return RecallEvent.None;
|
||||
string t = text.Trim();
|
||||
if (chatType == ChatTypeSpellcasting && t.StartsWith("You say, \"", StringComparison.Ordinal))
|
||||
return RecallEvent.OwnSpellWords;
|
||||
if (t.StartsWith("You have attuned your spirit to this Lifestone", StringComparison.OrdinalIgnoreCase))
|
||||
return RecallEvent.AttunedLifestone;
|
||||
if (t.StartsWith("You have successfully linked with the life stone", StringComparison.OrdinalIgnoreCase))
|
||||
|
|
|
|||
|
|
@ -71,13 +71,13 @@ internal static class RecallPlanner
|
|||
if (known != null)
|
||||
{
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone,
|
||||
"cast Lifestone Tie on a lifestone");
|
||||
"cast Lifestone Tie on a lifestone, cast Lifestone Recall once, or /rnav tie lifestone at the tied lifestone");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PortalRecall, "Portal Recall", RecallSlot.LastPortal,
|
||||
"walk through a portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1,
|
||||
"cast Primary Portal Tie on a portal");
|
||||
"cast Primary Portal Tie on a portal, cast Primary Portal Tie Recall once, or /rnav tie 1 at the tied portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2,
|
||||
"cast Secondary Portal Tie on a portal");
|
||||
"cast Secondary Portal Tie on a portal, cast Secondary Portal Tie Recall once, or /rnav tie 2 at the tied portal");
|
||||
}
|
||||
|
||||
// Command recalls (no spell): @lifestone always; house, mansion and hometown
|
||||
|
|
@ -123,6 +123,115 @@ internal static class RecallPlanner
|
|||
|
||||
private static string Where(RecallSpot s) => s.Label.Length > 0 ? "in " + s.Label : "in a dungeon";
|
||||
|
||||
// ── Learning from a recall cast by hand ──────────────────────────────────
|
||||
|
||||
/// <summary>Recall the Sanctuary (Lifestone Sending): lands where @lifestone does.</summary>
|
||||
public const int RecallTheSanctuary = 2023;
|
||||
/// <summary>WeenieError YouMustLinkToLifestoneToRecall / YouMustLinkToPortalToRecall.</summary>
|
||||
public const uint ErrorMustLinkLifestone = 0x049E, ErrorMustLinkPortal = 0x04A3;
|
||||
|
||||
/// <summary>What a teleport right after your own spell words teaches.</summary>
|
||||
public enum HandCast
|
||||
{
|
||||
/// <summary>Nothing new (already known, a fixed recall, or can't tell); <c>why</c> says which.</summary>
|
||||
Nothing,
|
||||
/// <summary>The landing of <c>slot</c>.</summary>
|
||||
Learn,
|
||||
/// <summary>A portal tie recall, but not which: ask (/rnav tie 1|2).</summary>
|
||||
AskTie,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// You spoke spell words, stood still and were teleported: a recall cast by hand. Which
|
||||
/// one, from where it landed: on a lifestone, Lifestone Recall; anywhere else, a portal tie
|
||||
/// recall (Portal Recall's landing is the last portal's, already known). A landing that
|
||||
/// matches a recall already known teaches nothing. When the spellbook leaves more than one
|
||||
/// tie recall (or Portal Recall with no last portal known), ask. No host calls.
|
||||
/// </summary>
|
||||
/// <param name="atLifestone">The landing is on a lifestone (the Atlas's).</param>
|
||||
/// <param name="nearUnits">Two landings this close are the same place.</param>
|
||||
public static HandCast GuessHandCast(RecallSpot landing, bool atLifestone, ISet<int>? known, RecallMemory memory,
|
||||
string charKey, double nearUnits, out RecallSlot slot, out string why)
|
||||
{
|
||||
slot = RecallSlot.Lifestone;
|
||||
if (known == null) { why = "the spellbook isn't read yet"; return HandCast.Nothing; }
|
||||
if (atLifestone)
|
||||
{
|
||||
if (!known.Contains(LifestoneRecall)) { why = "on a lifestone, but Lifestone Recall isn't in the spellbook"; return HandCast.Nothing; }
|
||||
if (Same(memory.Get(charKey, RecallSlot.Lifestone), landing, nearUnits)) { why = "Lifestone Recall, already known"; return HandCast.Nothing; }
|
||||
if (known.Contains(RecallTheSanctuary) && Same(memory.Get(charKey, RecallSlot.Sanctuary), landing, nearUnits))
|
||||
{ why = "on your @lifestone lifestone: Lifestone Recall or Recall the Sanctuary, can't tell"; return HandCast.Nothing; }
|
||||
why = "on a lifestone: Lifestone Recall";
|
||||
return HandCast.Learn;
|
||||
}
|
||||
if (Same(memory.Get(charKey, RecallSlot.LastPortal), landing, nearUnits)) { why = "where the last portal went: Portal Recall"; return HandCast.Nothing; }
|
||||
var ties = new List<RecallSlot>(2);
|
||||
if (known.Contains(PrimaryPortalTieRecall)) ties.Add(RecallSlot.Tie1);
|
||||
if (known.Contains(SecondaryPortalTieRecall)) ties.Add(RecallSlot.Tie2);
|
||||
foreach (RecallSlot t in ties)
|
||||
if (Same(memory.Get(charKey, t), landing, nearUnits)) { slot = t; why = RecallMemory.SlotName(t) + ", already known"; return HandCast.Nothing; }
|
||||
if (ties.Count == 0) { why = "no portal tie recall in the spellbook (a spell's teleport RynthNav doesn't know)"; return HandCast.Nothing; }
|
||||
bool maybePortalRecall = known.Contains(PortalRecall) && memory.Get(charKey, RecallSlot.LastPortal) == null;
|
||||
if (ties.Count == 1 && !maybePortalRecall)
|
||||
{
|
||||
slot = ties[0];
|
||||
why = "the only portal tie recall in the spellbook";
|
||||
return HandCast.Learn;
|
||||
}
|
||||
slot = ties[0];
|
||||
why = maybePortalRecall ? "a portal tie recall or Portal Recall (no last portal known yet)" : "a portal tie recall, primary or secondary";
|
||||
return HandCast.AskTie;
|
||||
}
|
||||
|
||||
/// <summary>Two landings are the same place: on the map within <paramref name="nearUnits"/>; off it, the same label.</summary>
|
||||
public static bool Same(RecallSpot? a, RecallSpot b, double nearUnits)
|
||||
{
|
||||
if (a == null || a.OnMap != b.OnMap) return false;
|
||||
if (a.OnMap) return NavCoords.Distance(a.Ns, a.Ew, b.Ns, b.Ew) < nearUnits;
|
||||
return a.Label.Equals(b.Label, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The recall the server says isn't linked: "You must link to a lifestone to recall it" is
|
||||
/// always Lifestone Recall; "...to a portal..." is whichever portal recall was just cast
|
||||
/// (<paramref name="castSpell"/>, 0 = not known: nothing).
|
||||
/// </summary>
|
||||
public static RecallSlot? SlotUnlinked(uint error, int castSpell) => error switch
|
||||
{
|
||||
ErrorMustLinkLifestone => RecallSlot.Lifestone,
|
||||
ErrorMustLinkPortal => castSpell switch
|
||||
{
|
||||
PrimaryPortalTieRecall => RecallSlot.Tie1,
|
||||
SecondaryPortalTieRecall => RecallSlot.Tie2,
|
||||
PortalRecall => RecallSlot.LastPortal,
|
||||
_ => null,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>The recall spell whose landing a slot holds (0 for the command recalls).</summary>
|
||||
public static int SpellFor(RecallSlot slot) => slot switch
|
||||
{
|
||||
RecallSlot.Lifestone => LifestoneRecall,
|
||||
RecallSlot.LastPortal => PortalRecall,
|
||||
RecallSlot.Tie1 => PrimaryPortalTieRecall,
|
||||
RecallSlot.Tie2 => SecondaryPortalTieRecall,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>A slot's name for players ("Primary Portal Tie Recall", "@lifestone").</summary>
|
||||
public static string Title(RecallSlot slot) => slot switch
|
||||
{
|
||||
RecallSlot.Sanctuary => "@lifestone",
|
||||
RecallSlot.Lifestone => "Lifestone Recall",
|
||||
RecallSlot.LastPortal => "Portal Recall",
|
||||
RecallSlot.Tie1 => "Primary Portal Tie Recall",
|
||||
RecallSlot.Tie2 => "Secondary Portal Tie Recall",
|
||||
RecallSlot.House => "House recall",
|
||||
RecallSlot.Mansion => "Allegiance mansion recall",
|
||||
_ => "Allegiance hometown recall",
|
||||
};
|
||||
|
||||
public static List<RecallLink> Links(List<RecallOption> options)
|
||||
{
|
||||
var links = new List<RecallLink>(options.Count);
|
||||
|
|
|
|||
|
|
@ -42,6 +42,13 @@
|
|||
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Text in the world on the Nav3D buffer (the path markers' labels; RynthAi's waypoint labels use it too). -->
|
||||
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
|
||||
<!-- Install folders (RynthAi's NavProfiles, where "save as nav route" writes). Read only. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- RynthAi's own nav file reader/writer (uTank2 NAV 1.2), so a saved route is written exactly
|
||||
the way RynthAi writes its own. Self-contained (System.IO only). -->
|
||||
<Compile Include="..\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Shared\NavRouteParser.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -48,18 +48,9 @@ public sealed partial class RynthNavPlugin
|
|||
_nextAvoidMs = now + AvoidRefreshMs;
|
||||
if (!_avoidPortals) { _avoid.Clear(); return; }
|
||||
|
||||
Atlas atlas = _atlas;
|
||||
if (!ReferenceEquals(atlas, _avoidAtlas))
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name));
|
||||
_atlasPortals = list;
|
||||
_avoidAtlas = atlas;
|
||||
}
|
||||
IReadOnlyList<PortalAvoid.Spot> atlasPortals = AtlasPortalSpots();
|
||||
var map = new List<PortalAvoid.Spot>();
|
||||
foreach (PortalAvoid.Spot sp in _atlasPortals)
|
||||
foreach (PortalAvoid.Spot sp in atlasPortals)
|
||||
if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp);
|
||||
|
||||
var live = new List<PortalAvoid.Spot>();
|
||||
|
|
|
|||
109
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs
Normal file
109
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
using System;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Running into a wall: the walk is running but the character isn't moving. The navmesh is baked
|
||||
// with a 2 m agent radius (RynthNav.Baker), which seals gaps under ~4 m and leaves some ground in
|
||||
// little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs
|
||||
// out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the
|
||||
// mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked
|
||||
// for StuckWindowMs = turn away at an angle (alternating sides), plan again, and after
|
||||
// StuckMaxTries on one leg without progress stop and say where.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long StuckWindowMs = 1200; // running this long...
|
||||
private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s)
|
||||
private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning)
|
||||
private const double UnstickAngleDeg = 120.0; // away from where it was heading, off to one side
|
||||
private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop
|
||||
|
||||
private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place)
|
||||
private double _lastDriveDeg;
|
||||
private long _stuckWinMs, _unstickUntilMs;
|
||||
private double _stuckWx, _stuckWy, _unstickDeg;
|
||||
private int _stuckTries, _stuckSide = 1;
|
||||
|
||||
/// <summary>DriveTo for the walk's own steering: remembers that it ran and which way.</summary>
|
||||
private void WalkDrive(double deg)
|
||||
{
|
||||
DriveTo(deg);
|
||||
_lastDriveDeg = deg;
|
||||
_ranLastTick = !_turnInPlace;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nothing between here and (<paramref name="tx"/>, <paramref name="ty"/>) as far as the navmesh
|
||||
/// shows: every metre of the line, bar 2 m at each end (we and a portal stand off the eroded
|
||||
/// mesh), is within 1.5 m of walkable ground. A wall leaves a gap of twice the agent radius plus
|
||||
/// its thickness, over 4 m, so its middle fails. No query (no tiles): true, as before.
|
||||
/// </summary>
|
||||
private bool StraightOnMesh(double tx, double ty)
|
||||
{
|
||||
if (_query == null) return true;
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
double dx = tx - _wx, dy = ty - _wy, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
for (double s = 2.0; s < len - 2.0; s += 1.0)
|
||||
{
|
||||
var pt = new RcVec3f((float)(_wx + dx * s / len), (float)_wz, (float)(_wy + dy * s / len));
|
||||
_query.FindNearestPoly(pt, new RcVec3f(1.5f, 4, 1.5f), filter, out long r, out _, out _);
|
||||
if (r == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A new leg (or goto): nothing blocked yet.</summary>
|
||||
private void ResetBlocked()
|
||||
{
|
||||
_ranLastTick = false;
|
||||
_stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once per walking tick, before steering. True when it drove this tick (stepping round
|
||||
/// something) or finished the goto; the caller returns.
|
||||
/// </summary>
|
||||
private bool StepBlocked()
|
||||
{
|
||||
long now = NowMs;
|
||||
bool ran = _ranLastTick;
|
||||
_ranLastTick = false;
|
||||
if (_unstickUntilMs > now)
|
||||
{
|
||||
DriveTo(_unstickDeg);
|
||||
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
|
||||
return true;
|
||||
}
|
||||
if (_unstickUntilMs != 0)
|
||||
{
|
||||
// Stepped aside: plan again from here (and allow one more push where the plan ends).
|
||||
_unstickUntilMs = 0;
|
||||
lock (_gotoGate) _gotoPath = null;
|
||||
_blindTicks = 0; _replanTick = 0;
|
||||
_stuckWinMs = 0;
|
||||
return false;
|
||||
}
|
||||
if (!ran || _stuckWinMs == 0) { _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; return false; }
|
||||
if (now - _stuckWinMs < StuckWindowMs) return false;
|
||||
double moved = Math.Sqrt((_wx - _stuckWx) * (_wx - _stuckWx) + (_wy - _stuckWy) * (_wy - _stuckWy));
|
||||
_stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy;
|
||||
if (moved >= StuckMoveUnits) return false;
|
||||
|
||||
string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx));
|
||||
if (++_stuckTries > StuckMaxTries)
|
||||
{
|
||||
string why; lock (_gate) why = _status;
|
||||
FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})");
|
||||
return true;
|
||||
}
|
||||
_stuckSide = -_stuckSide;
|
||||
_unstickDeg = ((_lastDriveDeg + 180.0 - _stuckSide * (180.0 - UnstickAngleDeg)) % 360.0 + 360.0) % 360.0;
|
||||
_unstickUntilMs = now + UnstickMs;
|
||||
Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); "
|
||||
+ $"turning to {_unstickDeg:F0} and planning again ({_stuckTries}/{StuckMaxTries})");
|
||||
DriveTo(_unstickDeg);
|
||||
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
220
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs
Normal file
220
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The planned trip on the ground: RynthNav's path markers (PathMarkers), drawn on the engine's
|
||||
// Nav3D buffer the way RynthAi draws its nav routes. When Route or Go plans a trip, a worker works
|
||||
// out the whole walk ahead of time (TilePathFinder: the route graph and the tiles, in its own
|
||||
// navmesh), and the markers show it: rings at the waypoints near you, lines between them, the
|
||||
// portal / recall / Town Network / goal markers in their own colours, and (switches) labels on
|
||||
// those and a guide line from your feet to the next waypoint. The same path is what "save as nav
|
||||
// route" writes (RynthNavPlugin.SaveRoute.cs).
|
||||
//
|
||||
// The markers go away when the trip ends (arrived, stopped), is cancelled (Stop, the d-pad), or you
|
||||
// land in a landblock that isn't on it (a teleport elsewhere). Switches in rynthnav.json
|
||||
// (markers, markerLabels, markerGuide); /rnav markers and the panel's Go tab change them.
|
||||
//
|
||||
// Threads: everything here runs on the tick, except the path worker, which reads only the frozen
|
||||
// trip (PlannedTrip), the immutable route graph and Atlas portal list, and the tile files. The
|
||||
// emit reads only the frozen MarkerSnapshot, never the trip, the route or the walker.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private volatile bool _markersOn = true, _markerLabels = true, _markerGuide;
|
||||
|
||||
// The last trip planned (Route or Go): kept for "save as nav route" after it ends.
|
||||
private volatile PlannedTrip? _trip;
|
||||
private int _tripSeq;
|
||||
private volatile bool _tripShown; // its markers are on the ground (not ended / cancelled / left)
|
||||
private TripPath? _tripPath; // its path, once worked out
|
||||
private Task<(TripPath Path, long Ms, int Tiles)>? _pathTask;
|
||||
private PlannedTrip? _pathTaskTrip;
|
||||
private string _nextEnterPortal = "", _enterPortal = "";
|
||||
|
||||
// Markers (tick thread).
|
||||
private MarkerSnapshot _markerSnap = MarkerSnapshot.Empty;
|
||||
private PlannedTrip? _snapTrip;
|
||||
private TripPath? _snapPath;
|
||||
private int _markNext = -1, _markStep = -2, _markTrip;
|
||||
private uint _markLb;
|
||||
private HostMarkerSink? _markerSink;
|
||||
private volatile string _markerStatus = "";
|
||||
|
||||
private void LoadMarkerSettings()
|
||||
{
|
||||
_markersOn = NavDataConfig.ReadSwitch("markers", true);
|
||||
_markerLabels = NavDataConfig.ReadSwitch("markerLabels", true);
|
||||
_markerGuide = NavDataConfig.ReadSwitch("markerGuide", false);
|
||||
}
|
||||
|
||||
// ── The trip ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread.</summary>
|
||||
private void SetTrip(List<RouteStep>? steps, string goal, double goalNs, double goalEw, List<RecallOption>? recalls,
|
||||
string enterName, bool live)
|
||||
{
|
||||
var tr = new List<TripRecall>();
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds));
|
||||
_trip = new PlannedTrip(++_tripSeq, steps ?? new List<RouteStep>(), goal, goalNs, goalEw,
|
||||
IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr,
|
||||
enterName.Length > 0 ? _enterPortal : "", enterName, live);
|
||||
_tripPath = null;
|
||||
_tripShown = true;
|
||||
_markNext = -1; _markStep = -2;
|
||||
_markLb = CurrentLandblock;
|
||||
_saveConflict = "";
|
||||
_saveDefault = NavRouteExport.SafeName("To " + goal);
|
||||
if (_markersOn) StartPathBuild();
|
||||
_markerStatus = "working out the path…";
|
||||
}
|
||||
|
||||
/// <summary>Takes the markers off the ground (the trip stays for "save as nav route"). Tick thread.</summary>
|
||||
private void HideMarkers(string why)
|
||||
{
|
||||
if (!_tripShown) return;
|
||||
_tripShown = false;
|
||||
_markNext = -1;
|
||||
_markerStatus = why;
|
||||
Host.Log($"[RynthNav] path markers: off ({why})");
|
||||
}
|
||||
|
||||
private void StartPathBuild()
|
||||
{
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null || (_tripPath != null && _tripPath.TripId == trip.Id)) return;
|
||||
if (_pathTask != null && ReferenceEquals(_pathTaskTrip, trip)) return;
|
||||
NavGraph? g = UsableGraph();
|
||||
IReadOnlyList<PortalAvoid.Spot> portals = AtlasPortalSpots();
|
||||
TownNet? net = _townNet;
|
||||
string dir = NavDataDir;
|
||||
_pathTaskTrip = trip;
|
||||
_pathTask = Task.Run(() =>
|
||||
{
|
||||
long t0 = Environment.TickCount64;
|
||||
var finder = new TilePathFinder(dir, g, portals);
|
||||
TripPath p = TripPathBuilder.Build(trip,
|
||||
(WorldPt a, WorldPt b, bool intoPortal, out string note) => finder.Walk(a, b, intoPortal, out note), net);
|
||||
return (p, Environment.TickCount64 - t0, finder.TilesRead);
|
||||
});
|
||||
}
|
||||
|
||||
private void TakePathResult()
|
||||
{
|
||||
if (_pathTask is not { IsCompleted: true } task) return;
|
||||
PlannedTrip? forTrip = _pathTaskTrip;
|
||||
_pathTask = null; _pathTaskTrip = null;
|
||||
if (task.IsFaulted)
|
||||
{
|
||||
Host.Log($"[RynthNav] trip path failed: {task.Exception?.GetBaseException().Message}");
|
||||
_markerStatus = "the path couldn't be worked out (see the log)";
|
||||
OnPathReady(forTrip, null);
|
||||
return;
|
||||
}
|
||||
var (path, ms, tiles) = task.Result;
|
||||
if (_trip == null || path.TripId != _trip.Id) { if (_markersOn || _pendingSave != null) StartPathBuild(); return; } // planned for an older trip
|
||||
_tripPath = path;
|
||||
int points = 0;
|
||||
foreach (WorldPt[]? w in path.Walks) points += w?.Length ?? 0;
|
||||
foreach (WorldPt[]? w in path.Hub) points += w?.Length ?? 0;
|
||||
Host.Log($"[RynthNav] trip path to {_trip.Goal}: {points} waypoints over {_trip.Count} step(s), {tiles} tile(s) read, {ms} ms");
|
||||
foreach (string n in path.Notes) Host.Log($"[RynthNav] trip path: {n}");
|
||||
_markerStatus = path.Notes.Count == 0 ? $"{points} waypoints" : $"{points} waypoints; {path.Notes[0]}";
|
||||
OnPathReady(_trip, path);
|
||||
}
|
||||
|
||||
// ── Tick ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void TickMarkers()
|
||||
{
|
||||
TakePathResult();
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null) return;
|
||||
|
||||
// A landblock that isn't on the trip (a teleport somewhere else): the markers go.
|
||||
if (_hasPose && _tripShown)
|
||||
{
|
||||
uint lb = CurrentLandblock;
|
||||
if (lb != _markLb && lb != 0)
|
||||
{
|
||||
_markLb = lb;
|
||||
TownNet? net = _townNet;
|
||||
if (!trip.Covers(lb, _tripPath, net == null ? null : net.Contains))
|
||||
HideMarkers($"landblock 0x{lb:X4} isn't on the trip");
|
||||
}
|
||||
}
|
||||
if (!_markersOn || !_tripShown || !Host.HasNav3D || !_hasPose) return;
|
||||
|
||||
if (!ReferenceEquals(trip, _snapTrip) || !ReferenceEquals(_tripPath, _snapPath))
|
||||
{
|
||||
_snapTrip = trip; _snapPath = _tripPath;
|
||||
_markerSnap = PathMarkers.Build(trip, _tripPath, _townNet);
|
||||
_markNext = -1; _markStep = -2;
|
||||
}
|
||||
MarkerSnapshot snap = _markerSnap;
|
||||
if (snap.Marks.Length == 0) return;
|
||||
if ((_cellId >> 16) == 0 || (Host.HasIsPortaling && Host.IsPortaling())) return;
|
||||
|
||||
// The marker the walk heads for: on the running goto's current step.
|
||||
int next = -1;
|
||||
if (_gotoActive && trip.Live && !_settling)
|
||||
{
|
||||
int step = _route != null ? _routeIdx : 0;
|
||||
if (step != _markStep || snap.TripId != _markTrip) { _markStep = step; _markTrip = snap.TripId; _markNext = -1; }
|
||||
_markNext = next = PathMarkers.Advance(snap, _markNext, step, _wx, _wy);
|
||||
}
|
||||
var view = new MarkerView(_wx, _wy, _wz, next, _markerLabels && Host.HasNav3DTriangle, _markerGuide);
|
||||
try { PathMarkers.Emit(snap, view, _markerSink ??= new HostMarkerSink(Host)); }
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] path markers: {ex.Message}"); }
|
||||
}
|
||||
|
||||
// ── /rnav markers ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/rnav markers [on|off | labels on|off | guide on|off]</summary>
|
||||
private void CmdMarkers(string rest)
|
||||
{
|
||||
string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (a.Length == 1 && a[0] is "on" or "off")
|
||||
{
|
||||
_markersOn = a[0] == "on";
|
||||
NavDataConfig.WriteSwitch("markers", _markersOn);
|
||||
if (_markersOn) StartPathBuild();
|
||||
}
|
||||
else if (a.Length == 2 && a[0] == "labels" && a[1] is "on" or "off")
|
||||
{ _markerLabels = a[1] == "on"; NavDataConfig.WriteSwitch("markerLabels", _markerLabels); }
|
||||
else if (a.Length == 2 && a[0] == "guide" && a[1] is "on" or "off")
|
||||
{ _markerGuide = a[1] == "on"; NavDataConfig.WriteSwitch("markerGuide", _markerGuide); }
|
||||
else if (a.Length > 0) { Say("/rnav markers on|off, markers labels on|off, markers guide on|off"); return; }
|
||||
Say($"path markers {(_markersOn ? "ON" : "OFF")}, labels {(_markerLabels ? "on" : "off")}, guide line {(_markerGuide ? "on" : "off")}"
|
||||
+ (_trip == null ? "" : _tripShown ? $" — showing the trip to {_trip.Goal}" : $" — the trip to {_trip.Goal} isn't shown ({_markerStatus})"));
|
||||
}
|
||||
|
||||
/// <summary>The Atlas's portals on the map (positions to 0.01 degree): the circles a walk keeps out of. Tick thread.</summary>
|
||||
private IReadOnlyList<PortalAvoid.Spot> AtlasPortalSpots()
|
||||
{
|
||||
Atlas atlas = _atlas;
|
||||
if (!ReferenceEquals(atlas, _avoidAtlas))
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name));
|
||||
_atlasPortals = list;
|
||||
_avoidAtlas = atlas;
|
||||
}
|
||||
return _atlasPortals;
|
||||
}
|
||||
|
||||
/// <summary>The engine's Nav3D buffer (the engine clears it each tick; every plugin adds to it).</summary>
|
||||
private sealed class HostMarkerSink : IMarkerSink
|
||||
{
|
||||
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
|
||||
public HostMarkerSink(RynthCore.PluginSdk.RynthCoreHost host) => _host = host;
|
||||
public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => _host.Nav3DAddRing(x, y, z, radius, thickness, colorArgb);
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
=> _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb);
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb)
|
||||
=> _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb);
|
||||
}
|
||||
}
|
||||
|
|
@ -114,13 +114,14 @@ public sealed partial class RynthNavPlugin
|
|||
long now = NowMs;
|
||||
if (landblockChanged && _hasPose)
|
||||
{
|
||||
try { _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; }
|
||||
// A dungeon's tile is its landblock's surface: no navmesh here (RynthNavPlugin.InDungeon).
|
||||
try { _tileHere = !InDungeon(_cellId) && File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; }
|
||||
}
|
||||
if (now < _nextInfoMs || now - Interlocked.Read(ref _lastStatusPollMs) > PanelPollWindowMs) return;
|
||||
_nextInfoMs = now + InfoRefreshMs;
|
||||
if (Interlocked.Exchange(ref _infoBusy, 1) != 0) return;
|
||||
uint lb = CurrentLandblock;
|
||||
bool hasPose = _hasPose;
|
||||
bool hasPose = _hasPose, dungeon = InDungeon(_cellId);
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
|
|
@ -129,7 +130,7 @@ public sealed partial class RynthNavPlugin
|
|||
if (Directory.Exists(NavDataDir))
|
||||
foreach (string _ in Directory.EnumerateFiles(NavDataDir, "nav_*.tile")) n++;
|
||||
_tilesOnDisk = n;
|
||||
if (hasPose) _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0;
|
||||
if (hasPose) _tileHere = !dungeon && File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0;
|
||||
}
|
||||
catch { }
|
||||
finally { Interlocked.Exchange(ref _infoBusy, 0); }
|
||||
|
|
@ -152,6 +153,14 @@ public sealed partial class RynthNavPlugin
|
|||
.Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0)
|
||||
.Append(",\"onDisk\":").Append(_tilesOnDisk)
|
||||
.Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}");
|
||||
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+.
|
||||
PlannedTrip? trip = _trip;
|
||||
sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0)
|
||||
.Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0)
|
||||
.Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}");
|
||||
sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? ""))
|
||||
.Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict))
|
||||
.Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}");
|
||||
}
|
||||
|
||||
// ── The character's own recall spots, for the Recalls section (travel JSON) ──
|
||||
|
|
|
|||
100
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs
Normal file
100
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// "Save as nav route": the last trip RynthNav planned (Route or Go) written as a RynthAi nav route
|
||||
// (NavRouteExport) into RynthAi's NavProfiles folder, where RynthAi's route picker lists it
|
||||
// (RynthAi re-reads the folder when it changes) and /ra nav load <name> loads it.
|
||||
// /rnav saveroute [name] [overwrite] (the panel: the name box and Save on the Go tab)
|
||||
// No name: "To <the place>". An existing file is never replaced without "overwrite" (the panel
|
||||
// then offers Replace). The path is the one the markers show; if it isn't worked out yet, it is
|
||||
// first, and the save follows when it's done. Tick thread, except the file write (a worker).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
/// <summary>RynthAi's route folder (what its Nav picker lists): <RynthSuite>\RynthAi\NavProfiles.</summary>
|
||||
private static string NavProfilesDir => Path.Combine(RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
|
||||
private (int TripId, string Name, bool Overwrite)? _pendingSave;
|
||||
// For the panel (any thread reads them).
|
||||
private volatile string _saveDefault = "", _saveConflict = "", _saveLast = "";
|
||||
private volatile bool _saveBusy;
|
||||
|
||||
/// <summary>/rnav saveroute [name] [overwrite]</summary>
|
||||
private void CmdSaveRoute(string rest)
|
||||
{
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null) { Note("saveroute: plan a trip first (Route or Go), then save it"); return; }
|
||||
string text = rest.Trim();
|
||||
bool overwrite = false;
|
||||
if (text.Equals("overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = ""; }
|
||||
else if (text.EndsWith(" overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = text[..^10].TrimEnd(); }
|
||||
if (text.Length == 0) text = _saveDefault.Length > 0 ? _saveDefault : NavRouteExport.SafeName("To " + trip.Goal);
|
||||
string name = NavRouteExport.FileName(text, out string error);
|
||||
if (name.Length == 0) { Note("saveroute: " + error); return; }
|
||||
|
||||
if (!overwrite && File.Exists(Path.Combine(NavProfilesDir, name + ".nav")))
|
||||
{
|
||||
_saveConflict = name;
|
||||
Note($"saveroute: {name}.nav is already in RynthAi's NavProfiles; /rnav saveroute {name} overwrite replaces it");
|
||||
return;
|
||||
}
|
||||
_saveConflict = "";
|
||||
if (_tripPath != null && _tripPath.TripId == trip.Id) { WriteRoute(trip, _tripPath, name, overwrite); return; }
|
||||
_pendingSave = (trip.Id, name, overwrite);
|
||||
StartPathBuild();
|
||||
_saveBusy = true;
|
||||
Note($"saveroute: working out the path to {trip.Goal} first…");
|
||||
}
|
||||
|
||||
/// <summary>The trip's path is in (or failed: null): a save waiting for it goes ahead. Tick thread.</summary>
|
||||
private void OnPathReady(PlannedTrip? trip, TripPath? path)
|
||||
{
|
||||
if (_pendingSave is not { } ps || trip == null || ps.TripId != trip.Id) return;
|
||||
_pendingSave = null;
|
||||
_saveBusy = false;
|
||||
if (path == null) { Note("saveroute: the path couldn't be worked out, so nothing was saved (see the log)"); return; }
|
||||
WriteRoute(trip, path, ps.Name, ps.Overwrite);
|
||||
}
|
||||
|
||||
private void WriteRoute(PlannedTrip trip, TripPath path, string name, bool overwrite)
|
||||
{
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, _townNet);
|
||||
if (r.Route.Points.Count == 0)
|
||||
{
|
||||
Note($"saveroute: nothing to save: {(r.StopReason.Length > 0 ? r.StopReason : "the trip has no steps")}");
|
||||
return;
|
||||
}
|
||||
string folder = NavProfilesDir;
|
||||
string goal = trip.Goal;
|
||||
int notes = path.Notes.Count;
|
||||
string firstNote = notes > 0 ? path.Notes[0] : "";
|
||||
_saveBusy = true;
|
||||
Task.Run(() =>
|
||||
{
|
||||
string line;
|
||||
bool ok = NavRouteExport.Save(folder, name, r.Route, overwrite, out string file, out bool exists, out string error);
|
||||
if (ok)
|
||||
{
|
||||
line = $"saveroute: saved {name}.nav to {folder}: {r.Route.Points.Count} steps ({r.Waypoints} waypoints"
|
||||
+ (r.Portals > 0 ? $", {r.Portals} portal(s)" : "") + (r.Recalls + r.Chats > 0 ? $", {r.Recalls + r.Chats} recall(s)" : "")
|
||||
+ $"). RynthAi: pick it in Nav, or /ra nav load {name}.";
|
||||
if (r.StoppedAt >= 0) line += $" It stops short of {goal}: {r.StopReason}.";
|
||||
if (notes > 0) line += $" Check it: {firstNote}{(notes > 1 ? $" (+{notes - 1} more in the log)" : "")}.";
|
||||
_saveConflict = "";
|
||||
Host.Log($"[RynthNav] {line} ({file})");
|
||||
}
|
||||
else if (exists)
|
||||
{
|
||||
_saveConflict = name;
|
||||
line = $"saveroute: {name}.nav is already there; /rnav saveroute {name} overwrite replaces it";
|
||||
}
|
||||
else line = $"saveroute: couldn't write {name}.nav: {error}";
|
||||
_saveLast = line;
|
||||
_saveBusy = false;
|
||||
Say(line);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -29,6 +29,10 @@ public sealed partial class RynthNavPlugin
|
|||
private const long RecallCastWindowMs = 40000; // our own recall cast -> the teleport within this
|
||||
private const long RecallStepTimeoutMs = 45000; // a route's recall step gives up after this
|
||||
private const long RecallRecastMs = 4500; // re-cast a recall spell this often while waiting
|
||||
private const long HandCastWindowMs = 12000; // your spell words -> portal space within this = a recall cast by hand
|
||||
private const double HandCastStillUnits = 2.0; // ...standing still meanwhile (walking into a portal moves you)
|
||||
private const double LifestoneLandUnits = 10.0; // a landing this close to a lifestone = on it (Lifestone Recall)
|
||||
private const double PortalBesideUnits = 4.0; // a live portal this close as portal space begins: maybe that portal, not a recall
|
||||
private const long StanceRetryMs = 1500;
|
||||
private const long WandAfterMs = 6000; // no magic stance by then: try wielding a wand
|
||||
private const int CombatModeNonCombat = 1, CombatModeMagic = 8;
|
||||
|
|
@ -37,6 +41,7 @@ public sealed partial class RynthNavPlugin
|
|||
private volatile Atlas _atlas = Atlas.Empty;
|
||||
private volatile string _atlasStatus = "loading…";
|
||||
private HashSet<uint> _mapLandblocks = new(); // landblocks with Atlas places on the map (tick thread)
|
||||
private volatile HashSet<uint> _dungeonLandblocks = new(); // dungeon landblocks the Atlas knows (Atlas.DungeonLandblocks; read-only once built)
|
||||
private AtlasStore _store = new();
|
||||
private RecallMemory _memory = new();
|
||||
private bool _storesLoaded;
|
||||
|
|
@ -67,12 +72,18 @@ public sealed partial class RynthNavPlugin
|
|||
private int _castRecallSpell;
|
||||
private long _castRecallMs;
|
||||
private RecallSpot? _pendingTie;
|
||||
// Your own spell words (a recall cast by hand teleports a few seconds later): when and where.
|
||||
private long _selfCastMs;
|
||||
private double _selfCastWx, _selfCastWy;
|
||||
private bool _selfCastDied;
|
||||
private int _weenieSeq = -1; // the last server refusal looked at (-1 = none yet)
|
||||
|
||||
// Teleport tracking (tick thread).
|
||||
private bool _trkPortaling, _trkHaveLast, _trkHavePre;
|
||||
private uint _trkLastCell, _trkPreCell;
|
||||
private double _trkLastWx, _trkLastWy, _trkPreWx, _trkPreWy;
|
||||
private long _trkLastTeleportMs;
|
||||
private long _trkLastTeleportMs, _trkPortalStartMs;
|
||||
private bool _trkPortalBeside; // a live portal stood right beside you as portal space began
|
||||
|
||||
// Route planning with recalls: the recalls the current route can use (by RouteStep.RecallIndex).
|
||||
private List<RecallOption> _routeRecalls = new();
|
||||
|
|
@ -146,7 +157,7 @@ public sealed partial class RynthNavPlugin
|
|||
private void OnLoginTravel()
|
||||
{
|
||||
_charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0;
|
||||
_pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null;
|
||||
_pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; _selfCastMs = 0;
|
||||
_trkHaveLast = false; _trkPortaling = false;
|
||||
}
|
||||
|
||||
|
|
@ -175,6 +186,7 @@ public sealed partial class RynthNavPlugin
|
|||
foreach (var l in atlas.Locations)
|
||||
if (l.OnMap && l.Cell.Length == 8 && uint.TryParse(l.Cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint lb)) lbs.Add(lb);
|
||||
_mapLandblocks = lbs;
|
||||
_dungeonLandblocks = atlas.DungeonLandblocks();
|
||||
_indexedAtlas = atlas;
|
||||
if (_known != null && atlas.Recalls.Count > 0) LogKnownRecalls(_known);
|
||||
}
|
||||
|
|
@ -183,6 +195,10 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd, fromPanel: false);
|
||||
while (_recallEvents.TryDequeue(out var ev)) OnRecallEvent(ev.Event, ev.Ms);
|
||||
PollRecallRefusal();
|
||||
if (_selfCastMs != 0 && !_selfCastDied && now - _selfCastMs < HandCastWindowMs + 30000
|
||||
&& Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0)
|
||||
_selfCastDied = true; // died mid-cast: the trip to the lifestone that follows isn't a recall
|
||||
|
||||
bool teleported = TrackTeleport(now);
|
||||
UpdateArrow(teleported);
|
||||
|
|
@ -250,6 +266,12 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>Outdoors, or in a building of a landblock that has Atlas places on the map.</summary>
|
||||
private bool IsOnMap(uint cell) => (cell & 0xFFFF) < 0x100 || _mapLandblocks.Contains(cell >> 16);
|
||||
|
||||
/// <summary>
|
||||
/// In a dungeon the Atlas knows. Its landblock's tile is the surface's (dungeon cells aren't
|
||||
/// baked), so there is no navmesh to walk here even though nav_XXXX.tile exists.
|
||||
/// </summary>
|
||||
private bool InDungeon(uint cell) => (cell & 0xFFFF) >= 0x100 && _dungeonLandblocks.Contains(cell >> 16);
|
||||
|
||||
// ── Teleports: the arrow's portal/recall steps and learning recall landings ──
|
||||
|
||||
private bool TrackTeleport(long now)
|
||||
|
|
@ -260,6 +282,9 @@ public sealed partial class RynthNavPlugin
|
|||
if (!_trkPortaling)
|
||||
{
|
||||
_trkPortaling = true;
|
||||
_trkPortalStartMs = now;
|
||||
// Only worth the look after your own spell words (a hand-cast recall, or a portal used standing at it?).
|
||||
_trkPortalBeside = _selfCastMs != 0 && now - _selfCastMs < HandCastWindowMs && _trkHaveLast && LivePortalWithin(_trkLastWx, _trkLastWy, PortalBesideUnits);
|
||||
_trkHavePre = _trkHaveLast;
|
||||
_trkPreCell = _trkLastCell; _trkPreWx = _trkLastWx; _trkPreWy = _trkLastWy;
|
||||
}
|
||||
|
|
@ -273,23 +298,32 @@ public sealed partial class RynthNavPlugin
|
|||
bool havePre = _trkPortaling ? _trkHavePre : _trkHaveLast;
|
||||
uint preCell = _trkPortaling ? _trkPreCell : _trkLastCell;
|
||||
double preWx = _trkPortaling ? _trkPreWx : _trkLastWx, preWy = _trkPortaling ? _trkPreWy : _trkLastWy;
|
||||
long startMs = _trkPortaling ? _trkPortalStartMs : now;
|
||||
bool portalBeside = _trkPortaling && _trkPortalBeside;
|
||||
_trkPortaling = false;
|
||||
if (now - _trkLastTeleportMs > 2000)
|
||||
{
|
||||
teleported = true;
|
||||
_trkLastTeleportMs = now;
|
||||
OnTeleported(havePre, preCell, preWx, preWy);
|
||||
OnTeleported(havePre, preCell, preWx, preWy, startMs, portalBeside);
|
||||
}
|
||||
}
|
||||
_trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy;
|
||||
return teleported;
|
||||
}
|
||||
|
||||
private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy)
|
||||
private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy, long startMs, bool portalBeside)
|
||||
{
|
||||
long now = NowMs;
|
||||
RecallSpot landing = SpotHere();
|
||||
string who = _charKey;
|
||||
// Your spell words shortly before portal space, standing still since, not dead, no portal
|
||||
// right beside you: a recall cast by hand (walking into a portal moves you; using one you
|
||||
// stand at doesn't, hence the portal check; dying is a trip, not a recall).
|
||||
bool handCast = _selfCastMs != 0 && startMs - _selfCastMs >= 0 && startMs - _selfCastMs < HandCastWindowMs
|
||||
&& !_selfCastDied && havePre && !portalBeside
|
||||
&& Math.Sqrt((preWx - _selfCastWx) * (preWx - _selfCastWx) + (preWy - _selfCastWy) * (preWy - _selfCastWy)) < HandCastStillUnits;
|
||||
_selfCastMs = 0; _selfCastDied = false;
|
||||
if (who.Length == 0) return;
|
||||
|
||||
if (_pendingRecallSlot is RecallSlot slot && now - _pendingRecallMs < RecallAnnounceWindowMs)
|
||||
|
|
@ -312,7 +346,17 @@ public sealed partial class RynthNavPlugin
|
|||
RecallPlanner.SecondaryPortalTieRecall => RecallSlot.Tie2,
|
||||
_ => null,
|
||||
};
|
||||
if (learned is RecallSlot ls) _memory.Set(who, ls, landing);
|
||||
if (learned is RecallSlot ls)
|
||||
{
|
||||
_memory.Set(who, ls, landing);
|
||||
Host.Log($"[RynthNav] learned {RecallMemory.SlotName(ls)} lands at {Describe(landing)}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A recall cast by hand (or by another plugin): never the last portal's landing.
|
||||
if (handCast && !CameThroughAtlasPortal(havePre, preCell, preWx, preWy, landing))
|
||||
{
|
||||
LearnHandCast(landing);
|
||||
return;
|
||||
}
|
||||
// Not a recall we know of: a portal, most likely. Portal Recall goes back to where
|
||||
|
|
@ -341,6 +385,101 @@ public sealed partial class RynthNavPlugin
|
|||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A live portal object within <paramref name="units"/> of a world point (this landblock's objects).</summary>
|
||||
private bool LivePortalWithin(double wx, double wy, double units)
|
||||
{
|
||||
if (!Host.HasGetLiveObjectIds) return false;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue;
|
||||
double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
if ((ox - wx) * (ox - wx) + (oy - wy) * (oy - wy) < units * units) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A known portal stood where you were, and goes where you landed: the teleport was that
|
||||
/// portal (used standing at it), not the spell you'd just cast.
|
||||
/// </summary>
|
||||
private bool CameThroughAtlasPortal(bool havePre, uint preCell, double preWx, double preWy, RecallSpot landing)
|
||||
{
|
||||
if (!havePre || !IsOnMap(preCell) || !landing.OnMap) return false;
|
||||
double pns = NavCoords.NsFromWorld(preWy), pew = NavCoords.EwFromWorld(preWx);
|
||||
foreach (AtlasLocation l in _atlas.Locations)
|
||||
{
|
||||
if (!l.OnMap || !l.HasDest || !l.DestOnMap || !l.Type.Equals("Portal", StringComparison.Ordinal)) continue;
|
||||
if (NavCoords.Distance(pns, pew, l.Ns, l.Ew) < PortalNearUnits
|
||||
&& NavCoords.Distance(landing.Ns, landing.Ew, l.DestNs, l.DestEw) < RecallNearUnits) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A recall cast by hand (RynthNav didn't cast it): learn which one from where it landed
|
||||
/// (RecallPlanner.GuessHandCast), so ties made before RynthNav was there, or cast from the
|
||||
/// spell bar, are planned from now on.
|
||||
/// </summary>
|
||||
private void LearnHandCast(RecallSpot landing)
|
||||
{
|
||||
if (landing.OnMap)
|
||||
foreach (AtlasRecall r in _atlas.Recalls)
|
||||
if (r.OnMap && NavCoords.Distance(landing.Ns, landing.Ew, r.Ns, r.Ew) < RecallNearUnits)
|
||||
{
|
||||
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {r.Name}'s landing, nothing to learn");
|
||||
return;
|
||||
}
|
||||
AtlasLocation? ls = landing.OnMap ? _atlas.Nearest("Lifestone", landing.Ns, landing.Ew, LifestoneLandUnits) : null;
|
||||
RecallPlanner.HandCast kind = RecallPlanner.GuessHandCast(landing, ls != null, _known, _memory, _charKey, RecallNearUnits,
|
||||
out RecallSlot slot, out string why);
|
||||
switch (kind)
|
||||
{
|
||||
case RecallPlanner.HandCast.Learn:
|
||||
if (ls != null) landing.Label = ls.Name + (landing.Label.Length > 0 ? " (" + landing.Label + ")" : "");
|
||||
_memory.Set(_charKey, slot, landing);
|
||||
Host.Log($"[RynthNav] learned {RecallMemory.SlotName(slot)} lands at {Describe(landing)} (a recall cast by hand: {why})");
|
||||
Say($"{RecallPlanner.Title(slot)} takes you to {Describe(landing)}: routes can use it now.");
|
||||
break;
|
||||
case RecallPlanner.HandCast.AskTie:
|
||||
_pendingTie = landing;
|
||||
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}; asking which tie");
|
||||
Say($"Recalled to {Describe(landing)}. If that was a portal tie recall: /rnav tie 1 (primary) or /rnav tie 2 (secondary).");
|
||||
break;
|
||||
default:
|
||||
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's "You must link to a lifestone / portal to recall it": that recall has no
|
||||
/// tie (any more), so forget its landing; a route waiting on it plans again without it.
|
||||
/// </summary>
|
||||
private void PollRecallRefusal()
|
||||
{
|
||||
if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint error, out _, out _)) return;
|
||||
if (_weenieSeq < 0 || seq == _weenieSeq) { _weenieSeq = seq; return; } // the first look only notes where the count stands
|
||||
_weenieSeq = seq;
|
||||
int cast = _castRecallSpell != 0 && NowMs - _castRecallMs < RecallCastWindowMs ? _castRecallSpell : 0;
|
||||
if (RecallPlanner.SlotUnlinked(error, cast) is not RecallSlot slot || _charKey.Length == 0) return;
|
||||
bool had = _memory.Get(_charKey, slot) != null;
|
||||
_memory.Clear(_charKey, slot);
|
||||
if (slot == RecallSlot.Tie1 || slot == RecallSlot.Tie2) _pendingTie = null;
|
||||
string name = RecallPlanner.Title(slot);
|
||||
Host.Log($"[RynthNav] {name}: the server says it isn't linked (0x{error:X4}){(had ? "; its landing is forgotten" : "")}");
|
||||
RecallOption? o = _recallWait ? CurrentRecallOption() : null;
|
||||
if (o != null && o.SpellId == RecallPlanner.SpellFor(slot) && _gotoActive)
|
||||
{
|
||||
string goal = _gotoName, type = _gotoType, enter = _enterName, enterType = _enterType;
|
||||
double gns = NavCoords.NsFromWorld(_finalTns), gew = NavCoords.EwFromWorld(_finalTew);
|
||||
Say($"goto: {name} isn't tied to anything; planning again without it");
|
||||
EndRecall();
|
||||
StartWalk(goal.Length > 0 ? goal : NavCoords.Fmt(gns, gew), type, gns, gew, enter, enterType);
|
||||
}
|
||||
else if (had) Say($"{name} isn't tied to anything: routes won't use it until you tie it again.");
|
||||
}
|
||||
|
||||
/// <summary>Where you stand now, as a recall landing: on the map or not, and a label.</summary>
|
||||
private RecallSpot SpotHere()
|
||||
{
|
||||
|
|
@ -362,7 +501,7 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
public override void OnChatWindowText(string? text, int chatType, ref int eat)
|
||||
{
|
||||
RecallEvent e = RecallMemory.Classify(text, _playerName);
|
||||
RecallEvent e = RecallMemory.Classify(text, _playerName, chatType);
|
||||
if (e != RecallEvent.None) _recallEvents.Enqueue((e, NowMs));
|
||||
}
|
||||
|
||||
|
|
@ -396,6 +535,11 @@ public sealed partial class RynthNavPlugin
|
|||
case RecallEvent.RecallingMarketplace:
|
||||
_pendingRecallSlot = null;
|
||||
break;
|
||||
case RecallEvent.OwnSpellWords:
|
||||
// Any spell: only a teleport soon after, standing here, makes it a recall (OnTeleported).
|
||||
if (!_hasPose) break;
|
||||
_selfCastMs = ms; _selfCastWx = _wx; _selfCastWy = _wy; _selfCastDied = false;
|
||||
break;
|
||||
default:
|
||||
if (RecallMemory.SlotFor(e, out RecallSlot slot))
|
||||
{
|
||||
|
|
@ -428,23 +572,42 @@ public sealed partial class RynthNavPlugin
|
|||
return l == null ? null : new RecallSpot { OnMap = true, Ns = l.Ns, Ew = l.Ew, Label = l.Name };
|
||||
}
|
||||
|
||||
private void OnPortalTied()
|
||||
/// <summary>
|
||||
/// The tied portal: the selected portal, looked up in the Atlas by its weenie class (ACE
|
||||
/// ties the portal's class), else the nearest portal in the Atlas within <paramref name="nearUnits"/>.
|
||||
/// </summary>
|
||||
private AtlasLocation? TiePortal(double nearUnits)
|
||||
{
|
||||
// The tied portal's destination: the selected portal, looked up in the Atlas by its
|
||||
// weenie class (ACE ties the portal's class), else the nearest portal in the Atlas.
|
||||
AtlasLocation? portal = null;
|
||||
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
PlayerMapPos(out double pns, out double pew);
|
||||
if (sel != 0 && Host.TryGetObjectWcid(sel, out uint wcid)) portal = _atlas.PortalByWcid(wcid, pns, pew);
|
||||
portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, 60) : null;
|
||||
portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, nearUnits) : null;
|
||||
return portal;
|
||||
}
|
||||
|
||||
private static RecallSpot TieLanding(AtlasLocation portal) => portal.DestOnMap
|
||||
? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name }
|
||||
: new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name };
|
||||
|
||||
/// <summary>/rnav tie 1|2 with no tie waiting: where the portal you've selected or stand at goes.</summary>
|
||||
private RecallSpot? TiedPortalSpot(out string why)
|
||||
{
|
||||
AtlasLocation? portal = TiePortal(PortalNearUnits);
|
||||
why = portal == null ? "select the tied portal, or stand at it, first"
|
||||
: !portal.HasDest ? $"{portal.Name} isn't in the Atlas with a destination" : "";
|
||||
return portal != null && portal.HasDest ? TieLanding(portal) : null;
|
||||
}
|
||||
|
||||
private void OnPortalTied()
|
||||
{
|
||||
AtlasLocation? portal = TiePortal(60);
|
||||
if (portal == null || !portal.HasDest)
|
||||
{
|
||||
Say("Portal tie noted, but the portal isn't in the Atlas: its recall won't be used for routes.");
|
||||
return;
|
||||
}
|
||||
var spot = portal.DestOnMap
|
||||
? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name }
|
||||
: new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name };
|
||||
RecallSpot spot = TieLanding(portal);
|
||||
bool k1 = _known?.Contains(RecallPlanner.PrimaryPortalTie) ?? false, k2 = _known?.Contains(RecallPlanner.SecondaryPortalTie) ?? false;
|
||||
if (k1 && !k2) { _memory.Set(_charKey, RecallSlot.Tie1, spot); Say($"Primary portal tie: {portal.Name}."); return; }
|
||||
if (k2 && !k1) { _memory.Set(_charKey, RecallSlot.Tie2, spot); Say($"Secondary portal tie: {portal.Name}."); return; }
|
||||
|
|
@ -819,9 +982,11 @@ public sealed partial class RynthNavPlugin
|
|||
"/rnav arrow <place|coords> | arrow off | arrow route <place> — the arrow\n" +
|
||||
"/rnav go <place|coords> — walk there (route with portals/recalls when /rnav portals on)\n" +
|
||||
"/rnav route <place|coords> — plan a route (portals and recalls), no walking\n" +
|
||||
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2\n" +
|
||||
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" +
|
||||
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>";
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
|
||||
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
|
||||
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)";
|
||||
|
||||
/// <summary>One /rnav command. Tick thread.</summary>
|
||||
private void RunCommand(string raw, bool fromPanel)
|
||||
|
|
@ -863,6 +1028,8 @@ public sealed partial class RynthNavPlugin
|
|||
break;
|
||||
case "recalls": CmdRecalls(rest); break;
|
||||
case "tie": CmdTie(rest); break;
|
||||
case "markers": CmdMarkers(rest); break;
|
||||
case "saveroute": CmdSaveRoute(rest); break;
|
||||
case "arrive":
|
||||
if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200)
|
||||
{ _arrow.ArriveUnits = yd; Say($"the arrow counts you as arrived within {yd:F0} yd"); }
|
||||
|
|
@ -937,6 +1104,7 @@ public sealed partial class RynthNavPlugin
|
|||
AtlasLocation? portal = Entrance.PortalFor(_atlas, place, hasPos, pns, pew, out string why);
|
||||
if (portal == null) { Note("goto: " + why); return; }
|
||||
ns = portal.Ns; ew = portal.Ew; enter = place.Name; enterType = place.Type;
|
||||
_nextEnterPortal = portal.Name; // the portal object a saved nav route uses (RynthNavPlugin.SaveRoute.cs)
|
||||
}
|
||||
StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't)
|
||||
}
|
||||
|
|
@ -1021,20 +1189,52 @@ public sealed partial class RynthNavPlugin
|
|||
foreach (string n in notes) Say(" " + n);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rnav tie 1|2: which portal tie the last one (or the last tie recall cast by hand) was;
|
||||
/// with none waiting, the portal you have selected or stand at is that tie (a tie made
|
||||
/// before RynthNav was there). /rnav tie lifestone: the lifestone you have selected or
|
||||
/// stand at is the one Lifestone Recall is tied to. /rnav tie clear 1|2|lifestone forgets one.
|
||||
/// </summary>
|
||||
private void CmdTie(string rest)
|
||||
{
|
||||
if (_pendingTie == null || _charKey.Length == 0) { Note("no portal tie waiting — cast a Portal Tie on a portal first"); return; }
|
||||
RecallSlot slot = rest.Trim() == "2" ? RecallSlot.Tie2 : rest.Trim() == "1" ? RecallSlot.Tie1 : (RecallSlot)(-1);
|
||||
if ((int)slot < 0) { Say("/rnav tie 1 (primary) or /rnav tie 2 (secondary)"); return; }
|
||||
_memory.Set(_charKey, slot, _pendingTie);
|
||||
Note($"{(slot == RecallSlot.Tie1 ? "Primary" : "Secondary")} portal tie: {Describe(_pendingTie)}");
|
||||
_pendingTie = null;
|
||||
if (_charKey.Length == 0) { Note("not logged in yet"); return; }
|
||||
string arg = rest.Trim().ToLowerInvariant();
|
||||
bool clear = arg.StartsWith("clear", StringComparison.Ordinal);
|
||||
if (clear) arg = arg.Substring(5).Trim();
|
||||
RecallSlot slot = arg switch
|
||||
{
|
||||
"1" => RecallSlot.Tie1,
|
||||
"2" => RecallSlot.Tie2,
|
||||
"lifestone" or "ls" => RecallSlot.Lifestone,
|
||||
_ => (RecallSlot)(-1),
|
||||
};
|
||||
if ((int)slot < 0) { Say("/rnav tie 1 (primary) | 2 (secondary) | lifestone, or /rnav tie clear 1|2|lifestone"); return; }
|
||||
string name = RecallPlanner.Title(slot);
|
||||
if (clear)
|
||||
{
|
||||
_memory.Clear(_charKey, slot);
|
||||
Note($"{name}: landing forgotten (routes won't use it until it's learned again)");
|
||||
return;
|
||||
}
|
||||
RecallSpot? spot;
|
||||
if (slot == RecallSlot.Lifestone)
|
||||
{
|
||||
// The Atlas lifestone at the selected object (anything else selected doesn't count), else the nearest one.
|
||||
RecallSpot? sel = SelectedObjectSpot(out _);
|
||||
AtlasLocation? ls = sel != null && sel.OnMap ? _atlas.Nearest("Lifestone", sel.Ns, sel.Ew, LifestoneLandUnits) : null;
|
||||
spot = ls != null ? new RecallSpot { OnMap = true, Ns = ls.Ns, Ew = ls.Ew, Label = ls.Name } : NearestAtlasSpot("Lifestone", 40);
|
||||
if (spot == null) { Note("tie lifestone: select your tied lifestone, or stand at it, first"); return; }
|
||||
}
|
||||
else if (_pendingTie != null) { spot = _pendingTie; _pendingTie = null; }
|
||||
else if ((spot = TiedPortalSpot(out string why)) == null) { Note($"tie {arg}: {why}"); return; }
|
||||
_memory.Set(_charKey, slot, spot);
|
||||
Note($"{name}: {Describe(spot)}");
|
||||
}
|
||||
|
||||
/// <summary>Plans a route (portals and, unless off, recalls) and shows it in the panel. Tick thread.</summary>
|
||||
private List<RouteStep>? PlanAndShow(string name, double ns, double ew, out int used, out double est, out string refusal)
|
||||
{
|
||||
TravelPlan.Result plan = PlanRoute(name, ns, ew, out _);
|
||||
TravelPlan.Result plan = PlanRoute(name, ns, ew, out List<RecallOption> recalls);
|
||||
List<RouteStep>? steps = plan.Steps;
|
||||
used = plan.Teleports; est = plan.Est; refusal = plan.Refusal;
|
||||
_shownRoute = steps ?? new List<RouteStep> { new(ns, ew, false, false, "walk") };
|
||||
|
|
@ -1042,6 +1242,7 @@ public sealed partial class RynthNavPlugin
|
|||
_shownRouteEst = est;
|
||||
_shownRouteLive = false;
|
||||
_routeVersion++;
|
||||
if (refusal.Length == 0) SetTrip(steps, name, ns, ew, recalls, "", live: false);
|
||||
return steps;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
public sealed partial class RynthNavPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
|
||||
internal const string PluginVersion = "0.6.5";
|
||||
internal const string PluginVersion = "0.6.6";
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
|
||||
|
||||
// Where the tiles, portals.tsv, locations.json and the player's atlas.txt/recalls.txt live.
|
||||
|
|
@ -140,6 +140,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_portalsEnabled = NavDataConfig.ReadSwitch("portals", false);
|
||||
_recallsEnabled = NavDataConfig.ReadSwitch("recalls", true);
|
||||
LoadAvoidSettings();
|
||||
LoadMarkerSettings();
|
||||
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
|
||||
InitTravel();
|
||||
LoadGraph();
|
||||
|
|
@ -180,6 +181,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_tileRegions.Clear(); _tilePrints.Clear(); ResetCoarse();
|
||||
_chatOut.Clear();
|
||||
_goNote = "";
|
||||
HideMarkers("logged out");
|
||||
_trip = null; _tripPath = null;
|
||||
OnLogoutTravel();
|
||||
}
|
||||
|
||||
|
|
@ -199,6 +202,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
TickTravel();
|
||||
ProcessRequests();
|
||||
ApplyMovement();
|
||||
TickMarkers();
|
||||
UpdateGoLine();
|
||||
FlushChat();
|
||||
}
|
||||
|
|
@ -342,6 +346,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (_gotoActive) _goNote = "stopped"; // the panel's status line (the d-pad and Stop say nothing in chat)
|
||||
_gotoActive = false; _route = null; _portalWait = false; if (_recallWait) EndRecall();
|
||||
ResetHub();
|
||||
HideMarkers("cancelled");
|
||||
}
|
||||
if (load && _hasPose) RefreshTiles(CurrentLandblock);
|
||||
if (test) TestImpl();
|
||||
|
|
@ -427,9 +432,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
{
|
||||
if (!_hasPose) { lock (_gate) _status = "no pose"; Note("goto: no player position yet"); return; }
|
||||
// A new goto (not the re-plan after "no route over land") may re-plan once again.
|
||||
if (!landReplan) _landReplanned = false;
|
||||
if (!landReplan) { _landReplanned = false; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; }
|
||||
// Whatever was running stops first: a refused goto must not leave the old one half-changed.
|
||||
if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); }
|
||||
if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); HideMarkers("a new goto"); }
|
||||
double twx = NavCoords.WorldX(tew), twy = NavCoords.WorldY(tns);
|
||||
int gLbX = (int)Math.Floor(twx / 192.0), gLbY = (int)Math.Floor(twy / 192.0);
|
||||
if (double.IsNaN(twx) || double.IsNaN(twy) || gLbX < 0 || gLbX > 255 || gLbY < 0 || gLbY > 255)
|
||||
|
|
@ -491,6 +496,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// needs no navmesh here.
|
||||
bool recallFirst = _route != null && _route.Count > 0 && (_route[0].UseRecall || _route[0].IsHub);
|
||||
uint hereLb = CurrentLandblock;
|
||||
// A dungeon's landblock has a tile too, but it's the surface's (dungeon cells aren't
|
||||
// baked): walking on it inside the dungeon runs into walls. Say so instead.
|
||||
if (!recallFirst && InDungeon(_cellId))
|
||||
{
|
||||
_route = null;
|
||||
lock (_gate) { _status = $"in a dungeon (0x{hereLb:X4}): no navmesh"; _lastPath = ""; }
|
||||
Note($"goto: no navmesh inside dungeons yet (landblock 0x{hereLb:X4}); walk out through its portal, or turn on recalls so the route can start with one");
|
||||
return;
|
||||
}
|
||||
if (!recallFirst && !File.Exists(Path.Combine(NavDataDir, $"nav_{hereLb:X4}.tile")))
|
||||
{
|
||||
_route = null;
|
||||
|
|
@ -503,6 +517,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (_route == null && !File.Exists(Path.Combine(NavDataDir, $"nav_{goalLb:X4}.tile")))
|
||||
Say($"goto: the target's landblock 0x{goalLb:X4} has no tile; walking as far as the navmesh goes");
|
||||
|
||||
SetTrip(_route, name, tns, tew, recalls, enter, live: true);
|
||||
_gotoActive = true;
|
||||
_gotoName = name; _gotoType = type;
|
||||
_walkHaveLast = false;
|
||||
|
|
@ -632,6 +647,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// ArrivalUnits from the typed point. Standing on that spot is arriving.
|
||||
bool atMeshGoal = !isPortalLeg && _goalOnMesh &&
|
||||
Math.Sqrt((_goalMeshEw - _wx) * (_goalMeshEw - _wx) + (_goalMeshNs - _wy) * (_goalMeshNs - _wy)) < ArrivalUnits;
|
||||
// A portal is run into straight from PortalArriveUnits: only with nothing between, as far as
|
||||
// the navmesh shows. A portal round a corner (a wall within 14 u of it) is reached along
|
||||
// the path first; it used to be run at through the wall, 12 s a try, five tries.
|
||||
if (isPortalLeg && toGoal < arrive && toGoal > PortalContactUnits && !atMeshGoal)
|
||||
{
|
||||
bool pathLeft;
|
||||
lock (_gotoGate) pathLeft = _gotoPath != null && _gotoIdx < _gotoPath.Count;
|
||||
if (pathLeft && !StraightOnMesh(_gotoTew, _gotoTns)) arrive = PortalContactUnits;
|
||||
}
|
||||
if (toGoal < arrive || atMeshGoal)
|
||||
{
|
||||
OnSubGoalReached();
|
||||
|
|
@ -644,7 +668,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// Following a route over land, progress is what's left of the route (it can lead away
|
||||
// from the target for a while); otherwise the straight distance.
|
||||
double left = _coarse != null ? _coarse.Remaining(_wx, _wy) : toGoal;
|
||||
if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; }
|
||||
if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; _stuckTries = 0; }
|
||||
else if (_coarse != null && left > _bestDist + RouteLostUnits)
|
||||
{
|
||||
// Following a route but getting ever farther from it: stop rather than wander.
|
||||
|
|
@ -658,6 +682,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
FinishGoto($"stopped: no progress for 30 s, {toGoal:F0}u short ({why})");
|
||||
return;
|
||||
}
|
||||
// Running into something (RynthNavPlugin.Blocked.cs): turn away, plan again, or stop and say where.
|
||||
if (StepBlocked()) return;
|
||||
|
||||
// Plan at once, re-plan every 20 ticks, and every 5 while there is no plan.
|
||||
bool due = _gotoPath == null ? (_replanTick++ % 5) == 0 : (++_replanTick % 20) == 0;
|
||||
|
|
@ -703,7 +729,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// Straight at the goal, or along the route at its next crossing.
|
||||
double bh = (_coarse != null ? Math.Atan2(_aimEw - _wx, _aimNs - _wy) : Math.Atan2(fdew, fdns)) * 180.0 / Math.PI;
|
||||
bh = SteerRoundPortals(bh < 0 ? bh + 360.0 : bh, 10.0);
|
||||
DriveTo(bh);
|
||||
WalkDrive(bh);
|
||||
if (_blindTicks % 10 == 0) lock (_gotoGate) _gotoPath = null; // re-plan soon
|
||||
}
|
||||
else if (_blindTicks++ == BlindPushTicks)
|
||||
|
|
@ -722,7 +748,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// hub portals' circles, a wall beside), it held 234 deg into the wall while the path wanted
|
||||
// 301 and re-planned every 0.6 s (10-01 20:07, "just spazzing"). Steering is for the
|
||||
// blind push and the last steps onto a portal, where there is no path.
|
||||
DriveTo(desired);
|
||||
WalkDrive(desired);
|
||||
}
|
||||
|
||||
// ── Portal routing ───────────────────────────────────────────────────────────
|
||||
|
|
@ -770,6 +796,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
else { _gotoTew = _finalTew; _gotoTns = _finalTns; }
|
||||
// New leg: fresh progress watchdog, and the old leg's walkable end no longer counts.
|
||||
ResetHub();
|
||||
ResetBlocked();
|
||||
_coarseHoldTicks = _graph != null ? CoarseHoldMaxTicks : 0;
|
||||
_nextAvoidMs = 0;
|
||||
_walkHaveLast = false; // a new leg starts where the last step's teleport put us
|
||||
|
|
@ -784,12 +811,14 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_gotoActive = false; _route = null; _portalWait = false;
|
||||
ResetHub();
|
||||
_avoid.Clear(); _coarseHoldTicks = 0;
|
||||
ResetBlocked();
|
||||
Host.SetAutoRun(false); Host.StopCompletely();
|
||||
lock (_gate) _status = status;
|
||||
Host.Log($"[RynthNav] goto: {status}");
|
||||
Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}");
|
||||
_goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status;
|
||||
_enterName = ""; _enterType = "";
|
||||
HideMarkers(status == "arrived" ? "arrived" : "the goto ended");
|
||||
}
|
||||
|
||||
// At a portal entrance, waiting for the teleport. A portal ALWAYS changes the
|
||||
|
|
@ -935,7 +964,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
var startP = new RcVec3f((float)_wx, (float)_wz, (float)_wy);
|
||||
_query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out long sRef, out RcVec3f sPt, out _);
|
||||
// The ground we stand on first: the mesh keeps the agent radius (2 m) from walls, so close
|
||||
// up it's within that, at our height. Only then the wide search, which can pick ground on
|
||||
// the far side of a thin wall or a roof overhead, and the walk then runs into that wall.
|
||||
_query.FindNearestPoly(startP, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _);
|
||||
if (sRef == 0) _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out sRef, out sPt, out _);
|
||||
// A failed plan drops the old one: StepGoto must not keep following a stale path.
|
||||
if (sRef == 0) { lock (_gate) _status = "off navmesh"; lock (_gotoGate) _gotoPath = null; return; }
|
||||
|
||||
|
|
@ -1018,8 +1051,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy);
|
||||
if (ol < 0.05) continue; // straight on: no corner to clear
|
||||
double nx = px + ox / ol * _wallClearance, ny = py + oy / ol * _wallClearance;
|
||||
q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out _, out _);
|
||||
if (rr != 0) wps[i] = (nx, ny);
|
||||
// Only onto walkable ground itself (inside a polygon), not merely near it: near it,
|
||||
// the moved corner could sit closer to the wall than the body is wide.
|
||||
q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out RcVec3f rp, out _);
|
||||
if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny);
|
||||
}
|
||||
}
|
||||
lock (_gotoGate) { _gotoPath = wps; _gotoIdx = 0; }
|
||||
|
|
@ -1154,9 +1189,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
bool exists = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile"));
|
||||
int onDisk = 0;
|
||||
try { if (Directory.Exists(NavDataDir)) onDisk = Directory.GetFiles(NavDataDir, "nav_*.tile").Length; } catch { }
|
||||
bool indoors = (_cellId & 0xFFFF) >= 0x0100;
|
||||
bool indoors = (_cellId & 0xFFFF) >= 0x0100, dungeon = InDungeon(_cellId);
|
||||
string status; lock (_gate) status = _status;
|
||||
return $"landblock 0x{lb:X4}{(indoors ? " (indoors)" : "")} — tile {(exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
|
||||
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")} — tile "
|
||||
+ $"{(dungeon ? (exists ? "surface only, no dungeon navmesh" : "MISSING") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
|
||||
+ $"{onDisk} tile(s) in {NavDataDir}; route graph: {_graphStatus}; Town Network: {_townNetStatus}; goto {(_gotoActive ? "ACTIVE" : "off")}"
|
||||
+ $"{(_coarse != null ? $" (route {_coarse.Crossed}/{_coarse.Count})" : "")}, portals {(_portalsEnabled ? "on" : "off")}; status: {status}";
|
||||
}
|
||||
|
|
|
|||
241
Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs
Normal file
241
Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using DotRecast.Detour.Io;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Whole walking legs on the navmesh, worked out ahead of time for a planned trip (the path
|
||||
/// markers and "save as nav route"), the way the walker would go: the route graph's border
|
||||
/// crossings from the start's region to the goal's (NavGraph A*), then the detailed Detour path
|
||||
/// between each pair of crossings, kept out of the Atlas's portals (AvoidFilter, PortalAvoid.Bend)
|
||||
/// except the leg's own. Its own navmesh, filled from the tile files a few tiles at a time, so it
|
||||
/// runs on a worker and never touches the walker's (tick-thread) navmesh. One instance per worker.
|
||||
/// Without a route graph only short legs (a few landblocks) are planned; longer ones get none.
|
||||
/// </summary>
|
||||
internal sealed class TilePathFinder
|
||||
{
|
||||
private const int MaxTiles = 64;
|
||||
private const int MaxDirectTiles = 16; // without a graph: a leg spanning at most this many tiles
|
||||
private const float ProbeReach = 40f;
|
||||
private const double OwnPortalUnits = 15.0; // the leg's own portal (its goal) isn't avoided
|
||||
private const double AvoidNearUnits = 300.0;
|
||||
|
||||
private readonly string _dir;
|
||||
private readonly NavGraph? _graph;
|
||||
private readonly IReadOnlyList<PortalAvoid.Spot> _portals;
|
||||
private readonly DtNavMesh _nav;
|
||||
private DtNavMeshQuery _query;
|
||||
private readonly HashSet<uint> _loaded = new(), _bad = new();
|
||||
private readonly PortalAvoid _avoid = new();
|
||||
private readonly AvoidFilter _filter;
|
||||
private readonly DtQueryDefaultFilter _plain = new();
|
||||
|
||||
/// <summary>Tile files read so far (for the log).</summary>
|
||||
public int TilesRead { get; private set; }
|
||||
|
||||
public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList<PortalAvoid.Spot>? portals)
|
||||
{
|
||||
_dir = navDataDir;
|
||||
_graph = graph;
|
||||
_portals = portals ?? Array.Empty<PortalAvoid.Spot>();
|
||||
_nav = new DtNavMesh();
|
||||
var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = MaxTiles, maxPolys = 1 << 16 };
|
||||
_nav.Init(p, 6);
|
||||
_query = new DtNavMeshQuery(_nav);
|
||||
_filter = new AvoidFilter(_avoid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The walk from <paramref name="from"/> to <paramref name="to"/>: corners, both ends included.
|
||||
/// <paramref name="ownPortal"/>: the walk ends by stepping into a portal there (not avoided).
|
||||
/// Null when the navmesh can't give one (no tiles, no way over land); <paramref name="note"/> says why.
|
||||
/// </summary>
|
||||
public List<WorldPt>? Walk(WorldPt from, WorldPt to, bool ownPortal, out string note)
|
||||
{
|
||||
note = "";
|
||||
var anchors = new List<WorldPt> { from };
|
||||
if (_graph != null)
|
||||
{
|
||||
NavCoarse.Probe? s = GroundProbe(from), g = GroundProbe(to);
|
||||
if (s == null || g == null) { note = $"no navmesh at its {(s == null ? "start" : "end")}"; return null; }
|
||||
List<int>? route = _graph.FindRoute(s.Region, s.Pt.X, s.Pt.Z, g.Region, g.Pt.X, g.Pt.Z, out _, out _);
|
||||
if (route == null) { note = "no way over land on the navmesh"; return null; }
|
||||
// Plan from and to the ground found there (the trip's own ends are added back by the caller).
|
||||
anchors[0] = new WorldPt(s.Pt.X, s.Pt.Z, s.Pt.Y);
|
||||
from = anchors[0];
|
||||
to = new WorldPt(g.Pt.X, g.Pt.Z, g.Pt.Y);
|
||||
foreach (int p in route)
|
||||
{
|
||||
var c = _graph.Portal(p);
|
||||
anchors.Add(new WorldPt(c.Ew, c.Ns, c.Up));
|
||||
}
|
||||
}
|
||||
else if (TileSpan(from, to) > MaxDirectTiles)
|
||||
{
|
||||
note = "too far to plan without the route graph (navgraph.bin)";
|
||||
return null;
|
||||
}
|
||||
anchors.Add(to);
|
||||
|
||||
var path = new List<WorldPt> { from };
|
||||
int gaps = 0;
|
||||
for (int k = 0; k + 1 < anchors.Count; k++)
|
||||
{
|
||||
bool last = k + 2 == anchors.Count;
|
||||
List<WorldPt>? piece = Piece(anchors[k], anchors[k + 1], last && ownPortal ? anchors[k + 1] : null);
|
||||
if (piece == null) { gaps++; piece = new List<WorldPt> { anchors[k], anchors[k + 1] }; }
|
||||
for (int i = 1; i < piece.Count; i++) path.Add(piece[i]);
|
||||
}
|
||||
if (gaps > 0) note = $"{gaps} gap(s) in the navmesh, straight lines there";
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walkable ground at <paramref name="p"/> for the route search. A point with no height (a
|
||||
/// landing, a portal, a town's centre) can find a roof or a ledge first: a region of a tiny
|
||||
/// landmass that leads nowhere (the real map: Lytelthorpe's centre is under a roof). Then the
|
||||
/// ground a few yards round it (rings out to 36 yd) that's part of a real landmass is taken.
|
||||
/// </summary>
|
||||
private NavCoarse.Probe? GroundProbe(WorldPt p)
|
||||
{
|
||||
NavGraph g = _graph!;
|
||||
NavCoarse.Probe? first = NavCoarse.ProbeFile(g, _dir, p.X, p.H, p.Y, ProbeReach);
|
||||
if (first != null && !Tiny(first.Region)) return first;
|
||||
for (double r = 6; r <= 36; r += 6)
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
double a = k * Math.PI / 4;
|
||||
NavCoarse.Probe? q = NavCoarse.ProbeFile(g, _dir, p.X + Math.Cos(a) * r, p.H, p.Y + Math.Sin(a) * r, 4f);
|
||||
if (q != null && !Tiny(q.Region)) return q;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/// <summary>A region of a landmass this small (a roof, a ledge); false when the graph has no landmasses worked out.</summary>
|
||||
private bool Tiny(int region)
|
||||
{
|
||||
int c = _graph!.Component(region);
|
||||
return c >= 0 && _graph.ComponentSize(c) < 8;
|
||||
}
|
||||
|
||||
private static int TileSpan(WorldPt a, WorldPt b)
|
||||
{
|
||||
int ax = (int)Math.Floor(a.X / 192.0), ay = (int)Math.Floor(a.Y / 192.0), bx = (int)Math.Floor(b.X / 192.0), by = (int)Math.Floor(b.Y / 192.0);
|
||||
return (Math.Abs(ax - bx) + 1) * (Math.Abs(ay - by) + 1);
|
||||
}
|
||||
|
||||
/// <summary>The Detour path a→b (both ends' tiles and those between loaded); null when there's none.</summary>
|
||||
private List<WorldPt>? Piece(WorldPt a, WorldPt b, WorldPt? own)
|
||||
{
|
||||
if (!LoadBox(a, b)) return null;
|
||||
var half = new RcVec3f(8, 600, 8);
|
||||
var pa = new RcVec3f((float)a.X, double.IsNaN(a.H) ? 0f : (float)a.H, (float)a.Y);
|
||||
var pb = new RcVec3f((float)b.X, double.IsNaN(b.H) ? 0f : (float)b.H, (float)b.Y);
|
||||
_query.FindNearestPoly(pa, half, _plain, out long sRef, out RcVec3f sPt, out _);
|
||||
_query.FindNearestPoly(pb, half, _plain, out long gRef, out RcVec3f gPt, out _);
|
||||
if (sRef == 0 || gRef == 0) return null;
|
||||
|
||||
// Portals near this piece, except the leg's own.
|
||||
var near = new List<PortalAvoid.Spot>();
|
||||
double minX = Math.Min(a.X, b.X) - AvoidNearUnits, maxX = Math.Max(a.X, b.X) + AvoidNearUnits;
|
||||
double minY = Math.Min(a.Y, b.Y) - AvoidNearUnits, maxY = Math.Max(a.Y, b.Y) + AvoidNearUnits;
|
||||
foreach (PortalAvoid.Spot sp in _portals)
|
||||
if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) near.Add(sp);
|
||||
if (own is WorldPt ownAt) _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near, ownAt.X, ownAt.Y, OwnPortalUnits);
|
||||
else _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near);
|
||||
_filter.AllowA = sRef; _filter.AllowB = gRef;
|
||||
|
||||
Span<long> polys = new long[1024];
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out int pc, 1024);
|
||||
if ((pc == 0 || polys[pc - 1] != gRef) && _avoid.Count > 0)
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _plain, polys, out pc, 1024);
|
||||
if (pc == 0 || polys[pc - 1] != gRef) return null;
|
||||
Span<DtStraightPath> sp2 = new DtStraightPath[256];
|
||||
_query.FindStraightPath(sPt, gPt, polys[..pc], pc, sp2, out int spc, 256, 0);
|
||||
if (spc < 2) return null;
|
||||
|
||||
var corners = new List<(double X, double Y)>(spc);
|
||||
List<double>? heights = new List<double>(spc);
|
||||
for (int i = 0; i < spc; i++) { corners.Add((sp2[i].pos.X, sp2[i].pos.Z)); heights.Add(sp2[i].pos.Y); }
|
||||
if (_avoid.Count > 0)
|
||||
{
|
||||
var q = _query;
|
||||
bool OnMesh(double x, double y)
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)x, pa.Y, (float)y), new RcVec3f(0.5f, 600, 0.5f), _plain, out long r, out RcVec3f np, out _);
|
||||
return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05;
|
||||
}
|
||||
bool LegOnMesh(double ax, double ay, double bx, double by)
|
||||
{
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len));
|
||||
for (int k = 1; k < n; k++)
|
||||
if (!OnMesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false;
|
||||
return true;
|
||||
}
|
||||
int before = corners.Count;
|
||||
corners = _avoid.Bend(corners, OnMesh, 12, LegOnMesh);
|
||||
if (corners.Count != before) heights = null; // bend corners: heights filled from the neighbours
|
||||
}
|
||||
var o = new List<WorldPt>(corners.Count) { a with { H = heights != null ? heights[0] : (double.IsNaN(a.H) ? sPt.Y : a.H) } };
|
||||
for (int i = 1; i < corners.Count; i++)
|
||||
o.Add(new WorldPt(corners[i].X, corners[i].Y, heights != null ? heights[i] : double.NaN));
|
||||
if (heights == null) o[^1] = o[^1] with { H = gPt.Y };
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Loads the tiles of the box a..b (evicting others when full); false when it's too big or none loads.</summary>
|
||||
private bool LoadBox(WorldPt a, WorldPt b)
|
||||
{
|
||||
int x0 = (int)Math.Floor(Math.Min(a.X, b.X) / 192.0), x1 = (int)Math.Floor(Math.Max(a.X, b.X) / 192.0);
|
||||
int y0 = (int)Math.Floor(Math.Min(a.Y, b.Y) / 192.0), y1 = (int)Math.Floor(Math.Max(a.Y, b.Y) / 192.0);
|
||||
// A crossing on a tile edge belongs to both tiles: take one more on each side then.
|
||||
if (a.X - x0 * 192.0 < 1 || b.X - x0 * 192.0 < 1) x0--;
|
||||
if ((x1 + 1) * 192.0 - Math.Max(a.X, b.X) < 1) x1++;
|
||||
if (a.Y - y0 * 192.0 < 1 || b.Y - y0 * 192.0 < 1) y0--;
|
||||
if ((y1 + 1) * 192.0 - Math.Max(a.Y, b.Y) < 1) y1++;
|
||||
x0 = Math.Max(0, x0); y0 = Math.Max(0, y0); x1 = Math.Min(255, x1); y1 = Math.Min(255, y1);
|
||||
int want = (x1 - x0 + 1) * (y1 - y0 + 1);
|
||||
if (want > MaxTiles / 2) return false;
|
||||
var needed = new HashSet<uint>();
|
||||
for (int x = x0; x <= x1; x++)
|
||||
for (int y = y0; y <= y1; y++) needed.Add((uint)((x << 8) | y));
|
||||
bool changed = false;
|
||||
if (_loaded.Count + want > MaxTiles - 1)
|
||||
{
|
||||
foreach (uint lb in new List<uint>(_loaded))
|
||||
{
|
||||
if (needed.Contains(lb)) continue;
|
||||
long r = _nav.GetTileRefAt((int)(lb >> 8), (int)(lb & 0xFF), 0);
|
||||
if (r != 0) _nav.RemoveTile(r);
|
||||
_loaded.Remove(lb);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
bool any = false;
|
||||
foreach (uint lb in needed)
|
||||
{
|
||||
if (_loaded.Contains(lb)) { any = true; continue; }
|
||||
if (_bad.Contains(lb)) continue;
|
||||
string path = Path.Combine(_dir, $"nav_{lb:X4}.tile");
|
||||
if (!File.Exists(path)) { _bad.Add(lb); continue; }
|
||||
try
|
||||
{
|
||||
DtMeshData md;
|
||||
using (var fr = File.OpenRead(path)) using (var br = new BinaryReader(fr)) md = new DtMeshDataReader().Read(br, 6);
|
||||
TilesRead++;
|
||||
if (_nav.AddTile(md, 0, 0, out _).Failed()) { _bad.Add(lb); continue; }
|
||||
_loaded.Add(lb);
|
||||
changed = any = true;
|
||||
}
|
||||
catch { _bad.Add(lb); }
|
||||
}
|
||||
if (changed) _query = new DtNavMeshQuery(_nav);
|
||||
return any;
|
||||
}
|
||||
}
|
||||
190
Plugins/RynthCore.Plugin.RynthNav/TripPath.cs
Normal file
190
Plugins/RynthCore.Plugin.RynthNav/TripPath.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// The ground a <see cref="PlannedTrip"/> walks, worked out once for the whole trip (on a worker:
|
||||
/// TilePathFinder reads the tiles and the route graph into its own navmesh): per walking step, the
|
||||
/// path from where the step starts to its point, thinned to the corners that matter; per hub step,
|
||||
/// the walk inside the Town Network. The path markers draw it and "save as nav route" writes it.
|
||||
/// Never changed after it's built. Host-free: the route tests build these with a fake path finder.
|
||||
/// </summary>
|
||||
internal sealed class TripPath
|
||||
{
|
||||
public readonly int TripId;
|
||||
/// <summary>Per step: the walk, first point = where it starts, last = the step's point (null = no walk).</summary>
|
||||
public readonly WorldPt[]?[] Walks;
|
||||
/// <summary>Per hub step: the walk inside the Town Network to the exit portal (null otherwise).</summary>
|
||||
public readonly WorldPt[]?[] Hub;
|
||||
/// <summary>What couldn't be worked out ("step 2: no navmesh path, a straight line"), for chat.</summary>
|
||||
public readonly IReadOnlyList<string> Notes;
|
||||
|
||||
public TripPath(int tripId, WorldPt[]?[] walks, WorldPt[]?[] hub, IReadOnlyList<string> notes)
|
||||
{
|
||||
TripId = tripId; Walks = walks; Hub = hub; Notes = notes;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TripPathBuilder
|
||||
{
|
||||
/// <summary>A corner closer than this (yards) to the straight line past it is dropped.</summary>
|
||||
public const double ThinTolerance = 0.75;
|
||||
/// <summary>Straight stretches get a point at least this often (yards), so the markers and a nav follow the ground.</summary>
|
||||
public const double MaxSpacing = 60.0;
|
||||
/// <summary>Points closer together than this are one point.</summary>
|
||||
public const double DuplicateUnits = 0.5;
|
||||
|
||||
/// <summary>
|
||||
/// A walkable path from <paramref name="from"/> to <paramref name="to"/> (corners, both ends
|
||||
/// included), or null when there is none to be had; <paramref name="note"/> says why or what was
|
||||
/// approximated. <paramref name="intoPortal"/>: the walk ends by stepping into a portal at
|
||||
/// <paramref name="to"/> (so that one isn't kept out of).
|
||||
/// </summary>
|
||||
public delegate List<WorldPt>? WalkFinder(WorldPt from, WorldPt to, bool intoPortal, out string note);
|
||||
|
||||
/// <summary>
|
||||
/// The trip's ground: each walking step through <paramref name="walk"/> (a straight line where it
|
||||
/// has nothing, with a note), each hub step from <paramref name="net"/>; all thinned.
|
||||
/// </summary>
|
||||
public static TripPath Build(PlannedTrip trip, WalkFinder? walk, TownNet? net)
|
||||
{
|
||||
int n = trip.Count;
|
||||
var walks = new WorldPt[]?[n];
|
||||
var hub = new WorldPt[]?[n];
|
||||
var notes = new List<string>();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (trip.Steps[i].IsHub)
|
||||
{
|
||||
List<WorldPt>? inside = trip.HubWalk(i, net, out string why);
|
||||
if (inside == null) notes.Add($"step {i + 1}: {why}");
|
||||
else hub[i] = Thin(inside).ToArray();
|
||||
continue;
|
||||
}
|
||||
if (trip.WalkFrom[i] is not WorldPt from || trip.Point[i] is not WorldPt to) continue;
|
||||
string note = "";
|
||||
List<WorldPt>? raw = null;
|
||||
try { raw = walk?.Invoke(from, to, trip.Steps[i].UsePortal, out note); }
|
||||
catch (Exception ex) { note = "path finder failed: " + ex.Message; raw = null; }
|
||||
if (raw == null || raw.Count < 2)
|
||||
{
|
||||
raw = new List<WorldPt> { from, to };
|
||||
notes.Add($"step {i + 1}: {(note.Length > 0 ? note : "no navmesh path")}; a straight line there");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (note.Length > 0) notes.Add($"step {i + 1}: {note}");
|
||||
// The path ends on the navmesh beside the point; the point itself is where the step goes.
|
||||
if (raw[0].FlatDistance(from) > 2.0) raw.Insert(0, from);
|
||||
if (raw[^1].FlatDistance(to) > 2.0) raw.Add(new WorldPt(to.X, to.Y, raw[^1].H));
|
||||
}
|
||||
walks[i] = Thin(raw).ToArray();
|
||||
}
|
||||
return new TripPath(trip.Id, walks, hub, notes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path with near-duplicate points merged, corners within <paramref name="tolerance"/> of the
|
||||
/// line past them dropped (Ramer-Douglas-Peucker, ends kept), and straight stretches longer than
|
||||
/// <paramref name="maxSpacing"/> split evenly. Unknown heights are filled from the neighbours.
|
||||
/// </summary>
|
||||
public static List<WorldPt> Thin(IReadOnlyList<WorldPt> pts, double tolerance = ThinTolerance, double maxSpacing = MaxSpacing)
|
||||
{
|
||||
var dedup = new List<WorldPt>(pts.Count);
|
||||
foreach (WorldPt p in pts)
|
||||
{
|
||||
if (double.IsNaN(p.X) || double.IsNaN(p.Y)) continue;
|
||||
if (dedup.Count > 0 && dedup[^1].FlatDistance(p) < DuplicateUnits)
|
||||
{
|
||||
if (double.IsNaN(dedup[^1].H) && !double.IsNaN(p.H)) dedup[^1] = dedup[^1] with { H = p.H };
|
||||
continue;
|
||||
}
|
||||
dedup.Add(p);
|
||||
}
|
||||
FillHeights(dedup);
|
||||
if (dedup.Count <= 2) return Split(dedup, maxSpacing);
|
||||
|
||||
var keep = new bool[dedup.Count];
|
||||
keep[0] = keep[^1] = true;
|
||||
var stack = new Stack<(int A, int B)>();
|
||||
stack.Push((0, dedup.Count - 1));
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
var (a, b) = stack.Pop();
|
||||
int best = -1;
|
||||
double bestD = tolerance;
|
||||
for (int i = a + 1; i < b; i++)
|
||||
{
|
||||
double d = PlannedTrip.SegmentDistance(dedup[i], dedup[a], dedup[b]);
|
||||
if (d > bestD) { bestD = d; best = i; }
|
||||
}
|
||||
if (best < 0) continue;
|
||||
keep[best] = true;
|
||||
stack.Push((a, best));
|
||||
stack.Push((best, b));
|
||||
}
|
||||
var kept = new List<WorldPt>();
|
||||
for (int i = 0; i < dedup.Count; i++) if (keep[i]) kept.Add(dedup[i]);
|
||||
return Split(kept, maxSpacing);
|
||||
}
|
||||
|
||||
private static List<WorldPt> Split(List<WorldPt> pts, double maxSpacing)
|
||||
{
|
||||
if (pts.Count < 2 || maxSpacing <= 0) return pts;
|
||||
var o = new List<WorldPt>(pts.Count) { pts[0] };
|
||||
for (int i = 1; i < pts.Count; i++)
|
||||
{
|
||||
WorldPt a = pts[i - 1], b = pts[i];
|
||||
int parts = (int)Math.Ceiling(a.FlatDistance(b) / maxSpacing);
|
||||
for (int k = 1; k < parts; k++)
|
||||
{
|
||||
double t = (double)k / parts;
|
||||
o.Add(new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t));
|
||||
}
|
||||
o.Add(b);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>NaN heights take the nearest known one before them (else after them).</summary>
|
||||
private static void FillHeights(List<WorldPt> pts)
|
||||
{
|
||||
double last = double.NaN;
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
if (!double.IsNaN(pts[i].H)) last = pts[i].H;
|
||||
else if (!double.IsNaN(last)) pts[i] = pts[i] with { H = last };
|
||||
}
|
||||
double next = double.NaN;
|
||||
for (int i = pts.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!double.IsNaN(pts[i].H)) next = pts[i].H;
|
||||
else if (!double.IsNaN(next)) pts[i] = pts[i] with { H = next };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path stopped <paramref name="units"/> short of its end, measured along it (a walk to a
|
||||
/// portal stops before stepping in). Only the start is left when the path is shorter than that.
|
||||
/// </summary>
|
||||
public static List<WorldPt> StopShort(IReadOnlyList<WorldPt> pts, double units)
|
||||
{
|
||||
var o = new List<WorldPt>(pts);
|
||||
double left = units;
|
||||
while (o.Count >= 2 && left > 0)
|
||||
{
|
||||
WorldPt a = o[^2], b = o[^1];
|
||||
double d = a.FlatDistance(b);
|
||||
if (d > left)
|
||||
{
|
||||
double t = (d - left) / d;
|
||||
o[^1] = new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t);
|
||||
return o;
|
||||
}
|
||||
left -= d;
|
||||
o.RemoveAt(o.Count - 1);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
}
|
||||
215
Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs
Normal file
215
Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// A point in RynthNav's world units: X = east, Y = north (landblock * 192 + local), H = height
|
||||
/// (the pose z; NaN = not known).
|
||||
/// </summary>
|
||||
internal readonly record struct WorldPt(double X, double Y, double H)
|
||||
{
|
||||
public static WorldPt FromMap(double ns, double ew, double h = double.NaN) => new(NavCoords.WorldX(ew), NavCoords.WorldY(ns), h);
|
||||
public double Ns => NavCoords.NsFromWorld(Y);
|
||||
public double Ew => NavCoords.EwFromWorld(X);
|
||||
public double FlatDistance(WorldPt o) => Math.Sqrt((X - o.X) * (X - o.X) + (Y - o.Y) * (Y - o.Y));
|
||||
/// <summary>The landblock under the point (0xXXYY), or uint.MaxValue off the map.</summary>
|
||||
public uint Landblock
|
||||
{
|
||||
get
|
||||
{
|
||||
int x = (int)Math.Floor(X / 192.0), y = (int)Math.Floor(Y / 192.0);
|
||||
return x is >= 0 and <= 255 && y is >= 0 and <= 255 ? (uint)((x << 8) | y) : uint.MaxValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A recall of the plan, as the plan was made (RouteStep.RecallIndex indexes these).</summary>
|
||||
internal readonly record struct TripRecall(string Name, int SpellId, string Command, double CastSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// One trip RynthNav planned (Route) or is walking (Go), frozen when it was planned: the steps,
|
||||
/// where it started, the recalls it may cast and the portal a dungeon goto ends in. Never changed
|
||||
/// after it's made, so the path builder (a worker), the markers and "save as nav route" all read
|
||||
/// the same thing without locks. Host-free: the route tests build these.
|
||||
///
|
||||
/// What each step walks (<see cref="WalkFrom"/> to <see cref="Point"/>):
|
||||
/// a walk step from where the last step left you to its point;
|
||||
/// a portal step the same, its point being the portal's entrance (then the teleport);
|
||||
/// a recall step nothing: cast where you stand (its point is that spot);
|
||||
/// a hub step nothing on the map: the walk inside the Town Network (TownNet's walks).
|
||||
/// After a portal or recall you stand at its landing (LandNs/LandEw); after a portal into a
|
||||
/// dungeon or the Town Network there's no map position until a hub step or a recall.
|
||||
/// </summary>
|
||||
internal sealed class PlannedTrip
|
||||
{
|
||||
/// <summary>A landblock this close to a leg (its centre, world units) counts as on the plan.</summary>
|
||||
public const double CoverUnits = 288.0;
|
||||
|
||||
public readonly int Id;
|
||||
public readonly IReadOnlyList<RouteStep> Steps;
|
||||
public readonly string Goal;
|
||||
public readonly double GoalNs, GoalEw;
|
||||
public readonly bool StartOnMap;
|
||||
public readonly WorldPt Start;
|
||||
public readonly uint StartCell;
|
||||
public readonly IReadOnlyList<TripRecall> Recalls;
|
||||
/// <summary>The portal object the last step walks into (a dungeon goto); "" = none or not known.</summary>
|
||||
public readonly string EnterPortal;
|
||||
/// <summary>The dungeon (or portal) that last step goes into; "" = none.</summary>
|
||||
public readonly string EnterName;
|
||||
/// <summary>The running goto's plan (false: planned with Route, not walked).</summary>
|
||||
public readonly bool Live;
|
||||
|
||||
/// <summary>Per step: where its walk starts (null = no walk: a recall, a hub step, or no map position).</summary>
|
||||
public readonly WorldPt?[] WalkFrom;
|
||||
/// <summary>Per step: where it happens (a walk's end, a portal's entrance, a recall's cast spot); null for a hub step.</summary>
|
||||
public readonly WorldPt?[] Point;
|
||||
|
||||
public PlannedTrip(int id, IReadOnlyList<RouteStep> steps, string goal, double goalNs, double goalEw,
|
||||
bool startOnMap, WorldPt start, uint startCell, IReadOnlyList<TripRecall>? recalls,
|
||||
string enterPortal = "", string enterName = "", bool live = false)
|
||||
{
|
||||
Id = id;
|
||||
Steps = steps.Count == 0 ? new[] { new RouteStep(goalNs, goalEw, false, false, "walk") } : new List<RouteStep>(steps).ToArray();
|
||||
Goal = goal; GoalNs = goalNs; GoalEw = goalEw;
|
||||
StartOnMap = startOnMap; Start = start; StartCell = startCell;
|
||||
Recalls = recalls ?? Array.Empty<TripRecall>();
|
||||
EnterPortal = enterPortal ?? ""; EnterName = enterName ?? ""; Live = live;
|
||||
|
||||
int n = Steps.Count;
|
||||
WalkFrom = new WorldPt?[n];
|
||||
Point = new WorldPt?[n];
|
||||
WorldPt? here = startOnMap ? start : null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
RouteStep s = Steps[i];
|
||||
if (s.UseRecall)
|
||||
{
|
||||
// Cast where you stand: the trip's start for a first step (in a dungeon too).
|
||||
Point[i] = here ?? (i == 0 ? start : null);
|
||||
here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
continue;
|
||||
}
|
||||
WorldPt to = WorldPt.FromMap(s.Ns, s.Ew);
|
||||
WalkFrom[i] = here;
|
||||
Point[i] = to;
|
||||
here = !s.UsePortal ? to : double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => Steps.Count;
|
||||
public bool HasHub { get { foreach (RouteStep s in Steps) if (s.IsHub) return true; return false; } }
|
||||
|
||||
/// <summary>The last step is a portal into the place the goto was for (a dungeon).</summary>
|
||||
public bool EndsInEntrance => EnterName.Length > 0 && Steps.Count > 0 && Steps[^1].UsePortal;
|
||||
|
||||
/// <summary>The portal object step <paramref name="i"/> walks into: its label, or for the dungeon entrance, the portal's own name.</summary>
|
||||
public string PortalName(int i)
|
||||
{
|
||||
if (i == Steps.Count - 1 && EndsInEntrance && EnterPortal.Length > 0) return EnterPortal;
|
||||
return Steps[i].Label ?? "";
|
||||
}
|
||||
|
||||
/// <summary>The recall of step <paramref name="i"/>, or null when the plan doesn't know it.</summary>
|
||||
public TripRecall? RecallOf(int i)
|
||||
{
|
||||
int r = Steps[i].RecallIndex;
|
||||
return r >= 0 && r < Recalls.Count ? Recalls[r] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is <paramref name="landblock"/> on this trip: the start's own landblock, near one of its walks
|
||||
/// (the straight leg, or the path built for it), its steps or landings, or inside the Town
|
||||
/// Network on a trip that takes it? A teleport somewhere else isn't.
|
||||
/// </summary>
|
||||
public bool Covers(uint landblock, TripPath? path, Func<uint, bool>? inHub)
|
||||
{
|
||||
if (landblock == 0 || landblock == ((StartCell >> 16) & 0xFFFF)) return true;
|
||||
if (HasHub && inHub != null && inHub(landblock)) return true;
|
||||
double cx = ((landblock >> 8) & 0xFF) * 192.0 + 96.0, cy = (landblock & 0xFF) * 192.0 + 96.0;
|
||||
var c = new WorldPt(cx, cy, 0);
|
||||
for (int i = 0; i < Steps.Count; i++)
|
||||
{
|
||||
if (Point[i] is WorldPt p && p.FlatDistance(c) <= CoverUnits) return true;
|
||||
if (WalkFrom[i] is WorldPt f && Point[i] is WorldPt t && SegmentDistance(c, f, t) <= CoverUnits) return true;
|
||||
RouteStep s = Steps[i];
|
||||
if (!double.IsNaN(s.LandNs) && WorldPt.FromMap(s.LandNs, s.LandEw).FlatDistance(c) <= CoverUnits) return true;
|
||||
WorldPt[]? w = path?.TripId == Id && i < path.Walks.Length ? path.Walks[i] : null;
|
||||
if (w != null)
|
||||
for (int k = 1; k < w.Length; k++)
|
||||
if (SegmentDistance(c, w[k - 1], w[k]) <= CoverUnits) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Flat distance from <paramref name="p"/> to the segment a→b.</summary>
|
||||
public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b) => SegmentDistance(p, a, b, out _);
|
||||
|
||||
/// <summary>Flat distance from <paramref name="p"/> to the segment a→b, and how far along it the nearest point is (0..1).</summary>
|
||||
public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b, out double t)
|
||||
{
|
||||
double vx = b.X - a.X, vy = b.Y - a.Y, l2 = vx * vx + vy * vy;
|
||||
t = l2 < 1e-9 ? 0 : Math.Clamp(((p.X - a.X) * vx + (p.Y - a.Y) * vy) / l2, 0, 1);
|
||||
double x = a.X + vx * t, y = a.Y + vy * t;
|
||||
return Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The walk inside the Town Network for hub step <paramref name="i"/>, in world units (the
|
||||
/// network's landblock): from the arrival the entry portal before it lands on (or, for a trip
|
||||
/// that starts inside, from where it started) to the exit portal. Null, with a reason, when
|
||||
/// townnet.json doesn't have it.
|
||||
/// </summary>
|
||||
public List<WorldPt>? HubWalk(int i, TownNet? net, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (net == null) { why = "the Town Network data (townnet.json) isn't loaded"; return null; }
|
||||
RouteStep s = Steps[i];
|
||||
int exit = s.HubExit;
|
||||
if (exit < 0 || exit >= net.Exits.Count) { why = "the Town Network exit isn't in townnet.json"; return null; }
|
||||
IReadOnlyList<TownNetPoint>? pts = null;
|
||||
if (i > 0 && Steps[i - 1].UsePortal)
|
||||
{
|
||||
// The entry portal walked into: the townnet.json entry at that spot, and its arrival.
|
||||
RouteStep e = Steps[i - 1];
|
||||
TownNetEntry? best = null;
|
||||
double bestD = 2.0; // the plan's entry coordinates are the entry's own
|
||||
foreach (TownNetEntry en in net.Entries)
|
||||
{
|
||||
if (!en.OnMap) continue;
|
||||
double d = NavCoords.Distance(en.Ns, en.Ew, e.Ns, e.Ew);
|
||||
if (d < bestD) { bestD = d; best = en; }
|
||||
}
|
||||
if (best == null || best.Arrival < 0) { why = $"the entry portal {e.Label} isn't in townnet.json"; return null; }
|
||||
pts = net.Walk(best.Arrival, exit)?.Points;
|
||||
if (pts == null) { why = $"townnet.json has no walk from {best.Name}'s arrival to the {net.Exits[exit].Name}"; return null; }
|
||||
}
|
||||
else if (i == 0 && !StartOnMap && net.Contains((StartCell >> 16) & 0xFFFF))
|
||||
{
|
||||
double lx = Start.X - ((StartCell >> 24) & 0xFF) * 192.0, ly = Start.Y - ((StartCell >> 16) & 0xFF) * 192.0;
|
||||
pts = net.WayTo(exit, lx, ly, HubWalker.OffRouteUnits, out _);
|
||||
if (pts == null) { why = "no Town Network walk to that exit passes where the trip started"; return null; }
|
||||
}
|
||||
else { why = "the plan doesn't say how it gets into the Town Network"; return null; }
|
||||
|
||||
var list = new List<WorldPt>(pts.Count);
|
||||
foreach (TownNetPoint p in pts)
|
||||
list.Add(new WorldPt(((p.Cell >> 24) & 0xFF) * 192.0 + p.X, ((p.Cell >> 16) & 0xFF) * 192.0 + p.Y, p.Z));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Where the hub step's exit portal stands (world units), or null.</summary>
|
||||
public static WorldPt? HubExitPoint(TownNet? net, RouteStep s)
|
||||
{
|
||||
if (net == null || s.HubExit < 0 || s.HubExit >= net.Exits.Count) return null;
|
||||
TownNetExit x = net.Exits[s.HubExit];
|
||||
return new WorldPt(((x.Cell >> 24) & 0xFF) * 192.0 + x.X, ((x.Cell >> 16) & 0xFF) * 192.0 + x.Y, x.Z);
|
||||
}
|
||||
}
|
||||
|
|
@ -38,4 +38,9 @@
|
|||
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ internal sealed class RynthNetCharacter
|
|||
|
||||
internal sealed class RynthNetSettings
|
||||
{
|
||||
public const string DefaultFolder = @"C:\Games\RynthSuite\RynthNet";
|
||||
public static readonly string DefaultFolder = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthNet"); // C:\Games\RynthSuite\RynthNet by default
|
||||
/// <summary>The settings folder; RYNTHNET_DIR overrides it (tests, portable setups).</summary>
|
||||
public static string Folder => Environment.GetEnvironmentVariable("RYNTHNET_DIR") is { Length: > 0 } dir ? dir : DefaultFolder;
|
||||
public static string FilePath => Path.Combine(Folder, "settings.json");
|
||||
|
|
|
|||
188
Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs
Normal file
188
Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthTracker;
|
||||
|
||||
/// <summary>
|
||||
/// Counts your kills, including the extra monsters a ring, wall, blast or chain spell kills.
|
||||
///
|
||||
/// Two ways a kill is counted:
|
||||
/// 1. The server's killer notification (it goes only to whoever landed the killing blow).
|
||||
/// One notification is one kill, as before.
|
||||
/// 2. A corpse ("Corpse of X") with no notification for it, when you hit an X with a
|
||||
/// multi-target spell in the last <see cref="TokenLifeMs"/>. Some servers send no
|
||||
/// notification for the extra monsters a spell kills (chain spells on Conquest), and on
|
||||
/// ACE a killing blow sends no damage line either, so the corpse is the one sign left.
|
||||
///
|
||||
/// "Multi-target" is read from the combat log: one cast's damage lines (and kill notices)
|
||||
/// arrive together, so lines no more than <see cref="VolleyGapMs"/> apart are one volley, and
|
||||
/// a volley with two or more of them hit several monsters. Each name hit in such a volley may
|
||||
/// be counted from its corpse as many times as that volley hit it (tokens). A single-target
|
||||
/// hit never makes a corpse count: a monster you hit once that someone else then finished
|
||||
/// isn't yours, the same as before.
|
||||
///
|
||||
/// A notification is matched to its corpse later (the corpse forms after the death animation),
|
||||
/// so a kill counted by its notification isn't counted again by its corpse.
|
||||
///
|
||||
/// Pure logic, no host: the plugin passes every event with its time, so tests can drive it.
|
||||
/// </summary>
|
||||
internal sealed class KillCounter
|
||||
{
|
||||
/// <summary>Damage lines and kill notices this close together belong to one cast.</summary>
|
||||
public const double VolleyGapMs = 800;
|
||||
/// <summary>How long after a multi-target hit a monster's corpse still counts as your kill.</summary>
|
||||
public const double TokenLifeMs = 15000;
|
||||
/// <summary>How long a kill notice waits for its corpse.</summary>
|
||||
public const double NoticeLifeMs = 20000;
|
||||
/// <summary>How long a single-target hit is remembered (only to explain an uncounted corpse in the log).</summary>
|
||||
public const double HitMemoryMs = 15000;
|
||||
|
||||
public int Kills { get; private set; }
|
||||
public int NoticeKills { get; private set; }
|
||||
public int CorpseKills { get; private set; }
|
||||
|
||||
private readonly List<(string Message, DateTime At)> _notices = new();
|
||||
private readonly Dictionary<string, (int Count, DateTime Until)> _tokens = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, DateTime> _lastHit = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// The volley in progress: hits per name, and how many members (lines + notices) it has.
|
||||
private readonly Dictionary<string, int> _volley = new(StringComparer.OrdinalIgnoreCase);
|
||||
private int _volleyMembers;
|
||||
private DateTime _volleyLast = DateTime.MinValue;
|
||||
|
||||
/// <summary>The server's killer notification: always one kill.</summary>
|
||||
public void OnKillNotice(string? message, DateTime now)
|
||||
{
|
||||
Kills++;
|
||||
NoticeKills++;
|
||||
Prune(now);
|
||||
_notices.Add((message ?? "", now));
|
||||
JoinVolley(now);
|
||||
// A notice is one of the volley's monsters too (the killing blow sends no damage line),
|
||||
// under the name of a monster we hit that the message contains.
|
||||
string? name = LongestRecentHitIn(message ?? "", now);
|
||||
if (name != null) _volley[name] = _volley.TryGetValue(name, out int n) ? n + 1 : 1;
|
||||
GrantTokens(now);
|
||||
}
|
||||
|
||||
private string? LongestRecentHitIn(string message, DateTime now)
|
||||
{
|
||||
string? best = null;
|
||||
foreach (var kv in _lastHit)
|
||||
{
|
||||
if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) continue;
|
||||
if (message.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) < 0) continue;
|
||||
if (best == null || kv.Key.Length > best.Length) best = kv.Key;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>One of your damage lines, naming the monster it hurt.</summary>
|
||||
public void OnHit(string victim, DateTime now)
|
||||
{
|
||||
if (string.IsNullOrEmpty(victim)) return;
|
||||
JoinVolley(now);
|
||||
_volley[victim] = _volley.TryGetValue(victim, out int n) ? n + 1 : 1;
|
||||
_lastHit[victim] = now;
|
||||
GrantTokens(now);
|
||||
}
|
||||
|
||||
/// <summary>What a corpse turned out to be.</summary>
|
||||
public enum CorpseResult
|
||||
{
|
||||
/// <summary>Its kill notice already counted it.</summary>
|
||||
Notified,
|
||||
/// <summary>No notice, but you hit it with a multi-target spell: counted now.</summary>
|
||||
Counted,
|
||||
/// <summary>You hit a monster of that name, but only single-target: not counted (someone else's kill?).</summary>
|
||||
HitNotCounted,
|
||||
/// <summary>Nothing of yours.</summary>
|
||||
NotOurs,
|
||||
}
|
||||
|
||||
/// <summary>A corpse appeared; <paramref name="monsterName"/> is the X of "Corpse of X".</summary>
|
||||
public CorpseResult OnCorpse(string monsterName, DateTime now)
|
||||
{
|
||||
if (string.IsNullOrEmpty(monsterName)) return CorpseResult.NotOurs;
|
||||
Prune(now);
|
||||
|
||||
// The oldest notice that names this monster.
|
||||
int match = -1;
|
||||
for (int i = 0; i < _notices.Count; i++)
|
||||
if (_notices[i].Message.IndexOf(monsterName, StringComparison.OrdinalIgnoreCase) >= 0) { match = i; break; }
|
||||
if (match >= 0)
|
||||
{
|
||||
_notices.RemoveAt(match);
|
||||
// It was one of the monsters a multi-target volley hit: it no longer vouches for another.
|
||||
if (_tokens.TryGetValue(monsterName, out var used) && used.Count > 0)
|
||||
_tokens[monsterName] = (used.Count - 1, used.Until);
|
||||
return CorpseResult.Notified;
|
||||
}
|
||||
|
||||
if (_tokens.TryGetValue(monsterName, out var t) && t.Count > 0 && t.Until >= now)
|
||||
{
|
||||
_tokens[monsterName] = (t.Count - 1, t.Until);
|
||||
Kills++;
|
||||
CorpseKills++;
|
||||
return CorpseResult.Counted;
|
||||
}
|
||||
|
||||
return _lastHit.TryGetValue(monsterName, out DateTime h) && (now - h).TotalMilliseconds <= HitMemoryMs
|
||||
? CorpseResult.HitNotCounted
|
||||
: CorpseResult.NotOurs;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Kills = NoticeKills = CorpseKills = 0;
|
||||
_notices.Clear();
|
||||
_tokens.Clear();
|
||||
_lastHit.Clear();
|
||||
_volley.Clear();
|
||||
_volleyMembers = 0;
|
||||
_volleyLast = DateTime.MinValue;
|
||||
}
|
||||
|
||||
private void JoinVolley(DateTime now)
|
||||
{
|
||||
if ((now - _volleyLast).TotalMilliseconds > VolleyGapMs)
|
||||
{
|
||||
_volley.Clear();
|
||||
_volleyMembers = 0;
|
||||
}
|
||||
_volleyMembers++;
|
||||
_volleyLast = now;
|
||||
}
|
||||
|
||||
// A volley that hit several monsters makes each name it hit countable from its corpse, as
|
||||
// many times as the volley hit that name. Max, not sum: the next cast hits the same monsters
|
||||
// again, and two casts at two monsters are still two monsters.
|
||||
private void GrantTokens(DateTime now)
|
||||
{
|
||||
if (_volleyMembers < 2) return;
|
||||
DateTime until = now.AddMilliseconds(TokenLifeMs);
|
||||
foreach (var kv in _volley)
|
||||
{
|
||||
int have = _tokens.TryGetValue(kv.Key, out var t) && t.Until >= now ? t.Count : 0;
|
||||
_tokens[kv.Key] = (Math.Max(have, kv.Value), until);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly List<string> _pruneScratch = new();
|
||||
private void Prune(DateTime now)
|
||||
{
|
||||
_notices.RemoveAll(n => (now - n.At).TotalMilliseconds > NoticeLifeMs);
|
||||
if (_tokens.Count > 32)
|
||||
{
|
||||
_pruneScratch.Clear();
|
||||
foreach (var kv in _tokens) if (kv.Value.Until < now) _pruneScratch.Add(kv.Key);
|
||||
foreach (string k in _pruneScratch) _tokens.Remove(k);
|
||||
}
|
||||
if (_lastHit.Count > 64)
|
||||
{
|
||||
_pruneScratch.Clear();
|
||||
foreach (var kv in _lastHit) if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _pruneScratch.Add(kv.Key);
|
||||
foreach (string k in _pruneScratch) _lastHit.Remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -40,6 +40,10 @@ public static unsafe class PluginExports
|
|||
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
|
||||
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
|
||||
|
||||
// Corpses (0.3.0): a kill a ring, wall or chain spell made without a kill notice is found by its corpse.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,11 @@
|
|||
<RynthPluginDescription>Kills, experience and luminance per hour for each session.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Reading our hits out of the combat log (victim + amount); RynthAi reads the same lines. -->
|
||||
<Compile Include="..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
|
||||
namespace RynthCore.Plugin.RynthTracker;
|
||||
|
|
@ -8,7 +9,7 @@ namespace RynthCore.Plugin.RynthTracker;
|
|||
public sealed class RynthTrackerPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker");
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.1");
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
|
||||
|
||||
private uint _playerId;
|
||||
private bool _loginComplete;
|
||||
|
|
@ -24,12 +25,28 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
|
|||
// blow: a fellow's kill, a summon's kill or a mob someone else finished never counts,
|
||||
// and neither does the XP they bring (damage share, fellowship share, quests). That XP
|
||||
// still counts toward the totals and XP/hour.
|
||||
//
|
||||
// 0.3.0: plus the extra monsters a ring, wall, blast or chain spell kills when the
|
||||
// server sends no notification for them (chain spells on Conquest): their corpse counts
|
||||
// when you hit that monster with a multi-target spell just before (KillCounter.cs).
|
||||
private long _killXp;
|
||||
private int _xpKills; // kills that closed their window (the per-kill divisor)
|
||||
private int _openKills; // kills whose window is still open
|
||||
private DateTime _killWindowUntil; // XP rises seen until then belong to those kills
|
||||
private const double KillWindowSec = 2.5;
|
||||
|
||||
// Kill notices, our damage lines and corpses, for the kills a notice doesn't cover.
|
||||
private readonly KillCounter _killCounter = new();
|
||||
// Corpses waiting for their name (the client may not have it on the create tick).
|
||||
private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new();
|
||||
private const double CorpseNameWaitSec = 3.0;
|
||||
private const int MaxPendingCorpses = 256;
|
||||
// XP that landed outside any kill window: a kill found by its corpse (seconds after the
|
||||
// death animation) takes the XP of the few seconds before it.
|
||||
private readonly List<(DateTime At, long Xp)> _unattributedXp = new();
|
||||
private const double CorpseXpLookbackSec = 8.0;
|
||||
private int _corpseLogCount;
|
||||
|
||||
private int _tickCounter;
|
||||
|
||||
// Everything comes from the player's own properties, never from chat text:
|
||||
|
|
@ -126,6 +143,76 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
|
|||
_killsTotal++;
|
||||
_openKills++;
|
||||
_killWindowUntil = DateTime.UtcNow.AddSeconds(KillWindowSec);
|
||||
_killCounter.OnKillNotice(deathMessage, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
// Our damage lines name each monster a spell hurt (one line per monster for rings, walls,
|
||||
// blasts and chain spells): that is how a multi-target hit is recognised.
|
||||
public override void OnChatWindowText(string? text, int chatType, ref int eat)
|
||||
{
|
||||
if (!_loginComplete) return;
|
||||
if (CombatText.TryParseOutgoingHit(text, out string victim, out _))
|
||||
_killCounter.OnHit(victim, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
// Corpses are read on the tick (their name may not be readable yet on the create).
|
||||
public override void OnCreateObject(uint objectId)
|
||||
{
|
||||
if (!_loginComplete || objectId == 0) return;
|
||||
if (_pendingCorpses.Count >= MaxPendingCorpses) _pendingCorpses.RemoveAt(0);
|
||||
_pendingCorpses.Add((objectId, DateTime.UtcNow));
|
||||
}
|
||||
|
||||
public override void OnDeleteObject(uint objectId)
|
||||
{
|
||||
for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
|
||||
if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i);
|
||||
}
|
||||
|
||||
/// <summary>Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.</summary>
|
||||
private void CheckPendingCorpses()
|
||||
{
|
||||
if (_pendingCorpses.Count == 0) return;
|
||||
if (!Host.HasGetObjectName) { _pendingCorpses.Clear(); return; }
|
||||
DateTime now = DateTime.UtcNow;
|
||||
for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var (id, seen) = _pendingCorpses[i];
|
||||
if (!Host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name))
|
||||
{
|
||||
if ((now - seen).TotalSeconds > CorpseNameWaitSec) _pendingCorpses.RemoveAt(i);
|
||||
continue;
|
||||
}
|
||||
_pendingCorpses.RemoveAt(i);
|
||||
string? monster = CombatText.CorpseOwnerName(name);
|
||||
if (monster == null) continue;
|
||||
var result = _killCounter.OnCorpse(monster, now);
|
||||
if (result == KillCounter.CorpseResult.Counted)
|
||||
CountCorpseKill(now);
|
||||
if ((result == KillCounter.CorpseResult.Counted || result == KillCounter.CorpseResult.HitNotCounted)
|
||||
&& _corpseLogCount < 40)
|
||||
{
|
||||
_corpseLogCount++;
|
||||
Host.Log(result == KillCounter.CorpseResult.Counted
|
||||
? $"[RynthTracker] Kill counted from its corpse (no kill notice): '{name}' 0x{id:X8}, hit by a multi-target spell. Kills {_killsTotal}."
|
||||
: $"[RynthTracker] Not counted: '{name}' 0x{id:X8} - you hit it, single-target, and got no kill notice (someone else's kill?).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A kill found by its corpse: one more kill, and the XP of the seconds before it.</summary>
|
||||
private void CountCorpseKill(DateTime now)
|
||||
{
|
||||
_killsTotal++;
|
||||
bool inKillWindow = _openKills > 0 && now <= _killWindowUntil;
|
||||
if (inKillWindow) _openKills++; // closes with the window, its XP already in it
|
||||
else _xpKills++;
|
||||
for (int i = _unattributedXp.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if ((now - _unattributedXp[i].At).TotalSeconds > CorpseXpLookbackSec) continue;
|
||||
_killXp += _unattributedXp[i].Xp;
|
||||
_unattributedXp.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
|
||||
|
|
@ -148,6 +235,8 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
|
|||
Host.Log("[RynthTracker] Session reset.");
|
||||
}
|
||||
|
||||
if (_loginComplete) CheckPendingCorpses();
|
||||
|
||||
if (++_tickCounter < 30) return; // rebuild every ~0.5s at 60Hz
|
||||
_tickCounter = 0;
|
||||
if (_loginComplete) PollExperience();
|
||||
|
|
@ -171,6 +260,12 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
|
|||
long gained = _xpRise.Take(xp);
|
||||
_xpTotal += gained;
|
||||
if (inKillWindow) _killXp += gained;
|
||||
else if (gained > 0)
|
||||
{
|
||||
DateTime now = DateTime.UtcNow;
|
||||
_unattributedXp.RemoveAll(e => (now - e.At).TotalSeconds > CorpseXpLookbackSec);
|
||||
_unattributedXp.Add((now, gained));
|
||||
}
|
||||
// Capped only when past retail's 275 total AND kills keep bringing nothing: an
|
||||
// awakened character's cap is higher (Aelrynth), so the total alone can't say.
|
||||
_maxLevel = xp >= MaxLevelXp && _xpKills >= 3 && _xpTotal == 0;
|
||||
|
|
@ -213,6 +308,9 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
|
|||
_xpKills = 0;
|
||||
_openKills = 0;
|
||||
_radTotal = 0;
|
||||
_killCounter.Reset();
|
||||
_pendingCorpses.Clear();
|
||||
_unattributedXp.Clear();
|
||||
// The next read of each is the new baseline.
|
||||
_xpRise.Clear(); _lumRise.Clear(); _radRise.Clear(); _bankedRise.Clear(); _drawnRise.Clear();
|
||||
_snapshot = EmptySnapshot;
|
||||
|
|
|
|||
633
Plugins/Shared/ActionPacer.cs
Normal file
633
Plugins/Shared/ActionPacer.cs
Normal file
|
|
@ -0,0 +1,633 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ActionPacer.cs
|
||||
// One server action at a time: RynthAi's pacing of uses, casts and combat-mode
|
||||
// changes on the server's answers (2026-10-06).
|
||||
//
|
||||
// Why: Drakkon's "can't use anything" and "stuck in the cast animation" stalls on
|
||||
// DreamWeave (ops/overnight/2026-10-06-action-pacing.md). Every stall began with a
|
||||
// combat-mode change sent while a corpse use was still unanswered by the server
|
||||
// (4 of 4 onsets; 0 stalls after ~920 uses with no such overlap). Once in that state
|
||||
// the server finishes nothing that waits on an animation until a relog, and the bot
|
||||
// made it worse by firing the next cast/use every 0.4-2.5 s because nothing waited
|
||||
// for the server's answer: the client busy count it paced on was zeroed and repaired
|
||||
// hundreds of times an hour, and "cast resolved" meant the enchantment, not the
|
||||
// server's UseDone.
|
||||
//
|
||||
// The rule here:
|
||||
// * A use, a use-on, a cast or a combat-mode change that RynthAi sends is the ONE
|
||||
// outstanding server action until the server answers it:
|
||||
// - use / use-on / cast: the next UseDone (GameEvent 0x01C7) after the send,
|
||||
// whatever its error (a refusal is an answer too); a wield also counts as
|
||||
// answered when the item reads wielded (a wield gets no UseDone);
|
||||
// - combat mode: the client reads the new mode and ModeSettleMs has passed
|
||||
// (the stance animation; the server sends no UseDone for it);
|
||||
// or its time limit passes (logged; nothing is force-cleared).
|
||||
// * While one is outstanding, RynthAi starts no other one (MayStart; mode changes
|
||||
// are refused right at ChangeCombatModeFor) and moves or turns the character
|
||||
// only to stop real movement (MoveAudit asks HoldsMovement).
|
||||
// * Heals keep some priority: at Emergency Heal At a heal may go ahead of a corpse/door
|
||||
// use the server hasn't answered after EmergencyAfterWorldUseMs, and one heal may
|
||||
// follow a cast whose result is already in (the server queues one cast behind the
|
||||
// recoil). A heal under the plain Heal line waits for the use's answer (2026-10-06,
|
||||
// below: an action during the use's server turn stops that turn for good).
|
||||
// * And nothing starts while the character is still animating: the client's own motion
|
||||
// queue (CMotionInterp pending motions, the engine's cast gate: GetCastBusyState) must
|
||||
// be empty, for uses, kits, potions, casts, stance changes, wields and the item
|
||||
// managers' moves (GestureHolds). Melee/missile attack repeats are exempt (MayStart
|
||||
// with gestureGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an
|
||||
// emergency heal), logged, like Combat/CastGateWatchdog for casts.
|
||||
//
|
||||
// Why the animation gate (2026-10-06 afternoon, ops/overnight/2026-10-06-turnto-stall.md,
|
||||
// replayed through ACE's own physics code): on ACE a use in reach is finished by the
|
||||
// server's MoveToManager turning the character (TurnRight on the server's copy of the
|
||||
// motion state). Every server motion for the character (a swing, a kit, a cast gesture,
|
||||
// a stance) is applied with MotionInterp.apply_raw_movement, which rewrites the
|
||||
// interpreted TurnCommand from the raw state (none) and so stops that TurnRight; the
|
||||
// MoveToManager is never told (its FailProgressCount is counted but never acted on) and
|
||||
// stays Initialized, which keeps the player "moving or animating", so Player_Tick never
|
||||
// runs the use's callback either. The use is answered only when the next use fails it:
|
||||
// "UseDone with no error, nothing opens", the stall's signature. Starting nothing while
|
||||
// the character animates, and nothing while a use's turn is unanswered, keeps every
|
||||
// server motion out of every server turn.
|
||||
//
|
||||
// Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before.
|
||||
// Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal enum PacedKind
|
||||
{
|
||||
None,
|
||||
/// <summary>A door, corpse, portal or NPC: the server walks/turns the character to it first.</summary>
|
||||
WorldUse,
|
||||
/// <summary>A kit, potion, stone, wand or weapon (wield), scroll... in the character's own packs.</summary>
|
||||
ItemUse,
|
||||
/// <summary>A spell cast.</summary>
|
||||
Cast,
|
||||
/// <summary>A combat-mode (stance) change.</summary>
|
||||
CombatMode,
|
||||
}
|
||||
|
||||
internal enum HealNeed
|
||||
{
|
||||
None,
|
||||
/// <summary>Health under a heal line.</summary>
|
||||
Heal,
|
||||
/// <summary>Health at or under Emergency Heal At.</summary>
|
||||
Emergency,
|
||||
}
|
||||
|
||||
/// <summary>The one server action RynthAi is waiting on.</summary>
|
||||
internal sealed class PacedAction
|
||||
{
|
||||
public PacedKind Kind;
|
||||
public uint Id;
|
||||
public string Label = "";
|
||||
public string Who = "";
|
||||
public long SentMs;
|
||||
public int SeqAtSend;
|
||||
public int ModeTarget;
|
||||
public bool WieldedAtSend;
|
||||
public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil
|
||||
public bool HealQueued; // the one heal allowed behind that recoil went out
|
||||
public long ModeSeenMs; // when the client first read the requested mode
|
||||
public long WieldSeenMs; // when a wield first read done
|
||||
public readonly HashSet<string> LoggedWaits = new();
|
||||
}
|
||||
|
||||
internal static class ActionPacer
|
||||
{
|
||||
/// <summary>Off = nothing is paced (every call goes through as before). RynthAi turns it on.</summary>
|
||||
public static volatile bool Enabled;
|
||||
|
||||
/// <summary>Clock (ms); tests replace it.</summary>
|
||||
public static Func<long> NowMs = () => Environment.TickCount64;
|
||||
|
||||
// Time limits: the longest the server took to answer in 3.7 h of healthy logs (10-05/10-06,
|
||||
// p99 / max): corpse use 3.0 / 3.7 s, kit 2.5 s, buff cast 3.6 s, vital cast 4.7 / 5.0 s.
|
||||
public const long WorldUseMaxMs = 5000;
|
||||
public const long ItemUseMaxMs = 3500;
|
||||
public const long CastMaxMs = 7000;
|
||||
public const long ModeMaxMs = 2000;
|
||||
/// <summary>The stance animation after the client reads the new mode: no action before it ends.</summary>
|
||||
public const long ModeSettleMs = 800;
|
||||
/// <summary>A wield that reads done: a short settle for the wield motion.</summary>
|
||||
public const long WieldSettleMs = 150;
|
||||
/// <summary>At Emergency Heal At a heal may go ahead of a door/corpse use unanswered this long. It stops
|
||||
/// the server's walk/turn to that object (the use is then answered by the next one); a plain heal waits.</summary>
|
||||
public const long EmergencyAfterWorldUseMs = 300;
|
||||
/// <summary>The client's motion queue reading busy this long is taken as stuck: the action goes (logged).
|
||||
/// Same backstop as Combat/CastGateWatchdog (no real gesture, stance or swing lasts this long).</summary>
|
||||
public const long GestureHoldMaxMs = 4000;
|
||||
/// <summary>An emergency heal waits for the character's animation at most this long.</summary>
|
||||
public const long GestureEmergencyMaxMs = 1500;
|
||||
/// <summary>A heal behind a stance change: once the client has read the new mode this long.</summary>
|
||||
public const long HealAfterModeReadMs = 300;
|
||||
/// <summary>An engine without UseDone: an action counts as answered after this (no real pacing).</summary>
|
||||
public const long NoUseDoneFallbackMs = 600;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static PacedAction? _cur;
|
||||
|
||||
// Counters for /ra pace and the periodic summary.
|
||||
private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped;
|
||||
private static long _heldStarts, _heldMoves, _healsAhead;
|
||||
private static long _gestureHolds, _gestureLimits;
|
||||
private static long _gestureBusySince; // when the client's motion queue was first seen busy (0 = clear)
|
||||
private static bool _gestureOverride; // the hold limit passed: open until the queue reads clear
|
||||
private static readonly HashSet<string> _gestureLogged = new();
|
||||
private static long _maxWaitMs;
|
||||
private static string _maxWaitWhat = "";
|
||||
private static readonly Dictionary<string, int> _holdsByWho = new();
|
||||
private static string _lastTimeout = "";
|
||||
|
||||
public static long Started => _started;
|
||||
public static long Answered => _answered;
|
||||
public static long TimedOut => _timedOut;
|
||||
public static long SentOverOutstanding => _sentOverOutstanding;
|
||||
public static long ModeChangesRefused => _modeRefused;
|
||||
public static long ModeChangesSkipped => _modeSkipped;
|
||||
public static long HeldStarts => _heldStarts;
|
||||
public static long HeldMoves => _heldMoves;
|
||||
public static long HealsAhead => _healsAhead;
|
||||
public static long GestureHoldCount => _gestureHolds;
|
||||
public static long GestureLimits => _gestureLimits;
|
||||
|
||||
/// <summary>Back to a fresh load (Init, logout, tests). Enabled is left as it is.</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_cur = null;
|
||||
_started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0;
|
||||
_heldStarts = _heldMoves = _healsAhead = 0;
|
||||
_gestureHolds = _gestureLimits = 0;
|
||||
_swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear();
|
||||
_gestureBusySince = 0;
|
||||
_gestureOverride = false;
|
||||
_gestureLogged.Clear();
|
||||
_maxWaitMs = 0;
|
||||
_maxWaitWhat = "";
|
||||
_holdsByWho.Clear();
|
||||
_lastTimeout = "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget the outstanding action (logout, death, portal): the server dropped it.</summary>
|
||||
public static void Forget(string why)
|
||||
{
|
||||
lock (Gate) { _cur = null; }
|
||||
}
|
||||
|
||||
// ── Recording what went out ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Records an action that just went out. <paramref name="seqAtSend"/> is the UseDone count read
|
||||
/// BEFORE the send. Logs once when it went out over another unanswered action (a player command,
|
||||
/// a meta, or a heal let ahead).
|
||||
/// </summary>
|
||||
public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0)
|
||||
{
|
||||
if (!Enabled || kind == PacedKind.None) return;
|
||||
PacedAction? prev = Current(host);
|
||||
long now = NowMs();
|
||||
var a = new PacedAction
|
||||
{
|
||||
Kind = kind, Id = id, Label = label, Who = who, SentMs = now, SeqAtSend = seqAtSend, ModeTarget = modeTarget,
|
||||
};
|
||||
if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id);
|
||||
string? over = null;
|
||||
lock (Gate)
|
||||
{
|
||||
_started++;
|
||||
if (prev != null)
|
||||
{
|
||||
_sentOverOutstanding++;
|
||||
over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms";
|
||||
}
|
||||
_cur = a;
|
||||
}
|
||||
if (over != null) Log(host, over);
|
||||
}
|
||||
|
||||
/// <summary>A cast's result (enchantment landed, "You cast ...") is in: the server is in its recoil.</summary>
|
||||
public static void NoteCastResult()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (_cur is { Kind: PacedKind.Cast }) _cur.ResultSeen = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ── The outstanding action ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The action still waiting for the server's answer, or null. Each call settles answers and
|
||||
/// time limits first, so it is always current.
|
||||
/// </summary>
|
||||
public static PacedAction? Current(RynthCoreHost host)
|
||||
{
|
||||
if (!Enabled) return null;
|
||||
PacedAction? a;
|
||||
lock (Gate) a = _cur;
|
||||
if (a == null) return null;
|
||||
|
||||
long now = NowMs();
|
||||
long age = now - a.SentMs;
|
||||
string? answeredHow = null;
|
||||
bool timedOut = false;
|
||||
|
||||
switch (a.Kind)
|
||||
{
|
||||
case PacedKind.WorldUse:
|
||||
case PacedKind.ItemUse:
|
||||
case PacedKind.Cast:
|
||||
{
|
||||
bool hasSeq = false;
|
||||
int seq = 0;
|
||||
try { hasSeq = host.HasUseDoneSeq; if (hasSeq) seq = host.GetUseDoneSeq(); } catch { hasSeq = false; }
|
||||
if (hasSeq && seq != a.SeqAtSend)
|
||||
{
|
||||
answeredHow = "UseDone";
|
||||
}
|
||||
else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend)
|
||||
{
|
||||
if (a.WieldSeenMs == 0) a.WieldSeenMs = now;
|
||||
if (now - a.WieldSeenMs >= WieldSettleMs) answeredHow = "wield";
|
||||
}
|
||||
else if (!hasSeq && age >= NoUseDoneFallbackMs)
|
||||
{
|
||||
answeredHow = "time (no UseDone on this engine)";
|
||||
}
|
||||
long max = a.Kind switch { PacedKind.WorldUse => WorldUseMaxMs, PacedKind.Cast => CastMaxMs, _ => ItemUseMaxMs };
|
||||
if (answeredHow == null && age >= max) timedOut = true;
|
||||
break;
|
||||
}
|
||||
case PacedKind.CombatMode:
|
||||
{
|
||||
int mode = -1;
|
||||
try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; }
|
||||
if (mode == a.ModeTarget || mode < 0)
|
||||
{
|
||||
if (a.ModeSeenMs == 0) a.ModeSeenMs = now;
|
||||
if (age >= ModeSettleMs) answeredHow = "mode";
|
||||
}
|
||||
if (answeredHow == null && age >= ModeMaxMs) timedOut = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (answeredHow == null && !timedOut) return a;
|
||||
|
||||
string? line = null;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!ReferenceEquals(_cur, a)) return _cur; // replaced meanwhile
|
||||
_cur = null;
|
||||
if (timedOut)
|
||||
{
|
||||
_timedOut++;
|
||||
_lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms";
|
||||
line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)";
|
||||
}
|
||||
else
|
||||
{
|
||||
_answered++;
|
||||
}
|
||||
}
|
||||
if (line != null) Log(host, line);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>True while an action is waiting for the server (out: it).</summary>
|
||||
public static bool Outstanding(RynthCoreHost host, out PacedAction? action)
|
||||
{
|
||||
action = Current(host);
|
||||
return action != null;
|
||||
}
|
||||
|
||||
// ── Gates ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// May <paramref name="who"/> send a use, a cast or a mode change now? False (with why) while
|
||||
/// another action waits for the server, except the heal rules in the file header, and while
|
||||
/// the character is still animating (<see cref="GestureHolds"/>; skipped with
|
||||
/// <paramref name="gestureGate"/> false: melee/missile attack repeats). One log line per
|
||||
/// outstanding action (or animation) and subsystem.
|
||||
/// </summary>
|
||||
public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true)
|
||||
{
|
||||
if (!Enabled) { why = ""; return true; }
|
||||
if (!OutstandingAllows(host, who, heal, out why)) return false;
|
||||
if (gestureGate && GestureHolds(host, who, heal, out why)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why)
|
||||
{
|
||||
why = "";
|
||||
PacedAction? a = Current(host);
|
||||
if (a == null) return true;
|
||||
long age = NowMs() - a.SentMs;
|
||||
|
||||
if (heal != HealNeed.None)
|
||||
{
|
||||
if (a.Kind == PacedKind.WorldUse && heal == HealNeed.Emergency && age >= EmergencyAfterWorldUseMs)
|
||||
{
|
||||
lock (Gate) _healsAhead++;
|
||||
Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)");
|
||||
return true;
|
||||
}
|
||||
// A stance change (most often the one this heal asked for: the wand swap, or peace for
|
||||
// a kit): the heal goes once the client has read the new mode for HealAfterModeReadMs,
|
||||
// like BuffManager's emergency settle, not the full ModeSettleMs.
|
||||
if (a.Kind == PacedKind.CombatMode && a.ModeSeenMs != 0 && NowMs() - a.ModeSeenMs >= HealAfterModeReadMs)
|
||||
return true;
|
||||
if (a.Kind == PacedKind.Cast && a.ResultSeen && !a.HealQueued)
|
||||
{
|
||||
a.HealQueued = true;
|
||||
lock (Gate) _healsAhead++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet";
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
_heldStarts++;
|
||||
_holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1;
|
||||
if (age > _maxWaitMs) { _maxWaitMs = age; _maxWaitWhat = Describe(a.Kind, a.Label); }
|
||||
log = a.LoggedWaits.Add(who);
|
||||
}
|
||||
if (log) Log(host, $"[Pace] {who} waits: {why}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True (with why) while the character is still animating: the client's own motion queue
|
||||
/// (CMotionInterp pending motions, read by the engine as GetCastBusyState) is not empty.
|
||||
/// The client animates exactly the motions the server sends for the character, a moment
|
||||
/// after the server applies them, so an empty queue means the server's copy is done too.
|
||||
/// Past GestureHoldMaxMs (GestureEmergencyMaxMs for an emergency heal) the action goes,
|
||||
/// logged once per busy spell. No opinion (false) on an engine without the gate.
|
||||
/// </summary>
|
||||
public static bool GestureHolds(RynthCoreHost host, string who, HealNeed heal, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (!Enabled) return false;
|
||||
bool busy;
|
||||
try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; }
|
||||
long now = NowMs();
|
||||
if (SwingHolds(host, who, heal, busy, now, out why)) return true;
|
||||
string? line = null;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!busy)
|
||||
{
|
||||
if (_gestureOverride)
|
||||
line = "[Pace] the character's animation queue reads clear again";
|
||||
_gestureBusySince = 0;
|
||||
_gestureOverride = false;
|
||||
_gestureLogged.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_gestureBusySince == 0) _gestureBusySince = now;
|
||||
long age = now - _gestureBusySince;
|
||||
if (!_gestureOverride && age >= GestureHoldMaxMs)
|
||||
{
|
||||
_gestureOverride = true;
|
||||
_gestureLimits++;
|
||||
line = $"[Pace] {who}: the character's animation queue has read busy for {age} ms - taken as stuck, going on";
|
||||
}
|
||||
if (_gestureOverride)
|
||||
{
|
||||
busy = false;
|
||||
}
|
||||
else if (heal == HealNeed.Emergency && age >= GestureEmergencyMaxMs)
|
||||
{
|
||||
_gestureLimits++;
|
||||
line = $"[Pace] {who}: emergency heal after {age} ms of animation - going on";
|
||||
busy = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
_gestureHolds++;
|
||||
_holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1;
|
||||
why = $"the character is still animating ({age} ms)";
|
||||
if (_gestureLogged.Add(who))
|
||||
line = $"[Pace] {who} waits: {why}";
|
||||
}
|
||||
}
|
||||
}
|
||||
if (line != null) Log(host, line);
|
||||
return busy;
|
||||
}
|
||||
|
||||
// A swing sent but not animating yet (Drakkon 2026-10-06 16:45:37): the wand's use went 110 ms
|
||||
// after a MeleeAttack, before the swing showed in the client's motion queue, so the motion gate
|
||||
// let it through; the switch landed on the swing the server was starting and the next cast was
|
||||
// held open. After CombatManager sends an attack, nothing else starts until the client's motion
|
||||
// queue has read busy and then clear (the swing played), or SwingStartMaxMs passes.
|
||||
public const long SwingStartMaxMs = 1500;
|
||||
public const long SwingEmergencyMaxMs = 500;
|
||||
private static long _swingSentMs;
|
||||
private static bool _swingSeenBusy;
|
||||
private static long _swingHolds;
|
||||
private static readonly HashSet<string> _swingLogged = new();
|
||||
public static long SwingHoldCount => _swingHolds;
|
||||
|
||||
/// <summary>CombatManager sent a melee or missile attack.</summary>
|
||||
public static void NoteAttackSent()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_swingSentMs = NowMs();
|
||||
_swingSeenBusy = false;
|
||||
_swingLogged.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SwingHolds(RynthCoreHost host, string who, HealNeed heal, bool busy, long now, out string why)
|
||||
{
|
||||
why = "";
|
||||
string? line = null;
|
||||
bool hold = false;
|
||||
lock (Gate)
|
||||
{
|
||||
if (_swingSentMs == 0) return false;
|
||||
long age = now - _swingSentMs;
|
||||
if (busy) _swingSeenBusy = true;
|
||||
if ((_swingSeenBusy && !busy) || age >= SwingStartMaxMs)
|
||||
{
|
||||
_swingSentMs = 0;
|
||||
}
|
||||
else if (!_swingSeenBusy && !(heal == HealNeed.Emergency && age >= SwingEmergencyMaxMs))
|
||||
{
|
||||
hold = true;
|
||||
_swingHolds++;
|
||||
why = $"a swing sent {age} ms ago hasn't started animating yet";
|
||||
if (_swingLogged.Add(who)) line = $"[Pace] {who} waits: {why}";
|
||||
}
|
||||
}
|
||||
if (line != null) Log(host, line);
|
||||
return hold;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the outstanding action is one the server animates (all of them: the walk/turn
|
||||
/// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds
|
||||
/// RynthAi's movement starts and turns meanwhile.
|
||||
/// </summary>
|
||||
public static bool HoldsMovement(RynthCoreHost host, out string what)
|
||||
{
|
||||
what = "";
|
||||
PacedAction? a = Current(host);
|
||||
if (a == null) return false;
|
||||
what = $"{Describe(a.Kind, a.Label)} ({a.Who}, {NowMs() - a.SentMs} ms)";
|
||||
lock (Gate) _heldMoves++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
internal static string Describe(PacedKind kind, string label) => kind switch
|
||||
{
|
||||
PacedKind.WorldUse => $"the use of {label}",
|
||||
PacedKind.ItemUse => $"the use of {label}",
|
||||
PacedKind.Cast => $"the cast of {label}",
|
||||
PacedKind.CombatMode => $"the change to {label} mode",
|
||||
_ => label,
|
||||
};
|
||||
|
||||
internal static string ModeName(int mode) => mode switch
|
||||
{
|
||||
1 => "Peace", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {mode}",
|
||||
};
|
||||
|
||||
internal static bool IsWieldedByPlayer(RynthCoreHost host, uint id)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (id == 0 || !host.HasGetObjectWielderInfo || !host.HasGetPlayerId) return false;
|
||||
uint player = host.GetPlayerId();
|
||||
return player != 0 && host.TryGetObjectWielderInfo(id, out uint wielder, out _) && wielder == player;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>World object (no container, no wielder) = the server walks to it; else an item of ours.</summary>
|
||||
internal static PacedKind ClassifyUse(RynthCoreHost host, uint id, bool doorOrCorpse)
|
||||
{
|
||||
if (doorOrCorpse) return PacedKind.WorldUse;
|
||||
try
|
||||
{
|
||||
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _))
|
||||
return container == 0 && wielder == 0 ? PacedKind.WorldUse : PacedKind.ItemUse;
|
||||
}
|
||||
catch { }
|
||||
return PacedKind.ItemUse;
|
||||
}
|
||||
|
||||
internal static int UseDoneSeqNow(RynthCoreHost host)
|
||||
{
|
||||
try { return host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { return 0; }
|
||||
}
|
||||
|
||||
private static void Log(RynthCoreHost host, string line)
|
||||
{
|
||||
try { host.Log(line); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>Lines for /ra pace.</summary>
|
||||
public static string[] DescribeLines(RynthCoreHost host)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
PacedAction? a = Current(host);
|
||||
lines.Add($"Action pacing: {(Enabled ? "on" : "off")} (one server action at a time; see ops note 2026-10-06-action-pacing)");
|
||||
lines.Add(a == null
|
||||
? " Waiting on: nothing"
|
||||
: $" Waiting on: {Describe(a.Kind, a.Label)} from {a.Who}, sent {NowMs() - a.SentMs} ms ago{(a.ResultSeen ? " (result in, recoil)" : "")}");
|
||||
lock (Gate)
|
||||
{
|
||||
lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}");
|
||||
lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}");
|
||||
lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}");
|
||||
lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}");
|
||||
if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})");
|
||||
if (_holdsByWho.Count > 0)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
foreach (var kv in _holdsByWho) parts.Add($"{kv.Key} {kv.Value}");
|
||||
lines.Add(" Holds by subsystem: " + string.Join(", ", parts));
|
||||
}
|
||||
}
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
// ── The paced sends that are not uses ────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// CastSpell, recorded as the outstanding action. RynthAi's callers check MayStart first;
|
||||
/// <paramref name="asked"/> (a player command or meta) is never held, only recorded.
|
||||
/// </summary>
|
||||
public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false)
|
||||
{
|
||||
int seq = UseDoneSeqNow(host);
|
||||
bool ok = host.CastSpell(targetId, spellId);
|
||||
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that
|
||||
/// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change
|
||||
/// cancels the walk/turn of a pending use and fails a cast in progress) unless
|
||||
/// <paramref name="force"/>; and nothing while another server action is unanswered unless
|
||||
/// <paramref name="force"/>. Returns false only when the pacing held the request back (or the
|
||||
/// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode
|
||||
/// call was before (whose result the callers never read), so their retry timers run as before.
|
||||
/// </summary>
|
||||
public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false)
|
||||
{
|
||||
if (!host.HasChangeCombatMode) return true; // nothing to send or pace (the callers went on before too)
|
||||
if (Enabled && !force)
|
||||
{
|
||||
int current = -1;
|
||||
try { if (host.HasGetCurrentCombatMode) current = host.GetCurrentCombatMode(); } catch { current = -1; }
|
||||
if (current == mode)
|
||||
{
|
||||
lock (Gate) _modeSkipped++;
|
||||
return false;
|
||||
}
|
||||
PacedAction? a = Current(host);
|
||||
if (a != null)
|
||||
{
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
_modeRefused++;
|
||||
log = a.LoggedWaits.Add("mode:" + who);
|
||||
}
|
||||
if (log)
|
||||
Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)");
|
||||
return false;
|
||||
}
|
||||
if (GestureHolds(host, "mode:" + who, HealNeed.None, out _))
|
||||
{
|
||||
lock (Gate) _modeRefused++;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
int seq = UseDoneSeqNow(host);
|
||||
if (host.ChangeCombatMode(mode))
|
||||
Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
127
Plugins/Shared/CombatText.cs
Normal file
127
Plugins/Shared/CombatText.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/CombatText.cs
|
||||
// Reading YOUR hits out of the combat log: who was hit and for how much.
|
||||
// Compiled into RynthAi and RynthTracker (linked source), so both read the
|
||||
// same lines the same way.
|
||||
//
|
||||
// A spell that hits several monsters (a ring, a wall, a blast, or a chain
|
||||
// spell on servers that have them) sends one line per monster it hurt, each
|
||||
// naming that monster:
|
||||
// ACE: "You blast Drudge Skulker for 153 points with Whirling Blade VII."
|
||||
// retail: "You scorch Mosswart Worshipper for 1,234 points of fire damage!"
|
||||
// with optional prefixes ("Critical hit! ", "Sneak Attack! ", "Overpower! ").
|
||||
// The victim's name is what tells the lines apart; nothing else in them does.
|
||||
//
|
||||
// Note (ACE SpellProjectile.DamageTarget): the line is sent only while the
|
||||
// target is still alive. The killing blow sends the killer notification
|
||||
// instead, so a monster killed by its first hit has no damage line at all.
|
||||
// ============================================================================
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class CombatText
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads one of OUR damage lines. True with the victim's name (no leading "the") and the
|
||||
/// amount; false for anything else: a monster hitting us (or our body part), drains and
|
||||
/// heals ("points of mana"), experience, evades. Allocation-light: one Substring for the name.
|
||||
/// </summary>
|
||||
public static bool TryParseOutgoingHit(string? text, out string victim, out int amount)
|
||||
{
|
||||
victim = "";
|
||||
amount = 0;
|
||||
if (string.IsNullOrEmpty(text)) return false;
|
||||
|
||||
int start = SkipPrefixes(text);
|
||||
if (!StartsWithWord(text, start, "You")) return false;
|
||||
int verbStart = start + 3;
|
||||
while (verbStart < text.Length && text[verbStart] == ' ') verbStart++;
|
||||
// The verb is one word ("blast", "gore", "scorch", "slash"...).
|
||||
int verbEnd = verbStart;
|
||||
while (verbEnd < text.Length && char.IsLetter(text[verbEnd])) verbEnd++;
|
||||
if (verbEnd == verbStart || verbEnd >= text.Length || text[verbEnd] != ' ') return false;
|
||||
|
||||
int pts = text.IndexOf(" points", verbEnd, StringComparison.OrdinalIgnoreCase);
|
||||
if (pts < 0) return false;
|
||||
|
||||
// What follows "points" decides whether it is damage.
|
||||
int w = pts + 7;
|
||||
while (w < text.Length && text[w] == ' ') w++;
|
||||
bool nextWith = WordAt(text, w, "with");
|
||||
bool nextOf = WordAt(text, w, "of");
|
||||
bool isDamage = nextWith || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
if (!isDamage) return false;
|
||||
|
||||
// The number right before " points".
|
||||
int i = pts - 1;
|
||||
long val = 0, mult = 1;
|
||||
bool any = false;
|
||||
while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ','))
|
||||
{
|
||||
if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; }
|
||||
i--;
|
||||
}
|
||||
if (!any || val <= 0 || val > 1_000_000) return false;
|
||||
|
||||
// "... <victim> for <n>": the victim runs from after the verb to " for ".
|
||||
const string forWord = " for ";
|
||||
int forAt = i - forWord.Length + 1;
|
||||
if (forAt <= verbEnd || string.CompareOrdinal(text, forAt, forWord, 0, forWord.Length) != 0) return false;
|
||||
int nameStart = verbEnd + 1;
|
||||
if (StartsWithWord(text, nameStart, "the")) nameStart += 4;
|
||||
if (forAt <= nameStart) return false;
|
||||
string name = text.Substring(nameStart, forAt - nameStart).Trim();
|
||||
// "You ... yourself", "your ..." are not monsters.
|
||||
if (name.Length == 0 || name.Equals("yourself", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.StartsWith("your ", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
victim = name;
|
||||
amount = (int)val;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The monster's name out of a corpse's name ("Corpse of Drudge Skulker"), else null.</summary>
|
||||
public static string? CorpseOwnerName(string? corpseName)
|
||||
{
|
||||
const string prefix = "Corpse of ";
|
||||
if (string.IsNullOrEmpty(corpseName) || !corpseName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
string n = corpseName.Substring(prefix.Length).Trim();
|
||||
return n.Length == 0 ? null : n;
|
||||
}
|
||||
|
||||
// "Critical hit! ", "Sneak Attack! ", "Overpower! " (any order, any number): a short run
|
||||
// of words ending in '!' before the sentence proper.
|
||||
private static int SkipPrefixes(string text)
|
||||
{
|
||||
int p = 0;
|
||||
for (int guard = 0; guard < 4; guard++)
|
||||
{
|
||||
while (p < text.Length && text[p] == ' ') p++;
|
||||
int bang = text.IndexOf('!', p);
|
||||
if (bang < 0 || bang - p > 24) break;
|
||||
bool words = true;
|
||||
for (int k = p; k < bang; k++)
|
||||
if (!(char.IsLetter(text[k]) || text[k] == ' ')) { words = false; break; }
|
||||
if (!words || bang == p) break;
|
||||
// A sentence that itself ends in '!' ("You scorch X for 5 points of fire damage!") is
|
||||
// not a prefix: prefixes never contain "You ".
|
||||
if (StartsWithWord(text, p, "You")) break;
|
||||
p = bang + 1;
|
||||
}
|
||||
while (p < text.Length && text[p] == ' ') p++;
|
||||
return p;
|
||||
}
|
||||
|
||||
private static bool StartsWithWord(string text, int pos, string word)
|
||||
{
|
||||
if (pos < 0 || pos + word.Length > text.Length) return false;
|
||||
if (string.Compare(text, pos, word, 0, word.Length, StringComparison.OrdinalIgnoreCase) != 0) return false;
|
||||
int end = pos + word.Length;
|
||||
return end >= text.Length || !char.IsLetter(text[end]);
|
||||
}
|
||||
|
||||
private static bool WordAt(string text, int pos, string word) => StartsWithWord(text, pos, word);
|
||||
}
|
||||
|
|
@ -50,37 +50,142 @@ internal static class MoveAudit
|
|||
|
||||
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
|
||||
{
|
||||
if (on && HeldForUse(host, who, "SetAutoRun(True)")) return false;
|
||||
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on)) return false;
|
||||
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
|
||||
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); }
|
||||
return host.SetAutoRun(on);
|
||||
}
|
||||
|
||||
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
|
||||
{
|
||||
if (HeldForAction(host, who, "StopCompletely()", isStop: true)) return false;
|
||||
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
|
||||
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); }
|
||||
return host.StopCompletely();
|
||||
}
|
||||
|
||||
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
|
||||
{
|
||||
if (on && HeldForUse(host, who, $"SetMotion(0x{motion:X8}, True)")) return false;
|
||||
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion)) return false;
|
||||
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
|
||||
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else _motionsOn.Remove(motion); }
|
||||
return host.SetMotion(motion, on);
|
||||
}
|
||||
|
||||
public static bool DoMovementBy(this RynthCoreHost host, string who, uint motion, float speed, int holdKey)
|
||||
{
|
||||
if (HeldForUse(host, who, $"DoMovement(0x{motion:X8})")) return false;
|
||||
if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false;
|
||||
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
|
||||
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); }
|
||||
return host.DoMovement(motion, speed, holdKey);
|
||||
}
|
||||
|
||||
// -- Hold while any paced server action is unanswered (2026-10-06, ActionPacer) ----------
|
||||
// A use, cast or stance change the server is still animating is what a movement packet
|
||||
// disturbs: on ACE every client MoveToState is applied to the server's physics, a mode change
|
||||
// or a stop cancels the walk/turn to a used object, and a cast's end waits for its gesture.
|
||||
// While ActionPacer has one outstanding:
|
||||
// * starting to move or turning is held (returns false, one log line per action and caller);
|
||||
// * a stop goes through only when RynthAi itself has the character moving (autorun, or the
|
||||
// motion it turned on); a stop with nothing of ours moving would only send a redundant
|
||||
// movement packet in the middle of the action, so it is held as well;
|
||||
// * the deliberate kick for a held cast (Buff/Nudge), a macro stop and typed commands pass.
|
||||
// Off unless ActionPacer.Enabled (RynthAi only).
|
||||
|
||||
private static bool _autoRunOn;
|
||||
private static long _lastStartMs = long.MinValue / 2;
|
||||
/// <summary>Our "moving" state counts only this long after the last start we sent: nav re-sends
|
||||
/// autorun every second while it drives, and AC can stop on its own (arrival, a portal) without
|
||||
/// RynthAi sending a stop, so an old "on" must not hold casts back forever.</summary>
|
||||
internal const long OwnMovementFreshMs = 3000;
|
||||
private static readonly System.Collections.Generic.HashSet<uint> _motionsOn = new();
|
||||
private static readonly System.Collections.Generic.HashSet<string> _actionHoldLogged = new();
|
||||
private static long _actionHoldLoggedFor = long.MinValue;
|
||||
|
||||
/// <summary>Callers whose movement is never held: the cast nudge, a macro stop, typed commands.</summary>
|
||||
internal static bool IsExemptFromActionHold(string who) =>
|
||||
who == "Buff/Nudge" || who == "MacroStop" || who == "Command";
|
||||
|
||||
/// <summary>True when RynthAi itself has the character moving (autorun or a motion it turned on).</summary>
|
||||
internal static bool OwnMovementActive
|
||||
{
|
||||
get { lock (Gate) return (_autoRunOn || _motionsOn.Count > 0) && NowMs() - _lastStartMs < OwnMovementFreshMs; }
|
||||
}
|
||||
|
||||
/// <summary>True when the call must wait for an unanswered paced action (internal for the tests).</summary>
|
||||
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0)
|
||||
{
|
||||
if (!ActionPacer.Enabled || IsExemptFromActionHold(who)) return false;
|
||||
if (isStop)
|
||||
{
|
||||
bool moving;
|
||||
lock (Gate) moving = (motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0))
|
||||
&& NowMs() - _lastStartMs < OwnMovementFreshMs;
|
||||
if (moving) return false; // a real stop always goes through
|
||||
}
|
||||
var pending = ActionPacer.Current(host);
|
||||
if (pending == null) return false;
|
||||
if (!ActionPacer.HoldsMovement(host, out string what)) return false;
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
if (_actionHoldLoggedFor != pending.SentMs) { _actionHoldLoggedFor = pending.SentMs; _actionHoldLogged.Clear(); }
|
||||
log = Enabled && _actionHoldLogged.Add(who + (isStop ? "|stop" : "|move"));
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
string kind = isStop ? "redundant stop, nothing of ours is moving" : "move/turn";
|
||||
try { host.Log($"[Move] {PluginName}/{who} {call} held ({kind}): the server is still answering {what}"); }
|
||||
catch { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Hold while a door/corpse use is in flight (2026-10-06) ─────────────────────
|
||||
// A move or a turn sent while the server is still walking/turning the character to a used
|
||||
// door or corpse cancels that use (ACE stops its move-to chain on a client MoveToState).
|
||||
// UseAudit knows when one is in flight (opt-in, UseAudit.TrackWorldUses); until the server
|
||||
// answers (UseDone) or UseAudit.WorldUseInFlightMaxMs passes, starting to move or turning
|
||||
// is skipped and the call returns false. Stops always go through. One line per held use.
|
||||
|
||||
private static uint _heldLoggedFor;
|
||||
private static long _heldLoggedAt;
|
||||
|
||||
/// <summary>True when the call must wait for an in-flight door/corpse use (internal for the tests).</summary>
|
||||
internal static bool HeldForUse(RynthCoreHost host, string who, string call)
|
||||
{
|
||||
if (!UseAudit.WorldUseInFlight(host, out uint objectId)) return false;
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
long now = NowMs();
|
||||
log = Enabled && (objectId != _heldLoggedFor || now - _heldLoggedAt > UseAudit.WorldUseInFlightMaxMs);
|
||||
if (log) { _heldLoggedFor = objectId; _heldLoggedAt = now; }
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
try { host.Log($"[Move] {PluginName}/{who} {call} held: the server is still answering the use of 0x{objectId:X8} (moving now would cancel it)"); }
|
||||
catch { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
|
||||
{
|
||||
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion)) return false;
|
||||
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
|
||||
lock (Gate) _motionsOn.Remove(motion);
|
||||
return host.StopMovement(motion, holdKey);
|
||||
}
|
||||
|
||||
/// <summary>A heading snap. Successive turns from one subsystem collapse whatever the angle.</summary>
|
||||
public static bool TurnToHeadingBy(this RynthCoreHost host, string who, float headingDegrees)
|
||||
{
|
||||
if (HeldForUse(host, who, "TurnToHeading")) return false;
|
||||
if (HeldForAction(host, who, "TurnToHeading", isStop: false)) return false;
|
||||
Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true);
|
||||
return host.TurnToHeading(headingDegrees);
|
||||
}
|
||||
|
|
@ -131,6 +236,13 @@ internal static class MoveAudit
|
|||
_lastWrittenMs = long.MinValue;
|
||||
_repeats = 0;
|
||||
_repeatLastArg = "";
|
||||
_heldLoggedFor = 0;
|
||||
_heldLoggedAt = 0;
|
||||
_autoRunOn = false;
|
||||
_motionsOn.Clear();
|
||||
_lastStartMs = long.MinValue / 2;
|
||||
_actionHoldLogged.Clear();
|
||||
_actionHoldLoggedFor = long.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
175
Plugins/Shared/Nav3DText.cs
Normal file
175
Plugins/Shared/Nav3DText.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/Nav3DText.cs
|
||||
// Text in the world on the engine's Nav3D buffer: a small stroke font drawn as
|
||||
// filled strokes (Nav3D triangles) on an upright plane turned toward the
|
||||
// character. RynthAi's waypoint labels (NavOverlay) and RynthNav's path
|
||||
// markers both draw with it. Compiled into each plugin (linked source); no
|
||||
// host calls, so the offline tests compile it too.
|
||||
//
|
||||
// Frame: the Nav3D one (X = east metres, Y = height, Z = north metres, in the
|
||||
// player's landblock). Call only from the plugin tick (the Nav3D submit side).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>Where Nav3D geometry goes: the engine's buffer in the game, a recorder in the tests.</summary>
|
||||
internal interface INav3DSink
|
||||
{
|
||||
void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb);
|
||||
void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One line of text over a point in the world, as filled strokes facing the viewer, sized up with
|
||||
/// distance so far text stays readable. Rows stack upward from just above the point.
|
||||
/// </summary>
|
||||
internal static class Nav3DText
|
||||
{
|
||||
/// <summary>Row 0's baseline above the point (m).</summary>
|
||||
public const float LabelLift = 1.1f;
|
||||
public const float MinLineHeight = 0.30f, MaxLineHeight = 1.5f, HeightPerMetre = 0.015f;
|
||||
|
||||
/// <summary>The line height (m) for text this far from the viewer.</summary>
|
||||
public static float LineHeight(float distance) =>
|
||||
Math.Clamp(MinLineHeight + HeightPerMetre * distance, MinLineHeight, MaxLineHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Emits <paramref name="text"/> over (x, y, z), row <paramref name="row"/>, facing the viewer at
|
||||
/// (viewX, viewZ). Counts triangles in <paramref name="tris"/>; returns false (having drawn what
|
||||
/// fitted) when the next stroke would go past <paramref name="maxTris"/>.
|
||||
/// </summary>
|
||||
public static bool Emit(float x, float y, float z, string text, int row, uint color,
|
||||
float viewX, float viewZ, INav3DSink sink, ref int tris, int maxTris)
|
||||
{
|
||||
float dx = x - viewX, dz = z - viewZ;
|
||||
float d = MathF.Sqrt(dx * dx + dz * dz);
|
||||
// Text faces the viewer: its right-hand direction is the view direction turned 90° clockwise.
|
||||
float fx = 0f, fz = 1f;
|
||||
if (d > 0.01f) { fx = dx / d; fz = dz / d; }
|
||||
float rx = fz, rz = -fx;
|
||||
|
||||
float h = LineHeight(d);
|
||||
float s = h / NavStrokeFont.Height;
|
||||
float width = NavStrokeFont.Width(text) * s;
|
||||
float u0 = -width * 0.5f;
|
||||
float v0 = y + LabelLift + row * h * 1.5f;
|
||||
float half = NavStrokeFont.Stroke * 0.5f * s;
|
||||
|
||||
for (int c = 0; c < text.Length; c++)
|
||||
{
|
||||
float[][]? strokes = NavStrokeFont.Glyph(text[c]);
|
||||
if (strokes == null) continue;
|
||||
float cu = u0 + c * NavStrokeFont.Advance * s;
|
||||
foreach (float[] poly in strokes)
|
||||
{
|
||||
for (int k = 0; k + 3 < poly.Length; k += 2)
|
||||
{
|
||||
if (tris + 2 > maxTris) return false;
|
||||
float au = cu + poly[k] * s, av = v0 + poly[k + 1] * s;
|
||||
float bu = cu + poly[k + 2] * s, bv = v0 + poly[k + 3] * s;
|
||||
Quad(sink, x, z, color, rx, rz, au, av, bu, bv, half);
|
||||
tris += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// A stroke a→b in the text plane (u along the text, v up) as two triangles, its ends pushed
|
||||
// out half a stroke so corners close.
|
||||
private static void Quad(INav3DSink sink, float x, float z, uint color, float rx, float rz,
|
||||
float au, float av, float bu, float bv, float half)
|
||||
{
|
||||
float eu = bu - au, ev = bv - av;
|
||||
float len = MathF.Sqrt(eu * eu + ev * ev);
|
||||
if (len < 1e-5f) { eu = 0f; ev = 1f; }
|
||||
else { eu /= len; ev /= len; }
|
||||
au -= eu * half; av -= ev * half;
|
||||
bu += eu * half; bv += ev * half;
|
||||
float nu = -ev * half, nv = eu * half;
|
||||
|
||||
// (u, v) → world: u runs along the right-hand direction, v is height.
|
||||
float a1x = x + rx * (au + nu), a1z = z + rz * (au + nu), a1y = av + nv;
|
||||
float a2x = x + rx * (au - nu), a2z = z + rz * (au - nu), a2y = av - nv;
|
||||
float b1x = x + rx * (bu + nu), b1z = z + rz * (bu + nu), b1y = bv + nv;
|
||||
float b2x = x + rx * (bu - nu), b2z = z + rz * (bu - nu), b2y = bv - nv;
|
||||
sink.Triangle(a1x, a1y, a1z, a2x, a2y, a2z, b1x, b1y, b1z, color);
|
||||
sink.Triangle(a2x, a2y, a2z, b2x, b2y, b2z, b1x, b1y, b1z, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A small stroke font for labels in the world: digits, A-Z and a few marks, each a set of
|
||||
/// polylines on a 4 x 6 grid (y up). Lower case draws as upper case; anything else is a gap.
|
||||
/// </summary>
|
||||
internal static class NavStrokeFont
|
||||
{
|
||||
public const float Height = 6f, Advance = 5.5f, Stroke = 0.75f;
|
||||
|
||||
/// <summary>The text's drawn width in grid units.</summary>
|
||||
public static float Width(string text) => text.Length == 0 ? 0f : text.Length * Advance - (Advance - 4f);
|
||||
|
||||
public static float[][]? Glyph(char c)
|
||||
{
|
||||
c = char.ToUpperInvariant(c);
|
||||
return Glyphs.TryGetValue(c, out float[][]? g) ? g : null;
|
||||
}
|
||||
|
||||
private static float[] P(params float[] xy) => xy;
|
||||
|
||||
private static readonly Dictionary<char, float[][]> Glyphs = new()
|
||||
{
|
||||
['0'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 0, 4, 6) },
|
||||
['1'] = new[] { P(1, 5, 2, 6, 2, 0), P(1, 0, 3, 0) },
|
||||
['2'] = new[] { P(0, 6, 4, 6, 4, 3, 0, 3, 0, 0, 4, 0) },
|
||||
['3'] = new[] { P(0, 6, 4, 6, 4, 0, 0, 0), P(1, 3, 4, 3) },
|
||||
['4'] = new[] { P(0, 6, 0, 3, 4, 3), P(4, 6, 4, 0) },
|
||||
['5'] = new[] { P(4, 6, 0, 6, 0, 4, 3, 4, 4, 3, 4, 1, 3, 0, 0, 0) },
|
||||
['6'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 0, 3) },
|
||||
['7'] = new[] { P(0, 6, 4, 6, 1, 0) },
|
||||
['8'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 3, 4, 3) },
|
||||
['9'] = new[] { P(4, 3, 0, 3, 0, 6, 4, 6, 4, 0, 0, 0) },
|
||||
['A'] = new[] { P(0, 0, 0, 4, 2, 6, 4, 4, 4, 0), P(0, 3, 4, 3) },
|
||||
['B'] = new[] { P(0, 0, 0, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3), P(3, 3, 4, 2, 4, 1, 3, 0, 0, 0) },
|
||||
['C'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0) },
|
||||
['D'] = new[] { P(0, 0, 0, 6, 2, 6, 4, 4, 4, 2, 2, 0, 0, 0) },
|
||||
['E'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0), P(0, 3, 3, 3) },
|
||||
['F'] = new[] { P(4, 6, 0, 6, 0, 0), P(0, 3, 3, 3) },
|
||||
['G'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 2, 3) },
|
||||
['H'] = new[] { P(0, 0, 0, 6), P(4, 0, 4, 6), P(0, 3, 4, 3) },
|
||||
['I'] = new[] { P(1, 6, 3, 6), P(2, 6, 2, 0), P(1, 0, 3, 0) },
|
||||
['J'] = new[] { P(4, 6, 4, 0, 0, 0, 0, 2) },
|
||||
['K'] = new[] { P(0, 0, 0, 6), P(4, 6, 0, 3, 4, 0) },
|
||||
['L'] = new[] { P(0, 6, 0, 0, 4, 0) },
|
||||
['M'] = new[] { P(0, 0, 0, 6, 2, 3, 4, 6, 4, 0) },
|
||||
['N'] = new[] { P(0, 0, 0, 6, 4, 0, 4, 6) },
|
||||
['O'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0) },
|
||||
['P'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3) },
|
||||
['Q'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(2, 2, 4, -1) },
|
||||
['R'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3, 4, 0) },
|
||||
['S'] = new[] { P(4, 6, 0, 6, 0, 3, 4, 3, 4, 0, 0, 0) },
|
||||
['T'] = new[] { P(0, 6, 4, 6), P(2, 6, 2, 0) },
|
||||
['U'] = new[] { P(0, 6, 0, 0, 4, 0, 4, 6) },
|
||||
['V'] = new[] { P(0, 6, 2, 0, 4, 6) },
|
||||
['W'] = new[] { P(0, 6, 1, 0, 2, 3, 3, 0, 4, 6) },
|
||||
['X'] = new[] { P(0, 0, 4, 6), P(0, 6, 4, 0) },
|
||||
['Y'] = new[] { P(0, 6, 2, 3, 4, 6), P(2, 3, 2, 0) },
|
||||
['Z'] = new[] { P(0, 6, 4, 6, 0, 0, 4, 0) },
|
||||
['-'] = new[] { P(1, 3, 3, 3) },
|
||||
['+'] = new[] { P(1, 3, 3, 3), P(2, 2, 2, 4) },
|
||||
['.'] = new[] { P(2, 0, 2, 0.4f) },
|
||||
[','] = new[] { P(2, 0.6f, 1.5f, -0.6f) },
|
||||
[':'] = new[] { P(2, 1, 2, 1.4f), P(2, 4, 2, 4.4f) },
|
||||
['\''] = new[] { P(2, 6, 2, 4.6f) },
|
||||
['/'] = new[] { P(0, 0, 4, 6) },
|
||||
['#'] = new[] { P(1, 0, 1, 6), P(3, 0, 3, 6), P(0, 2, 4, 2), P(0, 4, 4, 4) },
|
||||
['('] = new[] { P(3, 6, 2, 5, 2, 1, 3, 0) },
|
||||
[')'] = new[] { P(1, 6, 2, 5, 2, 1, 1, 0) },
|
||||
['?'] = new[] { P(0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 2, 3, 2, 2), P(2, 0, 2, 0.4f) },
|
||||
['!'] = new[] { P(2, 6, 2, 2), P(2, 0, 2, 0.4f) },
|
||||
['_'] = new[] { P(0, 0, 4, 0) },
|
||||
};
|
||||
}
|
||||
186
Plugins/Shared/RynthInstallPaths.cs
Normal file
186
Plugins/Shared/RynthInstallPaths.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
// ============================================================================
|
||||
// RynthInstallPaths.cs - where RynthCore and RynthSuite are installed.
|
||||
//
|
||||
// ONE FILE, TWO COPIES: RynthCore src\Shared\RynthInstallPaths.cs (engine,
|
||||
// launcher, injector, loader, StatusAgent) and RynthSuite
|
||||
// Plugins\Shared\RynthInstallPaths.cs (plugins, Loot Editor). Keep them
|
||||
// byte-identical; RynthSuite's RynthAi host tests compare the two when the
|
||||
// RynthCore sibling is checked out.
|
||||
//
|
||||
// READ ONLY. This only answers "which folder"; it never writes or deletes a
|
||||
// setting, and nothing here may be used to pick a DLL or EXE to load or run.
|
||||
//
|
||||
// Order, per folder (first usable answer wins):
|
||||
// 1. environment variable RYNTHCORE_DIR / RYNTHSUITE_DIR (dev setups)
|
||||
// 2. HKCU\Software\Rynth CoreDir / SuiteDir (per-user install)
|
||||
// 3. HKLM\Software\Rynth CoreDir / SuiteDir, 32-bit view (all-users install)
|
||||
// 4. C:\Games\RynthCore / C:\Games\RynthSuite (today's layout)
|
||||
// A value counts only if it is an absolute path; anything else is skipped.
|
||||
// With nothing set the result is exactly the old hard-coded folder.
|
||||
//
|
||||
// Idea from Silentkelpie (rynth PR #1); re-implemented here.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Install;
|
||||
|
||||
/// <summary>Where <see cref="RynthInstallPaths"/> reads settings from. Tests pass a fake.</summary>
|
||||
internal interface IInstallSettingSource
|
||||
{
|
||||
/// <summary>The process environment variable, or null.</summary>
|
||||
string? EnvironmentVariable(string name);
|
||||
|
||||
/// <summary>A string value under HKCU\Software\Rynth, or null.</summary>
|
||||
string? CurrentUser(string valueName);
|
||||
|
||||
/// <summary>A string value under HKLM\Software\Rynth (32-bit registry view), or null.</summary>
|
||||
string? LocalMachine(string valueName);
|
||||
}
|
||||
|
||||
internal static class RynthInstallPaths
|
||||
{
|
||||
/// <summary>RynthCore folder when nothing is set (launcher, Runtime\, Logs\, NavData\, AcClient\).</summary>
|
||||
public const string DefaultCoreDir = @"C:\Games\RynthCore";
|
||||
|
||||
/// <summary>RynthSuite folder when nothing is set (plugins and their data, e.g. RynthAi\).</summary>
|
||||
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
|
||||
|
||||
public const string CoreEnvironmentVariable = "RYNTHCORE_DIR";
|
||||
public const string SuiteEnvironmentVariable = "RYNTHSUITE_DIR";
|
||||
|
||||
/// <summary>Key under HKCU / HKLM.</summary>
|
||||
public const string RegistryKey = @"Software\Rynth";
|
||||
public const string CoreValueName = "CoreDir";
|
||||
public const string SuiteValueName = "SuiteDir";
|
||||
|
||||
private static string? _coreDir;
|
||||
private static string? _suiteDir;
|
||||
|
||||
/// <summary>The RynthCore install folder. Resolved once per process.</summary>
|
||||
public static string CoreDir =>
|
||||
_coreDir ??= Resolve(CoreEnvironmentVariable, CoreValueName, DefaultCoreDir, SystemInstallSettings.Instance);
|
||||
|
||||
/// <summary>The RynthSuite install folder. Resolved once per process.</summary>
|
||||
public static string SuiteDir =>
|
||||
_suiteDir ??= Resolve(SuiteEnvironmentVariable, SuiteValueName, DefaultSuiteDir, SystemInstallSettings.Instance);
|
||||
|
||||
/// <summary><CoreDir>\Logs - the unified log folder.</summary>
|
||||
public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
|
||||
|
||||
/// <summary><SuiteDir>\RynthAi - RynthAi's home and data root.</summary>
|
||||
public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
|
||||
|
||||
/// <summary>
|
||||
/// The first usable folder from <paramref name="source"/>: environment, then HKCU,
|
||||
/// then HKLM, else <paramref name="fallback"/> exactly as given. Never throws.
|
||||
/// </summary>
|
||||
internal static string Resolve(string environmentVariable, string valueName, string fallback, IInstallSettingSource source)
|
||||
{
|
||||
string? found = Normalize(Ask(() => source.EnvironmentVariable(environmentVariable)))
|
||||
?? Normalize(Ask(() => source.CurrentUser(valueName)))
|
||||
?? Normalize(Ask(() => source.LocalMachine(valueName)));
|
||||
return found ?? fallback;
|
||||
}
|
||||
|
||||
private static readonly char[] BadNameChars = { '*', '?', '<', '>', '"', '|' };
|
||||
|
||||
private static string? Ask(Func<string?> read)
|
||||
{
|
||||
try { return read(); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An absolute folder path, tidied (whitespace and surrounding quotes trimmed,
|
||||
/// trailing separators dropped except on a drive root); null when the value is
|
||||
/// empty, relative or not a valid path.
|
||||
/// </summary>
|
||||
internal static string? Normalize(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return null;
|
||||
string path = value.Trim().Trim('"').Trim();
|
||||
if (path.Length == 0) return null;
|
||||
// .NET accepts some names Windows folders can't have; refuse them here.
|
||||
if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || path.IndexOfAny(BadNameChars) >= 0) return null;
|
||||
if (path.Length > 2 && path.IndexOf(':', 2) >= 0) return null; // a colon only after the drive letter
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(path)) return null;
|
||||
string full = Path.GetFullPath(path);
|
||||
string root = Path.GetPathRoot(full) ?? string.Empty;
|
||||
string trimmed = full.TrimEnd('\\', '/');
|
||||
return trimmed.Length < root.Length ? root : trimmed;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The real environment and registry (read only, advapi32 directly: NativeAOT and trim safe).</summary>
|
||||
internal sealed class SystemInstallSettings : IInstallSettingSource
|
||||
{
|
||||
public static readonly SystemInstallSettings Instance = new();
|
||||
|
||||
private SystemInstallSettings() { }
|
||||
|
||||
public string? EnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name);
|
||||
|
||||
public string? CurrentUser(string valueName) => ReadString(HKEY_CURRENT_USER, valueName, 0);
|
||||
|
||||
public string? LocalMachine(string valueName) => ReadString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
|
||||
|
||||
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
|
||||
private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));
|
||||
private const uint RRF_RT_REG_SZ = 0x00000002;
|
||||
private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004;
|
||||
private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000;
|
||||
private const int ERROR_SUCCESS = 0;
|
||||
private const int MaxValueBytes = 64 * 1024;
|
||||
|
||||
// Every argument is a pointer or an integer, so no marshalling stub is needed.
|
||||
[DllImport("advapi32.dll", ExactSpelling = true)]
|
||||
private static extern int RegGetValueW(IntPtr hkey, IntPtr subKey, IntPtr valueName, uint flags,
|
||||
IntPtr type, IntPtr data, IntPtr dataBytes);
|
||||
|
||||
private static string? ReadString(IntPtr root, string valueName, uint viewFlag)
|
||||
{
|
||||
IntPtr subKey = IntPtr.Zero, name = IntPtr.Zero, size = IntPtr.Zero, data = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
subKey = Marshal.StringToHGlobalUni(RynthInstallPaths.RegistryKey);
|
||||
name = Marshal.StringToHGlobalUni(valueName);
|
||||
size = Marshal.AllocHGlobal(sizeof(uint));
|
||||
uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlag;
|
||||
|
||||
Marshal.WriteInt32(size, 0);
|
||||
if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, IntPtr.Zero, size) != ERROR_SUCCESS)
|
||||
return null;
|
||||
int bytes = Marshal.ReadInt32(size);
|
||||
if (bytes < 2 || bytes > MaxValueBytes) return null;
|
||||
|
||||
data = Marshal.AllocHGlobal(bytes + 2);
|
||||
Marshal.WriteInt32(size, bytes);
|
||||
if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, data, size) != ERROR_SUCCESS)
|
||||
return null;
|
||||
int written = Math.Min(Marshal.ReadInt32(size), bytes);
|
||||
Marshal.WriteInt16(data, written - (written % 2), 0); // terminate even if the value wasn't
|
||||
return Marshal.PtrToStringUni(data);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null; // no advapi32, access denied, ... -> the next source / the default
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (data != IntPtr.Zero) Marshal.FreeHGlobal(data);
|
||||
if (size != IntPtr.Zero) Marshal.FreeHGlobal(size);
|
||||
if (name != IntPtr.Zero) Marshal.FreeHGlobal(name);
|
||||
if (subKey != IntPtr.Zero) Marshal.FreeHGlobal(subKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -80,6 +80,10 @@ internal static class UseAudit
|
|||
_windowStart = long.MinValue;
|
||||
_windowLines = 0;
|
||||
_windowDropped = 0;
|
||||
_worldUseId = 0;
|
||||
_worldUseSentMs = 0;
|
||||
_worldUseSeqAtSend = 0;
|
||||
AfterSend = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -93,7 +97,95 @@ internal static class UseAudit
|
|||
return false;
|
||||
}
|
||||
Write(host, objectId, subsystem, $"0x{objectId:X8} {what} macro={MacroText} {KindText(kind)} - {why}", force: false);
|
||||
return host.UseObject(objectId);
|
||||
int seqBefore = 0;
|
||||
bool track = TrackWorldUses && doorOrCorpse;
|
||||
var after = AfterSend;
|
||||
if (track || after != null)
|
||||
{
|
||||
try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { }
|
||||
}
|
||||
bool sent = host.UseObject(objectId);
|
||||
if (track && sent)
|
||||
MarkWorldUse(objectId, seqBefore);
|
||||
if (sent && after != null)
|
||||
{
|
||||
try { after(host, new SentUse(objectId, 0, subsystem, what, doorOrCorpse, seqBefore, kind)); } catch { }
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
/// <summary>What went out (for <see cref="AfterSend"/>).</summary>
|
||||
internal readonly record struct SentUse(uint ObjectId, uint TargetId, string Subsystem, string What,
|
||||
bool DoorOrCorpse, int UseDoneSeqBefore, UseKind Kind);
|
||||
|
||||
/// <summary>
|
||||
/// Called after every use / use-on this plugin sent (RynthAi records it as the server action it
|
||||
/// waits on, Plugins/Shared/ActionPacer.cs). Null in plugins that don't pace. Cleared by Reset.
|
||||
/// </summary>
|
||||
public static Action<RynthCoreHost, SentUse>? AfterSend;
|
||||
|
||||
// ── A door or corpse use the server hasn't answered yet (2026-10-06) ──────────
|
||||
// The server walks/turns the character to a used door or corpse, and any movement packet
|
||||
// from the client cancels that (ACE: a MoveToState stops the move-to chain, and a combat
|
||||
// mode change cancels the move-to too). MoveAudit holds the plugin's own movement while
|
||||
// one is in flight. Opt-in per plugin (TrackWorldUses); off = nothing changes.
|
||||
|
||||
/// <summary>Opt-in: remember door/corpse uses so MoveAudit can hold movement until the server answers.</summary>
|
||||
public static volatile bool TrackWorldUses;
|
||||
|
||||
/// <summary>Longest a use counts as in flight when the server doesn't answer (a long walk to it).</summary>
|
||||
public const long WorldUseInFlightMaxMs = 1500;
|
||||
|
||||
private static uint _worldUseId;
|
||||
private static long _worldUseSentMs;
|
||||
private static int _worldUseSeqAtSend;
|
||||
|
||||
/// <summary>Records a door/corpse use that went out (internal for the tests).</summary>
|
||||
internal static void MarkWorldUse(uint objectId, int useDoneSeqBefore)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_worldUseId = objectId;
|
||||
_worldUseSentMs = NowMs();
|
||||
_worldUseSeqAtSend = useDoneSeqBefore;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the last door/corpse use is waiting for the server: sent less than
|
||||
/// WorldUseInFlightMaxMs ago and no UseDone has arrived since (when the engine counts them;
|
||||
/// without the count, the time alone). Always false unless TrackWorldUses.
|
||||
/// </summary>
|
||||
public static bool WorldUseInFlight(RynthCoreHost host, out uint objectId)
|
||||
{
|
||||
objectId = 0;
|
||||
if (!TrackWorldUses) return false;
|
||||
long sentMs; int seqAtSend; uint id;
|
||||
lock (Gate)
|
||||
{
|
||||
sentMs = _worldUseSentMs;
|
||||
seqAtSend = _worldUseSeqAtSend;
|
||||
id = _worldUseId;
|
||||
}
|
||||
if (sentMs == 0 || NowMs() - sentMs >= WorldUseInFlightMaxMs) return false;
|
||||
try
|
||||
{
|
||||
if (host.HasUseDoneSeq && host.GetUseDoneSeq() != seqAtSend) return false;
|
||||
}
|
||||
catch { }
|
||||
objectId = id;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Forget the in-flight use (Reset, tests).</summary>
|
||||
internal static void ClearWorldUse()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_worldUseId = 0;
|
||||
_worldUseSentMs = 0;
|
||||
_worldUseSeqAtSend = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>UseObjectOn (item on a target) with a log line and the same guard on the target.</summary>
|
||||
|
|
@ -107,7 +199,18 @@ internal static class UseAudit
|
|||
return false;
|
||||
}
|
||||
Write(host, targetId, subsystem, $"0x{sourceId:X8} {src} on 0x{targetId:X8} {tgt} macro={MacroText} {KindText(kind)} - {why}", force: false);
|
||||
return host.UseObjectOn(sourceId, targetId);
|
||||
var after = AfterSend;
|
||||
int seqBefore = 0;
|
||||
if (after != null)
|
||||
{
|
||||
try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { }
|
||||
}
|
||||
bool sent = host.UseObjectOn(sourceId, targetId);
|
||||
if (sent && after != null)
|
||||
{
|
||||
try { after(host, new SentUse(sourceId, targetId, subsystem, $"{src} on {tgt}", doorOrCorpse, seqBefore, kind)); } catch { }
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
private static string MacroText => MacroRunning switch { true => "on", false => "off", null => "n/a" };
|
||||
|
|
|
|||
|
|
@ -87,27 +87,28 @@ public enum AcIntProperty
|
|||
|
||||
/// <summary>
|
||||
/// Loot-relevant float item properties. Values match Chorizite STypeFloat sequential enum
|
||||
/// (UNDEF=0, HEARTBEAT_INTERVAL=1, …). Cast to int when calling item.Values(key, 0.0).
|
||||
/// (UNDEF=0, HEARTBEAT_INTERVAL=1, …) and ACE's PropertyFloat. Cast to int when calling item.Values(key, 0.0).
|
||||
/// AttackBonus, DamageMod, ManaConvMod and SlayerDamageBonus were one low until 2026-10-05.
|
||||
/// </summary>
|
||||
public enum AcFloatProperty
|
||||
{
|
||||
AcidProtMod = 18, // ARMOR_MOD_VS_ACID
|
||||
AttackBonus = 61, // WEAPON_OFFENSE — attack bonus %
|
||||
AttackBonus = 62, // WEAPON_OFFENSE — attack bonus %
|
||||
BluntProtMod = 15, // ARMOR_MOD_VS_BLUDGEON
|
||||
ColdProtMod = 16, // ARMOR_MOD_VS_COLD
|
||||
DamageMod = 62, // DAMAGE_MOD — damage bonus %
|
||||
DamageMod = 63, // DAMAGE_MOD — damage bonus %
|
||||
DamageVariance = 22, // DAMAGE_VARIANCE
|
||||
DefenseBonus = 29, // WEAPON_DEFENSE — melee defense bonus %
|
||||
ElectricProtMod = 19, // ARMOR_MOD_VS_ELECTRIC
|
||||
ElementalDamageMod = 152, // ELEMENTAL_DAMAGE_MOD
|
||||
FireProtMod = 17, // ARMOR_MOD_VS_FIRE
|
||||
MagicDefBonus = 150, // WEAPON_MAGIC_DEFENSE
|
||||
ManaConvMod = 143, // MANA_CONVERSION_MOD
|
||||
ManaConvMod = 144, // MANA_CONVERSION_MOD
|
||||
MissileDefBonus = 149, // WEAPON_MISSILE_DEFENSE
|
||||
NetherProtMod = 165, // ARMOR_MOD_VS_NETHER
|
||||
PierceProtMod = 14, // ARMOR_MOD_VS_PIERCE
|
||||
SlashProtMod = 13, // ARMOR_MOD_VS_SLASH
|
||||
SlayerDamageBonus = 137, // SLAYER_DAMAGE_BONUS
|
||||
SlayerDamageBonus = 138, // SLAYER_DAMAGE_BONUS
|
||||
}
|
||||
|
||||
/// <summary>AC material types. Integer values match the live acclient.exe property table.</summary>
|
||||
|
|
|
|||
|
|
@ -133,6 +133,11 @@ public sealed class LootEditItemRequest
|
|||
public string RuleName { get; set; } = string.Empty;
|
||||
/// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary>
|
||||
public bool ToOpenProfile { get; set; }
|
||||
/// <summary>
|
||||
/// Also require the item's T11 attributes (LootItemRuleOptions.IncludeT11). Added
|
||||
/// 2026-10-07; an older engine never sends it, so it reads false.
|
||||
/// </summary>
|
||||
public bool IncludeT11 { get; set; }
|
||||
/// <summary>Echoed in the draft so the popup knows the answer is to its latest ask.</summary>
|
||||
public int Seq { get; set; }
|
||||
}
|
||||
|
|
@ -156,6 +161,10 @@ public sealed class LootEditItemDraft
|
|||
public string Format { get; set; } = string.Empty;
|
||||
/// <summary>What was built (the defaults filled in).</summary>
|
||||
public int Match { get; set; }
|
||||
/// <summary>The rule was asked to include the item's T11 attributes (added 2026-10-07).</summary>
|
||||
public bool IncludeT11 { get; set; }
|
||||
/// <summary>The item is T11 gear, so "Include T11 attributes" has something to add (added 2026-10-07).</summary>
|
||||
public bool IsT11 { get; set; }
|
||||
public int Action { get; set; }
|
||||
public int KeepCount { get; set; }
|
||||
public string RuleName { get; set; } = string.Empty;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RynthCore.Loot.T11;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.Loot.Editing;
|
||||
|
|
@ -26,6 +27,11 @@ public sealed class LootItemFacts
|
|||
public Dictionary<int, double> Doubles { get; set; } = new();
|
||||
/// <summary>The item's spell names (empty when none or not identified).</summary>
|
||||
public List<string> Spells { get; set; } = new();
|
||||
/// <summary>
|
||||
/// The item's T11 reading (ACECustom tier 11+ text), or null when it wasn't asked for.
|
||||
/// <see cref="T11ItemInfo.None"/> for an item that isn't T11 gear.
|
||||
/// </summary>
|
||||
public T11ItemInfo? T11 { get; set; }
|
||||
|
||||
public bool Stackable => MaxStackSize > 1 || StackSize > 1;
|
||||
|
||||
|
|
@ -53,6 +59,11 @@ public sealed class LootItemRuleOptions
|
|||
public int? KeepCount { get; set; }
|
||||
/// <summary>Null or blank: "Keep Copper Pea" and the like.</summary>
|
||||
public string? RuleName { get; set; }
|
||||
/// <summary>
|
||||
/// Also require the item's T11 attributes (tier, grade, damage %, each modifier, slot
|
||||
/// special, Cast on Strike), each at least as good as this item's. Works with any match.
|
||||
/// </summary>
|
||||
public bool IncludeT11 { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A built rule, ready to preview and insert.</summary>
|
||||
|
|
@ -155,6 +166,7 @@ public static class LootItemRules
|
|||
};
|
||||
bool hasClass = f.ObjectClass != (int)AcObjectClass.Unknown;
|
||||
LootItemMatch match = o.Match;
|
||||
bool likeBare = false;
|
||||
if (match == LootItemMatch.NameAndClass && !hasClass)
|
||||
{
|
||||
match = LootItemMatch.Name;
|
||||
|
|
@ -177,13 +189,15 @@ public static class LootItemRules
|
|||
return null;
|
||||
}
|
||||
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
|
||||
int extra = AddLikeConditions(rule, f, notes);
|
||||
if (extra == 0)
|
||||
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
|
||||
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
|
||||
likeBare = AddLikeConditions(rule, f, notes) == 0;
|
||||
break;
|
||||
}
|
||||
|
||||
int t11Added = o.IncludeT11 ? AddT11Conditions(rule, f, notes) : 0;
|
||||
if (likeBare && t11Added == 0)
|
||||
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
|
||||
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
|
||||
|
||||
string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match);
|
||||
string ruleName = OneLine(o.RuleName).Trim();
|
||||
rule.Name = ruleName.Length > 0 ? ruleName : defaultName;
|
||||
|
|
@ -248,6 +262,59 @@ public static class LootItemRules
|
|||
return rule.Conditions.Count - n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The T11 conditions, on RynthAi's virtual T11 keys: Is T11, then tier, grade, damage %,
|
||||
/// every catalogued modifier, slot special and Cast on Strike count, each at least this
|
||||
/// item's. Left out on purpose: Can Wield (the character, not the item), Zone Locked
|
||||
/// (where it was appraised), the wield gates (they follow from the tier) and the modifier
|
||||
/// count / rating total / roll % (they follow from the per-modifier values).
|
||||
/// How many it added.
|
||||
/// </summary>
|
||||
private static int AddT11Conditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
|
||||
{
|
||||
T11ItemInfo? t = f.T11;
|
||||
if (t == null || !t.IsT11)
|
||||
{
|
||||
notes.Add("Not a T11 item, so there are no T11 attributes to add.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int n = rule.Conditions.Count;
|
||||
void Equal(int key, int v) => rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key)));
|
||||
void AtLeast(int key, int v) { if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
|
||||
|
||||
Equal(T11Keys.IsT11, 1);
|
||||
if (!t.HasText)
|
||||
{
|
||||
notes.Add("The item hasn't been identified, so only \"Is T11\" could be added. Assess it and preview again for its tier, grade and modifiers.");
|
||||
return rule.Conditions.Count - n;
|
||||
}
|
||||
|
||||
AtLeast(T11Keys.EstimatedTier, t.EstimatedTier);
|
||||
AtLeast(T11Keys.WeaponGrade, t.GradeRank);
|
||||
AtLeast(T11Keys.DamagePercent, t.DamagePercent);
|
||||
|
||||
bool valuelessSpecial = false;
|
||||
var unknown = new List<string>();
|
||||
foreach (T11Modifier m in t.Modifiers)
|
||||
{
|
||||
if (T11Catalog.ModifierByKey(m.Key) == null)
|
||||
{
|
||||
unknown.Add(m.Name);
|
||||
continue;
|
||||
}
|
||||
// A modifier's key reads 0 when it is absent, so a value-less one can't be required by value.
|
||||
if (m.Value > 0) AtLeast(T11Keys.ForModifier(m.Key), m.Value);
|
||||
else if (m.IsSlotSpecial) valuelessSpecial = true;
|
||||
}
|
||||
if (valuelessSpecial) Equal(T11Keys.HasSlotSpecial, 1);
|
||||
AtLeast(T11Keys.CastOnStrikeCount, t.Procs.Count);
|
||||
|
||||
if (unknown.Count > 0)
|
||||
notes.Add("Left out (RynthAi has no loot key for these modifiers yet): " + string.Join(", ", unknown) + ".");
|
||||
return rule.Conditions.Count - n;
|
||||
}
|
||||
|
||||
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
|
||||
|
||||
private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture);
|
||||
|
|
|
|||
|
|
@ -38,27 +38,55 @@ public static class LootRuleText
|
|||
|
||||
// ── Key tables (the common ones; unknown ids show as "key N") ──────────
|
||||
|
||||
public static readonly (int Id, string Name)[] LongKeys =
|
||||
{
|
||||
(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
|
||||
};
|
||||
/// <summary>Retail / Decal long keys, then RynthAi's virtual T11 keys (T11Keys; RynthAi-only).</summary>
|
||||
public static readonly (int Id, string Name)[] LongKeys = BuildLongKeys();
|
||||
|
||||
private static (int Id, string Name)[] BuildLongKeys()
|
||||
{
|
||||
var keys = new List<(int, string)>
|
||||
{
|
||||
(5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage (max)"), (45, "DamageType"),
|
||||
(48, "WeaponSkill"), (54, "WeaponEncumbrance"), // 54 was labelled MaxDamage until 2026-10-07; max damage is 44
|
||||
(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
|
||||
// Decal's other synthetic keys (Decal.Adapter LongValueKey), as VTank's editor names them;
|
||||
// RynthAi reads each as the game property it is (WorldObjectCache.GetDecalLongKey).
|
||||
(0x0D000001, "Icon"), (0x0D000004, "ItemSlots"), (0x0D000005, "PackSlots"),
|
||||
(0x0D000006, "StackCount"), (0x0D000007, "StackMax"), (0x0D000008, "AssociatedSpell"),
|
||||
(0x0D00000B, "WieldingSlot"), (0x0D00000D, "Coverage"), (0x0D00000E, "EquipableSlots"),
|
||||
(0x0D00000F, "EquipType"), (0x0D000010, "IconOutline"), (0x0D000011, "MissileType"),
|
||||
(0x0D000012, "UsageMask"), (0x0D000014, "HookMask"), (0x0D000015, "HookType"),
|
||||
(0x0D00001A, "Category"), (0x0D00001F, "WeapSpeed"), (0x0D000020, "EquipSkill"),
|
||||
(0x0D000021, "DamageType (Decal)"), (0x0D000022, "MaxDamage"),
|
||||
(0x0D000029, "IconOverlay"), (0x0D00002A, "IconUnderlay"),
|
||||
};
|
||||
keys.AddRange(T11.T11Keys.Names());
|
||||
return keys.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// STypeFloat ids (ACE's PropertyFloat), then the 0x0A0000xx keys VTank's own editor writes
|
||||
/// for the appraisal's weapon profile (uTank2 LootPlugins.DoubleValueKey). 5, 29, 62, 63 and
|
||||
/// 167 were labelled ApproachDistance, WeaponLength, WeaponDefense, WeaponOffense and ManaRate
|
||||
/// until 2026-10-05.
|
||||
/// </summary>
|
||||
public static readonly (int Id, string Name)[] DoubleKeys =
|
||||
{
|
||||
(5, "ApproachDistance"), (22, "DamageVariance"), (29, "WeaponLength"), (62, "WeaponDefense"),
|
||||
(63, "WeaponOffense"), (152, "ElementalDamageVsMonsters"), (167, "ManaRate"),
|
||||
(5, "ManaRate"), (22, "DamageVariance"), (29, "WeaponDefense"), (62, "WeaponOffense"),
|
||||
(63, "DamageMod"), (144, "ManaConversionMod"), (149, "WeaponMissileDefense"),
|
||||
(150, "WeaponMagicDefense"), (152, "ElementalDamageVsMonsters"), (167, "CooldownDuration"),
|
||||
(0x0A000009, "SalvageWorkmanship"), (0x0A00000B, "Variance"),
|
||||
(0x0A00000C, "AttackBonus"), (0x0A00000E, "DamageBonus"),
|
||||
};
|
||||
|
||||
/// <summary>String keys. Use (14) and LongDesc (16) hold the T11 "Modifiers:" / "Property Details:" text.</summary>
|
||||
public static readonly (int Id, string Name)[] StringKeys =
|
||||
{
|
||||
(1, "Name"), (5, "Inscription"), (7, "Title"),
|
||||
(1, "Name"), (5, "Inscription"), (7, "Title"), (14, "Use"), (16, "LongDesc"),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -85,12 +113,15 @@ public static class LootRuleText
|
|||
|
||||
// ── Value tables (what a long key's number means) ──────────────────────
|
||||
|
||||
/// <summary>WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement enum).</summary>
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>MaterialType (131): ACE's MaterialType enum, in id order (grouped cloth, gems, hides, metals, stone, wood).</summary>
|
||||
|
|
@ -129,19 +160,20 @@ public static class LootRuleText
|
|||
/// </summary>
|
||||
public static (int Id, string Name)[]? ValueTableFor(int longKey) => longKey switch
|
||||
{
|
||||
45 => DamageTypes,
|
||||
48 => Skills,
|
||||
45 or 0x0D000021 => DamageTypes,
|
||||
48 or 0x0D000020 => Skills,
|
||||
131 => Materials,
|
||||
158 => WieldRequirements,
|
||||
159 => Skills,
|
||||
T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>True when the long key's value is a set of flags (a named value is one flag or a common pair).</summary>
|
||||
public static bool ValueTableIsFlags(int longKey) => longKey == 45;
|
||||
public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021;
|
||||
|
||||
/// <summary>The long keys that have a value table, for the vocabulary.</summary>
|
||||
public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159 };
|
||||
public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade };
|
||||
|
||||
/// <summary>
|
||||
/// True for the conditions whose value is picked by name when the key has a
|
||||
|
|
|
|||
197
Shared/RynthCore.LootSdk/T11/T11Catalog.cs
Normal file
197
Shared/RynthCore.LootSdk/T11/T11Catalog.cs
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Loot.T11;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public enum T11Counter
|
||||
{
|
||||
/// <summary>LumAugItemCount (PropertyInt64 9008). The server checks the raw count, without Triune Weave.</summary>
|
||||
ItemAugmentations = 9008,
|
||||
/// <summary>TriuneWeaveCount (PropertyInt64 50000), the T16+ armor gate.</summary>
|
||||
TriuneWeave = 50000,
|
||||
/// <summary>BattlemagesWrathCharmCount (PropertyInt64 50001).</summary>
|
||||
BattlemagesWrath = 50001,
|
||||
/// <summary>NetherVeilCharmCount (PropertyInt64 50002).</summary>
|
||||
NetherVeil = 50002,
|
||||
/// <summary>CrashingSteelCharmCount (PropertyInt64 50003).</summary>
|
||||
CrashingSteel = 50003,
|
||||
/// <summary>TrueShotCharmCount (PropertyInt64 50004).</summary>
|
||||
TrueShot = 50004,
|
||||
}
|
||||
|
||||
/// <summary>One Zone Control modifier the server can stamp on T11 gear.</summary>
|
||||
/// <param name="Key">The server's catalog key (ZoneModifiers.Catalog).</param>
|
||||
/// <param name="Name">The name printed at the start of the appraisal line.</param>
|
||||
/// <param name="RatingKey">The retail Gear* rating property the modifier sets, or 0.</param>
|
||||
/// <param name="SlotSpecial">True for the one-per-slot specials, whose line has no roll band.</param>
|
||||
public sealed record T11ModifierDef(int Key, string Name, int RatingKey, bool SlotSpecial);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class T11Catalog
|
||||
{
|
||||
/// <summary>The name prefix the server gives every tier 11+ drop (ApplyT11NamePrefix).</summary>
|
||||
public const string NamePrefix = "T11 - ";
|
||||
|
||||
/// <summary>Retail rating keys counted by the TotalRatings condition (VTank's set).</summary>
|
||||
public static readonly int[] TotalRatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 };
|
||||
|
||||
/// <summary>
|
||||
/// Weapon sub-grades best to worst with their rank (S = 16 ... F- = 1, 0 = no grade).
|
||||
/// Order and labels follow WeaponScalingManager.SubGradeBands.
|
||||
/// </summary>
|
||||
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-"),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The catalog entry whose name starts <paramref name="text"/> as a whole word
|
||||
/// ("Max Health Pct +2%" is Max Health Pct, not Max Health), or null.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The catalog entry for a server key, or null.</summary>
|
||||
public static T11ModifierDef? ModifierByKey(int key)
|
||||
{
|
||||
foreach (var def in Modifiers)
|
||||
if (def.Key == key) return def;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Rank of a sub-grade label ("B+" = 12), or 0 when it isn't one.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The words a "Wield requires:" line uses for each counter.</summary>
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>The counter named by a "Wield requires:" line, or null.</summary>
|
||||
public static T11Counter? CounterByName(string name)
|
||||
{
|
||||
foreach (var (counter, n) in CounterNames)
|
||||
if (string.Equals(n, name.Trim(), StringComparison.OrdinalIgnoreCase)) return counter;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Display name of a counter.</summary>
|
||||
public static string CounterName(T11Counter counter)
|
||||
{
|
||||
foreach (var (c, n) in CounterNames)
|
||||
if (c == counter) return n;
|
||||
return counter.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Highest loot tier on the server's default weapon-scaling ladder (T11-T25).</summary>
|
||||
public const int MaxTier = 25;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const int TriunePerTier = 500;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The loot tier implied by both T11 wield gates. The item-aug gate stops rising at T15,
|
||||
/// so from T16 the Triune Weave gate (<see cref="TriunePerTier"/> 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 <see cref="MaxTier"/>. Without a
|
||||
/// Triune gate this is <see cref="EstimateTier(int, bool)"/>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Modifier keys with a rating, for callers that map Gear* keys back to modifiers.</summary>
|
||||
public static IEnumerable<T11ModifierDef> RatingModifiers()
|
||||
{
|
||||
foreach (var def in Modifiers)
|
||||
if (def.RatingKey != 0) yield return def;
|
||||
}
|
||||
}
|
||||
348
Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs
Normal file
348
Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Loot.T11;
|
||||
|
||||
/// <summary>One "Wield requires: N <counter>" gate.</summary>
|
||||
public readonly record struct T11WieldGate(T11Counter Counter, int Amount);
|
||||
|
||||
/// <summary>One line of the appraisal's "Modifiers:" section.</summary>
|
||||
public sealed class T11Modifier
|
||||
{
|
||||
/// <summary>Catalog key (T11Catalog.Modifiers), or 0 for a name the catalog doesn't know.</summary>
|
||||
public int Key { get; init; }
|
||||
/// <summary>The modifier name as printed.</summary>
|
||||
public string Name { get; init; } = string.Empty;
|
||||
/// <summary>The rolled value (the first number after the name; 0 for value-less specials).</summary>
|
||||
public int Value { get; init; }
|
||||
/// <summary>Low end of the "[min-max]" roll band, or null when the line has none.</summary>
|
||||
public int? Min { get; init; }
|
||||
/// <summary>High end of the "[min-max]" roll band, or null when the line has none.</summary>
|
||||
public int? Max { get; init; }
|
||||
/// <summary>Where the value landed in its band, 0-100, or -1 without a usable band.</summary>
|
||||
public int RollPercent { get; init; } = -1;
|
||||
/// <summary>The retail Gear* rating key the modifier sets, or 0.</summary>
|
||||
public int RatingKey { get; init; }
|
||||
/// <summary>True for a one-per-slot special (Fortify Vitals, Battle Mending, ...).</summary>
|
||||
public bool IsSlotSpecial { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class T11ItemInfo
|
||||
{
|
||||
/// <summary>A non-T11 item: every field at its default.</summary>
|
||||
public static readonly T11ItemInfo None = new();
|
||||
|
||||
/// <summary>True when the item is T11 gear (name prefix, or T11-only text in its description).</summary>
|
||||
public bool IsT11 { get; private set; }
|
||||
/// <summary>True when the name starts with "T11 - ".</summary>
|
||||
public bool HasNamePrefix { get; private set; }
|
||||
/// <summary>Weapon sub-grade label ("B+"), or null.</summary>
|
||||
public string? Grade { get; private set; }
|
||||
/// <summary>Sub-grade rank, S = 16 ... F- = 1, 0 = no grade.</summary>
|
||||
public int GradeRank { get; private set; }
|
||||
/// <summary>"N% of max damage" from the grade line, or -1.</summary>
|
||||
public int DamagePercent { get; private set; } = -1;
|
||||
/// <summary>Every wield gate, at most one per counter.</summary>
|
||||
public IReadOnlyList<T11WieldGate> WieldGates => _gates;
|
||||
/// <summary>The Zone Control modifier lines, in appraisal order.</summary>
|
||||
public IReadOnlyList<T11Modifier> Modifiers => _modifiers;
|
||||
/// <summary>"Cast on Strike" lines: spell name and proc chance percent.</summary>
|
||||
public IReadOnlyList<(string Name, double ChancePercent)> Procs => _procs;
|
||||
/// <summary>True when the appraisal said "Zone Locked (Power Reduced)" (depends on where the examiner stood).</summary>
|
||||
public bool ZoneLocked { get; private set; }
|
||||
/// <summary>True when the item had appraisal text (false for a T11 name seen before its ID).</summary>
|
||||
public bool HasText { get; private set; }
|
||||
|
||||
private readonly List<T11WieldGate> _gates = new();
|
||||
private readonly List<T11Modifier> _modifiers = new();
|
||||
private readonly List<(string, double)> _procs = new();
|
||||
|
||||
/// <summary>The item-augmentation gate, or 0 when there is none.</summary>
|
||||
public int WieldItemAugs => GateAmount(T11Counter.ItemAugmentations);
|
||||
|
||||
/// <summary>The amount required of <paramref name="counter"/>, or 0 when it isn't gated.</summary>
|
||||
public int GateAmount(T11Counter counter)
|
||||
{
|
||||
foreach (var g in _gates)
|
||||
if (g.Counter == counter) return g.Amount;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int EstimatedTier => T11Catalog.EstimateTier(WieldItemAugs, GateAmount(T11Counter.TriuneWeave), IsT11);
|
||||
|
||||
/// <summary>Sum of modifier values that land on the TotalRatings keys.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sum of modifier values that set <paramref name="ratingKey"/>, or 0.</summary>
|
||||
public int RatingFromModifiers(int ratingKey)
|
||||
{
|
||||
int total = 0;
|
||||
foreach (var m in _modifiers)
|
||||
if (m.RatingKey == ratingKey) total += m.Value;
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>The value of the modifier with catalog key <paramref name="key"/>, or 0 when absent.</summary>
|
||||
public int ModifierValue(int key)
|
||||
{
|
||||
foreach (var m in _modifiers)
|
||||
if (m.Key == key) return m.Value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Average roll position (0-100) of the banded modifiers, or 0 without any.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Best roll position (0-100) of the banded modifiers, or 0 without any.</summary>
|
||||
public int BestRollPercent
|
||||
{
|
||||
get
|
||||
{
|
||||
int best = 0;
|
||||
foreach (var m in _modifiers)
|
||||
if (m.RollPercent > best) best = m.RollPercent;
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when any modifier is a slot special.</summary>
|
||||
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*(?<g>S|[A-DF][+-]?)(?=\s|\(|$)(?:\s*\((?<pct>\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*(?<n>\d[\d,.\s']*?)\s+(?<what>[A-Za-z' ]+?)\s*$", Opt);
|
||||
|
||||
// "- Cast on Strike: Force Arc (13% proc chance)"
|
||||
private static readonly Regex ProcLine = new(
|
||||
@"^-\s*Cast on Strike:\s*(?<name>.+?)\s*\((?<pct>\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(@"\[(?<min>\d+)\s*-\s*(?<max>\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(@"^(?<name>.+?)\s+(?<val>[+-]?\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(@"^(?<name>Modifier (?<key>\d+))(?=\s|$)", RegexOptions.CultureInvariant);
|
||||
|
||||
private const string ModifiersHeader = "Modifiers:";
|
||||
private const string ZoneLockedText = "Zone Locked (Power Reduced)";
|
||||
|
||||
/// <summary>
|
||||
/// Parses an item. <paramref name="name"/>, <paramref name="longDesc"/> and
|
||||
/// <paramref name="use"/> may be null or empty (an item not yet appraised has no text;
|
||||
/// the name prefix alone still marks it T11). Never throws.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads "- ..." lines after a "Modifiers:" header; returns the index of the first line not consumed.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue