From aa25486d78c821082f9fd3d7ac8cb976dfdcee5c Mon Sep 17 00:00:00 2001 From: Sam Sung <51686767+samwhosung@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:10:48 +0700 Subject: [PATCH] Loot verbs, packets and auto-loot act where 1.12.1 acts (#2209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Loot went wrong: - Takes, closes and master gives queued, then ran in a fixed order. - The last row closed a frame late. - Auto-loot opened before it swept, read Shift when the loot arrived, and looted over an open window. - `GetNumLootItems` counted taken rows, and a response for an object the client lacked opened a window. The reference: - `LootSlot` is the confirm form (`0x4c2e70`). A row click takes after its `` (`0x4c1867`). `CloseLoot` zeroes only the source (`0x4c1da0`). - `SMSG_LOOT_REMOVED` closes an empty window in the packet (`0x4c1f8d`). - The sweep runs before `LOOT_OPENED` (`0x4c1ed3`, `0x4c2240`). Each interaction stores the byte (`0x5df460`), and `CanLootNow` refuses an open session (`0x5ec1e1`). - A missing object shows `ERR_LOOT_DIDNT_KILL` (`0x5ebb3f`). Each fact is tested against its address, with the stock `LootFrame` for the replacing window. Part of #2202 Fixes #2167 Fixes #2181 Fixes #2180 Fixes #2190 Fixes #1228 Fixes #784 Fixes #2189 Fixes #72 πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5.5 --- crates/benilla-app/src/capture/probe_clam.rs | 15 +- crates/benilla-app/src/game_plugins.rs | 4 +- crates/benilla-app/src/script_calls.rs | 17 +- crates/benilla-app/src/sound/money.rs | 7 +- crates/benilla-app/src/target/click.rs | 267 ++- .../src/target/click_loot_tests.rs | 540 +++++ crates/benilla-app/src/target/cursor_mode.rs | 22 +- crates/benilla-app/src/ui_action/drain.rs | 5 + crates/benilla-app/src/ui_action/mod.rs | 3 + crates/benilla-app/src/ui_items/drain.rs | 189 +- crates/benilla-app/src/ui_loot/call_tests.rs | 797 +++++++ crates/benilla-app/src/ui_loot/calls.rs | 442 ++++ crates/benilla-app/src/ui_loot/mod.rs | 1929 ++++++++--------- crates/benilla-app/src/ui_loot/net.rs | 203 +- crates/benilla-app/src/ui_loot/sweep_tests.rs | 250 +++ .../benilla-app/src/ui_script/escape_tests.rs | 7 +- .../src/ui_script/game_menu_tests.rs | 3 +- .../benilla-app/src/ui_script/loot_tests.rs | 125 +- .../benilla-app/src/ui_script/sweep_tests.rs | 3 + .../src/ui_script/world_entry_tests.rs | 3 +- crates/benilla-ui/src/script/button.rs | 16 +- crates/benilla-ui/src/script/calls.rs | 2 + crates/benilla-ui/src/script/container.rs | 17 +- crates/benilla-ui/src/script/loot.rs | 338 +-- crates/benilla-ui/src/script/mod.rs | 2 +- crates/benilla-ui/src/script/model.rs | 19 +- .../script/tests/tooltip_item/mechanics.rs | 4 +- docs/DEVIATIONS.md | 17 +- 28 files changed, 3765 insertions(+), 1481 deletions(-) create mode 100644 crates/benilla-app/src/target/click_loot_tests.rs create mode 100644 crates/benilla-app/src/ui_loot/call_tests.rs create mode 100644 crates/benilla-app/src/ui_loot/calls.rs create mode 100644 crates/benilla-app/src/ui_loot/sweep_tests.rs diff --git a/crates/benilla-app/src/capture/probe_clam.rs b/crates/benilla-app/src/capture/probe_clam.rs index c2a726a32..dd25c9e18 100644 --- a/crates/benilla-app/src/capture/probe_clam.rs +++ b/crates/benilla-app/src/capture/probe_clam.rs @@ -54,7 +54,16 @@ pub(crate) struct ProbeClamPlugin; impl Plugin for ProbeClamPlugin { fn build(&self, app: &mut App) { app.init_resource::() - .add_systems(Update, clam_probe); + .add_systems(Update, (hold_auto_loot_off, clam_probe).chain()); + } +} + +/// The window must survive to be looked at: with auto-loot on, the single row is taken at the open +/// edge and the last-row auto-release shuts it again immediately. Its own system, as the VM's call +/// host reads the config the probe writes. +fn hold_auto_loot_off(mut cfg: ResMut) { + if cfg.auto_loot { + cfg.auto_loot = false; } } @@ -182,7 +191,6 @@ fn clam_probe( self_store: Query<&ObjectStore, With>, objects: Objects, items: Res, - mut cfg: ResMut, net: Res, mut exit: MessageWriter, ) { @@ -198,9 +206,6 @@ fn clam_probe( match probe.phase { Phase::Wait => { - // The window must survive to be looked at: with auto-loot on, the single row is - // taken at the open edge and the last-row auto-release shuts it again immediately. - cfg.auto_loot = false; info!( "PROBE_CLAM: stocking one openable item (entry {entry}) β€” auto-loot forced off" ); diff --git a/crates/benilla-app/src/game_plugins.rs b/crates/benilla-app/src/game_plugins.rs index 53ed54838..b6f01cf77 100644 --- a/crates/benilla-app/src/game_plugins.rs +++ b/crates/benilla-app/src/game_plugins.rs @@ -1749,9 +1749,9 @@ pub(crate) mod schedule_tests { ("ui_logout.rs", "feed_logout", Because::PlayerRoundTrip, "both packets answer the `CMSG_LOGOUT_REQUEST`/cancel the game menu sent"), ("ui_loot/mod.rs", "drain_loot", Because::Deliberate, - "the pre-VM takes of `LootMoveStart` and `LootCloseAtRest` are documented at the line and publish nothing to the VM; the event-firing takes are Lua's queues"), + "its takes of `LootMoveStart` and `LootCloseAtRest` close on the engine's side and publish nothing to the VM, whose `LOOT_CLOSED` is the feed's diff; the at-rest sweep signals only on a disenchant window, which the interface's own cast opens"), ("ui_loot/mod.rs", "feed_loot", Because::PlayerRoundTrip, - "it takes `LootMoveStart` only on a window it has just opened, which answers a loot click"), + "the window steps it takes are the loot packets', which follow the response to a loot click, and it takes `LootMoveStart` only on a window it has just opened"), ("ui_loot_roll.rs", "feed_loot_rolls", Because::PlayerRoundTrip, "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, diff --git a/crates/benilla-app/src/script_calls.rs b/crates/benilla-app/src/script_calls.rs index d2fac4198..ed2d2b6f0 100644 --- a/crates/benilla-app/src/script_calls.rs +++ b/crates/benilla-app/src/script_calls.rs @@ -81,7 +81,15 @@ pub(crate) struct ScriptCallHost<'w, 's> { crate::ui_chat::EmoteDoer<'w, 's>, ), >, - crate::ui_items::ScriptItemUse<'w, 's>, + // The bags' and the loot window's. + ParamSet< + 'w, + 's, + ( + crate::ui_items::ScriptItemUse<'w, 's>, + crate::ui_loot::LootSteps<'w, 's>, + ), + >, crate::ui_pet::PetPress<'w, 's>, crate::ui_action::AttackPress<'w, 's>, ), @@ -149,10 +157,12 @@ impl CallHost for ScriptCallHost<'_, '_> { } } ScriptCall::UseContainerItem(call) => { - appliers.p5().use_container_item(script, call); + if let Some(open) = appliers.p5().p0().use_container_item(script, call) { + tail = appliers.p5().p1().open_item(script, open); + } } ScriptCall::UseInventoryItem { slot, on_self, .. } => { - appliers.p5().use_inventory_item(script, slot, on_self) + appliers.p5().p0().use_inventory_item(script, slot, on_self) } ScriptCall::CastPetSpell { spell_id, on_self } => { let send = @@ -177,6 +187,7 @@ impl CallHost for ScriptCallHost<'_, '_> { ScriptCall::AddonMessage(send) => appliers.p4().p1().addon_message(send), ScriptCall::PickItem(pick) => popup = appliers.p1().pick_item(pick), ScriptCall::EnchantConfirm(answer) => popup = appliers.p1().confirm_enchant(answer), + ScriptCall::Loot(call) => tail = appliers.p5().p1().apply(script, call), } // A selection this call made with the targeting cursor up was handed to the cast // (`SelectTarget`, `0x4935d5`) and is bound now, before the next call reads either. diff --git a/crates/benilla-app/src/sound/money.rs b/crates/benilla-app/src/sound/money.rs index 6b7b5faef..8e2520d09 100644 --- a/crates/benilla-app/src/sound/money.rs +++ b/crates/benilla-app/src/sound/money.rs @@ -5,9 +5,10 @@ //! //! The first value after login or reconnect seeds without playing; whether the reference's watcher //! fires on the login set is untraced. Deviation: the reference also plays an optimistic coin at -//! the loot-money click, so looted money sounds twice; benilla plays the watcher's coin alone, -//! because one coin on the confirmed change reads cleanly and the round trip the early coin hides -//! is imperceptible on a local server. +//! the loot-money click, and at the auto-loot sweep's money, once a session (`0x4c201b`-`0x4c2020`, +//! the same `0x458030` call), so looted money sounds twice; benilla plays the watcher's coin +//! alone, because one coin on the confirmed change reads cleanly and the round trip the early coin +//! hides is imperceptible on a local server. use bevy::prelude::*; diff --git a/crates/benilla-app/src/target/click.rs b/crates/benilla-app/src/target/click.rs index c0c9ba972..60ba01c44 100644 --- a/crates/benilla-app/src/target/click.rs +++ b/crates/benilla-app/src/target/click.rs @@ -303,6 +303,55 @@ pub(crate) struct Dispatch<'w, 's> { /// The walks, whose stand-up goes through the seam's writer: a system holds one. auto: crate::player::AutoMove<'w, 's>, player: Res<'w, crate::player::Player>, + /// Shift and the auto-loot setting, the interactions' `SetAutoLoot` byte. + keys: Res<'w, ButtonInput>, + loot_cfg: Res<'w, crate::ui_loot::LootConfig>, + /// Our player as the active mover (`0xc4da98`), which the loot legs' store asks. + mover: Query<'w, 's, (), (With, With)>, +} + +/// What a leg does once its `SetAutoLoot` has applied, the sweep it may run included: the loot or +/// the use the reference calls after the store returns (`0x5d6c78`, `0x60bff7`, `0x5f86a6`). The +/// store is a call, which inside the click's turn applies as the turn ends, so the rest is a turn +/// of its own. +enum Owed { + LootCorpse { + entity: Entity, + guid: u64, + walk: bool, + }, + LootUnit { + entity: Entity, + guid: u64, + walk: bool, + }, + UseObject { + entity: Entity, + guid: u64, + in_reach: bool, + walk: bool, + }, +} + +impl Owed { + fn run(self, dispatch: &mut Dispatch) { + match self { + Owed::LootCorpse { entity, guid, walk } => { + let can_loot = dispatch.can_loot_corpse(entity); + dispatch.loot_corpse(entity, guid, can_loot, walk); + } + Owed::LootUnit { entity, guid, walk } => { + let can_loot = dispatch.can_loot_unit(entity); + dispatch.loot_unit(entity, guid, can_loot, walk); + } + Owed::UseObject { + entity, + guid, + in_reach, + walk, + } => dispatch.use_gameobject(entity, guid, in_reach, walk), + } + } } /// The Loot walk's stop radius: the arm (`0x611130`) takes the square root (`0x6111ab`) of what @@ -313,6 +362,11 @@ fn loot_stop(reach: f32) -> f32 { } impl Dispatch<'_, '_> { + /// Our player is the active mover (`0x5d6c4a`, `0x60bfc6`). + fn is_active_mover(&self) -> bool { + !self.mover.is_empty() + } + fn me(&self) -> Option<(Entity, u64, bool)> { self.self_player .single() @@ -367,9 +421,35 @@ impl Dispatch<'_, '_> { self.dist_sq(target).is_some_and(|d2| d2 <= reach * reach) } - /// `CanLootNow 0x5ec110`: the melee reach, skipped under `CanAutoInteract` (`0x5ec11b`). + /// `CanLootNow 0x5ec110` for a unit: the melee reach, skipped under `CanAutoInteract` + /// (`0x5ec11b`), and no loot target held, this unit's own included (`0x5ec1e1`-`0x5ec1f8`). fn can_loot_unit(&self, target: Entity) -> bool { - self.auto.can_auto_interact() || self.in_melee_reach(target) + (self.auto.can_auto_interact() || self.in_melee_reach(target)) + && self.seam.loot_latch.0.is_none() + } + + /// `CanLootNow 0x5ec110` for a corpse object, as the corpse cursor asks it (`0x4827d7`): its + /// 5 yd reach, skipped under `CanAutoInteract`, and no loot target held. + fn can_loot_corpse(&self, target: Entity) -> bool { + (self.auto.can_auto_interact() + || self + .dist_sq(target) + .is_some_and(|d2| d2 <= cursor_mode::CORPSE_INTERACT_RANGE_SQ)) + && self.seam.loot_latch.0.is_none() + } + + /// `SetAutoLoot 0x5df460` with the interaction's byte ([`crate::ui_loot::interaction_byte`]), + /// as a call: inside the click's turn it applies as the turn ends, ahead of the leg's [`Owed`]. + fn set_auto_loot(&self, script: Option<&mut benilla_ui::script::UiScript>) { + if let Some(script) = script { + script.set_auto_loot(self.auto_loot_byte()); + } + } + + /// The interaction's byte ([`crate::ui_loot::interaction_byte`]) from the Shift held now. + fn auto_loot_byte(&self) -> bool { + let shift = self.keys.pressed(KeyCode::ShiftLeft) || self.keys.pressed(KeyCode::ShiftRight); + crate::ui_loot::interaction_byte(&self.loot_cfg, shift) } fn approach( @@ -560,11 +640,12 @@ impl Dispatch<'_, '_> { } } - /// `0x5df130`: `CMSG_LOOT` at a lootable corpse, never while [`Self::moving`] (`0x5df173`), - /// walked to first when `walk` and beyond its 5 yd (`0x5df1c3`), stopping at [`loot_stop`] of - /// 5. A walk that does not start falls through to the send. - fn loot_corpse(&mut self, entity: Entity, guid: u64, walk: bool) { - if self.moving() { + /// `0x5df130`: `CMSG_LOOT` at a lootable corpse, which `can_loot` (`CanLootNow`, `0x5df151`, + /// [`Self::can_loot_corpse`]) must allow, never while [`Self::moving`] (`0x5df173`), walked to + /// first when `walk` and beyond its 5 yd (`0x5df1c3`), stopping at [`loot_stop`] of 5. A walk + /// that does not start falls through to the send. + fn loot_corpse(&mut self, entity: Entity, guid: u64, can_loot: bool, walk: bool) { + if !can_loot || self.moving() { return; } if walk @@ -587,9 +668,10 @@ impl Dispatch<'_, '_> { self.seam.loot_latch.0 = Some(guid); } - /// `0x5df2a0`: `CMSG_LOOT` at a dead unit, which `can_loot` (`CanLootNow 0x5ec110`) must - /// allow, never while [`Self::moving`] (`0x5df2e9`), walked to first when `walk` and beyond - /// melee reach. A walk that does not start falls through to the send. + /// `0x5df2a0`: `CMSG_LOOT` at a dead unit, which `can_loot` (`CanLootNow 0x5ec110`, + /// [`Self::can_loot_unit`]) must allow (`0x5df2c1`), never while [`Self::moving`] (`0x5df2e9`), + /// walked to first when `walk` and beyond melee reach. A walk that does not start falls + /// through to the send. fn loot_unit(&mut self, entity: Entity, guid: u64, can_loot: bool, walk: bool) { if !can_loot || self.moving() { return; @@ -620,8 +702,13 @@ impl Dispatch<'_, '_> { /// rungs refuse it as they refuse a press: another spell in flight (`0x6e4d97`), the range /// test (`0x6e4f26`), the validator (`0x6e4f3b`), and a passing one is pushed in flight /// (`0x6e5026`) and sent (`0x6e54f0`). Queued for [`crate::ui_action::ClickCasts`]' drain. + /// With the leg's VM, `script`, the walk or the cast is followed by `SetAutoLoot`, its `set` + /// given (`0x5f06e1`-`0x5f06ef`): at once after a walk (`0x5f06c4`), after the cast in its + /// drain ([`crate::ui_action::ClickCast::AtUnit`]). + #[allow(clippy::too_many_arguments)] // `InteractWithSpell`'s own inputs fn skin( &mut self, + script: Option<&mut benilla_ui::script::UiScript>, entity: Entity, guid: u64, spell_id: u32, @@ -629,6 +716,7 @@ impl Dispatch<'_, '_> { in_reach: bool, walk: bool, ) { + let auto_loot = script.is_some().then(|| self.auto_loot_byte()); if !in_reach && walk { let reach = match subject { crate::player::Subject::Corpse => cursor_mode::MELEE_FLOOR, @@ -642,6 +730,9 @@ impl Dispatch<'_, '_> { subject, stop, ); + if let (Some(script), Some(byte)) = (script, auto_loot) { + script.set_auto_loot(byte); + } return; } debug!("right-click skin: {guid:#x} (spell {spell_id})"); @@ -652,6 +743,7 @@ impl Dispatch<'_, '_> { spell_id, entity, guid, + auto_loot, }); } @@ -799,7 +891,7 @@ pub(super) fn act_on_right_click( if clicks.read().last().is_none() || vm.own().0.seam.player_is_charmed() { return; } - vm.turn(|script, (mut dispatch, mut selection)| { + let owed = vm.turn(|script, (mut dispatch, mut selection)| { // The router's other legs: the world hit walks there (`0x5e0378`), and nothing walks along // the ray when the cursor is empty (`0x492d50`). if !press.over_object() { @@ -814,10 +906,13 @@ pub(super) fn act_on_right_click( } _ => {} } - return; + return None; } - interact(&mut dispatch, script, &press, Select::First(&mut selection)); - }) + interact(&mut dispatch, script, &press, Select::First(&mut selection)) + }); + if let Some(owed) = owed { + vm.turn(|_, (mut dispatch, _)| owed.run(&mut dispatch)); + } } /// Where [`interact`] selects its unit, if it does: the world click's entry (`0x492820`) selects @@ -854,7 +949,7 @@ fn interact( script: Option<&mut benilla_ui::script::UiScript>, press: &PressPick, mut select: Select, -) { +) -> Option { let (hovered, hovered_object, cursor) = (&press.hovered, &press.object, &press.cursor); let walk = dispatch.auto.can_auto_interact(); let self_mounted = dispatch.mounted(); @@ -879,29 +974,41 @@ fn interact( ), ); } - if cursor.kind != cursor_mode::CursorKind::Point { - if let (Some(entity), Some(guid)) = (hovered_object.target, hovered_object.guid) { - // Walking, the range arm (`0x5f330c`) is the object's own: the PickLock cursor - // never grays, and the gray folds the lock in. - let in_reach = if walk { - let go_type = dispatch - .stores - .get(entity) - .map_or(-1, |(s, _)| s.0.gameobject_type_id()); - dispatch - .dist_sq(entity) - .is_some_and(|d2| d2 <= cursor_mode::go_interact_range_sq(go_type)) - } else { - !cursor.unable - }; - dispatch.use_gameobject(entity, guid, in_reach, walk); - } + if cursor.kind == cursor_mode::CursorKind::Point { + return None; } - return; + let (Some(entity), Some(guid)) = (hovered_object.target, hovered_object.guid) else { + return None; + }; + // Walking, the range arm (`0x5f330c`) is the object's own: the PickLock cursor never + // grays, and the gray folds the lock in. + let in_reach = if walk { + let go_type = dispatch + .stores + .get(entity) + .map_or(-1, |(s, _)| s.0.gameobject_type_id()); + dispatch + .dist_sq(entity) + .is_some_and(|d2| d2 <= cursor_mode::go_interact_range_sq(go_type)) + } else { + !cursor.unable + }; + // `0x5f8660`, past its handler's slot 5: the byte for our player (`0x5f8690`, + // `0x5f869f`), then the use (`0x5f86a6`). + if dispatch.me().is_some() { + dispatch.set_auto_loot(script); + } + return Some(Owed::UseObject { + entity, + guid, + in_reach, + walk, + }); } // ── The corpse leg, `CGCorpse_C`'s interact slot `0x5d6bf0` ── // Leg 1: not mounted and lootable (`CORPSE_FIELD_DYNAMIC_FLAGS` bit 0) β†’ a stand-state check, - // `SetAutoLoot` (`0x5df460`) and `CMSG_LOOT` (`0x5df130`). Leg 2: `CORPSE_FIELD_FLAGS` bit 5, + // `SetAutoLoot` for the active mover (`0x5d6c4a`, `0x5d6c68`) and `CMSG_LOOT` (`0x5df130`). + // Leg 2: `CORPSE_FIELD_FLAGS` bit 5, // the `[0xb700e8]` latch (never set in 1.12.1) and an unfriendly corpse (`!0x6067d0`) β†’ the // skin cast (`0x5f05e0`). Your own corpse takes neither: the resurrect prompt comes from the // 40 yd `CORPSE_IN_RANGE` poll (`0x492130`), never a click. @@ -937,17 +1044,21 @@ fn interact( .feedback .errors .push(crate::ui_action::UiError::key("ERR_LOOT_NOTSTANDING")); - return; + return None; } - // Range rides the cursor's gray, so the pouch is never lit where the click refuses. - if !cursor.unable { - dispatch.loot_corpse(entity, guid, walk); + if dispatch.is_active_mover() { + dispatch.set_auto_loot(script); } + // `LootCorpse` asks `CanLootNow` once the store's sweep has run (`0x5df151`), which + // may have dropped the target (`0x4c224f` β†’ `0x48f2c9`). + return Some(Owed::LootCorpse { entity, guid, walk }); } else if insignia { // Leg 2. `skin_player_corpse` mirrors `[0xb700e8]`, `None` for every 1.12.1 player, // so this is inert as in the reference; the unfriendly test is not built. if let Some(spell_id) = dispatch.learned.skin_player_corpse { + // `InteractWithSpell`, its store's `set` given (`0x5d6cc7`). dispatch.skin( + script, entity, guid, spell_id, @@ -957,10 +1068,10 @@ fn interact( ); } } - return; + return None; } let (Some(entity), Some(guid)) = (hovered.target, hovered.guid) else { - return; + return None; }; // The dispatcher's attack arm (`0x60c18c`), not the sword: a dead, ghost or mounted player // still takes it and is refused inside (`0x60c1a1`, `0x60c1bc`), never reaching a service. @@ -1084,8 +1195,11 @@ fn interact( .errors .push(crate::ui_action::UiError::key("ERR_LOOT_NOTSTANDING")); } else { - let can_loot = dispatch.can_loot_unit(entity); - dispatch.loot_unit(entity, guid, can_loot, walk); + // The store for the active mover (`0x60bfc6`, `0x60bfe4`), then `0x5df2a0`. + if dispatch.is_active_mover() { + dispatch.set_auto_loot(script); + } + return Some(Owed::LootUnit { entity, guid, walk }); } } UnitBranch::Dead(DeadUnitLeg::Skin) => { @@ -1093,7 +1207,9 @@ fn interact( // loot leg declined, lootable ones included while mounted. if let Some(spell_id) = dispatch.learned.skinning { let in_reach = dispatch.in_melee_reach(entity); + // `InteractWithSpell`, its store's `set` given (`0x60c074`). dispatch.skin( + script, entity, guid, spell_id, @@ -1110,6 +1226,7 @@ fn interact( } UnitBranch::Service => dispatch.talk(script, entity, guid, walk), } + None } /// Interact with an object by running its own virtual dispatcher (slot `+0x60`): `0x60bea0` for a @@ -1148,42 +1265,55 @@ pub(super) fn act_on_interact( if requests.is_empty() && plate_clicks.is_empty() { return; } - vm.turn(|mut script, (mut set, mut selection)| { - for &PlateRightClick { selected } in plate_clicks.read() { + // Each its own dispatch, as the reference calls each slot: a leg's owed loot or use is a turn + // after its store's. + let plates: Vec = + plate_clicks.read().map(|click| click.selected).collect(); + for selected in plates { + let owed = vm.turn(|script, (mut set, mut selection)| { interact( &mut set.p1(), - script.as_deref_mut(), + script, &press, Select::Done(&mut selection, selected), - ); + ) + }); + if let Some(owed) = owed { + vm.turn(|_, (mut set, _)| owed.run(&mut set.p1())); } - for &Interact(entity) in requests.read() { - let Ok((guid, net)) = kinds.get(entity) else { - continue; - }; - let mut pick = PressPick::default(); - match net.kind { - EntityKind::Unit | EntityKind::Player => { - (pick.hovered.target, pick.hovered.guid) = (Some(entity), Some(guid.0)); - } - EntityKind::Corpse => { - (pick.hovered.corpse, pick.hovered.corpse_guid) = (Some(entity), Some(guid.0)); - } - EntityKind::GameObject => { - (pick.object.target, pick.object.guid) = (Some(entity), Some(guid.0)); - } - EntityKind::DynamicObject | EntityKind::Other => continue, + } + let entities: Vec = requests.read().map(|&Interact(entity)| entity).collect(); + for entity in entities { + let Ok((guid, net)) = kinds.get(entity) else { + continue; + }; + let mut pick = PressPick::default(); + match net.kind { + EntityKind::Unit | EntityKind::Player => { + (pick.hovered.target, pick.hovered.guid) = (Some(entity), Some(guid.0)); } + EntityKind::Corpse => { + (pick.hovered.corpse, pick.hovered.corpse_guid) = (Some(entity), Some(guid.0)); + } + EntityKind::GameObject => { + (pick.object.target, pick.object.guid) = (Some(entity), Some(guid.0)); + } + EntityKind::DynamicObject | EntityKind::Other => continue, + } + let owed = vm.turn(|script, (mut set, mut selection)| { (pick.cursor, pick.attack_fork) = cursor_mode::classify(&set.p0(), &pick.hovered, &pick.object); interact( &mut set.p1(), - script.as_deref_mut(), + script, &pick, Select::OnAttack(&mut selection), - ); + ) + }); + if let Some(owed) = owed { + vm.turn(|_, (mut set, _)| owed.run(&mut set.p1())); } - }) + } } /// The verb an approach owed, once it arrived (`0x60fa20`, run at the stop): the dispatcher alone, @@ -1267,7 +1397,7 @@ fn act_on_arrival_with( } else { Subject::Unit { dead: true } }; - dispatch.skin(entity, guid, spell_id, subject, true, false); + dispatch.skin(None, entity, guid, spell_id, subject, true, false); } } _ => {} @@ -1745,6 +1875,10 @@ pub(super) fn clear( } } +#[cfg(test)] +#[path = "click_loot_tests.rs"] +mod loot_tests; + #[cfg(test)] mod tests { use super::*; @@ -2414,6 +2548,7 @@ mod tests { spell_id: SKINNING, entity, guid: BOAR, + .. }] if entity == boar ), casts, diff --git a/crates/benilla-app/src/target/click_loot_tests.rs b/crates/benilla-app/src/target/click_loot_tests.rs new file mode 100644 index 000000000..0395c9bd7 --- /dev/null +++ b/crates/benilla-app/src/target/click_loot_tests.rs @@ -0,0 +1,540 @@ +//! The loot legs of the interaction dispatchers through the whole client's host. Each stores the +//! auto-loot byte through `SetAutoLoot` (`0x5df460`) before it loots or uses, which with a loot +//! target held sweeps the open window at once (`0x5df470`, `0x5df480`); the copier reads the byte +//! the click stored (`0x4c1ec7`). `CanLootNow` (`0x5ec110`) refuses while any loot target is held +//! (`0x5ec1e1`-`0x5ec1f8`), in both loot clicks (`0x5df151`, `0x5df2c1`) and the loot cursor +//! (`0x4824fe`, `0x4827d7`), which lights only over the object being looted (`0x48250a`, +//! `0x4827e3`). + +use benilla_protocol::messages::{slot_type, LootItem, ObjectFields}; +use benilla_protocol::{EntityKind, SessionEvent}; +use bevy::ecs::system::RunSystemOnce; +use crossbeam_channel::Receiver; + +use super::*; +use crate::net::{ActiveMover, ClientCommand, NetCommands, NetEntity, ObjectStore, SelfGuid}; +use crate::ui_loot::{AutoLootByte, LootLatch}; + +const ME: u64 = 0x10; +/// Two dead, lootable creatures in reach. +const BODY_A: u64 = 0xF130_0000_0000_00A1; +const BODY_B: u64 = 0xF130_0000_0000_00B2; +/// A skinnable creature that has been looted. +const HIDE: u64 = 0xF130_0000_0000_00C3; +const CHEST: u64 = 0xF110_0000_0000_00D4; +/// A lootable bone pile, a corpse object. +const BONES: u64 = 0xF000_0000_0000_00E5; +const LINEN: u32 = 2589; +const SKINNING: u32 = 8613; +/// `UNIT_DYNAMIC_FLAGS`: lootable. +const F_DYNAMIC_FLAGS: u16 = 143; +/// `GAMEOBJECT_TYPE_ID`; 3 is a chest. +const F_GO_TYPE: u16 = 21; + +struct Client { + app: App, + rx: Receiver, + bodies: [(u64, Entity); 3], + chest: Entity, + bones: Entity, +} + +fn fields(pairs: &[(u16, u32)]) -> ObjectStore { + ObjectStore(ObjectFields::from_pairs(pairs)) +} + +/// The whole client, headless: our player, the active mover, two dead lootable creatures, a +/// looted skinnable one, a chest and a lootable corpse, all in reach, Skinning known, with a VM +/// noting `LOOT_OPENED` and `LOOT_CLOSED` in `SEEN`. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(NetCommands(tx)); + // What the dispatchers and the cursor read that a headless build leaves to its plugins. + app.init_resource::() + .init_resource::>() + .init_resource::>() + .init_resource::>() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::>() + .init_resource::>(); + let world = app.world_mut(); + let unit = |kind| NetEntity { + kind, + display_id: None, + scale: 1.0, + }; + let me = world + .spawn(( + Guid(ME), + SelfPlayer, + ActiveMover, + unit(EntityKind::Player), + Transform::default(), + GlobalTransform::default(), + // `OBJECT_FIELD_TYPE` a player's, the cast ladder's actor. + fields(&[(2, 0x19), (22, 100), (28, 100)]), + )) + .id(); + world + .resource_mut::() + .0 + .insert(ME, me); + world.resource_mut::().0 = Some(ME); + let body = |world: &mut World, guid: u64, x: f32, store: ObjectStore| { + let e = world + .spawn(( + Guid(guid), + unit(EntityKind::Unit), + Transform::from_xyz(x, 0.0, 0.0), + GlobalTransform::default(), + store, + )) + .id(); + world + .resource_mut::() + .0 + .insert(guid, e); + (guid, e) + }; + let dead_lootable = || fields(&[(22, 0), (28, 100), (F_DYNAMIC_FLAGS, 0x1)]); + let bodies = [ + body(world, BODY_A, 2.0, dead_lootable()), + body(world, BODY_B, -2.0, dead_lootable()), + body( + world, + HIDE, + 0.0, + fields(&[ + (22, 0), + (28, 100), + ( + benilla_protocol::field::FIELD_UNIT_FLAGS, + cursor_mode::UNIT_FLAG_SKINNABLE, + ), + ]), + ), + ]; + let chest = world + .spawn(( + Guid(CHEST), + unit(EntityKind::GameObject), + Transform::from_xyz(0.0, 0.0, 2.0), + GlobalTransform::default(), + fields(&[(F_GO_TYPE, 3)]), + )) + .id(); + world + .resource_mut::() + .0 + .insert(CHEST, chest); + let bones = world + .spawn(( + Guid(BONES), + Transform::from_xyz(0.0, 0.0, -1.0), + GlobalTransform::default(), + fields(&[(benilla_protocol::field::FIELD_CORPSE_DYNAMIC_FLAGS, 0x1)]), + )) + .id(); + world + .resource_mut::() + .0 + .insert(BONES, bones); + world + .resource_mut::() + .skinning = Some(SKINNING); + let mut spells = crate::ui_action::Spells::empty_for_tests(); + spells.catalog = benilla_formats::SpellCatalog::from_displays( + [( + SKINNING, + benilla_formats::SpellDisplay { + targets: 0x402, + implicit_target_a1: 25, + ..Default::default() + }, + )] + .into_iter() + .collect(), + ); + world.insert_resource(spells); + world + .resource_mut::() + .insert_template(LINEN, Some(crate::items::test_template("Linen Cloth"))); + let script = benilla_ui::script::UiScript::new().expect("a VM"); + script + .run( + r#"SEEN = {} + local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_OPENED") f:RegisterEvent("LOOT_CLOSED") + f:SetScript("OnEvent", function() tinsert(SEEN, event) end)"#, + ) + .expect("the recorder installs"); + world.insert_non_send_resource(script); + Client { + app, + rx, + bodies, + chest, + bones, + } +} + +impl Client { + fn entity(&self, guid: u64) -> Entity { + self.bodies + .iter() + .find(|(g, _)| *g == guid) + .map(|&(_, e)| e) + .expect("a body") + } + + fn shift(&mut self, down: bool) { + let mut keys = self.app.world_mut().resource_mut::>(); + if down { + keys.press(KeyCode::ShiftLeft); + } else { + keys.release(KeyCode::ShiftLeft); + } + } + + /// A right-click on the body `guid`, its cursor lit. + fn right_click_body(&mut self, guid: u64) { + let entity = self.entity(guid); + self.right_click(PressPick { + hovered: Hovered { + target: Some(entity), + guid: Some(guid), + distance: 2.0, + ..Hovered::default() + }, + cursor: WorldCursor { + kind: cursor_mode::CursorKind::Pickup, + unable: false, + }, + ..PressPick::default() + }); + } + + fn right_click_chest(&mut self) { + self.right_click(PressPick { + object: HoveredObject { + target: Some(self.chest), + guid: Some(CHEST), + distance: 2.0, + }, + cursor: WorldCursor { + kind: cursor_mode::CursorKind::Interact, + unable: false, + }, + ..PressPick::default() + }); + } + + /// A right-click on the corpse, its cursor as the press found it: grey while another loot is + /// held (`0x4827d7`). + fn right_click_bones(&mut self, unable: bool) { + self.right_click(PressPick { + hovered: Hovered { + corpse: Some(self.bones), + corpse_guid: Some(BONES), + distance: 1.0, + ..Hovered::default() + }, + cursor: WorldCursor { + kind: cursor_mode::CursorKind::LootAll, + unable, + }, + ..PressPick::default() + }); + } + + /// The frame's right-click casts, sent through the cast ladder. + fn drain_casts(&mut self) { + self.app + .world_mut() + .run_system_once(crate::ui_action::drain_click_casts) + .unwrap(); + } + + fn right_click(&mut self, press: PressPick) { + let world = self.app.world_mut(); + *world.resource_mut::() = press; + world + .resource_mut::>() + .write(WorldRightClick); + world.run_system_once(act_on_right_click).unwrap(); + } + + /// The server's answer for `guid`, then the frame's loot feed. + fn respond(&mut self, guid: u64, items: Vec) { + let world = self.app.world_mut(); + crate::net::handlers::dispatch( + world, + vec![SessionEvent::LootResponse { + guid, + loot_type: 1, + gold: 0, + items, + }], + ); + crate::ui_loot::feed_loot_once(world); + } + + /// The window on `guid` open, as our loot click and its answer leave it. + fn looting(&mut self, guid: u64, items: Vec) { + self.app.world_mut().resource_mut::().0 = Some(guid); + self.respond(guid, items); + let _ = (self.sent(), self.seen()); + } + + fn sent(&self) -> Vec { + self.rx + .try_iter() + .filter(|c| { + matches!( + c, + ClientCommand::Loot { .. } + | ClientCommand::AutostoreLootItem { .. } + | ClientCommand::LootRelease { .. } + | ClientCommand::GameObjUse { .. } + ) + }) + .collect() + } + + fn seen(&mut self) -> String { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + s.expect("a VM") + .eval::("local s = table.concat(SEEN, ',') SEEN = {} return s") + }) + .expect("the chunk runs") + } + + fn byte(&self) -> bool { + self.app.world().resource::().0 + } +} + +fn linen(slot: u8) -> LootItem { + LootItem { + slot, + item_id: LINEN, + count: 1, + display_info_id: 0, + random_property_id: 0, + slot_type: slot_type::ALLOW_LOOT, + } +} + +/// The unit's loot leg stores Shift as the click finds it (`0x60bfe4`), and the copier reads that +/// byte (`0x4c1ec7`): a Shift let go before the answer still auto-loots, and a Shift pressed after +/// a plain click does not. +#[test] +fn the_click_not_the_answer_decides_the_auto_loot() { + for shift_at_click in [true, false] { + let mut c = client(); + c.shift(shift_at_click); + c.right_click_body(BODY_A); + assert!(matches!( + c.sent()[..], + [ClientCommand::Loot { guid: BODY_A }] + )); + assert_eq!(c.byte(), shift_at_click, "stored at the click"); + c.shift(!shift_at_click); + c.respond(BODY_A, vec![linen(0)]); + let swept = matches!(c.sent()[..], [ClientCommand::AutostoreLootItem { slot: 0 }]); + assert_eq!( + swept, shift_at_click, + "Shift at the click: {shift_at_click}" + ); + } +} + +/// A Shift-click on a second body with a window open: `SetAutoLoot(1)` sweeps the open window at +/// once (`0x5df470` β†’ `0x5df480`), and `LootUnit` stops at `CanLootNow`, the target being held +/// (`0x5df2c1` β†’ `0x5ec1f6`): the open window's row goes, the second body is not looted. +#[test] +fn a_shift_click_with_a_window_open_sweeps_it_and_loots_nothing_else() { + let mut c = client(); + c.looting(BODY_A, vec![linen(0)]); + c.shift(true); + c.right_click_body(BODY_B); + assert!( + matches!(c.sent()[..], [ClientCommand::AutostoreLootItem { slot: 0 }]), + "the sweep of the open window, and no CMSG_LOOT" + ); + assert_eq!(c.seen(), "LOOT_OPENED", "the sweep's end (`0x4c2240`)"); + assert!(!c.byte(), "the sweep cleared it (`0x4c2219`)"); +} + +/// A sweep that finds nothing left closes the window with release (`0x4c224f`), which drops the +/// target (`0x48f2c9`), so the click's `LootUnit` goes on; the byte the sweep cleared opens the +/// second window plain. +#[test] +fn a_shift_click_over_an_empty_window_closes_it_then_loots_plain() { + let mut c = client(); + c.looting(BODY_A, Vec::new()); + c.shift(true); + c.right_click_body(BODY_B); + assert!( + matches!( + c.sent()[..], + [ + ClientCommand::LootRelease { guid: BODY_A }, + ClientCommand::Loot { guid: BODY_B } + ] + ), + "the close, then the loot" + ); + assert_eq!(c.seen(), "LOOT_CLOSED"); + c.respond(BODY_B, vec![linen(0)]); + assert!(c.sent().is_empty(), "no sweep"); + assert_eq!(c.seen(), "LOOT_OPENED"); +} + +/// `CanLootNow` refuses while any loot target is held, this body's own included (`0x5ec1f4`, +/// `0x5ec1f6`): a plain click on either body sends nothing. +#[test] +fn a_loot_click_with_a_window_open_sends_nothing() { + for guid in [BODY_B, BODY_A] { + let mut c = client(); + c.looting(BODY_A, vec![linen(0)]); + c.right_click_body(guid); + assert!(c.sent().is_empty(), "{guid:#x}"); + } +} + +/// The game object's interaction stores the byte when its handler allows it (`0x5f869f`), before +/// the use (`0x5f86a6`): alone, the byte waits for the chest's answer; with a window open, the +/// sweep's stores go out ahead of the use, and the sweep clears the byte. +#[test] +fn a_shift_click_on_a_chest_stores_the_byte_before_the_use() { + let mut c = client(); + c.shift(true); + c.right_click_chest(); + assert!(matches!( + c.sent()[..], + [ClientCommand::GameObjUse { guid: CHEST }] + )); + assert!(c.byte()); + + let mut c = client(); + c.looting(BODY_A, vec![linen(0)]); + c.shift(true); + c.right_click_chest(); + assert!( + matches!( + c.sent()[..], + [ + ClientCommand::AutostoreLootItem { slot: 0 }, + ClientCommand::GameObjUse { guid: CHEST } + ] + ), + "the sweep, then the use" + ); + assert!(!c.byte()); +} + +/// The skin leg's `InteractWithSpell` casts (`0x5f06dc`), then stores the byte (`0x5f06e1`- +/// `0x5f06ef`, its `set` given by the leg, `0x60c06e`): alone, the byte waits for the skinning's +/// loot; with a window open, the cast goes out ahead of the sweep's stores. +#[test] +fn a_shift_skin_casts_then_stores_the_byte() { + let mut c = client(); + c.shift(true); + c.right_click_body(HIDE); + c.drain_casts(); + assert!(c.byte()); + + let mut c = client(); + c.looting(BODY_A, vec![linen(0)]); + c.shift(true); + c.right_click_body(HIDE); + c.drain_casts(); + let sent: Vec = + c.rx.try_iter() + .filter(|c| { + matches!( + c, + ClientCommand::CastSpell { .. } | ClientCommand::AutostoreLootItem { .. } + ) + }) + .collect(); + assert!( + matches!( + sent[..], + [ + ClientCommand::CastSpell { + spell_id: SKINNING, + .. + }, + ClientCommand::AutostoreLootItem { slot: 0 } + ] + ), + "the cast, then the sweep: {sent:?}" + ); +} + +/// The corpse leg stores the byte (`0x5d6c68`) before `LootCorpse` asks `CanLootNow` +/// (`0x5df151` β†’ `0x5ec110`): a Shift-click whose sweep closes an empty window has dropped the +/// target (`0x4c224f` β†’ `0x48f2c9`), so the corpse is looted, though the cursor was grey at the +/// press. +#[test] +fn a_shift_click_on_a_corpse_over_an_empty_window_loots_it() { + let mut c = client(); + c.looting(BODY_A, Vec::new()); + c.shift(true); + c.right_click_bones(true); + let sent = c.sent(); + assert!( + matches!( + sent[..], + [ + ClientCommand::LootRelease { guid: BODY_A }, + ClientCommand::Loot { guid: BONES } + ] + ), + "the close, then the loot: {sent:?}" + ); + + // With the window's row left, the sweep keeps it open and the corpse is refused. + let mut c = client(); + c.looting(BODY_A, vec![linen(0)]); + c.shift(true); + c.right_click_bones(true); + assert!(matches!( + c.sent()[..], + [ClientCommand::AutostoreLootItem { slot: 0 }] + )); +} + +/// The loot cursor grays over a lootable body or corpse while another loot is held (`0x4824fe`, +/// `0x4827d7` β†’ `0x5ec110`), and stays lit over the one being looted (`0x48250a`, `0x4827e3`). +#[test] +fn the_loot_cursor_lights_only_over_the_object_being_looted() { + let mut c = client(); + let unable = |c: &mut Client, guid: u64| { + let hovered = Hovered { + target: Some(c.entity(guid)), + guid: Some(guid), + distance: 2.0, + ..Hovered::default() + }; + c.app + .world_mut() + .run_system_once(move |inputs: cursor_mode::CursorInputs| { + cursor_mode::classify(&inputs, &hovered, &HoveredObject::default()) + .0 + .unable + }) + .unwrap() + }; + assert!(!unable(&mut c, BODY_B), "nothing held"); + c.looting(BODY_A, vec![linen(0)]); + assert!(unable(&mut c, BODY_B), "another loot held"); + assert!(!unable(&mut c, BODY_A), "the one being looted"); +} diff --git a/crates/benilla-app/src/target/cursor_mode.rs b/crates/benilla-app/src/target/cursor_mode.rs index 44a428832..8e6c50b98 100644 --- a/crates/benilla-app/src/target/cursor_mode.rs +++ b/crates/benilla-app/src/target/cursor_mode.rs @@ -540,6 +540,9 @@ struct CorpseFacts { skin_latch: bool, /// `d2`, centre to centre. dist_sq: f32, + /// Any loot target held (`[player+0x1d28/2c]` nonzero), which `CanLootNow` refuses + /// (`0x5ec1f6`). + loot_held: bool, /// The already-looting override: `[player+0x1d28/2c] == corpse GUID`. looting_this: bool, /// `CanAutoInteract`, which `CanLootNow` asks first and then skips its range (`0x5ec11b`). @@ -550,10 +553,13 @@ struct CorpseFacts { } fn corpse_cursor(f: CorpseFacts) -> Option<(CursorKind, bool)> { - // Leg 1, lootable: able within `CanLootNow 0x5ec110`'s reach or while this corpse's loot - // window is open; Pickup or LootAll by key 0 (`0x41f8f0` at `0x4827f8`), grayed at `0x482818`. + // Leg 1, lootable: able where `CanLootNow 0x5ec110` allows (`0x4827d7`), its reach and no loot + // target held, or while this corpse's loot window is open (`0x4827e3`); Pickup or LootAll by + // key 0 (`0x41f8f0` at `0x4827f8`), grayed at `0x482818`. if f.lootable { - let able = f.can_auto_interact || f.dist_sq <= CORPSE_INTERACT_RANGE_SQ || f.looting_this; + let can_loot_now = + !f.loot_held && (f.can_auto_interact || f.dist_sq <= CORPSE_INTERACT_RANGE_SQ); + let able = can_loot_now || f.looting_this; return Some((loot_cursor(f.auto_loot, f.shift_held), !able)); } // Leg 2, the PvP insignia (`0x482875..0x4828a2`), inert in 1.12.1 as no player holds a @@ -716,12 +722,15 @@ pub(super) fn classify( let dead = store.0.unit_is_dead(); if dead { if store.0.unit_lootable() { - // Grayed by `CanLootNow 0x5ec110`'s melee reach; the reference's mid-loot state - // block and open-loot-window override are not applied to units. + // Lit where `CanLootNow 0x5ec110` allows (`0x4824fe`), its melee reach and no loot + // target held, or over the unit being looted (`0x48250a`). let shift = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight); + let held = loot_latch.0; + let can_loot_now = held.is_none() && (can_auto_interact || in_melee); + let looting_this = held.is_some() && held == hovered.guid; return Some(( loot_cursor(loot_cfg.auto_loot, shift), - !(can_auto_interact || in_melee), + !(can_loot_now || looting_this), )); } // Skin also needs the learn latch `[0xb700e4 + 4Γ—isPlayerTarget]` (`0x482589`): a @@ -763,6 +772,7 @@ pub(super) fn classify( insignia: store.0.corpse_pvp_insignia(), skin_latch: learned.skin_player_corpse.is_some(), dist_sq: corpse_tf.translation.distance_squared(self_tf.translation), + loot_held: loot_latch.0.is_some(), looting_this: loot_latch.0.is_some() && loot_latch.0 == hovered.corpse_guid, can_auto_interact, auto_loot: loot_cfg.auto_loot, diff --git a/crates/benilla-app/src/ui_action/drain.rs b/crates/benilla-app/src/ui_action/drain.rs index 8bd5b3128..ade5d99a3 100644 --- a/crates/benilla-app/src/ui_action/drain.rs +++ b/crates/benilla-app/src/ui_action/drain.rs @@ -175,6 +175,7 @@ pub(crate) fn drain_click_casts( spell_id, entity, guid, + auto_loot, } => { debug!("ui_action: right-click casts {spell_id} at {guid:#x}"); ladder.send( @@ -182,6 +183,10 @@ pub(crate) fn drain_click_casts( &targeting.context_at(entity, guid), crate::spell::CastCommit::Spell, ); + // Then the store, whatever the attempt answered (`0x5f06e1`-`0x5f06ef`). + if let (Some(byte), Some(script)) = (auto_loot, script.as_deref_mut()) { + script.set_auto_loot(byte); + } } // The key goes through the shared `CGItem::Use` fork, as a bag click does. super::ClickCast::Key(it) => { diff --git a/crates/benilla-app/src/ui_action/mod.rs b/crates/benilla-app/src/ui_action/mod.rs index 62d048ffb..fc8a007d2 100644 --- a/crates/benilla-app/src/ui_action/mod.rs +++ b/crates/benilla-app/src/ui_action/mod.rs @@ -112,6 +112,9 @@ pub(crate) enum ClickCast { spell_id: u32, entity: Entity, guid: u64, + /// The byte `InteractWithSpell` passes `SetAutoLoot` after the cast, its `set` given + /// (`0x5f06e1`-`0x5f06ef`). + auto_loot: Option, }, } diff --git a/crates/benilla-app/src/ui_items/drain.rs b/crates/benilla-app/src/ui_items/drain.rs index 1fa686650..d7ec39c3f 100644 --- a/crates/benilla-app/src/ui_items/drain.rs +++ b/crates/benilla-app/src/ui_items/drain.rs @@ -145,8 +145,7 @@ pub(crate) struct ScriptItemUse<'w, 's> { equip_sound: MessageWriter<'w, crate::sound::AutoEquipSound>, item_text: ResMut<'w, crate::ui_item_text::ItemTextOpen>, targeting: crate::spell::cast_target::CastTargeting<'w, 's>, - // The loot latch the open arm sets, so `SMSG_LOOT_RESPONSE` admits an item loot, is the - // ladder's (`CastLadder::loot_latch`). + // The item use's casts and sends. ladder: crate::spell::CastLadder<'w, 's>, ui_errors: Res<'w, crate::ui_action::UiErrorKeys>, gate: crate::ui_bind_confirm::BindGate<'w>, @@ -212,8 +211,13 @@ impl ScriptItemUse<'_, '_> { } /// `UseContainerItem(bag, slot)` outside repair mode: the arm the call took, sent. The call - /// chose it and took its lock ([`benilla_ui::script::UseArm`]), so this only sends. - pub(crate) fn use_container_item(&mut self, script: &mut UiScript, call: ContainerUse) { + /// chose it and took its lock ([`benilla_ui::script::UseArm`]), so this only sends; an item + /// that opens is handed back for the loot window's `OpenItem` ([`crate::ui_loot::OpenItem`]). + pub(crate) fn use_container_item( + &mut self, + script: &mut UiScript, + call: ContainerUse, + ) -> Option { let Self { self_q, merchant, @@ -246,7 +250,7 @@ impl ScriptItemUse<'_, '_> { guid: item_guid, }, ); - return; + return None; } let slot0 = u8::try_from(slot.saturating_sub(1)).ok(); // The slot must still hold the item the call resolved (`0x4fa1a6`). The reference sends @@ -265,7 +269,7 @@ impl ScriptItemUse<'_, '_> { if arm_locked(arm) { script.unlock_item(item_guid); } - return; + return None; }; let fork = match arm { UseArm::Withdraw => { @@ -274,7 +278,7 @@ impl ScriptItemUse<'_, '_> { bag: bag_index, slot: wire_slot, }); - return; + return None; } UseArm::Deposit => { debug!("ui_items: deposit (lua bag {bag} β†’ wire {bag_index}/{wire_slot})"); @@ -282,14 +286,14 @@ impl ScriptItemUse<'_, '_> { bag: bag_index, slot: wire_slot, }); - return; + return None; } // The whole stack sells (`CMSG_SELL_ITEM`, count 0). UseArm::Sell => { let Some(vendor) = merchant.vendor else { debug!("ui_items: sale of {item_guid:#x} with no vendor open β€” let go"); script.unlock_item(item_guid); - return; + return None; }; debug!("ui_items: sell lua bag {bag} slot {slot} (item {item_guid:#x})"); let _ = ladder.commands.0.send(ClientCommand::SellItem { @@ -297,7 +301,7 @@ impl ScriptItemUse<'_, '_> { item_guid, count: 0, }); - return; + return None; } UseArm::Item(fork) => fork, }; @@ -400,21 +404,18 @@ impl ScriptItemUse<'_, '_> { ); } } - // The server answers with a loot window on the item (`SpellHandler.cpp:227`). The send - // tests neither the lock id nor the unlocked bit, so a locked box sends and the - // server's `EQUIP_ERR_ITEM_LOCKED` is the "Item is locked" line. The loot latch on the - // item's guid goes up before the send (`0x5edcc0`), as the call's lock did - // (`0x5edcd9`); the admission gate refuses the type-1 `SMSG_LOOT_RESPONSE` without it. - // No kneel (`0x612710`). + // `OpenItem 0x5edc80`, whose auto-loot byte, loot target and send are the loot + // window's. The server answers with a loot window on the item + // (`SpellHandler.cpp:227`). The send tests neither the lock id nor the unlocked bit, + // so a locked box sends and the server's `EQUIP_ERR_ITEM_LOCKED` is the "Item is + // locked" line. No kneel (`0x612710`). (UseFork::Open, Some(c)) => { debug!( "ui_items: open item {:#x} (lua bag {bag} β†’ wire {bag_index}/{wire_slot})", c.guid ); - if let Some(latch) = ladder.loot_latch.as_deref_mut() { - latch.0 = Some(c.guid); - } - let _ = ladder.commands.0.send(ClientCommand::OpenItem { + return Some(crate::ui_loot::OpenItem { + guid: c.guid, bag_index, slot: wire_slot, }); @@ -427,7 +428,7 @@ impl ScriptItemUse<'_, '_> { if arm_locked(arm) { script.unlock_item(item_guid); } - return; + return None; } debug!("ui_items: use item (lua bag {bag} β†’ wire {bag_index}/{wire_slot})"); super::send_item_use( @@ -451,6 +452,7 @@ impl ScriptItemUse<'_, '_> { ); } } + None } } @@ -459,10 +461,7 @@ impl ScriptItemUse<'_, '_> { fn arm_locked(arm: UseArm) -> bool { matches!( arm, - UseArm::Withdraw - | UseArm::Deposit - | UseArm::Sell - | UseArm::Item(UseFork::Equip | UseFork::Open) + UseArm::Withdraw | UseArm::Deposit | UseArm::Sell | UseArm::Item(UseFork::Equip) ) } @@ -765,19 +764,23 @@ pub(super) fn drain_container_destroys( } /// The bag clicks of a harness's VM ([`UiScript::keep_calls`]): the repair-mode drain, then the -/// kept `UseContainerItem` calls through their applier, as the app's host applies each inside its -/// verb. +/// kept `UseContainerItem` calls through their applier and an open through the loot window's, as +/// the app's host applies each inside its verb. #[cfg(test)] fn run_container_clicks(world: &mut World) { use benilla_ui::script::ScriptCall; - use bevy::ecs::system::RunSystemOnce; + use bevy::ecs::system::{ParamSet, RunSystemOnce}; + crate::ui_loot::seat_loot_steps(world); world.run_system_once(drain_container_repairs).unwrap(); world .run_system_once( - |mut script: NonSendMut, mut items: ScriptItemUse| { + |mut script: NonSendMut, + mut set: ParamSet<(ScriptItemUse, crate::ui_loot::LootSteps)>| { for call in script.take_script_calls() { if let ScriptCall::UseContainerItem(call) = call { - items.use_container_item(&mut script, call); + if let Some(open) = set.p0().use_container_item(&mut script, call) { + let _ = set.p1().open_item(&mut script, open); + } } } }, @@ -808,6 +811,14 @@ mod tests { /// Right-clicks backpack slot 1, holding a lootable template, and runs the click dispatcher. fn open_the_clam() -> (App, crossbeam_channel::Receiver) { + open_the_clam_with(false, |_| {}) + } + + /// [`open_the_clam`] with Shift held as `shift` says, after `setup`. + fn open_the_clam_with( + shift: bool, + setup: impl FnOnce(&mut App), + ) -> (App, crossbeam_channel::Receiver) { let (tx, rx) = crossbeam_channel::unbounded(); let mut app = App::new(); app.add_message::() @@ -848,11 +859,12 @@ mod tests { (F_PACK_SLOT_1 + 1, (CLAM >> 32) as u32), ])), )); - // The item object and its lootable template, so the open arm claims the click. + // The item object (`OBJECT_FIELD_TYPE` an item's) and its lootable template, so the open + // arm claims the click. crate::items::test_spawn_item( app.world_mut(), CLAM, - ObjectFields::from_pairs(&[(F_OBJECT_ENTRY, CLAM_ENTRY)]), + ObjectFields::from_pairs(&[(2, 0x3), (F_OBJECT_ENTRY, CLAM_ENTRY)]), false, ); let mut items = app.world_mut().resource_mut::(); @@ -866,6 +878,11 @@ mod tests { app.insert_non_send_resource(harness_vm()); feed_clam(&mut app); + crate::ui_loot::seat_loot_steps(app.world_mut()); + app.world_mut() + .non_send_resource_mut::() + .set_modifiers(shift, false, false); + setup(&mut app); app.world_mut() .non_send_resource_mut::() .run("UseContainerItem(0, 1)") @@ -954,6 +971,80 @@ mod tests { ); } + /// `OpenItem` stores whether Shift is down through `SetAutoLoot` (`0x5edca7`-`0x5edcb6`) before + /// it holds the item as the loot target (`0x5edcc0`), locks it (`0x5edcd9`) and sends + /// `CMSG_OPEN_ITEM`: alone the byte waits for the item's answer; with a window open on another + /// source the store sweeps it at once (`0x5df470` β†’ `0x5df480`), its rows and its + /// `LOOT_OPENED` ahead of the lock and the open. + #[test] + fn a_shift_open_stores_the_byte_and_sweeps_an_open_window_first() { + const CORPSE: u64 = 0xF130_0000_0000_00AB; + const LINEN: u32 = 2589; + let (app, rx) = open_the_clam_with(true, |_| {}); + assert!(matches!( + rx.try_iter().collect::>()[..], + [ClientCommand::OpenItem { .. }] + )); + assert!(app.world().resource::().0); + + let (app, rx) = open_the_clam_with(true, |app| { + let corpse = app + .world_mut() + .spawn(ObjectStore(ObjectFields::from_pairs(&[(2, 0x9)]))) + .id(); + let world = app.world_mut(); + world + .resource_mut::() + .0 + .insert(CORPSE, corpse); + world + .resource_mut::() + .insert_template(LINEN, Some(crate::items::test_template("Linen Cloth"))); + world.resource_mut::().open( + CORPSE, + 1, + 0, + vec![benilla_protocol::messages::LootItem { + slot: 0, + item_id: LINEN, + count: 1, + display_info_id: 0, + random_property_id: 0, + slot_type: benilla_protocol::messages::slot_type::ALLOW_LOOT, + }], + ); + world.resource_mut::().0 = Some(CORPSE); + app.world() + .non_send_resource::() + .run( + "SEEN = {} local f = CreateFrame('Frame') \ + f:RegisterEvent('LOOT_OPENED') f:RegisterEvent('ITEM_LOCK_CHANGED') \ + f:SetScript('OnEvent', function() tinsert(SEEN, event) end)", + ) + .unwrap(); + }); + let seen: String = app + .world() + .non_send_resource::() + .eval("return table.concat(SEEN, ',')") + .unwrap(); + assert_eq!( + seen, "LOOT_OPENED,ITEM_LOCK_CHANGED", + "the sweep, then the lock" + ); + let sent: Vec = rx.try_iter().collect(); + assert!( + matches!( + sent[..], + [ + ClientCommand::AutostoreLootItem { slot: 0 }, + ClientCommand::OpenItem { .. } + ] + ), + "the sweep, then the open: {sent:?}" + ); + } + /// A repair-mode right-click on a bag item: `ITEM_REPAIR` as it goes out (`0x4f9ce4`), then /// `CMSG_REPAIR_ITEM` with the vendor's and the item's guid, and no use or sale. #[test] @@ -1094,23 +1185,31 @@ mod tests { ); } - /// The open arm locks the item inside the call (`0x5edcd9`), so a second right-click in the - /// same frame stops at the lock (`0x4fa1cd`) and one `CMSG_OPEN_ITEM` goes out. + /// The open arm locks the item inside the call, past its `SetAutoLoot` (`0x5edcd9`), so a + /// second right-click in the same frame, each applied as its call returns, stops at the lock + /// (`0x4fa1cd`) and one `CMSG_OPEN_ITEM` goes out. #[test] fn two_opens_in_one_frame_send_once() { let (mut app, rx) = open_the_clam(); while rx.try_recv().is_ok() {} // drain the clam's own send - { - let mut script = app.world_mut().non_send_resource_mut::(); - script.unlock_item(CLAM); - script.run("UseContainerItem(0, 1)").unwrap(); - assert!( - script.item_locked(CLAM), - "locked in the call, before any send" - ); - script.run("UseContainerItem(0, 1)").unwrap(); - } - run_container_clicks(app.world_mut()); + let click = |app: &mut App| { + app.world_mut() + .non_send_resource_mut::() + .run("UseContainerItem(0, 1)") + .unwrap(); + run_container_clicks(app.world_mut()); + }; + app.world_mut() + .non_send_resource_mut::() + .unlock_item(CLAM); + click(&mut app); + assert!( + app.world() + .non_send_resource::() + .item_locked(CLAM), + "locked in the call, before any send" + ); + click(&mut app); assert_eq!(rx.try_iter().count(), 1); } diff --git a/crates/benilla-app/src/ui_loot/call_tests.rs b/crates/benilla-app/src/ui_loot/call_tests.rs new file mode 100644 index 000000000..96c76a905 --- /dev/null +++ b/crates/benilla-app/src/ui_loot/call_tests.rs @@ -0,0 +1,797 @@ +//! The loot window's verbs and packets through the whole client's host, each read on the line or +//! the packet after it: `LootSlot`, `CloseLoot` and `GiveMasterLoot` apply inside their calls +//! (`0x4c2e70`, `0x4c2ec0`, `0x4c2940`), a row's click takes inside its input record after its +//! `` (`0x4c1820`), the last row's removal and the coin line's clear close inside their +//! packets (`0x4c1f8d`, `0x4c2785`), the auto-loot copier sweeps before it signals (`0x4c1ed3` β†’ +//! `0x4c1fa0`), the count is the last occupied row's (`0x4c2260`), and a response for an object +//! the client lacks opens nothing (`0x5ebb3f`). + +use benilla_protocol::messages::{slot_type, ItemInfo, ItemPushResult, LootItem, ObjectFields}; +use benilla_protocol::{EntityKind, SessionEvent}; +use bevy::prelude::*; +use crossbeam_channel::Receiver; + +use benilla_ui::script::UiScript; + +use super::{AutoLootByte, LootLatch, LootState}; +use crate::items::Items; +use crate::net::{ + ClientCommand, Guid, GuidIndex, NetCommands, NetEntity, ObjectStore, SelfGuid, SelfPlayer, +}; +use crate::script_calls::with_hosted_vm; +use crate::ui_action::{UiError, UiErrorKeys}; + +/// A dead creature the object manager holds: the loot source. +pub(super) const CORPSE: u64 = 0xF130_0000_0000_00AB; +/// A guid no object carries. +pub(super) const GONE: u64 = 0xF130_0000_0000_0FFF; +pub(super) const ME: u64 = 0x10; +/// A lockbox in our bags, an item object the object manager holds. +pub(super) const LOCKBOX: u64 = 0x4000_0000_0000_0007; +/// A white, a bind-on-pickup epic, and a second white. +pub(super) const LINEN: u32 = 2589; +pub(super) const FELSTRIKER: u32 = 12590; +pub(super) const WOOL: u32 = 2592; +/// The display id the cloths share, which has an icon, so their pushes signal `ITEM_PUSH`. +const CLOTH_DISPLAY: u32 = 5; +/// A master-loot candidate. +pub(super) const THRALL: u64 = 0x22; + +pub(super) struct Loot { + pub(super) app: App, + rx: Receiver, +} + +/// The whole client, headless, holding our player, [`CORPSE`] and [`LOCKBOX`], with the three +/// templates and a VM that notes the loot events in `SEEN`, defines the loot error keys as +/// themselves and the money line's strings as the stock ones. +pub(super) fn client() -> Loot { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(NetCommands(tx)); + let world = app.world_mut(); + let me = world + .spawn(( + Guid(ME), + SelfPlayer, + NetEntity { + kind: EntityKind::Player, + display_id: None, + scale: 1.0, + }, + Transform::default(), + GlobalTransform::default(), + // `UNIT_FIELD_HEALTH` and `UNIT_FIELD_MAXHEALTH` 100. + ObjectStore(ObjectFields::from_pairs(&[(22, 100), (28, 100)])), + )) + .id(); + world.resource_mut::().0.insert(ME, me); + // `OBJECT_FIELD_TYPE` (2): `TYPEMASK_OBJECT | TYPEMASK_ITEM`. + let lockbox = world + .spawn(( + Guid(LOCKBOX), + ObjectStore(ObjectFields::from_pairs(&[(2, 0x3)])), + )) + .id(); + world.resource_mut::().0.insert(LOCKBOX, lockbox); + let corpse = world + .spawn(( + Guid(CORPSE), + NetEntity { + kind: EntityKind::Unit, + display_id: None, + scale: 1.0, + }, + Transform::default(), + GlobalTransform::default(), + // `UNIT_FIELD_HEALTH` 0, `UNIT_FIELD_MAXHEALTH` 100. + ObjectStore(ObjectFields::from_pairs(&[(22, 0), (28, 100)])), + )) + .id(); + world.resource_mut::().0.insert(CORPSE, corpse); + world.resource_mut::().0 = Some(ME); + world.insert_resource(crate::entities::ItemDisplays::icons_for_tests( + benilla_formats::ItemDisplayCatalog::from_displays(std::collections::HashMap::from([( + CLOTH_DISPLAY, + benilla_formats::ItemDisplay { + icon: Some("CLOTH".into()), + ..Default::default() + }, + )])), + )); + let mut items = world.resource_mut::(); + for (entry, name, quality, bonding) in [ + (LINEN, "Linen Cloth", 1, 0), + (FELSTRIKER, "Felstriker", 4, 1), + (WOOL, "Wool Cloth", 1, 0), + ] { + let mut t = crate::items::test_template(name); + t.display_info_id = CLOTH_DISPLAY; + items.insert_template( + entry, + Some(ItemInfo { + quality, + bonding, + ..t + }), + ); + } + let script = UiScript::new().expect("a VM"); + script + .run( + r#"ERR_LOOT_ROLL_PENDING = "ERR_LOOT_ROLL_PENDING" + ERR_LOOT_NO_UI = "ERR_LOOT_NO_UI" + ERR_LOOT_DIDNT_KILL = "ERR_LOOT_DIDNT_KILL" + YOU_LOOT_MONEY = "You loot %s" + GOLD = "Gold" SILVER = "Silver" COPPER = "Copper" + SEEN = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"LOOT_OPENED", "LOOT_SLOT_CLEARED", "LOOT_CLOSED", + "LOOT_BIND_CONFIRM", "OPEN_MASTER_LOOT_LIST", "ITEM_PUSH", + "UI_ERROR_MESSAGE", "ITEM_LOCK_CHANGED"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "LOOT_SLOT_CLEARED" or event == "LOOT_BIND_CONFIRM" + or event == "UI_ERROR_MESSAGE" then + tinsert(SEEN, event .. ":" .. tostring(arg1)) + else + tinsert(SEEN, event) + end + end) + ROW = CreateFrame("LootButton", "Row", UIParent) + ROW:SetPoint("BOTTOMLEFT", 100, 100) ROW:SetWidth(50) ROW:SetHeight(50) + ROW:EnableMouse(true)"#, + ) + .expect("the recorder installs"); + world.insert_non_send_resource(script); + Loot { app, rx } +} + +pub(super) fn row(slot: u8, entry: u32) -> LootItem { + LootItem { + slot, + item_id: entry, + count: 1, + display_info_id: CLOTH_DISPLAY, + random_property_id: 0, + slot_type: slot_type::ALLOW_LOOT, + } +} + +/// The packets, dispatched as one net drain in wire order. +pub(super) fn packets(l: &mut Loot, events: Vec) { + crate::net::handlers::dispatch(l.app.world_mut(), events); +} + +/// The answer to our `CMSG_LOOT` on `guid`, which armed the latch: the response, then the feed +/// that shows it. +pub(super) fn open(l: &mut Loot, guid: u64, loot_type: u8, gold: u32, items: Vec) { + l.app.world_mut().resource_mut::().0 = Some(guid); + packets( + l, + vec![SessionEvent::LootResponse { + guid, + loot_type, + gold, + items, + }], + ); + feed(l); +} + +pub(super) fn feed(l: &mut Loot) { + super::feed_loot_once(l.app.world_mut()); +} + +/// Run `lua` with the host lent, as every entry that runs Lua lends it. +pub(super) fn run(l: &mut Loot, lua: &str) { + with_hosted_vm(l.app.world_mut(), |s| s.expect("a VM").run(lua)).expect("the chunk runs"); +} + +pub(super) fn eval(l: &mut Loot, lua: &str) -> T { + with_hosted_vm(l.app.world_mut(), |s| s.expect("a VM").eval::(lua)).expect("the chunk runs") +} + +/// The events noted since the last read. +pub(super) fn seen(l: &mut Loot) -> String { + eval(l, "local s = table.concat(SEEN, ',') SEEN = {} return s") +} + +/// The loot packets sent since the last read, in order. +pub(super) fn sent(l: &Loot) -> Vec { + l.rx.try_iter() + .filter(|c| { + matches!( + c, + ClientCommand::AutostoreLootItem { .. } + | ClientCommand::LootMoney + | ClientCommand::LootRelease { .. } + | ClientCommand::LootMasterGive { .. } + ) + }) + .collect() +} + +/// A hardware left click on the `LootButton` slotted at `slot`, its own input record. +pub(super) fn click(l: &mut Loot, slot: u32) { + with_hosted_vm(l.app.world_mut(), |s| { + let s = s.expect("a VM"); + s.set_screen_size(1024.0, 768.0); + s.run(&format!("ROW:SetSlot({slot}) ROW:Show()")) + .expect("the row is slotted"); + s.resolve(); + s.mouse_button(125.0, 125.0, "LeftButton", true); + s.mouse_button(125.0, 125.0, "LeftButton", false); + }); +} + +/// The row click takes inside its input record, after its `` (`0x4c1820` β†’ `0x4c2790(slot, +/// 0)`): the send is out and the bind confirm signalled when the click returns, and a `LootSlot` in +/// the confirm's own handler finds no stash (`0x4c290f` before `0x4c2917`). +#[test] +fn a_rows_click_takes_inside_its_input_record() { + let mut l = client(); + open( + &mut l, + CORPSE, + 1, + 0, + vec![row(3, LINEN), row(4, FELSTRIKER)], + ); + assert_eq!(seen(&mut l), "LOOT_OPENED"); + let _ = sent(&l); + + click(&mut l, 1); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 3 }]), + "the white's store is out as the click returns" + ); + + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_BIND_CONFIRM") + f:SetScript("OnEvent", function() LootSlot(arg1) end)"#, + ); + click(&mut l, 2); + assert_eq!( + seen(&mut l), + "LOOT_BIND_CONFIRM:2", + "the confirm is signalled inside the click" + ); + assert!(sent(&l).is_empty(), "its handler's accept finds no stash"); + run(&mut l, "LootSlot(2)"); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 4 }]), + "an accept after the click sends the row (`0x4c27c0`)" + ); +} + +/// The coin row's click (`0x4c2826`-`0x4c287c`): `CMSG_LOOT_MONEY`, the money cell at -1 and +/// `LOOT_SLOT_CLEARED` 1 inside the click, and with nothing else left the close with release. +#[test] +fn the_coin_rows_click_clears_it_and_closes_an_emptied_window() { + let mut l = client(); + open(&mut l, CORPSE, 1, 150, vec![row(0, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + click(&mut l, 1); + assert!(matches!(sent(&l)[..], [ClientCommand::LootMoney])); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1"); + assert!( + eval::(&mut l, "return GetLootSlotInfo(1) == nil"), + "the coin row is a gap at once" + ); + + let mut l = client(); + open(&mut l, CORPSE, 1, 150, Vec::new()); + let _ = (seen(&mut l), sent(&l)); + click(&mut l, 1); + assert!( + matches!( + sent(&l)[..], + [ + ClientCommand::LootMoney, + ClientCommand::LootRelease { guid: CORPSE } + ] + ), + "the last row's click releases the loot inside it (`0x4c286a` β†’ `0x48f200`)" + ); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1,LOOT_CLOSED"); +} + +/// A roll-pending row refuses inside the click (`0x4c28b3`, `ERR_LOOT_ROLL_PENDING`), and a +/// master-loot row signals `OPEN_MASTER_LOOT_LIST` there (`0x4c28d1`); neither sends. +#[test] +fn a_roll_or_master_rows_click_answers_inside_it() { + let mut l = client(); + let mut rolling = row(0, LINEN); + rolling.slot_type = slot_type::ROLL_ONGOING; + let mut master = row(1, WOOL); + master.slot_type = slot_type::MASTER; + open(&mut l, CORPSE, 1, 0, vec![rolling, master]); + let _ = (seen(&mut l), sent(&l)); + click(&mut l, 1); + assert_eq!(seen(&mut l), "UI_ERROR_MESSAGE:ERR_LOOT_ROLL_PENDING"); + click(&mut l, 2); + assert_eq!(seen(&mut l), "OPEN_MASTER_LOOT_LIST"); + assert!(sent(&l).is_empty()); +} + +/// `CloseLoot` closes inside its call (`0x4c2ec0` β†’ `0x48f200` β†’ `0x4c1cb0`): the release is out, +/// `LOOT_CLOSED` has run and the window reads closed on the next line. +#[test] +fn close_loot_closes_inside_its_call() { + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + run(&mut l, "CloseLoot() N = GetNumLootItems()"); + assert!(matches!( + sent(&l)[..], + [ClientCommand::LootRelease { guid: CORPSE }] + )); + assert_eq!(seen(&mut l), "LOOT_CLOSED"); + assert_eq!(eval::(&mut l, "return N"), 0); +} + +/// The verbs apply in call order. `GiveMasterLoot` after `CloseLoot` finds no source +/// (`0x4c2946`-`0x4c2953`); `LootSlot` after it still answers the pending row, which the close +/// keeps (`0x48f200` and `0x4c1cb0(0)` leave `0x847cec` and the rows alone), and sends after the +/// release. +#[test] +fn the_verbs_after_a_close_apply_after_it() { + let mut l = client(); + let mut master = row(2, LINEN); + master.slot_type = slot_type::MASTER; + packets( + &mut l, + vec![SessionEvent::LootMasterList { + candidates: vec![THRALL], + }], + ); + open(&mut l, CORPSE, 1, 0, vec![master]); + let _ = sent(&l); + run(&mut l, "CloseLoot() GiveMasterLoot(1, 1)"); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootRelease { guid: CORPSE }]), + "no give after the close" + ); + + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(4, FELSTRIKER)]); + click(&mut l, 1); + let _ = sent(&l); + run(&mut l, "CloseLoot() LootSlot(1)"); + assert!( + matches!( + sent(&l)[..], + [ + ClientCommand::LootRelease { guid: CORPSE }, + ClientCommand::AutostoreLootItem { slot: 4 } + ] + ), + "the release, then the pending row's store" + ); +} + +/// The last row's `SMSG_LOOT_REMOVED` closes inside its packet (`0x4c1f7f`, `0x4c1f8d`): the +/// release goes out at the packet, and `LOOT_CLOSED` comes after its `LOOT_SLOT_CLEARED` and before +/// the `ITEM_PUSH` vmangos sends after it (`LootHandler.cpp:217-230`). +#[test] +fn the_last_rows_removal_closes_before_its_push() { + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + packets( + &mut l, + vec![ + SessionEvent::LootRemoved { slot: 0 }, + SessionEvent::ItemPushResult(ItemPushResult { + player_guid: ME, + from_npc: false, + created: false, + show_in_chat: true, + bag_slot: benilla_protocol::messages::BAG_PLAYER_INVENTORY, + item_slot: 23, + item_entry: LINEN, + suffix_factor: 0, + random_property_id: 0, + count: 1, + }), + ], + ); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootRelease { guid: CORPSE }]), + "released at the packet" + ); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1,LOOT_CLOSED,ITEM_PUSH"); +} + +/// With the byte the interaction stored set (`0x5df468`), the copier sweeps first (`0x4c1ec7`, +/// `0x4c1ed3` β†’ `0x4c1fa0`): the stores and the bind confirm, then `LOOT_OPENED` while anything is +/// left (`0x4c2240`), sent rows included; an empty window closes with release instead +/// (`0x4c224f`) and never signals it. The response reads the stored byte, never the keys. +#[test] +fn an_auto_loot_open_sweeps_before_it_signals() { + let mut l = client(); + l.app.world_mut().resource_mut::().0 = true; + open( + &mut l, + CORPSE, + 1, + 0, + vec![row(5, FELSTRIKER), row(6, LINEN)], + ); + assert!(matches!( + sent(&l)[..], + [ClientCommand::AutostoreLootItem { slot: 6 }] + )); + assert_eq!(seen(&mut l), "LOOT_BIND_CONFIRM:1,LOOT_OPENED"); + run(&mut l, "LootSlot(1)"); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 5 }]), + "the sweep stashed the confirmed row after its listeners (`0x4c21dc`)" + ); + + let mut l = client(); + l.app.world_mut().resource_mut::().0 = true; + open(&mut l, CORPSE, 1, 0, Vec::new()); + assert!(matches!( + sent(&l)[..], + [ClientCommand::LootRelease { guid: CORPSE }] + )); + assert_eq!(seen(&mut l), "LOOT_CLOSED"); + + let mut l = client(); + open(&mut l, CORPSE, 1, 0, Vec::new()); + assert!(sent(&l).is_empty(), "without the byte nothing closes it"); + assert_eq!(seen(&mut l), "LOOT_OPENED", "`0x4c1ee6` signals it empty"); +} + +/// `SMSG_LOOT_CLEAR_MONEY` (`0x5ec030` β†’ `0x4c2750`) on a window with nothing else left closes +/// with release inside its packet (`0x4c2777`, `0x4c2785`), after its `LOOT_SLOT_CLEARED` 1. +#[test] +fn the_coin_lines_clear_closes_an_emptied_window_at_its_packet() { + let mut l = client(); + open(&mut l, CORPSE, 1, 150, Vec::new()); + let _ = (seen(&mut l), sent(&l)); + packets(&mut l, vec![SessionEvent::LootClearMoney]); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootRelease { guid: CORPSE }]), + "released at the packet" + ); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1,LOOT_CLOSED"); +} + +/// `GetNumLootItems` (`0x4c2c30` β†’ `0x4c2260`): the last occupied row's position plus one, plus +/// one while the money cell is nonzero, a taken coin's -1 included. +#[test] +fn the_count_is_the_last_occupied_rows() { + let mut l = client(); + open(&mut l, CORPSE, 1, 5, vec![row(0, LINEN), row(1, WOOL)]); + let count = |l: &mut Loot| eval::(l, "return GetNumLootItems()"); + assert_eq!(count(&mut l), 3); + packets(&mut l, vec![SessionEvent::LootRemoved { slot: 1 }]); + feed(&mut l); + assert_eq!(count(&mut l), 2, "the last row taken"); + packets(&mut l, vec![SessionEvent::LootClearMoney]); + feed(&mut l); + assert_eq!(count(&mut l), 2, "a taken coin still counts"); + + let mut l = client(); + open(&mut l, CORPSE, 1, 5, vec![row(0, LINEN), row(1, WOOL)]); + packets( + &mut l, + vec![ + SessionEvent::LootRemoved { slot: 0 }, + SessionEvent::LootRemoved { slot: 1 }, + ], + ); + feed(&mut l); + assert_eq!(count(&mut l), 1, "the coin alone"); +} + +/// A response for an object the client does not hold shows `ERR_LOOT_DIDNT_KILL` and returns +/// (`0x5ebb33`-`0x5ebb57`), before the latch (`0x5ebb60`) and the open. +#[test] +fn a_response_for_an_object_we_lack_opens_nothing() { + let mut l = client(); + // A fishing answer on a cold latch, whose bobber is gone. + packets( + &mut l, + vec![SessionEvent::LootResponse { + guid: GONE, + loot_type: 3, + gold: 0, + items: vec![row(0, LINEN)], + }], + ); + feed(&mut l); + let world = l.app.world(); + assert_eq!(world.resource::().source(), None); + assert_eq!(world.resource::().0, None, "no latch written"); + assert!(world + .resource::() + .snapshot() + .contains(&UiError::key("ERR_LOOT_DIDNT_KILL"))); + assert_eq!(seen(&mut l), ""); +} + +/// `CloseLoot` on a disenchant window with rows left sweeps it (`0x48f264` β†’ `0x4c1fa0` with the +/// close's flag), and the sweep's tail signals `LOOT_OPENED` for a flag of 0 while rows are left +/// (`0x4c2237`, `0x4c2240`), so the window the close hid comes back. +#[test] +fn close_loot_on_a_disenchant_window_sweeps_and_reopens_it() { + let mut l = client(); + open(&mut l, CORPSE, 4, 0, vec![row(1, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + run(&mut l, "CloseLoot()"); + assert!(matches!( + sent(&l)[..], + [ClientCommand::AutostoreLootItem { slot: 1 }] + )); + assert_eq!(seen(&mut l), "LOOT_OPENED"); + run(&mut l, "CloseLoot(1)"); + assert_eq!(seen(&mut l), "", "a flag of 1 signals nothing (`0x4c2237`)"); +} + +/// A response that replaces the open window ends its session first (`0x4c1cb0`: `LOOT_CLOSED` at +/// `0x4c1dac` for a session open), then opens the new one. +#[test] +fn a_response_over_an_open_window_closes_it_first() { + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + let _ = seen(&mut l); + open(&mut l, CORPSE, 1, 0, vec![row(0, WOOL)]); + assert_eq!(seen(&mut l), "LOOT_CLOSED,LOOT_OPENED"); +} + +/// `IsFishingLoot` (`0x4c2740`) reads the type cell `0xb71bbc` with no guard, and a close leaves +/// it (`0x48f200` β†’ `0x4c1cb0(0)` zeroes only the source, `0x4c1da0`): after the close it still +/// answers the last window's type. +#[test] +fn is_fishing_loot_reads_the_last_windows_type_after_its_close() { + let mut l = client(); + // A fishing answer (type 3), which a cold latch admits (`0x5eb953`). + packets( + &mut l, + vec![SessionEvent::LootResponse { + guid: CORPSE, + loot_type: 3, + gold: 0, + items: vec![row(0, LINEN)], + }], + ); + feed(&mut l); + let fishing = |l: &mut Loot| eval::(l, "return IsFishingLoot() == 1"); + assert!(fishing(&mut l)); + run(&mut l, "CloseLoot()"); + assert!(fishing(&mut l), "the type cell outlives the close"); + feed(&mut l); + assert!(fishing(&mut l), "and the next frame's feed"); +} + +/// `SMSG_LOOT_CLEAR_MONEY` tests no latch (`0x5ec030` β†’ `0x4c2750`), and the close keeps the money +/// cell, so a clear that lands after the close still takes the coin row and signals +/// `LOOT_SLOT_CLEARED` 1 (`0x4c2765`, `0x4c276f`); the close it then asks for finds no window +/// (`0x4c2785` β†’ `0x48f23f`) and sends nothing. +#[test] +fn a_coin_clear_after_the_close_still_signals_its_row() { + let mut l = client(); + open(&mut l, CORPSE, 1, 150, vec![row(0, LINEN)]); + run(&mut l, "CloseLoot()"); + let _ = (seen(&mut l), sent(&l)); + packets(&mut l, vec![SessionEvent::LootClearMoney]); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1"); + assert!(sent(&l).is_empty()); +} + +/// `CloseLoot(1)` on a lockbox's window (`0x48f200`): `ERR_LOOT_NO_UI` first (`0x48f27b`), then +/// the close's unlock (`0x48f2bd`) and the teardown's (`0x4c1d36`), then `LOOT_CLOSED` +/// (`0x4c1dac`). +#[test] +fn close_loot_failed_shows_its_line_before_the_teardown() { + let mut l = client(); + open(&mut l, LOCKBOX, 1, 0, vec![row(0, LINEN)]); + let _ = seen(&mut l); + run(&mut l, "CloseLoot(1)"); + assert_eq!( + seen(&mut l), + "UI_ERROR_MESSAGE:ERR_LOOT_NO_UI,ITEM_LOCK_CHANGED,ITEM_LOCK_CHANGED,LOOT_CLOSED" + ); +} + +/// The last row's removal on a lockbox (`0x4c1f00`): `LOOT_SLOT_CLEARED` (`0x4c1f77`), then the +/// close it asks for (`0x4c1f8d` β†’ `0x48f200`) with its two unlocks (`0x48f2bd`, `0x4c1d36`) and +/// `LOOT_CLOSED` (`0x4c1dac`), all inside the packet. +#[test] +fn a_lockboxs_last_row_signals_its_unlocks_between_the_clear_and_the_close() { + let mut l = client(); + open(&mut l, LOCKBOX, 1, 0, vec![row(0, LINEN)]); + let _ = seen(&mut l); + packets(&mut l, vec![SessionEvent::LootRemoved { slot: 0 }]); + feed(&mut l); + assert_eq!( + seen(&mut l), + "LOOT_SLOT_CLEARED:1,ITEM_LOCK_CHANGED,ITEM_LOCK_CHANGED,LOOT_CLOSED" + ); + assert!( + !l.app.world().resource::().owes_unlocks(), + "signalled in their place, none left for the inventory pass" + ); +} + +/// A refusal (`loot_type` 0) whose guid is not the held loot target goes to `0x5eb963`: no line, +/// the target cleared (`0x5eb9d2`) and `UnlockItem` on the refused guid (`0x5eb9de`). With no +/// target held it takes the same leg (`0x5eb944`). +#[test] +fn a_refusal_for_another_session_shows_nothing_and_drops_the_target() { + use benilla_protocol::messages::loot_error; + for held in [Some(CORPSE), None] { + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + l.app.world_mut().resource_mut::().0 = held; + packets( + &mut l, + vec![SessionEvent::LootError { + guid: GONE, + error: loot_error::TOO_FAR, + }], + ); + let world = l.app.world(); + assert!( + world.resource::().snapshot().is_empty(), + "held {held:?}: no line" + ); + assert_eq!(world.resource::().0, None, "held {held:?}"); + assert!( + world.resource::().owes_unlocks(), + "held {held:?}" + ); + } +} + +/// A response over an open window runs its copier's teardown first (`0x4c1cb0`): the source is +/// zeroed (`0x4c1da0`) and `LOOT_CLOSED` signalled (`0x4c1dac`) before the new source is stored +/// (`0x4c1dc2`), so a `CloseLoot` in its handlers finds no window (`0x48f23f`) and releases +/// nothing; the new window opens. +#[test] +fn a_replacing_responses_close_finds_no_window() { + let mut l = client(); + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_CLOSED") + f:SetScript("OnEvent", function() CloseLoot() end)"#, + ); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + open(&mut l, LOCKBOX, 1, 0, vec![row(0, WOOL)]); + assert!(sent(&l).is_empty(), "no release"); + assert_eq!(seen(&mut l), "LOOT_CLOSED,LOOT_OPENED"); + assert_eq!( + l.app.world().resource::().source(), + Some(LOCKBOX) + ); + assert_eq!(l.app.world().resource::().0, Some(LOCKBOX)); + assert_eq!( + eval::( + &mut l, + "local _, name = GetLootSlotInfo(1) return name or ''" + ), + "Wool Cloth" + ); +} + +/// The same on the stock frames: `LOOT_CLOSED` hides `LootFrame` (`LootFrame.lua:53-55`), whose +/// `OnHide` calls `CloseLoot()` (`:143-145`), which finds no window at the copier's teardown; the +/// new window's `LOOT_OPENED` shows the frame again and the lockbox's loot is kept. +#[test] +fn the_stock_frames_hide_on_a_replacing_response_releases_nothing() { + benilla_formats::wow_data_or_skip!(); + let mut l = client(); + { + let mut s = l.app.world_mut().non_send_resource_mut::(); + s.set_screen_size(1024.0, 768.0); + for f in crate::ui_script::test_ui::production_order(&[ + crate::ui_script::test_ui::LOOT_UI, + &["Interface\\FrameXML\\LootFrame.xml"], + ]) { + crate::ui_script::test_ui::load_ui(&s, f); + } + } + let shown = |l: &mut Loot| eval::(l, "return LootFrame:IsShown() == 1"); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + assert!(shown(&mut l), "the corpse's window"); + let _ = sent(&l); + open(&mut l, LOCKBOX, 1, 0, vec![row(0, WOOL)]); + assert!(sent(&l).is_empty(), "no release"); + assert!(shown(&mut l), "the lockbox's window"); + assert_eq!( + l.app.world().resource::().source(), + Some(LOCKBOX) + ); +} + +/// Each function keeps its own confirm row: a take's (`0x4c2917`) and a sweep's (`0x4c21dc`). A +/// take's `LOOT_BIND_CONFIRM` whose handler closes a disenchant window runs the sweep inside it +/// (`0x48f264` β†’ `0x4c1fa0`), which signals its own row's confirm and goes on past it; the take +/// then stores its row, which the accept sends. +#[test] +fn a_take_and_a_sweep_inside_it_keep_their_own_confirm_rows() { + let mut l = client(); + open( + &mut l, + CORPSE, + 4, + 0, + vec![row(0, FELSTRIKER), row(1, FELSTRIKER), row(2, LINEN)], + ); + let _ = (seen(&mut l), sent(&l)); + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_BIND_CONFIRM") + f:SetScript("OnEvent", function() + if arg1 == 2 and not CLOSED then CLOSED = 1 CloseLoot() end + end)"#, + ); + click(&mut l, 2); + assert_eq!( + seen(&mut l), + "LOOT_BIND_CONFIRM:2,LOOT_BIND_CONFIRM:1,LOOT_OPENED" + ); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 2 }]), + "the sweep went on past its confirm" + ); + run(&mut l, "LootSlot(1)"); + assert!(sent(&l).is_empty(), "the sweep's row is not the stash"); + run(&mut l, "LootSlot(2)"); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 1 }]), + "the take's row is" + ); +} + +/// A close and the next response in one frame: the last row's removal closes inside its own +/// packet's dispatch (`0x4c1f8d` β†’ `0x48f200`), before the response arrives, so a `CloseLoot` in +/// its `LOOT_CLOSED` handlers finds the closed window and touches nothing of the next, a +/// disenchant window the server started on a cold target (`0x5eb95b`), which opens. +#[test] +fn a_close_and_the_next_response_in_one_frame_keep_their_order() { + let mut l = client(); + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_CLOSED") + f:SetScript("OnEvent", function() CloseLoot() end)"#, + ); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + packets( + &mut l, + vec![ + SessionEvent::LootRemoved { slot: 0 }, + SessionEvent::LootResponse { + guid: LOCKBOX, + loot_type: 4, + gold: 0, + items: vec![row(0, WOOL)], + }, + ], + ); + feed(&mut l); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootRelease { guid: CORPSE }]), + "the removal's close alone" + ); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1,LOOT_CLOSED,LOOT_OPENED"); + assert_eq!( + l.app.world().resource::().source(), + Some(LOCKBOX) + ); +} diff --git a/crates/benilla-app/src/ui_loot/calls.rs b/crates/benilla-app/src/ui_loot/calls.rs new file mode 100644 index 000000000..3bf6f8d03 --- /dev/null +++ b/crates/benilla-app/src/ui_loot/calls.rs @@ -0,0 +1,442 @@ +//! The loot window's reference functions, shared by the verbs' calls and the feed's turns +//! ([`LootSteps`]): the take dispatcher `0x4c2790`, `EndLootWindow 0x48f200` with the VM at hand, +//! the auto-loot sweep `0x4c1fa0`, the interactions' `SetAutoLoot 0x5df460`, `OpenItem +//! 0x5edc80`'s send and the master-loot give `0x4c2940`. A function that signals goes +//! on once its listeners have returned (`SignalEvent` runs them in place), so what it does after +//! the signal is a [`Then`], run by the call's tail ([`UiScript::resume_loot`]) or by the feed's +//! next turn ([`super::run_then`]): the listeners read the state as the signal left it. + +use benilla_protocol::messages::{loot_type, slot_type}; +use benilla_ui::script::{CallTail, LootCall, ScriptValue, UiScript}; +use bevy::ecs::system::SystemParam; +use bevy::prelude::*; + +use super::{ + bind_confirm_required, close_interaction, show, unlock_closed_source, AutoLootByte, + DeadUnitDeselect, LootAction, LootConfig, LootLatch, LootState, +}; +use crate::items::Items; +use crate::net::{ClientCommand, NetCommands}; +use crate::ui_action::{UiError, UiErrorKeys}; +use crate::ui_party::GroupState; + +/// `OpenItem`'s item (`0x5edc80`): its guid, which becomes the loot target (`0x5edcc0`), and its +/// wire position for `CMSG_OPEN_ITEM`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct OpenItem { + pub(crate) guid: u64, + pub(crate) bag_index: u8, + pub(crate) slot: u8, +} + +/// The byte an interaction passes `SetAutoLoot`: whether Shift is down (`EventIsKeyDown(0)`, +/// `0x492879`, `0x5edca7`), inverted by `autoLootDefault` ([`LootConfig::auto_loot`]), which is +/// not a 1.12 CVar and off by default, leaving Shift alone. +pub(crate) fn interaction_byte(cfg: &LootConfig, shift: bool) -> bool { + cfg.auto_loot != shift +} + +/// What a loot function does after its signal's listeners have returned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Then { + /// The take's stash takes the row it signalled `LOOT_BIND_CONFIRM` for (`0x4c2917`), its own + /// whatever a nested function signalled meanwhile. + StoreBind { row: u32 }, + /// The sweep after its `LOOT_BIND_CONFIRM` for `row` (`0x4c21dc` on): the stash, the rows + /// after it, and its end, with the sweep's flag. + SweepRest { row: u32, flag: bool }, + /// The coin click after its `LOOT_SLOT_CLEARED` (`0x4c286a`-`0x4c287c`): the close with + /// release when nothing is left. + CloseIfEmpty, + /// A close's two unlocks (`0x48f2bd`, `0x4c1d36`), after the line its flag shows + /// (`0x48f27b`). + Unlocks, + /// A close's teardown after its unlocks' signals: the window goes and `LOOT_CLOSED` + /// (`0x4c1dac`). + Announce, + /// `OpenItem` past its `SetAutoLoot` (`0x5edcbb` on), once a sweep that made has run. + OpenItem(OpenItem), +} + +/// The loot window's state and what its functions send and signal through: the engine half of +/// the loot calls ([`crate::script_calls::ScriptCallHost`]) and of the feed's and the drain's +/// turns. +#[derive(SystemParam)] +pub(crate) struct LootSteps<'w, 's> { + pub(super) loot: ResMut<'w, LootState>, + pub(super) latch: ResMut<'w, LootLatch>, + pub(super) net: Res<'w, NetCommands>, + pub(super) dead: DeadUnitDeselect<'w, 's>, + pub(super) objects: crate::net::Objects<'w, 's>, + pub(super) byte: ResMut<'w, AutoLootByte>, + items: Res<'w, Items>, + group: Res<'w, GroupState>, + pickup: MessageWriter<'w, crate::sound::LootPickupSound>, + errors: Res<'w, UiErrorKeys>, + chat: Res<'w, crate::ui_chat::ChatLog>, + cfg: Res<'w, LootConfig>, +} + +impl LootSteps<'_, '_> { + /// Apply `call` inside its verb. What its signals' listeners leave it to do runs in its tail, + /// a call of its own once they have returned ([`LootCall::Resume`]). + pub(crate) fn apply(&mut self, script: &mut UiScript, call: LootCall) -> Option { + let mut depth = self.loot.then.len(); + match call { + LootCall::Take(row) => self.take(script, row), + LootCall::Confirm(row) => self.confirm(row), + LootCall::Close { failed } => self.end_window(script, failed), + LootCall::GiveMaster { slot, candidate } => self.give_master(slot, candidate), + LootCall::SetAutoLoot(byte) => self.set_auto_loot(script, byte), + LootCall::Resume { depth: owed } => { + depth = owed; + if self.loot.then.len() > depth { + if let Some(then) = self.loot.then.pop() { + self.then(script, then); + } + } + } + } + self.resume_tail(depth) + } + + /// The tail that runs what the call owes past `depth`, once its signals' listeners have run. + fn resume_tail(&self, depth: usize) -> Option { + (self.loot.then.len() > depth) + .then(|| Box::new(move |script: &mut UiScript| script.resume_loot(depth)) as CallTail) + } + + /// `SetAutoLoot 0x5df460(byte)`: the byte stored (`0x5df468`), and a nonzero one with the loot + /// target held sweeps the open window at once (`0x5df470` β†’ `0x5df480`). + pub(super) fn set_auto_loot(&mut self, script: &mut UiScript, byte: bool) { + self.byte.0 = byte; + if byte && self.latch.0.is_some() { + self.sweep(script, false); + } + } + + /// `OpenItem 0x5edc80` from its `SetAutoLoot` (`0x5edcb6`) on, the call having chosen the + /// item: the byte from Shift as the call saw it, which with a window open sweeps it, then, + /// once that sweep's listeners have run, the item held as the loot target, its lock and + /// `CMSG_OPEN_ITEM` ([`Self::send_open_item`]). + pub(crate) fn open_item(&mut self, script: &mut UiScript, open: OpenItem) -> Option { + let owed = self.loot.then.len(); + self.loot.then.push(Then::OpenItem(open)); + let byte = interaction_byte(&self.cfg, script.shift_key_down()); + self.set_auto_loot(script, byte); + if self.loot.then.len() == owed + 1 { + self.loot.then.pop(); + self.send_open_item(script, open); + return None; + } + self.resume_tail(owed) + } + + /// `OpenItem`'s end: the item becomes the loot target (`0x5edcc0`), which the type-1 answer's + /// admission asks for (`0x5ebb3f`), it locks (`0x5edcd9`; `LockItem` signals nothing for a + /// guid that is no item object, `0x495407`), and `CMSG_OPEN_ITEM` goes out. + fn send_open_item(&mut self, script: &mut UiScript, open: OpenItem) { + debug!("ui_loot: open item {:#x}", open.guid); + self.latch.0 = Some(open.guid); + if self.objects.object(open.guid).is_some_and(|f| f.is_item()) { + script.lock_item(open.guid); + } + let _ = self.net.0.send(ClientCommand::OpenItem { + bag_index: open.bag_index, + slot: open.slot, + }); + } + + /// `0x4c2790(slot, 0)`, a row's own click (`0x4c1867`), on the window's cells as they stand, + /// whether a window is open or not: the dispatcher asks for no source, only the active player + /// (`0x4c27ad`, `0x4c27b6`). + fn take(&mut self, script: &mut UiScript, row: u32) { + if self.objects.player().is_none() { + return; + } + match self.loot.window.action_at(row) { + Some(LootAction::Money) => { + // `CMSG_LOOT_MONEY` while the player's loot target is held (`0x4c2847` β†’ + // `0x5ea8c6`). The coin sound is the coinage watcher's (`crate::sound`). + if self.latch.0.is_some() { + let _ = self.net.0.send(ClientCommand::LootMoney); + } + // The money cell to -1 (`0x4c2858`) and `LOOT_SLOT_CLEARED` 1 (`0x4c2862`), whose + // listeners read the coin row gone. + self.loot.take_coin(); + if let Some(mut shown) = script.shown_loot() { + if shown.has_money { + if let Some(coin) = shown.rows.first_mut() { + *coin = None; + } + } + script.set_loot(Some(shown)); + } + script.fire_event("LOOT_SLOT_CLEARED", vec![ScriptValue::Int(1)]); + self.loot.then.push(Then::CloseIfEmpty); + } + // The wire's roll-pending row refuses (`0x4c28ae`-`0x4c28b8`). + Some(LootAction::Item { + slot_type: slot_type::ROLL_ONGOING, + .. + }) => self.errors.push(UiError::key("ERR_LOOT_ROLL_PENDING")), + // A master-loot row opens the candidate list (`0x4c28c4`-`0x4c28d1`), whose anchor the + // row's `` has already stashed. + Some(LootAction::Item { + slot_type: slot_type::MASTER, + .. + }) => script.fire_event("OPEN_MASTER_LOOT_LIST", vec![]), + Some(LootAction::Item { + wire_slot, + display_id, + item_id, + .. + }) => { + // Bind on pickup and uncommon or better (`0x4c28f2`, `0x4c28fb`): the confirm, + // whose listeners run before the stash takes the row (`0x4c290f`, `0x4c2917`). + if bind_confirm_required(&self.items, item_id) { + script.fire_event("LOOT_BIND_CONFIRM", vec![ScriptValue::Int(i64::from(row))]); + self.loot.then.push(Then::StoreBind { row }); + return; + } + self.store(wire_slot, display_id); + } + None => {} + } + } + + /// The item's sound and `CMSG_AUTOSTORE_LOOT_ITEM` with its wire slot (`0x4c2926`, + /// `0x4c2936`), before any answer. + fn store(&mut self, wire_slot: u8, display_id: u32) { + self.pickup + .write(crate::sound::LootPickupSound { display_id }); + let _ = self + .net + .0 + .send(ClientCommand::AutostoreLootItem { slot: wire_slot }); + } + + /// `0x4c2790(slot, 1)`, `LootSlot`: only the pending row (`0x4c27c0`), and only while it holds + /// an item (`0x4c27d9`); the send clears the stash (`0x4c281a`), so a doubled accept cannot + /// loot twice. + fn confirm(&mut self, row: u32) { + if self.objects.player().is_none() || self.loot.pending_bind_confirm != Some(row) { + return; + } + let Some(LootAction::Item { + wire_slot, + display_id, + .. + }) = self.loot.window.action_at(row) + else { + return; + }; + self.store(wire_slot, display_id); + self.loot.pending_bind_confirm = None; + } + + /// `EndLootWindow 0x48f200(1, 0, failed)` with the VM at hand, `CloseLoot`'s and an emptied + /// window's: nothing with no window (`0x48f23f`); a disenchant window with contents is swept + /// with the flag (`0x48f24f`, `0x48f264`); else `ERR_LOOT_NO_UI` for a set flag (`0x48f27b`), + /// the release and the teardown. The line, which a call signals as it returns, comes before + /// the unlocks ([`Then::Unlocks`]), and those before the window goes ([`Then::Announce`]). + pub(super) fn end_window(&mut self, script: &mut UiScript, failed: bool) { + if self.loot.source().is_none() { + return; + } + if self.loot.disenchant_hold(&self.objects) { + self.sweep(script, failed); + return; + } + if failed { + self.errors.push(UiError::key("ERR_LOOT_NO_UI")); + } + let closed = close_interaction(&mut self.loot, &mut self.latch, Some(&self.net)); + self.dead.after_close(closed); + self.loot.then.push(Then::Announce); + self.loot.then.push(Then::Unlocks); + } + + /// `0x4c2940`: nothing with no window (`0x4c2953`) or for a row that is no master row + /// (`0x4c298e`); else `CMSG_LOOT_MASTER_GIVE` with the row's wire slot and the candidate. + fn give_master(&mut self, slot: u32, candidate: u32) { + let window = &self.loot.window; + let Some(guid) = window.source else { + return; + }; + let ( + Some(LootAction::Item { + wire_slot, + slot_type, + .. + }), + Some(target), + ) = ( + window.action_at(slot), + window.master_candidate(candidate, &self.group), + ) + else { + debug!("ui_loot: GiveMasterLoot({slot}, {candidate}) unresolvable β€” ignored"); + return; + }; + if slot_type != slot_type::MASTER { + return; + } + debug!("ui_loot: master-give row {slot} (wire slot {wire_slot}) to {target:#x}"); + let _ = self.net.0.send(ClientCommand::LootMasterGive { + guid, + slot: wire_slot, + target, + }); + } + + /// The copier's end (`0x4c1ea8`-`0x4c1ee6`, the cache callback's `0x4c2afe`-`0x4c2b37`): the + /// sweep while the auto-loot byte is set (`0x4c1ed3`, `0x4c2b29`), else `LOOT_OPENED`. With + /// `autoLootDefault` on, a pickpocket or disenchant window, which no interaction stores the + /// byte for, stores it here from the Shift held now ([`LootConfig`]'s deviation). + pub(super) fn copier_end(&mut self, script: &mut UiScript) { + if self.cfg.auto_loot + && matches!( + self.loot.window.loot_type, + loot_type::PICKPOCKETING | loot_type::DISENCHANTING + ) + { + self.byte.0 = interaction_byte(&self.cfg, script.shift_key_down()); + } + if self.byte.0 { + self.sweep(script, false); + } else { + script.fire_event("LOOT_OPENED", vec![]); + } + } + + /// `AutoLootAll 0x4c1fa0(flag)`. Nothing while an item record is pending (`0x4c1fb3`), only + /// `LOOT_OPENED` with no active player (`0x4c1fd9`, `0x4c1fe0`). Then for a nonzero money + /// cell, -1 included (`0x4c1ff4`): the coin request, sent while the loot target is held + /// (`0x4c1ffc` β†’ `0x5ea8c6`), and once a session for money above 0 (`0x4c2008`, `0x4c2015`) + /// the money line, which a party (`0x4c2030`) or a raid (`0x4c203d`) skips, added in place + /// (`0x4c2170` β†’ `AddChatLine 0x49a870`). Its early coin (`0x4c201b`-`0x4c2020`) is not played + /// (`crate::sound`'s money module). Then the rows. + pub(super) fn sweep(&mut self, script: &mut UiScript, flag: bool) { + if self.loot.records_pending(&self.items) { + return; + } + if self.objects.player().is_none() { + script.fire_event("LOOT_OPENED", vec![]); + return; + } + let window = &self.loot.window; + if window.coin_slot { + if self.latch.0.is_some() { + let _ = self.net.0.send(ClientCommand::LootMoney); + } + let grouped = self.group.party_slots().next().is_some_and(|m| m.guid != 0) + || self.group.raid_held(); + if !self.loot.coin_line_shown && window.has_coin() && !grouped { + let line = crate::ui_chat::ChatEvent::text_only( + crate::ui_chat::ChatEventKind::Money, + money_line(script, window.gold), + ); + self.chat.show_now(script, &line); + } + } + self.sweep_rows(script, 1, false, flag); + } + + /// The sweep's rows from display row `from` (`0x4c2180`-`0x4c220e`): each plain row + /// (`0x4c2196`) sent as a click sends it, but a bind-on-pickup row of quality 2 or more, the + /// first of which signals `LOOT_BIND_CONFIRM` (`0x4c21d4`), the sweep going on after its + /// listeners ([`Then::SweepRest`]), and the later ones stay (`0x4c21c2`); then its end. + fn sweep_rows(&mut self, script: &mut UiScript, from: u32, confirmed: bool, flag: bool) { + for row in from..=self.loot.window.row_count() { + let Some(LootAction::Item { + wire_slot, + display_id, + item_id, + slot_type: slot_type::ALLOW_LOOT, + }) = self.loot.window.action_at(row) + else { + continue; + }; + if bind_confirm_required(&self.items, item_id) { + if confirmed { + continue; + } + script.fire_event("LOOT_BIND_CONFIRM", vec![ScriptValue::Int(i64::from(row))]); + self.loot.then.push(Then::SweepRest { row, flag }); + return; + } + self.store(wire_slot, display_id); + } + self.sweep_end(script, flag); + } + + /// The sweep's end: the auto-loot byte cleared (`0x4c2219`) and the money line's flag set + /// (`0x4c221e`), then for a flag of 0 + /// `LOOT_OPENED` while anything is left (`0x4c2237`, `0x4c2240`), the rows it sent included, + /// and with nothing left the close with release (`0x4c224f`). + fn sweep_end(&mut self, script: &mut UiScript, flag: bool) { + self.byte.0 = false; + self.loot.coin_line_shown = true; // `0x4c221e` + if self.loot.has_contents(&self.objects) { + if !flag { + script.fire_event("LOOT_OPENED", vec![]); + } + } else { + self.end_window(script, false); + } + } + + /// Run what a function owed after its signal's listeners. + pub(super) fn then(&mut self, script: &mut UiScript, then: Then) { + match then { + Then::StoreBind { row } => self.loot.pending_bind_confirm = Some(row), + Then::SweepRest { row, flag } => { + self.loot.pending_bind_confirm = Some(row); // `0x4c21dc` + self.sweep_rows(script, row + 1, true, flag); + } + Then::CloseIfEmpty => { + if !self.loot.has_contents(&self.objects) { + self.end_window(script, false); + } + } + Then::Unlocks => unlock_closed_source(script, &mut self.loot, &self.objects), + Then::Announce => show(script, None), + Then::OpenItem(open) => self.send_open_item(script, open), + } + } +} + +/// The sweep's money line (`0x4c2043`-`0x4c2170`): `YOU_LOOT_MONEY` over the coins, each paid one +/// as `"%d %s"` with its `GOLD`, `SILVER` or `COPPER` global, gold first, joined by the +/// reference's own tests: `", "` after the gold when silver or copper is paid (`0x4c20e4`- +/// `0x4c20f0`), and before the copper when gold or silver is (`0x4c20bc`-`0x4c20c9`), so a zero +/// middle coin leaves `", , "`. +fn money_line(script: &UiScript, copper: u32) -> String { + // `SplitCopper 0x6c6260`. + let (g, s, c) = (copper / 10_000, copper / 100 % 100, copper % 100); + let coin = |n: u32, key: &str| match n { + 0 => String::new(), + n => format!("{n} {}", script.global_text(key)), + }; + let after_gold = if g != 0 && (s != 0 || c != 0) { + ", " + } else { + "" + }; + let before_copper = if (g != 0 || s != 0) && c != 0 { + ", " + } else { + "" + }; + let coins = format!( + "{}{after_gold}{}{before_copper}{}", + coin(g, "GOLD"), + coin(s, "SILVER"), + coin(c, "COPPER") + ); + benilla_ui::strings::fill( + &script.global_text("YOU_LOOT_MONEY"), + &[benilla_ui::strings::Arg::S(&coins)], + ) +} diff --git a/crates/benilla-app/src/ui_loot/mod.rs b/crates/benilla-app/src/ui_loot/mod.rs index a336bf778..330329d75 100644 --- a/crates/benilla-app/src/ui_loot/mod.rs +++ b/crates/benilla-app/src/ui_loot/mod.rs @@ -1,23 +1,33 @@ -//! The app side of the loot window: the net handlers fill [`LootState`], [`feed_loot`] pushes the -//! resolved rows to the VM and fires `LOOT_OPENED`, `LOOT_SLOT_CLEARED`, `UPDATE_MASTER_LOOT_LIST` -//! and `LOOT_CLOSED`, and [`drain_loot`] sends what the Lua asked for. +//! The app side of the loot window. The net handlers change [`LootState`] at their packets, each +//! change a step that [`feed_loot`] shows the VM in wire order, with the item pushes queued +//! between them: the window's rows, `LOOT_SLOT_CLEARED`, `UPDATE_MASTER_LOOT_LIST` and +//! `LOOT_CLOSED`, and at a response the copier's end, `LOOT_OPENED` or the auto-loot sweep. The +//! loot verbs and a row's click apply inside their calls ([`calls::LootSteps::apply`]), and +//! [`drain_loot`] takes the closes a movement and the precast's end owe. -use benilla_protocol::messages::{slot_type, ItemPushResult, LootItem, BAG_PLAYER_INVENTORY}; +use benilla_protocol::messages::{ItemPushResult, LootItem, BAG_PLAYER_INVENTORY}; use bevy::prelude::*; -use benilla_ui::script::{LootRow, LootState as LootSnapshot, LootTake, ScriptValue, UiScript}; +use benilla_ui::script::{LootRow, LootState as LootSnapshot, ScriptValue, UiScript}; use crate::entities::ItemDisplays; use crate::items::{Items, RollCatalogs}; use crate::names::NameCache; use crate::net::{ClientCommand, NetCommands}; use crate::query_cache::Ask; -use crate::ui_action::{UiError, UiErrorKeys}; +use crate::script_calls::VmWith; use crate::ui_items::KEYRING_CONTAINER; use crate::ui_party::{GroupState, GROUP_MEMBER_SUBGROUP}; use crate::ui_script::{SweepApp, SweepLeg, UiFeed}; +pub(crate) use calls::{interaction_byte, LootSteps, OpenItem}; + +#[cfg(test)] +mod call_tests; +mod calls; mod net; +#[cfg(test)] +mod sweep_tests; /// `ItemBondingType::BIND_WHEN_PICKED_UP`, the first conjunct of the `LOOT_BIND` confirm: the /// client compares `item_template + 0x194` against 1. @@ -55,32 +65,10 @@ struct PendingReceive { in_chat: bool, container: i64, tries: u16, - /// Where it came among the frame's window changes. - at: PushAt, -} - -/// Where a queued push came among the window changes the feed has yet to show: each packet's -/// events fire inside its dispatch (`0x537aa0`), so `ITEM_PUSH` reads the window the packets -/// before it left. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum PushAt { - /// Ahead of all of them: a push an earlier frame left waiting on its template, or one ahead - /// of the frame's response or close. - Ahead, - /// After this many of the frame's removals ([`LootState::removed`]). - After(usize), - /// After the frame's response or close: after its `LOOT_OPENED`, sweep and move-start - /// close, or its `LOOT_CLOSED`. - Behind, -} - -/// A removal from the window the feed last showed, with what undoes it. -#[derive(Clone, Copy, Debug)] -enum Removed { - /// `SMSG_LOOT_REMOVED`'s row, by wire slot (`0x4c1f00`). - Row(u8), - /// `SMSG_LOOT_CLEAR_MONEY`'s coin row, with the copper it held (`0x4c2750`). - Money(u32), + /// How many of the frame's window steps ([`LootState::steps`]) came before it: each packet's + /// events fire inside its dispatch (`0x537aa0`), so `ITEM_PUSH` reads the window the packets + /// before it left. + at: usize, } /// `ITEM_PUSH`'s `arg1`, the reference's selector at `0x491bb5`-`0x491bd6`: a wire bag other than @@ -96,67 +84,31 @@ fn push_container(bag: u8, slot: u32) -> i64 { 0 } -/// The open loot as the wire delivered it, plus the push queue, which outlives the window. The -/// layout is fixed at open: a looted row is a gap, as `LOOT_SLOT_CLEARED` hides its button in -/// place and `numLootItems` is read once at `OnShow` (`LootFrame.lua:22-37`, `:132`). -#[derive(Resource, Default, Clone)] -pub(crate) struct LootState { +/// The window's cells: the source `0xb71b48`, the money `0xb71ba0`, the type `0xb71bbc` and the +/// row array `0xb71968`. The copier fills them at a response (`0x4c1cb0`), a removal zeroes its +/// row in place (`0x4c1f59`), and a close zeroes only the source (`0x4c1da0`): the rows, the money +/// and the type stay until the next response, and the take dispatcher `0x4c2790` reads them +/// without asking for a source. +#[derive(Clone, Debug, Default, PartialEq)] +struct Window { /// The looted object; `None` when no loot is open. source: Option, /// The coin pile in copper, 0 once taken. gold: u32, - /// Whether layout position 1 is the coin pile: fixed at open, kept after the coin is taken. + /// The money cell is nonzero, so row 1 is the coin row: set at the response, kept once the + /// coin is taken (-1). coin_slot: bool, - /// The item rows in wire order; never shrinks while open, a taken row lands in `taken`. + /// The item rows in wire order; a taken row lands in `taken`, a gap in place. items: Vec, /// Wire slots taken by anyone (`SMSG_LOOT_REMOVED`), left as gaps. taken: Vec, - receives: Vec, - /// The removals from the window the feed last showed, in wire order, which it shows in step - /// with the pushes queued between them ([`PushAt::After`]). - removed: Vec, - /// A response or a close replaced the window since the feed last ran: a push after it comes - /// [`PushAt::Behind`]. - replaced: bool, - /// A removal just emptied the window, so the client releases it, as the reference does on the - /// last slot (`0x4c2a70` β†’ `0x48f200`); vmangos does not. Never set at open: an empty window - /// stays up (`LOOTWINDOWOPENEMPTY`). - auto_release: bool, - /// Wire `loot_type` 3, for `IsFishingLoot()`: `LootFrame_OnShow`'s reel-in sound and icon. - fishing: bool, - /// The open window's master-loot candidates (`SMSG_LOOT_MASTER_LIST`), in wire order. - master_candidates: Vec, - /// The row a `LOOT_BIND_CONFIRM` is open for, the reference's `[0x847cec]`: set by a click - /// (`0x4c2790`), cleared by the confirmed send (`0x4c281a`) and per window (`0x4c1df5`). - /// Deviation: it is the display row, where the reference's is the item index plus one - /// (`0x4c2885`), so an addon's `GetLootSlotInfo(arg1)` reads the row the dialog is for. - pending_bind_confirm: Option, - /// The row a `LOOT_BIND_CONFIRM` has just signalled for, which the stash takes once the - /// signal's handlers ran (`0x4c2917` after `0x4c290f`, `0x4c21dc` after `0x4c21d4`): their - /// own `LootSlot` finds the stash as it stood ([`settle_bind_confirm`]). - owed_bind_confirm: Option, - /// The list staged for the next open: vmangos sends it from inside `Player::SendLoot` - /// (`Player.cpp:8080`), just ahead of its response. Staging keeps it out of later windows. - pending_master_candidates: Vec, - /// The wire `loot_type` (`0x4c2740`); a disenchant window with rows left survives movement. + /// The wire `loot_type`, the cell `0xb71bbc` (`0x4c2740`) a close leaves: fishing for + /// `IsFishingLoot()`, and a disenchant window with rows left survives a close. loot_type: u8, - /// A close with `dl` clear found a disenchant window with rows left and owes its sweep - /// (`0x48f264` β†’ `0x4c1fa0`), run by [`feed_loot`], which holds the VM. - sweep_owed: bool, - /// The `UnlockItem` (`0x495420`) calls the loot paths owe, run ahead of the inventory feeds - /// ([`crate::ui_items::locks::apply_item_releases`]); a window's clear keeps them. The flag - /// marks a window source's, owed only while the guid resolves as a live item object. - item_unlocks: Vec<(u64, bool)>, - /// A response the feed has not read: its copier looks every row up with the callback - /// `0x4c2ac0` (`0x4c1e77`); the frames after it read, as the row getters do (`0x4c241d`). - opened: bool, + /// The window's master-loot candidates (`SMSG_LOOT_MASTER_LIST`), in wire order. + master_candidates: Vec, } -/// The client's candidate array: 40 slots at `0xc4dc38`, bound-checked by the getter `0x61c660`. -const MASTER_LOOT_CANDIDATE_SLOTS: usize = 40; -/// A raid subgroup's block within it (`0x61c609`). -const MEMBERS_PER_RAID_GROUP: usize = 5; - /// A clicked row resolved: the coin pile, or an item at its wire loot slot. enum LootAction { Money, @@ -164,206 +116,27 @@ enum LootAction { wire_slot: u8, display_id: u32, item_id: u32, - /// `MASTER` opens the master-loot dropdown instead of a take. + /// The take dispatcher branches on it (`0x4c28a9`). slot_type: u8, }, } -impl LootState { - /// Opens or replaces the window; quest items ride the same rows at `slot = items.len() + i`. - pub(crate) fn open(&mut self, source: u64, loot_type: u8, gold: u32, items: Vec) { - self.replace_window(); - // The frame's teardown of the window it replaces unlocks an item source (`0x5ebc35` β†’ - // `0x48f3a0` β†’ `0x4c1d36`). - if let Some(old) = self.source { - self.unlock_item_source(old); - } - self.source = Some(source); - self.gold = gold; - self.coin_slot = gold > 0; // fixed for the window's lifetime - self.items = items; - self.taken.clear(); - self.auto_release = false; // an empty window at open stays open - self.pending_bind_confirm = None; // `0x4c1df5`: the copier resets the stash - self.owed_bind_confirm = None; - self.loot_type = loot_type; - self.fishing = loot_type == benilla_protocol::messages::loot_type::FISHING; - self.master_candidates = std::mem::take(&mut self.pending_master_candidates); - self.opened = true; - } - - /// Stages a list for the next open; an open window takes it at once, as a refresh. - pub(crate) fn set_master_candidates(&mut self, candidates: Vec) { - if self.source.is_some() { - self.master_candidates.clone_from(&candidates); - } - self.pending_master_candidates = candidates; - } - - /// `SMSG_LOOT_REMOVED`: the row becomes a gap; an emptied window arms the auto-close. - pub(crate) fn remove_slot(&mut self, wire_slot: u8) { - if self.items.iter().any(|it| it.slot == wire_slot) && !self.taken.contains(&wire_slot) { - self.taken.push(wire_slot); - if !self.replaced { - self.removed.push(Removed::Row(wire_slot)); - } - } - self.arm_auto_release(); - } - - /// `SMSG_LOOT_CLEAR_MONEY`: the coin row becomes a gap; an emptied window arms the auto-close. - pub(crate) fn clear_money(&mut self) { - if self.gold > 0 && !self.replaced { - self.removed.push(Removed::Money(self.gold)); - } - self.gold = 0; - self.arm_auto_release(); - } - - /// The window as the frame's first `k` removals left it, the later ones undone. - fn as_of(&self, k: usize) -> LootState { - let mut then = self.clone(); - for removed in self.removed[k..].iter().rev() { - match *removed { - Removed::Row(slot) => then.taken.retain(|&t| t != slot), - Removed::Money(was) => then.gold = was, - } - } - then - } - - /// A response or a close replaces the window the feed showed: a push before it reads the old - /// window and one after it the new, and the old window's removals are past undoing. - fn replace_window(&mut self) { - for r in &mut self.receives { - r.at = PushAt::Ahead; - } - self.removed.clear(); - self.replaced = true; - } - - fn arm_auto_release(&mut self) { - if self.source.is_some() && self.is_empty() { - self.auto_release = true; - } - } - - fn take_auto_release(&mut self) -> bool { - std::mem::take(&mut self.auto_release) - } - - /// Queues a push the net handler has already checked is ours. - pub(crate) fn push_receive(&mut self, p: &ItemPushResult) { - self.receives.push(PendingReceive { - created: p.created, - entry: p.item_entry, - count: p.count, - from_npc: p.from_npc, - random_property_id: p.random_property_id, - suffix_factor: p.suffix_factor, - in_chat: p.show_in_chat, - container: push_container(p.bag_slot, p.item_slot), - tries: 0, - at: if self.replaced { - PushAt::Behind - } else { - PushAt::After(self.removed.len()) - }, - }); - } - - /// Closes the window; queued pushes outlive it. - pub(crate) fn clear(&mut self) { - self.replace_window(); - self.source = None; - self.gold = 0; - self.coin_slot = false; - self.items.clear(); - self.taken.clear(); - self.auto_release = false; - self.fishing = false; - self.loot_type = 0; - self.pending_bind_confirm = None; - self.owed_bind_confirm = None; - self.master_candidates.clear(); - self.pending_master_candidates.clear(); - self.sweep_owed = false; - } - - /// Session end: drops the window, the queued pushes and the owed unlocks. - pub(crate) fn clear_session(&mut self) { - self.clear(); - self.receives.clear(); - self.item_unlocks.clear(); - } - - /// Owe `UnlockItem` on `guid`, which fires its `ITEM_LOCK_CHANGED` whether or not the guid - /// names an item we hold (`0x495450`); a zero guid owes nothing (`0x49542d`). - pub(crate) fn unlock_item(&mut self, guid: u64) { - if guid != 0 { - self.item_unlocks.push((guid, false)); - } - } - - /// Owe the window teardown's `UnlockItem` on its source, which runs only when the source - /// resolves as a live item object (`0x48f299`/`0x48f2ab`, `0x4c1cdf`/`0x4c1d23`): checked - /// where the unlocks run, against the objects. - pub(crate) fn unlock_item_source(&mut self, guid: u64) { - if benilla_protocol::guid::is_item(guid) { - self.item_unlocks.push((guid, true)); - } - } - - /// Whether a `LOOT_BIND_CONFIRM` owes the stash its row ([`settle_bind_confirm`]). - fn owes_bind_confirm(&self) -> bool { - self.owed_bind_confirm.is_some() - } - - /// Whether any unlock is owed. - pub(crate) fn owes_unlocks(&self) -> bool { - !self.item_unlocks.is_empty() - } - - /// The owed unlocks, in order, each flagged when it needs a live item object. - pub(crate) fn take_item_unlocks(&mut self) -> Vec<(u64, bool)> { - std::mem::take(&mut self.item_unlocks) - } - - /// Queued pushes, for the net handler's self-gate test. - #[cfg(test)] - pub(crate) fn pending_receive_count(&self) -> usize { - self.receives.len() - } +/// The client's candidate array: 40 slots at `0xc4dc38`, bound-checked by the getter `0x61c660`. +const MASTER_LOOT_CANDIDATE_SLOTS: usize = 40; +/// A raid subgroup's block within it (`0x61c609`). +const MEMBERS_PER_RAID_GROUP: usize = 5; +impl Window { fn has_coin(&self) -> bool { self.gold > 0 } - /// The open loot's guid; the chest lid watcher in [`crate::go_anim`] reads it too. - pub(crate) fn source(&self) -> Option { - self.source - } - - /// Nothing lootable left: the reference's empty check `0x4c2a70`. + /// No money above 0 and no row left: the second half of `LootHasContents` (`0x4c2a9c`- + /// `0x4c2ab8`). fn is_empty(&self) -> bool { !self.has_coin() && self.items.iter().all(|it| self.taken.contains(&it.slot)) } - /// `0x48f200`'s early-out with `dl` clear (`0x48f245`-`0x48f26f`): a disenchant window - /// (`0x4c2740` == 4) with rows left (`0x4c2a70`) is not closed but swept (`0x48f264` β†’ - /// `0x4c1fa0`), with no release, no latch clear and no `LOOT_CLOSED`. Every close with `dl` - /// clear tests it; the move-start close, `dl` set, returns instead (`0x48f25a`). - pub(crate) fn disenchant_holds(&self) -> bool { - self.source.is_some() - && self.loot_type == benilla_protocol::messages::loot_type::DISENCHANTING - && !self.is_empty() - } - - /// Owe the hold's sweep to the feed, from a close with no VM at hand. - pub(crate) fn owe_sweep(&mut self) { - self.sweep_owed = true; - } - /// The display rows of the fixed layout, gaps included. fn row_count(&self) -> u32 { (self.items.len() + usize::from(self.coin_slot)) as u32 @@ -391,7 +164,7 @@ impl LootState { /// (`0x61c577`), not the group type: wire order with no roster held (`0x61c5b9`), a raid of one /// included; with one, each guid in the first free slot of its subgroup's block of five /// (`0x61c5c9`-`0x61c637`), holes kept for `GroupLootDropDown_Initialize`'s "Group N" submenus - /// (`LootFrame.lua:197-213`). The feed and the drain share it, so an index means one candidate. + /// (`LootFrame.lua:197-213`). The feed and the give share it, so an index means one candidate. fn placed_candidates(&self, group: &GroupState) -> Vec> { if !group.raid_held() { return self.master_candidates.iter().copied().map(Some).collect(); @@ -417,7 +190,7 @@ impl LootState { slots } - /// The candidate at a 1-based menu index, through [`LootState::placed_candidates`]. + /// The candidate at a 1-based menu index, through [`Window::placed_candidates`]. fn master_candidate(&self, index_1based: u32, group: &GroupState) -> Option { self.placed_candidates(group) .get(index_1based.checked_sub(1)? as usize) @@ -426,10 +199,278 @@ impl LootState { } } -/// The loot CVars. `autoLootDefault` is not a 1.12 CVar: 1.12 auto-loots only on a shift-click. -/// [`feed_loot`] sweeps the rows engine-side at the open, as the reference does, and a held Shift -/// inverts the setting. `showLootSpam` is 1.12's Detailed Loot Information checkbox (`0xb4e2bc`, +/// A change to the window the feed has yet to show, with the window it left. +#[derive(Clone, Debug)] +enum Step { + /// A removal (`0x4c1f00`, `0x4c2750`) or a close (`0x4c1cb0(0)`). + Changed(Window), + /// The coin row's clear with no window open (`0x4c2750`), which still signals + /// `LOOT_SLOT_CLEARED` with its row (`0x4c276f`). + SlotCleared(u32), + /// The unlocks of a close a packet asked for (`0x48f2bd`, `0x4c1d36`), signalled in their + /// place: after the removal's `LOOT_SLOT_CLEARED`, before the close's `LOOT_CLOSED`. Each is + /// flagged when it needs a live item object. + Unlocks(Vec<(u64, bool)>), + /// A response's copier (`0x4c1cb0`): the cells its teardown leaves, the ended session's with + /// the source zeroed (`0x4c1da0`), then the window it fills. + Opened { ended: Window, window: Window }, +} + +/// The loot session: the window, the steps the feed has yet to show, the push queue, which +/// outlives the window, and what the loot calls owe. +#[derive(Resource, Default)] +pub(crate) struct LootState { + window: Window, + receives: Vec, + /// The window's changes since the feed last ran, in wire order, each shown as the window it + /// left, with the pushes queued between them ([`PendingReceive::at`]). + steps: Vec, + /// The row a `LOOT_BIND_CONFIRM` is open for, the reference's `[0x847cec]`: set after the + /// signal's handlers (`0x4c2917`, `0x4c21dc`), cleared by the confirmed send (`0x4c281a`) and + /// by the next response (`0x4c1df5`), not by a close. + /// Deviation: it is the display row, where the reference's is the item index plus one + /// (`0x4c2885`), so an addon's `GetLootSlotInfo(arg1)` reads the row the dialog is for. + pending_bind_confirm: Option, + /// The list staged for the next open: vmangos sends it from inside `Player::SendLoot` + /// (`Player.cpp:8080`), just ahead of its response. Staging keeps it out of later windows. + pending_master_candidates: Vec, + /// A close with `dl` clear found a disenchant window with rows left and owes its sweep + /// (`0x48f264` β†’ `0x4c1fa0`), run by [`feed_loot`], which holds the VM. + sweep_owed: bool, + /// The `UnlockItem` (`0x495420`) calls the loot paths owe, run ahead of the inventory feeds + /// ([`crate::ui_items::locks::apply_item_releases`]); a window's clear keeps them. The flag + /// marks a window source's, owed only while the guid resolves as a live item object. + item_unlocks: Vec<(u64, bool)>, + /// The response's copier end, `LOOT_OPENED` or the sweep, waits on its item records: the + /// copier returns with a fetch outstanding (`0x4c1ea6`) and the cache callback ends it at the + /// last arrival (`0x4c2afc`). + copier_due: bool, + /// `0xb71bc4`: a sweep of this session has run (`0x4c221e`), so the next prints no money line + /// (`0x4c2008`); the session's end clears it (`0x4c1d95`). + coin_line_shown: bool, + /// What the loot steps owe once their signals' handlers have run, innermost last + /// ([`calls::Then`]). + then: Vec, +} + +impl LootState { + /// The copier (`0x4c1cb0`) at a response: it ends the session in progress, then fills the + /// window; quest items ride the same rows at `slot = items.len() + i`. + pub(crate) fn open(&mut self, source: u64, loot_type: u8, gold: u32, items: Vec) { + // The ending unlocks an item source (`0x5ebc35` β†’ `0x48f3a0` β†’ `0x4c1d36`) and clears + // the money line's flag (`0x4c1d95`). + if let Some(old) = self.window.source { + self.unlock_item_source(old); + self.coin_line_shown = false; + } + let ended = Window { + source: None, + ..self.window.clone() + }; + self.window = Window { + source: Some(source), + gold, + coin_slot: gold > 0, // `0x4c1de9` + items, + taken: Vec::new(), + loot_type, // `0x4c1dd6` + master_candidates: std::mem::take(&mut self.pending_master_candidates), + }; + self.pending_bind_confirm = None; // `0x4c1df5` + self.sweep_owed = false; + self.copier_due = true; + self.steps.push(Step::Opened { + ended, + window: self.window.clone(), + }); + } + + /// Stages a list for the next open; an open window takes it at once, as a refresh. + pub(crate) fn set_master_candidates(&mut self, candidates: Vec) { + if self.window.source.is_some() { + self.window.master_candidates.clone_from(&candidates); + } + self.pending_master_candidates = candidates; + } + + /// `ClearLootRow` (`0x4c1f00`): the row with the wire slot becomes a gap, whether or not a + /// window is open; whether one did. + pub(crate) fn remove_slot(&mut self, wire_slot: u8) -> bool { + let w = &mut self.window; + if !w.items.iter().any(|it| it.slot == wire_slot) || w.taken.contains(&wire_slot) { + return false; // `0x4c1f22` + } + w.taken.push(wire_slot); + self.steps.push(Step::Changed(self.window.clone())); + true + } + + /// `ClearLootCoinRow` (`0x4c2750`): money above 0 goes to -1, the coin row a gap, whether a + /// window is open or not; whether it was there (`0x4c2757`). + pub(crate) fn clear_money(&mut self) -> bool { + if !self.window.has_coin() { + return false; + } + self.take_coin(); + self.steps.push(match self.window.source { + Some(_) => Step::Changed(self.window.clone()), + None => Step::SlotCleared(1), + }); + true + } + + /// The money cell to -1 (`0x4c2858`, `0x4c2765`): the coin row stays a gap. + fn take_coin(&mut self) { + self.window.gold = 0; + } + + /// Queues a push the net handler has already checked is ours. + pub(crate) fn push_receive(&mut self, p: &ItemPushResult) { + self.receives.push(PendingReceive { + created: p.created, + entry: p.item_entry, + count: p.count, + from_npc: p.from_npc, + random_property_id: p.random_property_id, + suffix_factor: p.suffix_factor, + in_chat: p.show_in_chat, + container: push_container(p.bag_slot, p.item_slot), + tries: 0, + at: self.steps.len(), + }); + } + + /// The close's teardown (`0x4c1cb0(0)`): the source goes (`0x4c1da0`) and the rows stay; the + /// feed signals `LOOT_CLOSED` for a window it showed. Queued pushes outlive it. + pub(crate) fn clear(&mut self) { + if self.window.source.take().is_some() { + self.steps.push(Step::Changed(self.window.clone())); + self.coin_line_shown = false; // `0x4c1d95` + } + self.copier_due = false; + self.sweep_owed = false; + self.pending_master_candidates.clear(); + } + + /// Session end: drops the window, the queued pushes and the owed unlocks. + pub(crate) fn clear_session(&mut self) { + *self = LootState::default(); + } + + /// Owe `UnlockItem` on `guid`, which fires its `ITEM_LOCK_CHANGED` whether or not the guid + /// names an item we hold (`0x495450`); a zero guid owes nothing (`0x49542d`). + pub(crate) fn unlock_item(&mut self, guid: u64) { + if guid != 0 { + self.item_unlocks.push((guid, false)); + } + } + + /// Owe the window teardown's `UnlockItem` on its source, which runs only when the source + /// resolves as a live item object (`0x48f299`/`0x48f2ab`, `0x4c1cdf`/`0x4c1d23`): checked + /// where the unlocks run, against the objects. + pub(crate) fn unlock_item_source(&mut self, guid: u64) { + if benilla_protocol::guid::is_item(guid) { + self.item_unlocks.push((guid, true)); + } + } + + /// How many unlocks are owed, a mark for [`Self::defer_close_unlocks`]. + pub(crate) fn owed_unlocks(&self) -> usize { + self.item_unlocks.len() + } + + /// Signal the unlocks a close owed past `mark` in their place in the steps, ahead of its + /// teardown's step: for a close inside a packet, which the feed shows. + pub(crate) fn defer_close_unlocks(&mut self, mark: usize) { + let unlocks = self + .item_unlocks + .split_off(mark.min(self.item_unlocks.len())); + if unlocks.is_empty() { + return; + } + let at = self.steps.len().saturating_sub(1); + self.steps.insert(at, Step::Unlocks(unlocks)); + } + + /// Whether any unlock is owed. + pub(crate) fn owes_unlocks(&self) -> bool { + !self.item_unlocks.is_empty() + } + + /// The owed unlocks, in order, each flagged when it needs a live item object. + pub(crate) fn take_item_unlocks(&mut self) -> Vec<(u64, bool)> { + std::mem::take(&mut self.item_unlocks) + } + + /// Queued pushes, for the net handler's self-gate test. + #[cfg(test)] + pub(crate) fn pending_receive_count(&self) -> usize { + self.receives.len() + } + + /// The open loot's guid; the chest lid watcher in [`crate::go_anim`] reads it too. + pub(crate) fn source(&self) -> Option { + self.window.source + } + + /// `LootHasContents` (`0x4c2a70`): the source resolves as any object (`0x4c2a8c`, mask 1) and + /// has money above 0 or a row left. + fn has_contents(&self, objects: &crate::net::Objects) -> bool { + self.window + .source + .is_some_and(|source| objects.entity(source).is_some()) + && !self.window.is_empty() + } + + /// `0x48f200`'s early-out with `dl` clear (`0x48f245`-`0x48f26f`): a disenchant window + /// (`0x4c2740` == 4) with contents (`0x4c2a70`, its source resolving) is not closed but swept + /// (`0x48f264` β†’ `0x4c1fa0`), with no release, no latch clear and no `LOOT_CLOSED`. Every + /// close with `dl` clear tests it; the move-start close, `dl` set, returns instead + /// (`0x48f25a`). + pub(crate) fn disenchant_hold(&self, objects: &crate::net::Objects) -> bool { + self.window.loot_type == benilla_protocol::messages::loot_type::DISENCHANTING + && self.has_contents(objects) + } + + /// [`Self::disenchant_hold`] for the selection teardown's close, which holds no object manager: + /// a set source stands in for one that resolves (`0x4c2a8c`). + pub(crate) fn disenchant_holds(&self) -> bool { + self.window.source.is_some() + && self.window.loot_type == benilla_protocol::messages::loot_type::DISENCHANTING + && !self.window.is_empty() + } + + /// `0xb71b44` above 0: a row's item record is still being fetched, counted from the copier + /// (`0x4c1e77`) until its callback (`0x4c2ac0`); a negative answer releases the row, as + /// [`templates_outstanding`] has it. + fn records_pending(&self, items: &Items) -> bool { + let w = &self.window; + w.items.iter().any(|it| { + !w.taken.contains(&it.slot) + && items.template(it.item_id, 0, Ask::Read).is_none() + && !items.template_answered_unknown(it.item_id) + }) + } + + /// Owe the hold's sweep to the feed, from a close with no VM at hand. + pub(crate) fn owe_sweep(&mut self) { + self.sweep_owed = true; + } +} + +/// The active player's auto-loot byte (`+0x1d30`): the copier's end sweeps while it is set +/// (`0x4c1ec7`, `0x4c2b1d`), and the sweep clears it (`0x4c2219`). Each loot interaction stores it +/// through `SetAutoLoot` (`0x5df460`), from the keys held then ([`interaction_byte`]). +#[derive(Resource, Default)] +pub(crate) struct AutoLootByte(pub(crate) bool); + +/// The loot CVars. `showLootSpam` is 1.12's Detailed Loot Information checkbox (`0xb4e2bc`, /// registered at `0x48fd1c`, default `"1"`), read only by the loot-roll line composers. +/// Deviation: `autoLootDefault` is benilla's own option, 1.12 auto-looting only on a shift-click, +/// and off is 1.12's behaviour. On, every window auto-loots unless Shift is held: an interaction +/// stores the byte inverted by it ([`interaction_byte`]), and a pickpocket or disenchant window, +/// which no interaction stores the byte for, takes it at its copier's end from the Shift held +/// then. #[derive(Resource)] pub(crate) struct LootConfig { pub(crate) auto_loot: bool, @@ -490,7 +531,7 @@ pub(crate) fn resolve_loot_kneel( benilla_protocol::EntityKind::Unit | benilla_protocol::EntityKind::Player => { store.0.unit_health().unwrap_or(0) == 0 } - // An item never kneels (`0x612797`); we stream none, so a lockbox latch never resolves. + // An item, which the bags stream, never kneels (`0x612797`). _ => false, }); if kneel.0 != allowed { @@ -546,13 +587,14 @@ impl Plugin for UiLootPlugin { .init_resource::() .init_resource::() .init_resource::() + .init_resource::() .add_sweep_leg(SweepLeg::Loot, close_loot_on_leave_world) .add_systems( Update, ( - // Feed before the input pass and drain after it: an open shows, and a click - // sends, the same frame. The drain's deselect lands before the selection - // writers read it, and their teardown's close finds this frame's window. + // Feed before the input pass and drain after it: an open shows the same + // frame. The drain's deselect lands before the selection writers read it, and + // their teardown's close finds this frame's window. feed_loot.in_set(UiFeed), drain_loot .in_set(crate::ui_script::UiDrain) @@ -651,19 +693,19 @@ fn templates_outstanding(items: &Items, snap: &LootSnapshot) -> bool { /// The Lua snapshot: one entry per slot of the fixed layout, coin first, a looted slot `None`. fn snapshot( - loot: &LootState, + window: &Window, items: &Items, icons: Option<&ItemDisplays>, ask: Ask<'_>, rolls: RollCatalogs, who: Candidates, ) -> Option { - loot.source?; - let mut rows = Vec::with_capacity(loot.items.len() + 1); - if loot.coin_slot { - rows.push(loot.has_coin().then(|| LootRow { - name: Some(format_money(loot.gold)), - texture: Some(coin_icon(loot.gold).into()), + window.source?; + let mut rows = Vec::with_capacity(window.items.len() + 1); + if window.coin_slot { + rows.push(window.has_coin().then(|| LootRow { + name: Some(format_money(window.gold)), + texture: Some(coin_icon(window.gold).into()), // 0: `0x4c22e0`'s coin guard returns before the record read (`0x4c22fd`). quantity: 0, quality: Some(COIN_QUALITY), @@ -674,15 +716,15 @@ fn snapshot( random_property_id: 0, })); } - for it in &loot.items { + for it in &window.items { rows.push( - (!loot.taken.contains(&it.slot)).then(|| resolve_item(it, items, icons, ask, rolls)), + (!window.taken.contains(&it.slot)).then(|| resolve_item(it, items, icons, ask, rolls)), ); } Some(LootSnapshot { rows, - fishing: loot.fishing, - master_candidates: who.names_for(loot), + has_money: window.coin_slot, + master_candidates: who.names_for(window), // The feed's, which holds the object manager. source_unit: false, }) @@ -700,8 +742,9 @@ impl Candidates<'_> { /// The candidate slots as names, an empty slot and an unresolved name both `None`: the /// binding `0x4c2f10` pushes nil on a name-cache miss (`0x4c2f91`), and the cache callback /// `0x4c2fb0` fires `UPDATE_MASTER_LOOT_LIST` when the name lands. - fn names_for(&self, loot: &LootState) -> Vec> { - loot.placed_candidates(self.group) + fn names_for(&self, window: &Window) -> Vec> { + window + .placed_candidates(self.group) .into_iter() .map(|slot| slot.and_then(|guid| self.name(guid))) .collect() @@ -807,7 +850,6 @@ fn drain_receives( still } -/// Emits the queued pushes, then pushes the loot snapshot and fires the loot events on a change. /// The object manager as `SetLootPortrait` asks it (`0x468460`, typemask 8): whether the loot /// source is a unit object we hold. #[derive(bevy::ecs::system::SystemParam)] @@ -826,19 +868,18 @@ impl LootSourceObjects<'_, '_> { } } +/// Shows the frame's window steps in wire order, each a turn whose handlers run as it ends, with +/// the pushes queued between them fired in their places: each packet's events fire inside its +/// dispatch (`0x537aa0`), so `ITEM_PUSH` (`0x491be8`) reads the window the packets before it left. +/// A response's step ends with its copier's end. Then the window as it stands: a hold's owed +/// sweep, a copier's end a late item record let through, and the names and candidates that +/// resolved since. fn feed_loot( - mut vm: crate::script_calls::VmWith<( - ResMut<'static, LootState>, - OpenWhileMoving<'static, 'static>, - )>, + mut vm: VmWith<(LootSteps<'static, 'static>, ResMut<'static, LootMoveStart>)>, items: Res, icons: Option>, commands: Res, chat: Res, - mut last: crate::ui_script::WindowMemo>, - cfg: Res, - keys: Res>, - mut pickup: MessageWriter, // The random-suffix catalogs: a loot slot has no item object to carry the roll. props: Option>, enchants: Option>, @@ -846,11 +887,6 @@ fn feed_loot( names: Res, objects: LootSourceObjects, ) { - // Each step is a turn whose handlers run as it ends, with the host lent, reading what it - // left: the copier's open signals `LOOT_OPENED` before the auto-loot sweep and the move-start - // close run, so its handlers read the open window. Each push fires where its packet came - // ([`PushAt`]): `OnItemPush` signals `ITEM_PUSH` inside its dispatch (`0x491be8`), so its - // handlers read the window the packets before it left. let rolls = RollCatalogs { props: props.as_deref(), enchants: enchants.as_deref(), @@ -859,12 +895,16 @@ fn feed_loot( group: &group, names: &names, }; - let view = |loot: &LootState, ask: Ask<'_>| { - snapshot(loot, &items, icons.as_deref(), ask, rolls, who).map(|mut snap| { - snap.source_unit = loot.source().is_some_and(|g| objects.is_unit(g)); + let view = |w: &Window, ask: Ask<'_>| { + snapshot(w, &items, icons.as_deref(), ask, rolls, who).map(|mut snap| { + snap.source_unit = w.source.is_some_and(|g| objects.is_unit(g)); snap }) }; + let waits = |snap: &Option| { + snap.as_ref() + .is_some_and(|snap| templates_outstanding(&items, snap)) + }; let pushes = PushInputs { items: &items, icons: icons.as_deref(), @@ -872,102 +912,239 @@ fn feed_loot( chat: &chat, rolls, }; - let (mut ahead, mut after, mut behind) = (Vec::new(), Vec::new(), Vec::new()); - for r in std::mem::take(&mut vm.own().0.receives) { - match r.at { - PushAt::Ahead => ahead.push(r), - PushAt::After(k) => after.push((k, r)), - PushAt::Behind => behind.push(r), - } + let (receives, steps) = { + let (mut s, _) = vm.own(); + ( + std::mem::take(&mut s.loot.receives), + std::mem::take(&mut s.loot.steps), + ) + }; + let mut between: Vec> = (0..=steps.len()).map(|_| Vec::new()).collect(); + for r in receives { + let k = r.at.min(steps.len()); + between[k].push(r); } - let mut still = emit_pushes(&mut vm, ahead, &pushes); - // The removals before each push, shown as the window they left: its `LOOT_SLOT_CLEARED`s - // (`0x4c1f00`) come before the push's `ITEM_PUSH`. - let mut shown = 0; - let mut after = after.into_iter().peekable(); - while let Some(&(k, _)) = after.peek() { - if k > shown { - vm.turn(|script, (loot, _)| { - let Some(script) = script else { - return; - }; - let last = last.get(script); - if last.is_some() { - show_window(script, last, view(&loot.as_of(k), Ask::Read), &items); + let last_open = steps.iter().rposition(|s| matches!(s, Step::Opened { .. })); + // A step of a session a later response replaced runs on the cells it left, as its packet's + // dispatch ran it before the next arrived; the steps after the last response, on the window. + let replaced = |k: usize| last_open.is_some_and(|last| k < last); + let mut between = between.into_iter(); + let mut still = emit_pushes(&mut vm, between.next().unwrap_or_default(), &pushes); + for ((k, step), after) in steps.into_iter().enumerate().zip(between) { + match step { + Step::Changed(w) => { + let live = replaced(k).then(|| swap_in_cells(&mut vm, w.clone())); + vm.turn(|script, _| { + if let Some(script) = script { + show(script, view(&w, Ask::Read)); + } + }); + if let Some(live) = live { + restore_live(&mut vm, live); } - }); - shown = k; + } + Step::SlotCleared(row) => vm.turn(|script, _| { + if let Some(script) = script { + script.fire_event("LOOT_SLOT_CLEARED", vec![ScriptValue::Int(i64::from(row))]); + } + }), + Step::Unlocks(unlocks) => vm.turn(|script, (steps, _)| { + if let Some(script) = script { + fire_unlocks(script, unlocks, &steps.objects); + } + }), + Step::Opened { ended, window: w } => { + // The copier ends the session the VM shows (`0x4c1ccb`-`0x4c1dac`): its + // `LOOT_CLOSED` handlers run on the cells the teardown leaves, the source zeroed, + // before the new source is stored (`0x4c1dc2`), so their `CloseLoot` finds no + // window (`0x48f23f`). The stash clear comes after them (`0x4c1df5`). + let live = swap_in_cells(&mut vm, ended); + vm.turn(|script, _| { + if let Some(script) = script.filter(|s| s.shown_loot().is_some()) { + show(script, None); + } + }); + restore_live(&mut vm, live); + vm.own().0.loot.pending_bind_confirm = None; + let waiting = vm.turn(|script, _| { + let Some(script) = script else { + return true; + }; + // Then the type cell (`0x4c1dd6`), the window, and each row's record asked + // for (`0x4c1e77`). + script.set_loot_type(w.loot_type); + let snap = view(&w, Ask::Event(&commands)); + let waiting = waits(&snap); + show(script, snap); + waiting + }); + if !waiting { + if Some(k) != last_open { + let moving = vm.own().1 .0; + end_superseded_open(&mut vm, w, moving); + } else if vm.own().0.loot.copier_due { + let moving = std::mem::take(&mut vm.own().1 .0); + end_open(&mut vm, moving); + } + } + } } - let batch = std::iter::from_fn(|| after.next_if(|(j, _)| *j == k).map(|(_, r)| r)); - let batch = batch.collect(); - still.extend(emit_pushes(&mut vm, batch, &pushes)); + still.extend(emit_pushes(&mut vm, after, &pushes)); } - let opened = vm.turn(|script, (mut loot, _)| { + if vm.own().0.loot.sweep_owed { + vm.turn(|script, (mut steps, _)| { + steps.loot.sweep_owed = false; + if let (Some(script), true) = (script, steps.loot.source().is_some()) { + steps.sweep(script, false); + } + }); + run_then(&mut vm); + } + let late = vm.turn(|script, (steps, _)| { let Some(script) = script else { return false; }; - let last = last.get(script); - if std::mem::take(&mut loot.sweep_owed) && loot.source.is_some() { - sweep_rows(&mut loot, &items, &commands, script, &mut pickup); - } - let ask = if std::mem::take(&mut loot.opened) { - Ask::Event(&commands) - } else { - Ask::Read - }; - show_window(script, last, view(&loot, ask), &items) + // A new VM's type cell too (`/reload`): the C cell outlives the interface. + script.set_loot_type(steps.loot.window.loot_type); + let snap = view(&steps.loot.window, Ask::Read); + let ready = steps.loot.copier_due && !waits(&snap); + show(script, snap); + ready }); - // An owed sweep's bind confirm, once its handlers ran. - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); + if late { + let moving = std::mem::take(&mut vm.own().1 .0); + end_open(&mut vm, moving); } - if opened { - // Auto-loot (`LootConfig`), inverted by a held Shift: every row gets a hand pick's sends, - // and emptying the window auto-releases it. - let shift = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight); - if cfg.auto_loot != shift { - vm.turn(|script, (mut loot, _)| { - if let Some(script) = script { - sweep_rows(&mut loot, &items, &commands, script, &mut pickup); - } - }); - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); + // What waits on its template fires ahead of the next frame's steps. + let (mut s, _) = vm.own(); + for r in &mut still { + r.at = 0; + } + still.append(&mut s.loot.receives); + s.loot.receives = still; +} + +/// The copier end of a response a later one in the same frame replaced, which the reference ran +/// inside its own packet's dispatch (`0x4c1ea8`-`0x4c1ee6`) before the next arrived: on its own +/// window, which the live cells take for the while, then the next copier's resets over what it +/// left (`0x4c1d95`, `0x4c1def`, `0x4c1df5`). What it closes it releases; its teardown's step is +/// the replacing window's to show. +fn end_superseded_open( + vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, + own: Window, + moving: bool, +) { + let live = swap_in_cells(vm, own); + end_open(vm, moving); + restore_live(vm, live); + let (mut s, _) = vm.own(); + let loot = &mut *s.loot; + loot.copier_due = true; + loot.coin_line_shown = false; + loot.sweep_owed = false; + loot.pending_bind_confirm = None; +} + +/// The live window and the steps' mark, set aside while a step runs on the cells it left. +struct Live { + window: Window, + mark: usize, +} + +/// Put `cells`, the loot cells as a step left them, in the window's place for that step's turn. +fn swap_in_cells( + vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, + cells: Window, +) -> Live { + let (mut s, _) = vm.own(); + Live { + window: std::mem::replace(&mut s.loot.window, cells), + mark: s.loot.steps.len(), + } +} + +/// Put the live window back: the later copier rewrote every cell (`0x4c1dc2` on), so what the +/// step's handlers changed in them goes, with the steps their calls queued. +fn restore_live( + vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, + live: Live, +) { + let (mut s, _) = vm.own(); + s.loot.window = live.window; + s.loot.steps.truncate(live.mark); +} + +/// A response's end, once its window is filled: the copier's end ([`LootSteps::copier_end`]) and +/// what its signals owe, then the response's tail (`0x5ebc3a`-`0x5ebc51`): a window opened while +/// we move (`moving`, [`LootMoveStart`]) takes the move-start close in the same handler, so it +/// never paints. +fn end_open( + vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, + moving: bool, +) { + vm.turn(|script, (mut steps, _)| { + steps.loot.copier_due = false; + if let Some(script) = script { + steps.copier_end(script); + } + }); + run_then(vm); + if !moving { + return; + } + vm.turn(|script, (mut steps, _)| { + let closed = close_on_move_start(&mut steps.loot, &mut steps.latch, &steps.net); + if closed.is_some() { + steps.dead.after_close(closed); + if let Some(script) = script { + show(script, None); } } - // The response's tail (`0x5ebc3a`-`0x5ebc51`) closes a window that opened while we move, - // after the copier's open and sweep and in the same handler: `LOOT_CLOSED` fires in this - // pass, so the window never paints. - vm.turn(|script, (mut loot, mut moving)| { - let Some(script) = script else { - return; - }; - if !std::mem::take(&mut moving.move_start.0) { - return; - } - let closed = close_on_move_start(&mut loot, &mut moving.latch, &commands); - if closed.is_some() { - moving.dead.after_close(closed); - script.set_loot(None); - script.fire_event("LOOT_CLOSED", vec![]); - *last.get(script) = None; + }); +} + +/// Run what the steps owe once their signals' handlers have run ([`calls::Then`]), each a turn +/// of its own, innermost first. +fn run_then( + vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, +) { + loop { + let Some(then) = vm.own().0.loot.then.pop() else { + break; + }; + vm.turn(|script, (mut steps, _)| { + if let Some(script) = script { + steps.then(script, then); } }); } - still.extend(emit_pushes(&mut vm, behind, &pushes)); - // The window is shown as it stands: the next frame's pushes and removals count from it. - let (mut loot, _) = vm.own(); - for r in &mut still { - r.at = PushAt::Ahead; +} + +/// Push `fresh` over the window the VM shows and signal what went: `LOOT_SLOT_CLEARED` for each +/// row, with its position plus one (`0x4c1f77`, `0x4c276f`), `UPDATE_MASTER_LOOT_LIST` for a new +/// candidate list (`LootFrame.lua:62-64`), and `LOOT_CLOSED` for the window (`0x4c1dac`). A window +/// that appears signals nothing: its copier's end does. +fn show(script: &mut UiScript, fresh: Option) { + let before = script.shown_loot(); + if before == fresh { + return; + } + script.set_loot(fresh.clone()); + match (before, fresh) { + (Some(before), Some(after)) => { + for (i, was) in before.rows.iter().enumerate() { + let gone = was.is_some() && after.rows.get(i).is_none_or(Option::is_none); + if gone { + script.fire_event("LOOT_SLOT_CLEARED", vec![ScriptValue::Int(i as i64 + 1)]); + } + } + if before.master_candidates != after.master_candidates { + script.fire_event("UPDATE_MASTER_LOOT_LIST", vec![]); + } + } + (Some(_), None) => script.fire_event("LOOT_CLOSED", vec![]), + (None, _) => {} } - still.append(&mut loot.receives); - loot.receives = still; - loot.removed.clear(); - loot.replaced = false; } /// What a push's firing reads. @@ -981,7 +1158,7 @@ struct PushInputs<'a> { /// Fire `batch` as one turn ([`drain_receives`]); what still waits on its template comes back. fn emit_pushes( - vm: &mut crate::script_calls::VmWith<'_, '_, P>, + vm: &mut VmWith<'_, '_, P>, batch: Vec, with: &PushInputs, ) -> Vec { @@ -1002,108 +1179,32 @@ fn emit_pushes( }) } -/// Push `fresh` over `last`, the window the VM shows, and fire what changed; whether -/// `LOOT_OPENED` fired. -fn show_window( - script: &mut UiScript, - last: &mut Option, - fresh: Option, - items: &Items, -) -> bool { - if fresh == *last { - return false; - } - script.set_loot(fresh.clone()); - let opened = match (&*last, &fresh) { - (None, Some(snap)) => { - // No window until every template has landed: the copier fires nothing while a query - // is pending (`0x4c1e9f`), and the cache callback `0x4c2ac0` fires `LOOT_OPENED` - // (or the auto-loot sweep) at the last answer. Not advancing `last` retries next - // frame. - if templates_outstanding(items, snap) { - return false; - } - script.fire_event("LOOT_OPENED", vec![]); - true - } - // One `LOOT_SLOT_CLEARED` per row that went, with its 1-based row: the stock handler - // hides that button and pages down when the page empties (`LootFrame.lua:22-50`). - (Some(before), Some(after)) => { - for (i, was) in before.rows.iter().enumerate() { - let gone = was.is_some() && after.rows.get(i).is_none_or(Option::is_none); - if gone { - script.fire_event("LOOT_SLOT_CLEARED", vec![ScriptValue::Int(i as i64 + 1)]); - } - } - // Refreshes an open dropdown in place (`LootFrame.lua:62-64`). - if before.master_candidates != after.master_candidates { - script.fire_event("UPDATE_MASTER_LOOT_LIST", vec![]); - } - false - } - (Some(_), None) => { - script.fire_event("LOOT_CLOSED", vec![]); - false - } - (None, None) => false, - }; - *last = fresh; - opened -} - /// [`feed_loot`] as a one-shot, for a test that drives the window from outside the module. #[cfg(test)] pub(crate) fn feed_loot_once(world: &mut World) { use bevy::ecs::system::RunSystemOnce; + seat_loot_steps(world); world .run_system_once(feed_loot) .expect("the loot feed runs as a one-shot system"); } -/// The sweep `0x4c1fa0`, auto-loot's and a disenchant hold's: every row gets a hand pick's sends, -/// and emptying the window auto-releases it. Only `ALLOW_LOOT` rows (`0x4c2180`/`0x4c2196`); a -/// hand click's bind gate plus a one-shot latch (`0x4c21c2`, `0x4c21e2`): later bind-on-pickup -/// rows stay, untaken and unasked. The asked row is owed to the stash, which the caller settles -/// once the turn's handlers ran ([`settle_bind_confirm`]). -fn sweep_rows( - loot: &mut LootState, - items: &Items, - commands: &NetCommands, - script: &mut UiScript, - pickup: &mut MessageWriter, -) { - let mut bind_confirm_fired = false; - for index in 1..=loot.row_count() { - match loot.action_at(index) { - Some(LootAction::Money) => { - let _ = commands.0.send(ClientCommand::LootMoney); - } - Some(LootAction::Item { - wire_slot, - display_id, - item_id, - slot_type, - }) if slot_type == slot_type::ALLOW_LOOT => { - if bind_confirm_required(items, item_id) { - if bind_confirm_fired { - continue; - } - script.fire_event( - "LOOT_BIND_CONFIRM", - vec![ScriptValue::Int(i64::from(index))], - ); - loot.owed_bind_confirm = Some(index); - bind_confirm_fired = true; - continue; - } - let _ = commands - .0 - .send(ClientCommand::AutostoreLootItem { slot: wire_slot }); - pickup.write(crate::sound::LootPickupSound { display_id }); - } - Some(LootAction::Item { .. }) | None => {} - } - } +/// Seat what [`LootSteps`] reads that a harness's world need not hold; the commands are the +/// harness's own. +#[cfg(test)] +pub(crate) fn seat_loot_steps(world: &mut World) { + use bevy::ecs::message::Messages; + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::>(); + world.init_resource::>(); } /// Whether a take must raise `LOOT_BIND_CONFIRM` first (`0x4c28f2`/`0x4c28fb`): bind on pickup @@ -1123,7 +1224,7 @@ pub(crate) fn close_interaction( latch: &mut LootLatch, release: Option<&NetCommands>, ) -> Option { - let source = loot.source?; + let source = loot.source()?; latch.clear_for(source); if let Some(commands) = release { let _ = commands.0.send(ClientCommand::LootRelease { guid: source }); @@ -1140,59 +1241,39 @@ pub(crate) fn close_interaction( /// The leave-world sweep's loot leg (`0x490ab2` β†’ `0x4c1ca0` β†’ `0x48f200(cl=1, dl=0, 0)`): the /// shared close with its `CMSG_LOOT_RELEASE` (`0x48f2da`), told to the VM the sweep runs in, the /// dying one on a `/reload` ([`tell_loot_closed`]). The dead-unit deselect follows, as the -/// close's last step. A disenchant window with rows left is swept instead -/// ([`LootState::disenchant_holds`]). -pub(crate) fn close_loot_on_leave_world( - mut vm: crate::script_calls::VmWith<(ResMut<'static, LootState>, ResMut<'static, LootLatch>)>, - commands: Res, - objects: crate::net::Objects, - mut dead: DeadUnitDeselect, - sweep: LegSweepInputs, -) { - let LegSweepInputs { items, mut pickup } = sweep; - let closed = vm.turn(|script, (mut loot, mut latch)| { - if loot.disenchant_holds() { - if let Some(script) = script { - sweep_rows(&mut loot, &items, &commands, script, &mut pickup); - } else { - loot.owe_sweep(); +/// close's last step. A disenchant window with contents is swept instead +/// ([`LootState::disenchant_hold`]). +pub(crate) fn close_loot_on_leave_world(mut vm: VmWith<(LootSteps<'static, 'static>, ())>) { + let closed = vm.turn(|script, (mut steps, _)| { + if steps.loot.disenchant_hold(&steps.objects) { + match script { + Some(script) => steps.sweep(script, false), + None => steps.loot.owe_sweep(), } return None; } - let closed = close_interaction(&mut loot, &mut latch, Some(&commands))?; + let closed = close_interaction(&mut steps.loot, &mut steps.latch, Some(&steps.net))?; if let Some(script) = script { - unlock_closed_source(script, &mut loot, &objects); + unlock_closed_source(script, &mut steps.loot, &steps.objects); } Some(closed) }); + run_then(&mut vm); if closed.is_none() { - // The sweep's bind confirm, once its handlers ran. - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); - } return; } - vm.turn(|script, _| { + vm.turn(|script, (mut steps, _)| { if let Some(script) = script { announce_loot_closed(script); } - dead.after_close(closed); + steps.dead.after_close(closed); }) } -/// What the loot leg's disenchant hold sweeps with. -#[derive(bevy::ecs::system::SystemParam)] -pub(crate) struct LegSweepInputs<'w> { - items: Res<'w, Items>, - pickup: MessageWriter<'w, crate::sound::LootPickupSound>, -} - /// Tell the VM in the world that a close the feed will not see closed the window: the UI /// shutdown's deselect closing the loot on its target (`0x490bdf` β†’ `0x493910` β†’ `0x48f200`). pub(crate) fn tell_loot_closed( - mut vm: crate::script_calls::VmWith>, + mut vm: VmWith>, objects: crate::net::Objects, ) { vm.turn(|script, mut loot| { @@ -1216,7 +1297,13 @@ fn unlock_closed_source( loot: &mut LootState, objects: &crate::net::Objects, ) { - for (guid, live) in loot.take_item_unlocks() { + fire_unlocks(script, loot.take_item_unlocks(), objects); +} + +/// `UnlockItem` (`0x495420`) on each guid, with its `ITEM_LOCK_CHANGED`; one flagged as a +/// window source's only while it resolves as a live item object. +fn fire_unlocks(script: &mut UiScript, unlocks: Vec<(u64, bool)>, objects: &crate::net::Objects) { + for (guid, live) in unlocks { if !live || objects.object(guid).is_some_and(|f| f.is_item()) { script.unlock_item(guid); } @@ -1279,7 +1366,7 @@ fn close_on_move_start( use benilla_protocol::guid; use benilla_protocol::messages::loot_type; let source = loot.source()?; - if loot.loot_type == loot_type::DISENCHANTING && !loot.is_empty() { + if loot.window.loot_type == loot_type::DISENCHANTING && !loot.window.is_empty() { return None; } if guid::is_item(source) { @@ -1289,261 +1376,51 @@ fn close_on_move_start( close_interaction(loot, latch, Some(commands)) } -/// What [`feed_loot`] needs to take the move-start close on a window it has just opened. -#[derive(bevy::ecs::system::SystemParam)] -struct OpenWhileMoving<'w, 's> { - move_start: ResMut<'w, LootMoveStart>, - latch: ResMut<'w, LootLatch>, - dead: DeadUnitDeselect<'w, 's>, -} +/// The closes the drain takes: the movement start's and the precast end's at rest. +type OwedCloses = ( + ResMut<'static, LootMoveStart>, + ResMut<'static, LootCloseAtRest>, +); -/// Sends what the Lua asked for, as the take dispatcher `0x4c2790(slot, flag)`: a row click -/// (a `LootButton`'s own, flag 0) and the `LOOT_BIND` confirm (`LootSlot`, flag 1) stay apart, so -/// a second click on a bind-on-pickup row asks again, and run in their call order, so a confirm -/// meets the stash as it stood at its call. A step that signals is a turn whose handlers run as it -/// ends, as the reference runs them inside the step (`0x4c2920`), and what they ask goes out in -/// this pass. -fn drain_loot( - mut vm: crate::script_calls::VmWith<(ResMut<'static, LootState>, ResMut<'static, LootLatch>)>, - commands: Res, - mut pickup: MessageWriter, - group: Res, - items: Res, - // The move-start close and the close at rest run before the VM check: they need no Lua. - mut move_start: ResMut, - mut at_rest: ResMut, - mut dead: DeadUnitDeselect, - errors: Res, -) { - // The input pass's takes, ahead of anything the closes' handlers ask. - let takes = vm.run(|script| script.map(UiScript::take_loot_takes).unwrap_or_default()); - vm.turn(|script, (mut loot, mut latch)| { +/// The closes the frame owes from outside the VM, after the input pass: the movement start's +/// ([`LootMoveStart`]) and the precast end's at rest ([`LootCloseAtRest`]), which sweeps a +/// disenchant window with rows left instead. The feed signals `LOOT_CLOSED` for them. +fn drain_loot(mut vm: VmWith<(LootSteps<'static, 'static>, OwedCloses)>) { + vm.turn(|script, (mut steps, (mut move_start, mut at_rest))| { if std::mem::take(&mut move_start.0) { - dead.after_close(close_on_move_start(&mut loot, &mut latch, &commands)); + let closed = close_on_move_start(&mut steps.loot, &mut steps.latch, &steps.net); + steps.dead.after_close(closed); } // After the move-start close, which it subsumes: whichever runs first, a window either // keeps is the one this takes. if std::mem::take(&mut at_rest.0) { - if loot.disenchant_holds() { + if steps.loot.disenchant_hold(&steps.objects) { match script { - Some(script) => sweep_rows(&mut loot, &items, &commands, script, &mut pickup), - None => loot.owe_sweep(), + Some(script) => steps.sweep(script, false), + None => steps.loot.owe_sweep(), } } else { - dead.after_close(close_interaction(&mut loot, &mut latch, Some(&commands))); + let closed = close_interaction(&mut steps.loot, &mut steps.latch, Some(&steps.net)); + steps.dead.after_close(closed); } } }); - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); - } - for take in takes { - match take { - LootTake::Confirm(index) => { - answer_bind_confirm(&mut vm.own().0, index, &commands, &mut pickup); - } - LootTake::Pick(index) => { - vm.turn(|script, (mut loot, _)| { - if let Some(script) = script { - take_row(script, &mut loot, index, &items, &commands, &mut pickup); - } - }); - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); - } - } - } - } - vm.turn(|script, (mut loot, mut latch)| { - let Some(script) = script else { - return; - }; - // What the takes' other handlers asked: an `OPEN_MASTER_LOOT_LIST` handler's `LootSlot`. - for index in script.take_loot_confirms() { - answer_bind_confirm(&mut loot, index, &commands, &mut pickup); - } - // `GiveMasterLoot(slot, candidateIndex)`, both 1-based; one that does not resolve is - // dropped. - for (index, candidate) in script.take_loot_master_gives() { - let Some(guid) = loot.source else { - continue; - }; - let ( - Some(LootAction::Item { - wire_slot, - slot_type, - .. - }), - Some(target), - ) = ( - loot.action_at(index), - loot.master_candidate(candidate, &group), - ) - else { - debug!("ui_loot: GiveMasterLoot({index}, {candidate}) unresolvable β€” ignored"); - continue; - }; - // Only a master row: the sender `0x4c2940` re-reads the slot type and bails unless it - // is 2. - if slot_type != slot_type::MASTER { - debug!("ui_loot: GiveMasterLoot({index}) is not a master row β€” ignored"); - continue; - } - debug!("ui_loot: master-give row {index} (wire slot {wire_slot}) to {target:#x}"); - let _ = commands.0.send(ClientCommand::LootMasterGive { - guid, - slot: wire_slot, - target, - }); - } - // `CloseLoot` (`0x4c2ec0` β†’ `0x48f200(cl=1, dl=0)`), which stock `LootFrame_OnHide` calls. - if let Some(failed) = script.take_loot_close() { - if loot.disenchant_holds() { - debug!("ui_loot: CloseLoot on a disenchant window with rows left β€” sweeping it"); - sweep_rows(&mut loot, &items, &commands, script, &mut pickup); - } else { - // Past the no-loot and disenchant returns, a set flag shows `ERR_LOOT_NO_UI` - // (`0x48f272`-`0x48f280`, `DisplayError(0x87)`) before the release. - if failed && loot.source().is_some() { - errors.push(UiError::key("ERR_LOOT_NO_UI")); - } - let closed = close_interaction(&mut loot, &mut latch, Some(&commands)); - if let Some(guid) = closed { - debug!("ui_loot: release loot {guid:#x}"); - } - dead.after_close(closed); - } - } - // The last-row auto-close (`0x4c1f8d`, `0x4c2785` β†’ `0x48f200(cl=1, dl=0)`). The feed then - // fires `LOOT_CLOSED`, and the `CloseLoot()` from `OnHide` finds no source. - if loot.take_auto_release() { - let closed = close_interaction(&mut loot, &mut latch, Some(&commands)); - if let Some(guid) = closed { - debug!("ui_loot: loot emptied β€” auto-release {guid:#x}"); - } - dead.after_close(closed); - } - }); - // A `CloseLoot` on a disenchant window swept it. - if vm.own().0.owes_bind_confirm() { - vm.turn(|script, (mut loot, _)| { - settle_bind_confirm(script, &mut loot, &commands, &mut pickup); - }); - } + run_then(&mut vm); } - -/// The flag-0 take of display row `index`, a `LootButton`'s click (`0x4c2790(slot, 0)`). -fn take_row( - script: &mut UiScript, - loot: &mut LootState, - index: u32, - items: &Items, - commands: &NetCommands, - pickup: &mut MessageWriter, -) { - match loot.action_at(index) { - Some(LootAction::Money) => { - // No sound here: the coinage watcher (`sound::money`) plays it as the purse rises. - debug!("ui_loot: loot coin (row {index})"); - let _ = commands.0.send(ClientCommand::LootMoney); - } - // A master-loot row opens the candidate dropdown instead: the dispatcher branches on the - // slot type (`0x4c28a9`), and the Lua `OnClick` has already stashed the anchor. - Some(LootAction::Item { slot_type, .. }) if slot_type == slot_type::MASTER => { - debug!("ui_loot: row {index} is master-loot β€” opening the candidate list"); - script.fire_event("OPEN_MASTER_LOOT_LIST", vec![]); - } - Some(LootAction::Item { - wire_slot, - display_id, - item_id, - .. - }) => { - // The bind-on-pickup deferral (`0x4c28f2`-`0x4c2920`): fire the event, then owe the - // stash the row; send nothing, not even the pickup sound. - if bind_confirm_required(items, item_id) { - debug!("ui_loot: row {index} (wire {wire_slot}) binds on pickup β€” confirming"); - script.fire_event( - "LOOT_BIND_CONFIRM", - vec![ScriptValue::Int(i64::from(index))], - ); - loot.owed_bind_confirm = Some(index); - return; - } - debug!("ui_loot: autostore row {index} (wire slot {wire_slot})"); - let _ = commands - .0 - .send(ClientCommand::AutostoreLootItem { slot: wire_slot }); - // At the click, before any answer (`0x4c2926`): the item's ItemGroupSounds kit 0. - pickup.write(crate::sound::LootPickupSound { display_id }); - } - None => debug!("ui_loot: row {index} clicked out of range β€” ignored"), - } -} - -/// `LootSlot`, the confirm arm (`0x4c27c0`): it sends only for the pending row and clears the -/// stash on the send (`0x4c281a`), so a doubled OnAccept cannot loot twice. -fn answer_bind_confirm( - loot: &mut LootState, - index: u32, - commands: &NetCommands, - pickup: &mut MessageWriter, -) { - if loot.pending_bind_confirm != Some(index) { - debug!("ui_loot: LootSlot({index}) is not the pending bind confirm β€” ignored"); - return; - } - let Some(LootAction::Item { - wire_slot, - display_id, - .. - }) = loot.action_at(index) - else { - // The row went under the dialog: bail without clearing the stash, as `0x4c27d7` does. - debug!("ui_loot: bind confirm for row {index} β€” the row is gone, nothing sent"); - return; - }; - loot.pending_bind_confirm = None; - debug!("ui_loot: bind-confirmed row {index} (wire slot {wire_slot})"); - let _ = commands - .0 - .send(ClientCommand::AutostoreLootItem { slot: wire_slot }); - pickup.write(crate::sound::LootPickupSound { display_id }); -} - -/// The stash a `LOOT_BIND_CONFIRM` owes, once the turn that signalled it has run its handlers: -/// their own `LootSlot` calls are answered first, against the stash as it stood (`0x4c27c0`), so -/// one inside the handler sends nothing; then the stash takes the row (`0x4c2917`, `0x4c21dc`). -fn settle_bind_confirm( - script: Option<&mut UiScript>, - loot: &mut LootState, - commands: &NetCommands, - pickup: &mut MessageWriter, -) { - let Some(row) = loot.owed_bind_confirm.take() else { - return; - }; - if let Some(script) = script { - for index in script.take_loot_confirms() { - answer_bind_confirm(loot, index, commands, pickup); - } - } - loot.pending_bind_confirm = Some(row); -} - #[cfg(test)] mod tests { use super::*; + use crate::ui_action::UiErrorKeys; use benilla_protocol::messages::loot_type; + use benilla_protocol::messages::slot_type; use benilla_protocol::messages::GroupMemberEntry; use benilla_protocol::messages::ItemInfo; use benilla_protocol::messages::ObjectFields; use benilla_protocol::EntityKind; + use benilla_protocol::SessionEvent; + use benilla_ui::script::{CallHost, CallTail, ScriptCall}; use bevy::ecs::system::RunSystemOnce; + use bevy::ecs::system::SystemState; fn nobody() -> (GroupState, NameCache) { (GroupState::default(), NameCache::default()) @@ -1617,6 +1494,81 @@ mod tests { assert!(!app.world().resource::().0); } + /// A bare world with what the loot systems read and write, the feed's other inputs at rest. + fn bare_app() -> (App, crossbeam_channel::Receiver) { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + app.add_message::() + .add_message::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)); + // Our player, whom the take and the sweep ask for (`0x4c27b6`, `0x4c1fd9`). + app.world_mut().spawn(crate::net::SelfPlayer); + (app, rx) + } + + /// Stream `guid` as an object with `fields`, which the object manager then resolves. + fn stream(app: &mut App, guid: u64, kind: EntityKind, fields: &[(u16, u32)]) { + let e = app + .world_mut() + .spawn(( + crate::net::NetEntity { + kind, + display_id: None, + scale: 1.0, + }, + crate::net::ObjectStore(ObjectFields::from_pairs(fields)), + )) + .id(); + app.world_mut() + .resource_mut::() + .0 + .insert(guid, e); + } + + /// A host over a bare loot world: the loot calls apply through [`LootSteps`], as the engine's + /// host applies them; any other call is dropped. + struct LootHost<'a>(&'a mut World); + + impl CallHost for LootHost<'_> { + fn apply(&mut self, script: &mut UiScript, call: ScriptCall) -> Option { + let ScriptCall::Loot(call) = call else { + return None; + }; + let mut state = SystemState::::new(self.0); + let tail = state.get_mut(self.0).apply(script, call); + state.apply(self.0); + tail + } + } + + /// Run `f` on the app's VM with a [`LootHost`] lent, as every entry that runs Lua lends one. + fn hosted(app: &mut App, f: impl FnOnce(&mut UiScript) -> R) -> R { + let mut script = app + .world_mut() + .remove_non_send_resource::() + .expect("a VM"); + let r = script.hosted(&mut LootHost(app.world_mut()), f); + app.world_mut().insert_non_send_resource(script); + r + } + + /// Run `lua` with a [`LootHost`] lent. + fn run_hosted(app: &mut App, lua: &str) { + hosted(app, |s| s.run(lua)).expect("the chunk runs"); + } + // ── The soulbind confirm ────────────────────────────────────────────────── // // vmangos `item_template` rows: Felstriker a BoP epic, Flurry Axe a BoE epic, Tough Jerky a @@ -1629,7 +1581,7 @@ mod tests { const SECOND_BOP: u32 = 18832; /// A loot window over `rows` whose display rows `clicks` are clicked by the mouse, as a - /// `LootButton` takes (`0x4c1820`), then `lua` run, then one drain. + /// `LootButton` takes (`0x4c1820`), then `lua` run, each with the host lent. fn drain_with( gold: u32, rows: Vec, @@ -1647,20 +1599,7 @@ mod tests { clicks: &[u32], lua: &str, ) -> (App, crossbeam_channel::Receiver) { - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .insert_resource(NetCommands(tx)); - + let (mut app, rx) = bare_app(); let mut items = app.world_mut().resource_mut::(); let mut tmpl = |entry: u32, name: &str, quality: u32, bonding: u32| { items.insert_template( @@ -1680,6 +1619,7 @@ mod tests { app.world_mut() .resource_mut::() .open(0x42, loot_type::CORPSE, gold, rows); + app.world_mut().resource_mut::().0 = Some(0x42); let mut script = UiScript::new().unwrap(); script @@ -1691,22 +1631,23 @@ mod tests { ) .unwrap(); script.set_screen_size(1024.0, 768.0); - script.run(first).unwrap(); - for &row in clicks { - script - .run(&format!( - "local b = CreateFrame(\"LootButton\", \"DrainRow\", UIParent)\n\ - b:SetPoint(\"BOTTOMLEFT\", 100, 100) b:SetWidth(50) b:SetHeight(50)\n\ - b:EnableMouse(true) b:Show() b:SetSlot({row})" - )) - .unwrap(); - script.resolve(); - script.mouse_button(125.0, 125.0, "LeftButton", true); - script.mouse_button(125.0, 125.0, "LeftButton", false); - } - script.run(lua).unwrap(); app.insert_non_send_resource(script); - app.world_mut().run_system_once(drain_loot).unwrap(); + run_hosted(&mut app, first); + for &row in clicks { + hosted(&mut app, |script| { + script + .run(&format!( + "local b = CreateFrame(\"LootButton\", \"DrainRow\", UIParent)\n\ + b:SetPoint(\"BOTTOMLEFT\", 100, 100) b:SetWidth(50) b:SetHeight(50)\n\ + b:EnableMouse(true) b:Show() b:SetSlot({row})" + )) + .unwrap(); + script.resolve(); + script.mouse_button(125.0, 125.0, "LeftButton", true); + script.mouse_button(125.0, 125.0, "LeftButton", false); + }); + } + run_hosted(&mut app, lua); (app, rx) } @@ -1716,25 +1657,8 @@ mod tests { fn the_loot_portrait_follows_a_unit_source_only() { use benilla_protocol::ObjectFields; for (unit, expected) in [(true, true), (false, false)] { - let (tx, _rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - // What the feed's move-start close reads (`OpenWhileMoving`). - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::>() - .init_resource::() - .init_resource::() - .insert_resource(NetCommands(tx)) - .add_systems(bevy::prelude::Update, feed_loot); + let (mut app, _rx) = bare_app(); + app.add_systems(bevy::prelude::Update, feed_loot); // OBJECT_FIELD_TYPE (2): TYPEMASK_OBJECT | TYPEMASK_UNIT for a creature, | 0x20 for a // game object. let kind = if unit { 0x9 } else { 0x21 }; @@ -1779,25 +1703,8 @@ mod tests { }), None, ] { - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - // What the feed's move-start close reads (`OpenWhileMoving`). - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::>() - .init_resource::() - .insert_resource(NetCommands(tx)) - // Scheduled, not `run_system_once`: the `Local` memo must persist across frames. - .add_systems(bevy::prelude::Update, feed_loot); + let (mut app, rx) = bare_app(); + app.add_systems(bevy::prelude::Update, feed_loot); app.world_mut().resource_mut::().open( 0x42, loot_type::CORPSE, @@ -1899,11 +1806,7 @@ mod tests { assert_eq!(pending_confirm(&app), None, "and the stash clears"); // A second accept over the same dialog: nothing left to complete. - app.world_mut() - .non_send_resource_mut::() - .run("LootSlot(1)") - .unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); + run_hosted(&mut app, "LootSlot(1)"); assert!(sent(&rx).is_empty(), "a second accept sends nothing"); } @@ -1926,11 +1829,7 @@ mod tests { Some(1), "the stash takes the row after it" ); - app.world_mut() - .non_send_resource_mut::() - .run("LootSlot(1)") - .unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); + run_hosted(&mut app, "LootSlot(1)"); assert!( matches!( sent(&rx)[..], @@ -2009,11 +1908,7 @@ mod tests { assert!(sent(&rx).is_empty()); // The accept, with the same number, reaches the right wire slot. - app.world_mut() - .non_send_resource_mut::() - .run("LootSlot(2)") - .unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); + run_hosted(&mut app, "LootSlot(2)"); assert!(matches!( sent(&rx)[..], [ClientCommand::AutostoreLootItem { slot: 4 }] @@ -2027,9 +1922,7 @@ mod tests { assert_eq!(pending_confirm(&app), Some(1)); app.world_mut().resource_mut::().remove_slot(2); - let script = app.world_mut().non_send_resource_mut::(); - script.run("LootSlot(1)").unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); + run_hosted(&mut app, "LootSlot(1)"); assert!( sent(&rx) @@ -2039,14 +1932,15 @@ mod tests { ); } - /// `0x4c1df5`: the response copier resets the stash. + /// The close leaves the stash (`0x48f200` and `0x4c1cb0(0)` never store to `0x847cec`); the + /// next response's copier resets it (`0x4c1df5`). #[test] - fn a_pending_confirm_does_not_survive_the_window() { + fn a_pending_confirm_lasts_until_the_next_response() { let (mut app, _rx) = drain_with(0, vec![item(0, FELSTRIKER, 1)], &[1], ""); assert_eq!(pending_confirm(&app), Some(1)); app.world_mut().resource_mut::().clear(); - assert_eq!(pending_confirm(&app), None, "the close drops it"); + assert_eq!(pending_confirm(&app), Some(1), "the close keeps it"); app.world_mut().resource_mut::().open( 0x43, @@ -2061,30 +1955,13 @@ mod tests { ); } - /// A window over two BoP epics and a white (wire slots 5/6/7) with auto-loot on, its - /// `LOOT_BIND_CONFIRM` rows noted, then `lua` run; the feed has not run. + /// A window over two BoP epics and a white (wire slots 5/6/7) with the auto-loot byte the + /// interaction stored set, its `LOOT_BIND_CONFIRM` rows noted, then `lua` run; the feed has not + /// run. fn auto_loot_app(lua: &str) -> (App, crossbeam_channel::Receiver) { - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - // What the feed's move-start close reads (`OpenWhileMoving`). - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::>() - .init_resource::() - .insert_resource(LootConfig { - auto_loot: true, - ..LootConfig::default() - }) - .insert_resource(NetCommands(tx)); + let (mut app, rx) = bare_app(); + app.insert_resource(AutoLootByte(true)); + stream(&mut app, 0x42, EntityKind::Unit, &[]); let mut items = app.world_mut().resource_mut::(); for (entry, name, quality, bonding) in [ @@ -2148,41 +2025,24 @@ mod tests { ); } - /// The sweep signals `LOOT_BIND_CONFIRM` (`0x4c21d4`) before the stash takes the row - /// (`0x4c21dc`), so a `LootSlot` inside the handler finds no stash (`0x4c27c0`) and sends - /// nothing, and one after it sends the row. + /// The sweep stores the stash after its `LOOT_BIND_CONFIRM`'s listeners (`0x4c21dc` after + /// `0x4c21d4`) and sends the rows after it; an accept then sends the row. #[test] - fn a_swept_bind_confirms_own_handler_cannot_accept_it() { - let (mut app, rx) = auto_loot_app( - "local f = CreateFrame(\"Frame\")\n\ - f:RegisterEvent(\"LOOT_BIND_CONFIRM\")\n\ - f:SetScript(\"OnEvent\", function() LootSlot(arg1) end)", - ); + fn a_swept_bind_confirm_is_accepted_after_the_sweep() { + let (mut app, rx) = auto_loot_app(""); app.world_mut().run_system_once(feed_loot).unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); - assert!( - matches!( - sent(&rx)[..], - [ClientCommand::AutostoreLootItem { slot: 7 }] - ), - "the white is swept, and the handler's accept sends nothing" - ); - assert_eq!( - pending_confirm(&app), - Some(1), - "the stash takes the row after it" - ); - app.world_mut() - .non_send_resource_mut::() - .run("LootSlot(1)") - .unwrap(); - app.world_mut().run_system_once(drain_loot).unwrap(); + assert!(matches!( + sent(&rx)[..], + [ClientCommand::AutostoreLootItem { slot: 7 }] + )); + assert_eq!(pending_confirm(&app), Some(1)); + run_hosted(&mut app, "LootSlot(1)"); assert!( matches!( sent(&rx)[..], [ClientCommand::AutostoreLootItem { slot: 5 }] ), - "an accept after the handler sends the row" + "an accept after the sweep sends the row" ); } @@ -2213,30 +2073,38 @@ mod tests { loot.set_master_candidates(vec![0xA, 0xB, 0xC]); assert_eq!( - loot.master_candidate(1, &party), + loot.window.master_candidate(1, &party), None, "no window, no candidates" ); loot.open(0x42, loot_type::CORPSE, 0, vec![master_item(0, 117, 1)]); - assert_eq!(loot.master_candidate(1, &party), Some(0xA)); - assert_eq!(loot.master_candidate(3, &party), Some(0xC)); - assert_eq!(loot.master_candidate(4, &party), None, "past the end"); + assert_eq!(loot.window.master_candidate(1, &party), Some(0xA)); + assert_eq!(loot.window.master_candidate(3, &party), Some(0xC)); assert_eq!( - loot.master_candidate(0, &party), + loot.window.master_candidate(4, &party), + None, + "past the end" + ); + assert_eq!( + loot.window.master_candidate(0, &party), None, "0 is not a Lua index" ); // A refresh while the window is up applies in place. loot.set_master_candidates(vec![0xA, 0xB]); - assert_eq!(loot.master_candidate(2, &party), Some(0xB)); - assert_eq!(loot.master_candidate(3, &party), None, "the list shrank"); + assert_eq!(loot.window.master_candidate(2, &party), Some(0xB)); + assert_eq!( + loot.window.master_candidate(3, &party), + None, + "the list shrank" + ); loot.clear(); loot.open(0x43, loot_type::CORPSE, 0, vec![item(0, 117, 1)]); assert_eq!( - loot.master_candidate(1, &party), + loot.window.master_candidate(1, &party), None, "a fresh window starts empty" ); @@ -2270,35 +2138,43 @@ mod tests { // Subgroup 0 fills slots 1-2 (us at 0xA, then Cairne); subgroup 2 fills 11-12, in the // order the wire listed them. - assert_eq!(loot.master_candidate(1, &raid), Some(0xA), "us, group 1"); assert_eq!( - loot.master_candidate(2, &raid), + loot.window.master_candidate(1, &raid), + Some(0xA), + "us, group 1" + ); + assert_eq!( + loot.window.master_candidate(2, &raid), Some(0xB), "Cairne, group 1" ); for empty in [3, 4, 5, 6, 7, 8, 9, 10] { assert_eq!( - loot.master_candidate(empty, &raid), + loot.window.master_candidate(empty, &raid), None, "slot {empty} belongs to an empty group" ); } - assert_eq!(loot.master_candidate(11, &raid), Some(0xC), "Vol, group 3"); assert_eq!( - loot.master_candidate(12, &raid), + loot.window.master_candidate(11, &raid), + Some(0xC), + "Vol, group 3" + ); + assert_eq!( + loot.window.master_candidate(12, &raid), Some(0xD), "Sylvanas, group 3" ); - assert_eq!(loot.master_candidate(13, &raid), None); + assert_eq!(loot.window.master_candidate(13, &raid), None); // In a party the same list is flat, in wire order. let party = GroupState { members: raid.members.clone(), ..GroupState::default() }; - assert_eq!(loot.master_candidate(1, &party), Some(0xC)); - assert_eq!(loot.master_candidate(4, &party), Some(0xB)); - assert_eq!(loot.master_candidate(5, &party), None); + assert_eq!(loot.window.master_candidate(1, &party), Some(0xC)); + assert_eq!(loot.window.master_candidate(4, &party), Some(0xB)); + assert_eq!(loot.window.master_candidate(5, &party), None); // A raid of one holds no roster (`0x5e6e71`), so the count reads 0 and the list is flat, // whatever subgroup we sit in. @@ -2310,7 +2186,11 @@ mod tests { let mut solo = LootState::default(); solo.set_master_candidates(vec![0xA]); solo.open(0x42, loot_type::CORPSE, 0, vec![master_item(0, 117, 1)]); - assert_eq!(solo.master_candidate(1, &alone), Some(0xA), "a raid of one"); + assert_eq!( + solo.window.master_candidate(1, &alone), + Some(0xA), + "a raid of one" + ); } #[test] @@ -2323,7 +2203,7 @@ mod tests { vec![master_item(0, 117, 1), item(1, 2589, 5)], ); assert!(matches!( - loot.action_at(1), + loot.window.action_at(1), Some(LootAction::Item { wire_slot: 0, slot_type: slot_type::MASTER, @@ -2331,7 +2211,7 @@ mod tests { }) )); assert!(matches!( - loot.action_at(2), + loot.window.action_at(2), Some(LootAction::Item { wire_slot: 1, slot_type: slot_type::ALLOW_LOOT, @@ -2365,18 +2245,18 @@ mod tests { #[test] fn action_maps_coin_first_then_items_by_wire_slot() { let mut loot = LootState::default(); - assert!(loot.source.is_none()); + assert!(loot.source().is_none()); loot.open( 0x42, loot_type::CORPSE, 1234, vec![item(0, 117, 1), item(1, 2589, 5)], ); - assert!(loot.source.is_some()); + assert!(loot.source().is_some()); // Row 1 is the coin, rows 2 and 3 the items; the helper's display id is `1000 + entry`. - assert!(matches!(loot.action_at(1), Some(LootAction::Money))); + assert!(matches!(loot.window.action_at(1), Some(LootAction::Money))); assert!(matches!( - loot.action_at(2), + loot.window.action_at(2), Some(LootAction::Item { wire_slot: 0, display_id: 1117, @@ -2384,15 +2264,15 @@ mod tests { }) )); assert!(matches!( - loot.action_at(3), + loot.window.action_at(3), Some(LootAction::Item { wire_slot: 1, display_id: 3589, .. }) )); - assert!(loot.action_at(4).is_none()); - assert!(loot.action_at(0).is_none()); + assert!(loot.window.action_at(4).is_none()); + assert!(loot.window.action_at(0).is_none()); } #[test] @@ -2405,14 +2285,14 @@ mod tests { vec![item(3, 117, 1), item(7, 2589, 5)], ); assert!(matches!( - loot.action_at(1), + loot.window.action_at(1), Some(LootAction::Item { wire_slot: 3, .. }) )); assert!(matches!( - loot.action_at(2), + loot.window.action_at(2), Some(LootAction::Item { wire_slot: 7, .. }) )); - assert!(loot.action_at(3).is_none()); + assert!(loot.window.action_at(3).is_none()); } #[test] @@ -2426,12 +2306,15 @@ mod tests { ); loot.remove_slot(1); assert!(matches!( - loot.action_at(1), + loot.window.action_at(1), Some(LootAction::Item { wire_slot: 0, .. }) )); - assert!(loot.action_at(2).is_none(), "the looted row is a gap"); + assert!( + loot.window.action_at(2).is_none(), + "the looted row is a gap" + ); assert!(matches!( - loot.action_at(3), + loot.window.action_at(3), Some(LootAction::Item { wire_slot: 2, .. }) )); } @@ -2440,59 +2323,39 @@ mod tests { fn clear_money_leaves_the_coin_slot_as_a_gap() { let mut loot = LootState::default(); loot.open(0x42, loot_type::CORPSE, 500, vec![item(0, 117, 1)]); - assert!(loot.has_coin()); - assert!(matches!(loot.action_at(1), Some(LootAction::Money))); + assert!(loot.window.has_coin()); + assert!(matches!(loot.window.action_at(1), Some(LootAction::Money))); loot.clear_money(); - assert!(!loot.has_coin()); - assert!(loot.action_at(1).is_none(), "the looted coin slot is a gap"); + assert!(!loot.window.has_coin()); + assert!( + loot.window.action_at(1).is_none(), + "the looted coin slot is a gap" + ); assert!(matches!( - loot.action_at(2), + loot.window.action_at(2), Some(LootAction::Item { wire_slot: 0, .. }) )); } + /// The close zeroes the source alone (`0x4c1da0`; `0x4c1cb0(0)` returns at `0x4c1db7` before the + /// copier's clear at `0x4c1ddb`): the rows and the money stay for the take dispatcher, which + /// asks for no source, until the next response replaces them. #[test] - fn auto_release_arms_only_on_the_transition_to_empty() { + fn a_close_keeps_the_rows_until_the_next_response() { let mut loot = LootState::default(); - loot.open( - 0x42, - loot_type::CORPSE, - 500, - vec![item(0, 117, 1), item(1, 2589, 5)], - ); - loot.remove_slot(0); - assert!(!loot.take_auto_release(), "items + coin remain"); - loot.clear_money(); - assert!(!loot.take_auto_release(), "an item remains"); - loot.remove_slot(1); - assert!(loot.take_auto_release(), "last row gone β€” auto-close due"); - assert!(!loot.take_auto_release(), "the edge drains once"); - } - - #[test] - fn auto_release_arms_when_the_coin_line_is_the_last_row() { - let mut loot = LootState::default(); - loot.open(0x42, loot_type::CORPSE, 500, vec![]); - loot.clear_money(); - assert!( - loot.take_auto_release(), - "coin-only loot empties β†’ auto-close" - ); - } - - #[test] - fn empty_at_open_does_not_auto_release() { - let mut loot = LootState::default(); - // An empty window at open stays up (`LOOTWINDOWOPENEMPTY`). - loot.open(0x42, loot_type::CORPSE, 0, vec![]); - assert!(!loot.take_auto_release()); - loot.open(0x43, loot_type::CORPSE, 500, vec![]); - loot.clear_money(); - loot.open(0x44, loot_type::CORPSE, 0, vec![item(0, 117, 1)]); - assert!( - !loot.take_auto_release(), - "open() disarms the previous window's edge" - ); + loot.open(0x42, loot_type::CORPSE, 500, vec![item(3, 117, 1)]); + loot.clear(); + assert_eq!(loot.source(), None); + assert!(matches!(loot.window.action_at(1), Some(LootAction::Money))); + assert!(matches!( + loot.window.action_at(2), + Some(LootAction::Item { wire_slot: 3, .. }) + )); + loot.open(0x43, loot_type::CORPSE, 0, vec![item(5, 117, 1)]); + assert!(matches!( + loot.window.action_at(1), + Some(LootAction::Item { wire_slot: 5, .. }) + )); } #[test] @@ -2505,19 +2368,17 @@ mod tests { assert_eq!(latch.0, None, "the matching release drops it"); } + /// `IsFishingLoot` reads the type cell (`0x4c2740` == 3), which each response's copier stores + /// (`0x4c1dd6`) and the close leaves (`0x4c1cb0(0)` zeroes only the source). #[test] - fn fishing_loot_type_sets_and_clears_the_flag() { + fn the_type_cell_follows_the_responses_and_outlives_the_close() { let mut loot = LootState::default(); loot.open(0x42, loot_type::FISHING, 0, vec![item(0, 117, 1)]); - assert!(loot.fishing); + assert_eq!(loot.window.loot_type, loot_type::FISHING); loot.clear(); - assert!(!loot.fishing); + assert_eq!(loot.window.loot_type, loot_type::FISHING, "no window"); loot.open(0x42, loot_type::CORPSE, 0, vec![item(0, 117, 1)]); - assert!(!loot.fishing); - // A fishing open replaced by another, with no clear between, drops it too. - loot.open(0x42, loot_type::FISHING, 0, vec![]); - loot.open(0x43, loot_type::CORPSE, 0, vec![]); - assert!(!loot.fishing); + assert_eq!(loot.window.loot_type, loot_type::CORPSE); } #[test] @@ -2526,7 +2387,7 @@ mod tests { loot.open(0x42, loot_type::CORPSE, 0, vec![item(0, 117, 1)]); loot.push_receive(&push(117, 1, false, false)); loot.clear(); - assert!(loot.source.is_none()); + assert!(loot.source().is_none()); assert_eq!(loot.receives.len(), 1, "a receive line outlives the window"); loot.clear_session(); assert!(loot.receives.is_empty(), "disconnect drops receive lines"); @@ -2683,7 +2544,7 @@ mod tests { // A pure-copper drop: name reads "4 Copper", icon is the copper coin pile (_05). loot.open(0x42, loot_type::CORPSE, 4, vec![]); let snap = snapshot( - &loot, + &loot.window, &items, None, Ask::Event(&commands), @@ -2709,7 +2570,7 @@ mod tests { let (grp, nm) = nobody(); let mut loot = LootState::default(); assert!(snapshot( - &loot, + &loot.window, &items, None, Ask::Event(&commands), @@ -2722,7 +2583,7 @@ mod tests { .is_none()); loot.open(0x42, loot_type::CORPSE, 12_345, vec![item(0, 117, 3)]); let snap = snapshot( - &loot, + &loot.window, &items, None, Ask::Event(&commands), @@ -2747,7 +2608,7 @@ mod tests { // Looting the coin turns row 1 into a gap; the item keeps its position. loot.clear_money(); let snap = snapshot( - &loot, + &loot.window, &items, None, Ask::Event(&commands), @@ -2764,7 +2625,7 @@ mod tests { loot.remove_slot(0); let snap = snapshot( - &loot, + &loot.window, &items, None, Ask::Event(&commands), @@ -2776,7 +2637,8 @@ mod tests { ) .expect("still open"); assert_eq!(snap.rows, vec![None, None]); - assert!(loot.take_auto_release(), "nothing lootable left"); + assert!(snap.has_money, "the taken coin's cell is -1, not 0"); + assert!(loot.window.is_empty(), "nothing lootable left"); } #[test] @@ -2803,37 +2665,13 @@ mod tests { /// `drain_loot` scheduled, with [`CORPSE`] streamed at health 0 and [`LIVE`] at 100. fn close_app() -> (App, crossbeam_channel::Receiver) { - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .insert_resource(NetCommands(tx)) - .add_systems(Update, drain_loot); + let (mut app, rx) = bare_app(); + app.add_systems(Update, drain_loot); for (guid, health) in [(CORPSE, 0), (LIVE, 100)] { - let e = app - .world_mut() - .spawn(( - crate::net::NetEntity { - kind: EntityKind::Unit, - display_id: None, - scale: 1.0, - }, - crate::net::ObjectStore(ObjectFields::from_pairs(&[(F_UNIT_HEALTH, health)])), - )) - .id(); - app.world_mut() - .resource_mut::() - .0 - .insert(guid, e); + stream(&mut app, guid, EntityKind::Unit, &[(F_UNIT_HEALTH, health)]); } + // The disenchanted item, which the object manager holds while its window is open. + stream(&mut app, ESSENCE_SOURCE, EntityKind::Other, &[(2, 0x3)]); (app, rx) } @@ -2869,13 +2707,7 @@ mod tests { .collect() }; app.insert_non_send_resource(UiScript::new().unwrap()); - let close_loot = |app: &mut App| { - app.world_mut() - .non_send_resource_mut::() - .run("CloseLoot()") - .unwrap(); - app.update(); - }; + let close_loot = |app: &mut App| run_hosted(app, "CloseLoot()"); // `CloseLoot`, as the close button, Escape or any other hide reaches it. open_loot( @@ -2902,8 +2734,9 @@ mod tests { 0, vec![item(0, 117, 1)], ); - app.world_mut().resource_mut::().remove_slot(0); - app.update(); + app.world_mut() + .run_system_once_with(net::on_removed, SessionEvent::LootRemoved { slot: 0 }) + .unwrap(); assert_eq!(released(&rx), [CORPSE]); assert_eq!( deselects(&mut app), @@ -2913,8 +2746,9 @@ mod tests { // The coin taken from a coin-only window. open_loot(&mut app, CORPSE, loot_type::CORPSE, 250, vec![]); - app.world_mut().resource_mut::().clear_money(); - app.update(); + app.world_mut() + .run_system_once_with(net::on_clear_money, SessionEvent::LootClearMoney) + .unwrap(); assert_eq!(released(&rx), [CORPSE]); assert_eq!(deselects(&mut app), [CORPSE], "the coin's close deselects"); @@ -2947,11 +2781,7 @@ mod tests { let (mut app, rx) = close_app(); app.insert_non_send_resource(UiScript::new().unwrap()); let close_loot = |app: &mut App, chunk: &str| -> Vec<&'static str> { - app.world_mut() - .non_send_resource_mut::() - .run(chunk) - .unwrap(); - app.update(); + run_hosted(app, chunk); app.world_mut() .resource_mut::() .take() @@ -3080,11 +2910,6 @@ mod tests { assert_eq!(app.world().resource::().source(), Some(CORPSE)); assert!(rx.try_recv().is_err()); app.world_mut().resource_mut::().remove_slot(0); - // The emptying armed the auto-release; take it so the step's close is the one measured. - assert!(app - .world_mut() - .resource_mut::() - .take_auto_release()); step(&mut app); assert_eq!(app.world().resource::().source(), None); assert!(matches!(rx.try_recv(), Ok(ClientCommand::LootRelease { guid }) if guid == CORPSE)); @@ -3165,23 +2990,8 @@ mod tests { /// The feed and the sweep's loot leg over an empty world, the feed's other inputs at rest. fn sweep_loot_app() -> (App, crossbeam_channel::Receiver) { use crate::ui_script::SweepApp; - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.add_message::() - .add_message::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::>() - .init_resource::() - .insert_resource(NetCommands(tx)) - .add_sweep_leg(SweepLeg::Loot, close_loot_on_leave_world) + let (mut app, rx) = bare_app(); + app.add_sweep_leg(SweepLeg::Loot, close_loot_on_leave_world) .add_systems(Update, feed_loot); (app, rx) } @@ -3533,11 +3343,7 @@ mod tests { 0, vec![item(0, 117, 1)], ); - app.world_mut() - .non_send_resource_mut::() - .run("CloseLoot()") - .unwrap(); - app.update(); + run_hosted(&mut app, "CloseLoot()"); let sent: Vec = rx.try_iter().collect(); assert!( matches!( @@ -3554,7 +3360,9 @@ mod tests { } /// The sweep's loot leg has `dl` clear too: a disenchant window with rows left is swept in - /// the VM the sweep runs in, not closed, and no `LOOT_CLOSED` fires. + /// the VM the sweep runs in, not closed, and no `LOOT_CLOSED` fires; the sweep's flag is the + /// leg's 0 (`0x4c1ca0`), so its end signals `LOOT_OPENED` again with the rows left + /// (`0x4c2240`). #[test] fn the_loot_leg_sweeps_a_disenchant_window_with_rows_left() { use crate::ui_script::sweep_test::{seen_in, spied_vm, sweep_in_place}; @@ -3571,6 +3379,7 @@ mod tests { vec![item(0, 117, 1)], ); app.world_mut().resource_mut::().0 = Some(ESSENCE_SOURCE); + stream(&mut app, ESSENCE_SOURCE, EntityKind::Other, &[(2, 0x3)]); app.update(); let _ = rx.try_iter().count(); sweep_in_place(&mut app); @@ -3582,7 +3391,7 @@ mod tests { ), "{sent:?}" ); - assert_eq!(seen_in(&app), ["LOOT_OPENED"]); + assert_eq!(seen_in(&app), ["LOOT_OPENED", "LOOT_OPENED"]); assert_eq!( app.world().resource::().source(), Some(ESSENCE_SOURCE) diff --git a/crates/benilla-app/src/ui_loot/net.rs b/crates/benilla-app/src/ui_loot/net.rs index 5b510409c..2c1042bd9 100644 --- a/crates/benilla-app/src/ui_loot/net.rs +++ b/crates/benilla-app/src/ui_loot/net.rs @@ -24,15 +24,19 @@ pub(super) fn register(app: &mut App) { .net_handler(K::Disconnected, on_session_end); } -/// An admitted response selects a looted unit (`0x5ebc35` β†’ `0x48f3a0`) before the window opens -/// (`0x4c1cb0`), so the outgoing target's teardown closes a window still open on it. One that lands -/// while our own body moves takes the move-start close (`0x5ebc3a`-`0x5ebc51`), which the feed runs -/// after it fires `LOOT_OPENED`, or the drain when the window waits on an item template. +/// An admitted response for an object we hold selects a looted unit (`0x5ebc35` β†’ `0x48f3a0`) +/// before the window opens (`0x4c1cb0`), so the outgoing target's teardown closes a window still +/// open on it. One for an object we lack shows `ERR_LOOT_DIDNT_KILL` and returns (`0x5ebb33`, +/// mask 1, `0x5ebb3f`) before the latch (`0x5ebb60`) and the open. One that lands while our own +/// body moves takes the move-start close (`0x5ebc3a`-`0x5ebc51`), which the feed runs after the +/// copier's end, or the drain when the window waits on an item template. fn on_response( In(ev): In, mut select: crate::target::SelectCommit, player: Option>, mut move_start: ResMut, + index: Res, + errors: Res, ) { let SessionEvent::LootResponse { guid, @@ -53,6 +57,13 @@ fn on_response( ) { return; } + if !index.0.contains_key(&guid) { + debug!("net: loot response {guid:#x} for an object we lack β€” ERR_LOOT_DIDNT_KILL"); + errors.push(UiError::key("ERR_LOOT_DIDNT_KILL")); + return; + } + // A fishing bobber first arms here and still does not kneel: `LootKneel` decides the pose. + seam.loot_latch.0 = Some(guid); debug!( "net: loot response {guid:#x} type {loot_type} gold {gold} {} item(s)", items.len() @@ -78,9 +89,9 @@ fn on_error( } } -fn on_removed(In(ev): In, mut loot: ResMut) { +pub(super) fn on_removed(In(ev): In, mut window: WindowPacket) { if let SessionEvent::LootRemoved { slot } = ev { - loot_removed(slot, &mut loot); + window.removed(slot); } } @@ -90,9 +101,61 @@ fn on_money_notify(In(ev): In) { } } -fn on_clear_money(In(ev): In, mut loot: ResMut) { +pub(super) fn on_clear_money(In(ev): In, mut window: WindowPacket) { if let SessionEvent::LootClearMoney = ev { - loot_clear_money(&mut loot); + window.money_cleared(); + } +} + +/// What the removal packets change: the window, and the close an emptied one takes. +#[derive(bevy::ecs::system::SystemParam)] +pub(super) struct WindowPacket<'w, 's> { + loot: ResMut<'w, LootState>, + latch: ResMut<'w, LootLatch>, + net: Res<'w, NetCommands>, + objects: crate::net::Objects<'w, 's>, + dead: super::DeadUnitDeselect<'w, 's>, +} + +impl WindowPacket<'_, '_> { + /// `SMSG_LOOT_REMOVED` (`0x5ebeb0`): with the player's loot target resolving (`0x5ebedf`, mask + /// 1; else `0x5ebee7` leaves), `ClearLootRow` (`0x4c1f00`), the feed's `LOOT_SLOT_CLEARED`. + fn removed(&mut self, slot: u8) { + debug!("net: loot slot {slot} removed"); + if !self + .latch + .0 + .is_some_and(|g| self.objects.entity(g).is_some()) + { + return; + } + if self.loot.remove_slot(slot) { + self.close_if_empty(); + } + } + + /// `SMSG_LOOT_CLEAR_MONEY` (`0x5ec030` β†’ `0x4c2750`): the coin row goes, for every looter. + fn money_cleared(&mut self) { + debug!("net: loot coin line cleared"); + if self.loot.clear_money() { + self.close_if_empty(); + } + } + + /// A window with nothing left (`0x4c2a70`) closes with release inside the packet + /// (`0x4c1f8d`, `0x4c2785` β†’ `0x48f200(1, 0, 0)`); the feed signals its `LOOT_CLOSED` after the + /// removal's `LOOT_SLOT_CLEARED` and before the pushes behind it. vmangos does not release it. + fn close_if_empty(&mut self) { + if self.loot.source().is_none() || self.loot.has_contents(&self.objects) { + return; + } + let owed = self.loot.owed_unlocks(); + let closed = super::close_interaction(&mut self.loot, &mut self.latch, Some(&self.net)); + if let Some(guid) = closed { + debug!("net: loot emptied β€” release {guid:#x}"); + } + self.loot.defer_close_unlocks(owed); + self.dead.after_close(closed); } } @@ -101,9 +164,11 @@ fn on_release_response( mut loot: ResMut, mut latch: ResMut, mut dead: super::DeadUnitDeselect, + objects: crate::net::Objects, ) { if let SessionEvent::LootReleaseResponse { guid, result } = ev { - dead.after_close(loot_release_response(guid, result, &mut loot, &mut latch)); + let closed = loot_release_response(guid, result, &mut loot, &mut latch, &objects); + dead.after_close(closed); } } @@ -132,14 +197,17 @@ fn on_item_push_result( } } -/// The open window and the latch die with the session, unconditionally. +/// The open window, the latch and the auto-loot byte die with the session, unconditionally: the +/// next player object is built with both at 0 (`0x5dd403`, `0x5dd40f`). fn on_session_end( In(_): In, mut loot: ResMut, mut latch: ResMut, + mut byte: ResMut, ) { loot.clear_session(); latch.0 = None; + byte.0 = false; } /// The `loot_type`s a cold latch admits (`0x5eb94b`, `0x5eb953`, `0x5eb95b`): pickpocketing, @@ -151,8 +219,8 @@ const SERVER_STARTED_LOOT: [u8; 3] = [2, 3, 4]; /// latch holds the packet's guid, or when the latch is cold and the type is server-started. /// Anything else is refused (`0x5eb963`): no window, a `CMSG_LOOT_RELEASE` for the packet's guid, /// the latch cleared whatever it held, and `UnlockItem` on the packet's guid (`0x5eb9de`). An -/// admitted one writes the latch (`0x5ebb60`) and plays no anim; a chest already knelt at its -/// `SMSG_SPELL_GO` (`0x6e831b`). +/// admitted one for an object we hold writes the latch (`0x5ebb60`) and plays no anim; a chest +/// already knelt at its `SMSG_SPELL_GO` (`0x6e831b`). fn admit_response( guid: u64, loot_type: u8, @@ -177,8 +245,6 @@ fn admit_response( loot.unlock_item(guid); return false; } - // A fishing bobber first arms here and still does not kneel: `LootKneel` decides the pose. - latch.0 = Some(guid); true } @@ -234,11 +300,12 @@ fn loot_refusal(reason: u8) -> LootRefusal { LootRefusal { key, releases } } -/// `SMSG_LOOT_RESPONSE`'s error shape: the arm's message by key, as `DisplayError(stringId)` takes -/// its surface and voice from the record; a releasing arm drops the latch and runs -/// `UnlockItem 0x495420` on the packet's guid (the tail `0x5ebac2`, `0x5ebae0`). There is no admission gate -/// here: a guid-mismatched error still shows and keeps the latch, where the reference refuses it -/// at `0x5eb963`, clearing the latch and showing nothing. +/// `SMSG_LOOT_RESPONSE`'s error shape. Only for the held loot target (`0x5eb936`-`0x5eb93e`): the +/// arm's message by key, as `DisplayError(stringId)` takes its surface and voice from the record, +/// and a releasing arm drops the target and runs `UnlockItem 0x495420` on the packet's guid (the +/// tail `0x5ebac2`, `0x5ebae0`). A refusal for any other guid, or with no target held, takes the +/// refusal leg (`0x5eb944` β†’ `0x5eb963`): no line, the target cleared whatever it held +/// (`0x5eb9d2`) and the guid unlocked (`0x5eb9de`). fn loot_error( guid: u64, error: u8, @@ -246,22 +313,21 @@ fn loot_error( latch: &mut LootLatch, loot: &mut LootState, ) { + if latch.0 != Some(guid) { + debug!("net: loot error {error} on {guid:#x}, not the loot target β€” dropped"); + latch.0 = None; + loot.unlock_item(guid); + return; + } let LootRefusal { key, releases } = loot_refusal(error); debug!("net: loot error {error} on {guid:#x} β†’ {key} (releases: {releases})"); errors.push(UiError::key(key)); if releases { - // Guid-matched: the tail's store is unconditional, but only a matching latch reaches it. - latch.clear_for(guid); + latch.0 = None; loot.unlock_item(guid); } } -/// `SMSG_LOOT_REMOVED`: a row was taken, by anyone; the feed fires `LOOT_SLOT_CLEARED` for it. -fn loot_removed(slot: u8, loot: &mut LootState) { - debug!("net: loot slot {slot} removed"); - loot.remove_slot(slot); -} - /// `SMSG_LOOT_MONEY_NOTIFY`, our share of a group's coin: only logged, as the coin row drops on /// `SMSG_LOOT_CLEAR_MONEY` and the purse rides the coinage field. vmangos sends none for a solo /// loot (`LootHandler.cpp:331`). @@ -269,12 +335,6 @@ fn loot_money_notify(amount: u32) { debug!("net: loot money {amount}"); } -/// `SMSG_LOOT_CLEAR_MONEY`: the coin row goes, for every looter. -fn loot_clear_money(loot: &mut LootState) { - debug!("net: loot coin line cleared"); - loot.clear_money(); -} - /// `SMSG_LOOT_RELEASE_RESPONSE` (`0x5ec090`): acted on only with a nonzero result (`0x5ec0b6`) /// and the latched guid (`0x5ec0bd`-`0x5ec0ce`), so a release for an old window, which vmangos /// sends when a new `CMSG_LOOT` replaces it (`Player.cpp:7694-7695`), closes nothing, and one @@ -288,6 +348,7 @@ fn loot_release_response( result: u8, loot: &mut LootState, latch: &mut LootLatch, + objects: &crate::net::Objects, ) -> Option { if result == 0 || latch.0 != Some(guid) { debug!( @@ -298,9 +359,9 @@ fn loot_release_response( } debug!("net: loot released {guid:#x}"); latch.0 = None; - // The handler's close has `dl` clear (`0x5ec0ef`), so a disenchant window with rows left is + // The handler's close has `dl` clear (`0x5ec0ef`), so a disenchant window with contents is // swept instead, by the feed. - if loot.disenchant_holds() { + if loot.disenchant_hold(objects) { loot.owe_sweep(); return None; } @@ -490,14 +551,16 @@ mod tests { } } - /// The reference's behaviour: the tail's store is unconditional, but the error leg is reached - /// only through `0x5eb93e`, which already required a matching latch. + /// The error leg is reached only through `0x5eb93e`, a matching target; a refusal for another + /// guid takes the refusal leg (`0x5eb963`), which shows nothing and clears the target whatever + /// it held (`0x5eb9d2`). #[test] - fn the_error_legs_clear_is_guid_matched() { + fn a_refusal_for_another_guid_clears_the_target_and_shows_nothing() { let errors = UiErrorKeys::default(); let mut latch = LootLatch(Some(CHEST)); loot_error(CORPSE, 8, &errors, &mut latch, no_item!()); - assert_eq!(latch.0, Some(CHEST)); + assert_eq!(latch.0, None); + assert!(errors.snapshot().is_empty()); } /// A GameObject guid: a chest. @@ -829,6 +892,16 @@ mod tests { #[test] fn a_release_on_a_disenchant_window_with_rows_left_owes_its_sweep() { let mut world = opened_lockbox_world(); + // The disenchanted item, which `LootHasContents` resolves (`0x4c2a8c`). + let item = world + .spawn(crate::net::ObjectStore( + benilla_protocol::messages::ObjectFields::from_pairs(&[(2, 0x3)]), + )) + .id(); + world + .resource_mut::() + .0 + .insert(LOCKBOX, item); world.resource_mut::().open( LOCKBOX, benilla_protocol::messages::loot_type::DISENCHANTING, @@ -941,6 +1014,8 @@ mod tests { world.init_resource::(); world.init_resource::(); world.init_resource::(); + world.init_resource::(); + world.init_resource::(); world.spawn(( SelfPlayer, Guid(1), @@ -1264,10 +1339,7 @@ mod tests { /// word at `player`'s. fn seat_drain(world: &mut World, player: crate::player::Player) { world.insert_resource(player); - world.init_resource::(); - world.init_resource::(); - world.init_resource::(); - world.init_resource::>(); + super::super::seat_loot_steps(world); } /// The deselects asked for since the last call. @@ -1345,8 +1417,9 @@ mod tests { } } - /// The copier `0x4c1cb0` sweeps an auto-loot window (`0x4c1fa0`) before the response's - /// movement close (`0x5ebc51`), so a body auto-looted on the run is taken, then released. + /// With the byte the click stored set, the copier `0x4c1cb0` sweeps the window (`0x4c1fa0`) + /// before the response's movement close (`0x5ebc51`), so a body auto-looted on the run is + /// taken, then released. #[test] fn auto_loot_on_the_run_takes_the_rows_before_the_release() { const TOUGH_JERKY: u32 = 117; @@ -1362,18 +1435,14 @@ mod tests { TOUGH_JERKY, Some(crate::items::test_template("Tough Jerky")), ); - app.insert_resource(super::super::LootConfig { - auto_loot: true, - ..Default::default() - }) - .init_resource::() - .init_resource::() - .init_resource::>() - .insert_non_send_resource(benilla_ui::script::UiScript::new().expect("VM")) - .add_systems( - Update, - (super::super::feed_loot, super::super::drain_loot).chain(), - ); + app.insert_resource(super::super::AutoLootByte(true)) + .init_resource::() + .init_resource::() + .insert_non_send_resource(benilla_ui::script::UiScript::new().expect("VM")) + .add_systems( + Update, + (super::super::feed_loot, super::super::drain_loot).chain(), + ); app.world_mut().resource_mut::().0 = Some(CORPSE); app.world_mut() @@ -1430,17 +1499,15 @@ mod tests { app.world_mut(), crate::player::Player::with_move_flags(flags), ); - app.init_resource::() - .init_resource::>() - .add_systems( - Update, - ( - super::super::feed_loot, - super::super::drain_loot, - crate::target::click::clear_target_requests, - ) - .chain(), - ); + app.init_resource::().add_systems( + Update, + ( + super::super::feed_loot, + super::super::drain_loot, + crate::target::click::clear_target_requests, + ) + .chain(), + ); app.world() .non_send_resource::() .run( diff --git a/crates/benilla-app/src/ui_loot/sweep_tests.rs b/crates/benilla-app/src/ui_loot/sweep_tests.rs new file mode 100644 index 000000000..d122fafa7 --- /dev/null +++ b/crates/benilla-app/src/ui_loot/sweep_tests.rs @@ -0,0 +1,250 @@ +//! The auto-loot sweep `0x4c1fa0` through the whole client's host: its gates (`0x4c1fb3`, +//! `0x4c1fd9`), its money (`0x4c1ff4`-`0x4c2170`, `0xb71bc4`), the disenchant hold that runs it +//! (`0x48f245`-`0x48f264`), and a frame's responses each ending their own copier (`0x4c1ea8`). + +use benilla_protocol::messages::GroupMemberEntry; +use benilla_protocol::SessionEvent; +use bevy::ecs::system::RunSystemOnce; +use bevy::prelude::*; + +use super::call_tests::{ + client, eval, feed, open, packets, row, run, seen, sent, Loot, CORPSE, LINEN, ME, THRALL, WOOL, +}; +use super::{AutoLootByte, LootCloseAtRest, LootLatch}; +use crate::net::{ClientCommand, GuidIndex, SelfPlayer}; + +/// Disenchanting: a window `CloseLoot` sweeps while rows are left. +const DISENCHANT: u8 = 4; +/// An entry the item cache has no record of. +const UNCACHED: u32 = 40_000; + +/// A recorder for the money lines: `CHAT_MSG_MONEY` noted in `SEEN` in its place among the loot +/// events, and its text in `MONEY`. +fn note_money(l: &mut Loot) { + run( + l, + r#"MONEY = {} + local f = CreateFrame("Frame") + f:RegisterEvent("CHAT_MSG_MONEY") + f:SetScript("OnEvent", function() tinsert(SEEN, event) tinsert(MONEY, arg1) end)"#, + ); +} + +/// The money lines signalled so far, in order. +fn money_lines(l: &mut Loot) -> Vec { + eval::(l, "return table.concat(MONEY, '|')") + .split('|') + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() +} + +/// An auto-loot open: the byte the interaction stored, then the response. +fn auto_open( + l: &mut Loot, + loot_type: u8, + gold: u32, + items: Vec, +) { + l.app.world_mut().resource_mut::().0 = true; + open(l, CORPSE, loot_type, gold, items); +} + +/// Money above 0 with the flag `0xb71bc4` clear (`0x4c2008`, `0x4c2015`): outside a party and a +/// raid, the line `YOU_LOOT_MONEY` with the coins, gold first, as `"%d %s"` joined by the +/// reference's separator tests (`0x4c2043`-`0x4c2123`), on chat type 86, added in place +/// (`0x4c2170` β†’ `AddChatLine 0x49a870`): its `CHAT_MSG_MONEY` runs inside the sweep, ahead of the +/// rows and the sweep's `LOOT_OPENED` (`0x4c2240`). The sweep's end sets the flag (`0x4c221e`), so +/// a second sweep of the session prints none; the next session's copier clears it (`0x4c1d95`). +#[test] +fn the_sweep_prints_the_money_line_once_per_session() { + let mut l = client(); + note_money(&mut l); + auto_open(&mut l, DISENCHANT, 10_203, vec![row(1, LINEN)]); + assert_eq!(money_lines(&mut l), ["You loot 1 Gold, 2 Silver, 3 Copper"]); + assert_eq!(seen(&mut l), "CHAT_MSG_MONEY,LOOT_OPENED", "in place"); + let _ = sent(&l); + run(&mut l, "CloseLoot()"); + assert!( + matches!( + sent(&l)[..], + [ + ClientCommand::LootMoney, + ClientCommand::AutostoreLootItem { slot: 1 } + ] + ), + "the second sweep asks for the coin again (`0x4c1ffc`)" + ); + assert_eq!(money_lines(&mut l).len(), 1, "but prints no second line"); + + // The next session, a zero middle coin: both separators stand (`0x4c20c7`, `0x4c20e8`). + auto_open(&mut l, DISENCHANT, 10_003, vec![row(1, LINEN)]); + assert_eq!( + money_lines(&mut l)[1..], + ["You loot 1 Gold, , 3 Copper".to_string()] + ); +} + +/// A party member in the first party slot (`[0xbc6f48]`, `0x4c2030`) or a raid roster +/// (`[0xb713e0]`, `0x4c203d`) skips the line; the coin request still goes. Alone, the next +/// session prints it. +#[test] +fn a_party_or_a_raid_skips_the_money_line() { + for group_type in [0, 1] { + let mut l = client(); + let member = GroupMemberEntry { + name: "Thrall".into(), + guid: THRALL, + status: 1, + flags: 0, + }; + let group = |l: &mut Loot, members: Vec| { + l.app + .world_mut() + .resource_mut::() + .apply_list(group_type, 0, members, ME, None, Some(ME)); + }; + note_money(&mut l); + group(&mut l, vec![member]); + auto_open(&mut l, 1, 500, vec![row(1, LINEN)]); + assert!(money_lines(&mut l).is_empty(), "group type {group_type}"); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootMoney, ..]), + "group type {group_type}" + ); + let mut l = client(); + note_money(&mut l); + auto_open(&mut l, 1, 500, vec![row(1, LINEN)]); + assert_eq!(money_lines(&mut l), ["You loot 5 Silver"], "alone"); + } +} + +/// While an item record is pending (`0xb71b44`) the sweep returns at once (`0x4c1fb3`): `CloseLoot` +/// on a disenchant window whose row's record has not come sends and signals nothing. +#[test] +fn a_sweep_with_a_record_pending_does_nothing() { + let mut l = client(); + open(&mut l, CORPSE, DISENCHANT, 0, vec![row(1, UNCACHED)]); + let _ = (seen(&mut l), sent(&l)); + run(&mut l, "CloseLoot()"); + assert!(sent(&l).is_empty()); + assert_eq!(seen(&mut l), ""); +} + +/// With no active player the sweep signals `LOOT_OPENED` and returns (`0x4c1fd9`, `0x4c1fe0`), +/// whatever its flag, sending nothing; the take dispatcher leaves at once (`0x4c27b6`). +#[test] +fn with_no_player_the_sweep_only_signals_and_a_take_does_nothing() { + let mut l = client(); + open(&mut l, CORPSE, DISENCHANT, 0, vec![row(1, LINEN)]); + let _ = (seen(&mut l), sent(&l)); + let world = l.app.world_mut(); + let me = world + .query_filtered::>() + .single(world) + .expect("our player"); + world.despawn(me); + world.resource_mut::().0.remove(&ME); + run(&mut l, "CloseLoot(1)"); + assert_eq!(seen(&mut l), "LOOT_OPENED"); + assert!(sent(&l).is_empty()); + super::call_tests::click(&mut l, 1); + assert!(sent(&l).is_empty(), "the row's click takes nothing"); +} + +/// `0x48f200`'s hold asks `LootHasContents` (`0x48f24f` β†’ `0x4c2a70`), which resolves the source +/// (`0x4c2a8c`): a disenchant window whose source has left the object manager is closed with +/// release at rest, not swept. +#[test] +fn a_disenchant_window_whose_source_is_gone_closes_at_rest() { + let mut l = client(); + open(&mut l, CORPSE, DISENCHANT, 0, vec![row(1, LINEN)]); + let _ = sent(&l); + let world = l.app.world_mut(); + let corpse = world.resource_mut::().0.remove(&CORPSE).unwrap(); + world.despawn(corpse); + world.resource_mut::().0 = true; + world.run_system_once(super::drain_loot).unwrap(); + assert!(matches!( + sent(&l)[..], + [ClientCommand::LootRelease { guid: CORPSE }] + )); + assert_eq!(l.app.world().resource::().0, None); +} + +/// Two responses in one frame each end their own copier, as each packet's dispatch runs it +/// (`0x4c1ea8`-`0x4c1ee6`): the first window signals `LOOT_OPENED` before the second's copier ends +/// it (`0x4c1dac`). Under the byte the first is swept, its own rows, and the sweep clears the byte +/// (`0x4c2219`), so the second opens plain. +#[test] +fn two_responses_in_one_frame_each_end_their_own_copier() { + for byte in [false, true] { + let mut l = client(); + l.app.world_mut().resource_mut::().0 = byte; + l.app.world_mut().resource_mut::().0 = Some(CORPSE); + let response = |item| SessionEvent::LootResponse { + guid: CORPSE, + loot_type: 1, + gold: 0, + items: vec![item], + }; + packets( + &mut l, + vec![response(row(0, LINEN)), response(row(1, WOOL))], + ); + feed(&mut l); + assert_eq!( + seen(&mut l), + "LOOT_OPENED,LOOT_CLOSED,LOOT_OPENED", + "byte {byte}" + ); + let stores: Vec = sent(&l); + if byte { + assert!( + matches!(stores[..], [ClientCommand::AutostoreLootItem { slot: 0 }]), + "the first window's row: {stores:?}" + ); + } else { + assert!(stores.is_empty(), "{stores:?}"); + } + assert!(!l.app.world().resource::().0); + assert_eq!( + eval::( + &mut l, + "local _, name = GetLootSlotInfo(1) return name or ''" + ), + "Wool Cloth", + "the second window shows" + ); + } +} + +/// `autoLootDefault`, benilla's own option, auto-loots every window when on, with Shift held +/// opening it plain: a pickpocket or disenchant window, which no interaction stores the byte for, +/// takes it at its copier's end from the Shift held then. Off, they open plain, as in 1.12. +#[test] +fn auto_loot_default_sweeps_a_pickpocket_and_a_disenchant_window() { + for loot_type in [2, DISENCHANT] { + for (on, shift, swept) in [ + (true, false, true), + (true, true, false), + (false, false, false), + ] { + let mut l = client(); + l.app + .world_mut() + .resource_mut::() + .auto_loot = on; + crate::script_calls::with_hosted_vm(l.app.world_mut(), |s| { + s.expect("a VM").set_modifiers(shift, false, false); + }); + open(&mut l, CORPSE, loot_type, 0, vec![row(0, LINEN)]); + let stores = sent(&l); + assert_eq!( + matches!(stores[..], [ClientCommand::AutostoreLootItem { slot: 0 }]), + swept, + "type {loot_type}, on {on}, shift {shift}: {stores:?}" + ); + } + } +} diff --git a/crates/benilla-app/src/ui_script/escape_tests.rs b/crates/benilla-app/src/ui_script/escape_tests.rs index 4fac1d7cc..0472f7a37 100644 --- a/crates/benilla-app/src/ui_script/escape_tests.rs +++ b/crates/benilla-app/src/ui_script/escape_tests.rs @@ -57,6 +57,7 @@ fn one_item_backpack() -> ContainerState { fn escape_closes_bag_and_panel_releases_loot_and_keeps_the_held_item() { let _data = benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); // `LOOT_UI` whole: a missing `ItemButtonTemplate` is only a load warning, so it fails silently. for file in super::test_ui::production_order(&[ @@ -79,7 +80,7 @@ fn escape_closes_bag_and_panel_releases_loot_and_keeps_the_held_item() { s.run("MainMenuBarBackpackButton:Click()").unwrap(); s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: vec![Some(LootRow { item_id: 0, @@ -123,8 +124,8 @@ fn escape_closes_bag_and_panel_releases_loot_and_keeps_the_held_item() { "ESC hid the loot window" ); assert_eq!( - s.take_loot_close(), - Some(false), + s.take_loot_calls(), + vec![benilla_ui::script::LootCall::Close { failed: false }], "closing the loot fired the release (OnHide β†’ CloseLoot)" ); // Stock `ToggleGameMenu` has no `ClearCursor` arm, so the held item survives ESC. diff --git a/crates/benilla-app/src/ui_script/game_menu_tests.rs b/crates/benilla-app/src/ui_script/game_menu_tests.rs index 4a3a19224..60cd16af8 100644 --- a/crates/benilla-app/src/ui_script/game_menu_tests.rs +++ b/crates/benilla-app/src/ui_script/game_menu_tests.rs @@ -247,12 +247,13 @@ fn the_open_menu_takes_the_screen_and_refuses_every_other_panel() { "Interface\\FrameXML\\LootFrame.xml", "ScrollTemplates.xml", ]); + s.keep_calls(); s.set_money(0); s.set_container(0, Some(backpack())); s.run("MainMenuBarBackpackButton:Click()").unwrap(); s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: vec![Some(LootRow { item_id: 0, diff --git a/crates/benilla-app/src/ui_script/loot_tests.rs b/crates/benilla-app/src/ui_script/loot_tests.rs index a2461af9e..271781676 100644 --- a/crates/benilla-app/src/ui_script/loot_tests.rs +++ b/crates/benilla-app/src/ui_script/loot_tests.rs @@ -1,10 +1,34 @@ use benilla_ui::script::{ - DressUpIntent, ExtractedQuad, LootRow, LootState, MerchantItem, MerchantState, QuadContent, - SoundRequest, UiScript, + DressUpIntent, ExtractedQuad, LootCall, LootRow, LootState, MerchantItem, MerchantState, + QuadContent, SoundRequest, UiScript, }; use super::test_ui::load_ui as load_xml; +/// The rows the VM's row clicks took, from the loot calls it kept ([`UiScript::keep_calls`]); +/// the other kept loot calls go with them. +fn picks(s: &mut UiScript) -> Vec { + s.take_loot_calls() + .into_iter() + .filter_map(|c| match c { + LootCall::Take(row) => Some(row), + _ => None, + }) + .collect() +} + +/// The `GiveMasterLoot(slot, candidate)` calls the VM kept, the other kept loot calls going with +/// them. +fn gives(s: &mut UiScript) -> Vec<(u32, u32)> { + s.take_loot_calls() + .into_iter() + .filter_map(|c| match c { + LootCall::GiveMaster { slot, candidate } => Some((slot, candidate)), + _ => None, + }) + .collect() +} + /// The rect of the `QuadContent::Frame` quad sized `w` by `h`: every frame emits one. fn frame_rect(quads: &[ExtractedQuad], w: f32, h: f32) -> benilla_ui::layout::Rect { quads @@ -43,7 +67,7 @@ fn text_color(quads: &[ExtractedQuad], t: &str) -> Option<[f32; 4]> { fn coin_and_two_items() -> LootState { LootState { source_unit: false, - fishing: false, + has_money: true, master_candidates: Vec::new(), rows: vec![ Some(LootRow { @@ -85,6 +109,7 @@ fn coin_and_two_items() -> LootState { fn shipped_loot_frame_drives_end_to_end() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in super::test_ui::LOOT_UI { load_xml(&s, f); @@ -215,11 +240,10 @@ fn shipped_loot_frame_drives_end_to_end() { s.mouse_button(ix, iy, "LeftButton", true); s.mouse_button(ix, iy, "LeftButton", false); assert_eq!( - s.take_loot_picks(), - vec![1, 2], - "coin row is pick 1, the first item row is pick 2" + s.take_loot_calls(), + vec![LootCall::Take(1), LootCall::Take(2)], + "coin row is pick 1, the first item row is pick 2, and nothing closes" ); - assert_eq!(s.take_loot_close(), None); // The looted coin row hides in place, off `LOOT_SLOT_CLEARED` alone, and the items keep their // rows. @@ -244,8 +268,8 @@ fn shipped_loot_frame_drives_end_to_end() { s.run("LootCloseButton:Click()").unwrap(); assert_eq!( - s.take_loot_close(), - Some(false), + s.take_loot_calls(), + vec![LootCall::Close { failed: false }], "closing the window releases the loot (OnHide β†’ CloseLoot)" ); assert!(!s.eval::("return LootFrame:IsVisible()").unwrap()); @@ -261,6 +285,7 @@ fn shipped_loot_frame_drives_end_to_end() { fn loot_empty_roll_plays_the_empty_open_kit() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -282,7 +307,7 @@ fn loot_empty_roll_plays_the_empty_open_kit() { s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: vec![], })); @@ -301,6 +326,7 @@ fn loot_empty_roll_plays_the_empty_open_kit() { fn fishing_loot_open_plays_the_reel_and_swaps_the_portrait() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -314,9 +340,8 @@ fn fishing_loot_open_plays_the_reel_and_swaps_the_portrait() { }) }; - let mut fished = coin_and_two_items(); - fished.fishing = true; - s.set_loot(Some(fished)); + s.set_loot_type(3); + s.set_loot(Some(coin_and_two_items())); s.fire_event("LOOT_OPENED", vec![]); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); assert_eq!( @@ -336,6 +361,7 @@ fn fishing_loot_open_plays_the_reel_and_swaps_the_portrait() { s.fire_event("LOOT_CLOSED", vec![]); let _ = s.take_sounds(); + s.set_loot_type(1); s.set_loot(Some(coin_and_two_items())); s.fire_event("LOOT_OPENED", vec![]); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); @@ -353,6 +379,7 @@ fn fishing_loot_open_plays_the_reel_and_swaps_the_portrait() { fn shipped_loot_frame_pages_five_items() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -377,7 +404,7 @@ fn shipped_loot_frame_pages_five_items() { .collect(); s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: rows.clone(), })); @@ -418,7 +445,7 @@ fn shipped_loot_frame_pages_five_items() { cleared[2] = None; s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: cleared, })); @@ -445,6 +472,7 @@ fn shipped_loot_frame_pages_five_items() { fn shipped_loot_pushed_to_center_by_merchant() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -512,6 +540,7 @@ fn shipped_loot_pushed_to_center_by_merchant() { fn the_loot_window_draws_over_the_party_frames() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -559,6 +588,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { benilla_formats::wow_data_or_skip!(); const WOOL_LINK: &str = "|cffffffff|Hitem:2589:0:0:0|h[Wool Cloth]|h|r"; let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -582,7 +612,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: true, master_candidates: Vec::new(), rows: vec![ Some(LootRow { @@ -616,7 +646,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { s.mouse_button(x, y, "LeftButton", true); s.mouse_button(x, y, "LeftButton", false); assert_eq!( - s.take_loot_picks(), + picks(&mut s), vec![2], "an unmodified click still loots the row" ); @@ -633,7 +663,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { "the row's full escaped link landed in the chat box" ); assert!( - s.take_loot_picks().is_empty(), + picks(&mut s).is_empty(), "a shift-click must not also loot the row" ); @@ -654,7 +684,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { "and it must not disturb what is already typed" ); assert!( - s.take_loot_picks().is_empty(), + picks(&mut s).is_empty(), "a shift-click on the coin row must not loot the money either" ); @@ -665,7 +695,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { s.mouse_button(x, y, "LeftButton", false); s.set_modifiers(false, false, false); assert!( - s.take_loot_picks().is_empty(), + picks(&mut s).is_empty(), "an alt-click must not loot the row (the C gate's third modifier)" ); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); @@ -682,7 +712,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { "re-dress first, then try the looted item on" ); assert!( - s.take_loot_picks().is_empty(), + picks(&mut s).is_empty(), "a ctrl-click must not also loot the row" ); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); @@ -694,6 +724,7 @@ fn ctrl_and_shift_on_a_loot_row_preview_and_post_without_looting() { fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -716,13 +747,13 @@ fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { }; s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: vec![Some("Thrall".into()), Some("Cairne".into())], rows: vec![row("Wool Cloth", 2), row("Thunderfury", 4)], })); s.fire_event("LOOT_OPENED", vec![]); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); - let _ = s.take_loot_picks(); + let _ = s.take_loot_calls(); // ── The row click stashes the selection the dropdown will read ──────────────────────────── let click = |s: &mut UiScript, frame: &str| { @@ -752,7 +783,7 @@ fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { "the dropdown anchors on the clicked row, not the window" ); // The pick still queues: the app chooses take or menu off the wire slot type, as 1.12 does. - assert_eq!(s.take_loot_picks(), vec![1]); + assert_eq!(picks(&mut s), vec![1]); // ── The app answers a MASTER row with the event; the menu lists the candidates ───────────── s.fire_event("OPEN_MASTER_LOOT_LIST", vec![]); @@ -776,11 +807,7 @@ fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { // ── Below the threshold: straight out, no confirmation ──────────────────────────────────── click(&mut s, "DropDownList1Button2"); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); - assert_eq!( - s.take_loot_master_gives(), - vec![(1, 2)], - "row 1 to candidate 2" - ); + assert_eq!(gives(&mut s), vec![(1, 2)], "row 1 to candidate 2"); assert!( !s.eval::("return StaticPopup1:IsVisible()").unwrap(), "an uncommon item is under MASTER_LOOT_THREHOLD β€” no confirmation" @@ -792,13 +819,13 @@ fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { s.eval::("return LootFrame.selectedQuality").unwrap(), 4 ); - let _ = s.take_loot_picks(); + let _ = s.take_loot_calls(); s.fire_event("OPEN_MASTER_LOOT_LIST", vec![]); s.resolve(); click(&mut s, "DropDownList1Button1"); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); assert!( - s.take_loot_master_gives().is_empty(), + gives(&mut s).is_empty(), "an epic asks first β€” nothing is sent on the dropdown click" ); assert!( @@ -808,7 +835,7 @@ fn shipped_loot_frame_hands_a_master_row_to_a_candidate() { s.run("StaticPopup1Button1:Click()").unwrap(); // Yes assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); assert_eq!( - s.take_loot_master_gives(), + gives(&mut s), vec![(2, 1)], "row 2 to candidate 1, only after the accept" ); @@ -833,6 +860,7 @@ fn the_master_loot_menu_groups_raid_candidates_by_subgroup() { use benilla_ui::script::{PartyState, RaidMemberInfo}; let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -857,7 +885,7 @@ fn the_master_loot_menu_groups_raid_candidates_by_subgroup() { candidates[10] = Some("Sylvanas".to_string()); s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: candidates, rows: vec![Some(LootRow { item_id: 17182, @@ -877,7 +905,7 @@ fn the_master_loot_menu_groups_raid_candidates_by_subgroup() { s.mouse_button(x as f32, y as f32, "LeftButton", true); s.mouse_button(x as f32, y as f32, "LeftButton", false); s.resolve(); - let _ = s.take_loot_picks(); + let _ = s.take_loot_calls(); s.fire_event("OPEN_MASTER_LOOT_LIST", vec![]); s.resolve(); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); @@ -913,6 +941,7 @@ fn the_master_loot_menu_groups_raid_candidates_by_subgroup() { fn the_loot_bind_confirm_raises_the_dialog_and_okay_calls_loot_slot() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -922,7 +951,7 @@ fn the_loot_bind_confirm_raises_the_dialog_and_okay_calls_loot_slot() { } s.set_loot(Some(coin_and_two_items())); s.fire_event("LOOT_OPENED", vec![]); - let _ = s.take_loot_picks(); + let _ = s.take_loot_calls(); // The app defers row 2 and says so. s.fire_event( @@ -963,10 +992,9 @@ fn the_loot_bind_confirm_raises_the_dialog_and_okay_calls_loot_slot() { s.run("StaticPopup_OnClick(StaticPopup1, 2)").unwrap(); assert!(!s.eval::("return StaticPopup1:IsVisible()").unwrap()); assert!( - s.take_loot_confirms().is_empty(), - "Cancel completes nothing" + s.take_loot_calls().is_empty(), + "Cancel completes nothing, and takes nothing either" ); - assert!(s.take_loot_picks().is_empty(), "and takes nothing either"); // Button 1, Okay: the row goes back out through `LootSlot`. s.fire_event( @@ -975,9 +1003,9 @@ fn the_loot_bind_confirm_raises_the_dialog_and_okay_calls_loot_slot() { ); s.run("StaticPopup_OnClick(StaticPopup1, 1)").unwrap(); assert!(!s.eval::("return StaticPopup1:IsVisible()").unwrap()); - assert_eq!(s.take_loot_confirms(), vec![2]); - assert!( - s.take_loot_picks().is_empty(), + assert_eq!( + s.take_loot_calls(), + vec![LootCall::Confirm(2)], "the accept is a continuation, never a fresh take" ); @@ -1000,6 +1028,7 @@ fn the_loot_bind_confirm_raises_the_dialog_and_okay_calls_loot_slot() { fn a_row_click_takes_rather_than_continues() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -1014,10 +1043,10 @@ fn a_row_click_takes_rather_than_continues() { let (ix, iy) = icon_center(&quads, "INV_Fabric_Wool_01"); s.mouse_button(ix, iy, "LeftButton", true); s.mouse_button(ix, iy, "LeftButton", false); - assert_eq!(s.take_loot_picks(), vec![2], "the click is a TAKE"); - assert!( - s.take_loot_confirms().is_empty(), - "and never a continuation" + assert_eq!( + s.take_loot_calls(), + vec![LootCall::Take(2)], + "the click is a TAKE, never a continuation" ); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); } @@ -1028,6 +1057,7 @@ fn a_row_click_takes_rather_than_continues() { fn loot_row_awaiting_its_template_opens_clean() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, @@ -1039,7 +1069,7 @@ fn loot_row_awaiting_its_template_opens_clean() { // One row in flight: the wire gives the icon (by display id) and the count, nothing else. s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: vec![Some(LootRow { item_id: 2582, @@ -1100,7 +1130,7 @@ fn loot_row_awaiting_its_template_opens_clean() { s.fire_event("LOOT_CLOSED", vec![]); s.set_loot(Some(LootState { source_unit: false, - fishing: false, + has_money: false, master_candidates: Vec::new(), rows: vec![Some(LootRow { item_id: 2582, @@ -1131,6 +1161,7 @@ fn loot_row_awaiting_its_template_opens_clean() { fn stock_loot_rows_wear_the_item_button_art_and_light_under_the_cursor() { benilla_formats::wow_data_or_skip!(); let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.set_screen_size(1024.0, 768.0); for f in crate::ui_script::test_ui::production_order(&[ super::test_ui::LOOT_UI, diff --git a/crates/benilla-app/src/ui_script/sweep_tests.rs b/crates/benilla-app/src/ui_script/sweep_tests.rs index 452f28a86..ac37a8d11 100644 --- a/crates/benilla-app/src/ui_script/sweep_tests.rs +++ b/crates/benilla-app/src/ui_script/sweep_tests.rs @@ -75,8 +75,11 @@ fn legs_app() -> (App, crossbeam_channel::Receiver) { .init_resource::() .init_resource::() .init_resource::() + .init_resource::() + .init_resource::() .add_message::() .add_message::(); + crate::ui_loot::seat_loot_steps(app.world_mut()); (app, rx) } diff --git a/crates/benilla-app/src/ui_script/world_entry_tests.rs b/crates/benilla-app/src/ui_script/world_entry_tests.rs index 67d40147a..a4e9f36c4 100644 --- a/crates/benilla-app/src/ui_script/world_entry_tests.rs +++ b/crates/benilla-app/src/ui_script/world_entry_tests.rs @@ -471,8 +471,7 @@ fn sweep_lock_legs(world: &mut World) { let (tx, _rx) = crossbeam_channel::unbounded(); world.insert_resource(crate::net::NetCommands(tx)); world.init_resource::(); - world.init_resource::(); - world.init_resource::>(); + crate::ui_loot::seat_loot_steps(world); world.init_resource::(); world.init_resource::(); world.init_resource::(); diff --git a/crates/benilla-ui/src/script/button.rs b/crates/benilla-ui/src/script/button.rs index 2ec53a61e..2bcb9a058 100644 --- a/crates/benilla-ui/src/script/button.rs +++ b/crates/benilla-ui/src/script/button.rs @@ -1209,13 +1209,15 @@ pub(super) fn click_button(lua: &Lua, id: u32, button: &str, down: bool, scripte if !down { super::nameplate::note_click(lua, id, button); } - // The take runs whatever the handler did (`0x4c1867`): a row whose `OnClick` errored still - // loots. + // The take runs whatever the handler did (`0x4c1867`), inside the click: a row whose `OnClick` + // errored still loots, and the click's next listener reads what the take did. if let Some(slot) = take_loot { - // The slot is 0-based; the take queue speaks the 1-based row. - lua.app_data_mut::() - .expect("model app_data") - .loot_takes - .push(super::loot::LootTake::Pick(slot + 1)); + // The slot is 0-based; the call speaks the 1-based row. + let take = super::ScriptCall::Loot(super::loot::LootCall::Take(slot + 1)); + if let Err(e) = super::calls::submit(lua, take) { + lua.app_data_mut::() + .expect("model app_data") + .record_lua_error(&e); + } } } diff --git a/crates/benilla-ui/src/script/calls.rs b/crates/benilla-ui/src/script/calls.rs index 169b1c0e0..d5192e027 100644 --- a/crates/benilla-ui/src/script/calls.rs +++ b/crates/benilla-ui/src/script/calls.rs @@ -140,6 +140,8 @@ pub enum ScriptCall { /// `BindEnchant()` (`0x48d2e0`) or `ReplaceEnchant()` (`0x48d300`): a confirm popup's Yes on /// the item the seam parked. EnchantConfirm(super::EnchantAnswer), + /// A loot window verb, a row's own click among them ([`super::LootCall`]). + Loot(super::LootCall), } /// The mode the four `TargetNearest*` shims hand the TAB cycler `0x493f60`, the only byte that diff --git a/crates/benilla-ui/src/script/container.rs b/crates/benilla-ui/src/script/container.rs index 978267df5..92d1e1246 100644 --- a/crates/benilla-ui/src/script/container.rs +++ b/crates/benilla-ui/src/script/container.rs @@ -152,8 +152,9 @@ pub enum UseFork { Read, /// A mail letter, the instance's `ITEM_FIELD_ITEM_TEXT_ID`, opens the reader. Letter, - /// A lootable template sends `CMSG_OPEN_ITEM` (`0x5d8f7c`), locking the item first - /// (`0x5edcd9`). + /// A lootable template sends `CMSG_OPEN_ITEM` (`0x5d8f7c`) through `OpenItem`, which locks + /// the item (`0x5edcd9`) after its `SetAutoLoot` (`0x5edcb6`): the host's, as that store + /// sweeps an open window first. Open, /// The plain use, and a slot whose template is still in flight, which `0x5d9ff0` reads as /// not equippable. @@ -176,7 +177,8 @@ pub enum UseArm { } /// One `UseContainerItem` call past its gates: the slot, the item it resolved (`0x4fa1a6`) and -/// the arm it took, whose lock the call has already taken. +/// the arm it took, whose lock the call has already taken, but the open arm's, which the host +/// takes ([`UseFork::Open`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ContainerUse { pub bag: i64, @@ -549,9 +551,7 @@ fn use_cleared( may_cast, })); match arm { - UseArm::Withdraw | UseArm::Deposit | UseArm::Sell | UseArm::Item(UseFork::Open) => { - cursor::lock_item(model, guid); - } + UseArm::Withdraw | UseArm::Deposit | UseArm::Sell => cursor::lock_item(model, guid), UseArm::Item(UseFork::WrapPaper) => arm_gift_wrap(model, bag, slot), UseArm::Item(_) => {} } @@ -1832,13 +1832,14 @@ mod tests { assert_eq!(s.take_ui_errors(), vec!["ERR_CANT_USE_ITEM"]); assert!(!s.item_locked(0x11)); - // Control back, the requirement met: the open locks and goes out. + // Control back, the requirement met: the open goes out, for the host to lock past its + // `SetAutoLoot` (`0x5edcb6`, `0x5edcd9`). s.set_player_control(true); s.set_item_template(871, template(0, 0, 5)); s.run("UseContainerItem(0, 1)").unwrap(); assert!(s.take_ui_errors().is_empty()); assert_eq!(s.take_script_calls().len(), 1); - assert!(s.item_locked(0x11)); + assert!(!s.item_locked(0x11)); } /// The dispatcher's order (`0x5d8d00`): the gift, wrapping paper and quest-starter arms run diff --git a/crates/benilla-ui/src/script/loot.rs b/crates/benilla-ui/src/script/loot.rs index e144122d3..9c3233487 100644 --- a/crates/benilla-ui/src/script/loot.rs +++ b/crates/benilla-ui/src/script/loot.rs @@ -1,27 +1,38 @@ -//! The loot-window bindings: the app pushes the open loot ([`UiScript::set_loot`]), a coin row -//! first when there is gold, and the Lua verbs queue intents it drains. `slot` is 1-based; the app -//! maps a row to the money intent or the item's wire slot, which Lua never sees. +//! The loot-window bindings: the app pushes the window ([`UiScript::set_loot`]), a coin row first +//! while the money cell is set, and the verbs over it are script calls ([`LootCall`]) the host +//! applies inside them, as the reference's are done when they return. `slot` is 1-based; the app +//! maps a row to the money or the item's wire slot, which Lua never sees. //! -//! `LootSlot` is only the LOOT_BIND confirmation: `0x4c2e70` passes flag 1 to the take dispatcher -//! `0x4c2790`, which then refuses every slot but the pending one. The take itself is flag 0, the -//! row click of [`crate::widget::FrameKind::LootButton`]. Master loot's dropdown opens from the -//! app, on a picked row whose wire `slot_type` is `MASTER`, as the dispatcher branches on that byte -//! before any Lua runs. +//! The take dispatcher `0x4c2790(slot, confirm)` has two arms. The take itself, `confirm` 0, is the +//! row click of [`crate::widget::FrameKind::LootButton`] (`0x4c1820`), made after its `` +//! inside the click's input record. `LootSlot` is the other arm (`0x4c2e70` passes 1 at +//! `0x4c2ea5`), which acts only on the row a `LOOT_BIND_CONFIRM` stashed (`0x4c27c0`). use mlua::{Lua, MultiValue, Table, Value}; use super::binding_abi::{self, bool_or_default, flag}; -use super::Model; +use super::{Model, ScriptCall}; -/// A take the take dispatcher `0x4c2790` runs: a row click (flag 0) or a `LootSlot` (flag 1, the -/// confirm arm), 1-based. One queue in call order, so the app answers each confirm against the -/// pending-slot stash as it stood at its call. +/// A loot verb the host applies inside its call ([`ScriptCall::Loot`]), its rows 1-based. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LootTake { - /// A `LootButton`'s own click (`0x4c1820`). - Pick(u32), - /// `LootSlot(slot)` (`0x4c2e70`). +pub enum LootCall { + /// A `LootButton`'s own click: `0x4c2790(slot, 0)` (`0x4c1867`). + Take(u32), + /// `LootSlot(slot)`: `0x4c2790(slot, 1)`, the confirm arm (`0x4c2e70`). Confirm(u32), + /// `CloseLoot([failed])`: `0x48f200(1, 0, failed)` (`0x4c2ec0`). + Close { failed: bool }, + /// `GiveMasterLoot(slot, candidateIndex)` (`0x4c2940`). + GiveMaster { slot: u32, candidate: u32 }, + /// `SetAutoLoot(byte)` (`0x5df460`), which the engine's interactions make, never a verb. + SetAutoLoot(bool), + /// The rest of a loot call once the handlers its signal ran have returned, as the + /// reference's function goes on after `SignalEvent` runs them in place: the bind stash after + /// `LOOT_BIND_CONFIRM` (`0x4c2917` after `0x4c290f`), the coin click's close after + /// `LOOT_SLOT_CLEARED` (`0x4c286a` after `0x4c2862`). No verb makes it; the host's tail for + /// the call does ([`UiScript::resume_loot`]), down to the depth of what the call owed when it + /// began, so a call owing several steps runs each. + Resume { depth: usize }, } /// `CLootButton`'s own Lua method table (`0x847ce4`): one entry, per the registrar's `mov edx,1`. @@ -73,12 +84,12 @@ pub struct LootRow { /// One open loot window, pushed whole by the app; `None` means no loot is open. #[derive(Clone, Debug, Default, PartialEq)] pub struct LootState { - /// The fixed slot list. A looted slot becomes `None`: still counted by `GetNumLootItems`, read - /// once at `OnShow` (`LootFrame.lua:132`), but neither item nor coin, so `LootFrame_Update` - /// hides its button in place (`LootFrame.lua:80`). + /// The fixed slot list, the coin row first while [`Self::has_money`]. A looted slot becomes + /// `None` in place (`0x4c1f59`), neither item nor coin, so `LootFrame_Update` hides its button + /// there (`LootFrame.lua:80`). pub rows: Vec>, - /// `IsFishingLoot` (wire `loot_type` 3): the reel-in sound and portrait (`LootFrame.lua:137`). - pub fishing: bool, + /// The money cell is nonzero (`0xb71ba0`): row 1 is the coin row, taken (-1) or not. + pub has_money: bool, /// The names `GetMasterLootCandidate(i)` answers by 1-based slot, from `SMSG_LOOT_MASTER_LIST`. /// Not packed: in a raid each candidate sits in their subgroup's five-slot block, which the /// dropdown labels "Group N" (`LootFrame.lua:197-213`). A `None` (an empty slot, or a name not @@ -94,60 +105,68 @@ pub struct LootState { /// source. Upper case, so no `SetPortraitTexture` token, which is lowercased, can name it. pub const LOOT_PORTRAIT_UNIT: &str = "LOOT"; +/// The wire `loot_type` of fishing loot. +const FISHING: u8 = 3; + +impl LootState { + /// `GetNumLootItems` (`0x4c2260`): the last occupied row's position plus one (`0x4c2281`), plus + /// one while the money cell is nonzero (`0x4c229b`), so a gap before the last row counts, one + /// after it does not, and a taken coin still counts. + pub fn count(&self) -> usize { + let coin = usize::from(self.has_money); + let items = self.rows.get(coin..).unwrap_or_default(); + items.iter().rposition(Option::is_some).map_or(0, |i| i + 1) + coin + } +} + impl super::UiScript { /// Push (or clear, with `None`) the open loot. pub fn set_loot(&mut self, state: Option) { self.model_mut().loot = state; } - /// Drain the takes in call order; the app maps a pick to the coin or the item's wire slot and - /// applies the bind-on-pickup deferral, and honours a confirm only for the row a LOOT_BIND - /// confirm is pending for (the reference's `[0x847cec]` gate). - pub fn take_loot_takes(&mut self) -> Vec { - std::mem::take(&mut self.model_mut().loot_takes) + /// The loot type cell (`0xb71bbc`), which the copier stores (`0x4c1dd6`) and no close clears: + /// `IsFishingLoot` reads it, window or not. + pub fn set_loot_type(&mut self, loot_type: u8) { + self.model_mut().loot_type = loot_type; } - /// Drain the 1-based rows the row click took, leaving the confirms queued. - pub fn take_loot_picks(&mut self) -> Vec { - self.take_loot_kind(|t| match t { - LootTake::Pick(row) => Some(row), - LootTake::Confirm(_) => None, + /// `SetAutoLoot` (`0x5df460`) as a call, the interaction's: the byte stored, and with a loot + /// target held a sweep of the open window. Inside an engine turn it applies as the turn ends. + pub fn set_auto_loot(&mut self, byte: bool) { + let lua = self.lua().clone(); + if let Err(e) = super::calls::submit(&lua, ScriptCall::Loot(LootCall::SetAutoLoot(byte))) { + self.model_mut().record_lua_error(&e); + } + } + + /// Shift as the VM's calls see it (`EventIsKeyDown(0)`, the state `IsShiftKeyDown` reads too): + /// what `OpenItem` passes `SetAutoLoot` (`0x5edca7`), read inside its `UseContainerItem` call. + pub fn shift_key_down(&self) -> bool { + self.model_ref().modifiers.0 + } + + /// The loot the VM shows now, as the last push or a call left it. + pub fn shown_loot(&self) -> Option { + self.model_ref().loot.clone() + } + + /// Make [`LootCall::Resume`] down to `depth`, for the host's tail to a loot call whose signal's + /// handlers have run; a refusal is reported as a script error. + pub fn resume_loot(&mut self, depth: usize) { + let lua = self.lua().clone(); + if let Err(e) = super::calls::submit(&lua, ScriptCall::Loot(LootCall::Resume { depth })) { + self.model_mut().record_lua_error(&e); + } + } + + /// The loot calls a harness's VM kept ([`Self::keep_calls`]), in call order. + pub fn take_loot_calls(&mut self) -> Vec { + self.take_calls_where(|call| match call { + ScriptCall::Loot(call) => Some(*call), + _ => None, }) } - - /// Drain the 1-based rows `LootSlot` queued, leaving the picks queued. - pub fn take_loot_confirms(&mut self) -> Vec { - self.take_loot_kind(|t| match t { - LootTake::Confirm(row) => Some(row), - LootTake::Pick(_) => None, - }) - } - - /// Drain the takes `kind` answers a row for, in order, keeping the rest. - fn take_loot_kind(&mut self, kind: impl Fn(LootTake) -> Option) -> Vec { - let takes = &mut self.model_mut().loot_takes; - let mut rows = Vec::new(); - takes.retain(|&t| match kind(t) { - Some(row) => { - rows.push(row); - false - } - None => true, - }); - rows - } - - /// Whether `CloseLoot` was called since the last drain, with its `failed` flag: the app - /// releases an open loot and, on a set flag, shows `ERR_LOOT_NO_UI`. - pub fn take_loot_close(&mut self) -> Option { - self.model_mut().loot_close.take() - } - - /// Drain the `GiveMasterLoot(slot, candidateIndex)` pairs, both 1-based; the app resolves them - /// to a wire slot and a guid for `CMSG_LOOT_MASTER_GIVE`. - pub fn take_loot_master_gives(&mut self) -> Vec<(u32, u32)> { - std::mem::take(&mut self.model_mut().loot_master_gives) - } } /// Register the loot globals. @@ -176,12 +195,12 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { })?, )?; - // GetNumLootItems(): cleared slots included, so it holds still while a window is open. + // GetNumLootItems() (`0x4c2c30`): the count, 0 with no window (`0x4c226d`). g.set( "GetNumLootItems", lua.create_function(|lua, ()| { let model = lua.app_data_ref::().expect("model app_data"); - Ok(model.loot.as_ref().map_or(0, |l| l.rows.len()) as i64) + Ok(model.loot.as_ref().map_or(0, LootState::count) as i64) })?, )?; @@ -284,8 +303,9 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { g.set( "IsFishingLoot", lua.create_function(|lua, ()| { + // `0x4c2740` reads the type cell unguarded: a close leaves it. let model = lua.app_data_ref::().expect("model app_data"); - Ok(flag(model.loot.as_ref().is_some_and(|l| l.fishing))) + Ok(flag(model.loot_type == FISHING)) })?, )?; @@ -327,9 +347,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { lua.create_function(|lua, slot: Value| { // `is-number` else `Usage: LootSlot(slot)` (`0x84807c`, `0x4c2e81`). let slot = binding_abi::index_arg32(lua, slot, "Usage: LootSlot(slot)")?; - let mut model = lua.app_data_mut::().expect("model app_data"); - model.loot_takes.push(LootTake::Confirm(slot)); - Ok(()) + super::calls::submit(lua, ScriptCall::Loot(LootCall::Confirm(slot))) })?, )?; @@ -341,9 +359,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { "CloseLoot", lua.create_function(|lua, args: MultiValue| { let failed = bool_or_default(args.front(), false); - let mut model = lua.app_data_mut::().expect("model app_data"); - model.loot_close.get_or_insert(failed); - Ok(()) + super::calls::submit(lua, ScriptCall::Loot(LootCall::Close { failed })) })?, )?; @@ -380,9 +396,10 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let slot = binding_abi::index_arg32(lua, slot, "Usage: GiveMasterLoot(slot, index)")?; let candidate = binding_abi::index_arg32(lua, candidate, "Usage: GiveMasterLoot(slot, index)")?; - let mut model = lua.app_data_mut::().expect("model app_data"); - model.loot_master_gives.push((slot, candidate)); - Ok(()) + super::calls::submit( + lua, + ScriptCall::Loot(LootCall::GiveMaster { slot, candidate }), + ) })?, )?; @@ -391,7 +408,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { #[cfg(test)] mod tests { - use super::{LootRow, LootState}; + use super::{LootCall, LootRow, LootState}; use crate::script::UiScript; /// The region data behind a named texture: its portrait key and file. @@ -450,6 +467,7 @@ mod tests { LootState { source_unit: false, master_candidates: Vec::new(), + has_money: true, rows: vec![ Some(LootRow { item_id: 0, @@ -483,7 +501,6 @@ mod tests { random_property_id: 0, }), ], - fishing: false, } } @@ -540,10 +557,14 @@ mod tests { assert!(s.eval::("return GetLootSlotLink(3) == nil").unwrap()); assert!(s.eval::("return not IsFishingLoot()").unwrap()); - let mut fished = loot(); - fished.fishing = true; - s.set_loot(Some(fished)); + s.set_loot_type(3); assert!(s.eval::("return IsFishingLoot()").unwrap()); + s.set_loot(None); + assert!( + s.eval::("return IsFishingLoot()").unwrap(), + "the type cell, not the window" + ); + s.set_loot_type(1); s.set_loot(Some(loot())); assert!(s.eval::("return GetLootSlotInfo(9) == nil").unwrap()); @@ -670,57 +691,101 @@ mod tests { ); } - #[test] - fn give_master_loot_queues_the_assignment() { + /// A VM with no host behind it that keeps its calls, the loot open. + fn kept() -> UiScript { let mut s = UiScript::new().unwrap(); - let mut ml = loot(); - ml.master_candidates = vec![Some("Thrall".into())]; - s.set_loot(Some(ml)); - assert!(s.take_loot_master_gives().is_empty()); + s.keep_calls(); + s.set_loot(Some(loot())); + s + } + + #[test] + fn give_master_loot_is_a_call() { + let mut s = kept(); s.run("GiveMasterLoot(2, 1)").unwrap(); - assert_eq!(s.take_loot_master_gives(), vec![(2, 1)]); - assert!(s.take_loot_master_gives().is_empty(), "drained"); - assert!(s.take_loot_picks().is_empty()); + assert_eq!( + s.take_loot_calls(), + vec![LootCall::GiveMaster { + slot: 2, + candidate: 1 + }] + ); } - /// In the pick queue `LootSlot` would loot any row an addon named, which the reference refuses. + /// `LootSlot` is the confirm arm (`0x4c2ea5`, `edx` 1), never the take: as a take it would + /// loot any row an addon named, which the reference refuses. #[test] - fn loot_slot_queues_confirms_not_picks() { - let mut s = UiScript::new().unwrap(); - s.set_loot(Some(loot())); + fn loot_slot_is_the_confirm_call_not_the_take() { + let mut s = kept(); s.run("LootSlot(2)").unwrap(); - assert!( - s.take_loot_picks().is_empty(), - "LootSlot is not the take verb" - ); - assert_eq!(s.take_loot_confirms(), vec![2]); - assert!(s.take_loot_confirms().is_empty(), "drained"); + assert_eq!(s.take_loot_calls(), vec![LootCall::Confirm(2)]); } #[test] - fn close_loot_flags_the_intent() { - let mut s = UiScript::new().unwrap(); - s.set_loot(Some(loot())); - assert_eq!(s.take_loot_close(), None); - s.run("CloseLoot()").unwrap(); - assert_eq!(s.take_loot_close(), Some(false)); - assert_eq!(s.take_loot_close(), None, "drained"); - s.run("CloseLoot(1)").unwrap(); - assert_eq!( - s.take_loot_close(), - Some(true), - "the failed flag (`0x6f1c10`)" - ); - for (arg, failed) in [("nil", false), ("0", false), ("'1'", true), ("true", true)] { + fn close_loot_is_a_call_with_its_flag() { + let mut s = kept(); + for (arg, failed) in [ + ("", false), + ("1", true), + ("nil", false), + ("0", false), + ("'1'", true), + ("true", true), + ] { s.run(&format!("CloseLoot({arg})")).unwrap(); - assert_eq!(s.take_loot_close(), Some(failed), "CloseLoot({arg})"); + assert_eq!( + s.take_loot_calls(), + vec![LootCall::Close { failed }], + "CloseLoot({arg}), the flag through `0x6f1c10`" + ); } - s.run("CloseLoot() CloseLoot(1)").unwrap(); - assert_eq!( - s.take_loot_close(), - Some(false), - "the first close releases the loot; the second finds none" - ); + } + + /// With no host lent and no harness keeping them, a loot verb raises, as every call does. + #[test] + fn a_loot_verb_with_no_host_raises() { + let s = UiScript::new().unwrap(); + let e = s.run("CloseLoot()").unwrap_err().to_string(); + assert!(e.contains("no call host"), "{e}"); + } + + /// `0x4c2260`: the last occupied row's position plus one, plus one while the money cell is + /// set (`0x4c229b`), a taken coin's -1 included. + #[test] + fn the_count_is_the_last_occupied_row_plus_the_money_cell() { + let item = || { + Some(LootRow { + name: Some("Wool Cloth".into()), + ..LootRow::default() + }) + }; + let coin = || { + Some(LootRow { + is_coin: true, + ..LootRow::default() + }) + }; + let count = |has_money: bool, rows: Vec>| { + LootState { + rows, + has_money, + ..LootState::default() + } + .count() + }; + // Coin, A, B with B taken: 2; with the coin taken too: still 2; A and B taken: 1. + assert_eq!(count(true, vec![coin(), item(), None]), 2); + assert_eq!(count(true, vec![None, item(), None]), 2); + assert_eq!(count(true, vec![coin(), None, None]), 1); + // No money: a gap before the last row counts, one after it does not. + assert_eq!(count(false, vec![None, item()]), 2); + assert_eq!(count(false, vec![item(), None]), 1); + assert_eq!(count(false, vec![None, None]), 0); + let mut s = UiScript::new().unwrap(); + let mut state = loot(); + state.rows[2] = None; + s.set_loot(Some(state)); + assert_eq!(s.eval::("return GetNumLootItems()").unwrap(), 2); } #[test] @@ -784,6 +849,7 @@ mod tests { #[test] fn an_unmodified_click_runs_the_handler_and_then_takes() { let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.run( r#" lb = CreateFrame("LootButton", "LB1", UIParent) @@ -795,19 +861,28 @@ mod tests { .unwrap(); hardware_click(&mut s, "LB1", "LeftButton"); assert_eq!(s.eval::("return ran").unwrap(), 1, "the handler ran"); - assert_eq!(s.take_loot_picks(), vec![3], "and then the take, 1-based"); + assert_eq!( + s.take_loot_calls(), + vec![LootCall::Take(3)], + "and then the take, 1-based" + ); // An erroring handler still loots: `0x4c1833`'s result is never tested. s.run(r#"lb:SetScript("OnClick", function() error("boom") end)"#) .unwrap(); hardware_click(&mut s, "LB1", "LeftButton"); - assert_eq!(s.take_loot_picks(), vec![3], "a broken hook still loots"); + assert_eq!( + s.take_loot_calls(), + vec![LootCall::Take(3)], + "a broken hook still loots" + ); } /// `0x4c1820` forwards the button code without ever comparing it. #[test] fn right_click_loots_like_left_click() { let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.run( r#" lb = CreateFrame("LootButton", "LB1", UIParent) @@ -817,7 +892,7 @@ mod tests { ) .unwrap(); hardware_click(&mut s, "LB1", "RightButton"); - assert_eq!(s.take_loot_picks(), vec![2]); + assert_eq!(s.take_loot_calls(), vec![LootCall::Take(2)]); } /// The handler still runs, so stock `LootFrameItem_OnClick` owns ctrl and shift alone. @@ -832,6 +907,7 @@ mod tests { .enumerate() { let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.run( r#" lb = CreateFrame("LootButton", "LB1", UIParent) @@ -848,7 +924,7 @@ mod tests { 1, "case {i}: handler ran" ); - assert!(s.take_loot_picks().is_empty(), "case {i}: no take"); + assert!(s.take_loot_calls().is_empty(), "case {i}: no take"); } } @@ -856,6 +932,7 @@ mod tests { #[test] fn a_scripted_click_does_nothing_at_all() { let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.run( r#" lb = CreateFrame("LootButton", "LB1", UIParent) @@ -871,7 +948,7 @@ mod tests { 0, "the handler never ran" ); - assert!(s.take_loot_picks().is_empty(), "and nothing was taken"); + assert!(s.take_loot_calls().is_empty(), "and nothing was taken"); // A plain Button's Click() is unaffected. s.run( r#" @@ -889,17 +966,18 @@ mod tests { #[test] fn set_slot_converts_and_guards() { let mut s = UiScript::new().unwrap(); + s.keep_calls(); s.run(r#"lb = CreateFrame("LootButton", "LB1", UIParent)"#) .unwrap(); // `ftol` truncates toward zero: 4.9 is row 4, not 5. s.run("lb:SetSlot(4.9)").unwrap(); hardware_click(&mut s, "LB1", "LeftButton"); - assert_eq!(s.take_loot_picks(), vec![4]); + assert_eq!(s.take_loot_calls(), vec![LootCall::Take(4)]); s.run(r#"lb:SetSlot("2")"#).unwrap(); hardware_click(&mut s, "LB1", "LeftButton"); - assert_eq!(s.take_loot_picks(), vec![2]); + assert_eq!(s.take_loot_calls(), vec![LootCall::Take(2)]); let e = s.run("lb:SetSlot('x')").unwrap_err().to_string(); assert!(e.contains("Usage: SetSlot(index)"), "{e}"); @@ -910,7 +988,7 @@ mod tests { s.run(r#"fresh = CreateFrame("LootButton", "LB2", UIParent)"#) .unwrap(); hardware_click(&mut s, "LB2", "LeftButton"); - assert!(s.take_loot_picks().is_empty()); + assert!(s.take_loot_calls().is_empty()); s.run(r#"b = CreateFrame("Button", "PlainB", UIParent)"#) .unwrap(); diff --git a/crates/benilla-ui/src/script/mod.rs b/crates/benilla-ui/src/script/mod.rs index 8849124b1..7c6a16a8d 100644 --- a/crates/benilla-ui/src/script/mod.rs +++ b/crates/benilla-ui/src/script/mod.rs @@ -311,7 +311,7 @@ pub use item_stats::{ pub use item_text::ItemTextState; pub use layout_cache::{AnchorLayout, FrameLayout, LayoutPoint}; pub use lock_check::{check_lock, LockCheck, LockOpener, LockOpeners, LockSlotView}; -pub use loot::{LootRow, LootState, LootTake, LOOT_PORTRAIT_UNIT}; +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, diff --git a/crates/benilla-ui/src/script/model.rs b/crates/benilla-ui/src/script/model.rs index a026652b2..8d09c0589 100644 --- a/crates/benilla-ui/src/script/model.rs +++ b/crates/benilla-ui/src/script/model.rs @@ -928,18 +928,11 @@ pub(crate) struct Model { pub(crate) pending_equip_answers: Vec, pub(crate) bind_on_use_confirms: Vec, - /// The open loot, the row clicks and whether `CloseLoot` ran. A click is the reference's take - /// `0x4c2790` with flag 0, raising `LOOT_BIND` for a bind-on-pickup row (a `LootButton`'s own - /// click, `0x4c1820`); `LootSlot` passes 1 (`0x4c2e70`), taking it after the confirm. + /// The open loot as the app pushed it; the verbs over it are script calls + /// ([`loot::LootCall`]). pub(crate) loot: Option, - /// The row clicks and `LootSlot(slot)` rows, 1-based, in call order, for the reference's - /// pending-slot gate. - pub(crate) loot_takes: Vec, - /// The first `CloseLoot` since the last drain, with its `failed` flag; a later one in the - /// same frame finds the loot already released. - pub(crate) loot_close: Option, - /// `GiveMasterLoot(slot, candidateIndex)`, both 1-based display positions the app translates. - pub(crate) loot_master_gives: Vec<(u32, u32)>, + /// The loot type cell (`0xb71bbc`), which outlives the window. + pub(crate) loot_type: u8, /// The open group-loot rolls, and the `RollOnLoot` `(roll_id, roll_type)` votes. pub(crate) loot_rolls: loot_roll::LootRollsState, @@ -1773,11 +1766,9 @@ impl Model { craft_selection: 0, craft_close: false, loot: None, + loot_type: 0, pending_equip_answers: Vec::new(), bind_on_use_confirms: Vec::new(), - loot_takes: Vec::new(), - loot_close: None, - loot_master_gives: Vec::new(), loot_rolls: loot_roll::LootRollsState::default(), loot_roll_votes: Vec::new(), item_text: None, diff --git a/crates/benilla-ui/src/script/tests/tooltip_item/mechanics.rs b/crates/benilla-ui/src/script/tests/tooltip_item/mechanics.rs index ddfabb31b..1f4005ada 100644 --- a/crates/benilla-ui/src/script/tests/tooltip_item/mechanics.rs +++ b/crates/benilla-ui/src/script/tests/tooltip_item/mechanics.rs @@ -869,6 +869,7 @@ fn a_looted_roll_shows_its_lines_and_never_the_placeholder() { s.set_loot(Some(LootState { source_unit: false, master_candidates: Vec::new(), + has_money: false, rows: vec![Some(LootRow { name: Some("Bloodrazor of the Monkey".into()), texture: None, @@ -880,7 +881,6 @@ fn a_looted_roll_shows_its_lines_and_never_the_placeholder() { // The row carries the roll id; the engine resolves it, as the reference reads `+0x424`. random_property_id: 584, })], - fishing: false, })); s.set_random_properties( [( @@ -951,6 +951,7 @@ fn a_looted_item_with_no_roll_shows_neither_line_nor_placeholder() { s.set_loot(Some(LootState { source_unit: false, master_candidates: Vec::new(), + has_money: false, rows: vec![Some(LootRow { name: Some("Bloodrazor".into()), quantity: 1, @@ -958,7 +959,6 @@ fn a_looted_item_with_no_roll_shows_neither_line_nor_placeholder() { item_id: 8888, ..Default::default() })], - fishing: false, })); s.run( r#" diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index aba0a2282..9e2833585 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -29,7 +29,7 @@ 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): 239 +- [benilla-app](#benilla-app): 240 - [benilla-assets](#benilla-assets): 6 - [benilla-blp](#benilla-blp): 1 - [benilla-formats](#benilla-formats): 22 @@ -267,7 +267,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - Default off where the reference registers "1". Its reverb is FMOD 3's EAX API, which renders only with hardware 3D mixing, so off is what the reference is heard to produce (inferred: `fmod.dll`'s render side is untraced). ([`src/sound/mod.rs:103`](../crates/benilla-app/src/sound/mod.rs#L103)) - `SoundOutputLimiter`, not a 1.12 CVar, default on, so overlapping full-scale kits are limited rather than clipped. ([`src/sound/mod.rs:121`](../crates/benilla-app/src/sound/mod.rs#L121)) - With no character the reference leaves the listener where it was; benilla seats it on the camera, where the view is. ([`src/sound/mod.rs:472`](../crates/benilla-app/src/sound/mod.rs#L472)) -- The reference also plays an optimistic coin at the loot-money click, so looted money sounds twice; benilla plays the watcher's coin alone, because one coin on the confirmed change reads cleanly and the round trip the early coin hides is imperceptible on a local server. ([`src/sound/money.rs:7`](../crates/benilla-app/src/sound/money.rs#L7)) +- The reference also plays an optimistic coin at the loot-money click, and at the auto-loot sweep's money, once a session (`0x4c201b`-`0x4c2020`, the same `0x458030` call), so looted money sounds twice; benilla plays the watcher's coin alone, because one coin on the confirmed change reads cleanly and the round trip the early coin hides is imperceptible on a local server. ([`src/sound/money.rs:7`](../crates/benilla-app/src/sound/money.rs#L7)) - 1.12.1 sets FMOD up on driver 0 and, when that fails, runs silent for the session (`Sound::Initialize` `0x7a4330`, the driver βˆ’1 β†’ 0 at `0x7a445f`); here another output stands in, because on Linux the default is often a stock `dmix` whose card a sound server holds. ([`src/sound/output/cpal.rs:193`](../crates/benilla-app/src/sound/output/cpal.rs#L193)) - A change of the default output device is followed (here and in `coreaudio.rs`), where 1.12.1 initialises its sound device once and never again (`Sound::Initialize` `0x7a4330` refuses a second call; the driver-enumeration functions `0x7a6320`-`0x7a6380` have no caller), because a headset plugged in mid-session should play at once. ([`src/sound/output/cpal.rs:544`](../crates/benilla-app/src/sound/output/cpal.rs#L544)) @@ -279,8 +279,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### target -- The reference's arm reads the last object's stop (`0x611336` before `0x610383` stores this one's), so its first walk has no stop. ([`src/target/click.rs:413`](../crates/benilla-app/src/target/click.rs#L413)) -- It runs on the first frame with none, so an arrival that sends no stop (mid-air, rooted, under a held turn key) acts at once or on landing or release, where the reference waits for the next ground stop and can act long after, wherever the player then is. ([`src/target/click.rs:1211`](../crates/benilla-app/src/target/click.rs#L1211)) +- The reference's arm reads the last object's stop (`0x611336` before `0x610383` stores this one's), so its first walk has no stop. ([`src/target/click.rs:493`](../crates/benilla-app/src/target/click.rs#L493)) +- It runs on the first frame with none, so an arrival that sends no stop (mid-air, rooted, under a held turn key) acts at once or on landing or release, where the reference waits for the next ground stop and can act long after, wherever the player then is. ([`src/target/click.rs:1341`](../crates/benilla-app/src/target/click.rs#L1341)) - The rank is held to 7, the top of the ring scale's eight entries (`0..=7`), where the reference keeps any value; a server rank past 7 would index outside our palette. ([`src/target/relations.rs:491`](../crates/benilla-app/src/target/relations.rs#L491)) - TAB uses Classic Era's screen-space priority, not 1.12's Β±30Β° facing cone and snapshot cursor (`0x493f60`), because the cone skips a close mob in front of the camera, which sits behind the character. ([`src/target/scan.rs:3`](../crates/benilla-app/src/target/scan.rs#L3)) - Our own body is never a candidate. The reference's friendly scan picks the player at some facings (`CanAssist(P, P)` is true, `0x6061e0`; the cone test `0x47f220`), but our scoring always puts the player dead centre at distance 0, so CTRL-TAB would pick us on every press. ([`src/target/scan.rs:194`](../crates/benilla-app/src/target/scan.rs#L194)) @@ -369,10 +369,11 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### ui_loot -- It is the display row, where the reference's is the item index plus one (`0x4c2885`), so an addon's `GetLootSlotInfo(arg1)` reads the row the dialog is for. ([`src/ui_loot/mod.rs:131`](../crates/benilla-app/src/ui_loot/mod.rs#L131)) -- Our close paths clear it guid-matched, where `CloseInteraction` clears it unconditionally (`0x48f2c9`), so closing an old window keeps a newer `CMSG_LOOT`'s latch. ([`src/ui_loot/mod.rs:456`](../crates/benilla-app/src/ui_loot/mod.rs#L456)) -- A negative answer releases the row, where the reference's callback `0x4c2ac0` returns on a failed query and the window never opens, because an entry the server cannot describe would otherwise keep the loot shut for good. ([`src/ui_loot/mod.rs:640`](../crates/benilla-app/src/ui_loot/mod.rs#L640)) -- A push is dropped after `RECEIVE_MAX_TRIES` frames, where the reference waits on the item-cache callback with no timeout, because an entry the server never describes would otherwise stay queued. ([`src/ui_loot/mod.rs:752`](../crates/benilla-app/src/ui_loot/mod.rs#L752)) +- It is the display row, where the reference's is the item index plus one (`0x4c2885`), so an addon's `GetLootSlotInfo(arg1)` reads the row the dialog is for. ([`src/ui_loot/mod.rs:231`](../crates/benilla-app/src/ui_loot/mod.rs#L231)) +- `autoLootDefault` is benilla's own option, 1.12 auto-looting only on a shift-click, and off is 1.12's behaviour. ([`src/ui_loot/mod.rs:469`](../crates/benilla-app/src/ui_loot/mod.rs#L469)) +- Our close paths clear it guid-matched, where `CloseInteraction` clears it unconditionally (`0x48f2c9`), so closing an old window keeps a newer `CMSG_LOOT`'s latch. ([`src/ui_loot/mod.rs:497`](../crates/benilla-app/src/ui_loot/mod.rs#L497)) +- A negative answer releases the row, where the reference's callback `0x4c2ac0` returns on a failed query and the window never opens, because an entry the server cannot describe would otherwise keep the loot shut for good. ([`src/ui_loot/mod.rs:682`](../crates/benilla-app/src/ui_loot/mod.rs#L682)) +- A push is dropped after `RECEIVE_MAX_TRIES` frames, where the reference waits on the item-cache callback with no timeout, because an entry the server never describes would otherwise stay queued. ([`src/ui_loot/mod.rs:795`](../crates/benilla-app/src/ui_loot/mod.rs#L795)) #### ui_loot_roll