From 9195a4d05e287cce85c3abd09a81ee4315614bc9 Mon Sep 17 00:00:00 2001 From: Sam Sung <51686767+samwhosung@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:52:53 +0700 Subject: [PATCH] Profession, craft and loot windows follow 1.12.1 across reloads (#2308) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The profession, craft and loot windows, and two death timers, disagreed with 1.12.1 across a `/reload`, a group header and a busy frame. - A `/reload` keeps the profession book open and unshown (`0x4fc750`), and its record waits outlive the VM. Clicking an open profession closes it, as the toggle `0x4fc910` does. - The world-enter cascade, and so a reload or a worldport, closes the craft window silently (`0x4f5ee0`). - The craft list heads each group once there are two (`0x4f60c0`). It sorts them with the comparators' header skip over the CRT qsort, answers `"header"` and folds. - A replaced loot session's steps run on their own latch, stash and copier wait. An inventory failure re-signals `LOOT_OPENED` under the auto-loot byte (`0x5e3aff`). - The release and corpse timers answer whole seconds (`0x48b5ae`, `0x48b5f0`). Tests fail on main. Fixes #2295 Fixes #2296 Fixes #2291 Fixes #2210 Fixes #2256 Fixes #1530 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5.5 --- crates/benilla-app/src/item_lane.rs | 1 + crates/benilla-app/src/ui_craft.rs | 87 ++- crates/benilla-app/src/ui_items/net.rs | 9 +- crates/benilla-app/src/ui_loot/call_tests.rs | 149 +++++ crates/benilla-app/src/ui_loot/mod.rs | 97 ++- crates/benilla-app/src/ui_loot/net.rs | 2 + .../benilla-app/src/ui_script/death_tests.rs | 40 ++ .../src/ui_script/verb_event_gate.rs | 14 - crates/benilla-app/src/ui_tooltip/tests.rs | 1 + crates/benilla-app/src/ui_tradeskill.rs | 265 +++++++- crates/benilla-app/tests/tradeskill_frame.rs | 1 + crates/benilla-ui/src/script/craft.rs | 609 +++++++++++++++--- crates/benilla-ui/src/script/death.rs | 8 +- crates/benilla-ui/src/script/model.rs | 20 +- .../src/script/tests/tooltip_spell.rs | 2 + .../benilla-ui/src/script/tooltip_item/mod.rs | 6 +- crates/benilla-ui/src/script/tooltip_spell.rs | 9 +- .../benilla-ui/src/script/tradeskill/mod.rs | 28 +- .../benilla-ui/src/script/tradeskill/tests.rs | 29 + docs/DEVIATIONS.md | 12 +- 20 files changed, 1225 insertions(+), 164 deletions(-) diff --git a/crates/benilla-app/src/item_lane.rs b/crates/benilla-app/src/item_lane.rs index 48dc83391..aece761fc 100644 --- a/crates/benilla-app/src/item_lane.rs +++ b/crates/benilla-app/src/item_lane.rs @@ -452,6 +452,7 @@ mod tests { tools: Vec::new(), tooltip: CraftTooltip::Spell(7418), spell_level: 1, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, diff --git a/crates/benilla-app/src/ui_craft.rs b/crates/benilla-app/src/ui_craft.rs index 2394ef2be..f8a58b220 100644 --- a/crates/benilla-app/src/ui_craft.rs +++ b/crates/benilla-app/src/ui_craft.rs @@ -26,8 +26,9 @@ use crate::ui_unit::UnitFeed; /// The open Craft window, client-local. A nonzero opener `EffectMiscValue[0]` routes here /// (`Spell_C::TryCast` `0x6e4b60`) and is the craft type (1 Beast Training, 3 Enchanting) the -/// client keeps at `0xbdcfb8` for admission and row order. The session end clears it too: a -/// logout's fresh VM never runs the old one's `OnHide`. +/// client keeps at `0xbdcfb8` for admission and row order. The opener of the open type, the +/// world-enter init (`0x4f5ee0`) and the session end clear it too: a logout's fresh VM never runs +/// the old one's `OnHide`. #[derive(Resource, Default)] pub(crate) struct CraftOpen { pub(crate) line: Option, @@ -503,6 +504,7 @@ fn feed_craft( // `spellLevel` at `+0x74` (column 29), not `baseLevel` (column 28). spell_level: d.spell_level, // The group key is the ability row's line (`0x4f61b1`), 0 with none. + group: sla.map_or(0, |a| a.skill_id), skill_line: sla .and_then(|a| skill_lines.catalog.line(a.skill_id)) .map(|l| l.name.clone()), @@ -524,6 +526,12 @@ fn feed_craft( }) })(); + // The type stays open while a frame cannot resolve its book (a worldport's purge of our + // own player): only a close or the world-enter init ends it (`0x4f5fe0`, `0x4f5ee0`). + let fresh = match fresh { + None if open.line.is_some() => memo.state.clone(), + f => f, + }; // `CloseCraft` closes the VM's window and signals `CRAFT_CLOSE` in the verb (`0x4f5fef`). let closed_in_place = !script.craft_open(); // The getters' item callbacks, kept by their calls; each record that landed rebuilds @@ -550,7 +558,9 @@ fn feed_craft( match (&memo.state, &fresh) { (_, Some(f)) if opened => { debug!("ui_craft: window opens — {} recipe(s)", f.recipes.len()); - // The open's build signals the update (`0x4f661a`), then the show. + // The open's resets and build (`0x4f601c`-`0x4f6036`), whose tail signals the + // update (`0x4f661a`), then the show (`0x4f6040`). + script.craft_opened(); fires.post("CRAFT_UPDATE", vec![]); fires.post("CRAFT_SHOW", vec![]); } @@ -1472,4 +1482,75 @@ mod tests { .insert_template(DUST, Some(crate::items::test_template("Strange Dust"))); assert_eq!(heard(&mut app), ["CRAFT_UPDATE", "CRAFT_UPDATE"]); } + + /// The world-enter init `0x4f5ee0` (`0x4909c4`) zeroes the craft type (`[0xbdcfb8]`) and + /// signals nothing; `CRAFT_CLOSE` is `0x4f5fe0`'s alone. A worldport's cascade closes the + /// window under the interface that survives it with no close, and a reload's closes it under + /// the new one, which hears no show. + #[test] + fn the_world_enter_init_closes_the_window_silently() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + app.init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)) + .insert_resource(crate::ui_action::Spells::empty_for_tests()) + .insert_resource(SkillLines { + catalog: benilla_formats::SkillLineCatalog::from_spell_lines([]), + }) + .add_message::(); + app.world_mut() + .spawn((ObjectStore(Default::default()), SelfPlayer)); + let listening = || { + let script = UiScript::new().unwrap(); + script + .run( + "HEARD = {} local f = CreateFrame('Frame') f:RegisterEvent('CRAFT_SHOW') \ + f:RegisterEvent('CRAFT_UPDATE') f:RegisterEvent('CRAFT_CLOSE') \ + f:SetScript('OnEvent', function() table.insert(HEARD, event) end)", + ) + .unwrap(); + script + }; + app.insert_non_send_resource(listening()); + app.add_systems( + Update, + ( + crate::ui_tradeskill::reset_crafts_on_world_enter, + crate::ui_tradeskill::close_craft_on_world_enter, + feed_craft, + ) + .chain(), + ); + let heard = |app: &mut App| { + app.update(); + app.world() + .non_send_resource::() + .eval::>("local h = HEARD HEARD = {} return h") + .unwrap() + }; + let open = |app: &mut App| { + *app.world_mut().resource_mut::() = CraftOpen { + line: Some(333), + craft_type: 3, + }; + heard(app) + }; + + assert_eq!(open(&mut app), ["CRAFT_UPDATE", "CRAFT_SHOW"]); + app.world_mut() + .write_message(crate::net::WorldEnterCascadeMessage); + assert!(heard(&mut app).is_empty(), "a worldport closes it silently"); + assert_eq!(app.world().resource::().line, None); + + assert_eq!(open(&mut app), ["CRAFT_UPDATE", "CRAFT_SHOW"]); + app.insert_non_send_resource(listening()); + app.world_mut() + .write_message(crate::net::WorldEnterCascadeMessage); + assert!(heard(&mut app).is_empty(), "a reload shows nothing"); + assert_eq!(app.world().resource::().line, None); + } } diff --git a/crates/benilla-app/src/ui_items/net.rs b/crates/benilla-app/src/ui_items/net.rs index a90d8fb4b..34e20726f 100644 --- a/crates/benilla-app/src/ui_items/net.rs +++ b/crates/benilla-app/src/ui_items/net.rs @@ -6,7 +6,7 @@ use bevy::prelude::*; use super::{EquipError, EquipErrors}; use crate::net::{NetHandlerApp, SelfGuid}; -use crate::ui_loot::LootLatch; +use crate::ui_loot::{LootLatch, LootState}; pub(super) fn register(app: &mut App) { app.net_handler(SessionEventKind::InventoryFailure, on_inventory_failure) @@ -56,6 +56,7 @@ fn on_inventory_failure( In(ev): In, mut equip_errors: ResMut, mut latch: ResMut, + mut loot: ResMut, ) { if let SessionEvent::InventoryFailure { reason, @@ -72,6 +73,9 @@ fn on_inventory_failure( bag_slot, }; inventory_failure(failure, &mut equip_errors, &mut latch); + // The tail, after the unlocks: `LOOT_OPENED` again under an open window and a set + // auto-loot byte (`0x5e3aff`-`0x5e3b20`), on the loot lane at the packet's place. + loot.owe_failure_tail(); } } @@ -86,7 +90,8 @@ struct Failure { /// A refused inventory operation (reason 0 never arrives: `benilla_protocol::events` drops it): /// queues the error line, and after it the unlock of both guids the packet names (`0x5e3ac0`, -/// the second only when nonzero, `0x5e3ad3`), on the refusal lane at the packet's place. +/// the second only when nonzero, `0x5e3ad3`), on the refusal lane at the packet's place; the +/// handler then owes the loot tail ([`LootState::owe_failure_tail`]). fn inventory_failure(failure: Failure, equip_errors: &mut EquipErrors, latch: &mut LootLatch) { let Failure { reason, diff --git a/crates/benilla-app/src/ui_loot/call_tests.rs b/crates/benilla-app/src/ui_loot/call_tests.rs index 2fe7f9112..c2276f66e 100644 --- a/crates/benilla-app/src/ui_loot/call_tests.rs +++ b/crates/benilla-app/src/ui_loot/call_tests.rs @@ -796,3 +796,152 @@ fn a_close_and_the_next_response_in_one_frame_keep_their_order() { Some(LOCKBOX) ); } + +/// A removal and the next response in one frame: the removal's `LOOT_SLOT_CLEARED` handlers run +/// inside its own packet (`0x4c1f77`), before the response's copier clears the bind stash +/// (`[0x847cec]`, `0x4c1df5`), so a `LootSlot` there takes the pending row (`0x4c2790(i, 1)`, +/// `0x4c27c0`) and sends it. +#[test] +fn a_replaced_sessions_handlers_read_its_own_bind_stash() { + let mut l = client(); + open( + &mut l, + CORPSE, + 1, + 0, + vec![row(0, FELSTRIKER), row(1, LINEN)], + ); + click(&mut l, 1); + assert_eq!(seen(&mut l), "LOOT_OPENED,LOOT_BIND_CONFIRM:1"); + let _ = sent(&l); + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_SLOT_CLEARED") + f:SetScript("OnEvent", function() LootSlot(1) end)"#, + ); + packets( + &mut l, + vec![ + SessionEvent::LootRemoved { slot: 1 }, + SessionEvent::LootResponse { + guid: CORPSE, + loot_type: 1, + gold: 0, + items: vec![row(0, WOOL)], + }, + ], + ); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:2,LOOT_CLOSED,LOOT_OPENED"); + assert!( + matches!(sent(&l)[..], [ClientCommand::AutostoreLootItem { slot: 0 }]), + "the old session's pending row" + ); +} + +/// A `CloseLoot` in a replaced session's `LOOT_SLOT_CLEARED` handler ends that session alone +/// (`0x48f200`): the next response, a pickpocket window the server starts on a cold target +/// (`0x5eb94b`), still waits on its rows' records and signals `LOOT_OPENED` at the last answer +/// (`0x4c2ac0`, `0x4c2afc`). +#[test] +fn a_replaced_sessions_close_keeps_the_next_copiers_end() { + const UNCACHED: u32 = 40_000; + let mut l = client(); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN), row(1, WOOL)]); + let _ = (seen(&mut l), sent(&l)); + run( + &mut l, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_SLOT_CLEARED") + f:SetScript("OnEvent", function() CloseLoot() end)"#, + ); + packets( + &mut l, + vec![ + SessionEvent::LootRemoved { slot: 0 }, + SessionEvent::LootResponse { + guid: CORPSE, + loot_type: 2, + gold: 0, + items: vec![row(0, UNCACHED)], + }, + ], + ); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_SLOT_CLEARED:1,LOOT_CLOSED"); + assert!( + matches!(sent(&l)[..], [ClientCommand::LootRelease { guid: CORPSE }]), + "the old session's release" + ); + let world = l.app.world_mut(); + world + .resource_mut::() + .insert_template(UNCACHED, Some(crate::items::test_template("Silk Cloth"))); + world.resource_scope(|world, mut loot: Mut| { + loot.row_answered(world.resource::()) + }); + feed(&mut l); + assert_eq!(seen(&mut l), "LOOT_OPENED"); +} + +/// An inventory failure ends by signalling `LOOT_OPENED` again while a window is open +/// (`0xb71b48`) and the auto-loot byte is set (`0x5e3aff`-`0x5e3b20`): a window whose copier +/// waits on a row's record keeps the byte its interaction stored (`0x4c1ea6`, before the sweep's +/// clear at `0x4c2219`). With the byte clear the failure signals no loot event. +#[test] +fn an_inventory_failure_signals_the_window_again_under_the_byte() { + for byte in [true, false] { + let mut l = client(); + l.app.world_mut().resource_mut::().0 = byte; + run(&mut l, "ERR_INV_FULL = 'ERR_INV_FULL'"); + open(&mut l, CORPSE, 1, 0, vec![row(0, LINEN), row(1, 40_000)]); + assert_eq!(seen(&mut l), "", "the copier waits on its record"); + packets( + &mut l, + vec![SessionEvent::InventoryFailure { + reason: 50, + required_level: None, + item_guid: 0, + item2_guid: 0, + bag_slot: 0, + }], + ); + crate::lanes::fire_in_order(l.app.world_mut()); + let seen = seen(&mut l); + assert!(seen.starts_with("UI_ERROR_MESSAGE"), "{seen}"); + assert_eq!(seen.ends_with(",LOOT_OPENED"), byte, "byte {byte}: {seen}"); + } +} + +/// The failure's tail reads whether a window is open at its own packet (`0x5e3af3`-`0x5e3aff`): +/// a response later in the same drain opens its window after it, so the tail signals nothing, +/// though the byte is set and that window's copier waits on its record. +#[test] +fn an_inventory_failure_reads_the_window_at_its_own_packet() { + let mut l = client(); + run(&mut l, "ERR_INV_FULL = 'ERR_INV_FULL'"); + l.app.world_mut().resource_mut::().0 = true; + l.app.world_mut().resource_mut::().0 = Some(CORPSE); + packets( + &mut l, + vec![ + SessionEvent::InventoryFailure { + reason: 50, + required_level: None, + item_guid: 0, + item2_guid: 0, + bag_slot: 0, + }, + SessionEvent::LootResponse { + guid: CORPSE, + loot_type: 1, + gold: 0, + items: vec![row(0, 40_000)], + }, + ], + ); + crate::lanes::fire_in_order(l.app.world_mut()); + assert_eq!(seen(&mut l), "UI_ERROR_MESSAGE:ERR_INV_FULL"); + assert!(l.app.world().resource::().0, "no sweep ran"); +} diff --git a/crates/benilla-app/src/ui_loot/mod.rs b/crates/benilla-app/src/ui_loot/mod.rs index 28e6ea515..0fe8cc63f 100644 --- a/crates/benilla-app/src/ui_loot/mod.rs +++ b/crates/benilla-app/src/ui_loot/mod.rs @@ -203,6 +203,19 @@ impl Window { } } +/// The cells a response's handler writes over before its copier runs, as the session it replaces +/// left them: the latch (`0x5ebb60`), the bind stash (`[0x847cec]`, `0x4c1df5`) and whether a +/// copier's end waits on records (`0x4c1e77`). The steps that session's packets queued ahead of +/// the response run on these, as each packet's dispatch ran them before the response arrived. +/// The auto-loot byte is none of them: only `SetAutoLoot` writes it (`0x5df468`), never a +/// response, so every step reads it live. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Cells { + latch: Option, + stash: Option, + copier_due: bool, +} + /// What a packet did that the VM has yet to hear, in its order on the loot lane: a change to the /// window, with the window it left, or an item push. #[derive(Clone, Debug)] @@ -224,11 +237,16 @@ enum Step { ended: Window, window: Window, ends: Option, + prior: Cells, }, /// The copier's end a response's pending records held, run by the cache callback at the last /// answer (`0x4c2ac0`, `0x4c2afc`), on its own session's window: a later response in the /// frame replaced the live cells. CopierEnd(Window), + /// An inventory failure's tail (`0x5e3af3`-`0x5e3b20`): `LOOT_OPENED` again while a window + /// is open (`0xb71b48`, as the failure's packet found it: `window_open`) and the active + /// player's auto-loot byte is set, read at the failure's place. + FailureTail { window_open: bool }, /// The sweep a close with no VM owed a disenchant window with rows left (`0x48f264` → /// `0x4c1fa0`). Sweep, @@ -292,6 +310,11 @@ impl LootState { source: None, ..self.window.clone() }; + let prior = Cells { + latch: self.window.source, + stash: self.pending_bind_confirm, + copier_due: self.copier_due, + }; self.window = Window { source: Some(source), gold, @@ -308,9 +331,34 @@ impl LootState { ended, window: self.window.clone(), ends: None, + prior, }); } + /// The latch as it stood before the response's handler wrote it (`0x5ebb60`), for the steps + /// of the session it replaces. + pub(crate) fn note_replaced_latch(&mut self, latch: Option) { + if let Some(prior) = self.replaced_cells_from_back() { + prior.latch = latch; + } + } + + /// The last queued response's cells, the one a handler just queued. + fn replaced_cells_from_back(&mut self) -> Option<&mut Cells> { + self.steps.iter_mut().rev().find_map(|(_, s)| match s { + Step::Opened { prior, .. } => Some(prior), + _ => None, + }) + } + + /// The first queued response's cells: those of the session the steps ahead of it belong to. + fn replaced_cells(&mut self) -> Option<&mut Cells> { + self.steps.iter_mut().find_map(|(_, s)| match s { + Step::Opened { prior, .. } => Some(prior), + _ => None, + }) + } + /// The copier's asks at its packet (`0x4c1e77`): each row's record looked up with the callback /// `0x4c2ac0`, the copier returning with any outstanding (`0x4c1ea6`), so its end waits for /// the last answer ([`Step::CopierEnd`]) whatever lands before the lane fires it; with none @@ -611,6 +659,14 @@ impl LootState { }) } + /// Owe an inventory failure's tail to the lane, behind its line and unlocks, with whether a + /// window is open at the failure's packet (`0x5e3aff`). + pub(crate) fn owe_failure_tail(&mut self) { + self.queue(Step::FailureTail { + window_open: self.window.source.is_some(), + }); + } + /// Owe the hold's sweep to the lane, from a close with no VM at hand. pub(crate) fn owe_sweep(&mut self) { self.sweep_owed = true; @@ -1234,20 +1290,23 @@ fn fire_step(vm: &mut LootVm, reads: &LootReads, step: Step) { ended, window: w, ends, + prior, } => { let replaced = vm.own().0.loot.replaced(); // 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`). + // window (`0x48f23f`). The stash is the ended session's until the clear after them + // (`0x4c1df5`); the latch is already the response's (`0x5ebb60`). let live = swap_in_cells(vm, ended); + vm.own().0.loot.pending_bind_confirm = prior.stash; vm.turn(|script, _| { if let Some(script) = script.filter(|s| s.shown_loot().is_some()) { show(script, None); } }); - restore_live(vm, live); vm.own().0.loot.pending_bind_confirm = None; + restore_live(vm, live); let ends = vm.turn(|script, (mut steps, _)| { let Some(script) = script else { return false; @@ -1275,6 +1334,12 @@ fn fire_step(vm: &mut LootVm, reads: &LootReads, step: Step) { end_session_open(vm, w, replaced); } } + Step::FailureTail { window_open } => vm.turn(|script, (steps, _)| { + let open = window_open && steps.objects.player().is_some(); + if let (Some(script), true) = (script, open && steps.byte.0) { + script.fire_event("LOOT_OPENED", vec![]); + } + }), Step::Sweep => { if !vm.own().0.loot.sweep_owed { return; @@ -1361,9 +1426,13 @@ fn end_superseded_open( struct Live { window: Window, mark: crate::lanes::Mark, + /// The replaced session's other cells were swapped in ([`exchange_replaced_cells`]). + cells: bool, } -/// Put `cells`, the loot cells as a step left them, in the window's place for that step's turn. +/// Put `cells`, the loot window as a step left it, in the window's place for that step's turn, +/// and, for a session a later response replaced, the latch, the stash and the copier's wait it +/// left ([`Cells`]). fn swap_in_cells( vm: &mut VmWith<(LootSteps<'static, 'static>, X)>, cells: Window, @@ -1372,10 +1441,27 @@ fn swap_in_cells( Live { window: std::mem::replace(&mut s.loot.window, cells), mark: crate::lanes::mark(), + cells: exchange_replaced_cells(&mut s), } } -/// Put the live window back: the later copier rewrote every cell (`0x4c1dc2` on), so what the +/// Exchange the live [`Cells`] with those the first queued response holds for the session it +/// replaces; run twice it puts the live ones back and keeps what the turn left in the replaced +/// session's, for its next step. Whether a response is queued. +fn exchange_replaced_cells(s: &mut LootSteps) -> bool { + let Some(mut cells) = s.loot.replaced_cells().copied() else { + return false; + }; + std::mem::swap(&mut s.latch.0, &mut cells.latch); + std::mem::swap(&mut s.loot.pending_bind_confirm, &mut cells.stash); + std::mem::swap(&mut s.loot.copier_due, &mut cells.copier_due); + if let Some(prior) = s.loot.replaced_cells() { + *prior = cells; + } + true +} + +/// Put the live cells 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)>, @@ -1383,6 +1469,9 @@ fn restore_live( ) { let (mut s, _) = vm.own(); s.loot.window = live.window; + if live.cells { + exchange_replaced_cells(&mut s); + } s.loot.steps.retain(|(stamp, _)| !stamp.since(live.mark)); } diff --git a/crates/benilla-app/src/ui_loot/net.rs b/crates/benilla-app/src/ui_loot/net.rs index 2c721a568..cb30186d6 100644 --- a/crates/benilla-app/src/ui_loot/net.rs +++ b/crates/benilla-app/src/ui_loot/net.rs @@ -68,6 +68,7 @@ fn on_response( return; } // A fishing bobber first arms here and still does not kneel: `LootKneel` decides the pose. + let latch_before = seam.loot_latch.0; seam.loot_latch.0 = Some(guid); debug!( "net: loot response {guid:#x} type {loot_type} gold {gold} {} item(s)", @@ -76,6 +77,7 @@ fn on_response( select.select_unit(guid); let seam = &mut select.seam; seam.loot.open(guid, loot_type, gold, rows); + seam.loot.note_replaced_latch(latch_before); seam.loot.ask_rows(&items, &seam.net); if player.is_some_and(|p| { p.foreign_mover.is_none() diff --git a/crates/benilla-app/src/ui_script/death_tests.rs b/crates/benilla-app/src/ui_script/death_tests.rs index 0c5b0b927..e633f4bcd 100644 --- a/crates/benilla-app/src/ui_script/death_tests.rs +++ b/crates/benilla-app/src/ui_script/death_tests.rs @@ -459,3 +459,43 @@ fn corpse_map_position_binding() { assert!((x - 0.25).abs() < 1e-6 && (y - 0.75).abs() < 1e-6); assert!(s.errors().is_empty(), "script errors: {:?}", s.errors()); } + +/// Both timers answer whole seconds: the release timer truncates its milliseconds by a signed +/// divide (`0x48b5ae`-`0x48b5bd`), the reclaim delay floors them by an unsigned one +/// (`0x48b5f0`-`0x48b5f7`). +#[test] +fn the_death_timers_answer_whole_seconds() { + let mut s = UiScript::new().unwrap(); + s.set_death(DeathUiState { + release_remaining: Some(299.7), + recovery_delay: 0.4, + ..Default::default() + }); + assert_eq!( + s.eval::("return GetReleaseTimeRemaining()").unwrap(), + 299.0 + ); + assert_eq!( + s.eval::("return GetCorpseRecoveryDelay()").unwrap(), + 0.0 + ); + s.set_death(DeathUiState { + release_remaining: Some(0.4), + recovery_delay: 1.6, + ..Default::default() + }); + assert_eq!( + s.eval::("return GetReleaseTimeRemaining()").unwrap(), + 0.0 + ); + assert_eq!( + s.eval::("return GetCorpseRecoveryDelay()").unwrap(), + 1.0 + ); + // No timer: `0x4962a0` answers -1000 ms, which the signed divide keeps as -1. + s.set_death(DeathUiState::default()); + assert_eq!( + s.eval::("return GetReleaseTimeRemaining()").unwrap(), + -1.0 + ); +} diff --git a/crates/benilla-app/src/ui_script/verb_event_gate.rs b/crates/benilla-app/src/ui_script/verb_event_gate.rs index d3d280fc3..069836e9b 100644 --- a/crates/benilla-app/src/ui_script/verb_event_gate.rs +++ b/crates/benilla-app/src/ui_script/verb_event_gate.rs @@ -23,20 +23,6 @@ const ELSEWHERE: &[(&str, &str, &str)] = &[]; /// Pairs nothing fires on the verb's path, each with its reason. const GAP: &[(&str, &str, &str)] = &[ - ( - "CollapseCraftSkillLine", - "CRAFT_UPDATE", - "the reference commits through the 21-byte thunk 0x4f6be0 (the trainer's 0x4d8c90 shape); \ - a no-op here because the craft list is flat — the header law was never ported from \ - TradeSkill — so there is nothing to repaint. Whether any 1.12 \ - craft list carries more than one group is not established: Enchanting's does not, \ - Beast Training is unchecked", - ), - ( - "ExpandCraftSkillLine", - "CRAFT_UPDATE", - "the same thunk and the same no-op as CollapseCraftSkillLine", - ), ( "SelectGossipOption", "GOSSIP_ENTER_CODE", diff --git a/crates/benilla-app/src/ui_tooltip/tests.rs b/crates/benilla-app/src/ui_tooltip/tests.rs index f13892d72..c4c22c7c8 100644 --- a/crates/benilla-app/src/ui_tooltip/tests.rs +++ b/crates/benilla-app/src/ui_tooltip/tests.rs @@ -1662,6 +1662,7 @@ fn the_feed_pushes_the_spells_the_vm_holds_before_a_hover() { reagents: vec![], tools: vec![], spell_level: 0, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, diff --git a/crates/benilla-app/src/ui_tradeskill.rs b/crates/benilla-app/src/ui_tradeskill.rs index 0cbbdd0dc..d30fb00ce 100644 --- a/crates/benilla-app/src/ui_tradeskill.rs +++ b/crates/benilla-app/src/ui_tradeskill.rs @@ -39,8 +39,9 @@ use benilla_assets::{AssetSet, LockRecover, WorldAssets}; #[derive(Resource, Default)] pub(crate) struct TradeSkillOpens(pub(crate) Vec); -/// The open book's skill line. The Lua close and the session end clear it: a logout replaces the -/// VM without running the old `OnHide`, so the close alone never comes. +/// The open book's skill line (`[0xbde040]`). An opener of it, the Lua close and the session end +/// clear it: a logout replaces the VM without running the old `OnHide`, so the close alone never +/// comes. A `/reload` keeps it. #[derive(Resource, Default)] pub(crate) struct TradeSkillOpen { pub(crate) line: Option, @@ -88,6 +89,17 @@ pub(crate) fn reset_crafts_on_world_enter( }) } +/// The craft init's type write (`0x4f5ee0` zeroes `[0xbdcfb8]`) on each cascade, with no event: +/// the window is closed under the VM that survives a worldport and under a reload's new one. +pub(crate) fn close_craft_on_world_enter( + mut cascades: MessageReader, + mut craft_open: ResMut, +) { + if cascades.read().count() > 0 { + craft_open.line = None; + } +} + /// `SpellFocusObject.dbc`, the names on a "Requires: Anvil" line. #[derive(Resource)] pub(crate) struct SpellFocus { @@ -116,7 +128,9 @@ impl Plugin for UiTradeSkillPlugin { feed_trade_skill.in_set(UnitFeed), drain_trade_skill.in_set(crate::ui_script::UiDrain), // In the feed phase, ahead of every feed that pushes the lists. - reset_crafts_on_world_enter.in_set(crate::ui_script::UiFeed), + (reset_crafts_on_world_enter, close_craft_on_world_enter) + .in_set(crate::ui_script::UiFeed) + .before(UnitFeed), ), ); } @@ -152,8 +166,10 @@ fn load_spell_focus(mut commands: Commands, assets: Option>) { } } -/// Open the book for each intercepted opener: its line is the opener's `SkillLineAbility` row -/// (3908 Tailoring is line 197), the client's `SkillLineRecIndex_Find` (`0x6de040`). +/// Toggle the book for each intercepted opener (`0x4fc910`, `0x4f6000`): its line is the opener's +/// `SkillLineAbility` row (3908 Tailoring is line 197), the client's `SkillLineRecIndex_Find` +/// (`0x6de040`). The open line's opener closes it (`0x4fc918`), the open craft type's its window +/// (`0x4f6006`); any other opens. fn open_trade_skill( mut opens: ResMut, mut open: ResMut, @@ -179,11 +195,19 @@ fn open_trade_skill( .and_then(|d| u32::try_from(d.effect_misc_value[0]).ok()) .unwrap_or(0); if craft_type != 0 { - debug!( - "ui_tradeskill: opener {spell_id} opens the CraftFrame (line {line}, craft type {craft_type})" - ); - craft_open.line = Some(line); - craft_open.craft_type = craft_type; + if craft_open.line.is_some() && craft_open.craft_type == craft_type { + debug!("ui_tradeskill: opener {spell_id} closes the CraftFrame"); + craft_open.line = None; + } else { + debug!( + "ui_tradeskill: opener {spell_id} opens the CraftFrame (line {line}, craft type {craft_type})" + ); + craft_open.line = Some(line); + craft_open.craft_type = craft_type; + } + } else if open.line == Some(line) { + debug!("ui_tradeskill: opener {spell_id} closes skill line {line}"); + open.line = None; } else { debug!("ui_tradeskill: opener {spell_id} opens skill line {line}"); open.line = Some(line); @@ -593,6 +617,7 @@ fn feed_trade_skill( commands: Res, clock: Res, mut memo: Local>, + mut engine: Local, ) { vm.feed(|script, cooldowns, fires| { let Some(script) = script else { @@ -655,19 +680,28 @@ fn feed_trade_skill( }) })(); + // The line stays open while a frame cannot resolve its book (a worldport's purge of our + // own player): only a close ends it (`0x4fc870`, `0x4fc920`). + let fresh = match fresh { + None if open.line.is_some() => memo.state.clone(), + f => f, + }; // `CloseTradeSkill` closes the VM's window and signals `TRADE_SKILL_CLOSE` in the verb // (`0x4fc884`). let closed_in_place = !script.trade_skill_open(); // The getters' item callbacks, kept by their calls; each record that landed rebuilds // (`0x4fdc30` → `0x4fdc3c`), and a refusal runs it with status 0, which does nothing - // (`0x4fdc38`). - memo.item_waits.extend(script.take_trade_skill_item_waits()); - let arrivals = landed(&mut memo.item_waits, &items); - let opened = match (&memo.state, &fresh) { - (None, Some(_)) => true, - (Some(l), Some(f)) => l.line != f.line, - _ => false, - }; + // (`0x4fdc38`). The item cache holds them, so they outlive a VM. + engine + .item_waits + .extend(script.take_trade_skill_item_waits()); + let arrivals = landed(&mut engine.item_waits, &items); + // An open is the open line's change, which a `/reload` keeps (`[0xbde040]`): the new VM + // takes the list with no event, as its world-enter init left it. + let opened = fresh.as_ref().is_some_and(|f| engine.shown != Some(f.line)); + if fresh.is_some() || open.line.is_none() { + engine.shown = fresh.as_ref().map(|f| f.line); + } // Every push is silent: the rebuilds signal, and the getters read the state at their call. if fresh != memo.state { script.set_trade_skill(fresh.clone()); @@ -708,9 +742,10 @@ fn feed_trade_skill( } // Each product record a build waited on runs its callback as it lands (`0x4fc8e0`), // which rebuilds with flag 1 once nothing is pending. - memo.build_waits + engine + .build_waits .extend(script.take_trade_skill_build_waits()); - let built = landed(&mut memo.build_waits, &items); + let built = landed(&mut engine.build_waits, &items); for _ in 0..built { if script.trade_skill_record_landed() && script.rebuild_trade_skill_with(true, &mut |_| {}) @@ -722,14 +757,23 @@ fn feed_trade_skill( }) } -/// What [`feed_trade_skill`] remembers from its last frame. +/// What [`feed_trade_skill`] remembers from its last frame, per VM. #[derive(Default)] struct TradeMemo { /// The state it last pushed. state: Option, - /// The item records the getters' calls wait on, one per call. +} + +/// What [`feed_trade_skill`] keeps across VMs, as the engine does across a `/reload`. +#[derive(Default)] +struct TradeEngine { + /// The line whose open it signalled; a frame that finds no line open clears it, so the next + /// session's first open signals again. + shown: Option, + /// The item records the getters' callbacks wait on in the item cache, one per call + /// (`0x4fdc30`), which no cancel removes (`0x4fc890`). item_waits: Vec, - /// The product records the builds wait on, one per miss. + /// The product records the builds' callbacks wait on, one per miss (`0x4fc8e0`). build_waits: Vec, } @@ -1906,4 +1950,179 @@ mod tests { assert_eq!(app.world().resource::().line, None); } + + /// The Bolt of Silk Cloth book behind the Tailoring opener 3908, its product's record in + /// flight, fed and opened as the client runs them; each VM installed through [`listening`]. + fn silk_book() -> App { + const SILK: u32 = 4305; + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + actions.spells.extend([3839, 3908]); + actions.profession_order.push(3839); + let mut effect_item_type = [0; 3]; + effect_item_type[0] = SILK; + let bolt = SpellDisplay { + name: "Bolt of Silk Cloth".into(), + attributes: SPELL_ATTR_IS_TRADESKILL, + effects: [SPELL_EFFECT_CREATE_ITEM, 0, 0], + effect_item_type, + ..Default::default() + }; + let opener = SpellDisplay { + name: "Tailoring".into(), + effects: [benilla_formats::SPELL_EFFECT_TRADE_SKILL, 0, 0], + ..Default::default() + }; + let sla = benilla_formats::SlaInfo { + skill_id: 197, + req_skill_value: 1, + forward_spell_id: 0, + trivial_low: 1, + trivial_high: 2, + }; + app.init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(actions) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(crate::net::NetCommands(tx)) + .insert_resource(Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [(3839, bolt), (3908, opener)].into_iter().collect(), + ), + ..Spells::empty_for_tests() + }) + .insert_resource(SkillLines { + catalog: benilla_formats::SkillLineCatalog::from_abilities([ + (3839, sla), + (3908, sla), + ]), + }); + app.world_mut() + .spawn((ObjectStore(Default::default()), SelfPlayer)); + app.insert_non_send_resource(listening()); + app.add_systems(Update, (open_trade_skill, feed_trade_skill).chain()); + app + } + + /// A VM that records the book's three events. + fn listening() -> UiScript { + let script = UiScript::new().unwrap(); + script + .run( + "HEARD = {} local f = CreateFrame('Frame') f:RegisterEvent('TRADE_SKILL_SHOW') \ + f:RegisterEvent('TRADE_SKILL_UPDATE') f:RegisterEvent('TRADE_SKILL_CLOSE') \ + f:SetScript('OnEvent', function() table.insert(HEARD, event) end)", + ) + .unwrap(); + script + } + + /// One frame, and what the VM heard in it. + fn heard(app: &mut App) -> Vec { + app.update(); + app.world() + .non_send_resource::() + .eval::>("local h = HEARD HEARD = {} return h") + .unwrap() + } + + /// A `/reload` (`0x490bd0`): the leave sweep zeroes the pending count (`0x4fc8cb`), a new VM + /// replaces the old, and the world-enter init zeroes the list (`0x4fc750` at `0x4909bf`). + fn reload(app: &mut App) { + let mut old = app.world_mut().non_send_resource_mut::(); + old.trade_skill_cancel_waits(); + let mut script = listening(); + script.reset_crafts_on_world_enter(); + app.insert_non_send_resource(script); + } + + /// A `/reload` with the book open keeps its line (`[0xbde040]`) and signals nothing, so the + /// new interface shows no window and reads an empty list under the line. The product record + /// the old build waited on still runs its callback (`0x4fc8e0`), whose rebuild signals the + /// update into the new interface (`0x4fc900`). + #[test] + fn a_reload_keeps_the_book_open_unshown_until_a_rebuild() { + let mut app = silk_book(); + app.world_mut() + .resource_mut::() + .0 + .push(3908); + assert_eq!(heard(&mut app), ["TRADE_SKILL_SHOW"]); + reload(&mut app); + assert!(heard(&mut app).is_empty(), "no update, no show"); + let script = app.world().non_send_resource::(); + assert_eq!( + script + .eval::<(i64, String)>("return GetNumTradeSkills(), (GetTradeSkillLine())") + .unwrap(), + (0, "Skill 197".into()) + ); + app.world_mut().resource_mut::().insert_template( + 4305, + Some(crate::items::test_template("Bolt of Silk Cloth")), + ); + assert_eq!(heard(&mut app), ["TRADE_SKILL_UPDATE"]); + assert!( + app.world() + .non_send_resource::() + .eval::("return GetNumTradeSkills()") + .unwrap() + > 0 + ); + } + + /// An opener toggles the book (`0x4fc910`): the open line's opener closes it with + /// `TRADE_SKILL_CLOSE` (`0x4fc918`-`0x4fc930`), and the next opens it again. After a reload + /// the line is still open, so the first opener closes the unshown book and the second shows it. + #[test] + fn an_opener_of_the_open_line_closes_the_book() { + let mut app = silk_book(); + let open = |app: &mut App| { + app.world_mut() + .resource_mut::() + .0 + .push(3908); + heard(app) + }; + assert_eq!(open(&mut app), ["TRADE_SKILL_SHOW"]); + assert_eq!(open(&mut app), ["TRADE_SKILL_CLOSE"]); + assert_eq!(app.world().resource::().line, None); + assert_eq!(open(&mut app), ["TRADE_SKILL_SHOW"]); + reload(&mut app); + assert!(heard(&mut app).is_empty()); + assert_eq!(open(&mut app), ["TRADE_SKILL_CLOSE"]); + assert_eq!(open(&mut app), ["TRADE_SKILL_SHOW"]); + } + + /// A frame that cannot resolve the book while its line stays open, as a worldport's purge of + /// our own player leaves it, closes nothing: only a close ends the line (`0x4fc870`, + /// `0x4fc920`), and the player's return signals no second open. + #[test] + fn a_frame_without_our_player_keeps_the_book_open() { + let mut app = silk_book(); + app.world_mut() + .resource_mut::() + .0 + .push(3908); + assert_eq!(heard(&mut app), ["TRADE_SKILL_SHOW"]); + let me = app + .world_mut() + .query_filtered::>() + .single(app.world()) + .unwrap(); + app.world_mut().despawn(me); + assert!(heard(&mut app).is_empty(), "no close"); + app.world_mut() + .spawn((ObjectStore(Default::default()), SelfPlayer)); + assert!(heard(&mut app).is_empty(), "no second open"); + assert!(app + .world() + .non_send_resource::() + .trade_skill_open()); + } } diff --git a/crates/benilla-app/tests/tradeskill_frame.rs b/crates/benilla-app/tests/tradeskill_frame.rs index 58d63bba0..5b9d96bdb 100644 --- a/crates/benilla-app/tests/tradeskill_frame.rs +++ b/crates/benilla-app/tests/tradeskill_frame.rs @@ -538,6 +538,7 @@ fn a_hovered_or_selected_craft_row_paints_its_label_white() { tools: vec![], tooltip: CraftTooltip::Spell(spell_id), spell_level: 0, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, diff --git a/crates/benilla-ui/src/script/craft.rs b/crates/benilla-ui/src/script/craft.rs index 9091f2b5c..e2fbb9a6d 100644 --- a/crates/benilla-ui/src/script/craft.rs +++ b/crates/benilla-ui/src/script/craft.rs @@ -3,11 +3,11 @@ //! window has one action button, `DoCraft(GetCraftSelectionIndex())` (`Blizzard_CraftUI.xml:667`), //! and no Create All, so a craft intent is a bare spell id. //! -//! Not built: the reference's header rows (`0x4f60c0`). The list is flat, `GetCraftInfo` never -//! answers `"header"` and `Expand`/`CollapseCraftSkillLine` do nothing; Enchanting, with a single -//! group, renders flat in the reference too. +//! The engine owns the row array (`0x4f60c0`): the recipes in the list's learn order, then a +//! header row per group once there are two, sorted by the craft type's comparator; every Lua +//! index is 1-based into that whole array, the displayed rows first ([`recipe`]). -use mlua::{Lua, MultiValue, Value, Variadic}; +use mlua::{Lua, MultiValue, Value}; use super::binding_abi::{self, number_arg}; use super::item_stats::item_link; @@ -122,8 +122,11 @@ pub struct CraftRecipe { /// `Spell.dbc` `spellLevel` (`+0x74`), the Beast Training comparator's rank key. The /// `requiredLevel` return reads the learned spell's instead (`0x4f705f` → `0x60c840`). pub spell_level: u32, - /// The name of the recipe's group key, the skill line of the spell's ability (row `+0x04`, - /// `0x4f61b1`), for `GetCraftSkillLine`; `None` when `SkillLine.dbc` has no such row. + /// The recipe's group key (row `+0x04`): the skill line of the spell's ability (`0x4f61b1`), + /// 0 with none (`0x4f61b6`). + pub group: u32, + /// The name of [`Self::group`], for `GetCraftSkillLine` and the header row; `None` when + /// `SkillLine.dbc` has no such row. pub skill_line: Option, /// `GetCraftInfo`'s sixth value, the training-point cost (`0x4f7078`). pub training_point_cost: u32, @@ -157,34 +160,191 @@ const CRAFT_TYPE_BEAST_TRAINING: u32 = 1; /// Enchanting's craft type, the one `GetCraftDisplaySkillLine` answers for (`0x4f6ce3`). const CRAFT_TYPE_ENCHANTING: u32 = 3; -/// The craft row order: difficulty tier (`[+0xc]`) ascending, then name (collator `0x64a4c0`), -/// then, at Beast Training only (`0x4f6920`; every other type uses `0x4f67a0`), `spellLevel` -/// ascending, which orders a pet ability's ranks. +/// One row of the array (`0xbdcf78`): a header (spell id -1, `0x4f65c5`) keyed by its group, or +/// a recipe's position in [`CraftState::recipes`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Row { + Header { group: u32 }, + Recipe(usize), +} + +/// One header of the array (`0xbdcf88`): its group key, the group's name, its member count +/// (`+4`) and whether it is collapsed (`+8`). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Header { + group: u32, + name: Option, + members: u32, + collapsed: bool, +} + +/// `0x4f6ac0`: the same key ties; a key with no `SkillLine.dbc` row ties (`0x4f6b03`); else the +/// names, case-blind (`0x64a4c0`). +fn header_order(a: &Header, b: &Header) -> i32 { + if a.group == b.group { + return 0; + } + match (&a.name, &b.name) { + (Some(x), Some(y)) => crate::crt::str_cmp_i(x, y), + _ => 0, + } +} + +/// The row comparators, `0x4f6920` at Beast Training and `0x4f67a0` at every other type +/// (`0x4f6765`). With headers, each recipe takes its group's position in the header array and is +/// shown unless the group is collapsed; a header row skips the scan (`0x4f67fd`, `0x4f6818`; +/// `0x4f697d`, `0x4f6998`), so it keeps position 0 and shows. Shown rows come first, then by +/// position; then a header ahead of a recipe, and two headers answer 1 (`0x4f68e9`); then the +/// difficulty bucket ascending (`0x4f68ac`), the names case-blind (`0x64a4c0`) and, at Beast +/// Training, `spellLevel` ascending (`0x4f6a5b`). /// /// Deviation: a last `spell_id` key breaks the remaining ties (Charge's six ranks all have /// `spellLevel` 0), because the reference leaves them to its qsort over an array benilla does not /// reproduce; ascending id is ascending rank in every 1.12 pet-ability family. -fn recipe_order(a: &CraftRecipe, b: &CraftRecipe, craft_type: u32) -> std::cmp::Ordering { - a.difficulty - .bucket() - .cmp(&b.difficulty.bucket()) - .then_with(|| collate(&a.name, &b.name)) - .then_with(|| { - if craft_type == CRAFT_TYPE_BEAST_TRAINING { - a.spell_level.cmp(&b.spell_level) - } else { - std::cmp::Ordering::Equal - } - }) - .then_with(|| a.spell_id.cmp(&b.spell_id)) +fn row_order(a: &Row, b: &Row, headers: &[Header], c: &CraftState) -> i32 { + let group = |r: &Row| match *r { + Row::Header { .. } => None, + Row::Recipe(i) => Some(c.recipes[i].group), + }; + let place = |g: Option| { + g.and_then(|g| headers.iter().position(|h| h.group == g)) + .map_or((0, true), |p| (p, !headers[p].collapsed)) + }; + if !headers.is_empty() { + let ((pa, va), (pb, vb)) = (place(group(a)), place(group(b))); + match (va, vb) { + (false, false) => return 0, + (false, true) => return 1, + (true, false) => return -1, + _ if pa != pb => return if pb < pa { 1 } else { -1 }, + _ => {} + } + } + let (ra, rb) = match (*a, *b) { + (Row::Header { .. }, Row::Header { .. }) => return 1, + (Row::Header { .. }, _) => return -1, + (_, Row::Header { .. }) => return 1, + (Row::Recipe(x), Row::Recipe(y)) => (&c.recipes[x], &c.recipes[y]), + }; + let (ba, bb) = (ra.difficulty.bucket(), rb.difficulty.bucket()); + if ba != bb { + return if ba > bb { 1 } else { -1 }; + } + let by_name = crate::crt::str_cmp_i(&ra.name, &rb.name); + if by_name != 0 { + return by_name; + } + let by_level = if c.craft_type == CRAFT_TYPE_BEAST_TRAINING { + ra.spell_level.cmp(&rb.spell_level) + } else { + std::cmp::Ordering::Equal + }; + match by_level.then_with(|| ra.spell_id.cmp(&rb.spell_id)) { + std::cmp::Ordering::Less => -1, + std::cmp::Ordering::Equal => 0, + std::cmp::Ordering::Greater => 1, + } } -/// Approximates the case-insensitive enUS collator the craft comparators call (`0x64a4c0`; the -/// trainer rows use `0x64a480`): case-folded order, raw bytes breaking ties. -fn collate(a: &str, b: &str) -> std::cmp::Ordering { - a.to_lowercase() - .cmp(&b.to_lowercase()) - .then_with(|| a.cmp(b)) +/// The build `0x4f60c0` past its open check: the rows refilled with the recipes in the list's +/// order, one header per group in the order the recipes first name it (`0x4f6404`-`0x4f64cb`), +/// a header row each (`0x4f65ba`-`0x4f65f9`), a single header dropped (`0x4f65fb`), then the +/// recount and sorts. +pub(crate) fn build(model: &mut Model) { + let Some(c) = model.craft.as_ref() else { + clear(model); + return; + }; + let mut headers: Vec
= Vec::new(); + for r in &c.recipes { + if headers.iter().all(|h| h.group != r.group) { + headers.push(Header { + group: r.group, + name: r.skill_line.clone(), + members: 0, + collapsed: false, + }); + } + } + if headers.len() == 1 { + headers.clear(); + } + let mut rows: Vec = (0..c.recipes.len()).map(Row::Recipe).collect(); + rows.extend(headers.iter().map(|h| Row::Header { group: h.group })); + model.craft_rows = rows; + model.craft_headers = headers; + recount(model); +} + +/// The counts a closed window's build zeroes ahead of its open check (`0x4f60d1`-`0x4f60e3`). +fn clear(model: &mut Model) { + model.craft_rows.clear(); + model.craft_headers.clear(); + model.craft_visible = 0; +} + +/// `0x4f6630`: each header's collapse word from its bit by its position as the array stands +/// (`0x4f6650`-`0x4f666d`) and its member count; the displayed count less each row whose group +/// is empty and each recipe of a collapsed group (`0x4f66e1`-`0x4f673a`, a group not found +/// reading header 0); then the CRT `qsort` of the headers (`0x4f6756`) and of the rows +/// (`0x4f6785`) as the last sort left them. +fn recount(model: &mut Model) { + let Some(c) = model.craft.as_ref() else { + clear(model); + return; + }; + let mask = model.craft_fold_mask; + let mut headers = std::mem::take(&mut model.craft_headers); + for (j, h) in headers.iter_mut().enumerate() { + h.collapsed = mask & (1u32 << (j & 31)) == 0; + h.members = 0; + } + let group = |r: &Row| match *r { + Row::Header { group } => group, + Row::Recipe(i) => c.recipes[i].group, + }; + for r in &model.craft_rows { + if let Row::Recipe(_) = r { + for h in headers.iter_mut().filter(|h| h.group == group(r)) { + h.members += 1; + } + } + } + let mut visible = model.craft_rows.len(); + if !headers.is_empty() { + for r in &model.craft_rows { + let h = headers + .iter() + .find(|h| h.group == group(r)) + .unwrap_or(&headers[0]); + if h.members == 0 || (matches!(r, Row::Recipe(_)) && h.collapsed) { + visible -= 1; + } + } + } + crate::crt::qsort(&mut headers, header_order); + let mut rows = std::mem::take(&mut model.craft_rows); + crate::crt::qsort(&mut rows, |a, b| row_order(a, b, &headers, c)); + model.craft_rows = rows; + model.craft_headers = headers; + model.craft_visible = visible; +} + +/// The collapse writer `0x4f6be0`: the mask stored, the recount and sorts (`0x4f6630`), then +/// `CRAFT_UPDATE` in place (`0x4f6bf0`). +fn set_fold_mask(model: &mut Model, mask: u32) { + model.craft_fold_mask = mask; + recount(model); + model.raise("CRAFT_UPDATE", Vec::new()); +} + +/// `0x4f6b30`: a header row's position in the header array, `None` for a recipe row or an index +/// past the rows. +fn header_position(model: &Model, row: usize) -> Option { + match model.craft_rows.get(row)? { + Row::Header { group } => model.craft_headers.iter().position(|h| h.group == *group), + Row::Recipe(_) => None, + } } impl CraftState { @@ -203,42 +363,42 @@ impl CraftState { impl super::UiScript { /// Push the open craft window's snapshot, or mark it closed with `None`, which keeps the - /// list and selection as the reference's close does (`0x4f5fe0`). A push sorts the rows and - /// keeps the selection on its spell id, clearing it when that recipe is gone. + /// list and selection as the reference's close does (`0x4f5fe0`). A push builds the rows + /// (`0x4f60c0`) from the recipes in the list's order; the selection rides its spell id. pub fn set_craft(&mut self, state: Option) { let mut model = self.model_mut(); model.craft_open = state.is_some(); - match state { - None => {} - Some(mut s) => { - let craft_type = s.craft_type; - s.recipes.sort_by(|a, b| recipe_order(a, b, craft_type)); - let prev_spell_id = model - .craft_selection - .checked_sub(1) - .and_then(|i| model.craft.as_ref().and_then(|c| c.recipes.get(i as usize))) - .map(|r| r.spell_id); - model.craft_selection = prev_spell_id - .and_then(|sid| s.recipes.iter().position(|r| r.spell_id == sid)) - .map_or(0, |i| (i + 1) as u32); - model.craft = Some(s); - } + if let Some(s) = state { + model.craft = Some(s); + build(&mut model); } } + /// The open's resets (`0x4f601c`-`0x4f602c`): the selection cleared and every group expanded, + /// then the build (`0x4f6036`). + pub fn craft_opened(&mut self) { + let mut model = self.model_mut(); + model.craft_selection = 0; + model.craft_fold_mask = u32::MAX; + build(&mut model); + } + /// A rebuild of the craft list (`0x4f60c0`), as the bag and item watchers run one on each of /// their runs: while a craft window is open, the state read again where `refresh` brings the - /// watcher's change in; the rows the last push sorted sort the same. Whether the window is - /// open, for the caller's `CRAFT_UPDATE` (`0x4f661a`), signalled whether or not anything - /// changed; a closed window builds nothing (`0x4f60e3`). + /// watcher's change in, and the rows built again. Whether the window is open, for the caller's + /// `CRAFT_UPDATE` (`0x4f661a`), signalled whether or not anything changed; a closed window + /// zeroes the counts and builds nothing (`0x4f60d1`-`0x4f60e3`). pub fn rebuild_craft(&mut self, refresh: &mut dyn FnMut(&mut CraftState)) -> bool { let mut model = self.model_mut(); - if model.craft_open { - if let Some(c) = model.craft.as_mut() { - refresh(c); - } + if !model.craft_open { + clear(&mut model); + return false; } - model.craft_open + if let Some(c) = model.craft.as_mut() { + refresh(c); + } + build(&mut model); + true } /// The item records the getters' calls missed since the last take, one per call. @@ -263,14 +423,26 @@ impl super::UiScript { } } -/// The recipe at a 1-based index. -fn recipe(model: &Model, index: usize) -> Option<&CraftRecipe> { - let n = index.checked_sub(1)?; - model.craft.as_ref()?.recipes.get(n) +/// The recipe at a 1-based index into the whole row array, bounded by the full count +/// (`0xbdcfc0`); `None` on a header, whose spell id -1 finds no record. +pub(crate) fn recipe(model: &Model, index: usize) -> Option<&CraftRecipe> { + match model.craft_rows.get(index.checked_sub(1)?)? { + Row::Recipe(i) => model.craft.as_ref()?.recipes.get(*i), + Row::Header { .. } => None, + } } -fn num_recipes(model: &Model) -> usize { - model.craft.as_ref().map_or(0, |c| c.recipes.len()) +/// The row's group name (`+4`): a recipe's line, or its header's. +fn row_line(model: &Model, row: usize) -> Option<&String> { + match model.craft_rows.get(row)? { + Row::Recipe(i) => model.craft.as_ref()?.recipes.get(*i)?.skill_line.as_ref(), + Row::Header { group } => model + .craft_headers + .iter() + .find(|h| h.group == *group)? + .name + .as_ref(), + } } fn opt_str(lua: &Lua, s: Option<&String>) -> mlua::Result { @@ -299,21 +471,15 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { )?; // GetCraftSkillLine(index) (`0x4f7210`): the name of the skill line in the row's group field - // (`+0x04`), nil for a row outside the list (`dec`, then an unsigned compare against the row - // count, `ds:0xbdcfc0`) or a line `SkillLine.dbc` lacks. The list here is flat: the - // reference's header rows are not built, so an index counts recipes alone. + // (`+0x04`), a header row's included, nil for a row outside the list (`dec`, then an unsigned + // compare against the row count, `ds:0xbdcfc0`) or a line `SkillLine.dbc` lacks. g.set( "GetCraftSkillLine", lua.create_function(|lua, index: Value| { let row = binding_abi::number_arg(lua, index, "Usage: GetCraftSkillLine(index)")? .wrapping_sub(1) as u32; let model = lua.app_data_ref::().expect("model app_data"); - let line = model - .craft - .as_ref() - .and_then(|c| c.recipes.get(row as usize)) - .and_then(|r| r.skill_line.as_ref()); - opt_str(lua, line) + opt_str(lua, row_line(&model, row as usize)) })?, )?; @@ -340,12 +506,12 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { })?, )?; - // GetNumCrafts() → the recipe count, 0 when closed. + // GetNumCrafts() (`0x4f6e70`): the displayed count (`0xbdcfc8`), headers included. g.set( "GetNumCrafts", lua.create_function(|lua, ()| { let model = lua.app_data_ref::().expect("model app_data"); - Ok(num_recipes(&model) as i64) + Ok(model.craft_visible as i64) })?, )?; @@ -400,16 +566,41 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { // GetCraftInfo(index) → craftName, craftSubSpellName, craftType, numAvailable, isExpanded, // trainingPointCost, requiredLevel (`Blizzard_CraftUI.lua:168`); a miss pushes the seven too. - // `isExpanded` is always nil. The cost and the level are the app's, read off the pet bar's - // unit (`0xb714a0`) for the spell a pet-learn effect teaches (`0x4f6fe6`-`0x4f7093`). + // A header row answers its line's name, nil, `header`, 0, 1 while its mask bit by its place + // in the sorted header array is set or nil while clear (`0x4f6f4f` → `0x4f6b80`, `0x4f6bc1`), + // not the collapse word the recount stored before the sort, then 0, 0; a recipe's + // `isExpanded` is nil. The cost and the level are the app's, read off the pet bar's unit + // (`0xb714a0`) for the spell a pet-learn effect teaches (`0x4f6fe6`-`0x4f7093`). g.set( "GetCraftInfo", lua.create_function(|lua, index: Value| { // `is-number` else `Usage: GetCraftInfo(index)` (`0x84d398`, `0x4f6ea9`). let index = binding_abi::index_arg(lua, index, "Usage: GetCraftInfo(index)")?; let model = lua.app_data_ref::().expect("model app_data"); + let header = index.checked_sub(1).and_then(|row| { + header_position(&model, row).and_then(|p| { + let collapsed = model.craft_fold_mask & (1u32 << (p & 31)) == 0; + model.craft_headers[p].name.clone().map(|n| (n, collapsed)) + }) + }); + if let Some((name, collapsed)) = header { + return Ok(MultiValue::from_vec(vec![ + Value::String(lua.create_string(&name)?), + Value::Nil, + Value::String(lua.create_string("header")?), + Value::Integer(0), + if collapsed { + Value::Nil + } else { + Value::Integer(1) + }, + Value::Integer(0), + Value::Integer(0), + ])); + } let Some(r) = recipe(&model, index) else { - // `0x4f70a4`: nil, nil, nil, 0, nil, 0, 0. + // `0x4f70a4`: nil, nil, nil, 0, nil, 0, 0, a header with no `SkillLine.dbc` row + // included (`0x4f6f1a`). return Ok(binding_abi::tuple(&[ None, None, @@ -553,20 +744,16 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { })?, )?; - // SelectCraft(index) / GetCraftSelectionIndex(): the selection, 1-based with 0 for none; an - // out-of-range select clears it, and the getter answers 0 past the recipe count. + // SelectCraft(index) (`0x4f70f0` → `0x4f6050`) stores the row's spell id, 0 for a header or an + // index past the rows; GetCraftSelectionIndex() (`0x4f7130` → `0x4f6080`) answers the + // position of that spell's row plus 1, 0 for none or a spell no row holds. g.set( "SelectCraft", lua.create_function(|lua, index: Value| { // `is-number` else `Usage: SelectCraft(index)` (`0x84d3b4`, `0x4f7101`). let index = binding_abi::index_arg32(lua, index, "Usage: SelectCraft(index)")?; let mut model = lua.app_data_mut::().expect("model app_data"); - let count = num_recipes(&model) as u32; - model.craft_selection = if index >= 1 && index <= count { - index - } else { - 0 - }; + model.craft_selection = recipe(&model, index as usize).map_or(0, |r| r.spell_id); Ok(()) })?, )?; @@ -574,9 +761,14 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { "GetCraftSelectionIndex", lua.create_function(|lua, ()| { let model = lua.app_data_ref::().expect("model app_data"); - let count = num_recipes(&model) as u32; let sel = model.craft_selection; - Ok(i64::from(if sel >= 1 && sel <= count { sel } else { 0 })) + let at = (sel != 0) + .then(|| { + (1..=model.craft_rows.len()) + .find(|&i| recipe(&model, i).is_some_and(|r| r.spell_id == sel)) + }) + .flatten(); + Ok(at.unwrap_or(0) as i64) })?, )?; @@ -615,19 +807,52 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { })?, )?; - // Expand/CollapseCraftSkillLine(index): no-ops over the flat list (module doc). + // Expand/CollapseCraftSkillLine(index) (`0x4f7c90`, `0x4f7c10`): an index of 0 or below + // expands or collapses every group (`0x4f7cc7`, `0x4f7c47`); else the row must be a header + // (`0x4f6b30`), whose bit by its array position is set or cleared (`0x4f7cf2`, `0x4f7c71`), + // and any other row raises. Each write re-sorts and signals `CRAFT_UPDATE` (`0x4f6be0`). g.set( "ExpandCraftSkillLine", - lua.create_function(|_, _args: Variadic| Ok(()))?, + lua.create_function(|lua, index: Value| { + // `is-number` else `Usage: ExpandCraftSkillLine(index)` (`0x84d5a0`, `0x4f7ca1`). + let index = number_arg(lua, index, "Usage: ExpandCraftSkillLine(index)")?; + fold(lua, index, false, "Bad skill line in ExpandCraftSkillLine") + })?, )?; g.set( "CollapseCraftSkillLine", - lua.create_function(|_, _args: Variadic| Ok(()))?, + lua.create_function(|lua, index: Value| { + // `is-number` else `Usage: CollapseCraftSkillLine(index)` (`0x84d550`, `0x4f7c21`). + let index = number_arg(lua, index, "Usage: CollapseCraftSkillLine(index)")?; + fold(lua, index, true, "Bad skill line in CollapseCraftSkillLine") + })?, )?; Ok(()) } +/// A fold verb past its usage check: every group for an index of 0 or below, else the header +/// row's bit, or the verb's `bad` line with nothing touched (`0x4f7c5b`, `0x4f7cdc`). +fn fold(lua: &Lua, index: i32, collapse: bool, bad: &'static str) -> mlua::Result<()> { + super::tick::verb(lua, |model| { + let mask = match index.checked_sub(1).filter(|&row| row >= 0) { + None if collapse => 0, + None => u32::MAX, + Some(row) => { + let bit = 1u32 << (header_position(model, row as usize)? & 31); + if collapse { + model.craft_fold_mask & !bit + } else { + model.craft_fold_mask | bit + } + } + }; + set_fold_mask(model, mask); + Some(()) + }) + .ok_or_else(|| mlua::Error::RuntimeError(bad.into())) +} + #[cfg(test)] mod tests { use super::*; @@ -658,6 +883,7 @@ mod tests { }], tools: vec![("Runed Copper Rod".into(), true)], spell_level: 0, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, @@ -863,12 +1089,216 @@ mod tests { assert!(s .eval::("local _,_,t = GetCraftInfo(1) return t ~= 'header'") .unwrap()); - // Expand and collapse do nothing. - s.run("ExpandCraftSkillLine(1) CollapseCraftSkillLine(1)") - .unwrap(); + // One group builds no header (`0x4f65fb`), so no row folds. + assert!(s.run("CollapseCraftSkillLine(1)").is_err()); assert_eq!(s.eval::("return GetNumCrafts()").unwrap(), 2); } + /// Made-up two-group data for the header mechanism, not a real list: no shipped craft list + /// holds two groups (every learnable Beast Training spell has a line-261 row, so the real one + /// shows a single group and no header). Three rows in line 261 and one in group 0, whose line + /// has no `SkillLine.dbc` row; the names and ids are labels only. + fn two_groups() -> CraftState { + let row = |spell_id: u32, name: &str, group: u32| { + let mut r = recipe(spell_id, name, CraftDifficulty::None, 0); + r.group = group; + r.skill_line = (group != 0).then(|| "Beast Training".to_string()); + r + }; + CraftState { + name: "Beast Training".into(), + display_line: None, + rank: 0, + max_rank: 0, + craft_type: CRAFT_TYPE_BEAST_TRAINING, + recipes: vec![ + row(2649, "Growl", 261), + row(24604, "Furious Howl", 0), + row(1742, "Cower", 261), + row(4187, "Great Stamina", 261), + ], + } + } + + /// `isExpanded` reads the mask bit at the header's place in the array after the sort + /// (`0x4f6f4f` → `0x4f6b80`, `0x4f6bc1`), where the displayed rows follow the collapse words + /// the recount set before it (`0x4f6650` ahead of `0x4f6756`). A rebuild remakes the headers + /// in the order the recipes name them (`0x4f6404`), so one whose sort moves a header reads + /// the folded bit on the other group: the rows hide one group, the flag names the other. + #[test] + fn a_headers_expanded_flag_reads_its_bit_after_the_sort() { + let row = |spell_id: u32, name: &str, group: u32, line: &str| { + let mut r = recipe(spell_id, name, CraftDifficulty::None, 0); + r.group = group; + r.skill_line = Some(line.to_string()); + r + }; + // Made-up data: Zeta named first, Alpha sorting first. + let st = CraftState { + name: "Test".into(), + display_line: None, + rank: 0, + max_rank: 0, + craft_type: CRAFT_TYPE_BEAST_TRAINING, + recipes: vec![ + row(1, "Zeta One", 270, "Zeta"), + row(2, "Alpha One", 261, "Alpha"), + row(3, "Alpha Two", 261, "Alpha"), + ], + }; + let mut s = UiScript::new().unwrap(); + s.set_craft(Some(st.clone())); + let header = |s: &UiScript, line: &str| { + (1..=2) + .find(|i| { + s.eval::(&format!("return GetCraftInfo({i}) == '{line}'")) + .unwrap() + }) + .unwrap() + }; + let expanded = |s: &UiScript, line: &str| { + let at = header(s, line); + s.eval::>(&format!("local _,_,_,_,e = GetCraftInfo({at}) return e")) + .unwrap() + }; + s.run(&format!("CollapseCraftSkillLine({})", header(&s, "Alpha"))) + .unwrap(); + assert_eq!(s.eval::("return GetNumCrafts()").unwrap(), 3); + assert_eq!( + (expanded(&s, "Alpha"), expanded(&s, "Zeta")), + (None, Some(1)) + ); + s.set_craft(Some(st)); + assert_eq!( + s.eval::("return GetNumCrafts()").unwrap(), + 4, + "Zeta's word took bit 0 before the sort" + ); + assert_eq!( + (expanded(&s, "Alpha"), expanded(&s, "Zeta")), + (None, Some(1)), + "Alpha holds position 0 after it" + ); + } + + /// The rows the stock window walks, `(name, type, isExpanded)` for each displayed index. + fn shown(s: &UiScript) -> Vec<(Option, Option, Option)> { + let n = s.eval::("return GetNumCrafts()").unwrap(); + (1..=n) + .map(|i| { + s.eval(&format!("local n,_,t,_,e = GetCraftInfo({i}) return n,t,e")) + .unwrap() + }) + .collect() + } + + /// Two groups build a header row each (`0x4f60c0`, spell id -1). A header skips the + /// comparator's group scan (`0x4f697d`, `0x4f6998`), so it keeps position 0 and sorts ahead of + /// every recipe; the recipes follow by their group's place in the name-sorted headers, then + /// name. A header answers `header` and its expanded flag (`0x4f6f38`, `0x4f6f4f`); one whose + /// line has no `SkillLine.dbc` row answers the failure tuple (`0x4f6f1a`), and a header holds + /// no recipe for the row verbs. + #[test] + fn two_groups_head_each_group_ahead_of_the_recipes() { + let mut s = UiScript::new().unwrap(); + s.set_craft(Some(two_groups())); + let header = |name: Option<&str>| { + ( + name.map(str::to_string), + name.map(|_| "header".to_string()), + name.map(|_| 1), + ) + }; + let rec = |name: &str| (Some(name.to_string()), Some("none".to_string()), None); + // The CRT's `shortsort` over the build's order (`0x73f772`): the tied headers swap, so the + // nameless line 0 heads the array and its recipe leads the shown ones. + assert_eq!( + shown(&s), + [ + header(None), + header(Some("Beast Training")), + rec("Furious Howl"), + rec("Cower"), + rec("Great Stamina"), + rec("Growl"), + ] + ); + let at = (1..=2) + .find(|i| { + s.eval::(&format!("return GetCraftInfo({i}) == 'Beast Training'")) + .unwrap() + }) + .unwrap(); + assert_eq!( + s.eval::(&format!("return GetCraftSkillLine({at})")) + .unwrap(), + "Beast Training" + ); + assert!(s + .eval::(&format!("return GetCraftIcon({at}) == nil")) + .unwrap()); + s.run(&format!("SelectCraft({at}) DoCraft({at})")).unwrap(); + assert_eq!(s.eval::("return GetCraftSelectionIndex()").unwrap(), 0); + assert!(s.take_craft_dos().is_empty()); + assert_eq!(s.arity(&format!("GetCraftInfo({at})")).unwrap(), 7); + } + + /// `CollapseCraftSkillLine` clears its header's bit and `ExpandCraftSkillLine` sets it + /// (`0x4f7c71`, `0x4f7cf2`); each re-sorts and signals `CRAFT_UPDATE` in place (`0x4f6be0`). A + /// collapsed group's recipes leave the displayed count and sort past it (`0x4f673a`), its + /// header shows with a nil `isExpanded`; an index of 0 or below folds every group + /// (`0x4f7c47`, `0x4f7cc7`); a recipe row raises (`0x4f7c5d`). The open expands every group + /// (`0x4f602c`). + #[test] + fn the_fold_verbs_fold_a_header_and_every_group_at_zero() { + use crate::script::tick::heard; + let mut s = UiScript::new().unwrap(); + // Two named lines, so the header sort never ties (`0x4f6b1e`): Beast Training heads row 1. + let mut st = two_groups(); + st.recipes[1].group = 270; + st.recipes[1].skill_line = Some("Pet - Wolf".into()); + s.set_craft(Some(st)); + heard::listen(&s, &["CRAFT_UPDATE"], Some("GetNumCrafts()")); + let at = |s: &UiScript| { + (1..=2) + .find(|i| { + s.eval::(&format!("return GetCraftInfo({i}) == 'Beast Training'")) + .unwrap() + }) + .unwrap() + }; + assert_eq!(at(&s), 1); + s.run(&format!("CollapseCraftSkillLine({})", at(&s))) + .unwrap(); + assert_eq!(heard::take(&s), ["CRAFT_UPDATE 3"]); + let rows = shown(&s); + assert!( + rows.contains(&(Some("Beast Training".into()), Some("header".into()), None)), + "{rows:?}" + ); + assert_eq!( + rows[2], + (Some("Furious Howl".into()), Some("none".into()), None) + ); + let err = s.run("CollapseCraftSkillLine(3)").unwrap_err().to_string(); + assert!( + err.contains("Bad skill line in CollapseCraftSkillLine"), + "{err}" + ); + assert!(heard::take(&s).is_empty()); + s.run(&format!("ExpandCraftSkillLine({})", at(&s))).unwrap(); + assert_eq!(heard::take(&s), ["CRAFT_UPDATE 6"]); + s.run("CollapseCraftSkillLine(0)").unwrap(); + assert_eq!(heard::take(&s), ["CRAFT_UPDATE 2"]); + s.craft_opened(); + assert_eq!(s.eval::("return GetNumCrafts()").unwrap(), 6); + s.run("CollapseCraftSkillLine(-1) ExpandCraftSkillLine(0)") + .unwrap(); + assert_eq!(heard::take(&s), ["CRAFT_UPDATE 2", "CRAFT_UPDATE 6"]); + let err = s.run("ExpandCraftSkillLine('x')").unwrap_err().to_string(); + assert!(err.contains("Usage: ExpandCraftSkillLine(index)"), "{err}"); + } + /// `GetCraftButtonToken` (`0x4f6c90`) pushes the word at the open craft type (`0xbdcfb8`) in /// the table at `0x84d0f4`: `USE`, `TRAIN`, `DISGUISE`, `ENSCRIBE`, then a zero word, which /// pushes nil. A close zeroes the type (`0x4f5fe0`), so a closed window answers `USE`. @@ -1050,6 +1480,7 @@ mod tests { reagents: vec![], tools: vec![], spell_level: level, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, diff --git a/crates/benilla-ui/src/script/death.rs b/crates/benilla-ui/src/script/death.rs index 829f1dda2..8c4cd000a 100644 --- a/crates/benilla-ui/src/script/death.rs +++ b/crates/benilla-ui/src/script/death.rs @@ -98,6 +98,8 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { })?, )?; + // Whole seconds: the milliseconds left over 1000 by a signed, truncating divide + // (`0x48b5ae`-`0x48b5bd`); no timer is -1000 ms, so -1. g.set( "GetReleaseTimeRemaining", lua.create_function(|lua, ()| { @@ -105,15 +107,17 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { Ok(model .death .release_remaining - .map_or(-1.0, |s| f64::from(s.max(0.0)))) + .map_or(-1.0, |s| f64::from(s.max(0.0).trunc()))) })?, )?; + // Whole seconds: the milliseconds left over 1000 by an unsigned divide, a floor + // (`0x48b5f0`-`0x48b5f7`). g.set( "GetCorpseRecoveryDelay", lua.create_function(|lua, ()| { let model = lua.app_data_ref::().expect("model app_data"); - Ok(f64::from(model.death.recovery_delay.max(0.0).ceil())) + Ok(f64::from(model.death.recovery_delay.max(0.0).floor())) })?, )?; diff --git a/crates/benilla-ui/src/script/model.rs b/crates/benilla-ui/src/script/model.rs index 488c7cd23..b837eee3e 100644 --- a/crates/benilla-ui/src/script/model.rs +++ b/crates/benilla-ui/src/script/model.rs @@ -886,6 +886,9 @@ pub(crate) struct Model { /// rows first, and the displayed count (`0xbde054`). pub(crate) trade_skill_rows: Vec, pub(crate) trade_skill_visible: usize, + /// The world-enter init zeroed the counts (`0x4fc750`) and no build has run since: a push + /// holds the state without rows until a rebuild (`0x4fca20`) fills them. + pub(crate) trade_skill_unbuilt: bool, /// The header array as the last sort left it (`0xbde000`). pub(crate) trade_skill_headers: Vec, pub(crate) trade_skill_close: bool, @@ -917,8 +920,18 @@ pub(crate) struct Model { pub(crate) craft_open: bool, /// `DoCraft` spell ids; no count, as the 1.12 CraftFrame has no Create All. pub(crate) craft_dos: Vec, - /// The 1-based selection, 0 for none, carried across a re-push by the recipe's spell id. + /// The selected spell id (`0xbdcfbc`), 0 for none, which a header or an index past the rows + /// stores (`0x4f6050`); the index answers by finding its row (`0x4f6080`). pub(crate) craft_selection: u32, + /// The row array as the last sort left it (`0xbdcf78`, full count `0xbdcfc0`), the displayed + /// rows first, and the displayed count (`0xbdcfc8`). + pub(crate) craft_rows: Vec, + pub(crate) craft_visible: usize, + /// The header array as the last sort left it (`0xbdcf88`, count `0xbdcfc4`). + pub(crate) craft_headers: Vec, + /// The collapse mask (`0x84d0f0`), a clear bit a collapsed header by its array position; the + /// open sets it to all ones (`0x4f602c`). + pub(crate) craft_fold_mask: u32, pub(crate) craft_close: bool, /// The open loot as the app pushed it; the verbs over it are script calls @@ -1723,6 +1736,7 @@ impl Model { trade_skill_dos: Vec::new(), trade_skill_rows: Vec::new(), trade_skill_visible: 0, + trade_skill_unbuilt: false, trade_skill_headers: Vec::new(), trade_skill_close: false, trade_skill_collapsed: HashSet::new(), @@ -1736,6 +1750,10 @@ impl Model { craft_open: false, craft_dos: Vec::new(), craft_selection: 0, + craft_rows: Vec::new(), + craft_visible: 0, + craft_headers: Vec::new(), + craft_fold_mask: u32::MAX, craft_close: false, loot: None, loot_type: 0, diff --git a/crates/benilla-ui/src/script/tests/tooltip_spell.rs b/crates/benilla-ui/src/script/tests/tooltip_spell.rs index c6f8294ad..177a2ebe4 100644 --- a/crates/benilla-ui/src/script/tests/tooltip_spell.rs +++ b/crates/benilla-ui/src/script/tests/tooltip_spell.rs @@ -1262,6 +1262,7 @@ fn set_craft_spell_selects_the_builder_like_the_trainer_hover_does() { reagents: vec![], tools: vec![], spell_level: 0, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, @@ -1511,6 +1512,7 @@ fn craft_recipe(spell_id: u32, name: &str, tooltip: CraftTooltip) -> CraftRecipe reagents: vec![], tools: vec![], spell_level: 0, + group: 0, skill_line: None, training_point_cost: 0, required_level: 0, diff --git a/crates/benilla-ui/src/script/tooltip_item/mod.rs b/crates/benilla-ui/src/script/tooltip_item/mod.rs index e544f086c..273f4fbb3 100644 --- a/crates/benilla-ui/src/script/tooltip_item/mod.rs +++ b/crates/benilla-ui/src/script/tooltip_item/mod.rs @@ -1133,11 +1133,7 @@ pub(super) fn install_methods(lua: &Lua, m: &Table) -> mlua::Result<()> { let reagent_index = binding_abi::index_arg(lua, reagent_index, LINE)?; let found = { let model = lua.app_data_ref::().expect("model app_data"); - let Some(c) = &model.craft else { - return Ok(()); - }; - let Some(recipe) = craft_index.checked_sub(1).and_then(|i| c.recipes.get(i)) - else { + let Some(recipe) = crate::script::craft::recipe(&model, craft_index) else { return Ok(()); }; reagent_index diff --git a/crates/benilla-ui/src/script/tooltip_spell.rs b/crates/benilla-ui/src/script/tooltip_spell.rs index 2e774db32..3c6020ce0 100644 --- a/crates/benilla-ui/src/script/tooltip_spell.rs +++ b/crates/benilla-ui/src/script/tooltip_spell.rs @@ -1007,8 +1007,8 @@ pub(super) fn install_methods(lua: &Lua, m: &Table) -> mlua::Result<()> { )?; // GameTooltip:SetCraftSpell(craftIndex): the craft detail icon's hover // (`Blizzard_CraftUI.xml:566`). `SetCraftSpell 0x533e90` hands a shared builder the subject the - // app resolved from the recipe's own effects (`CraftRecipe::tooltip`). `craftIndex` is a plain - // recipe position: the craft list has no headers. + // app resolved from the recipe's own effects (`CraftRecipe::tooltip`). `craftIndex` is 1-based + // into the craft rows, where a header holds no recipe. m.set( "SetCraftSpell", lua.create_function(|lua, (this, craft_index): (Table, Value)| { @@ -1017,10 +1017,7 @@ pub(super) fn install_methods(lua: &Lua, m: &Table) -> mlua::Result<()> { binding_abi::index_arg(lua, craft_index, "Invalid craft in SetCraftSpell(index)")?; let subject = { let model = lua.app_data_ref::().expect("model app_data"); - let Some(c) = &model.craft else { - return Ok(()); - }; - match craft_index.checked_sub(1).and_then(|i| c.recipes.get(i)) { + match super::craft::recipe(&model, craft_index) { Some(r) => r.tooltip.clone(), None => return Ok(()), } diff --git a/crates/benilla-ui/src/script/tradeskill/mod.rs b/crates/benilla-ui/src/script/tradeskill/mod.rs index f1587cef3..d0d607acf 100644 --- a/crates/benilla-ui/src/script/tradeskill/mod.rs +++ b/crates/benilla-ui/src/script/tradeskill/mod.rs @@ -169,7 +169,7 @@ impl super::UiScript { /// selection rides its spell id (`0xbde044`); fold and subclass keys are pruned to live groups, /// while the inv-slot mask (`0x84dd64`) is never pruned. /// `None` marks the window closed and keeps the list and selection, as the close does - /// (`0x4fc870`). + /// (`0x4fc870`). After the world-enter init no push builds rows until a rebuild does. pub fn set_trade_skill(&mut self, state: Option) { let mut model = self.model_mut(); model.trade_skill_open = state.is_some(); @@ -206,7 +206,9 @@ impl super::UiScript { .as_ref() .is_none_or(|t| spells(&t.recipes) != spells(&s.recipes)); model.trade_skill = Some(s); - view::build(&mut model, remake); + if !model.trade_skill_unbuilt { + view::build(&mut model, remake); + } } } } @@ -239,6 +241,7 @@ impl super::UiScript { if let Some(t) = model.trade_skill.as_mut() { refresh(t); } + model.trade_skill_unbuilt = false; let complete = view::build(&mut model, remake); note_build(&mut model); complete @@ -248,6 +251,9 @@ impl super::UiScript { /// records in flight counted and waited on as any build's. Whether its update follows. pub fn trade_skill_open_build(&mut self) -> bool { let mut model = self.model_mut(); + if std::mem::take(&mut model.trade_skill_unbuilt) { + view::build(&mut model, true); + } note_build(&mut model); model.trade_skill_pending == 0 } @@ -345,21 +351,25 @@ impl super::UiScript { /// The world-enter inits (`0x4908c0` at `0x4909bf` and `0x4909c4`), which a login, a /// cross-map worldport and a `/reload` all run, with no event: the tradeskill init `0x4fc750` - /// zeroes the selection (`[0xbde044]`), the visible and held counts (`[0xbde04c]`, - /// `[0xbde054]`), the line key (`[0xbde064]`), so the next push resets the filters, and the - /// armed spell (`[0xbde05c]`, `0x4fc76b`), keeping the count (`[0xbde060]`) and the open marker - /// (`[0xbde040]`); the craft init `0x4f5ee0` zeroes the craft open marker (`[0xbdcfb8]`), its - /// selection and its count (`[0xbdcfc8]`). + /// zeroes the selection (`[0xbde044]`), the row, displayed and header counts (`[0xbde04c]`, + /// `[0xbde054]`, `[0xbde050]`), the line key (`[0xbde064]`), so the next push resets the + /// filters, and the armed spell (`[0xbde05c]`, `0x4fc76b`), keeping the count (`[0xbde060]`) + /// and the open line (`[0xbde040]`), whose list waits for the next rebuild; the craft init + /// `0x4f5ee0` zeroes the craft type (`[0xbdcfb8]`), which closes its window, its selection and + /// its counts (`[0xbdcfbc]`-`[0xbdcfc8]`). pub fn reset_crafts_on_world_enter(&mut self) { let mut model = self.model_mut(); - model.trade_skill = None; - view::build(&mut model, true); + model.trade_skill_rows.clear(); + model.trade_skill_headers.clear(); + model.trade_skill_visible = 0; + model.trade_skill_unbuilt = true; model.trade_skill_selected_spell = 0; model.trade_skill_last_line = 0; model.trade_skill_repeat_spell = 0; model.craft = None; model.craft_open = false; model.craft_selection = 0; + super::craft::build(&mut model); } /// Seat the repeat count a previous VM left (`[0xbde060]`), which the world-enter init keeps diff --git a/crates/benilla-ui/src/script/tradeskill/tests.rs b/crates/benilla-ui/src/script/tradeskill/tests.rs index eece2a2cb..2aea1db3c 100644 --- a/crates/benilla-ui/src/script/tradeskill/tests.rs +++ b/crates/benilla-ui/src/script/tradeskill/tests.rs @@ -1548,3 +1548,32 @@ fn the_item_stats_getter_waits_only_on_a_record_in_flight() { .unwrap(); assert!(s.take_trade_skill_item_waits().is_empty()); } + +/// The world-enter init (`0x4fc750`) zeroes the row and header counts and keeps the open line +/// (`[0xbde040]`): the line still answers, the list is empty, a push builds nothing, and only a +/// rebuild (`0x4fca20`) fills it again, with its `TRADE_SKILL_UPDATE` (`0x4fd164`). +#[test] +fn the_world_enter_init_empties_the_list_until_a_rebuild() { + use crate::script::tick::heard; + let mut s = UiScript::new().unwrap(); + s.set_trade_skill(Some(two_recipe_state())); + assert_eq!(s.eval::("return GetNumTradeSkills()").unwrap(), 3); + s.reset_crafts_on_world_enter(); + heard::listen(&s, &["TRADE_SKILL_UPDATE"], Some("GetNumTradeSkills()")); + assert_eq!(s.eval::("return GetNumTradeSkills()").unwrap(), 0); + assert_eq!( + s.eval::("return (GetTradeSkillLine())").unwrap(), + "Tailoring" + ); + assert_eq!(s.model_ref().open_professions().trade_skill, Some(197)); + let mut more = two_recipe_state(); + more.recipes[0].num_available = 4; + s.set_trade_skill(Some(more)); + assert_eq!(s.eval::("return GetNumTradeSkills()").unwrap(), 0); + assert!( + heard::take(&s).is_empty(), + "the init and the push signal nothing" + ); + s.rebuild_trade_skill(&mut |_| {}); + assert_eq!(heard::take(&s), ["TRADE_SKILL_UPDATE 3"]); +} diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index da6566e4d..271f3929f 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -374,10 +374,10 @@ 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:253`](../crates/benilla-app/src/ui_loot/mod.rs#L253)) -- `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:629`](../crates/benilla-app/src/ui_loot/mod.rs#L629)) -- 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:657`](../crates/benilla-app/src/ui_loot/mod.rs#L657)) -- 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:854`](../crates/benilla-app/src/ui_loot/mod.rs#L854)) +- 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:271`](../crates/benilla-app/src/ui_loot/mod.rs#L271)) +- `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:685`](../crates/benilla-app/src/ui_loot/mod.rs#L685)) +- 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:713`](../crates/benilla-app/src/ui_loot/mod.rs#L713)) +- 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:910`](../crates/benilla-app/src/ui_loot/mod.rs#L910)) #### ui_loot_roll @@ -724,8 +724,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - A row the session owns (an env lever) is passed, because the env chose its value for this run and the file never holds it, so a reset would undo the lever and save nothing. ([`src/script/console_exec.rs:199`](../crates/benilla-ui/src/script/console_exec.rs#L199)) - The backpack is bounded by its own 16 slots, where `0x4f990f` bounds bag 0 by the player list's count (0x71), a reference bug that lets the backpack index read other containers. ([`src/script/container.rs:321`](../crates/benilla-ui/src/script/container.rs#L321)) - A row index the list no longer holds buys nothing and drops, where this path reads through a null row (`0x4f9f35`). ([`src/script/container.rs:792`](../crates/benilla-ui/src/script/container.rs#L792)) -- A last `spell_id` key breaks the remaining ties (Charge's six ranks all have `spellLevel` 0), because the reference leaves them to its qsort over an array benilla does not reproduce; ascending id is ascending rank in every 1.12 pet-ability family. ([`src/script/craft.rs:164`](../crates/benilla-ui/src/script/craft.rs#L164)) -- The reference reads past the table unbounded (`0x4f6c90`), so type 5 would answer "CloseCraft"; no shipped opener carries a type past 3, and benilla answers nil rather than read past it. ([`src/script/craft.rs:538`](../crates/benilla-ui/src/script/craft.rs#L538)) +- A last `spell_id` key breaks the remaining ties (Charge's six ranks all have `spellLevel` 0), because the reference leaves them to its qsort over an array benilla does not reproduce; ascending id is ascending rank in every 1.12 pet-ability family. ([`src/script/craft.rs:201`](../crates/benilla-ui/src/script/craft.rs#L201)) +- The reference reads past the table unbounded (`0x4f6c90`), so type 5 would answer "CloseCraft"; no shipped opener carries a type past 3, and benilla answers nil rather than read past it. ([`src/script/craft.rs:729`](../crates/benilla-ui/src/script/craft.rs#L729)) - On `Terrain` the reference keeps a spell, action, macro or pet action on the left button; we clear them, because otherwise a spell has no left-click way off the cursor. ([`src/script/cursor.rs:643`](../crates/benilla-ui/src/script/cursor.rs#L643)) - Every lock lifts here, bag contents included. The reference's walk of a bag's contents indexes the bag by its own player-array index (`0x495528`, `0x495535`), at least 19, past a bag's slots in every case but the biggest bags, so it normally unlocks none of them; a lock it strands lasts until the item's seat or stack moves, which this does not copy. ([`src/script/cursor.rs:841`](../crates/benilla-ui/src/script/cursor.rs#L841)) - Returns nothing. The handler ends `mov eax,1` with nothing pushed (`0x4895bc`), so Lua 5.0 hands back the stack top, the last argument or the function itself: an accident of the handler, not an API, and copying a stack-top leak would copy a bug. ([`src/script/cursor.rs:1070`](../crates/benilla-ui/src/script/cursor.rs#L1070))