From 4c2cce979c7d3a12492d1696f39b0818c42eec63 Mon Sep 17 00:00:00 2001 From: Sam Sung <51686767+samwhosung@users.noreply.github.com> Date: Fri, 23 Oct 2026 06:13:29 +0700 Subject: [PATCH] Macros and the action bar's range and events follow 1.12.1 (#2273) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Macros and the action bar's queries follow 1.12.1. - Create, edit and delete fire `UPDATE_MACROS` and the edited slots' `ACTIONBAR_SLOT_CHANGED` in the reference's order, inside the call, and derive the bound spell there (`0x4f1322`, `0x4f1329`, `0x4f1313`). - A macro's spell is re-derived only at load, arrival, create and edit (`0x4efe00`'s four callers). - A rank supersede rewrites bar macros, and clears slots still on the old rank, items included (`0x4e5e60`, `0x5e6392`); an unlearn clears every slot on the spell (`0x4e5e20`). - The macro file reads and writes as `0x4f0600` and its writer do: final newlines, `END`, quote-aware names, signed ids, 255-byte lines. - Item slots answer range by their on-use spell; `ActionHasRange` tests "not below" 2^-22 (`0x4e5a50`, `0x8029d4`). A line cut that would split a UTF-8 character is a recorded Deviation. Tests pin each address. Built on macOS. Fixes #2115 Fixes #2111 Fixes #2107 Fixes #2065 Fixes #2062 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5.5 --- crates/benilla-app/src/game_plugins.rs | 2 - crates/benilla-app/src/spell/net.rs | 18 + crates/benilla-app/src/ui_action/feed.rs | 18 +- .../benilla-app/src/ui_action/feed_tests.rs | 117 ++++- crates/benilla-app/src/ui_action/mod.rs | 24 +- .../benilla-app/src/ui_action/range_tests.rs | 203 +++++++++ crates/benilla-app/src/ui_action/ranks.rs | 2 + crates/benilla-app/src/ui_action/state.rs | 74 ++- crates/benilla-app/src/ui_action/unlearn.rs | 205 +++++++++ crates/benilla-app/src/ui_macro/mod.rs | 141 +++--- crates/benilla-app/src/ui_macro/run.rs | 425 +----------------- crates/benilla-app/src/ui_macro/store.rs | 353 ++++++++++++--- crates/benilla-app/src/ui_macro/tests.rs | 306 ++++++++++++- crates/benilla-app/src/ui_spellbook.rs | 5 + crates/benilla-ui/src/script/action.rs | 20 +- crates/benilla-ui/src/script/macros.rs | 191 ++++++-- crates/benilla-ui/src/script/macros/bind.rs | 397 ++++++++++++++++ .../benilla-ui/src/script/macros/lua_tests.rs | 85 ++++ crates/benilla-ui/src/script/mod.rs | 4 +- crates/benilla-ui/src/script/model.rs | 8 +- docs/DEVIATIONS.md | 17 +- 21 files changed, 1994 insertions(+), 621 deletions(-) create mode 100644 crates/benilla-app/src/ui_action/range_tests.rs create mode 100644 crates/benilla-app/src/ui_action/unlearn.rs create mode 100644 crates/benilla-ui/src/script/macros/bind.rs diff --git a/crates/benilla-app/src/game_plugins.rs b/crates/benilla-app/src/game_plugins.rs index 905b1f88b..b3d8503d3 100644 --- a/crates/benilla-app/src/game_plugins.rs +++ b/crates/benilla-app/src/game_plugins.rs @@ -1850,8 +1850,6 @@ pub(crate) mod schedule_tests { "a roll exists only after a group member loots under group loot; leftovers are cleared at socket teardown (another player's act: coincidence-only residual)"), ("ui_macro/mod.rs", "load_macros", Because::MemoLatched, "`MacroFiles.identity` is a `VmMemo`, so a new session re-reads the files and re-fires UPDATE_MACROS; also `InWorldGated`"), - ("ui_macro/mod.rs", "save_dirty_macros", Because::FilledByVm, - "`take_macros_dirty` is raised only by the macro window's Lua"), ("ui_mail/mod.rs", "feed_mail", Because::SelfHealing, "the window queues are mailbox-click replies; the one server push (`SMSG_RECEIVED_MAIL`) is re-asked by `send_query_next_mail_time_on_enter`, whose reply sets `notify` unconditionally"), ("ui_merchant/mod.rs", "feed_merchant", Because::PlayerRoundTrip, diff --git a/crates/benilla-app/src/spell/net.rs b/crates/benilla-app/src/spell/net.rs index e17a630fa..d63449227 100644 --- a/crates/benilla-app/src/spell/net.rs +++ b/crates/benilla-app/src/spell/net.rs @@ -748,6 +748,11 @@ fn removed_spell( if actions.spells.remove(&spell_id) { actions.dirty = true; } + // `UnlearnSpell 0x5e9fe0` does nothing for a spell with no record (`0x5ea02a`); otherwise it + // clears the bar slots that stand for the spell (`0x5ea253`), which the bar's queue makes. + if spells.is_some_and(|s| s.catalog.get(spell_id).is_some()) { + actions.unlearned.push(spell_id); + } // `0x5ea24c`: every unlearn runs `0x4b2c50`. unlist_opener(spell_id, actions); announce_unlearn(spell_id, spells, errors); @@ -780,6 +785,7 @@ fn superceded_spell( debug!("net: superceded spell {old_spell_id} -> {new_spell_id}"); actions.spells.remove(&old_spell_id); actions.spells.insert(new_spell_id); + actions.superseded.push((old_spell_id, new_spell_id)); actions.dirty = true; // `0x4b2f50` unlists the old rank and registers the new one at the tail; the player's own // unlearn of the old rank (`0x5e6392` → `0x5ea24c`) then runs the removal once more, and its @@ -793,6 +799,12 @@ fn superceded_spell( announce_learn(new_spell_id, spells, errors); // The same flag flashes the tab of the new rank. tab_flash.0.push(new_spell_id); + // That unlearn (`UnlearnSpell(old, 1)`, `0x5e6392` into `0x5e9fe0`) then clears every bar slot + // still standing for the old rank (`0x5ea253`), an item's on-use spell included; a spell with + // no record unlearns nothing (`0x5ea02a`). + if spells.is_some_and(|s| s.catalog.get(old_spell_id).is_some()) { + actions.unlearned.push(old_spell_id); + } } /// The server's verdict on our cast (`SMSG_CAST_RESULT`, `HandleCastResult 0x6e7330`). @@ -1846,6 +1858,12 @@ mod tests { let mut flash = LearnedInTab::default(); superceded_spell(78, 284, &mut actions, Some(&spells), &errors, &mut flash); + assert_eq!( + actions.unlearned, + [78], + "the handler's `UnlearnSpell(old, 1)` clears what still stands for the old rank \ + (`0x5e6392` into `0x5e9fe0`, `0x5ea253`)" + ); assert_eq!(errors.len(), 1, "one line for a rank-up, not two"); assert_eq!( flash.0, diff --git a/crates/benilla-app/src/ui_action/feed.rs b/crates/benilla-app/src/ui_action/feed.rs index 449b43b4e..9116d997a 100644 --- a/crates/benilla-app/src/ui_action/feed.rs +++ b/crates/benilla-app/src/ui_action/feed.rs @@ -280,8 +280,9 @@ pub(super) fn feed_actions( // `ACTIONBAR_SLOT_CHANGED` only when what it pushes differs visibly from what the VM // shows, so the store catching up with a verb is no change. The item's ON_USE spell is // pushed but never signalled: the place leaves it to this re-feed, and no handler - // paints it. A macro rename changes the name line (`GetActionText`) but not the slot - // value, so a macro edit re-fires every macro slot. + // paints it. A macro slot whose word stands is signalled by `EditMacro` alone, inside + // its call (`0x4f1329` into `0x4e5cc0`), and reads its macro's icon and name live, so + // a load, a create or an edit pushes it silently. let held = script.action_slots(); let shown = |s: Option<&ActionSlot>| { s.map(|s| ActionSlot { @@ -296,14 +297,15 @@ pub(super) fn feed_actions( .collect::>() .into_iter() .filter_map(|a| { - let macro_moved = macros_moved - && fresh - .get(&a) - .is_some_and(|s| macro_slot_id(s.kind, s.action).is_some()); + let word = |s: Option<&ActionSlot>| s.map(|s| (s.kind, s.action)); + let macro_stands = fresh + .get(&a) + .is_some_and(|s| macro_slot_id(s.kind, s.action).is_some()) + && word(fresh.get(&a)) == word(memory.pushed.get(&a)); let moved = fresh.get(&a) != memory.pushed.get(&a); let signal = - macro_moved || (moved && shown(fresh.get(&a)) != shown(held.get(&a))); - (moved || macro_moved).then_some((a, signal)) + moved && !macro_stands && shown(fresh.get(&a)) != shown(held.get(&a)); + moved.then_some((a, signal)) }) .collect(); for &(action, _) in &changed { diff --git a/crates/benilla-app/src/ui_action/feed_tests.rs b/crates/benilla-app/src/ui_action/feed_tests.rs index ad06fe24b..011e61cd9 100644 --- a/crates/benilla-app/src/ui_action/feed_tests.rs +++ b/crates/benilla-app/src/ui_action/feed_tests.rs @@ -433,8 +433,8 @@ fn a_macro_slot_shows_the_macros_own_icon_and_follows_an_edit() { "the generation gate re-resolved the slot" ); - // A rename leaves the slot's texture, kind and id unchanged, so a value diff alone would - // fire nothing; the feed must re-fire the slot anyway. + // A rename leaves the slot's texture, kind and id unchanged: the edit signals the slot inside + // its call (`0x4f1329`), and the feed adds nothing. let events = |app: &mut App| { app.world_mut() .non_send_resource::() @@ -458,7 +458,7 @@ fn a_macro_slot_shows_the_macros_own_icon_and_follows_an_edit() { assert_eq!( events(&mut app), 1, - "a rename re-fires ACTIONBAR_SLOT_CHANGED for the slot" + "a rename fires ACTIONBAR_SLOT_CHANGED for the slot once" ); assert_eq!( app.world_mut() @@ -1015,3 +1015,114 @@ fn a_charged_item_slot_shows_the_uses_left() { app.update(); assert_eq!(jerky_count(&mut app), 2, "|-2| charges, one item"); } + +/// Only `EditMacro` signals a macro's slots (`0x4f1329` into `0x4e5cc0`), inside its call: the feed +/// pushes a macro slot's new icon and name silently, so a load (`0x4f0600`, which ends in the order +/// rebuild alone) and a create (`0x4f1010`) signal no slot, and an edit's slots are not signalled +/// a second time. +#[test] +fn the_feed_signals_no_macro_slot_of_its_own() { + use benilla_protocol::messages::ACTION_KIND_MACRO; + use benilla_ui::script::{MacroState, MacroView}; + + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + // Macro 1 on slots 1 and 3, macro 2 on slot 2. + for (slot, id) in [(0u8, 1u32), (1, 2), (2, 1)] { + actions.buttons.insert( + slot, + ActionButton { + slot, + action: id, + kind: ACTION_KIND_MACRO, + }, + ); + } + actions.dirty = true; + app.insert_resource(actions) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)); + let mut script = UiScript::new().unwrap(); + script.set_macro_icons(vec!["Interface\\Icons\\Spell_Fire_FlameBolt".into()]); + let view = |name: &str, icon: &str| MacroView { + name: name.into(), + texture: Some(format!("Interface\\Icons\\{icon}")), + ..Default::default() + }; + script.set_macros(MacroState::from_scopes( + vec![view("a", "Ability_Ambush"), view("b", "Ability_BackStab")], + Vec::new(), + )); + app.insert_non_send_resource(script); + app.add_systems(Update, feed_actions); + app.update(); + app.world_mut() + .non_send_resource::() + .run( + r#" + SLOT_EVENTS = {} + local f = CreateFrame("Frame") + f:RegisterEvent("ACTIONBAR_SLOT_CHANGED") + f:SetScript("OnEvent", function() table.insert(SLOT_EVENTS, arg1) end) + "#, + ) + .unwrap(); + let events = |app: &mut App| { + app.world_mut() + .non_send_resource::() + .eval::>("local t = SLOT_EVENTS SLOT_EVENTS = {} return t") + .unwrap() + }; + + // A load with new icons for both macros. + app.world_mut() + .non_send_resource_mut::() + .set_macros(MacroState::from_scopes( + vec![view("a", "Spell_Holy_Heal"), view("b", "Spell_Holy_Renew")], + Vec::new(), + )); + app.update(); + assert_eq!( + events(&mut app), + Vec::::new(), + "a load signals no slot" + ); + assert_eq!( + app.world() + .non_send_resource::() + .eval::("return GetActionTexture(3)") + .unwrap(), + "Interface\\Icons\\Spell_Holy_Heal", + "but the slot shows the loaded icon" + ); + + app.world_mut() + .non_send_resource::() + .run(r#"CreateMacro("c", 1, "")"#) + .unwrap(); + app.update(); + assert_eq!( + events(&mut app), + Vec::::new(), + "a create signals no slot" + ); + + app.world_mut() + .non_send_resource::() + .run("EditMacro(GetMacroIndexByName('a'), nil, 1)") + .unwrap(); + app.update(); + assert_eq!( + events(&mut app), + [1, 3], + "the edit's two slots, once each, and not macro 2's" + ); +} diff --git a/crates/benilla-app/src/ui_action/mod.rs b/crates/benilla-app/src/ui_action/mod.rs index 2635b5f11..40c712d75 100644 --- a/crates/benilla-app/src/ui_action/mod.rs +++ b/crates/benilla-app/src/ui_action/mod.rs @@ -47,6 +47,7 @@ pub(crate) mod recount; mod state; pub(crate) use state::ActionStates; pub(crate) mod toggle; +mod unlearn; mod weapon_icon; /// Every feed that pushes cooldown triples runs `.before` this set: [`state::fire_action_events`] @@ -87,6 +88,14 @@ pub(crate) struct PlayerActions { /// item tooltip's lock walk `0x5da5e0` scan it from the front, so its order picks between /// 6478 "Opening" and 22810 "Opening - No Text", which open the same locks. pub openers: Vec, + /// `SMSG_SUPERCEDED_SPELL`'s `(old, new)` pairs in arrival order, for the macro arm of + /// `0x4e5e60`: a macro on the bar whose cached spell is `old` gets `new` (`0x4e5ec4`). The + /// macro rebind drains it ([`crate::ui_macro`]). + pub superseded: Vec<(u32, u32)>, + /// The spells unlearned (`0x5e9fe0`), by `SMSG_REMOVED_SPELL` or a supersede's old rank, in + /// arrival order, whose bar slots the unlearn clears (`0x5ea253` into `0x4e5e20`), drained by + /// the bar's clear (`unlearn`). + pub unlearned: Vec, /// Set by every book or bar change, cleared once the feed re-resolves slot identity, which a /// landed item template ([`crate::items::Items::template_epoch`]) also triggers. Between /// resolves an item slot's count moves only by the item watchers' recount (`recount`). @@ -377,6 +386,15 @@ impl Plugin for UiActionPlugin { ranks::normalize_action_ranks .in_set(UnitFeed) .before(feed::feed_actions), + // The unlearns' clears, after the macros' bound spells a macro slot resolves + // through and after the rank pass, which stands in for the supersede's move + // of the spell slots (`0x4e5e60`) that its unlearn (`0x5e6392`) follows; before + // the identity feed that consumes their `dirty`. + unlearn::clear_unlearned_slots + .in_set(UnitFeed) + .after(crate::ui_macro::MacroBindings) + .after(ranks::normalize_action_ranks) + .before(feed::feed_actions), // Our player's arrival recount, after the server's unlocks. recount::recount_item_actions .in_set(UnitFeed) @@ -389,13 +407,15 @@ impl Plugin for UiActionPlugin { .before(crate::ui_aura::AuraEvents), // A seat: the world-enter events' handlers read the slots' state, which the // reference's arrival stores before its enter cascade (`0x5deafc`, `0x5deb60`). - // After the bag feed, a seat too: left to the VM pass, the pair links through - // one more command barrier ([`crate::vm_pass`]). + // After the macros' bound spells, which a macro slot resolves through. After the + // bag feed, a seat too: left to the VM pass, the pair links through one more + // command barrier ([`crate::vm_pass`]). state::feed_action_state .in_set(UnitFeed) .in_set(crate::ui_unit::WorldEnterSeats) .after(crate::player::ControlRestore) .after(crate::ui_items::feed::feed_containers) + .after(crate::ui_macro::MacroBindings) .after(feed::feed_actions), // After the unit snapshots, which its handlers read (the target stored at // `0x4936e2`, a watched field written before its watch runs), and ahead of the diff --git a/crates/benilla-app/src/ui_action/range_tests.rs b/crates/benilla-app/src/ui_action/range_tests.rs new file mode 100644 index 000000000..bf0002334 --- /dev/null +++ b/crates/benilla-app/src/ui_action/range_tests.rs @@ -0,0 +1,203 @@ +//! `ActionHasRange` (`0x4e5810`) and `IsActionInRange` (`0x4e56f0`) through +//! [`super::feed_action_state`] and a real Lua VM: both resolve the slot with `0x4e5a50` and test +//! the spell it stands for. + +use super::*; +use crate::spell::AutoRepeatActive; +use crate::target::Selection; +use benilla_formats::{SpellDisplay, SpellRange}; +use benilla_protocol::messages::{ActionButton, ItemUseSpell}; +use benilla_protocol::ObjectFields; +use benilla_ui::script::UiScript; + +/// The player's guid. +const ME: u64 = 0x10; +/// The selected unit's guid. +const SELECTED: u64 = 0xB2; +/// The spell every slot here stands for, aimed at an enemy (implicit target 6), so the pre-check +/// compares (`0x6e45f1`) and a selection answers 1 (`0x4e579c`). +const BOLT: u32 = 133; +/// Its `SpellRange.dbc` row. +const BOLT_RANGE: u32 = 4; +/// An item whose first trigger-0 block casts [`BOLT`]. +const GRENADE: u32 = 4390; + +/// What one pass of the feed answers for slot 1: `ActionHasRange(1)` and `IsActionInRange(1)`. +fn range_answers( + button: ActionButton, + items: Items, + row: SpellRange, + distance: f32, +) -> (bool, Option) { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + actions.buttons.insert(button.slot, button); + let bolt = SpellDisplay { + range_index: BOLT_RANGE, + effect_implicit_target_a: [6, 0, 0], + ..Default::default() + }; + app.insert_resource(actions) + .insert_resource(crate::ui_macro::MacroBoundSpells::default()) + .insert_resource(Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [(BOLT, bolt)].into_iter().collect(), + ), + forms: Default::default(), + ranges: benilla_formats::SpellRangeCatalog::from_rows( + [(BOLT_RANGE, row)].into_iter().collect(), + ), + cast_times: Default::default(), + durations: Default::default(), + radii: Default::default(), + }) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .add_message::() + .add_message::() + .add_message::() + .init_resource::() + .insert_resource(crate::net::SelfGuid(Some(ME))) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(items) + .insert_resource(NetCommands(tx)); + // A player under its own control, alive, with mana; an attackable creature at `distance`. + app.world_mut().spawn(( + SelfPlayer, + Transform::default(), + ObjectStore(ObjectFields::from_pairs(&[ + (2, 0x19), + (22, 100), + (23, 500), + (46, 0x8), + ])), + )); + let selected = app + .world_mut() + .spawn(( + Transform::from_xyz(distance, 0.0, 0.0), + ObjectStore(ObjectFields::from_pairs(&[(2, 0x9), (22, 100)])), + )) + .id(); + app.world_mut() + .resource_mut::() + .0 + .insert(SELECTED, selected); + app.insert_resource(Selection { + target: Some(selected), + guid: Some(SELECTED), + last: None, + lit: None, + }); + app.insert_non_send_resource(UiScript::new().unwrap()); + app.init_resource::() + .init_resource::() + .add_systems(Update, feed_action_state); + app.update(); + app.world() + .non_send_resource::() + .eval::<(bool, Option)>("return ActionHasRange(1) == 1, IsActionInRange(1)") + .unwrap() +} + +fn spell_slot() -> ActionButton { + ActionButton { + slot: 0, + action: BOLT, + kind: ACTION_KIND_SPELL, + } +} + +fn item_slot() -> ActionButton { + ActionButton { + slot: 0, + action: GRENADE, + kind: ACTION_KIND_ITEM, + } +} + +/// A grenade's template, whose on-use spell is its first trigger-0 block (`0x4e5ae0`). +fn grenade() -> Items { + let mut items = Items::default(); + items.insert_template( + GRENADE, + Some(benilla_protocol::messages::ItemInfo { + use_spell: Some(ItemUseSpell { + spell_id: BOLT, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }), + ..crate::items::test_template("Iron Grenade") + }), + ); + items +} + +fn row(max: f32) -> SpellRange { + SpellRange { + min: 0.0, + max, + flags: 0, + } +} + +/// `ActionHasRange` (`0x4e5810`) tests `|min|` and `|max|` with `fcomp [0x8029d4]` and +/// `test ah,5` (`0x4e5885`, `0x4e5898`): a range not below 0x34800000, 2^-22, is a range, so 2^-22 +/// itself counts and 1.5 * 2^-23, above `f32::EPSILON`, does not. +#[test] +fn action_has_range_tests_against_two_to_the_minus_22() { + let at_bound = f32::from_bits(0x3480_0000); + assert_eq!(at_bound, 2f32.powi(-22)); + assert!( + range_answers(spell_slot(), Items::default(), row(at_bound), 1.0).0, + "equal to the constant is a range" + ); + let below = 1.5 * f32::EPSILON; + assert!(below > f32::EPSILON && below < at_bound); + assert!( + !range_answers(spell_slot(), Items::default(), row(below), 1.0).0, + "between 2^-23 and 2^-22 is no range" + ); +} + +/// An item slot resolves through `GetActionSlotSpell` (`0x4e5a50`) to its template's first +/// trigger-0 spell (`0x4e5ae0`) with book 0, which both queries require (`0x4e584b`, `0x4e5757`): +/// a grenade casting a 0-35 spell has a range and reads in range at 37.5 yards (padded by both +/// reaches) and out at 38.5, as the same spell on a spell slot does. +#[test] +fn an_item_slot_answers_range_by_its_on_use_spell() { + for button in [spell_slot(), item_slot()] { + assert_eq!( + range_answers(button, grenade(), row(35.0), 37.5), + (true, Some(1)), + "in range: {button:?}" + ); + assert_eq!( + range_answers(button, grenade(), row(35.0), 38.5), + (true, Some(0)), + "out of range: {button:?}" + ); + } +} + +/// An item whose template is not cached resolves to spell 0 (`0x4e5ae0` fails the template +/// fetch), whose missing record answers no range and nil (`0x4e5846`, `0x4e5752`). +#[test] +fn an_uncached_item_answers_no_range() { + assert_eq!( + range_answers(item_slot(), Items::default(), row(35.0), 10.0), + (false, None) + ); +} diff --git a/crates/benilla-app/src/ui_action/ranks.rs b/crates/benilla-app/src/ui_action/ranks.rs index 1c8b89127..dcdc2fc3d 100644 --- a/crates/benilla-app/src/ui_action/ranks.rs +++ b/crates/benilla-app/src/ui_action/ranks.rs @@ -94,6 +94,8 @@ mod tests { buttons: buttons.iter().map(|b| (b.slot, *b)).collect(), spells: spells.iter().copied().collect(), openers: Vec::new(), + superseded: Vec::new(), + unlearned: Vec::new(), dirty: true, }) .insert_resource(SkillLines { catalog }) diff --git a/crates/benilla-app/src/ui_action/state.rs b/crates/benilla-app/src/ui_action/state.rs index c1c79c513..f239818a1 100644 --- a/crates/benilla-app/src/ui_action/state.rs +++ b/crates/benilla-app/src/ui_action/state.rs @@ -252,6 +252,44 @@ fn pet_book_state(leg: PetBookLeg) -> ActionState { st } +/// The float `ActionHasRange` compares each range with (`0x8029d4`): 0x34800000, 2^-22. +const HAS_RANGE_BOUND: f32 = f32::from_bits(0x3480_0000); + +/// What the two range queries read beside the spell. +struct RangeLeg<'a, 'w> { + caster: benilla_formats::RangeUnit, + mods: &'a crate::spell::SpellModifiers, + cast_ctx: &'a crate::spell::cast_target::CastContext<'w>, + /// Whether there is an active player, which `IsActionInRange` requires (`0x4e572b`). + player: bool, +} + +/// `ActionHasRange` and `IsActionInRange` for the spell a book-0 slot stands for: +/// - `0x4e5810` asks `GetMinMaxRange` with a null target (`0x4e5852`) and answers whether `|min|` +/// or `|max|` is not below [`HAS_RANGE_BOUND`] (`fcomp`, `test ah,5`, `0x4e5885`, `0x4e5898`), +/// which an unordered compare passes too. The auto-attack target the melee arm falls back to +/// cannot move that: its max is at least the 5.0 floor; +/// - `0x4e56f0` is nil with no player, else the pre-check `0x6e4440` on the selection, whose +/// compare `0x6e47b0` hands `GetMinMaxRange` that target (`0x6e47ca`): its reach pads a ranged +/// row, and its motion with the caster's earns the moving bonus. +fn range_answers( + d: &benilla_formats::SpellDisplay, + spells: Option<&Spells>, + leg: &RangeLeg<'_, '_>, +) -> (bool, Option) { + let row = spells.and_then(|s| s.ranges.get(d.range_index)); + let a_range = |x: f32| x.abs() >= HAS_RANGE_BOUND || x.is_nan(); + let has_range = leg + .mods + .min_max_range(d, row, leg.caster, RangeTargets::default()) + .is_some_and(|(min, max)| a_range(min) || a_range(max)); + let in_range = leg + .player + .then(|| crate::spell::range_check::action_in_range(d, leg.cast_ctx, row, leg.mods)) + .flatten(); + (has_range, in_range) +} + /// The events one pass of [`feed_action_state`] raised, which [`fire_action_events`] signals. #[derive(Resource, Default)] pub(crate) struct ActionEvents { @@ -540,6 +578,12 @@ impl ActionStates<'_, '_> { .and_then(|g| objects.entity(g)) .and_then(|e| units.get(e).ok()); let cast_ctx = targeting.context(); + let range_leg = RangeLeg { + caster, + mods: spell_mods, + cast_ctx: &cast_ctx, + player: me.is_some(), + }; // The pet gate `0x4bcf70`, asked once for every slot bound to a pet spell: the bar those // slots read the history of, and the pet's object when the gate holds. let pet_leg = pet_bar.as_deref().map(|bar| { @@ -633,23 +677,8 @@ impl ActionStates<'_, '_> { } else { st.usable = true; } - let row = spells.as_ref().and_then(|s| s.ranges.get(d.range_index)); - // `ActionHasRange 0x4e5810` asks `GetMinMaxRange` with a null target - // (`0x4e5852`) and tests `|min|` and `|max|` against `FLT_EPSILON`. The - // auto-attack target the melee arm falls back to cannot move that: its max is - // at least the 5.0 floor. - st.has_range = spell_mods - .min_max_range(d, row, caster, RangeTargets::default()) - .is_some_and(|(min, max)| { - min.abs() > f32::EPSILON || max.abs() > f32::EPSILON - }); - // `IsActionInRange 0x4e56f0`: nil with no player (`0x4e572b`), else the - // pre-check `0x6e4440` on the selection, whose compare `0x6e47b0` hands - // `GetMinMaxRange` that target (`0x6e47ca`): its reach pads a ranged row, and - // its motion with the caster's earns the moving bonus. - st.in_range = me.and_then(|_| { - crate::spell::range_check::action_in_range(d, &cast_ctx, row, spell_mods) - }); + let range = range_answers(d, spells.as_deref(), &range_leg); + (st.has_range, st.in_range) = range; let info = cooldowns.info(button.action, 0, Some(d), now); st.cooldown = info.ui_triple(anchor, ui_now); if st.cooldown.is_some() && trace_cd { @@ -727,6 +756,13 @@ impl ActionStates<'_, '_> { } if let Some(u) = use_spell { let d = spells.as_ref().and_then(|s| s.catalog.get(u.spell_id)); + // Both range queries resolve the slot to this spell with book 0 + // (`0x4e5a50` into `0x4e5ae0`) and test it as a spell slot's; a missing + // record answers none (`0x4e5846`, `0x4e5752`). + if let Some(d) = d { + (st.has_range, st.in_range) = + range_answers(d, spells.as_deref(), &range_leg); + } let info = cooldowns.info_item(u.spell_id, button.action, u.category, d, now); st.cooldown = info.ui_triple(anchor, ui_now); @@ -893,3 +929,7 @@ pub(super) fn fire_action_events( #[cfg(test)] #[path = "state_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "range_tests.rs"] +mod range_tests; diff --git a/crates/benilla-app/src/ui_action/unlearn.rs b/crates/benilla-app/src/ui_action/unlearn.rs new file mode 100644 index 000000000..5c8003150 --- /dev/null +++ b/crates/benilla-app/src/ui_action/unlearn.rs @@ -0,0 +1,205 @@ +//! The unlearn's bar clear: `UnlearnSpell 0x5e9fe0` ends in `0x4e5e20` (`0x5ea253`), which clears +//! every slot that stands for the spell. + +use bevy::prelude::*; + +use benilla_protocol::messages::{ACTION_KIND_ITEM, ACTION_KIND_SPELL}; +use benilla_ui::script::macro_slot_id; + +use super::PlayerActions; +use crate::items::Items; +use crate::net::{ClientCommand, NetCommands}; +use crate::query_cache::Ask; +use crate::ui_macro::{BoundSpell, MacroBoundSpells}; + +/// `0x4e5e20` for each spell the removed-spell message unlearned ([`PlayerActions::unlearned`]): +/// the 120 slots in order, each whose spell `0x4e5a50` resolves to it cleared with a send of 0 +/// (`0x4e5e40` into `0x4e5db0`). A spell slot resolves to its word, a macro slot to its cached +/// spell whatever its book (`0x4e5ba0`), an item slot to its template's on-use spell +/// (`0x4e5ae0`), none while the template is not cached. The identity feed then signals each +/// cleared slot. +pub(super) fn clear_unlearned_slots( + mut actions: ResMut, + bound: Res, + items: Res, + commands: Res, +) { + if actions.unlearned.is_empty() { + return; + } + let unlearned = std::mem::take(&mut actions.unlearned); + for spell in unlearned { + let mut slots: Vec = actions + .buttons + .values() + .filter(|b| { + let resolved = match b.kind { + ACTION_KIND_SPELL => Some(b.action), + ACTION_KIND_ITEM => items + .template(b.action, 0, Ask::Read) + .and_then(|t| t.use_spell) + .map(|u| u.spell_id), + kind => macro_slot_id(kind, b.action) + .and_then(|id| bound.0.get(&id)) + .and_then(|b| match b.spell { + BoundSpell::Spell(s) => Some(s), + _ => None, + }), + }; + resolved == Some(spell) + }) + .map(|b| b.slot) + .collect(); + slots.sort_unstable(); + for slot in slots { + actions.buttons.remove(&slot); + actions.dirty = true; + debug!("ui_action: unlearned spell {spell} clears wire slot {slot}"); + let _ = commands.0.send(ClientCommand::SetActionButton { + button: slot, + packed: 0, + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::items::Items; + use crate::net::{ClientCommand, NetCommands}; + use crate::ui_macro::{Bound, BoundSpell, MacroBoundSpells}; + use benilla_protocol::messages::{ + ActionButton, ItemUseSpell, ACTION_KIND_ITEM, ACTION_KIND_MACRO, ACTION_KIND_SPELL, + }; + + /// `0x4e5e20` walks the 120 slots and clears, each with a send of 0 (`0x4e5db0`), every slot + /// whose spell `0x4e5a50` resolves to the unlearned one: a spell slot holding it, a macro slot + /// whose cached spell it is whatever its book (`0x4e5ba0`), and an item slot whose on-use spell + /// it is (`0x4e5ae0`). The rest stand. + #[test] + fn an_unlearn_clears_every_slot_that_stands_for_the_spell() { + const FIREBALL: u32 = 133; + const FROSTBOLT: u32 = 116; + const GRENADE: u32 = 4390; + let (tx, rx) = crossbeam_channel::unbounded(); + let mut actions = PlayerActions::default(); + for (slot, kind, action) in [ + (0u8, ACTION_KIND_SPELL, FIREBALL), + (1, ACTION_KIND_SPELL, FROSTBOLT), + (2, ACTION_KIND_MACRO, 1), + (3, ACTION_KIND_MACRO, 2), + (4, ACTION_KIND_ITEM, GRENADE), + (5, ACTION_KIND_MACRO, 3), + ] { + actions + .buttons + .insert(slot, ActionButton { slot, action, kind }); + } + actions.unlearned.push(FIREBALL); + let mut bound = MacroBoundSpells::default(); + bound.0.insert(1, Bound::from(BoundSpell::Spell(FIREBALL))); + bound.0.insert(2, Bound::from(BoundSpell::Spell(FROSTBOLT))); + bound.0.insert( + 3, + Bound { + spell: BoundSpell::Spell(FIREBALL), + pet_book: true, + }, + ); + let mut items = Items::default(); + items.insert_template( + GRENADE, + Some(benilla_protocol::messages::ItemInfo { + use_spell: Some(ItemUseSpell { + spell_id: FIREBALL, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }), + ..crate::items::test_template("Iron Grenade") + }), + ); + let mut app = App::new(); + app.insert_resource(actions) + .insert_resource(bound) + .insert_resource(items) + .insert_resource(NetCommands(tx)) + .add_systems(Update, clear_unlearned_slots); + app.update(); + + let actions = app.world().resource::(); + let mut left: Vec = actions.buttons.keys().copied().collect(); + left.sort_unstable(); + assert_eq!(left, [1, 3]); + assert!( + actions.dirty, + "the identity feed re-resolves the cleared slots" + ); + assert!(actions.unlearned.is_empty()); + let sent: Vec<(u8, u32)> = rx + .try_iter() + .filter_map(|c| match c { + ClientCommand::SetActionButton { button, packed } => Some((button, packed)), + _ => None, + }) + .collect(); + assert_eq!(sent, [(0, 0), (2, 0), (4, 0), (5, 0)], "lowest first"); + } +} + +#[cfg(test)] +mod order_tests { + use crate::game_plugins::schedule_tests::{ + census, headless_client, type_names_available, SyncPoints, + }; + use bevy::ecs::schedule::SystemKey; + use bevy::prelude::*; + use std::collections::{HashMap, HashSet}; + + /// The supersede's unlearn clears what still stands for the old rank after `0x4e5e60` moved the + /// rest, so the clear runs after the rank pass, which stands in for that move on spell slots, + /// and both bar writers run before the identity feed that consumes their `dirty`. + #[test] + fn the_unlearn_clear_runs_after_the_rank_pass_and_before_the_feed() { + let mut app = headless_client(); + let c = census(&mut app, Update, SyncPoints::Declared); + if !type_names_available(&c) { + eprintln!( + "skipped: this build carries no type names (bevy/debug rides with the dev feature)" + ); + return; + } + let one = |suffix: &str| -> SystemKey { + let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); + match (hits.next(), hits.next()) { + (Some((k, _)), None) => *k, + _ => panic!("exactly one system named `…{suffix}` in Update"), + } + }; + let mut succ: HashMap> = HashMap::new(); + for (a, b) in &c.dependencies { + succ.entry(*a).or_default().push(*b); + } + let reach = |start: SystemKey| { + let mut seen = HashSet::new(); + let mut stack = vec![start]; + while let Some(n) = stack.pop() { + for m in succ.get(&n).into_iter().flatten() { + if seen.insert(*m) { + stack.push(*m); + } + } + } + seen + }; + let ranks = one("::ui_action::ranks::normalize_action_ranks"); + let clear = one("::ui_action::unlearn::clear_unlearned_slots"); + let feed = one("::ui_action::feed::feed_actions"); + assert!( + reach(ranks).contains(&clear), + "the clear runs after the rank pass" + ); + assert!(reach(clear).contains(&feed), "and before the identity feed"); + } +} diff --git a/crates/benilla-app/src/ui_macro/mod.rs b/crates/benilla-app/src/ui_macro/mod.rs index b55876e86..f00f313c4 100644 --- a/crates/benilla-app/src/ui_macro/mod.rs +++ b/crates/benilla-app/src/ui_macro/mod.rs @@ -34,6 +34,10 @@ pub(crate) struct MacroBoundSpells(pub(crate) std::collections::HashMap| -> Vec { + let read = |path: &Option, + per_character: bool| + -> Vec { let Some(path) = path else { return Vec::new() }; match std::fs::read_to_string(path) { - Ok(text) => store::parse(&text), + Ok(text) => store::parse(&text, per_character), // Absent is the first run, not a failure. Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), Err(e) => { @@ -139,9 +146,9 @@ fn load_macros( } } }; - let character_records = read(&files.character); + let character_records = read(&files.character, true); let moves = store::legacy_character_words(&character_records); - let state = MacroState::from_scopes(read(&files.account), character_records); + let state = MacroState::from_scopes(read(&files.account, false), character_records); info!( "ui_macro: {} account + {} character macros for {character} on {realm}", state.count(false), @@ -203,7 +210,8 @@ fn migrate_character_bar( script.queue_action_sets(writes); } -/// Persist on the engine's dirty edge, and fire `UPDATE_MACROS`. +/// Persist on the engine's dirty edge. The verbs signal `UPDATE_MACROS` themselves, inside their +/// calls. fn save_dirty_macros(mut hosted_vm: crate::script_calls::HostedVm, files: Res) { hosted_vm.run(|script| { let Some(script) = script else { return }; @@ -211,8 +219,6 @@ fn save_dirty_macros(mut hosted_vm: crate::script_calls::HostedVm, files: Res, } -/// Derive every macro's bound spell again on any change to the macro table (the engine's macro -/// generation) or to the action store (change detection), as the first pass of a VM does. When only -/// the pet's spell list changes, derive the records that follow the pet's book alone, as `0x4f0ce0` -/// does: a `/cast` that did not resolve and any record whose book selector is the pet's -/// (`0x4f0cfb`-`0x4f0d11`). A `CastSpellByName` that missed keeps its 0 through that alone; the -/// reference keeps it until the macro is edited, where the next table or bar change here derives -/// it again. +/// Derive the bound spells the engine's verbs do not (they derive the record a create or an edit +/// touches inside the call, `0x4f123c`, `0x4f1313`), where the reference's other callers of +/// `0x4efe00` do, and nowhere else: +/// - every record after the macro files load (`0x4f0a55` into `0x4f0ca0`) and after our player's +/// arrival learns its initial spells (`0x5deacc`); +/// - at the pet's spell list (`0x4bdae0` into `0x4f0ce0`), the records that follow the pet's book: +/// a `/cast` that did not resolve and any record whose selector is the pet's (`0x4f0cfb`- +/// `0x4f0d11`). +/// +/// A learned spell derives nothing, so a `/cast` of a spell not yet known stays -1 until its macro +/// is edited, loaded again or the player arrives again. A superseded rank rewrites the cached +/// spell of each macro on the bar that holds the old one (`0x4e5e60`'s macro arm, `0x4e5ec4`), +/// derived from nothing. Runs after the book's feed, so a derivation reads the book as it stands, +/// and copies the engine's records out for the action bar. fn rebind_macro_spells( - // The records, which the call host's usable refresh reads, so a turn: no Lua runs here. - mut vm: crate::script_calls::VmWith>, - actions: Res, - table: Option>, - mut seen: Local>, + // The bar, whose supersede queue this drains, and the records, which the call host's presses + // and usable refresh read, so a turn: no Lua runs here. + mut vm: crate::script_calls::VmWith<( + ResMut<'static, crate::ui_action::PlayerActions>, + ResMut<'static, MacroBoundSpells>, + )>, + arrivals: Query<(), Added>, + mut owed: Local<(bool, crate::ui_script::VmMemo)>, ) { - vm.turn(|script, mut bound| { - let (Some(script), Some(table)) = (script, table) else { + let (arrived, seen) = &mut *owed; + *arrived |= !arrivals.is_empty(); + vm.turn(|script, (mut actions, mut bound)| { + // With no VM the supersede pairs wait for the first pass that can apply them. + let Some(script) = script else { return; }; let seen = seen.get(script); - let first = seen.macros.is_none(); let generation = script.macros_generation(); let pet_generation = script.pet_book_generation(); - let table_moved = seen.macros != Some(generation) || actions.is_changed(); + let table_moved = seen.macros != Some(generation); let pet_moved = seen.pet_book != Some(pet_generation); - if !table_moved && !pet_moved { + if !table_moved && !pet_moved && !*arrived && actions.superseded.is_empty() { return; } seen.macros = Some(generation); seen.pet_book = Some(pet_generation); + // Both taken, so neither stays owed to the next pass. + let (arrival, load) = (std::mem::take(arrived), script.take_macro_derives().loaded); + let every = arrival || load; - let (macros, book, pet_book) = - (script.macros(), script.spellbook(), script.pet_spellbook()); - let mut fresh = std::collections::HashMap::new(); - for m in macros.views() { - // The records are new on a VM's first pass, with no book selector to keep. - let was = bound - .0 - .get(&m.id) - .copied() - .filter(|_| !first) - .unwrap_or_default(); - let next = if table_moved || was.follows_the_pet_book() { - run::bound_spell(&table, &m.body, &book, &pet_book, was) - } else { - was - }; - fresh.insert(m.id, next); + // The queue empties without marking the bar changed: the supersede marked it already. + let superseded = std::mem::take(&mut actions.bypass_change_detection().superseded); + if !superseded.is_empty() { + // The macros the bar holds are the ones a supersede reaches (`0x4e5e70`-`0x4e5ece`). + let on_bar: std::collections::HashSet = actions + .buttons + .values() + .filter_map(|b| benilla_ui::script::macro_slot_id(b.kind, b.action)) + .collect(); + let mut records = script.macro_bindings(); + for (_, b) in records.iter_mut().filter(|(id, _)| on_bar.contains(id)) { + for &(old, new) in &superseded { + if b.spell == old as i32 { + b.spell = new as i32; + } + } + } + script.set_macro_bindings(records); } - // The engine's copy, for `GetActionAutocast`, re-pushed on every recompute so a fresh VM - // has it. - script.set_macro_bindings( - fresh - .iter() - .map(|(&id, b)| { - let spell = match b.spell { - BoundSpell::None => 0, - BoundSpell::Unresolved => -1, - BoundSpell::Spell(id) => id as i32, - }; - ( - id, - benilla_ui::script::MacroBinding { - spell, - pet_book: b.pet_book, - }, - ) - }) - .collect(), - ); + script.derive_macro_bindings(|_, b| every || (pet_moved && b.follows_the_pet_book())); + + let records = script.macro_bindings(); + let fresh: std::collections::HashMap = script + .macros() + .views() + .map(|m| (m.id, records.get(&m.id).copied().unwrap_or_default().into())) + .collect(); if fresh != bound.0 { let spells = fresh .values() diff --git a/crates/benilla-app/src/ui_macro/run.rs b/crates/benilla-app/src/ui_macro/run.rs index 38748ff8e..40e5b98b2 100644 --- a/crates/benilla-app/src/ui_macro/run.rs +++ b/crates/benilla-app/src/ui_macro/run.rs @@ -1,31 +1,12 @@ -//! A macro body's runnable lines, and the spell it binds for the action bar. +//! A macro body's runnable lines, and the app's view of the spell it binds for the action bar. //! //! A macro slot shows the macro's icon but the cooldown, usability, range and checked state of its //! bound spell, the record's `[rec+0x564]`, which the slot resolver `0x4e5a50` returns for a -//! macro. `0x4efe00` derives it from the first line that is a `/cast` alias or holds -//! `CastSpellByName(`, through the resolver the `CastSpellByName` binding (`0x4b4ab0`) uses -//! (`0x4b3950` → `0x4b3a10`), so a bare name binds the highest known rank. -//! -//! `[rec+0x568]` is the book the spell resolved from, 0 the player's and 1 the pet's: the name is -//! looked up in the player's book, then the pet's (`0x4b3a10`), and a pet match binds the pet's -//! spell, which the action bar then reads through the pet's legs (`ui_action::state`). +//! macro, and `[rec+0x568]`, the book it resolved from. The engine derives both +//! ([`benilla_ui::script::MacroBinding`]); the action bar reads them through [`Bound`] +//! (`ui_action::state`). -use benilla_ui::script::{resolve_spell_in_books, PetBookState, SpellBookState}; - -use crate::ui_chat::commands::{Command, SlashCommands, SlashIndex}; - -/// Arm B's literal (`0x84cab0`), searched case-sensitively anywhere in the line (`0x4efed5`). -const CAST_BY_NAME_CALL: &str = "CastSpellByName("; - -/// Which of `0x4efe00`'s arms matched: an unresolved name stores -1 from arm A (`0x4eff48`) and -/// 0 from arm B (`0x4eff81`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CastArm { - /// A `/cast`-alias line (`SLASH_CAST%d`, read as Lua globals at `0x703bf0`). - Slash, - /// A `CastSpellByName("…")` call anywhere in the line. - ByName, -} +use benilla_ui::script::MacroBinding; /// A macro record's cached bound spell, the reference's `[rec+0x564]` (written by `0x4efe00`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -60,392 +41,18 @@ impl From for Bound { } } -impl Bound { - /// Whether `0x4f0ce0` derives this record again when the pet's spell list arrives - /// (`0x4f0cfb`-`0x4f0d11`): a `/cast` that did not resolve (`[rec+0x564] < 0`), or any record - /// whose book selector is the pet's (`[rec+0x568] != 0`), whatever it is bound to now. Any - /// other record keeps its cast. - pub(crate) fn follows_the_pet_book(self) -> bool { - self.spell == BoundSpell::Unresolved || self.pet_book - } -} - -/// A macro body's runnable lines: the reference's tokenizer (`0x64ae50`) splits on either `\r` or -/// `\n` and skips empty tokens. Deviation: each line is trimmed, because the reference sends an -/// indented `" /say hi"` as plain chat, never as the command meant. A whitespace-only line is fired -/// there and dropped by `ChatEdit_SendText`, the same observable. -pub(crate) fn macro_lines(body: &str) -> impl Iterator { - body.split(['\r', '\n']) - .map(str::trim) - .filter(|l| !l.is_empty()) -} - -/// The spell name a macro body casts (`0x4efe00`): the first `/cast`-alias line, or line holding -/// `CastSpellByName(` and then a quote, whose text is the name even when it is empty -/// ([`quoted_call_argument`]). Deviation: the `/cast` argument is trimmed, because the reference -/// binds `/cast Fireball` (two spaces) to a name that never resolves. -pub(crate) fn cast_name(table: &SlashCommands, body: &str) -> Option<(CastArm, String)> { - for line in macro_lines(body) { - // Arm A: the alias folds ASCII case (`_strnicmp`, `0x414310`, as `SlashCommands::lookup` - // does), and the next byte must be a space (`0x4efe96`), so a tab or a bare `/cast` misses. - if let Some(rest) = line.strip_prefix('/') { - let (cmd, args) = rest.split_once(' ').unwrap_or((rest, "")); - if table.lookup(cmd) == Some(Command::Slash(SlashIndex::Cast)) { - let args = args.trim(); - if !args.is_empty() { - return Some((CastArm::Slash, args.to_string())); - } - // The reference tries arm B on this line, then the next line. - continue; - } - } - // Arm B, second, on the same line (`0x4efed5`): its quote decides the binding, so the walk - // ends here whatever the name is or resolves to. - if let Some(name) = quoted_call_argument(line) { - return Some((CastArm::ByName, name)); - } - } - None -} - -/// The text of the first quote after `CastSpellByName(` on the line: from the first `"` at or -/// after the match (`0x4efef0`-`0x4efefb`, the literal holds none) to the next `"` or the line's -/// end (`0x4eff58`-`0x4eff6d`). Whatever stands between the parenthesis and the quote is skipped, -/// so `CastSpellByName(IsShiftKeyDown() and "Frostbolt(Rank 1)" or "Frostbolt")` gives -/// `Frostbolt(Rank 1)`. A line with no such quote gives nothing and the walk goes on (`0x4efefd`); -/// an empty name is a name, which `0x4b3bc0` answers 0. -fn quoted_call_argument(line: &str) -> Option { - let after_call = &line[line.find(CAST_BY_NAME_CALL)?..]; - let open = after_call.find('"')?; - let rest = &after_call[open + 1..]; - Some(rest.split('"').next().unwrap_or_default().to_string()) -} - -/// The macro's cast, derived again (`0x4efe00`) from `was`: [`cast_name`] resolved as -/// `CastSpellByName` resolves a name ([`resolve_spell_in_books`]), so the cooldown swirl and the -/// press agree on the rank. A match writes the book it came from; a miss leaves the selector. -pub(crate) fn bound_spell( - table: &SlashCommands, - body: &str, - player: &SpellBookState, - pet: &PetBookState, - was: Bound, -) -> Bound { - let Some((arm, name)) = cast_name(table, body) else { - return Bound { - spell: BoundSpell::None, - ..was - }; - }; - match (resolve_spell_in_books(player, pet, &name), arm) { - (Some(s), _) => Bound { - spell: BoundSpell::Spell(s.spell_id), - pet_book: s.pet, - }, - (None, CastArm::Slash) => Bound { - spell: BoundSpell::Unresolved, - ..was - }, - (None, CastArm::ByName) => Bound { - spell: BoundSpell::None, - ..was - }, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::ui_chat::commands::SlashCommands; - use benilla_ui::script::SpellSlotView; - - /// The aliases these tests need, built through the global-string reader as boot builds it. - fn table() -> SlashCommands { - SlashCommands::build( - |name| match name { - "SLASH_CAST1" => Some("/cast".into()), - "SLASH_CAST2" => Some("/spell".into()), - "SLASH_SCRIPT1" => Some("/script".into()), - "SLASH_TARGET1" => Some("/target".into()), - _ => None, +impl From for Bound { + /// The engine's record: 0 none, -1 unresolved, else the spell. + fn from(b: MacroBinding) -> Self { + Self { + spell: match b.spell { + 0 => BoundSpell::None, + s if s < 0 => BoundSpell::Unresolved, + s => BoundSpell::Spell(s as u32), }, - |_| None, - ) - } - - #[test] - fn macro_lines_trims_blanks_and_windows_line_endings() { - let body = "/cast Fireball\r\n\r\n /say pew \n"; - let lines: Vec<&str> = macro_lines(body).collect(); - assert_eq!(lines, ["/cast Fireball", "/say pew"]); - } - - /// `/spell` is `SLASH_CAST2` in the shipped strings. - #[test] - fn cast_name_reads_the_first_cast_line_through_the_alias_table() { - let t = table(); - assert_eq!( - cast_name(&t, "/target Bob\n/cast Fireball\n/say pew"), - Some((CastArm::Slash, "Fireball".into())) - ); - assert_eq!( - cast_name(&t, "/spell Frostbolt"), - Some((CastArm::Slash, "Frostbolt".into())) - ); - // The whole argument, rank included; `resolve_spell_by_name` parses it. - assert_eq!( - cast_name(&t, "/cast Fireball(Rank 1)"), - Some((CastArm::Slash, "Fireball(Rank 1)".into())) - ); - // First match wins. - assert_eq!( - cast_name(&t, "/cast Fireball\n/cast Frostbolt"), - Some((CastArm::Slash, "Fireball".into())) - ); - // A bare `/cast` binds nothing and does not stop the walk. - assert_eq!( - cast_name(&t, "/cast\n/cast Frostbolt"), - Some((CastArm::Slash, "Frostbolt".into())) - ); - assert_eq!(cast_name(&t, "/say hello\n/target Bob"), None); - } - - #[test] - fn the_alias_separator_is_a_literal_space_and_the_alias_folds_case() { - let t = table(); - let fireball = Some((CastArm::Slash, "Fireball".into())); - assert_eq!(cast_name(&t, "/CAST Fireball"), fireball); - assert_eq!(cast_name(&t, "/Cast Fireball"), fireball); - // A tab does not separate, so the walk goes on. - assert_eq!( - cast_name(&t, "/cast\tFireball\n/cast Frostbolt"), - Some((CastArm::Slash, "Frostbolt".into())) - ); - // Arm B is case-sensitive. - assert_eq!( - cast_name(&t, r#"/script castspellbyname("Fireball")"#), - None - ); - } - - #[test] - fn cast_name_reads_a_quoted_cast_spell_by_name_call() { - let t = table(); - assert_eq!( - cast_name(&t, r#"/script CastSpellByName("Shadow Bolt")"#), - Some((CastArm::ByName, "Shadow Bolt".into())) - ); - // Spacing and a second argument don't matter; the first quoted argument is the name. - assert_eq!( - cast_name(&t, r#"/script CastSpellByName( "Healing Touch", 1 )"#), - Some((CastArm::ByName, "Healing Touch".into())) - ); - // A computed argument with no quote has no name to bind. - assert_eq!(cast_name(&t, "/script CastSpellByName(spell)"), None); - } - - /// `0x4efef0`-`0x4efefb` scan for the first quote anywhere after the match, whatever the - /// parenthesis holds, and `0x4eff58`-`0x4eff6d` read to the next quote or the line's end. - #[test] - fn the_first_quote_after_the_call_is_the_name_wherever_it_stands() { - let t = table(); - assert_eq!( - cast_name( - &t, - r#"/script CastSpellByName(IsShiftKeyDown() and "Frostbolt(Rank 1)" or "Frostbolt")"# - ), - Some((CastArm::ByName, "Frostbolt(Rank 1)".into())) - ); - assert_eq!( - cast_name(&t, r#"/script CastSpellByName(GetSpell("Fire"))"#), - Some((CastArm::ByName, "Fire".into())), - "up to the next quote, the call's own closing parenthesis not a stop" - ); - assert_eq!( - cast_name(&t, r#"/script CastSpellByName("Fire"#), - Some((CastArm::ByName, "Fire".into())), - "an unterminated name runs to the line's end" - ); - // The scan starts at the match: a quote ahead of it is not the name, and a line with none - // after it goes on to the next line (`0x4efefd`). - assert_eq!( - cast_name( - &t, - "/script local a = \"x\"; CastSpellByName(spell)\n/cast Frostbolt" - ), - Some((CastArm::Slash, "Frostbolt".into())) - ); - } - - /// The bound spell of `body` for a macro that was bound to nothing, against the player's book. - fn bound(t: &SlashCommands, body: &str, book: &SpellBookState) -> BoundSpell { - bound_spell(t, body, book, &PetBookState::default(), Bound::default()).spell - } - - fn fireball_book() -> SpellBookState { - SpellBookState { - tabs: Vec::new(), - slots: vec![SpellSlotView { - spell_id: 133, - name: "Fireball".into(), - ..Default::default() - }], + pet_book: b.pet_book, } } - - /// An empty name is a name: `0x4eff7b` resolves it to 0 and `0x4eff81` stores that, ending the - /// walk on its line, where a later `/cast` is never read. - #[test] - fn an_empty_name_binds_nothing_and_ends_the_walk() { - let t = table(); - let body = "/script CastSpellByName(\"\")\n/cast Fireball"; - assert_eq!(cast_name(&t, body), Some((CastArm::ByName, String::new()))); - assert_eq!(bound(&t, body, &fireball_book()), BoundSpell::None); - // A computed first argument binds the quoted fallback after it, not the later line. - assert_eq!( - bound( - &t, - "/script CastSpellByName(x and \"Fireball\" or \"Frostbolt\")\n/cast Frostbolt", - &fireball_book() - ), - BoundSpell::Spell(133) - ); - } - - #[test] - fn bound_spell_resolves_through_the_book() { - let book = SpellBookState { - tabs: Vec::new(), - slots: vec![ - SpellSlotView { - spell_id: 133, - name: "Fireball".into(), - rank: Some("Rank 1".into()), - ..Default::default() - }, - SpellSlotView { - spell_id: 145, - name: "Fireball".into(), - rank: Some("Rank 2".into()), - ..Default::default() - }, - ], - }; - let t = table(); - // No subtext -> the highest known rank. - assert_eq!(bound(&t, "/cast Fireball", &book), BoundSpell::Spell(145)); - // A pinned subtext -> that rank. The spaced form keeps its space in the name - // (`0x4b3950` trims nothing), so it names no spell and the bar greys the slot. - assert_eq!( - bound(&t, "/cast Fireball(Rank 1)", &book), - BoundSpell::Spell(133) - ); - assert_eq!( - bound(&t, "/cast Fireball (Rank 1)", &book), - BoundSpell::Unresolved - ); - } - - /// An unknown `/cast` is -1 (`0x4eff48`), which the bar greys; no cast line, or an unknown - /// `CastSpellByName(`, is 0 (`0x4eff81`). - #[test] - fn an_unresolved_cast_is_arm_dependent() { - let book = SpellBookState::default(); - let t = table(); - assert_eq!(bound(&t, "/cast Pyroblast", &book), BoundSpell::Unresolved); - assert_eq!( - bound(&t, "/spell Pyroblast\n/say pew", &book), - BoundSpell::Unresolved - ); - assert_eq!(bound(&t, "/say hi", &book), BoundSpell::None); - assert_eq!(bound(&t, ".spawn 16032", &book), BoundSpell::None); - assert_eq!( - bound(&t, r#"/script CastSpellByName("Pyroblast")"#, &book), - BoundSpell::None - ); - } - - fn named(spell_id: u32, name: &str) -> SpellSlotView { - SpellSlotView { - spell_id, - name: name.into(), - ..Default::default() - } - } - - /// `0x4b3a10` searches the player's book, then the pet's, and `0x4b3b51` writes which one - /// matched; `0x4efe00` hands that book to the record (`0x4eff2b`, `0x4eff72`). - #[test] - fn a_name_only_the_pets_book_holds_binds_its_spell_with_the_pets_book() { - let t = table(); - let player = SpellBookState { - tabs: Vec::new(), - slots: vec![named(133, "Fireball"), named(1, "Seduction")], - }; - let pet = PetBookState { - token: None, - slots: vec![named(6358, "Seduction"), named(19647, "Spell Lock")], - }; - let derive = |body: &str| bound_spell(&t, body, &player, &pet, Bound::default()); - let from_pet = |id| Bound { - spell: BoundSpell::Spell(id), - pet_book: true, - }; - assert_eq!(derive("/cast Spell Lock"), from_pet(19647)); - assert_eq!( - derive(r#"/script CastSpellByName("Spell Lock")"#), - from_pet(19647), - "the quoted form binds it too" - ); - // The player's book is searched first. - assert_eq!(derive("/cast Seduction"), Bound::from(BoundSpell::Spell(1))); - assert_eq!( - derive("/cast Fireball"), - Bound::from(BoundSpell::Spell(133)) - ); - // A name in neither book is what it was: -1 for a `/cast`, 0 for the quoted form. - assert_eq!(derive("/cast Claw"), Bound::from(BoundSpell::Unresolved)); - assert_eq!( - derive(r#"/script CastSpellByName("Claw")"#), - Bound::from(BoundSpell::None) - ); - // With the pet gone, a pet spell is a name in neither. - let gone = |was| { - bound_spell( - &t, - "/cast Spell Lock", - &player, - &PetBookState::default(), - was, - ) - }; - assert_eq!(gone(Bound::default()).spell, BoundSpell::Unresolved); - // A miss leaves the book selector (`0x4b3a10` writes it on a match alone), so a record - // that was the pet's stays the pet's through it, and a cast line that is gone keeps it too. - assert!(gone(from_pet(19647)).pet_book); - assert!(!gone(Bound::default()).pet_book); - let gone_line = bound_spell(&t, "/say hi", &player, &pet, from_pet(19647)); - assert_eq!( - gone_line, - Bound { - spell: BoundSpell::None, - pet_book: true - } - ); - } - - /// `0x4f0ce0` derives a record again at a pet spell message only when `[rec+0x564] < 0` or - /// `[rec+0x568] != 0` (`0x4f0cfb`-`0x4f0d11`), whatever it is bound to now. - #[test] - fn only_an_unresolved_or_pet_selected_record_follows_the_pets_list() { - let record = |spell, pet_book| Bound { spell, pet_book }; - assert!(record(BoundSpell::Unresolved, false).follows_the_pet_book()); - assert!(record(BoundSpell::Spell(6358), true).follows_the_pet_book()); - assert!( - record(BoundSpell::None, true).follows_the_pet_book(), - "a quoted call that lost the pet's spell keeps the pet's book" - ); - assert!(!record(BoundSpell::None, false).follows_the_pet_book()); - assert!(!record(BoundSpell::Spell(133), false).follows_the_pet_book()); - } } + +pub(crate) use benilla_ui::script::macro_lines; diff --git a/crates/benilla-app/src/ui_macro/store.rs b/crates/benilla-app/src/ui_macro/store.rs index ed35f34f2..a0541bd78 100644 --- a/crates/benilla-app/src/ui_macro/store.rs +++ b/crates/benilla-app/src/ui_macro/store.rs @@ -4,63 +4,119 @@ //! `macros-cache.txt` drops into `benilla-config/macros/`. The number is the macro's id, which an //! action slot holds. A save writes a scope in name order, the sorted table's (`0x4f0ad0`); a load //! keeps the file's order as the list order the reference's sort and name lookups start from -//! (`MacroState`). A name holding a `"` runs from the first quote to the last, since the -//! reference's `"%s"` is unescaped. +//! (`MacroState`). The writer's `"%s"` is unescaped and the reader's name token ends at the next +//! quote, so a name holding a `"` does not survive the round trip. -use benilla_ui::script::{macro_slot_word, MacroView, CHARACTER_ID_BASE, MAX_MACROS}; +use benilla_ui::script::{ + macro_slot_word, s_str_to_int, s_str_tokenize, MacroView, CHARACTER_ID_BASE, MAX_MACROS, +}; + +/// The reader's and the writer's line buffers, and the reader's header token buffers: 0x100 bytes +/// (`0x4f0677`, `0x4f0b93`, `0x4f06b3`). +const LINE_BYTES: usize = 0x100; + +/// The header's name and icon delimiters (`0x84cb48`), with quotes on. +const NAME_DELIMS: &[u8] = b" \"\r\n"; + +/// A token as its buffer kept it. Deviation: the reference's 255-byte cut (`0x4f0677`, +/// `0x4f0b93`) can end inside a character and keep its stray bytes; a `String` must stay UTF-8, +/// so the cut backs off to the character's start. +fn token_text(bytes: Vec) -> String { + match String::from_utf8(bytes) { + Ok(text) => text, + Err(e) => { + let valid = e.utf8_error().valid_up_to(); + let mut bytes = e.into_bytes(); + bytes.truncate(valid); + String::from_utf8(bytes).unwrap_or_default() + } + } +} + +/// The lines of `text` as the tokenizer splits them on CR and LF into a [`LINE_BYTES`] buffer: +/// blank lines are no tokens, and each keeps its first 255 bytes. +fn lines(text: &str) -> impl Iterator + '_ { + let mut cursor = text.as_bytes(); + std::iter::from_fn(move || { + let line = s_str_tokenize(&mut cursor, LINE_BYTES, b"\r\n"); + (!line.is_empty()).then(|| token_text(line)) + }) +} /// The path prefix the client prepends to a stored icon basename (`0x84ca64`). pub(super) const ICON_PREFIX: &str = "Interface\\Icons\\"; -/// Parse one scope's file into its records in file order, each with its id. A header with no id, or -/// a zero one, is no record (`0x4f072a`); the table that takes them skips what the scope cannot -/// hold and any id it has, and gives an id below its base the base (`MacroState::from_scopes`). -pub(super) fn parse(text: &str) -> Vec { +/// Parse one scope's file into its records in file order, each with its id, as the reader +/// `0x4f0600` walks it: the file splits into [`lines`] (`0x4f0687`). With no record open, a line +/// whose first space-separated token is `MACRO` without case is a header (`0x4f06c1`, +/// `0x4f06d7`), which opens nothing in a scope that holds 18 (`0x4f06f8`): its id is `SStrToInt` +/// of the next space-separated token, and a zero one, or one the scope's file opened already, is +/// no record (`0x4f072a`, `0x4f078b`); then the name and the icon are the next two tokens on +/// `` "\r\n`` with quotes on (`0x4f07bb`, `0x4f0986`), so a name runs to the next quote. A header +/// with an empty name is read but opens no record (`0x4f07c8`), the table skipping it once its +/// id has counted. Within a record each line is body text followed by `\n` (`0x4f0a15`, +/// `0x4f0a2b`), a `MACRO` line included (`0x4f06a2`), until a line that is `END` without case +/// (`0x4f09d3`), where the body is stored (`0x4f09e4`): a record the file ends inside keeps an +/// empty body. The table that takes the records skips what the scope cannot hold and any id it +/// has, and gives an id below its base the base (`MacroState::from_scopes`). +pub(super) fn parse(text: &str, per_character: bool) -> Vec { + let base = if per_character { CHARACTER_ID_BASE } else { 0 }; let mut out: Vec = Vec::new(); - let mut lines = text.lines().peekable(); - while let Some(line) = lines.next() { - let Some(rest) = line.trim_start().strip_prefix("MACRO ") else { - continue; // stray text between records - }; - let Some((id, name, icon)) = parse_header(rest) else { - continue; - }; - // The body runs to a bare END, or to the next MACRO or EOF, so a truncated file keeps its - // last macro. - let mut body: Vec<&str> = Vec::new(); - loop { - match lines.peek() { - None => break, - Some(l) if l.trim() == "END" => { - lines.next(); - break; - } - Some(l) if l.trim_start().starts_with("MACRO ") => break, - Some(_) => body.push(lines.next().unwrap_or_default()), + // The ids of the records opened so far, as the table holds them: past the base + // (`0x4f0737`, a signed compare). + let mut held: std::collections::HashSet = std::collections::HashSet::new(); + // The open record, its index in `out`, and the body read so far. + let mut open: Option<(usize, String)> = None; + for line in lines(text) { + if let Some((at, body)) = &mut open { + if benilla_ui::crt::str_cmp_i(&line, "END") == 0 { + out[*at].body = std::mem::take(body); + open = None; + } else { + body.push_str(&line); + body.push('\n'); } + continue; + } + let mut cursor = line.as_bytes(); + let mut token = |delims: &[u8]| token_text(s_str_tokenize(&mut cursor, LINE_BYTES, delims)); + if benilla_ui::crt::str_cmp_i(&token(b" "), "MACRO") != 0 { + continue; // stray text between records + } + // A full scope opens no record (`0x4f06f8`). + if held.len() >= MAX_MACROS { + continue; + } + let id = s_str_to_int(&token(b" ")) as u32; + if id == 0 { + continue; + } + // An id the table holds opens no record (`0x4f078b`). + let as_held = if (id as i32) < base as i32 { + id.wrapping_add(base) + } else { + id + }; + if held.contains(&as_held) { + continue; + } + let name = token(NAME_DELIMS); + let icon = token(NAME_DELIMS); + if !name.is_empty() { + held.insert(as_held); + open = Some((out.len(), String::new())); } out.push(MacroView { id, name, - texture: icon.map(icon_path), - body: body.join("\n"), + texture: (!icon.is_empty()).then(|| icon_path(icon)), + body: String::new(), local_only: false, }); } out } -/// The tail of a `MACRO ` header line: ` "" `. -fn parse_header(rest: &str) -> Option<(u32, String, Option)> { - let (id, rest) = rest.split_once('"')?; - let id: u32 = id.trim().parse().ok().filter(|&id| id != 0)?; - // To the last quote on the line: the reference's `"%s"` is unescaped. - let close = rest.rfind('"')?; - let name = rest[..close].to_string(); - let icon = rest[close + 1..].trim(); - Some((id, name, (!icon.is_empty()).then(|| icon.to_string()))) -} - /// The bar words of the builds that numbered macros by position, in the character file's terms /// (`(old word, new word)`, empty when the file is not such a build's). /// @@ -92,14 +148,17 @@ pub(super) fn legacy_character_words(records: &[MacroView]) -> Vec<(u32, u32)> { .collect() } -/// Serialize a scope's macros back into the reference's format, in the order given. +/// Serialize a scope's macros back into the reference's format, in the order given: the header +/// (`0x4f0b61`), each of the body's [`lines`] with its own line end, so a blank line writes nothing +/// (`0x4f0b8c`-`0x4f0be5`), then `END` (`0x4f0bec`). pub(super) fn write<'a>(macros: impl Iterator) -> String { let mut out = String::new(); for m in macros { let icon = m.texture.as_deref().map(icon_token).unwrap_or_default(); - out.push_str(&format!("MACRO {} \"{}\" {}\n", m.id, m.name, icon)); - if !m.body.is_empty() { - out.push_str(&m.body); + // `%d`: the id signed. + out.push_str(&format!("MACRO {} \"{}\" {}\n", m.id as i32, m.name, icon)); + for line in lines(&m.body) { + out.push_str(&line); out.push('\n'); } out.push_str("END\n"); @@ -141,7 +200,7 @@ mod tests { #[test] fn a_real_1_12_macros_cache_file_parses_in_file_order_with_its_ids() { - let macros = parse(REAL_112_FILE); + let macros = parse(REAL_112_FILE, false); assert_eq!(macros.len(), 3); // The file's order is the list order; the ids are the file's own. let seen: Vec<(u32, &str)> = macros.iter().map(|m| (m.id, m.name.as_str())).collect(); @@ -151,20 +210,24 @@ mod tests { Some("Interface\\Icons\\Ability_Ambush"), "the stored token is a basename; the client's own prefix completes it" ); - assert_eq!(macros[0].body, ".cheat fly on\n.modify aspeed 10"); - assert_eq!(macros[2].body, ".wchange 0 0"); + assert_eq!( + macros[0].body, ".cheat fly on\n.modify aspeed 10\n", + "each line is followed by a newline, the last too (`0x4f0a2b`)" + ); + assert_eq!(macros[2].body, ".wchange 0 0\n"); } #[test] fn write_then_parse_round_trips_and_matches_the_reference_shape() { - let macros = parse(REAL_112_FILE); + let macros = parse(REAL_112_FILE, false); let text = write(macros.iter()); // The reference's line shape, each record under its own id. assert!(text.starts_with("MACRO 1 \"f\" Ability_Ambush\n")); assert!(text.contains("\nMACRO 3 \"ns\" Ability_BackStab\n")); assert!(text.contains("\nMACRO 2 \"w\" Ability_Creature_Cursed_05\n")); assert!(text.ends_with("END\n")); - assert_eq!(parse(&text), macros, "round trip"); + assert_eq!(parse(&text, false), macros, "round trip"); + assert_eq!(text, REAL_112_FILE, "the file as it was read"); } #[test] @@ -178,11 +241,12 @@ mod tests { }]; let text = write(m.iter()); assert_eq!(text, "MACRO 1 \"bare\" \nEND\n"); - assert_eq!(parse(&text), m); + assert_eq!(parse(&text, false), m); } - /// A file truncated before its last `END` still yields that macro. A header with a zero or - /// no id is no record (`0x4f0728`). + /// A file truncated before its last `END` still yields that macro, with an empty body: the + /// body is stored at `END` alone (`0x4f09e4`). A header with a zero or no id is no record + /// (`0x4f0728`). #[test] fn malformed_records_lose_only_themselves() { let text = "garbage line\n\ @@ -195,29 +259,194 @@ mod tests { END\n\ MACRO 3 \"truncated\" Ability_Ambush\n\ /say bye\n"; - let macros = parse(text); + let macros = parse(text, false); assert_eq!(macros.len(), 2); assert_eq!((macros[0].id, macros[0].name.as_str()), (2, "good")); assert_eq!((macros[1].id, macros[1].name.as_str()), (3, "truncated")); - assert_eq!(macros[1].body, "/say bye", "no END is still a macro"); + assert_eq!(macros[0].body, "/say hi\n"); + assert_eq!(macros[1].body, "", "no END is still a macro, with no body"); } + /// Within a record only a line that is `END` without case closes it (`0x4f09c8`, `SStrCmpI` + /// on the whole line): a `MACRO` line, or an `END` with a space before it, is body text. + /// Blank lines are no tokens of the reader's line split on CR and LF (`0x4f0687`), so they + /// vanish. #[test] - fn a_quoted_name_round_trips_the_way_the_reference_would_write_it() { - let m = vec![MacroView { + fn only_an_end_line_closes_a_record() { + let text = "MACRO 1 \"a\" Ability_Ambush\r\n\ + /say one\r\n\ + \r\n\ + MACRO 2 \"b\" Ability_Ambush\r\n\ + \x20END\r\n\ + end\r\n\ + MACRO 3 \"c\" Ability_Ambush\n\ + \x20 /say three \n\ + End\n"; + let macros = parse(text, false); + let seen: Vec<(u32, &str)> = macros.iter().map(|m| (m.id, m.body.as_str())).collect(); + assert_eq!( + seen, + [ + (1, "/say one\nMACRO 2 \"b\" Ability_Ambush\n END\n"), + (3, " /say three \n") + ] + ); + } + + /// The reader opens a record on a line whose first space-separated token is `MACRO` without + /// case (`0x4f06c1`, `0x4f06d7`). + #[test] + fn a_header_is_read_without_case() { + let macros = parse(" macro 7 \"m\" Ability_Ambush\n/say hi\nEND\n", false); + assert_eq!(macros.len(), 1); + assert_eq!((macros[0].id, macros[0].body.as_str()), (7, "/say hi\n")); + } + + /// The writer tokenizes the body on CR and LF (`0x4f0b8c`) and writes each token with its own + /// line end (`0x4f0bc5`, `0x4f0bdb`), so a blank line or a trailing newline writes no line. + #[test] + fn the_writer_writes_no_blank_line() { + let m = [MacroView { + id: 1, + name: "a".into(), + texture: None, + body: "/say one\n\n/say two\r\n".into(), + local_only: false, + }]; + assert_eq!(write(m.iter()), "MACRO 1 \"a\" \n/say one\n/say two\nEND\n"); + } + + /// The name token is the tokenizer's with `` "\r\n`` as delimiters and quotes on (`0x4f07bb`, + /// `0x84cb48`): a leading `"` opens a span the next `"` closes, so a name runs to the next + /// quote, and the icon token (`0x4f0986`) starts after it. A name holding a quote does not + /// survive the round trip; an empty name is no record (`0x4f07c8`). + #[test] + fn a_name_runs_to_the_next_quote() { + let m = [MacroView { id: 4, name: "say \"hi\"".into(), texture: Some("Interface\\Icons\\Ability_Ambush".into()), - body: "/say hi".into(), + body: "/say hi\n".into(), local_only: false, }]; - assert_eq!(parse(&write(m.iter())), m); + let text = write(m.iter()); + assert_eq!( + text, + "MACRO 4 \"say \"hi\"\" Ability_Ambush\n/say hi\nEND\n" + ); + let back = parse(&text, false); + assert_eq!(back.len(), 1); + assert_eq!(back[0].name, "say "); + assert_eq!(back[0].texture.as_deref(), Some("Interface\\Icons\\hi")); + let empty = parse("MACRO 2 \"\" Ability_Ambush\n/say x\nEND\n", false); + assert_eq!( + empty.iter().map(|m| m.name.as_str()).collect::>(), + [""], + "read, for the table to skip after it has counted its id" + ); + let state = MacroState::from_scopes(empty, Vec::new()); + assert_eq!(state.count(false), 0); + } + + /// The id is `SStrToInt` of its space-separated token (`0x4f0721`): leading digits, a sign, and + /// a negative id below the scope's base gets the base added (`0x4f0737`, a signed compare). + #[test] + fn the_id_is_read_as_sstrtoint_reads_it() { + let macros = parse( + "MACRO 12x \"a\" Ability_Ambush\nEND\nMACRO -5 \"b\" Ability_Ambush\nEND\n", + true, + ); + let ids: Vec = macros.iter().map(|m| m.id).collect(); + assert_eq!(ids, [12, (-5i32) as u32]); + let state = MacroState::from_scopes(Vec::new(), macros); + let ids: Vec = state.saved(true).iter().map(|m| m.id).collect(); + assert_eq!(ids, [CHARACTER_ID_BASE + 12, CHARACTER_ID_BASE - 5]); + } + + /// A header whose id the table holds opens no record (`0x4f0789` into `0x4f0a30`), so the + /// reader looks for a header on the next line: a `MACRO` line in that body is one. Before + /// that, a full scope opens none either (`0x4f06f8`). + #[test] + fn a_header_with_an_id_already_read_opens_no_record() { + let text = "MACRO 1 \"a\" Ability_Ambush\n/say a\nEND\n\ + MACRO 1 \"b\" Ability_Ambush\n\ + MACRO 2 \"c\" Ability_Ambush\n/say c\nEND\n"; + let seen: Vec<(u32, String, String)> = parse(text, false) + .into_iter() + .map(|m| (m.id, m.name, m.body)) + .collect(); + assert_eq!( + seen, + [ + (1, "a".to_string(), "/say a\n".to_string()), + (2, "c".to_string(), "/say c\n".to_string()) + ] + ); + // A character file's small id is the same record as its full one (`0x4f0737` first). + let text = format!( + "MACRO {} \"a\" Ability_Ambush\nEND\nMACRO 1 \"b\" Ability_Ambush\n\ + MACRO 2 \"c\" Ability_Ambush\nEND\n", + CHARACTER_ID_BASE + 1 + ); + let names: Vec = parse(&text, true).into_iter().map(|m| m.name).collect(); + assert_eq!(names, ["a", "c"]); + let full: String = (1..=19) + .map(|i| format!("MACRO {i} \"m{i}\" Ability_Ambush\nEND\n")) + .chain([ + "MACRO 30 \"late\" Ability_Ambush\nMACRO 31 \"x\" Ability_Ambush\nEND\n".into(), + ]) + .collect(); + let ids: Vec = parse(&full, false).into_iter().map(|m| m.id).collect(); + assert_eq!(ids, (1..=18).collect::>(), "nothing past the 18th"); + } + + /// The header is formatted with `%d` (`0x84cb60`, pushed at `0x4f0b61`): an id is written + /// signed. + #[test] + fn the_writer_writes_the_id_signed() { + let m = [MacroView { + id: (-5i32) as u32, + name: "n".into(), + texture: None, + body: String::new(), + local_only: false, + }]; + assert_eq!(write(m.iter()), "MACRO -5 \"n\" \nEND\n"); + } + + /// The reader's line buffer and the writer's are 0x100 bytes (`0x4f0677`, `0x4f0b93`), so each + /// keeps a line's first 255 bytes; a cut inside a character backs off to its start. + #[test] + fn a_line_keeps_its_first_255_bytes() { + let long = "a".repeat(300); + let wide = "\u{e9}".repeat(200); + let text = format!("MACRO 1 \"m\" Ability_Ambush\n{long}\n{wide}\nEND\n"); + let body = &parse(&text, false)[0].body; + assert_eq!( + body, + &format!("{}\n{}\n", "a".repeat(255), "\u{e9}".repeat(127)) + ); + let m = [MacroView { + id: 1, + name: "m".into(), + texture: None, + body: format!("{long}\n{wide}"), + local_only: false, + }]; + assert_eq!( + write(m.iter()), + format!( + "MACRO 1 \"m\" \n{}\n{}\nEND\n", + "a".repeat(255), + "\u{e9}".repeat(127) + ) + ); } #[test] fn a_full_path_icon_token_is_taken_whole() { let text = "MACRO 1 \"custom\" Interface\\Buttons\\UI-Panel-Button\nEND\n"; - let macros = parse(text); + let macros = parse(text, false); assert_eq!( macros[0].texture.as_deref(), Some("Interface\\Buttons\\UI-Panel-Button") @@ -232,7 +461,7 @@ mod tests { let text: String = (1..=25) .map(|i| format!("MACRO {i} \"m{i}\" Ability_Ambush\nEND\n")) .collect(); - let state = MacroState::from_scopes(parse(&text), Vec::new()); + let state = MacroState::from_scopes(parse(&text, false), Vec::new()); assert_eq!(state.count(false), MAX_MACROS); assert_eq!(state.count(true), 0); } @@ -242,13 +471,13 @@ mod tests { #[test] fn a_character_file_with_small_ids_is_rebased_and_saved_with_the_full_id() { let text = "MACRO 1 \"mine\" Ability_Ambush\n/say hi\nEND\n"; - let state = MacroState::from_scopes(Vec::new(), parse(text)); + let state = MacroState::from_scopes(Vec::new(), parse(text, true)); let saved = write(state.saved(true).into_iter()); assert!( saved.starts_with("MACRO 16777217 \"mine\" Ability_Ambush\n"), "{saved}" ); - let again = MacroState::from_scopes(Vec::new(), parse(&saved)); + let again = MacroState::from_scopes(Vec::new(), parse(&saved, true)); assert_eq!(again, state, "the full id loads as itself"); } } diff --git a/crates/benilla-app/src/ui_macro/tests.rs b/crates/benilla-app/src/ui_macro/tests.rs index 55446c5fa..4b6b0d78e 100644 --- a/crates/benilla-app/src/ui_macro/tests.rs +++ b/crates/benilla-app/src/ui_macro/tests.rs @@ -28,9 +28,10 @@ fn a_saved_macro_table_round_trips_through_benilla_macros() { let account = crate::local_state::macros_account_path().unwrap(); let character = crate::local_state::macros_character_path("Test Realm", "Probeone").unwrap(); + // Bodies as the reader builds them, each line followed by a newline (`0x4f0a2b`). let state = MacroState::from_scopes( - vec![macro_view("Ambush", "/cast Ambush\n/say pew")], - vec![macro_view("Charge", "/cast Charge")], + vec![macro_view("Ambush", "/cast Ambush\n/say pew\n")], + vec![macro_view("Charge", "/cast Charge\n")], ); crate::local_state::write_atomic( &account, @@ -55,8 +56,8 @@ fn a_saved_macro_table_round_trips_through_benilla_macros() { ); let back = MacroState::from_scopes( - super::store::parse(&std::fs::read_to_string(&account).unwrap()), - super::store::parse(&std::fs::read_to_string(&character).unwrap()), + super::store::parse(&std::fs::read_to_string(&account).unwrap(), false), + super::store::parse(&std::fs::read_to_string(&character).unwrap(), true), ); assert_eq!(back, state); std::fs::remove_dir_all(&tmp).ok(); @@ -322,16 +323,14 @@ fn the_entry_vms_icon_chooser_is_listed_on_first_use() { .starts_with("Interface\\Icons\\")); } -/// A mini app around [`super::rebind_macro_spells`]: the VM, an empty bar and the `/cast` alias. +/// A mini app around [`super::rebind_macro_spells`]: the VM with the shipped `/cast` alias, which +/// the derivation reads from the globals (`0x703bf0`), and an empty bar. fn rebind_app(script: UiScript) -> bevy::prelude::App { use bevy::prelude::*; + script.run(r#"SLASH_CAST1 = "/cast""#).unwrap(); let mut app = App::new(); app.init_resource::() .init_resource::() - .insert_resource(crate::ui_chat::commands::SlashCommands::build( - |name| (name == "SLASH_CAST1").then(|| "/cast".to_string()), - |_| None, - )) .insert_non_send_resource(script) .add_systems(Update, super::rebind_macro_spells); app @@ -510,7 +509,7 @@ fn a_save_writes_the_sorted_table_and_a_load_sorts_it_again() { text.starts_with("MACRO 2 \"B\""), "the table's order: {text}" ); - let loaded = MacroState::from_scopes(super::store::parse(&text), Vec::new()); + let loaded = MacroState::from_scopes(super::store::parse(&text, false), Vec::new()); assert_eq!(loaded.get(1).unwrap().name, "b"); std::fs::remove_dir_all(&tmp).ok(); } @@ -647,3 +646,290 @@ fn a_position_numbered_character_bar_moves_to_macro_ids_once() { ); std::fs::remove_dir_all(&tmp).ok(); } + +/// The bound spell of macro `id` in a [`rebind_app`]. +fn bound_of(app: &bevy::prelude::App, id: u32) -> super::run::BoundSpell { + app.world().resource::().0[&id].spell +} + +fn learn(app: &mut bevy::prelude::App, slots: Vec) { + let ids: Vec = slots.iter().map(|s| s.spell_id).collect(); + app.world_mut() + .non_send_resource_mut::() + .set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots, + }); + let mut actions = app + .world_mut() + .resource_mut::(); + actions.spells.extend(ids); + actions.dirty = true; +} + +/// `0x4efe00` has four callers (`0x4f0cbd`, `0x4f0d11`, `0x4f123c`, `0x4f1313`): a learned spell +/// derives nothing, and a create or an edit derives the one record it touches. So a `/cast` of a +/// spell not yet known stays -1 until that macro is edited, whatever else changes. +#[test] +fn only_a_create_or_an_edit_of_that_macro_derives_its_spell_again() { + use super::run::BoundSpell; + let mut script = UiScript::new().unwrap(); + script.set_macros(MacroState::from_scopes( + vec![ + macro_view("Pyro", "/cast Pyroblast"), + macro_view("Say", "/say hi"), + ], + Vec::new(), + )); + let mut app = rebind_app(script); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Unresolved, "not yet known"); + + learn(&mut app, vec![book_slot(11366, "Pyroblast")]); + app.update(); + assert_eq!( + bound_of(&app, 1), + BoundSpell::Unresolved, + "a learned spell derives nothing" + ); + + app.world_mut() + .non_send_resource::() + .run("EditMacro(GetMacroIndexByName('Say'), nil, nil, '/say yo')") + .unwrap(); + app.update(); + assert_eq!( + bound_of(&app, 1), + BoundSpell::Unresolved, + "an edit of another macro derives only that one" + ); + + app.world_mut() + .non_send_resource::() + .run(r#"CreateMacro("Again", 1, "/cast Pyroblast")"#) + .unwrap(); + app.update(); + assert_eq!( + (bound_of(&app, 1), bound_of(&app, 3)), + (BoundSpell::Unresolved, BoundSpell::Spell(11366)), + "a create derives the new record alone" + ); + + app.world_mut() + .non_send_resource::() + .run("EditMacro(GetMacroIndexByName('Pyro'), 'Pyro')") + .unwrap(); + app.update(); + assert_eq!( + bound_of(&app, 1), + BoundSpell::Spell(11366), + "its own edit does" + ); +} + +/// The active player's arrival learns the initial spells, then derives every record (`0x5deacc` +/// into `0x4f0ca0`). +#[test] +fn the_players_arrival_derives_every_macro() { + use super::run::BoundSpell; + let mut script = UiScript::new().unwrap(); + script.set_macros(MacroState::from_scopes( + vec![macro_view("Pyro", "/cast Pyroblast")], + Vec::new(), + )); + let mut app = rebind_app(script); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Unresolved); + // The book the arrival's learns built, with no bar or macro change beside it. + app.world_mut() + .non_send_resource_mut::() + .set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots: vec![book_slot(11366, "Pyroblast")], + }); + app.update(); + assert_eq!( + bound_of(&app, 1), + BoundSpell::Unresolved, + "a book alone derives nothing" + ); + app.world_mut().spawn(crate::net::SelfPlayer); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Spell(11366)); +} + +/// `SMSG_SUPERCEDED_SPELL` (`0x5e6356` into `0x4e5e60`) walks the 120 slots: a macro slot whose +/// spell (`0x4e5a50`) is the old rank gets the new one in its record's cached spell (`0x4e5ec4`), +/// derived from nothing. A macro on no slot keeps the old rank. +#[test] +fn a_superseded_rank_rewrites_the_cached_spell_of_a_macro_on_the_bar() { + use super::run::BoundSpell; + use benilla_protocol::messages::{ActionButton, ACTION_KIND_MACRO}; + let mut script = UiScript::new().unwrap(); + script.set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots: vec![book_slot(116, "Frostbolt")], + }); + script.set_macros(MacroState::from_scopes( + vec![ + macro_view("Bar", "/cast Frostbolt"), + macro_view("Off", "/cast Frostbolt"), + ], + Vec::new(), + )); + let mut app = rebind_app(script); + app.world_mut() + .resource_mut::() + .buttons + .insert( + 4, + ActionButton { + slot: 4, + action: 1, + kind: ACTION_KIND_MACRO, + }, + ); + app.update(); + assert_eq!( + (bound_of(&app, 1), bound_of(&app, 2)), + (BoundSpell::Spell(116), BoundSpell::Spell(116)) + ); + + learn(&mut app, vec![book_slot(205, "Frostbolt")]); + app.world_mut() + .resource_mut::() + .superseded + .push((116, 205)); + app.update(); + assert_eq!( + (bound_of(&app, 1), bound_of(&app, 2)), + (BoundSpell::Spell(205), BoundSpell::Spell(116)) + ); +} + +/// A supersede waits for the VM: the pairs are applied by the first pass that runs, not dropped by +/// the passes that cannot. +#[test] +fn a_supersede_with_no_vm_yet_is_kept_for_the_first_pass() { + use super::run::BoundSpell; + use benilla_protocol::messages::{ActionButton, ACTION_KIND_MACRO}; + let mut script = UiScript::new().unwrap(); + script.set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots: vec![book_slot(116, "Frostbolt")], + }); + script.set_macros(MacroState::from_scopes( + vec![macro_view("Bar", "/cast Frostbolt")], + Vec::new(), + )); + let mut app = rebind_app(script); + app.world_mut() + .resource_mut::() + .buttons + .insert( + 4, + ActionButton { + slot: 4, + action: 1, + kind: ACTION_KIND_MACRO, + }, + ); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Spell(116)); + + let script = app + .world_mut() + .remove_non_send_resource::() + .unwrap(); + app.world_mut() + .resource_mut::() + .superseded + .push((116, 205)); + app.update(); + app.world_mut().insert_non_send_resource(script); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Spell(205)); +} + +/// `EditMacroRecord` derives the record inside the call (`0x4f1313`), against the book as it +/// stands then: a `/cast Frostbolt(Rank 1)` edited while rank 1 is known binds it, and a +/// supersede arriving after the call moves it to rank 2 (`0x4e5ec4`). Derived a frame late, +/// against the book the supersede left, it would find no rank 1. +#[test] +fn an_edit_derives_against_the_book_at_its_call() { + use super::run::BoundSpell; + use benilla_protocol::messages::{ActionButton, ACTION_KIND_MACRO}; + let ranked = |id: u32, rank: &str| benilla_ui::script::SpellSlotView { + rank: Some(rank.into()), + ..book_slot(id, "Frostbolt") + }; + let mut script = UiScript::new().unwrap(); + script.set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots: vec![ranked(116, "Rank 1")], + }); + script.set_macros(MacroState::from_scopes( + vec![macro_view("Bar", "/say hi")], + Vec::new(), + )); + let mut app = rebind_app(script); + app.world_mut() + .resource_mut::() + .buttons + .insert( + 4, + ActionButton { + slot: 4, + action: 1, + kind: ACTION_KIND_MACRO, + }, + ); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::None); + + app.world_mut() + .non_send_resource::() + .run("EditMacro(1, nil, nil, '/cast Frostbolt(Rank 1)')") + .unwrap(); + // The next packet: rank 2 supersedes rank 1. + app.world_mut() + .non_send_resource_mut::() + .set_spellbook(benilla_ui::script::SpellBookState { + tabs: Vec::new(), + slots: vec![ranked(205, "Rank 2")], + }); + app.world_mut() + .resource_mut::() + .superseded + .push((116, 205)); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Spell(205)); +} + +/// A load and our player's arrival in one pass derive every record once: the next pass, with +/// neither, derives nothing, so a spell learned after them leaves a `/cast` at -1. +#[test] +fn a_load_and_an_arrival_in_one_pass_derive_once() { + use super::run::BoundSpell; + let mut script = UiScript::new().unwrap(); + script.set_macros(MacroState::from_scopes( + vec![macro_view("Pyro", "/cast Pyroblast")], + Vec::new(), + )); + let mut app = rebind_app(script); + app.world_mut().spawn(crate::net::SelfPlayer); + app.update(); + assert_eq!(bound_of(&app, 1), BoundSpell::Unresolved); + learn(&mut app, vec![book_slot(11366, "Pyroblast")]); + // A change that runs the pass: the macro table's generation moves with no derive owed. + app.world_mut() + .non_send_resource::() + .run("CreateMacro('Other', 1, '/say hi')") + .unwrap(); + app.update(); + assert_eq!( + bound_of(&app, 1), + BoundSpell::Unresolved, + "the load's flag was taken with the arrival's" + ); +} diff --git a/crates/benilla-app/src/ui_spellbook.rs b/crates/benilla-app/src/ui_spellbook.rs index e7aa392e2..50d74d6c5 100644 --- a/crates/benilla-app/src/ui_spellbook.rs +++ b/crates/benilla-app/src/ui_spellbook.rs @@ -47,6 +47,10 @@ const GENERAL_TAB_ICON: &str = "Interface\\Icons\\Ability_Kick"; #[derive(Resource, Default)] pub(crate) struct LearnedInTab(pub(crate) Vec); +/// The book's feed, which the macros' bound spells read after ([`crate::ui_macro`]). +#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct BookFeed; + pub(crate) struct UiSpellbookPlugin; impl Plugin for UiSpellbookPlugin { @@ -59,6 +63,7 @@ impl Plugin for UiSpellbookPlugin { // re-read its cooldowns. A click's cast is a script call (`cast_spell`). feed_spellbook .in_set(UnitFeed) + .in_set(BookFeed) .before(crate::ui_action::CooldownEvents) .before(crate::ui_cast::feed_cast_reports), ); diff --git a/crates/benilla-ui/src/script/action.rs b/crates/benilla-ui/src/script/action.rs index 864c5be83..dcca3cb10 100644 --- a/crates/benilla-ui/src/script/action.rs +++ b/crates/benilla-ui/src/script/action.rs @@ -17,6 +17,10 @@ pub(crate) const ACTION_KIND_SPELL: u8 = 0x00; pub(crate) const ACTION_KIND_MACRO: u8 = 0x40; pub(crate) const ACTION_KIND_ITEM: u8 = 0x80; +/// The icon directory a macro's basename is formatted after (`0x84c988`, the string at +/// `0x84ca64`). +const MACRO_ICON_DIR: &str = "Interface\\Icons\\"; + /// The macro id a slot word holds, if it is a macro's: the word with bit 30 cleared when its top /// nibble is 4 (`0x4e5030`, `0x4e5ba0`, `0x4e7086`; `0x4e7090 and ecx,0xbfffffff`). A character /// macro's id has bit 24 set, so its slot's kind byte is 0x41 (vmangos `ACTION_BUTTON_CMACRO`). @@ -361,9 +365,23 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { lua.create_function(|lua, action: Value| { // `is-number` else `Usage: GetActionTexture(slot)` (`0x84bf78`, `0x4e6e5a`). let action = binding_abi::index_arg32(lua, action, "Usage: GetActionTexture(slot)")?; + // A macro slot reads its macro's icon live (`0x4e6bf9` into `0x4f0fd0`), so a handler + // of the edit's own slot signal sees the new one. The arm formats the icon directory + // and the basename (`0x4f0ffa`) and the binding pushes the buffer (`0x4e6e42`), so a + // macro with no icon gives the directory alone. let tex = { let model = lua.app_data_ref::().expect("model app_data"); - model.actions.get(&action).and_then(|s| s.texture.clone()) + model + .actions + .get(&action) + .and_then(|s| match macro_slot_id(s.kind, s.action) { + Some(id) => model.macros.by_id(id).map(|m| { + m.texture + .clone() + .unwrap_or_else(|| MACRO_ICON_DIR.to_string()) + }), + None => s.texture.clone(), + }) }; match tex { Some(t) => Ok(Value::String(lua.create_string(&t)?)), diff --git a/crates/benilla-ui/src/script/macros.rs b/crates/benilla-ui/src/script/macros.rs index 2a3a01b73..f2bb31669 100644 --- a/crates/benilla-ui/src/script/macros.rs +++ b/crates/benilla-ui/src/script/macros.rs @@ -9,12 +9,15 @@ //! ([`crate::crt`]) and rebuilt after every create, edit and delete (`0x4f0d30`), so the first //! character macro is index 19 however few account macros there are. An action slot holds the id //! (`macroId | 0x40000000`, `0x4e62e0`), never the position. A macro's bound spell -//! (`0x4e5a50`'s macro arm returns `[rec+0x564]`) is the app's to derive: it needs the spell catalog -//! and the player's book. +//! (`0x4e5a50`'s macro arm returns `[rec+0x564]`) is derived here from the pushed books +//! ([`bind`]): inside a create or an edit, and when the app's pass asks. +mod bind; #[cfg(test)] mod lua_tests; +pub use bind::macro_lines; + use mlua::{Lua, MultiValue, Value}; use super::binding_abi; @@ -54,7 +57,8 @@ pub struct MacroView { /// The icon's texture path, kept by name because the reference saves the icon by name /// (`MACRO %d "%s" %s`, `0x84cb60`). pub texture: Option, - /// The macro's lines, `\n`-separated. + /// The macro's text: as a verb gave it, or as the file reader builds it, each line followed + /// by `\n` (`0x4f0a2b`). pub body: String, /// `isLocal` and the `local` argument, carried but not saved here. The 1.12 client saves these /// to `macros-local.txt` beside `macros-cache.txt` (`0x45de74`, `0x45de88`); the stock UI never @@ -63,7 +67,8 @@ pub struct MacroView { } /// A macro record's cached cast, the reference's `([rec+0x564], [rec+0x568])` pair (`0x4efe00`): -/// the bound spell and the book it resolved from, which the app derives. +/// the bound spell and the book it resolved from. A create or an edit derives it inside its call +/// (`0x4f123c`, `0x4f1313`); the app's pass derives the rest ([`UiScript::derive_macro_bindings`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct MacroBinding { /// The bound spell id; 0 for none, -1 for a `/cast` that did not resolve. @@ -72,6 +77,24 @@ pub struct MacroBinding { pub pet_book: bool, } +impl MacroBinding { + /// Whether `0x4f0ce0` derives this record again when the pet's spell list arrives + /// (`0x4f0cfb`-`0x4f0d11`): a `/cast` that did not resolve (`[rec+0x564] < 0`), or any record + /// whose book selector is the pet's (`[rec+0x568] != 0`), whatever it is bound to now. Any + /// other record keeps its cast. + pub fn follows_the_pet_book(self) -> bool { + self.spell < 0 || self.pet_book + } +} + +/// The derivations a load owes: the load derives every record (`0x4f0a55` into `0x4f0ca0`), each +/// new with its selector clear (`0x4f1ca0`). The app makes them once the VM holds the book. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MacroDerives { + /// The table was loaded since the last take. + pub loaded: bool, +} + /// A record and the scope it belongs to (`rec+0x1c`). #[derive(Clone, Debug, PartialEq)] struct Record { @@ -128,9 +151,10 @@ fn cut_body(body: &str) -> String { impl MacroState { /// The table the file reader builds (`0x4f0600`), the account scope read first: per scope, in /// order, a record past the 18th is skipped (`0x4f06ee`); an id below the scope's base gets the - /// base added (`0x4f0737`); the largest id seen becomes the scope's last (`0x4f0744`); an id - /// that exists is skipped (`0x4f0789`); the local flag is cleared (`0x4f095c`). A view with no - /// id, the seed form, takes the scope's next. The name and body keep their verbs' caps. + /// base added (`0x4f0737`); the largest id seen becomes the scope's last (`0x4f0744`), both + /// compares signed; an id that exists is skipped (`0x4f0789`), then a read record with an + /// empty name (`0x4f07c8`); the local flag is cleared (`0x4f095c`). A view with no id, the seed + /// form, takes the scope's next. The name and body keep their verbs' caps. pub fn from_scopes(account: Vec, character: Vec) -> Self { let mut state = Self::default(); for (per_character, views) in [(false, account), (true, character)] { @@ -139,13 +163,16 @@ impl MacroState { if state.count(per_character) >= MAX_MACROS { break; } - if view.id == 0 { + let seed = view.id == 0; + if seed { view.id = state.last_id[scope] + 1; - } else if view.id < SCOPE_BASE[scope] { - view.id += SCOPE_BASE[scope]; + } else if (view.id as i32) < SCOPE_BASE[scope] as i32 { + view.id = view.id.wrapping_add(SCOPE_BASE[scope]); } - state.last_id[scope] = state.last_id[scope].max(view.id); - if state.by_id(view.id).is_some() { + if view.id as i32 > state.last_id[scope] as i32 { + state.last_id[scope] = view.id; + } + if state.by_id(view.id).is_some() || (!seed && view.name.is_empty()) { continue; } view.name = cut_name(&view.name); @@ -271,6 +298,13 @@ impl super::UiScript { model.macros = state; model.macros_dirty = false; model.macros_generation += 1; + model.macro_derives = MacroDerives { loaded: true }; + model.macro_bindings.clear(); + } + + /// Take the derivations owed since the last take ([`MacroDerives`]). + pub fn take_macro_derives(&mut self) -> MacroDerives { + std::mem::take(&mut self.model_mut().macro_derives) } /// The live table, for the app's save. @@ -283,8 +317,36 @@ impl super::UiScript { self.model_mut().macro_bindings = bindings; } - /// Whether a script changed the table since the last call; the app then saves it and fires - /// `UPDATE_MACROS` (`0x452460`). + /// Each macro's cached cast by id; a record with none is bound to nothing. + pub fn macro_bindings(&self) -> std::collections::HashMap { + self.model_ref().macro_bindings.clone() + } + + /// Derive again (`0x4efe00`) each record `pick` names by its id and its cast now, against the + /// books and the `/cast` aliases as they stand: the load's and the arrival's every record + /// (`0x4f0ca0`), the pet message's followers (`0x4f0ce0`). + pub fn derive_macro_bindings(&mut self, pick: impl Fn(u32, MacroBinding) -> bool) { + let aliases = bind::cast_aliases(self.lua()); + let mut model = self.model_mut(); + let model = &mut *model; + for record in &model.macros.list { + let id = record.view.id; + let was = model.macro_bindings.get(&id).copied().unwrap_or_default(); + if pick(id, was) { + let next = bind::derive( + &aliases, + &record.view.body, + &model.spellbook, + &model.pet_book, + was, + ); + model.macro_bindings.insert(id, next); + } + } + } + + /// Whether a script changed the table since the last call; the app then saves it. The verbs + /// signal `UPDATE_MACROS` (`0x852460`) themselves, from the order's rebuild (`0x4f0d30`). pub fn take_macros_dirty(&mut self) -> bool { std::mem::take(&mut self.model_mut().macros_dirty) } @@ -329,8 +391,8 @@ fn create_macro( name: &str, texture: Option, body: &str, - local_only: bool, - per_character: bool, + (local_only, per_character): (bool, bool), + aliases: &[String], ) -> mlua::Result { let state = &mut model.macros; if state.count(per_character) >= MAX_MACROS { @@ -351,8 +413,19 @@ fn create_macro( local_only, }, }); + // The new record's cast, its selector clear (`0x4f1ca0`), derived in the call (`0x4f123c`). + let binding = bind::derive( + aliases, + &cut_body(body), + &model.spellbook, + &model.pet_book, + MacroBinding::default(), + ); + model.macro_bindings.insert(id, binding); model.macros_dirty = true; model.macros_generation += 1; + // The order's rebuild (`0x4f125c` into `0x4f0d30`), which signals no slot. + model.raise("UPDATE_MACROS", vec![]); Ok(model.macros.index_of_id(id).unwrap_or(0)) } @@ -366,10 +439,9 @@ fn create_macro( fn edit_macro( model: &mut Model, index: usize, - name: Option, - texture: Option, - body: Option, + (name, texture, body): (Option, Option, Option), local_only: bool, + aliases: &[String], ) -> usize { let id = model.macros.id_at(index); if let Some(record) = model @@ -389,9 +461,29 @@ fn edit_macro( view.body = cut_body(&body); } view.local_only = local_only; + // The record's cast derived again in the call (`0x4f1313`), against the book as it is. + let was = model.macro_bindings.get(&id).copied().unwrap_or_default(); + let binding = bind::derive(aliases, &view.body, &model.spellbook, &model.pet_book, was); + model.macro_bindings.insert(id, binding); model.macros_dirty = true; model.macros_generation += 1; model.macro_edits += 1; + // The order's rebuild (`0x4f1322` into `0x4f0d30`), then each slot that holds the id, + // lowest first, signalled and sent nothing (`0x4f1329` into `0x4e5cc0`, `0x4e58e0`). + model.raise("UPDATE_MACROS", vec![]); + let mut held: Vec = model + .actions + .iter() + .filter(|(_, slot)| super::action::macro_slot_id(slot.kind, slot.action) == Some(id)) + .map(|(&slot, _)| slot) + .collect(); + held.sort_unstable(); + for slot in held { + model.raise( + "ACTIONBAR_SLOT_CHANGED", + vec![crate::script::ScriptValue::Int(i64::from(slot))], + ); + } } model.macros.index_of_id(id).unwrap_or(0) } @@ -410,9 +502,12 @@ fn delete_macro(model: &mut Model, index: usize) -> bool { return false; }; model.macros.list.remove(at); + model.macro_bindings.remove(&id); super::cursor::clear_macro_slots(model, id); model.macros_dirty = true; model.macros_generation += 1; + // The order's rebuild, after the slots (`0x4f1451` into `0x4f0d30`). + model.raise("UPDATE_MACROS", vec![]); true } @@ -575,16 +670,18 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { )); } ensure_macro_icons(lua); - let mut model = lua.app_data_mut::().expect("model app_data"); - // `0x4f1632`, `0x4f163c`. - let texture = icon_at(&model, icon); let body = a .get(2) .and_then(|v| super::binding_abi::optional_string(lua, v)) .unwrap_or_default(); - let (local_only, per_character) = (flag(a.get(3)), flag(a.get(4))); - create_macro(&mut model, &name, texture, &body, local_only, per_character) - .map(|i| Value::Integer(i as i64)) + let flags = (flag(a.get(3)), flag(a.get(4))); + let aliases = bind::cast_aliases(lua); + super::tick::verb(lua, |model| { + // `0x4f1632`, `0x4f163c`. + let texture = icon_at(model, icon); + create_macro(model, &name, texture, &body, flags, &aliases) + }) + .map(|i| Value::Integer(i as i64)) })?, )?; @@ -616,13 +713,16 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { if names_macro && icon.is_some() { ensure_macro_icons(lua); } - let mut model = lua.app_data_mut::().expect("model app_data"); - // `0x4f1966`-`0x4f1983`: a miss leaves the pointer null, and the macro its old icon. - let texture = icon.and_then(|n| icon_at(&model, n)); let name = a.get(1).and_then(|v| binding_abi::optional_string(lua, v)); let body = a.get(3).and_then(|v| binding_abi::optional_string(lua, v)); let local_only = flag(a.get(4)); - let at = edit_macro(&mut model, index, name, texture, body, local_only); + let aliases = bind::cast_aliases(lua); + let at = super::tick::verb(lua, |model| { + // `0x4f1966`-`0x4f1983`: a miss leaves the pointer null, and the macro its old + // icon. + let texture = icon.and_then(|n| icon_at(model, n)); + edit_macro(model, index, (name, texture, body), local_only, &aliases) + }); Ok(Value::Integer(at as i64)) })?, )?; @@ -662,6 +762,39 @@ mod tests { use super::*; use crate::script::UiScript; + /// The reader counts a header's id into the scope's last before it reads the name, and skips + /// a record with an empty one only then (`0x4f0744`, `0x4f07c8`): the next create takes the id + /// after it. + #[test] + fn an_unnamed_record_is_skipped_after_its_id_counts() { + let state = MacroState::from_scopes( + vec![MacroView { + id: 5, + ..Default::default() + }], + Vec::new(), + ); + assert_eq!(state.count(false), 0); + assert_eq!(state.last_id[0], 5); + } + + /// `GetActionTexture`'s macro arm formats `"%s%s"` of the icon directory and the record's + /// basename (`0x4f0fd0`, `0x4f0ffa`) and the binding pushes the buffer (`0x4e6e42`), so a macro + /// with no icon gives the directory alone, where `GetMacroInfo` gives nil. + #[test] + fn a_macro_with_no_icon_shows_the_icon_directory_on_the_bar() { + let s = seeded(); + s.run(r#"CreateMacro("bare", 99, "") PickupMacro(1) PlaceAction(5)"#) + .unwrap(); + assert_eq!( + s.eval::<(Option, Option)>( + "local _, t = GetMacroInfo(1) return t, GetActionTexture(5)" + ) + .unwrap(), + (None, Some("Interface\\Icons\\".into())) + ); + } + fn seeded() -> UiScript { let mut s = UiScript::new().unwrap(); s.set_macro_icons(vec![ diff --git a/crates/benilla-ui/src/script/macros/bind.rs b/crates/benilla-ui/src/script/macros/bind.rs new file mode 100644 index 000000000..4861adbca --- /dev/null +++ b/crates/benilla-ui/src/script/macros/bind.rs @@ -0,0 +1,397 @@ +//! A macro body's runnable lines, and the spell it binds for the action bar. +//! +//! A macro slot shows the macro's icon but the cooldown, usability, range and checked state of its +//! bound spell, the record's `[rec+0x564]`, which the slot resolver `0x4e5a50` returns for a +//! macro. `0x4efe00` derives it from the first line that is a `/cast` alias or holds +//! `CastSpellByName(`, through the resolver the `CastSpellByName` binding (`0x4b4ab0`) uses +//! (`0x4b3950` → `0x4b3a10`), so a bare name binds the highest known rank. +//! +//! `[rec+0x568]` is the book the spell resolved from, 0 the player's and 1 the pet's: the name is +//! looked up in the player's book, then the pet's (`0x4b3a10`), and a pet match binds the pet's +//! spell, which the action bar then reads through the pet's legs. + +use super::MacroBinding; +use crate::script::{resolve_spell_in_books, PetBookState, SpellBookState}; + +/// Arm B's literal (`0x84cab0`), searched case-sensitively anywhere in the line (`0x4efed5`). +const CAST_BY_NAME_CALL: &str = "CastSpellByName("; + +/// Which of `0x4efe00`'s arms matched: an unresolved name stores -1 from arm A (`0x4eff48`) and +/// 0 from arm B (`0x4eff81`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CastArm { + /// A `/cast`-alias line (`SLASH_CAST%d`, read as Lua globals at `0x703bf0`). + Slash, + /// A `CastSpellByName("…")` call anywhere in the line. + ByName, +} + +/// A macro body's runnable lines: the reference's tokenizer (`0x64ae50`) splits on either `\r` or +/// `\n` and skips empty tokens. Deviation: each line is trimmed, because the reference sends an +/// indented `" /say hi"` as plain chat, never as the command meant. A whitespace-only line is fired +/// there and dropped by `ChatEdit_SendText`, the same observable. +pub fn macro_lines(body: &str) -> impl Iterator { + body.split(['\r', '\n']) + .map(str::trim) + .filter(|l| !l.is_empty()) +} + +/// The `/cast` aliases as `0x4efe00` reads them, each time it derives: the globals `SLASH_CAST1`, +/// `SLASH_CAST2`, … through `FrameScript_GetText` (`0x703bf0`), to the first that is absent or +/// empty. +pub(crate) fn cast_aliases(lua: &mlua::Lua) -> Vec { + (1..) + .map_while(|n| crate::strings::global(lua, &format!("SLASH_CAST{n}"))) + .collect() +} + +/// The spell name a macro body casts (`0x4efe00`): the first `/cast`-alias line, or line holding +/// `CastSpellByName(` and then a quote, whose text is the name even when it is empty +/// ([`quoted_call_argument`]). Deviation: the `/cast` argument is trimmed, because the reference +/// binds `/cast Fireball` (two spaces) to a name that never resolves. +pub(crate) fn cast_name(aliases: &[String], body: &str) -> Option<(CastArm, String)> { + for line in macro_lines(body) { + // Arm A: an alias compared without case over its length (`SStrCmpI`, `0x64a4c0`), and the + // next byte must be a space (`0x4efe96`), so a tab or a bare `/cast` misses. + let after_alias = aliases.iter().find_map(|alias| { + let head = line.get(..alias.len())?; + let rest = line.get(alias.len()..)?; + (head.eq_ignore_ascii_case(alias)) + .then_some(rest) + .and_then(|rest| rest.strip_prefix(' ')) + }); + if let Some(args) = after_alias { + let args = args.trim(); + if !args.is_empty() { + return Some((CastArm::Slash, args.to_string())); + } + // The reference stores any alias hit's result and returns, -1 for a name that resolves + // nothing (`0x4eff28`-`0x4eff48`); under the trim above, an argument of spaces alone + // goes on to the next line instead. + continue; + } + // Arm B, second, on the same line (`0x4efed5`): its quote decides the binding, so the walk + // ends here whatever the name is or resolves to. + if let Some(name) = quoted_call_argument(line) { + return Some((CastArm::ByName, name)); + } + } + None +} + +/// The text of the first quote after `CastSpellByName(` on the line: from the first `"` at or +/// after the match (`0x4efef0`-`0x4efefb`, the literal holds none) to the next `"` or the line's +/// end (`0x4eff58`-`0x4eff6d`). Whatever stands between the parenthesis and the quote is skipped, +/// so `CastSpellByName(IsShiftKeyDown() and "Frostbolt(Rank 1)" or "Frostbolt")` gives +/// `Frostbolt(Rank 1)`. A line with no such quote gives nothing and the walk goes on (`0x4efefd`); +/// an empty name is a name, which `0x4b3bc0` answers 0. +fn quoted_call_argument(line: &str) -> Option { + let after_call = &line[line.find(CAST_BY_NAME_CALL)?..]; + let open = after_call.find('"')?; + let rest = &after_call[open + 1..]; + Some(rest.split('"').next().unwrap_or_default().to_string()) +} + +/// The macro's cast, derived again (`0x4efe00`) from `was`: [`cast_name`] resolved as +/// `CastSpellByName` resolves a name ([`resolve_spell_in_books`]), so the cooldown swirl and the +/// press agree on the rank. A match writes the book it came from; a miss leaves the selector. +pub(crate) fn derive( + aliases: &[String], + body: &str, + player: &SpellBookState, + pet: &PetBookState, + was: MacroBinding, +) -> MacroBinding { + let Some((arm, name)) = cast_name(aliases, body) else { + return MacroBinding { spell: 0, ..was }; + }; + match (resolve_spell_in_books(player, pet, &name), arm) { + (Some(s), _) => MacroBinding { + spell: s.spell_id as i32, + pet_book: s.pet, + }, + (None, CastArm::Slash) => MacroBinding { spell: -1, ..was }, + (None, CastArm::ByName) => MacroBinding { spell: 0, ..was }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::script::SpellSlotView; + + /// The aliases these tests need: the shipped `SLASH_CAST1` and `SLASH_CAST2`. + fn aliases() -> Vec { + vec!["/cast".into(), "/spell".into()] + } + + #[test] + fn macro_lines_trims_blanks_and_windows_line_endings() { + let body = "/cast Fireball\r\n\r\n /say pew \n"; + let lines: Vec<&str> = macro_lines(body).collect(); + assert_eq!(lines, ["/cast Fireball", "/say pew"]); + } + + /// The aliases are the globals as they stand, to the first absent one. + #[test] + fn the_aliases_are_read_from_the_globals_to_the_first_gap() { + let s = crate::script::UiScript::new().unwrap(); + s.run(r#"SLASH_CAST1 = "/cast" SLASH_CAST2 = "/spell" SLASH_CAST4 = "/x""#) + .unwrap(); + assert_eq!(cast_aliases(s.lua()), aliases()); + } + + /// `/spell` is `SLASH_CAST2` in the shipped strings. + #[test] + fn cast_name_reads_the_first_cast_line_through_the_aliases() { + let t = aliases(); + assert_eq!( + cast_name(&t, "/target Bob\n/cast Fireball\n/say pew"), + Some((CastArm::Slash, "Fireball".into())) + ); + assert_eq!( + cast_name(&t, "/spell Frostbolt"), + Some((CastArm::Slash, "Frostbolt".into())) + ); + // The whole argument, rank included; `resolve_spell_by_name` parses it. + assert_eq!( + cast_name(&t, "/cast Fireball(Rank 1)"), + Some((CastArm::Slash, "Fireball(Rank 1)".into())) + ); + // First match wins. + assert_eq!( + cast_name(&t, "/cast Fireball\n/cast Frostbolt"), + Some((CastArm::Slash, "Fireball".into())) + ); + // A bare `/cast` binds nothing and does not stop the walk. + assert_eq!( + cast_name(&t, "/cast\n/cast Frostbolt"), + Some((CastArm::Slash, "Frostbolt".into())) + ); + assert_eq!(cast_name(&t, "/say hello\n/target Bob"), None); + } + + #[test] + fn the_alias_separator_is_a_literal_space_and_the_alias_folds_case() { + let t = aliases(); + let fireball = Some((CastArm::Slash, "Fireball".into())); + assert_eq!(cast_name(&t, "/CAST Fireball"), fireball); + assert_eq!(cast_name(&t, "/Cast Fireball"), fireball); + // A tab does not separate, so the walk goes on. + assert_eq!( + cast_name(&t, "/cast\tFireball\n/cast Frostbolt"), + Some((CastArm::Slash, "Frostbolt".into())) + ); + // Arm B is case-sensitive. + assert_eq!( + cast_name(&t, r#"/script castspellbyname("Fireball")"#), + None + ); + } + + #[test] + fn cast_name_reads_a_quoted_cast_spell_by_name_call() { + let t = aliases(); + assert_eq!( + cast_name(&t, r#"/script CastSpellByName("Shadow Bolt")"#), + Some((CastArm::ByName, "Shadow Bolt".into())) + ); + // Spacing and a second argument don't matter; the first quoted argument is the name. + assert_eq!( + cast_name(&t, r#"/script CastSpellByName( "Healing Touch", 1 )"#), + Some((CastArm::ByName, "Healing Touch".into())) + ); + // A computed argument with no quote has no name to bind. + assert_eq!(cast_name(&t, "/script CastSpellByName(spell)"), None); + } + + /// `0x4efef0`-`0x4efefb` scan for the first quote anywhere after the match, whatever the + /// parenthesis holds, and `0x4eff58`-`0x4eff6d` read to the next quote or the line's end. + #[test] + fn the_first_quote_after_the_call_is_the_name_wherever_it_stands() { + let t = aliases(); + assert_eq!( + cast_name( + &t, + r#"/script CastSpellByName(IsShiftKeyDown() and "Frostbolt(Rank 1)" or "Frostbolt")"# + ), + Some((CastArm::ByName, "Frostbolt(Rank 1)".into())) + ); + assert_eq!( + cast_name(&t, r#"/script CastSpellByName(GetSpell("Fire"))"#), + Some((CastArm::ByName, "Fire".into())), + "up to the next quote, the call's own closing parenthesis not a stop" + ); + assert_eq!( + cast_name(&t, r#"/script CastSpellByName("Fire"#), + Some((CastArm::ByName, "Fire".into())), + "an unterminated name runs to the line's end" + ); + // The scan starts at the match: a quote ahead of it is not the name, and a line with none + // after it goes on to the next line (`0x4efefd`). + assert_eq!( + cast_name( + &t, + "/script local a = \"x\"; CastSpellByName(spell)\n/cast Frostbolt" + ), + Some((CastArm::Slash, "Frostbolt".into())) + ); + } + + /// The bound spell of `body` for a macro that was bound to nothing, against the player's book. + fn bound(t: &[String], body: &str, book: &SpellBookState) -> i32 { + derive( + t, + body, + book, + &PetBookState::default(), + MacroBinding::default(), + ) + .spell + } + + fn fireball_book() -> SpellBookState { + SpellBookState { + tabs: Vec::new(), + slots: vec![SpellSlotView { + spell_id: 133, + name: "Fireball".into(), + ..Default::default() + }], + } + } + + /// An empty name is a name: `0x4eff7b` resolves it to 0 and `0x4eff81` stores that, ending the + /// walk on its line, where a later `/cast` is never read. + #[test] + fn an_empty_name_binds_nothing_and_ends_the_walk() { + let t = aliases(); + let body = "/script CastSpellByName(\"\")\n/cast Fireball"; + assert_eq!(cast_name(&t, body), Some((CastArm::ByName, String::new()))); + assert_eq!(bound(&t, body, &fireball_book()), 0); + // A computed first argument binds the quoted fallback after it, not the later line. + assert_eq!( + bound( + &t, + "/script CastSpellByName(x and \"Fireball\" or \"Frostbolt\")\n/cast Frostbolt", + &fireball_book() + ), + 133 + ); + } + + #[test] + fn a_bound_spell_resolves_through_the_book() { + let book = SpellBookState { + tabs: Vec::new(), + slots: vec![ + SpellSlotView { + spell_id: 133, + name: "Fireball".into(), + rank: Some("Rank 1".into()), + ..Default::default() + }, + SpellSlotView { + spell_id: 145, + name: "Fireball".into(), + rank: Some("Rank 2".into()), + ..Default::default() + }, + ], + }; + let t = aliases(); + // No subtext -> the highest known rank. + assert_eq!(bound(&t, "/cast Fireball", &book), 145); + // A pinned subtext -> that rank. The spaced form keeps its space in the name + // (`0x4b3950` trims nothing), so it names no spell and the bar greys the slot. + assert_eq!(bound(&t, "/cast Fireball(Rank 1)", &book), 133); + assert_eq!(bound(&t, "/cast Fireball (Rank 1)", &book), -1); + } + + /// An unknown `/cast` is -1 (`0x4eff48`), which the bar greys; no cast line, or an unknown + /// `CastSpellByName(`, is 0 (`0x4eff81`). + #[test] + fn an_unresolved_cast_is_arm_dependent() { + let book = SpellBookState::default(); + let t = aliases(); + assert_eq!(bound(&t, "/cast Pyroblast", &book), -1); + assert_eq!(bound(&t, "/spell Pyroblast\n/say pew", &book), -1); + assert_eq!(bound(&t, "/say hi", &book), 0); + assert_eq!(bound(&t, ".spawn 16032", &book), 0); + assert_eq!( + bound(&t, r#"/script CastSpellByName("Pyroblast")"#, &book), + 0 + ); + } + + fn named(spell_id: u32, name: &str) -> SpellSlotView { + SpellSlotView { + spell_id, + name: name.into(), + ..Default::default() + } + } + + /// `0x4b3a10` searches the player's book, then the pet's, and `0x4b3b51` writes which one + /// matched; `0x4efe00` hands that book to the record (`0x4eff2b`, `0x4eff72`). + #[test] + fn a_name_only_the_pets_book_holds_binds_its_spell_with_the_pets_book() { + let t = aliases(); + let player = SpellBookState { + tabs: Vec::new(), + slots: vec![named(133, "Fireball"), named(1, "Seduction")], + }; + let pet = PetBookState { + token: None, + slots: vec![named(6358, "Seduction"), named(19647, "Spell Lock")], + }; + let at = |spell, pet_book| MacroBinding { spell, pet_book }; + let derived = |body: &str| derive(&t, body, &player, &pet, MacroBinding::default()); + assert_eq!(derived("/cast Spell Lock"), at(19647, true)); + assert_eq!( + derived(r#"/script CastSpellByName("Spell Lock")"#), + at(19647, true), + "the quoted form binds it too" + ); + // The player's book is searched first. + assert_eq!(derived("/cast Seduction"), at(1, false)); + assert_eq!(derived("/cast Fireball"), at(133, false)); + // A name in neither book is what it was: -1 for a `/cast`, 0 for the quoted form. + assert_eq!(derived("/cast Claw"), at(-1, false)); + assert_eq!(derived(r#"/script CastSpellByName("Claw")"#), at(0, false)); + // With the pet gone, a pet spell is a name in neither. + let gone = |was| { + derive( + &t, + "/cast Spell Lock", + &player, + &PetBookState::default(), + was, + ) + }; + assert_eq!(gone(MacroBinding::default()).spell, -1); + // A miss leaves the book selector (`0x4b3a10` writes it on a match alone), so a record + // that was the pet's stays the pet's through it, and a cast line that is gone keeps it too. + assert!(gone(at(19647, true)).pet_book); + assert!(!gone(MacroBinding::default()).pet_book); + assert_eq!( + derive(&t, "/say hi", &player, &pet, at(19647, true)), + at(0, true) + ); + } + + /// `0x4f0ce0` derives a record again at a pet spell message only when `[rec+0x564] < 0` or + /// `[rec+0x568] != 0` (`0x4f0cfb`-`0x4f0d11`), whatever it is bound to now. + #[test] + fn only_an_unresolved_or_pet_selected_record_follows_the_pets_list() { + let at = |spell, pet_book| MacroBinding { spell, pet_book }; + assert!(at(-1, false).follows_the_pet_book()); + assert!(at(6358, true).follows_the_pet_book()); + assert!( + at(0, true).follows_the_pet_book(), + "a quoted call that lost the pet's spell keeps the pet's book" + ); + assert!(!at(0, false).follows_the_pet_book()); + assert!(!at(133, false).follows_the_pet_book()); + } +} diff --git a/crates/benilla-ui/src/script/macros/lua_tests.rs b/crates/benilla-ui/src/script/macros/lua_tests.rs index 651b9dde0..be3a1ecc5 100644 --- a/crates/benilla-ui/src/script/macros/lua_tests.rs +++ b/crates/benilla-ui/src/script/macros/lua_tests.rs @@ -342,3 +342,88 @@ fn get_macro_index_by_name_takes_its_argument_as_the_reference_does() { ); } } + +/// `EditMacroRecord` (`0x4f1280`) rebuilds the order, whose tail signals `UPDATE_MACROS` +/// (`0x4f1322` into `0x4f0d30`), then signals each slot that holds the edited macro, lowest first +/// (`0x4f1329` into `0x4e5cc0`), all inside the call. A slot holding another macro hears nothing, +/// and a handler reads the macro's new icon (`GetActionTexture`'s macro arm, `0x4e6bf9`). +#[test] +fn an_edit_signals_only_the_slots_that_hold_the_macro() { + let mut s = script(); + make(&s, "b", false); + make(&s, "d", false); + s.run( + "PickupMacro(2) PlaceAction(9) PickupMacro(2) PlaceAction(5) PickupMacro(1) PlaceAction(7)", + ) + .unwrap(); + s.take_action_sets(); + heard::listen( + &s, + &["UPDATE_MACROS", "ACTIONBAR_SLOT_CHANGED"], + Some("arg1"), + ); + s.run("EditMacro(2, 'dd')").unwrap(); + assert_eq!( + heard::take(&s), + [ + "UPDATE_MACROS nil", + "ACTIONBAR_SLOT_CHANGED 5", + "ACTIONBAR_SLOT_CHANGED 9" + ] + ); + + heard::listen( + &s, + &["ACTIONBAR_SLOT_CHANGED"], + Some("arg1 .. ' ' .. tostring(GetActionTexture(arg1))"), + ); + s.run("EditMacro(GetMacroIndexByName('dd'), nil, 2)") + .unwrap(); + assert_eq!( + heard::take(&s), + [ + "ACTIONBAR_SLOT_CHANGED 5 Interface\\Icons\\Ability_BackStab", + "ACTIONBAR_SLOT_CHANGED 9 Interface\\Icons\\Ability_BackStab" + ] + ); + assert!(s.take_action_sets().is_empty(), "a notify sends nothing"); + + heard::listen(&s, &["UPDATE_MACROS", "ACTIONBAR_SLOT_CHANGED"], None); + s.run("EditMacro(30, 'none')").unwrap(); + assert!( + heard::take(&s).is_empty(), + "no record, no work (`0x4f1333`)" + ); +} + +/// `CreateMacro`'s worker (`0x4f1010`) rebuilds the order (`0x4f125c`) and signals no slot, even +/// one whose word already names the id it hands out. +#[test] +fn a_create_signals_only_the_order() { + let mut s = script(); + make(&s, "b", false); + s.set_action( + 3, + Some(crate::script::ActionSlot { + kind: 0x40, + action: 2, + ..Default::default() + }), + ); + heard::listen(&s, &["UPDATE_MACROS", "ACTIONBAR_SLOT_CHANGED"], None); + make(&s, "d", false); + assert_eq!(heard::take(&s), ["UPDATE_MACROS"]); +} + +/// `DeleteMacro`'s worker (`0x4f1340`) clears and signals the macro's slots (`0x4f1449`) before +/// it rebuilds the order (`0x4f1451`), inside the call. +#[test] +fn a_delete_signals_its_slots_then_the_order() { + let mut s = script(); + make(&s, "b", false); + s.run("PickupMacro(1) PlaceAction(4)").unwrap(); + s.take_action_sets(); + heard::listen(&s, &["UPDATE_MACROS", "ACTIONBAR_SLOT_CHANGED"], None); + s.run("DeleteMacro(1)").unwrap(); + assert_eq!(heard::take(&s), ["ACTIONBAR_SLOT_CHANGED", "UPDATE_MACROS"]); +} diff --git a/crates/benilla-ui/src/script/mod.rs b/crates/benilla-ui/src/script/mod.rs index 65a798f34..6e34a3528 100644 --- a/crates/benilla-ui/src/script/mod.rs +++ b/crates/benilla-ui/src/script/mod.rs @@ -318,8 +318,8 @@ pub use lock_check::{check_lock, LockCheck, LockOpener, LockOpeners, LockSlotVie pub use loot::{LootCall, LootRow, LootState, LOOT_PORTRAIT_UNIT}; pub use loot_roll::{LootRollEntry, LootRollsState}; pub use macros::{ - MacroBinding, MacroState, MacroView, CHARACTER_ID_BASE, MAX_MACROS, MAX_MACRO_BODY, - MAX_MACRO_NAME, + macro_lines, MacroBinding, MacroDerives, MacroState, MacroView, CHARACTER_ID_BASE, MAX_MACROS, + MAX_MACRO_BODY, MAX_MACRO_NAME, }; pub use mail::{ MailCall, MailInboxRow, MailInvoice, MailRowVerb, MailSendRequest, MailState, PackageView, diff --git a/crates/benilla-ui/src/script/model.rs b/crates/benilla-ui/src/script/model.rs index ed64cc0e4..3e5f51827 100644 --- a/crates/benilla-ui/src/script/model.rs +++ b/crates/benilla-ui/src/script/model.rs @@ -634,14 +634,17 @@ pub(crate) struct Model { pub(crate) pet_book_generation: u64, /// The player's macros, owned here as 1.12 macros have no server side; the app persists them. pub(crate) macros: macros::MacroState, - /// A script changed the macros: the save and `UPDATE_MACROS` cue. + /// A script changed the macros: the save's cue. pub(crate) macros_dirty: bool, /// Bumped by every seed and change, for readers that must not drain `macros_dirty`. pub(crate) macros_generation: u64, /// Bumped by every `EditMacro` that names a macro, whose worker `0x4f1280` ends in the action /// bar's usable refresh (`0x4f132e`). pub(crate) macro_edits: u64, - /// Each macro's cached cast by id, from the app; an absent macro reads unbound. + /// The load's derivations the table owes the app since its last take. + pub(crate) macro_derives: macros::MacroDerives, + /// Each macro's cached cast by id, derived in the verbs and the app's pass; an absent macro + /// reads unbound. pub(crate) macro_bindings: HashMap, /// The macro icon chooser's paths, behind `GetMacroIconInfo`: `0x4f0090`'s listing of /// `Interface\Icons\`, not `SpellIcon.dbc`. @@ -1586,6 +1589,7 @@ impl Model { macros_dirty: false, macros_generation: 0, macro_edits: 0, + macro_derives: Default::default(), macro_bindings: HashMap::new(), macro_icons: Vec::new(), macro_icon_source: None, diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 60e6466bd..3ecd70e53 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -29,14 +29,14 @@ A setting boots at the reference's default unless it is listed here (`docs/METHO Each entry is the first sentence of a `Deviation:` comment, linking to where it lives. -- [benilla-app](#benilla-app): 247 +- [benilla-app](#benilla-app): 246 - [benilla-assets](#benilla-assets): 6 - [benilla-blp](#benilla-blp): 1 - [benilla-formats](#benilla-formats): 22 - [benilla-lua](#benilla-lua): 11 - [benilla-protocol](#benilla-protocol): 27 - [benilla-srp](#benilla-srp): 2 -- [benilla-ui](#benilla-ui): 129 +- [benilla-ui](#benilla-ui): 131 - [benilla-world](#benilla-world): 49 ### benilla-app @@ -277,7 +277,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### spell - An out-of-range byte drops the packet, because the reference's unchecked write overruns the table (`(64, 19)` lands on the class family at `0xcecaac`). ([`src/spell/mods.rs:132`](../crates/benilla-app/src/spell/mods.rs#L132)) -- The fallback is the packet's target guid, never the nearest-hostile acquire, because that would attack something the player never named. ([`src/spell/net.rs:1208`](../crates/benilla-app/src/spell/net.rs#L1208)) +- The fallback is the packet's target guid, never the nearest-hostile acquire, because that would attack something the player never named. ([`src/spell/net.rs:1220`](../crates/benilla-app/src/spell/net.rs#L1220)) - A range failure leaves targeting armed and working. The reference's report cancels the cast (`0x6e2218` → `0x6e4940`): its line, `SPELLCAST_FAILED` and the tradeskill disarm, which benilla keeps; with the word the bind emptied it also sends `CMSG_CANCEL_CAST` for the unsent spell (`0x6e4970`) and clears the caster, then restores the pre-click word (`0x6e6096`), so every later click fails the caster test (`0x6e5b93`) and the cursor is stranded until a cancel. ([`src/spell/targeting/mod.rs:570`](../crates/benilla-app/src/spell/targeting/mod.rs#L570)) #### target @@ -386,8 +386,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### ui_macro -- Each line is trimmed, because the reference sends an indented `" /say hi"` as plain chat, never as the command meant. ([`src/ui_macro/run.rs:74`](../crates/benilla-app/src/ui_macro/run.rs#L74)) -- The `/cast` argument is trimmed, because the reference binds `/cast Fireball` (two spaces) to a name that never resolves. ([`src/ui_macro/run.rs:85`](../crates/benilla-app/src/ui_macro/run.rs#L85)) +- The reference's 255-byte cut (`0x4f0677`, `0x4f0b93`) can end inside a character and keep its stray bytes; a `String` must stay UTF-8, so the cut backs off to the character's start. ([`src/ui_macro/store.rs:21`](../crates/benilla-app/src/ui_macro/store.rs#L21)) #### ui_mail @@ -701,7 +700,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### script -- An out-of-range slot answers nil, because the reference indexes `0xbc6980` with no bounds check and reads the memory beside its 120 slots. ([`src/script/action.rs:382`](../crates/benilla-ui/src/script/action.rs#L382)) +- An out-of-range slot answers nil, because the reference indexes `0xbc6980` with no bounds check and reads the memory beside its 120 slots. ([`src/script/action.rs:400`](../crates/benilla-ui/src/script/action.rs#L400)) - The files the handler writes beside the install (`.pub` with the key, `.url`; `0x51dce0`, `0x51dde0`) are not written, as the install is read-only; the key is never read either, as there is no signature to verify with it. ([`src/script/addon.rs:207`](../crates/benilla-ui/src/script/addon.rs#L207)) - The reference fails silently; we report it, as a player needs to know, and hold the file so the shutdown write keeps it. ([`src/script/addon.rs:785`](../crates/benilla-ui/src/script/addon.rs#L785)) - The reference drops a send that resolves to PARTY while party slot 0's guid (`0xbc6f48`) is zero (`0x49fa9f`-`0x49faab`); benilla sends it, because `PartyState` is empty until the first `SMSG_GROUP_LIST` and the gate would swallow a real broadcast. vmangos drops a group-less party line anyway (`ChatHandler.cpp:476`). ([`src/script/addon_message.rs:7`](../crates/benilla-ui/src/script/addon_message.rs#L7)) @@ -757,8 +756,10 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - A key rebound to the command it already has keeps a duplicate index in 1.12.1 (`0x4b7786` lowers the other keys' indices before `0x4b77ac` returns on the same name), so both getters there answer one key too few; that client fault is not reproduced. ([`src/script/keybind.rs:223`](../crates/benilla-ui/src/script/keybind.rs#L223)) - An addon file whose first binding has no header opens a `HEADER_` row, where the reference files those rows under the previous file's last header, because under a foreign header the player could not find them. ([`src/script/keybind.rs:297`](../crates/benilla-ui/src/script/keybind.rs#L297)) - The handle's value is the address of a `CGxTex` (`SMemAlloc(0x54)`, `0x594a96`), which benilla cannot reproduce; each texture ranks instead by a creation stamp, one global sequence number taken when its cache key is first created and taken anew once its last region has let go of it (`super::texel::Texels`). ([`src/script/layer_batch.rs:9`](../crates/benilla-ui/src/script/layer_batch.rs#L9)) -- The reference's byte copy can end inside a character and keep the stray bytes; a `String` must stay UTF-8, so the cut stops at the character boundary. ([`src/script/macros.rs:111`](../crates/benilla-ui/src/script/macros.rs#L111)) -- A listing that finds no icon stays empty, to be listed again on the next ask, where the reference's dedup then reads below its null list (`0x4f0134`-`0x4f0145`) and faults. ([`src/script/macros.rs:439`](../crates/benilla-ui/src/script/macros.rs#L439)) +- The reference's byte copy can end inside a character and keep the stray bytes; a `String` must stay UTF-8, so the cut stops at the character boundary. ([`src/script/macros.rs:134`](../crates/benilla-ui/src/script/macros.rs#L134)) +- A listing that finds no icon stays empty, to be listed again on the next ask, where the reference's dedup then reads below its null list (`0x4f0134`-`0x4f0145`) and faults. ([`src/script/macros.rs:534`](../crates/benilla-ui/src/script/macros.rs#L534)) +- Each line is trimmed, because the reference sends an indented `" /say hi"` as plain chat, never as the command meant. ([`src/script/macros/bind.rs:30`](../crates/benilla-ui/src/script/macros/bind.rs#L30)) +- The `/cast` argument is trimmed, because the reference binds `/cast Fireball` (two spaces) to a name that never resolves. ([`src/script/macros/bind.rs:50`](../crates/benilla-ui/src/script/macros/bind.rs#L50)) - The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:880`](../crates/benilla-ui/src/script/mod.rs#L880)) - The reference sets the cells only when glue or the interface is built, `0x41ad10` from `0x46a828` (`0x46a7b0`) and `0x48fe2b` (`0x48fbf0`), and a resize reaches them only through the rebuild it asks for. ([`src/script/mod.rs:931`](../crates/benilla-ui/src/script/mod.rs#L931)) - A path that does not resolve is stored, where the reference raises `Invalid model file: %s` (`0x878b44`), because the file loads asynchronously here and the call cannot know yet. ([`src/script/modelframe.rs:339`](../crates/benilla-ui/src/script/modelframe.rs#L339))