diff --git a/crates/benilla-app/src/lanes.rs b/crates/benilla-app/src/lanes.rs index 5c521bfe2..77595581b 100644 --- a/crates/benilla-app/src/lanes.rs +++ b/crates/benilla-app/src/lanes.rs @@ -444,6 +444,8 @@ mod item_live_tests; #[cfg(test)] mod item_tests; #[cfg(test)] +mod name_live_tests; +#[cfg(test)] mod packet_signal_tests; #[cfg(test)] mod quiet_tests; diff --git a/crates/benilla-app/src/lanes/guard_tests.rs b/crates/benilla-app/src/lanes/guard_tests.rs index 414e031bc..a28a61bab 100644 --- a/crates/benilla-app/src/lanes/guard_tests.rs +++ b/crates/benilla-app/src/lanes/guard_tests.rs @@ -1649,13 +1649,13 @@ const VERSIONED_FOR_THE_DRAIN: &[&str] = &["net::reputations::Reputations"]; /// longer matches its firing fails. #[rustfmt::skip] const LANE_READS_FRAME_FINAL: &[(&str, &[&str])] = &[ - // The watchers' callbacks: the drunk line's name, the quest log's slots, the skill line's race - // and class and the bonus bar's form off our live descriptor, and the aura watcher's join of - // the durations the duration packet writes (`0x4e4390` into `0xbc5f68`), as the frame left them - // (#2217); the aura watcher's own store is the one its packet left. `SetPetGuid`'s trainer - // refresh reads the open trainer, and its `PET_UI_CLOSE` the new pet's object and ours, as - // the frame left them. - ("field notices", &["names::NameCache", "net::GuidIndex", "net::ObjectStore", + // The watchers' callbacks: the quest log's slots, the skill line's race and class and the + // bonus bar's form off our live descriptor, and the aura watcher's join of the durations the + // duration packet writes (`0x4e4390` into `0xbc5f68`), as the frame left them (#2217); the + // aura watcher's own store is the one its packet left. The drunk line's name is read through + // the host. `SetPetGuid`'s trainer refresh reads the open trainer, and its `PET_UI_CLOSE` the + // new pet's object and ours, as the frame left them. + ("field notices", &["net::GuidIndex", "net::ObjectStore", "ui_aura::AuraDurations", "ui_trainer::TrainerOpen"]), // The views lane reads the stores, records and roster cells it rewinds as of each packet, and // the reputations as the reputation lane replays them; the names, the relations' stores, the diff --git a/crates/benilla-app/src/lanes/name_live_tests.rs b/crates/benilla-app/src/lanes/name_live_tests.rs new file mode 100644 index 000000000..6e488665c --- /dev/null +++ b/crates/benilla-app/src/lanes/name_live_tests.rs @@ -0,0 +1,276 @@ +//! The name caches' getters read the caches as they stand where they run, through the lent host: +//! `UnitName` names a unit through `GetUnitName` (`0x609210`), `UnitPVPName` builds on it +//! (`0x5172b0` → `0x609370`), and `UnitCreatureType` (`0x51a280`), `UnitClassification` +//! (`0x516d90`) and `UnitLevel`'s world-boss leg read the unit's cached creature record +//! (`0x605570`, `0x605620`). A name answer's events fire at its packet's place, as the callback +//! runs inside the handler that filed the record (`0x5fb840`, `0x604660`). + +use benilla_protocol::SessionEvent; +use benilla_ui::script::live::ask; +use benilla_ui::script::PlayerNameQuery; +use bevy::prelude::*; + +use super::unit_view_tests::{client, frame, health, values}; +use crate::names::{CreatureRecord, NameCache}; + +/// The target [`client`] seats: a creature. +const WOLF: u64 = 0xF130_0000_0044_0001; +/// The template entry the wolf's descriptor names. +const WOLF_ENTRY: u32 = 299; +/// `OBJECT_FIELD_ENTRY`. +const OBJECT_ENTRY: u16 = 3; +/// `UNIT_FIELD_PETNUMBER`. +const UNIT_PETNUMBER: u16 = 139; +/// A player the name cache holds, and one it lacks. +const BOB: u64 = 0x61; +const STRANGER: u64 = 0x62; + +/// The wolf's template, an elite beast. +fn wolf_record() -> CreatureRecord { + CreatureRecord { + name: "Wolf".into(), + subname: None, + creature_type: 1, + pet_family: 0, + rank: 1, + type_flags: 0, + pet_spell_list: 0, + civilian: false, + racial_leader: false, + display_id: 0, + } +} + +/// The wolf's answer packet, as the server sends it. +fn wolf_named() -> SessionEvent { + SessionEvent::CreatureName { + entry: WOLF_ENTRY, + name: Some("Wolf".into()), + subname: None, + creature_type: Some(1), + pet_family: 0, + rank: 1, + type_flags: 0, + pet_spell_list: 0, + display_id: 0, + civilian: false, + racial_leader: false, + } +} + +/// The client with the wolf's descriptor naming its template, the type words loaded and a spy on +/// the name events that reads the getters as each one fires. +fn named_client() -> App { + let mut app = client(); + let world = app.world_mut(); + let entity = world.resource::().0[&WOLF]; + world + .get_mut::(entity) + .expect("a store") + .0 + .merge(benilla_protocol::ObjectFields::from_pairs(&[( + OBJECT_ENTRY, + WOLF_ENTRY, + )])); + world.insert_resource(crate::target::CreatureTypes( + benilla_formats::CreatureTypeTable::from_rows([(1, "Beast", 0), (7, "Humanoid", 0)]), + )); + app.world_mut() + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + for _, e in ipairs({"UNIT_NAME_UPDATE", "UNIT_CLASSIFICATION_CHANGED"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. arg1 .. ":" .. tostring(UnitName(arg1)) + .. ":" .. tostring(UnitClassification(arg1))) + end) + "#, + ) + .unwrap(); + app +} + +/// `chunk` with the host lent, as a listener's call runs. +fn hosted(app: &mut App, chunk: &str) -> T { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval(chunk).expect("runs") + }) +} + +/// A creature's record that lands after the frame's push is read by the getters as they run: its +/// name, its type word, its rank and the world-boss -1 of its level, where the snapshot, pushed +/// before, still holds none of them. +#[test] +fn the_creature_getters_read_the_record_as_they_run() { + let mut app = named_client(); + const CHUNK: &str = "return UnitName('target'), UnitPVPName('target'), \ + UnitCreatureType('target'), UnitClassification('target'), UnitLevel('target')"; + type Answer = (Option, Option, Option, String, i64); + let before: Answer = hosted(&mut app, CHUNK); + assert_eq!( + before, + ( + Some("Unknown Being".into()), + Some("Unknown Being".into()), + None, + "normal".into(), + 0 + ), + "no record yet: both name the unknown object (`0x609324`), no type, the normal rank" + ); + // A boss template: its rank 3 hides the level (`0x51807d`). + let mut record = wolf_record(); + record.rank = 3; + app.world_mut() + .resource_mut::() + .insert_creature(WOLF_ENTRY, Some(record)); + let live: Answer = hosted(&mut app, CHUNK); + assert_eq!( + live, + ( + Some("Wolf".into()), + Some("Wolf".into()), + Some("Beast".into()), + "worldboss".into(), + -1 + ) + ); + // The snapshot, pushed ahead of the record, holds none of it: a VM with no host lent. + let snapshot: Answer = crate::script_calls::eval_in_vm(app.world(), CHUNK); + assert_eq!(snapshot.2, None, "the push held no record"); + assert_eq!(snapshot.3, "normal"); +} + +/// A pet or charm reads rank 0 whatever its template says (`0x605620`), live as in the push. +#[test] +fn a_charmed_creature_reads_rank_zero_live() { + let mut app = named_client(); + app.world_mut() + .resource_mut::() + .insert_creature(WOLF_ENTRY, Some(wolf_record())); + let elite: String = hosted(&mut app, "return UnitClassification('target')"); + assert_eq!(elite, "elite"); + let world = app.world_mut(); + let entity = world.resource::().0[&WOLF]; + world + .get_mut::(entity) + .expect("a store") + .0 + .merge(benilla_protocol::ObjectFields::from_pairs(&[( + UNIT_PETNUMBER, + 5, + )])); + let charmed: String = hosted(&mut app, "return UnitClassification('target')"); + assert_eq!(charmed, "normal"); +} + +/// The player-name cache's record is read as the call runs: a name filed between two reads shows +/// in the second, a miss answers its own empty answer, and with no host lent nothing answers. +#[test] +fn a_player_name_reads_the_cache_as_it_runs() { + let mut app = named_client(); + app.world_mut() + .resource_mut::() + .insert_player(BOB, "Bob".into(), None); + let read = |app: &mut App, guid: u64| { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + ask(s.expect("a VM").lua(), &PlayerNameQuery(guid)) + }) + }; + assert_eq!(read(&mut app, BOB), Some(Some("Bob".to_string()))); + assert_eq!(read(&mut app, STRANGER), Some(None), "a miss"); + app.world_mut() + .resource_mut::() + .insert_player(STRANGER, "Stranger".into(), None); + assert_eq!(read(&mut app, STRANGER), Some(Some("Stranger".to_string()))); + let unlent = ask( + app.world() + .non_send_resource::() + .lua(), + &PlayerNameQuery(BOB), + ); + assert_eq!(unlent, None, "no host lent, no live read"); +} + +/// A creature's answer raises `UNIT_NAME_UPDATE` then `UNIT_CLASSIFICATION_CHANGED` for each held +/// unit of the entry (`0x6046d1`, `0x6046dd`) at the answer packet's place, between the packets +/// ahead of it and behind it, and their listeners read the record the handler filed. +#[test] +fn a_creature_answers_its_name_events_at_its_packets_place() { + let mut app = named_client(); + assert_eq!( + frame( + &mut app, + vec![ + values(WOLF, &health(70)), + wolf_named(), + values(WOLF, &health(40)), + ] + ), + [ + "UNIT_HEALTH:target:70", + "UNIT_NAME_UPDATE:target:Wolf:elite", + "UNIT_CLASSIFICATION_CHANGED:target:Wolf:elite", + "UNIT_HEALTH:target:40", + ] + ); +} + +/// The civilian flag is the record's, read as the call runs: `UnitIsCivilian` and the `UnitPVPName` +/// prefix (`0x612550`, `0x609370`) see a template that landed after the frame's push, where the +/// snapshot holds a record-less unit. The PvP flag, the level and the reaction are held as the +/// push has them. +#[test] +fn the_civilian_flag_is_read_off_the_record_as_the_call_runs() { + let mut app = named_client(); + let world = app.world_mut(); + let entity = world.resource::().0[&WOLF]; + // `UNIT_FIELD_FLAGS` PvP, and a level far below the player's. + world + .get_mut::(entity) + .expect("a store") + .0 + .merge(benilla_protocol::ObjectFields::from_pairs(&[ + (benilla_protocol::field::FIELD_UNIT_FLAGS, 0x1000), + (benilla_protocol::field::FIELD_UNIT_LEVEL, 1), + ])); + { + let mut script = world.non_send_resource_mut::(); + script.run(r#"PVP_RANK_CIVILIAN = "Civilian""#).unwrap(); + script.set_player_req_state(benilla_ui::script::PlayerReqState { + level: 60, + ..Default::default() + }); + // The push, as a record-less unit hostile to us holds it. + script.set_unit( + "target", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + is_connected: true, + guid: WOLF, + name: Some("Wolf".into()), + reaction: 1, + pvp: true, + level: 1, + ..Default::default() + }), + ); + } + const CHUNK: &str = "return UnitIsCivilian('target'), UnitPVPName('target')"; + let before: (Option, Option) = hosted(&mut app, CHUNK); + assert_eq!(before, (None, Some("Wolf".into())), "no record yet"); + let mut record = wolf_record(); + record.civilian = true; + app.world_mut() + .resource_mut::() + .insert_creature(WOLF_ENTRY, Some(record)); + let live: (Option, Option) = hosted(&mut app, CHUNK); + assert_eq!(live, (Some(1), Some("Civilian Wolf".into()))); + let snapshot: (Option, Option) = + crate::script_calls::eval_in_vm(app.world(), CHUNK); + assert_eq!(snapshot.0, None, "the push held no record"); +} diff --git a/crates/benilla-app/src/names.rs b/crates/benilla-app/src/names.rs index cfc55fca7..6665d5be7 100644 --- a/crates/benilla-app/src/names.rs +++ b/crates/benilla-app/src/names.rs @@ -22,6 +22,9 @@ use benilla_protocol::messages::ObjectFields; use crate::net::{ClientCommand, NetCommands, ObjectStore, Objects}; use crate::query_cache::{Ask, QueryCache, Refused}; +mod live; +pub(crate) use live::NameLive; + /// The creature template's `type_flags` dword from `SMSG_CREATURE_QUERY_RESPONSE`, cached by the /// reference at `[CGUnit+0xb30] + 0x14`. Adjacent bits mean unrelated things, and the reference /// gives each its own getter, so every consumer names the bit it reads: diff --git a/crates/benilla-app/src/names/live.rs b/crates/benilla-app/src/names/live.rs new file mode 100644 index 000000000..621bdd573 --- /dev/null +++ b/crates/benilla-app/src/names/live.rs @@ -0,0 +1,71 @@ +//! The name caches' reads at the call, the call host's half of +//! [`benilla_ui::script::PlayerNameQuery`] and [`benilla_ui::script::UnitRecordQuery`]: the +//! player-name cache's record read only (`0x55f080`), and the creature-record legs of a held +//! unit, each as the snapshot's build derives them ([`crate::ui_unit::snapshot`], +//! [`crate::ui_unit::enrich_unit`]) off the unit object as of the drain's place. + +use bevy::ecs::system::SystemParam; +use bevy::prelude::*; + +use benilla_ui::script::{PlayerNameQuery, UnitRecord, UnitRecordQuery}; + +use super::NameCache; +use crate::creature_type::CreatureTypeSources; +use crate::query_cache::Ask; + +/// What the name getters read as they run. +#[derive(SystemParam)] +pub(crate) struct NameLive<'w, 's> { + names: Option>, + index: Option>, + stores: crate::ui_unit::views::ViewStores<'w, 's>, + /// The form table and the type words the creature type resolves through. + spells: Option>, + words: Option>, +} + +impl NameLive<'_, '_> { + /// The player-name cache's record for `guid`, read only: `Some(None)` for a miss or a refusal. + /// Declined in a harness without the cache. + fn player(&self, guid: u64) -> Option> { + let names = self.names.as_deref()?; + Some(names.resolve_player(guid, Ask::Read).map(str::to_string)) + } + + /// The creature-record legs of the unit held under `guid` as of here (`0x605570`, `0x605620`, + /// `0x612550`): a player has no record to read (the snapshot reads none either), and a + /// creature without its template cached reads rank 0, no civilian flag, and its race's type. + /// Declined for no unit held and in a harness without the cache. + fn record(&self, guid: u64) -> Option { + let names = self.names.as_deref()?; + let entity = self.index.as_deref().and_then(|i| i.0.get(&guid).copied()); + let store = self.stores.at(guid, entity).filter(|s| s.is_unit())?; + let types = + CreatureTypeSources::of_resources(names, self.spells.as_deref(), self.words.as_deref()); + let creature_type = types.word(types.of(store)).map(str::to_string); + if benilla_protocol::guid::is_player(guid) { + return Some(UnitRecord { + creature_type, + ..Default::default() + }); + } + // Keyed by the unit's own `OBJECT_FIELD_ENTRY`, an entry of 0 being no key (`0x604629`). + let record = store + .0 + .object_entry() + .filter(|&e| e != 0) + .and_then(|e| names.creature_record(e)); + Some(UnitRecord { + creature_type, + rank: super::gated_rank(record, Some(store)), + civilian: record.is_some_and(|r| r.civilian), + }) + } +} + +impl crate::script_calls::live::LiveFamily for NameLive<'_, '_> { + fn answer(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + ask.answer(|q: &PlayerNameQuery| self.player(q.0)) + || ask.answer(|q: &UnitRecordQuery| self.record(q.0)) + } +} diff --git a/crates/benilla-app/src/script_calls.rs b/crates/benilla-app/src/script_calls.rs index cc1b28bd0..9c2c34302 100644 --- a/crates/benilla-app/src/script_calls.rs +++ b/crates/benilla-app/src/script_calls.rs @@ -563,10 +563,6 @@ impl CallHost for ScriptCallHost<'_, '_> { self.appliers.live().items().read(key, read) } - fn player_name(&mut self, guid: u64) -> Option { - self.appliers.asks().player_name(guid) - } - fn read_unit_object( &mut self, guid: u64, diff --git a/crates/benilla-app/src/script_calls/engine.rs b/crates/benilla-app/src/script_calls/engine.rs index e28d6cb5c..d6798c13c 100644 --- a/crates/benilla-app/src/script_calls/engine.rs +++ b/crates/benilla-app/src/script_calls/engine.rs @@ -68,14 +68,6 @@ pub(crate) struct RecordAsks<'w> { } impl RecordAsks<'_> { - /// The player-name cache's record for `guid`, read only ([`benilla_ui::script::CallHost::player_name`]). - pub(crate) fn player_name(&self, guid: u64) -> Option { - self.names - .as_deref()? - .resolve_player(guid, crate::query_cache::Ask::Read) - .map(str::to_string) - } - /// `ask` inside its getter, whose VM a hit the mirror lacked is told. pub(crate) fn apply(&mut self, script: &mut UiScript, ask: RecordAsk) { use crate::query_cache::Ask; diff --git a/crates/benilla-app/src/script_calls/live.rs b/crates/benilla-app/src/script_calls/live.rs index 672ff3e0b..64d03c637 100644 --- a/crates/benilla-app/src/script_calls/live.rs +++ b/crates/benilla-app/src/script_calls/live.rs @@ -77,6 +77,8 @@ live_reads! { roster: crate::ui_party::RosterLive<'static, 'static>, /// The faction rows, the watched slot and the pane's snapshot. reputation: crate::ui_reputation::ReputationLive<'static, 'static>, + /// The name caches' reads: a player's name and a unit's creature record. + names: crate::names::NameLive<'static, 'static>, #[cfg(test)] probe: tests::ProbeLive<'static>, } diff --git a/crates/benilla-app/src/ui_auction/sort_tests.rs b/crates/benilla-app/src/ui_auction/sort_tests.rs index b98c3cef6..86b4e198c 100644 --- a/crates/benilla-app/src/ui_auction/sort_tests.rs +++ b/crates/benilla-app/src/ui_auction/sort_tests.rs @@ -286,8 +286,8 @@ impl benilla_ui::script::CallHost for AuctionHost<'_, '_, '_> { None } - fn player_name(&mut self, guid: u64) -> Option { - self.0.player_name(guid) + fn read_live(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + ask.answer(|q: &benilla_ui::script::PlayerNameQuery| Some(self.0.player_name(q.0))) } } diff --git a/crates/benilla-app/src/ui_auction/verbs.rs b/crates/benilla-app/src/ui_auction/verbs.rs index 02a9c609a..e8304974e 100644 --- a/crates/benilla-app/src/ui_auction/verbs.rs +++ b/crates/benilla-app/src/ui_auction/verbs.rs @@ -46,7 +46,7 @@ impl AuctionVerbs<'_, '_> { /// `GetAuctionItemInfo`'s name lookup inside its call /// ([`benilla_ui::script::RecordAsk::AuctionName`]): the cache asks a miss, and the list's /// callback waits on the name, once per name and list (`0x55f080`'s dedupe flag 1). The getter - /// makes it only on a miss, having read the cache first ([`Self::player_name`]). + /// makes it only on a miss, having read the cache first ([`benilla_ui::script::PlayerNameQuery`]). pub(crate) fn wait_for_name(&mut self, guid: u64, list: usize) { if let Some(names) = self.names.as_deref() { let _ = names.resolve_player(guid, Ask::Event(&self.commands)); diff --git a/crates/benilla-app/src/ui_unit/field_events.rs b/crates/benilla-app/src/ui_unit/field_events.rs index e96caa8c8..71a0c8a9d 100644 --- a/crates/benilla-app/src/ui_unit/field_events.rs +++ b/crates/benilla-app/src/ui_unit/field_events.rs @@ -26,8 +26,6 @@ pub(crate) struct FieldEventPushes; #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct NoticeFiring<'w, 's> { sink: crate::ui_action::MessageSink<'w>, - // The drunk watcher names the player it runs on (`0x609210`). - names: Res<'w, crate::names::NameCache>, // The quest log's watcher reads the slots. me: Query<'w, 's, &'static crate::net::ObjectStore, With>, tutorials: Option>, @@ -82,7 +80,7 @@ impl NoticeFiring<'_, '_> { return false; } if let FieldNotice::Drunk { guid, old, new } = notice { - drunk(script, &mut self.sink, &self.names, guid, old, new); + drunk(script, &mut self.sink, guid, old, new); return false; } if notice == FieldNotice::SkillLines { @@ -349,7 +347,6 @@ pub(crate) fn fire_field_notices( fn drunk( script: &mut UiScript, sink: &mut crate::ui_action::MessageSink, - names: &crate::names::NameCache, guid: u64, old: u8, new: u8, @@ -358,10 +355,11 @@ fn drunk( if me && script.player_can_attack_target() { script.fire_event("UNIT_LEVEL", vec![ScriptValue::Str("target".to_string())]); } + // The name cache as the watcher runs, through the lent host (`0x609210`). let name = (!me).then(|| { - names - .resolve_player(guid, crate::query_cache::Ask::Read) - .map_or_else(|| script.unknown_object_text(), str::to_string) + benilla_ui::script::live::ask(script.lua(), &benilla_ui::script::PlayerNameQuery(guid)) + .flatten() + .unwrap_or_else(|| script.unknown_object_text()) }); let lines: Vec<_> = drunk_messages(old, new) .into_iter() @@ -731,6 +729,20 @@ mod tests { .init_resource::() .init_resource::() .init_resource::(); + spy(&mut app, guids); + app + } + + /// [`world`] in the whole client's, whose notices fire with the call host lent, as a getter + /// reads the name caches through it. + fn hosted_world(guids: benilla_ui::script::UnitGuids) -> App { + let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + spy(&mut app, guids); + app + } + + /// The VM that records every event the notices fire, with `guids` seated. + fn spy(app: &mut App, guids: benilla_ui::script::UnitGuids) { let mut script = UiScript::new().unwrap(); script .run( @@ -746,7 +758,6 @@ mod tests { .unwrap(); script.set_unit_guids(&guids); app.insert_non_send_resource(script); - app } fn fired(app: &mut App, notices: &[FieldNotice]) -> Vec { @@ -1037,7 +1048,7 @@ mod tests { None } } - let mut app = world(benilla_ui::script::UnitGuids { + let mut app = hosted_world(benilla_ui::script::UnitGuids { target: MOB, ..seated() }); diff --git a/crates/benilla-ui/src/script/auction.rs b/crates/benilla-ui/src/script/auction.rs index b4b25f1aa..fd47c3fdf 100644 --- a/crates/benilla-ui/src/script/auction.rs +++ b/crates/benilla-ui/src/script/auction.rs @@ -860,7 +860,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { // (`0x4cf167`), then the seller's (`0x4cf1c8`); the push's only with no host lent. A // miss is asked inside the call with the list's callback; nothing else asks a name. let mut r = r; - let live = |guid: u64| super::host::read_host(lua, |h| h.player_name(guid)); + let live = |guid: u64| super::live::ask(lua, &super::PlayerNameQuery(guid)); let bidder = (r.named_bidder != 0).then(|| match live(r.named_bidder) { Some(name) => name, None => match &r.high_bidder { diff --git a/crates/benilla-ui/src/script/host.rs b/crates/benilla-ui/src/script/host.rs index 151192a57..f7154f67e 100644 --- a/crates/benilla-ui/src/script/host.rs +++ b/crates/benilla-ui/src/script/host.rs @@ -42,13 +42,6 @@ pub trait CallHost { false } - /// The player-name cache's record for `guid` as a getter reads it now (`0x55f080` on a valid - /// node), reading only: `None` for a miss, a refusal, and from a host that reads none. - fn player_name(&mut self, guid: u64) -> Option { - let _ = guid; - None - } - /// Hand `read` the unit object the engine holds under `guid`, as a getter reads it now: its /// descriptor's own fields, each derived as it is asked for, as of the place the getter runs /// (`UnitHealth` reads the object, `0x5174d0`). Whether there was one to hand: `false` when it diff --git a/crates/benilla-ui/src/script/mod.rs b/crates/benilla-ui/src/script/mod.rs index 6c6a8928f..228b4936e 100644 --- a/crates/benilla-ui/src/script/mod.rs +++ b/crates/benilla-ui/src/script/mod.rs @@ -426,8 +426,9 @@ pub use types::{ pub use unit::by_name::{self, NameCandidate, SeatedSelection}; pub use unit::{ grey_band, level_reads_unknown, parse_unit_token, power_token, resolve_unit_in, unit_is_grey, - PlayerRecord, SelectionRequest, UnitBase, UnitGuids, UnitIdentityRead, UnitObject, - UnitObjectRead, UnitRelations, UnitState, UnitTokenGlobals, UnitTokenObjects, UnitTokenParse, + PlayerNameQuery, PlayerRecord, SelectionRequest, UnitBase, UnitGuids, UnitIdentityRead, + UnitObject, UnitObjectRead, UnitRecord, UnitRecordQuery, UnitRelations, UnitState, + UnitTokenGlobals, UnitTokenObjects, UnitTokenParse, }; pub use weapon_enchant::WeaponEnchant; pub use who_sort::{WhoSortChain, WhoSortKey}; diff --git a/crates/benilla-ui/src/script/pvp/mod.rs b/crates/benilla-ui/src/script/pvp/mod.rs index 5dfb38db5..d285556de 100644 --- a/crates/benilla-ui/src/script/pvp/mod.rs +++ b/crates/benilla-ui/src/script/pvp/mod.rs @@ -19,7 +19,7 @@ use mlua::{Lua, MultiValue, Value}; use super::binding_abi::{number_arg, string_arg}; -use super::unit::{check_unit_token, is_civilian_kill}; +use super::unit::{check_unit_token, is_civilian_kill, read_identity, read_record, unknownobject}; use super::Model; /// The local player's honor snapshot, decoded by the app from the private honor descriptor @@ -517,8 +517,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { // B else a unit passing the civilian predicate (`0x612550`): `PVP_RANK_CIVILIAN`, a space // and the name. Only creatures reach it. // C else the plain name. - // No snapshot, no object (the unit lookup `0x517309`, typemask 8, finds none and pushes nil - // at `0x51733e`) or an unresolved name answers nil. + // No snapshot or no object (the unit lookup `0x517309`, typemask 8, finds none and pushes nil + // at `0x51733e`) answers nil. A held unit whose name is not cached yet is built from + // `UNKNOWNOBJECT` (`0x609210` returns it on a miss, `0x609324`-`0x60933c`; `0x5172b0` always + // pushes the buffer), and the miss asks the name cache with its callback (`0x55f080`, + // `0x5fb840`) as `UnitName`'s does. // // Deviation: a token resolving to guid 0 answers nil too. The reference jumps from the guid // test (`0x5172f6`) to `return 1` (`0x517343`) with nothing pushed, so the one value is its @@ -542,12 +545,19 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { model.player_req.level, ) }; - let Some(u) = unit.filter(|u| u.has_object) else { + let Some(mut u) = unit.filter(|u| u.has_object) else { return Ok(Value::Nil); }; - let Some(name) = u.name.clone() else { - return Ok(Value::Nil); + // The name (`GetUnitName`, `0x609210`) and the civilian leg (`0x612550`) are read off + // the name caches as the call runs, the snapshot's only with no host free to ask. + let tok = token.as_deref().unwrap_or_default(); + let name = match read_identity(lua, tok, |_, id| id.name()).flatten() { + Some(name) => name, + None => unknownobject(lua)?.to_str()?.to_string(), }; + if let Some(civilian) = read_record(lua, tok, |_, r| r.civilian) { + u.civilian = civilian; + } let decorated = pvp_name(lua, &u, &name, player_level); Ok(Value::String(lua.create_string(&decorated)?)) })?, diff --git a/crates/benilla-ui/src/script/pvp/tests.rs b/crates/benilla-ui/src/script/pvp/tests.rs index 74b489aa5..6bbca6cb8 100644 --- a/crates/benilla-ui/src/script/pvp/tests.rs +++ b/crates/benilla-ui/src/script/pvp/tests.rs @@ -873,10 +873,19 @@ fn unit_pvp_name_decorates_a_ranked_player_and_falls_back_three_ways() { ..Default::default() }), ); - assert!( - s.eval::(r#"return UnitPVPName("mouseover") == nil"#) + // `0x609210` returns UNKNOWNOBJECT on a miss (`0x609324`-`0x60933c`), and `0x5172b0` pushes + // the buffer: the held unit's name is the unknown object's until the cache answers. + assert_eq!( + s.eval::(r#"return UnitPVPName("mouseover")"#) .unwrap(), - "a snapshot whose name has not resolved is nil, not an empty decoration" + "Unknown Being", + "a held unit whose name has not resolved reads the unknown object" + ); + s.run(r#"UNKNOWNOBJECT = "Unknown""#).unwrap(); + assert_eq!( + s.eval::(r#"return UnitPVPName("mouseover")"#) + .unwrap(), + "Unknown" ); assert!(s.eval::("return UnitPVPName()").is_err()); } diff --git a/crates/benilla-ui/src/script/unit/bindings.rs b/crates/benilla-ui/src/script/unit/bindings.rs index 182f14908..d989f3658 100644 --- a/crates/benilla-ui/src/script/unit/bindings.rs +++ b/crates/benilla-ui/src/script/unit/bindings.rs @@ -13,8 +13,8 @@ use super::super::stat_read::read_self; use super::super::Model; use super::{ check_unit_token, classification_word, grey_band, level_is_hidden_at, names_self, - object_predicate, read_identity, read_object, unit_is_grey, unit_predicate, unknownobject, - with_object, with_unit, PlayerRecord, SelectionRequest, + object_predicate, read_identity, read_object, read_record, unit_is_grey, unit_predicate, + unknownobject, with_object, with_unit, PlayerRecord, SelectionRequest, }; /// The `"player"` fast path of `UnitName`, `UnitRace`, `UnitClass` and `UnitSex`, never @@ -204,10 +204,15 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { .expect("model app_data") .player_req .level; + // The rank is the creature record's, read off the name cache as the call runs. + let rank = token + .as_deref() + .and_then(|t| read_record(lua, t, |_, r| r.rank)) + .unwrap_or(0); let Some((hidden, level, has_object, guid)) = token.as_deref().and_then(|t| { read_object(lua, t, |u, o| { let level = o.level(); - let hidden = level_is_hidden_at(u, level, player_level); + let hidden = level_is_hidden_at(u, level, rank, player_level); (hidden, level, u.has_object, u.guid) }) }) else { @@ -338,9 +343,12 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { .expect("model app_data") .player_req .level; + // The record's civilian flag is read off the name cache as the call runs. Ok(flag(unit.is_some_and(|t| { - read_object(lua, &t, |u, o| super::civilian_kill_of(u, o, player_level)) - == Some(true) + let civilian = read_record(lua, &t, |_, r| r.civilian).unwrap_or(false); + read_object(lua, &t, |u, o| { + super::civilian_kill_of(u, civilian, o, player_level) + }) == Some(true) }))) })?, )?; @@ -750,7 +758,11 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { Value::Number(_) | Value::Integer(_) => Some(String::new()), _ => return Err(mlua::Error::runtime("Usage: UnitCreatureType(\"unit\")")), }; - let word = with_unit(lua, &token, None, |u| u.creature_type_name.clone())?; + check_unit_token(&token)?; + let word = token + .as_deref() + .and_then(|t| read_record(lua, t, |_, r| r.creature_type.clone())) + .flatten(); match word { Some(w) => Ok(Value::String(lua.create_string(&w)?)), None => Ok(Value::Nil), @@ -763,7 +775,11 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { g.set( "UnitClassification", lua.create_function(|lua, token: Option| { - let rank = with_unit(lua, &token, 0u32, |u| u.rank)?; + check_unit_token(&token)?; + let rank = token + .as_deref() + .and_then(|t| read_record(lua, t, |_, r| r.rank)) + .unwrap_or(0); Ok(classification_word(rank).to_string()) })?, )?; diff --git a/crates/benilla-ui/src/script/unit/mod.rs b/crates/benilla-ui/src/script/unit/mod.rs index d3c4fddaf..0e32e4778 100644 --- a/crates/benilla-ui/src/script/unit/mod.rs +++ b/crates/benilla-ui/src/script/unit/mod.rs @@ -272,12 +272,18 @@ pub fn unit_is_grey(player_level: u32, unit_level: u32) -> bool { /// `UnitReaction` <= 2 here) and grey to it (`0x5f0700`, `0x6125a6`). The tooltip's CIVILIAN line /// and `UnitPVPName`'s civilian prefix (`0x609370`) both read it. pub fn is_civilian_kill(u: &UnitState, player_level: u32) -> bool { - civilian_kill_of(u, u, player_level) + civilian_kill_of(u, u.civilian, u, player_level) } -/// [`is_civilian_kill`] with the PvP flag and the level off `object`. -fn civilian_kill_of(u: &UnitState, object: &dyn UnitObjectRead, player_level: u32) -> bool { - u.civilian +/// [`is_civilian_kill`] with the record's civilian flag as given, and the PvP flag and the level +/// off `object`. +fn civilian_kill_of( + u: &UnitState, + civilian: bool, + object: &dyn UnitObjectRead, + player_level: u32, +) -> bool { + civilian && object.pvp() && u.reaction != 0 && u.reaction <= 2 @@ -294,14 +300,15 @@ pub fn level_reads_unknown(u: &UnitState, player_level: u32) -> bool { /// `UnitReaction` <= 2 here) at least 10 levels above the player, players among them, since /// neither path tests the unit's type; and world-boss rank 3 (`0x51807d`-`0x518087`, `0x52a373`). pub fn level_is_hidden(u: &UnitState, player_level: u32) -> bool { - level_is_hidden_at(u, u.level, player_level) + level_is_hidden_at(u, u.level, u.rank, player_level) } -/// [`level_is_hidden`] at `level`, the one read off the unit's object. -fn level_is_hidden_at(u: &UnitState, level: u32, player_level: u32) -> bool { +/// [`level_is_hidden`] at `level`, the one read off the unit's object, and `rank`, the one read +/// off its creature record. +fn level_is_hidden_at(u: &UnitState, level: u32, rank: u32, player_level: u32) -> bool { let much_higher_hostile = u.reaction != 0 && u.reaction <= 2 && level >= player_level.saturating_add(10); - u.rank == 3 || much_higher_hostile + rank == 3 || much_higher_hostile } /// The level a drunk player sees on a unit it can attack, the unit tooltip's arithmetic @@ -772,6 +779,7 @@ pub mod by_name; #[cfg(test)] mod chain_tests; mod object; +mod record; mod relations; mod resolve; #[cfg(test)] @@ -780,6 +788,8 @@ mod selection_tests; mod tests; pub use object::{UnitIdentityRead, UnitObject, UnitObjectRead}; +pub(crate) use record::read_record; +pub use record::{PlayerNameQuery, UnitRecord, UnitRecordQuery}; pub use relations::UnitRelations; pub use resolve::{ bound_tokens_in, field_watchers_in, parse_unit_token, resolve_unit_in, tokens_in, UnitBase, diff --git a/crates/benilla-ui/src/script/unit/record.rs b/crates/benilla-ui/src/script/unit/record.rs new file mode 100644 index 000000000..466c87605 --- /dev/null +++ b/crates/benilla-ui/src/script/unit/record.rs @@ -0,0 +1,70 @@ +//! The name caches' reads at the call. A getter that names a unit or reads its creature record +//! asks the lent host ([`crate::script::live::ask`]) and reads the caches as they stand where it +//! runs: `UnitName` names a unit through `GetUnitName` (`0x609210`) and `UnitCreatureType`, +//! `UnitClassification`, `UnitLevel`'s world-boss leg and the civilian gate read the unit's cached +//! creature record (`[unit+0xb30]`, `0x605570`, `0x605620`, `0x612550`). With no host free to ask, +//! the frame's snapshot answers. + +use mlua::Lua; + +use super::{view, UnitState}; +use crate::script::live::{ask, LiveQuery}; +use crate::script::Model; + +/// The player-name cache's record for a guid as a getter reads it, reading only (`0x55f080` on a +/// valid node): the answer is `None` for a miss and a refusal, and the query itself is declined +/// (no answer) with no cache to ask. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlayerNameQuery(pub u64); + +impl LiveQuery for PlayerNameQuery { + type Answer = Option; +} + +/// The creature-record legs of the unit object held under a guid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UnitRecordQuery(pub u64); + +impl LiveQuery for UnitRecordQuery { + type Answer = UnitRecord; +} + +/// What the unit getters read of a unit's creature record, as of the place they run. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UnitRecord { + /// [`UnitState::creature_type_name`]. + pub creature_type: Option, + /// [`UnitState::rank`]: the gated rank (`0x605620`). + pub rank: u32, + /// [`UnitState::civilian`]. + pub civilian: bool, +} + +impl UnitRecord { + /// The record legs a snapshot holds as its build read them. + fn of_snapshot(unit: &UnitState) -> Self { + UnitRecord { + creature_type: unit.creature_type_name.clone(), + rank: unit.rank, + civilian: unit.civilian, + } + } +} + +/// The unit `token` names, mapped through `f` with its snapshot and its creature record; `None` +/// for no unit. The token resolves at the call ([`view`]); a held unit's record legs are read off +/// the name caches through the lent host, so a record that landed after the frame's push, or for a +/// unit no snapshot holds, answers; with no host free to ask, or no object held, the snapshot does. +pub(crate) fn read_record( + lua: &Lua, + token: &str, + f: impl FnOnce(&UnitState, &UnitRecord) -> T, +) -> Option { + let model = lua.app_data_ref::().expect("model app_data"); + let unit = view(lua, &model, token)?; + let live = (unit.has_object && unit.guid != 0) + .then(|| ask(lua, &UnitRecordQuery(unit.guid))) + .flatten(); + let record = live.unwrap_or_else(|| UnitRecord::of_snapshot(&unit)); + Some(f(&unit, &record)) +} diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index e5bd56ec4..defadd52f 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -170,7 +170,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### names -- For a guid it does not hold, the reference's combat-log namer (`0x6264e0`) asks the creature cache under guid bits 32-47 (`0x6265c4`-`0x6265e0`) for every guid whose top nibble is 0xf and whose bits 32-47 are nonzero, a game object's and a pet's included, and never the pet-name cache (only a held unit reaches it, `0x6092c7`). ([`src/names.rs:132`](../crates/benilla-app/src/names.rs#L132)) +- For a guid it does not hold, the reference's combat-log namer (`0x6264e0`) asks the creature cache under guid bits 32-47 (`0x6265c4`-`0x6265e0`) for every guid whose top nibble is 0xf and whose bits 32-47 are nonzero, a game object's and a pet's included, and never the pet-name cache (only a held unit reaches it, `0x6092c7`). ([`src/names.rs:135`](../crates/benilla-app/src/names.rs#L135)) #### net @@ -761,16 +761,16 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - A listing that finds no icon stays empty, to be listed again on the next ask, where the reference's dedup then reads below its null list (`0x4f0134`-`0x4f0145`) and faults. ([`src/script/macros.rs:534`](../crates/benilla-ui/src/script/macros.rs#L534)) - Each line is trimmed, because the reference sends an indented `" /say hi"` as plain chat, never as the command meant. ([`src/script/macros/bind.rs:30`](../crates/benilla-ui/src/script/macros/bind.rs#L30)) - The `/cast` argument is trimmed, because the reference binds `/cast Fireball` (two spaces) to a name that never resolves. ([`src/script/macros/bind.rs:50`](../crates/benilla-ui/src/script/macros/bind.rs#L50)) -- The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:931`](../crates/benilla-ui/src/script/mod.rs#L931)) -- The reference sets the cells only when glue or the interface is built, `0x41ad10` from `0x46a828` (`0x46a7b0`) and `0x48fe2b` (`0x48fbf0`), and a resize reaches them only through the rebuild it asks for. ([`src/script/mod.rs:982`](../crates/benilla-ui/src/script/mod.rs#L982)) +- The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:932`](../crates/benilla-ui/src/script/mod.rs#L932)) +- The reference sets the cells only when glue or the interface is built, `0x41ad10` from `0x46a828` (`0x46a7b0`) and `0x48fe2b` (`0x48fbf0`), and a resize reaches them only through the rebuild it asks for. ([`src/script/mod.rs:983`](../crates/benilla-ui/src/script/mod.rs#L983)) - A path that does not resolve is stored, where the reference raises `Invalid model file: %s` (`0x878b44`), because the file loads asynchronously here and the call cannot know yet. ([`src/script/modelframe.rs:339`](../crates/benilla-ui/src/script/modelframe.rs#L339)) - The reference's free list is FIFO; either keeps every index stable, all an addon can observe. ([`src/script/nameplate.rs:455`](../crates/benilla-ui/src/script/nameplate.rs#L455)) - The reference adds this rim over the bar; we brighten the bar (`LIT_BOOST`), because the rim reads as hard edge lines in our linear-blending pipeline. ([`src/script/nameplate.rs:911`](../crates/benilla-ui/src/script/nameplate.rs#L911)) - A wrapper that decodes to no live widget takes `default_parent`, because the reference, with no `IsA` check, reads a wild pointer. ([`src/script/object/anchor_args.rs:159`](../crates/benilla-ui/src/script/object/anchor_args.rs#L159)) - An `OnSizeChanged` that resolve produces fires at the next `UiScript::resolve`, because a Lua handler must not run in the middle of a level compaction. ([`src/script/object/toplevel.rs:74`](../crates/benilla-ui/src/script/object/toplevel.rs#L74)) - A third `%s` gets an empty string, because the reference pushes two varargs (`0x6093f2 add esp,0x14`) and would read uninitialised stack. ([`src/script/pvp/mod.rs:277`](../crates/benilla-ui/src/script/pvp/mod.rs#L277)) -- A token resolving to guid 0 answers nil too. The reference jumps from the guid test (`0x5172f6`) to `return 1` (`0x517343`) with nothing pushed, so the one value is its top argument, the token it read (`0x5172e6`); that is a stack quirk, not an answer. ([`src/script/pvp/mod.rs:523`](../crates/benilla-ui/src/script/pvp/mod.rs#L523)) -- With `UNIT_PVP_NAME` or the title missing from `_G` (no install) this answers the plain name, where the reference would format an empty string, because the decoration is install data. ([`src/script/pvp/mod.rs:527`](../crates/benilla-ui/src/script/pvp/mod.rs#L527)) +- A token resolving to guid 0 answers nil too. The reference jumps from the guid test (`0x5172f6`) to `return 1` (`0x517343`) with nothing pushed, so the one value is its top argument, the token it read (`0x5172e6`); that is a stack quirk, not an answer. ([`src/script/pvp/mod.rs:526`](../crates/benilla-ui/src/script/pvp/mod.rs#L526)) +- With `UNIT_PVP_NAME` or the title missing from `_G` (no install) this answers the plain name, where the reference would format an empty string, because the decoration is install data. ([`src/script/pvp/mod.rs:530`](../crates/benilla-ui/src/script/pvp/mod.rs#L530)) - An in-flight name reads `...`, where the reference's reads `" "` (`0x82ee00`), because a blank looks like a nameless objective. ([`src/script/quest_log.rs:54`](../crates/benilla-ui/src/script/quest_log.rs#L54)) - One signal per missed record, where the reference runs every callback of every miss as its record lands (creatures in `0x556e20` at `0x556f91`, items in `0x55bc70` via `0x55bdb0` from `0x555140`; `0x4e07ea`, `0x4e083a`), 2^k - 1 updates for a walking handler over k first-seen records. ([`src/script/quest_log.rs:1105`](../crates/benilla-ui/src/script/quest_log.rs#L1105)) - A local clock step mid-session (an NTP correction) jumps the reference's countdown but not ours, because the step changes no time the quest has left. ([`src/script/quest_log.rs:1160`](../crates/benilla-ui/src/script/quest_log.rs#L1160)) @@ -804,7 +804,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - A header clears it too, because it has no spell id; the reference stores its `0xffffffff` (`0x4d7b05`) and reads back 1, which the stock window's `> 1` test treats the same as 0. ([`src/script/trainer/mod.rs:1224`](../crates/benilla-ui/src/script/trainer/mod.rs#L1224)) - Index 0 is a no-op, because one stray call would spend the purse; the reference buys every visible service for any index at or below 0 (`0x4da244`, `0x4d8a70`). ([`src/script/trainer/mod.rs:1248`](../crates/benilla-ui/src/script/trainer/mod.rs#L1248)) - Kept apart from `Self::vertex_color`, which the reference's `Texture:SetAlpha` (`0x79b580`) rewrites, because the drawn product differs only on a region that sets both, or a gradient and an alpha, which no stock code does, and a FontString's `SetAlpha` then keeps its font colour. ([`src/script/types.rs:428`](../crates/benilla-ui/src/script/types.rs#L428)) -- Among whole-name matches ours picks the nearest, because the reference's first-walked pick is order-dependent and reads as a bug. ([`src/script/unit/bindings.rs:1013`](../crates/benilla-ui/src/script/unit/bindings.rs#L1013)) +- Among whole-name matches ours picks the nearest, because the reference's first-walked pick is order-dependent and reads as a bug. ([`src/script/unit/bindings.rs:1029`](../crates/benilla-ui/src/script/unit/bindings.rs#L1029)) - The reference's matcher takes a whole-string hit at once only when it is nearer than the best so far (`0x493c88`-`0x493ca2`); an exact hit that is not nearer competes on prefix length alone (`0x493cf8`-`0x493d09`), so a nearer "Bobby" walked first beats an exact "Bob", and the pick follows the object list's order. ([`src/script/unit/by_name.rs:19`](../crates/benilla-ui/src/script/unit/by_name.rs#L19)) - A full tie goes to the lower guid, where the reference keeps the first unit its walk (`0x493aa0`) reaches, an order neither of ours has; a guid keeps the two picks equal. ([`src/script/unit/by_name.rs:61`](../crates/benilla-ui/src/script/unit/by_name.rs#L61)) - `0x4e81d0` has no bound and reads past its four-entry table, which is stale memory, not a mechanism; past it, nobody. ([`src/script/unit/resolve.rs:83`](../crates/benilla-ui/src/script/unit/resolve.rs#L83))