diff --git a/crates/benilla-app/src/combat_log/chat.rs b/crates/benilla-app/src/combat_log/chat.rs index ebbb17926..7bd6bf4b8 100644 --- a/crates/benilla-app/src/combat_log/chat.rs +++ b/crates/benilla-app/src/combat_log/chat.rs @@ -41,6 +41,10 @@ pub(crate) struct ChatCtx<'a> { pub skill_lines: Option<&'a benilla_formats::SkillLineCatalog>, /// `SpellItemEnchantment.dbc` (`0xc0d7d8`), which the enchantment lines name. pub enchants: Option<&'a benilla_formats::EnchantCatalog>, + /// The item cache (`0xc0e2a0`), which `LogOpenLock` reads for an opened item. + pub items: Option<&'a crate::items::Items>, + /// The game object cache (`0xc0e318`), which `LogOpenLock` reads for an opened object. + pub gameobjects: Option<&'a crate::go_templates::GameObjectTemplates>, /// The display ranges: the reference's `0x8629e0` table, CVar-backed. pub ranges: &'a combat::CombatLogRanges, /// `CombatLogPeriodicSpells`, for its two chat-only read sites; the whole-packet gate is in @@ -84,6 +88,25 @@ impl ChatCtx<'_> { combat::logged_spell(self.spells, spell_id).map(|d| d.name.clone()) } + /// The record name `LogOpenLock` writes for what a lock opened (`0x62dcb9`-`0x62ddb6`): an + /// item's, by its entry in the item cache, tested first (type bit 1); else a game object's, by + /// its entry in the game object cache (bit 5). `None` for any other object, one not held and + /// one with no cached record. + fn opened_name(&self, guid: u64, stores: &impl Stores) -> Option { + let fields = &self.index.0.get(&guid).and_then(|&e| stores.store(e))?.0; + if fields.is_item() { + let entry = fields.object_entry()?; + let item = self + .items? + .template(entry, 0, crate::query_cache::Ask::Read)?; + return Some(item.name.clone()); + } + if fields.object_type() == Some(benilla_protocol::messages::ObjectType::GameObject) { + return Some(self.gameobjects?.of(fields)?.name.clone()); + } + None + } + /// `0x6ea280 == 2`, "this spell targets enemies": the predicate the chat-type stubs /// `0x627d30`/`0x627d60` use to choose a family's `…_DAMAGE` or `…_BUFF` row. A spell the /// catalog does not know reads as harmful, keeping the `…_DAMAGE` row. @@ -444,9 +467,6 @@ pub(super) fn enchantment_log( /// effect id through the index table `0x5e845c` and the jump table `0x5e8430`. An effect with no /// arm of its own takes the cast line [`spell_cast_line`] once per row, with no target /// (`0x5e83e3`); so does a packet whose one group is a row-less effect 3 (`0x5e8004`-`0x5e8034`). -/// -/// Not built: effects 33 and 59 `OPEN_LOCK` (its `%s` is a gameobject name, and there is no -/// gameobject-name cache). pub(super) fn spell_log_execute( s: &SpellLogExecute, ctx: &ChatCtx, @@ -505,15 +525,17 @@ pub(super) fn spell_log_execute( ); } // Effect 19 ADD_EXTRA_ATTACKS: no caster in the sentence (`0x62d9f0`), only the - // unit that gained the attacks, worded `EXTRA_ATTACKS` with the count when that is - // you (`0x62db7d`-`0x62dba9`); a count of 0 writes neither (`0x62da2a`). + // unit that gained the attacks, typed by the spell's hostility (`0x62b190`, from + // `0x62db78`) and worded `EXTRA_ATTACKS` with the count when that is you + // (`0x62db7d`-`0x62dba9`); a count of 0 writes neither (`0x62da2a`). E::ExtraAttacks { target, count } => { if count == 0 { continue; } let Some(spell) = spell() else { continue }; let victim = ctx.classify(target, stores); - let Some(kind) = combat::spell_kind(victim, victim, false) else { + let buff = !ctx.spell_harmful(s.spell_id); + let Some(kind) = combat::spell_kind(victim, victim, buff) else { continue; }; queue_worded( @@ -657,9 +679,20 @@ pub(super) fn spell_log_execute( E::Target { target } if cast_names_target(*_effect) => { cast_line(log, Some(target)); } - // Effects 33 and 59 OPEN_LOCK (`0x5e82b2`), not built. - E::Target { .. } - if matches!(*_effect, EFFECT_OPEN_LOCK | EFFECT_OPEN_LOCK_ITEM) => {} + // Effects 33 and 59 OPEN_LOCK (`0x5e82b2`): [`open_lock_line`]. + E::Target { target } + if matches!(*_effect, EFFECT_OPEN_LOCK | EFFECT_OPEN_LOCK_ITEM) => + { + open_lock_line( + log, + ctx, + stores, + poses, + s.spell_id, + (s.caster, caster), + target, + ); + } // The default arm, which reads nothing of the row: heals and energizes, which are // worded from their own packets, the summons and the rest. E::Heal { .. } | E::Energize { .. } | E::Target { .. } => cast_line(log, None), @@ -686,6 +719,50 @@ fn cast_names_target(effect: u32) -> bool { ) } +/// `LogOpenLock` (`0x62dc10`), the line for `SMSG_SPELLLOGEXECUTE`'s effects 33 and 59: "You perform +/// Pick Lock on Copper Vein." After the spell gates, the caster must be held as a unit within its +/// class's range (`0x628010`). The target must be a held item with a record in the item cache +/// (`0x62dce2`) or a held game object with one in the game object cache (`0x62ddac`), read +/// without asking; the line names its record. `OPEN_LOCK_SELF` or `OPEN_LOCK_OTHER` on the +/// caster, typed by the caster against itself through the spell's hostility (`0x627d30`). No word +/// follows. +fn open_lock_line( + log: &mut ChatLog, + ctx: &ChatCtx, + stores: &impl Stores, + poses: &impl Poses, + spell_id: u32, + caster: (u64, UnitClass), + target: u64, +) { + let Some(spell) = ctx.spell_name(spell_id) else { + return; + }; + if !ctx.holds_unit(caster.0, stores) { + return; + } + let Some(opened) = ctx.opened_name(target, stores) else { + return; + }; + let Some(kind) = combat::spell_kind(caster.1, caster.1, !ctx.spell_harmful(spell_id)) else { + return; + }; + queue( + log, + ctx, + poses, + kind, + combat::OPEN_LOCK, + caster, + caster, + Fills { + spell, + named: opened, + ..Default::default() + }, + ); +} + /// `SPELL_ATTR_IS_ABILITY` (vmangos `SpellDefines.h:796`): the cast line says "performs" (`0x62aff0`). const ATTR_IS_ABILITY: u32 = 0x10; diff --git a/crates/benilla-app/src/combat_log/chat/spell.rs b/crates/benilla-app/src/combat_log/chat/spell.rs index c5119555f..f54920303 100644 --- a/crates/benilla-app/src/combat_log/chat/spell.rs +++ b/crates/benilla-app/src/combat_log/chat/spell.rs @@ -52,9 +52,12 @@ fn spell_damage_line( // Split damage (`hit_info & 8`, to `0x62de60`) is tested first, before the periodic split: it // reads "%s's %s causes %s %d damage.", has no `…SELFSELF` key and no trailers, and words the - // split amount to its target (`0x62dfd9`). + // split amount to its target (`0x62dfd9`). The form with you as the source of another unit's + // damage is typed by the buff table (`0x627820`, from `0x62df92`); the other two by the damage + // table (`0x626be0`, from `0x62df69` and `0x62dfc4`). if s.hit_info & SPELL_HIT_TYPE_SPLIT != 0 { - let Some(kind) = combat::spell_kind(attacker, victim, false) else { + let buff = attacker == UnitClass::Me && victim != UnitClass::Me; + let Some(kind) = combat::spell_kind(attacker, victim, buff) else { return; }; return queue_worded( diff --git a/crates/benilla-app/src/combat_log/chat/tests.rs b/crates/benilla-app/src/combat_log/chat/tests.rs index 4c1ccc1f3..00d7de196 100644 --- a/crates/benilla-app/src/combat_log/chat/tests.rs +++ b/crates/benilla-app/src/combat_log/chat/tests.rs @@ -47,6 +47,8 @@ fn a_spell_with_no_record_writes_no_line() { names: None, skill_lines: None, enchants: None, + items: None, + gameobjects: None, ranges: &ranges, periodic: true, }; @@ -117,6 +119,7 @@ mod emitters { use super::super::ChatCtx; + mod lines; mod words; const ME: u64 = 1; @@ -139,6 +142,8 @@ mod emitters { const HIDDEN: u32 = 20_001; /// `Attributes & 0x80` alone: no line, but its `UNIT_COMBAT` fires. const UNDISPLAYED: u32 = 20_002; + /// `Targets & 0x80`, the enemy flag: `GetSpellHostility` answers 2. + const HOSTILE: u32 = 20_003; /// Fireball with no duration row, the two heals with theirs, and the casts. fn spells() -> crate::ui_action::Spells { @@ -185,6 +190,15 @@ mod emitters { cast(PICK_LOCK, "Pick Lock", 0, 0, 33), cast(HIDDEN, "Hidden", 0x100, 0, 0), cast(UNDISPLAYED, "Undisplayed", 0x80, 0, 0), + ( + HOSTILE, + benilla_formats::SpellDisplay { + id: HOSTILE, + name: "Venom".into(), + targets: 0x80, + ..Default::default() + }, + ), ] .into_iter() .collect(), @@ -214,6 +228,8 @@ mod emitters { factions: Factions, spells: crate::ui_action::Spells, enchants: benilla_formats::EnchantCatalog, + items: crate::items::Items, + gameobjects: crate::go_templates::GameObjectTemplates, } impl Bench { @@ -229,6 +245,8 @@ mod emitters { [(CRUSADER, "Crusader".to_string())].into(), [(CRUSADER, 0), (ROCKBITER, 0x2)].into(), ), + items: crate::items::Items::default(), + gameobjects: crate::go_templates::GameObjectTemplates::default(), }; bench.hold(&player(ME, HUMAN)); bench.hold(&creature(MOB, ORC)); @@ -294,6 +312,8 @@ mod emitters { names: None, skill_lines: None, enchants: Some(&self.enchants), + items: Some(&self.items), + gameobjects: Some(&self.gameobjects), ranges: &ranges, periodic: true, }; diff --git a/crates/benilla-app/src/combat_log/chat/tests/emitters/lines.rs b/crates/benilla-app/src/combat_log/chat/tests/emitters/lines.rs new file mode 100644 index 000000000..0cd68be0c --- /dev/null +++ b/crates/benilla-app/src/combat_log/chat/tests/emitters/lines.rs @@ -0,0 +1,172 @@ +//! The chat type of the split-damage and extra-attack lines, and the open-lock line. + +use benilla_protocol::field::FIELD_OBJECT_ENTRY; +use benilla_protocol::messages::{ExecuteLog, SpellDamageLog, SpellLogExecute}; + +use super::{ + execute, row, spell_hit, stems, words, Bench, CLEANSE, FIREBALL, HIDDEN, HOSTILE, ME, MOB, ORC, + PICK_LOCK, UNDISPLAYED, +}; +use crate::net::ObjectStore; +use crate::target::relations::fixture::creature; +use crate::ui_chat::combat::PendingCombat; +use crate::ui_chat::ChatEventKind as K; + +fn kinds(lines: &[PendingCombat]) -> Vec { + lines.iter().map(|l| l.kind).collect() +} + +/// `0x62de60` picks its chat type by the line's form (`0x62e000`): you as the source of another +/// unit's damage (`SELFOTHER`) goes through the buff table `0x627820` (`0x62df92`), whose row for +/// a source of class 0 is `SPELL_SELF_BUFF`; the other two forms go through the damage table +/// `0x626be0` (`0x62df69`, `0x62dfc4`). +#[test] +fn split_damage_you_cause_is_typed_as_a_buff() { + const OTHER: u64 = 3; + let split = |attacker, target| { + let mut bench = Bench::new(); + bench.hold(&creature(OTHER, ORC)); + let s = SpellDamageLog { + attacker, + target, + hit_info: 0x8, + ..spell_hit(120, 0, 0, 0) + }; + bench.lines(|ctx, st, po, log| super::super::super::spell_damage_log(s, ctx, st, po, log)) + }; + let mine = split(ME, MOB); + assert_eq!(stems(&mine), ["SPELLSPLITDAMAGE"]); + assert_eq!(kinds(&mine), [K::SpellSelfBuff]); + assert_eq!(kinds(&split(MOB, ME)), [K::SpellCreatureVsSelfDamage]); + assert_eq!( + kinds(&split(MOB, OTHER)), + [K::SpellCreatureVsCreatureDamage] + ); +} + +/// `0x62d9f0` types its line with `0x62b190` (`0x62db78`): the damage table for a spell +/// `GetSpellHostility` (`0x6ea280`) calls hostile, else the buff table, so a self-targeted +/// extra-attack proc is `SPELL_SELF_BUFF`. +#[test] +fn extra_attacks_are_typed_by_the_spells_hostility() { + let extra = |spell_id, unit| { + execute( + spell_id, + unit, + vec![( + 19, + vec![ExecuteLog::ExtraAttacks { + target: unit, + count: 1, + }], + )], + ) + }; + assert_eq!(kinds(&extra(FIREBALL, ME)), [K::SpellSelfBuff]); + assert_eq!(kinds(&extra(HOSTILE, ME)), [K::SpellSelfDamage]); + assert_eq!( + kinds(&extra(FIREBALL, MOB)), + [K::SpellCreatureVsCreatureBuff] + ); + assert_eq!( + kinds(&extra(HOSTILE, MOB)), + [K::SpellCreatureVsCreatureDamage] + ); +} + +const CHEST: u64 = 0xf110_0000_0000_0007; +const JUNKBOX: u64 = 0x4000_0000_0000_0042; +const CHEST_ENTRY: u32 = 1731; +const JUNKBOX_ENTRY: u32 = 2589; +/// `Effect` 59, `OPEN_LOCK_ITEM`. +const OPEN_LOCK_ITEM: u32 = 59; + +/// A bench holding a chest, a game object whose template is cached, and a junkbox, an item +/// whose template is. +fn lock_bench() -> Bench { + let mut bench = Bench::new(); + for (guid, mask, entry) in [(CHEST, 0x21, CHEST_ENTRY), (JUNKBOX, 0x3, JUNKBOX_ENTRY)] { + let e = bench.world.spawn_empty().id(); + bench.index.0.insert(guid, e); + bench.stores.insert( + e, + ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[ + // `OBJECT_FIELD_TYPE`. + (2, mask), + (FIELD_OBJECT_ENTRY, entry), + ])), + ); + } + bench + .gameobjects + .insert(CHEST_ENTRY, 3, "Copper Vein".into(), &[0; 24]); + bench + .items + .insert_template(JUNKBOX_ENTRY, Some(crate::items::test_template("Junkbox"))); + bench +} + +fn open(bench: &Bench, spell_id: u32, caster: u64, effect: u32, target: u64) -> Vec { + let s = SpellLogExecute { + caster, + spell_id, + effects: vec![(effect, vec![row(target)])], + }; + bench.lines(|ctx, st, po, log| super::super::super::spell_log_execute(&s, ctx, st, po, log)) +} + +/// `SMSG_SPELLLOGEXECUTE`'s effects 33 and 59 go to `LogOpenLock` (`0x62dc10`, from `0x5e82f7`), +/// which names the opened game object from the object cache (`0x62ddac`) or item from the item +/// cache (`0x62dce2`) and writes `OPEN_LOCK_SELF` or `OPEN_LOCK_OTHER`, typed by the caster against +/// itself through the spell's hostility (`0x62dd36`). +#[test] +fn opening_a_lock_names_the_opened_object_or_item() { + let bench = lock_bench(); + let chest = open(&bench, PICK_LOCK, ME, 33, CHEST); + assert_eq!(stems(&chest), ["OPEN_LOCK_"]); + assert_eq!(chest[0].fills.spell, "Pick Lock"); + assert_eq!(chest[0].fills.named, "Copper Vein"); + assert_eq!(kinds(&chest), [K::SpellSelfBuff]); + assert_eq!(words(&chest), [None], "no word follows the line"); + + let junkbox = open(&bench, PICK_LOCK, ME, OPEN_LOCK_ITEM, JUNKBOX); + assert_eq!(stems(&junkbox), ["OPEN_LOCK_"]); + assert_eq!(junkbox[0].fills.named, "Junkbox"); + + // Another unit opening it: its own type, its name in the sentence. + let theirs = open(&bench, PICK_LOCK, MOB, 33, CHEST); + assert_eq!(kinds(&theirs), [K::SpellCreatureVsCreatureBuff]); + assert_eq!(theirs[0].subject, MOB); +} + +/// `LogOpenLock` writes nothing for a target the client holds no record of (`0x62dce7`, +/// `0x62ddb1`) or holds as neither an item nor a game object (`0x62dd90`), for a caster the +/// client holds as no unit (`0x628010`), or for a spell with no record, flagged `0x180` or +/// nameless (`0x62dc35`-`0x62dc78`). +#[test] +fn opening_a_lock_needs_its_target_its_record_and_a_unit_caster() { + let mut bench = lock_bench(); + assert_eq!(open(&bench, CLEANSE, ME, 33, CHEST).len(), 1, "any spell"); + assert!(open(&bench, PICK_LOCK, ME, 33, 0xf110_0000_0000_0099).is_empty()); + assert!(open(&bench, PICK_LOCK, ME, 33, MOB).is_empty(), "a unit"); + assert!( + open(&bench, PICK_LOCK, 99, 33, CHEST).is_empty(), + "not held" + ); + assert!( + open(&bench, HIDDEN, ME, 33, CHEST).is_empty(), + "Attributes & 0x100" + ); + assert!( + open(&bench, UNDISPLAYED, ME, 33, CHEST).is_empty(), + "Attributes & 0x80" + ); + assert!(open(&bench, 24_000, ME, 33, CHEST).is_empty(), "no record"); + bench.gameobjects = crate::go_templates::GameObjectTemplates::default(); + bench.items = crate::items::Items::default(); + assert!( + open(&bench, PICK_LOCK, ME, 33, CHEST).is_empty(), + "no template" + ); + assert!(open(&bench, PICK_LOCK, ME, OPEN_LOCK_ITEM, JUNKBOX).is_empty()); +} diff --git a/crates/benilla-app/src/combat_log/death_tests.rs b/crates/benilla-app/src/combat_log/death_tests.rs new file mode 100644 index 000000000..c0320d6ec --- /dev/null +++ b/crates/benilla-app/src/combat_log/death_tests.rs @@ -0,0 +1,108 @@ +//! The death line against the XP award that replaces it: `SMSG_LOG_XPGAIN` naming a held victim +//! sets bit 3 of the unit's `+0xc58` (`0x60a0e6`), and the death line `0x62c160` skips a unit with +//! it set (`0x62c232`-`0x62c23e`). + +use benilla_protocol::field::FIELD_UNIT_HEALTH; +use benilla_protocol::messages::{ObjectType, XpGain}; +use benilla_protocol::SessionEvent; +use bevy::ecs::system::RunSystemOnce; + +use super::*; +use crate::target::relations::fixture::{creature, player, store_of, HUMAN, ORC}; +use crate::ui_chat::combat::watch::death_lines; + +const ME: u64 = 1; +const MOB: u64 = 2; +const OTHER: u64 = 3; + +/// You and two creatures held, the log empty. +fn world() -> App { + let mut app = App::new(); + app.add_message::() + .add_message::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(SelfGuid(Some(ME))) + .insert_resource(LogPeriodicSpells(true)); + for unit in [player(ME, HUMAN), creature(MOB, ORC), creature(OTHER, ORC)] { + let e = app + .world_mut() + .spawn((Guid(unit.guid), store_of(&unit))) + .id(); + app.world_mut() + .resource_mut::() + .0 + .insert(unit.guid, e); + } + app +} + +fn award(app: &mut App, victim: u64, total: u32, kill: bool) { + let packet = SessionEvent::XpGain(XpGain { + victim, + total, + base: total, + kill, + group: 1.0, + }); + app.world_mut() + .run_system_once_with(on_xp_gain, packet) + .unwrap(); +} + +/// `guid` drops from alive to dead; what lines the death watcher then parks, by key. +fn dies(app: &mut App, guid: u64) -> Vec { + let entity = app.world().resource::().0[&guid]; + app.world_mut().write_message(crate::net::FieldChanged { + entity, + guid, + kind: ObjectType::Unit, + index: FIELD_UNIT_HEALTH, + old: 40, + new: 0, + }); + app.world_mut().run_system_once(death_lines).unwrap(); + app.world() + .resource::() + .pending_combat() + .into_iter() + .map(|l| l.family.key(l.variant)) + .collect() +} + +/// A kill that awards experience prints the XP line and no death line, even a zero award +/// (`0x60a0c0` sets the bit before `0x6251e0` tests the amount); a kill that awards none, or one +/// the packet names no held unit for, prints its death line. +#[test] +fn a_kill_that_awards_experience_prints_no_death_line() { + let death = |setup: &dyn Fn(&mut App)| { + let mut app = world(); + setup(&mut app); + dies(&mut app, MOB) + }; + assert_eq!(death(&|_| {}), ["UNITDIESOTHER"], "no award"); + assert!(death(&|app| award(app, MOB, 60, true)).is_empty()); + assert!( + death(&|app| award(app, MOB, 0, true)).is_empty(), + "a zero award" + ); + assert_eq!( + death(&|app| award(app, 77, 60, true)), + ["UNITDIESOTHER"], + "a victim not held" + ); + assert_eq!( + death(&|app| award(app, 0, 60, false)), + ["UNITDIESOTHER"], + "experience that names no victim" + ); + assert_eq!( + death(&|app| award(app, OTHER, 60, true)), + ["UNITDIESOTHER"], + "another unit's award" + ); +} diff --git a/crates/benilla-app/src/combat_log/mod.rs b/crates/benilla-app/src/combat_log/mod.rs index aa05fae89..0800a5aac 100644 --- a/crates/benilla-app/src/combat_log/mod.rs +++ b/crates/benilla-app/src/combat_log/mod.rs @@ -26,6 +26,8 @@ use crate::ui_chat::combat::{CombatLogRanges, LogPeriodicSpells}; use crate::ui_chat::ChatLog; pub(crate) mod chat; +#[cfg(test)] +mod death_tests; pub(crate) mod feedback; pub(crate) mod text; @@ -72,12 +74,23 @@ impl Ctx<'_> { names: self.names.as_deref(), skill_lines: self.skill_lines.as_deref().map(|s| &s.catalog), enchants: self.enchants.as_deref().map(|e| &e.0), + items: None, + gameobjects: None, ranges: &self.ranges, periodic: self.periodic.0, } } } +/// The caches `LogOpenLock` reads (`0xc0e2a0`, `0xc0e318`). They stay out of [`Ctx`] because +/// `on_missile_miss` runs in `Update` with it, and the sound systems that write the item cache run +/// there too: a claim on a cache no line of that leg reads would only add undeclared orders. +#[derive(SystemParam)] +struct LockCaches<'w> { + items: Option>, + gameobjects: Option>, +} + /// What the two legs resolve endpoints through and write to. #[derive(SystemParam)] pub(crate) struct Sinks<'w, 's> { @@ -379,9 +392,13 @@ fn on_enchantment_log(In(ev): In, c: Ctx, mut l: Sinks) { } } -fn on_spell_log_execute(In(ev): In, c: Ctx, mut l: Sinks) { +fn on_spell_log_execute(In(ev): In, c: Ctx, caches: LockCaches, mut l: Sinks) { if let SessionEvent::SpellLogExecute(x) = ev { - let ctx = c.ctx(); + let ctx = chat::ChatCtx { + items: caches.items.as_deref(), + gameobjects: caches.gameobjects.as_deref(), + ..c.ctx() + }; chat::spell_log_execute(&x, &ctx, &l.stores, &l.poses, &mut l.log); } } @@ -393,7 +410,7 @@ fn on_environmental_damage_log(In(ev): In, c: Ctx, mut l: Sinks) { } } -fn on_xp_gain(In(ev): In, c: Ctx, mut l: Sinks) { +fn on_xp_gain(In(ev): In, c: Ctx, mut l: Sinks, mut commands: Commands) { if let SessionEvent::XpGain(x) = ev { text::xp_gain( x, @@ -402,6 +419,7 @@ fn on_xp_gain(In(ev): In, c: Ctx, mut l: Sinks) { &l.stores, &mut l.text, &mut l.log, + &mut commands, ); } } @@ -860,6 +878,7 @@ mod tests { total, base: 40, kill, + group: 1.0, }); app.world_mut() .run_system_once_with(on_xp_gain, packet) @@ -873,21 +892,24 @@ mod tests { .count(); (lines, kinds, floats) }; - assert_eq!(gain(MOB, 60, true), (vec![(MOB, 60, 40)], vec!["xp"], 1)); + assert_eq!( + gain(MOB, 60, true), + (vec![(MOB, 60, 40, 1.0)], vec!["xp"], 1) + ); assert_eq!( gain(77, 60, true), - (vec![(0, 60, 40)], vec!["xp"], 1), + (vec![(0, 60, 40, 1.0)], vec!["xp"], 1), "not held" ); assert_eq!( gain(MOB, 60, false), - (vec![(0, 60, 40)], vec!["xp"], 1), + (vec![(0, 60, 40, 1.0)], vec!["xp"], 1), "no kill" ); assert_eq!(gain(MOB, 0, true), (vec![], vec![], 0), "a zero kill"); assert_eq!( gain(0, 0, false), - (vec![(0, 0, 40)], vec!["xp"], 1), + (vec![(0, 0, 40, 1.0)], vec!["xp"], 1), "a zero award" ); assert_eq!( diff --git a/crates/benilla-app/src/combat_log/text.rs b/crates/benilla-app/src/combat_log/text.rs index 2a3cf7f24..7ee86e2d0 100644 --- a/crates/benilla-app/src/combat_log/text.rs +++ b/crates/benilla-app/src/combat_log/text.rs @@ -15,6 +15,7 @@ use benilla_protocol::messages::{ use crate::combat_text::{ damage_color, miss_word, spell_text, CombatTextSpawn, DamageSource, DamageTextGates, TextBody, }; +use crate::ui_chat::combat::watch::XpAwarded; use crate::ui_chat::{combat, ChatLog}; use crate::net::{GuidIndex, ObjectStore, SelfGuid}; @@ -302,10 +303,10 @@ pub(super) const SPELL_MISS_REFLECT: u8 = 11; /// `SMSG_LOG_XPGAIN`, as `0x637ec0` dispatches it. Your own guid as the victim is an XP loss, /// written with no float (`0x637f70`). A kill of a unit the client holds (type mask 8) is named: -/// `CGUnit_C::SetPendingXP` (`0x60a0c0`) stores it and flushes it at once through `0x6251e0`, -/// which writes and floats nothing for a zero gain (`0x625202`). Anything else is the unnamed -/// line (`0x637f90`, victim NULL). Both gains float `"XP: %d"` over self, category 4, the one -/// emitter that skips Gate A (`0x607260`). +/// `CGUnit_C::SetPendingXP` (`0x60a0c0`) marks the unit ([`XpAwarded`], `0x60a0e6`), stores the +/// gain and flushes it at once through `0x6251e0`, which writes and floats nothing for a zero +/// gain (`0x625202`). Anything else is the unnamed line (`0x637f90`, victim NULL). Both gains +/// float `"XP: %d"` over self, category 4, the one emitter that skips Gate A (`0x607260`). pub(super) fn xp_gain( x: XpGain, index: &GuidIndex, @@ -313,6 +314,7 @@ pub(super) fn xp_gain( stores: &Query<&mut ObjectStore>, text: &mut MessageWriter, chat_log: &mut ChatLog, + commands: &mut Commands, ) { // `0x468550`: the active player's guid, 0 with none. if x.victim == self_guid.0.unwrap_or(0) { @@ -331,12 +333,17 @@ pub(super) fn xp_gain( ) }); if x.kill && victim_held { + // The mark goes on before the amount is looked at (`0x60a0e6` precedes `0x625202`). + if let Some(&victim) = index.0.get(&x.victim) { + commands.entity(victim).insert(XpAwarded); + } if x.total == 0 { return; } - chat_log.push_xp_gain(x.victim, x.total, x.base); + chat_log.push_xp_gain(x.victim, x.total, x.base, x.group); } else { - chat_log.push_xp_gain(0, x.total, x.base); + // The unnamed forms never see a float (`0x637f90` passes 1.0). + chat_log.push_xp_gain(0, x.total, x.base, 1.0); } if let Some(&me) = self_guid.0.as_ref().and_then(|g| index.0.get(g)) { text.write(CombatTextSpawn { diff --git a/crates/benilla-app/src/creature_anim/impact.rs b/crates/benilla-app/src/creature_anim/impact.rs index 75124afd1..193d69414 100644 --- a/crates/benilla-app/src/creature_anim/impact.rs +++ b/crates/benilla-app/src/creature_anim/impact.rs @@ -552,7 +552,7 @@ mod tests { receive(&mut app, swing(a, Some(v), 1)); app.world_mut() .resource_mut::() - .push_xp_gain(0, 10, 10); + .push_xp_gain(0, 10, 10, 1.0); tag(&mut app, a, *b"$CAH"); assert_eq!(kinds(&app), ["xp", "unit combat"]); let flashed = app.world().resource::().pending_unit_combat(); diff --git a/crates/benilla-app/src/net/objects.rs b/crates/benilla-app/src/net/objects.rs index 29cca0569..8e8d4f189 100644 --- a/crates/benilla-app/src/net/objects.rs +++ b/crates/benilla-app/src/net/objects.rs @@ -91,6 +91,7 @@ pub(crate) struct Scene<'w, 's> { countdowns: Query<'w, 's, &'static mut crate::items::Countdowns>, remote: Query<'w, 's, &'static mut RemoteMotion>, modes: Query<'w, 's, &'static mut UnitMoveModes>, + xp_awarded: Query<'w, 's, (), With>, riders: Query<'w, 's, &'static mut crate::transport::TransportRider>, speeds: Query<'w, 's, &'static mut UnitSpeeds>, field_changes: MessageWriter<'w, FieldChanged>, diff --git a/crates/benilla-app/src/net/objects/update.rs b/crates/benilla-app/src/net/objects/update.rs index db4bc69d9..7b616f738 100644 --- a/crates/benilla-app/src/net/objects/update.rs +++ b/crates/benilla-app/src/net/objects/update.rs @@ -29,6 +29,7 @@ use super::{item_watch, object_create, object_move, CreateBlock, Landing, Scene} use crate::field_watch::{Notified, Sent}; use crate::query_cache::Ask; use crate::transport::TransportRider; +use crate::ui_chat::combat::watch::XpAwarded; use benilla_world::vis_chain::VisChainOnly; /// Registers the update packet's block handlers, its end, and `SMSG_DESTROY_OBJECT`. @@ -130,6 +131,9 @@ enum Body { speeds: Option, modes: Option, rider: Option, + /// Bit 3 of the unit's `+0xc58`, which only the constructor clears (`0x5fae7a`): the + /// object a block brings back is the one that left. + xp_awarded: bool, }, /// An item or a container, with its countdown cells. Item { @@ -269,9 +273,14 @@ fn on_object_create(In(ev): In, mut sc: Scene) { }), ) => { let moved = write_fields(&mut store, fields.clone()); - let (pose, modes) = match body { - Body::World { pose, modes, .. } => (Some(pose), modes), - Body::Item { .. } => (None, None), + let (pose, modes, xp_awarded) = match body { + Body::World { + pose, + modes, + xp_awarded, + .. + } => (Some(pose), modes, xp_awarded), + Body::Item { .. } => (None, None, false), }; // Only a unit takes the block's movement (`0x46638c`); any other type keeps its pose. let unit = matches!(kind, EntityKind::Unit | EntityKind::Player); @@ -280,6 +289,9 @@ fn on_object_create(In(ev): In, mut sc: Scene) { if let Some(modes) = modes { sc.commands.entity(e).insert(modes); } + if xp_awarded { + sc.commands.entity(e).insert(XpAwarded); + } sc.pass.reactivated.push(guid); moved } @@ -487,6 +499,7 @@ fn respawn(sc: &mut Scene, guid: u64, body: Body, store: ObjectFields, pose: Opt speeds, modes, rider, + xp_awarded, } => { let mut entity = sc.commands.spawn(( Guid(guid), @@ -510,6 +523,9 @@ fn respawn(sc: &mut Scene, guid: u64, body: Body, store: ObjectFields, pose: Opt if let Some(r) = rider { entity.insert(r); } + if xp_awarded { + entity.insert(XpAwarded); + } let e = entity.id(); sc.index.0.insert(guid, e); } @@ -627,6 +643,7 @@ fn release(sc: &mut Scene, guid: u64) { local_pos: r.local_pos, local_orientation: r.local_orientation, }), + xp_awarded: sc.xp_awarded.contains(e), } }; Some(Kept { fields, body }) diff --git a/crates/benilla-app/src/net/objects/update_tests.rs b/crates/benilla-app/src/net/objects/update_tests.rs index e15c41773..c3d9aa955 100644 --- a/crates/benilla-app/src/net/objects/update_tests.rs +++ b/crates/benilla-app/src/net/objects/update_tests.rs @@ -527,6 +527,43 @@ fn a_destroy_frees_a_released_object() { assert!(notices(world).contains(&FieldNotice::Global { id: 376 })); } +/// A block brings back the object that left (`0x464530`), not a new one, so the bit an XP award set +/// in its flags word (`0x60a0e6`), which only the constructor clears (`0x5fae7a`), is still set; +/// a unit made new after its destroy is a new object, and has none. +#[test] +fn a_released_unit_keeps_its_xp_mark() { + use crate::ui_chat::combat::watch::XpAwarded; + const OTHER: u64 = 0xF130_0000_1234_0002; + let mut app = client(); + let world = app.world_mut(); + world.resource_mut::().0 = Some(ME); + send( + world, + [unit(MOB, &[(ENTRY, 299)]), unit(OTHER, &[(ENTRY, 299)])], + ); + let marked = |world: &World, guid: u64| { + let e = world.resource::().0[&guid]; + world.get::(e).is_some() + }; + let e = world.resource::().0[&MOB]; + world.entity_mut(e).insert(XpAwarded); + + send(world, [out_of_range(&[MOB, OTHER])]); + send( + world, + [values(MOB, &[(STAT0, 6)]), values(OTHER, &[(STAT0, 6)])], + ); + assert!(marked(world, MOB), "the marked unit came back marked"); + assert!( + !marked(world, OTHER), + "control: an unmarked one did not gain it" + ); + + super::super::handlers::dispatch(world, vec![SessionEvent::ObjectDestroyed(MOB)]); + send(world, [unit(MOB, &[(ENTRY, 299)])]); + assert!(!marked(world, MOB), "a destroyed unit's next create is new"); +} + /// An out-of-range list releases only as a packet's first block (`0x4651e1`); in any other place /// the notify pass skips it (`0x465fd0`) and nothing is released. #[test] diff --git a/crates/benilla-app/src/net/session/reputation_tests.rs b/crates/benilla-app/src/net/session/reputation_tests.rs index 9f085f4cb..d41cbc9e4 100644 --- a/crates/benilla-app/src/net/session/reputation_tests.rs +++ b/crates/benilla-app/src/net/session/reputation_tests.rs @@ -103,7 +103,7 @@ fn delta(app: &mut App, slot: u32, standing: i32) { fn xp_gain(app: &mut App) { app.world_mut() .resource_mut::() - .push_xp_gain(0, 100, 100); + .push_xp_gain(0, 100, 100, 1.0); } fn rank_lines(app: &App) -> Vec<(String, u8, bool)> { diff --git a/crates/benilla-app/src/ui_chat.rs b/crates/benilla-app/src/ui_chat.rs index b7428c4cd..473d7c9bd 100644 --- a/crates/benilla-app/src/ui_chat.rs +++ b/crates/benilla-app/src/ui_chat.rs @@ -19,6 +19,8 @@ pub(crate) mod bubbles; mod channels; /// The combat log's chat lines: classification, chat type and each sentence's GlobalString key. pub(crate) mod combat; +#[cfg(test)] +mod combat_drain_tests; pub(crate) mod commands; /// The edit box's send path: the chat-type token passed to `SendChatMessage` and its wire kind. /// `pub(crate)` for `ui_script::chat_tests`, which joins the stock file's token to this resolve. diff --git a/crates/benilla-app/src/ui_chat/combat.rs b/crates/benilla-app/src/ui_chat/combat.rs index c8dfda80f..eedb912d8 100644 --- a/crates/benilla-app/src/ui_chat/combat.rs +++ b/crates/benilla-app/src/ui_chat/combat.rs @@ -5,6 +5,10 @@ use bevy::prelude::*; +use benilla_ui::strings::{fill_exact, Arg}; + +use crate::go_templates::GameObjectTemplates; +use crate::items::Items; use crate::names::NameCache; use crate::ui_chat::event::ChatEventKind; @@ -731,10 +735,10 @@ fn append_trailers(lua: &benilla_ui::script::UiScript, line: &mut String, t: Tra return; }; let args = match arg { - Some(n) => vec![Arg::Num(n)], + Some(n) => vec![Arg::D(n)], None => Vec::new(), }; - match fill(&template, &args) { + match fill_exact(&template, &args) { Some(text) => line.push_str(&text), None => warn!("combat log: {key} does not match its trailer shape"), } @@ -781,7 +785,12 @@ pub(crate) struct Fills { /// Resolve a family and variant to a finished line; `None`, silently, when the key is absent, /// where the reference prints a not-found warning line (`0x6269f0`) for any key but a missing -/// `…SELFSELF`. The fill is `vsnprintf` over a fixed argument list, as at `0x626850`. +/// `…SELFSELF`. The fill is Storm's ordered printf over a fixed argument list +/// ([`benilla_ui::strings::fill_exact`]): `0x626850` formats through `SStrVPrintf` (`0x64a8b0`), +/// which takes `vsnoprintf` (`0x6697d0`) once option `0xa` is set, as the client does at start +/// (`0x402141`, `0x64ede9`). It binds a numbered hole (`%2$d`, the deDE templates': `Ihr trefft +/// %1$s. Schaden: %2$d.`) to its argument in the list enUS fills in sequence, and prints a +/// template that leaves an argument out. pub(crate) fn compose_line( lua: &benilla_ui::script::UiScript, family: Family, @@ -802,19 +811,19 @@ pub(crate) fn compose_line( let mut args: Vec = Vec::with_capacity(family.slots.len()); for slot in family.slots { match slot { - Slot::Attacker if family.names_subject(variant) => args.push(Arg::Str(&fills.attacker)), - Slot::Victim if family.names_object(variant) => args.push(Arg::Str(&fills.victim)), + Slot::Attacker if family.names_subject(variant) => args.push(Arg::S(&fills.attacker)), + Slot::Victim if family.names_object(variant) => args.push(Arg::S(&fills.victim)), Slot::Attacker | Slot::Victim => {} - Slot::Named => args.push(Arg::Str(&fills.named)), - Slot::Spell => args.push(Arg::Str(&fills.spell)), - Slot::School => args.push(Arg::Str(school.as_deref()?)), - Slot::Power => args.push(Arg::Str(power.as_deref()?)), - Slot::Power2 => args.push(Arg::Str(power2.as_deref()?)), - Slot::Amount => args.push(Arg::Num(fills.amount)), - Slot::Amount2 => args.push(Arg::Num(fills.amount2)), + Slot::Named => args.push(Arg::S(&fills.named)), + Slot::Spell => args.push(Arg::S(&fills.spell)), + Slot::School => args.push(Arg::S(school.as_deref()?)), + Slot::Power => args.push(Arg::S(power.as_deref()?)), + Slot::Power2 => args.push(Arg::S(power2.as_deref()?)), + Slot::Amount => args.push(Arg::D(fills.amount)), + Slot::Amount2 => args.push(Arg::D(fills.amount2)), } } - match fill(&template, &args) { + match fill_exact(&template, &args) { Some(mut line) => { if let Some(t) = fills.trailers { append_trailers(lua, &mut line, t); @@ -832,55 +841,6 @@ pub(crate) fn compose_line( } } -/// One `vsnprintf` argument. -enum Arg<'a> { - Str(&'a str), - Num(i64), -} - -/// The line's formatter over the `%s`/`%d` subset the combat-log templates use. `0x626850` formats -/// through `SStrVPrintf 0x64a8b0`, which takes Storm's ordered printf (`0x6697d0`) once option -/// `0xa` is set, as the client does at start (`0x402141`, `0x64ede9`); that printf reads `%N$` -/// (`0x669af2`), so a numbered hole (`%2$d`, the deDE templates') names its argument in the list -/// enUS fills in sequence (`Ihr trefft %1$s. Schaden: %2$d.`). `None` on any mismatch, an unused -/// argument included. -fn fill(template: &str, args: &[Arg<'_>]) -> Option { - let mut out = String::with_capacity(template.len() + 32); - let mut used = vec![false; args.len()]; - let mut cursor = 0; - let mut chars = template.chars().peekable(); - while let Some(c) = chars.next() { - if c != '%' { - out.push(c); - continue; - } - if chars.next_if_eq(&'%').is_some() { - out.push('%'); - continue; - } - let mut number = String::new(); - while let Some(d) = chars.next_if(char::is_ascii_digit) { - number.push(d); - } - let index = if number.is_empty() { - cursor += 1; - cursor - 1 - } else { - chars.next_if_eq(&'$')?; - number.parse::().ok()?.checked_sub(1)? - }; - let arg = args.get(index)?; - used[index] = true; - match (chars.next(), arg) { - (Some('s'), Arg::Str(s)) => out.push_str(s), - (Some('d'), Arg::Num(n)) => out.push_str(&n.to_string()), - // Any other conversion is a mismatch, never a half-filled sentence. - _ => return None, - } - } - used.iter().all(|&u| u).then_some(out) -} - /// A GlobalString off the VM's globals, `None` when absent or empty: the two tests `0x703bf0`'s /// callers make (`GetPVPRankInfo` at `0x51aa1c`/`0x51aa20`). pub(crate) fn global_string(script: &benilla_ui::script::UiScript, key: &str) -> Option { @@ -925,11 +885,11 @@ pub(crate) fn power_word(script: &benilla_ui::script::UiScript, power: u32) -> O global_string(script, power_key(power)?) } -/// One endpoint's display name as `GetObjectName 0x6264e0` finds it: what the caches hold now, a -/// lookup asked for what they do not (`0x6265a7`, `0x6265e0`, with an empty callback), and `None` -/// for that ([`logged_name`] prints the miss). A streamed unit names through its descriptor -/// (`GetUnitName`, `0x609210`), which is how a pet is named. -pub(crate) fn object_name( +/// A unit's name as `GetUnitName 0x609210` finds it: what the caches hold now, a lookup asked for +/// what they do not (`0x6265a7`, `0x6265e0`, with an empty callback), and `None` for that. A +/// streamed unit names through its descriptor, which is how a pet is named. The XP and honor lines +/// name their victim here (`0x637ac0`, `0x625387`). +pub(crate) fn unit_name( guid: u64, unit: Option<&ObjectStore>, names: &NameCache, @@ -942,6 +902,49 @@ pub(crate) fn object_name( names.resolve_unit(guid, unit, ask).map(str::to_owned) } +/// The caches `GetObjectName` (`0x6264e0`) reads: the name caches, the game object cache +/// (`0xc0e318`) and the item cache (`0xc0e2a0`). +#[derive(Clone, Copy)] +pub(crate) struct NameSources<'a> { + pub names: &'a NameCache, + pub gameobjects: &'a GameObjectTemplates, + pub items: &'a Items, +} + +/// One endpoint's display name as `GetObjectName 0x6264e0` finds it. A guid the client holds goes +/// by its object's type mask (`0x626513`-`0x626557`): a unit (bit 3) through `GetUnitName` +/// ([`unit_name`]), a game object (bit 5) by the record name it holds (`0x5f8100`, the cache by +/// the descriptor's entry), an item (bit 1) from the item cache by its entry, read without asking +/// (`0x55ba30` with no callback); any other object has no name. A guid not held goes to the name +/// caches (`0x6265a7`, `0x6265e0`, with an empty callback). `None` for a miss, and for a record +/// with an empty name (`0x6265ef`), which [`logged_name`] prints. +pub(crate) fn object_name( + guid: u64, + held: Option<&ObjectStore>, + sources: &NameSources<'_>, + ask: Ask<'_>, +) -> Option { + use benilla_protocol::messages::ObjectType; + if guid == 0 { + return None; + } + let name = match held { + None => return unit_name(guid, None, sources.names, ask), + Some(store) if is_unit(store) => return unit_name(guid, Some(store), sources.names, ask), + Some(store) if store.0.object_type() == Some(ObjectType::GameObject) => sources + .gameobjects + .of(&store.0) + .map(|template| template.name.as_str()), + Some(store) if store.0.is_item() => store + .0 + .object_entry() + .and_then(|entry| sources.items.template(entry, 0, Ask::Read)) + .map(|item| item.name.as_str()), + Some(_) => None, + }; + name.filter(|name| !name.is_empty()).map(str::to_owned) +} + /// The name `GetObjectName` prints for an object nothing names: the `UNKNOWNOBJECT` string, else /// the literal `UKNOWNOBJECT` (`0x6265f4`-`0x62660c`). pub(crate) fn unknown_object(script: &benilla_ui::script::UiScript) -> String { @@ -955,11 +958,11 @@ pub(crate) fn unknown_object(script: &benilla_ui::script::UiScript) -> String { pub(crate) fn logged_name( guid: u64, store: Option<&ObjectStore>, - names: &NameCache, + sources: &NameSources<'_>, ask: Ask<'_>, script: &benilla_ui::script::UiScript, ) -> String { - object_name(guid, store, names, ask).unwrap_or_else(|| { + object_name(guid, store, sources, ask).unwrap_or_else(|| { if store.is_some_and(is_unit) { script.unknown_object_text() } else { @@ -985,6 +988,7 @@ pub(crate) struct PendingCombat { /// Everything the template needs but the names, which are filled at drain. pub fills: Fills, pub named: Named, + /// The drains that found the line waiting; the first asks for its names, the rest only read. pub tries: u16, /// The `COMBAT_TEXT_UPDATE` the formatter raises once the line is written, and only then: a /// missing template, range or spell writes neither. diff --git a/crates/benilla-app/src/ui_chat/combat/families.rs b/crates/benilla-app/src/ui_chat/combat/families.rs index cde61e761..73c47964c 100644 --- a/crates/benilla-app/src/ui_chat/combat/families.rs +++ b/crates/benilla-app/src/ui_chat/combat/families.rs @@ -512,6 +512,15 @@ duo!( "`\"Your %s is dismissed.\"` (:3834) / `\"%s's %s is dismissed.\"` (:3833) — the trailing name \ is the PET." ); +duo!( + OPEN_LOCK, + "OPEN_LOCK_", + "SELF", + "OTHER", + [Attacker, Spell, Named], + "`\"You perform %s on %s.\"` (:2823) / `\"%s performs %s on %s.\"` (:2822) — `0x62dc10`'s \ + line; the trailing name is the opened game object's or item's record name." +); duo!( SPELLHAPPINESSDRAIN, "SPELLHAPPINESSDRAIN", @@ -696,6 +705,7 @@ pub(crate) const ALL_FAMILIES: &[Family] = &[ SPELLDURABILITYDAMAGE, SPELLDURABILITYDAMAGEALL, SPELLDISMISSPET, + OPEN_LOCK, SPELLHAPPINESSDRAIN, SPELLFAILCAST, SPELLFAILPERFORM, diff --git a/crates/benilla-app/src/ui_chat/combat/tests.rs b/crates/benilla-app/src/ui_chat/combat/tests.rs index 844f96ba1..c100b24ad 100644 --- a/crates/benilla-app/src/ui_chat/combat/tests.rs +++ b/crates/benilla-app/src/ui_chat/combat/tests.rs @@ -3,8 +3,9 @@ use super::*; -/// A template's `%s`/`%d` conversions by argument, a numbered hole (`%2$d`, deDE's) at its number; -/// two templates with the same one take the same arguments. +/// A template's `%s`/`%d` conversions by argument, bound as `vsnoprintf` binds them (`0x669892`): +/// a numbered hole (`%2$d`, deDE's) at its number, a plain one at the running index, which every +/// hole leaves one past its own; two templates with the same one take the same arguments. fn signature(template: &str) -> Vec { let mut out = Vec::new(); let mut cursor = 0; @@ -18,14 +19,14 @@ fn signature(template: &str) -> Vec { number.push(d); } let index = if number.is_empty() { - cursor += 1; - cursor - 1 + cursor } else { chars.next_if_eq(&'$'); number .parse::() .map_or(usize::MAX, |n| n.saturating_sub(1)) }; + cursor = index.saturating_add(1); let Some(k) = chars.next() else { break }; if index >= out.len() { out.resize(index.saturating_add(1).min(64), '?'); @@ -38,35 +39,70 @@ fn signature(template: &str) -> Vec { } /// deDE numbers its holes in the argument order enUS fills in sequence, so both read one list; a -/// hole past the list, a wrong type or an unused argument stays a mismatch. +/// hole past the list or of the wrong type stays a mismatch, an argument no hole names does not. #[test] fn numbered_holes_fill_from_the_same_argument_list() { - let hit = [Arg::Str("Ragnaros"), Arg::Num(1000)]; + let hit = [Arg::S("Ragnaros"), Arg::D(1000)]; assert_eq!( - fill("You hit %s for %d.", &hit).as_deref(), + fill_exact("You hit %s for %d.", &hit).as_deref(), Some("You hit Ragnaros for 1000.") ); assert_eq!( - fill("Ihr trefft %1$s. Schaden: %2$d.", &hit).as_deref(), + fill_exact("Ihr trefft %1$s. Schaden: %2$d.", &hit).as_deref(), Some("Ihr trefft Ragnaros. Schaden: 1000.") ); - let reflect = [Arg::Num(50), Arg::Str("Feuer"), Arg::Str("Ragnaros")]; + let reflect = [Arg::D(50), Arg::S("Feuer"), Arg::S("Ragnaros")]; assert_eq!( - fill("Ihr reflektiert %1$d %2$sschaden auf %3$s.", &reflect).as_deref(), + fill_exact("Ihr reflektiert %1$d %2$sschaden auf %3$s.", &reflect).as_deref(), Some("Ihr reflektiert 50 Feuerschaden auf Ragnaros.") ); assert_eq!( - fill("%2$s von %1$s", &[Arg::Str("A"), Arg::Str("B")]).as_deref(), + fill_exact("%2$s von %1$s", &[Arg::S("A"), Arg::S("B")]).as_deref(), Some("B von A") ); assert_eq!( - fill("100%% %1$s", &[Arg::Str("x")]).as_deref(), + fill_exact("100%% %1$s", &[Arg::S("x")]).as_deref(), Some("100% x") ); - assert_eq!(fill("%3$s", &[Arg::Str("a")]), None); - assert_eq!(fill("%1$d", &[Arg::Str("a")]), None); - assert_eq!(fill("%1$s", &[Arg::Str("a"), Arg::Num(1)]), None); - assert_eq!(fill("%0$s", &[Arg::Str("a")]), None); + assert_eq!(fill_exact("%3$s", &[Arg::S("a")]), None); + assert_eq!(fill_exact("%1$d", &[Arg::S("a")]), None); + assert_eq!( + fill_exact("%1$s", &[Arg::S("a"), Arg::D(1)]).as_deref(), + Some("a"), + "an argument no hole names is skipped" + ); + assert_eq!(fill_exact("%0$s", &[Arg::S("a")]).as_deref(), Some("a")); +} + +/// `vsnoprintf` prints the arguments the template names, in the template's own binding, and +/// skips one no hole takes (`0x6698b5`-`0x669919`); a plain hole after `%N$` takes argument N + 1 +/// (`0x669892`). So a template that leaves a name out, or mixes the two hole forms, still prints. +#[test] +fn a_template_that_omits_an_argument_or_mixes_hole_forms_still_prints() { + let script = benilla_ui::script::UiScript::new().expect("VM"); + script + .run( + r#" + COMBATHITSELFOTHER = "You land a blow for %2$d." + COMBATHITOTHERSELF = "%1$s hits you for %d." + "#, + ) + .unwrap(); + let fills = Fills { + attacker: "Ragnaros".into(), + victim: "Ragnaros".into(), + amount: 12, + ..Default::default() + }; + let line = |variant| compose_line(&script, COMBATHIT, variant, &fills); + assert_eq!( + line(Variant::SelfOther).as_deref(), + Some("You land a blow for 12.") + ); + assert_eq!( + line(Variant::OtherSelf).as_deref(), + Some("Ragnaros hits you for 12.") + ); } /// The signature a family's declared slots give for one variant; `Attacker` and `Victim` count @@ -270,24 +306,26 @@ fn the_reported_sentences_read_correctly() { ); } +/// The fill refuses a hole with nothing to print (`fill_exact`), and skips an argument no hole +/// names (`0x6698b5`-`0x669919`). #[test] -fn the_fill_is_vsnprintf_and_refuses_a_mismatch() { +fn the_fill_is_vsnoprintf_and_refuses_a_hole_it_cannot_print() { fn s(v: &str) -> Arg<'_> { - Arg::Str(v) + Arg::S(v) } assert_eq!( - fill("%s hits %s for %d.", &[s("A"), s("B"), Arg::Num(7)]).as_deref(), + fill_exact("%s hits %s for %d.", &[s("A"), s("B"), Arg::D(7)]).as_deref(), Some("A hits B for 7.") ); - assert_eq!(fill("100%% sure", &[]).as_deref(), Some("100% sure")); + assert_eq!(fill_exact("100%% sure", &[]).as_deref(), Some("100% sure")); // A `%d` where a string is queued, and vice versa. - assert_eq!(fill("%d", &[s("A")]), None); - assert_eq!(fill("%s", &[Arg::Num(1)]), None); - // Too few, and too many. - assert_eq!(fill("%s %s", &[s("A")]), None); - assert_eq!(fill("%s", &[s("A"), s("B")]), None); + assert_eq!(fill_exact("%d", &[s("A")]), None); + assert_eq!(fill_exact("%s", &[Arg::D(1)]), None); + // Too few holes' arguments is a mismatch; too many is not. + assert_eq!(fill_exact("%s %s", &[s("A")]), None); + assert_eq!(fill_exact("%s", &[s("A"), s("B")]).as_deref(), Some("A")); // A conversion outside the vocabulary is a mismatch, not a passthrough. - assert_eq!(fill("%f", &[Arg::Num(1)]), None); + assert_eq!(fill_exact("%f", &[Arg::D(1)]), None); } /// The melee msgType matrix of `0x62a0d0`/`0x62a2e0`, through the 94-entry type table at @@ -728,8 +766,14 @@ fn a_unit_name_never_holds_a_line_and_an_item_name_does() { fn an_unnamed_held_unit_prints_the_unit_getters_miss() { let script = benilla_ui::script::UiScript::new().expect("VM"); let names = NameCache::default(); + let (gameobjects, items) = (GameObjectTemplates::default(), Items::default()); + let sources = NameSources { + names: &names, + gameobjects: &gameobjects, + items: &items, + }; let store = |kind: u32| ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[(2, kind)])); - let name = |store: Option<&ObjectStore>| logged_name(7, store, &names, Ask::Read, &script); + let name = |store: Option<&ObjectStore>| logged_name(7, store, &sources, Ask::Read, &script); assert_eq!(name(Some(&store(0x19))), "Unknown Being", "a held player"); assert_eq!(name(Some(&store(0x9))), "Unknown Being", "a held creature"); assert_eq!(name(Some(&store(0x21))), "UKNOWNOBJECT", "a game object"); @@ -744,6 +788,43 @@ fn an_unnamed_held_unit_prints_the_unit_getters_miss() { assert_eq!(name(None), "Unknown"); } +/// `GetObjectName` (`0x6264e0`) names a held object by its type mask: a game object by the record +/// it holds (`0x5f8100`), an item, a bag included, from the item cache without asking +/// (`0x55ba30` with no callback). No record, or an empty name (`0x6265ef`), is the miss. +#[test] +fn a_held_game_object_or_item_is_named_from_its_record() { + let script = benilla_ui::script::UiScript::new().expect("VM"); + let names = NameCache::default(); + let mut gameobjects = GameObjectTemplates::default(); + gameobjects.insert(1731, 3, "Copper Vein".into(), &[0; 24]); + gameobjects.insert(1732, 3, String::new(), &[0; 24]); + let mut items = Items::default(); + items.insert_template(2589, Some(crate::items::test_template("Junkbox"))); + let sources = NameSources { + names: &names, + gameobjects: &gameobjects, + items: &items, + }; + let held = |mask: u32, entry: u32| { + ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[ + (2, mask), + (benilla_protocol::field::FIELD_OBJECT_ENTRY, entry), + ])) + }; + let name = |store: &ObjectStore| logged_name(7, Some(store), &sources, Ask::Read, &script); + assert_eq!(name(&held(0x21, 1731)), "Copper Vein"); + assert_eq!(name(&held(0x3, 2589)), "Junkbox", "an item"); + assert_eq!(name(&held(0x7, 2589)), "Junkbox", "a bag"); + assert_eq!(name(&held(0x21, 9)), "UKNOWNOBJECT", "no record"); + assert_eq!(name(&held(0x3, 9)), "UKNOWNOBJECT", "no record"); + assert_eq!(name(&held(0x21, 1732)), "UKNOWNOBJECT", "an empty name"); + assert_eq!( + name(&held(0x21, 2589)), + "UKNOWNOBJECT", + "an object's entry names no item" + ); +} + /// A school with no name writes no line, even where the template names none: each formatter that /// takes a school returns on its name first (`0x62cd99`, `0x628117`), before the line and its word. #[test] diff --git a/crates/benilla-app/src/ui_chat/combat/watch.rs b/crates/benilla-app/src/ui_chat/combat/watch.rs index 502ff0a39..30156036d 100644 --- a/crates/benilla-app/src/ui_chat/combat/watch.rs +++ b/crates/benilla-app/src/ui_chat/combat/watch.rs @@ -101,16 +101,20 @@ fn queue_one( /// as "destroyed", `0x62c320`'s byte table: totems, summoned objects, guardians. const DESTROYED_EFFECTS: [u32; 10] = [50, 74, 87, 88, 89, 90, 104, 105, 106, 107]; +/// Bit 3 of a unit's `+0xc58`: an XP award named it (`0x60a0e6`, from `0x637f1d`). Only the unit's +/// constructor clears the word (`0x5fae7a`), so the mark lives as long as the unit does, +/// released and brought back included. The death line stands down for a marked unit +/// (`0x62c232`-`0x62c23e`): the XP line ("X dies, you gain N experience.") is its sentence. +#[derive(Component, Clone, Copy, Debug, Default)] +pub(crate) struct XpAwarded; + /// The unit-death line (`0x625190` → `0x62c160`), off the `UNIT_FIELD_HEALTH` edge as the /// reference's watcher `0x6046f0` takes it (alive to dead at `0x6047a3`); a unit that streams in -/// dead prints nothing. -/// -/// Not modelled: the reference prints the XP-award line in place of the death line while -/// `[CGUnit+0xc58]` bit 3, set in the `SMSG_LOG_XPGAIN` chain, is set (`0x62c23e`); the bit's -/// clearing site is untraced, so a kill that awards experience prints both lines here. +/// dead prints nothing, and neither does one an XP award named ([`XpAwarded`]). pub(crate) fn death_lines( ctx: WatchCtx, stores: Query<(Entity, &ObjectStore)>, + awarded: Query<(), With>, mut edges: MessageReader, poses: Query<&Transform>, mut log: ResMut, @@ -119,6 +123,9 @@ pub(crate) fn death_lines( if !(e.unit_field(benilla_protocol::field::FIELD_UNIT_HEALTH) && e.old > 0 && e.new == 0) { continue; } + if awarded.contains(e.entity) { + continue; + } let Ok((_, store)) = stores.get(e.entity) else { continue; }; diff --git a/crates/benilla-app/src/ui_chat/combat_drain_tests.rs b/crates/benilla-app/src/ui_chat/combat_drain_tests.rs new file mode 100644 index 000000000..947d133c5 --- /dev/null +++ b/crates/benilla-app/src/ui_chat/combat_drain_tests.rs @@ -0,0 +1,228 @@ +//! The combat lines through the drain: what holds a line, what names its endpoints, and the XP +//! line's group and raid forms. + +use benilla_protocol::field::FIELD_OBJECT_ENTRY; + +use super::combat::{self, Fills, Named, UnitClass}; +use super::feed::{xp_gain_line, RestState}; +use super::notice_tests::Feed; +use super::ChatEventKind as K; + +const ME: u64 = 7; + +/// A frame that records the first argument of each `event` it sees, into `Seen`. +fn spy(feed: &Feed, event: &str) { + feed.script() + .run(&format!( + r#" + Seen = {{}} + Drain = CreateFrame("Frame", "BenillaDrainSpy") + Drain:SetScript("OnEvent", function() table.insert(Seen, arg1) end) + Drain:RegisterEvent("{event}") + "# + )) + .unwrap(); +} + +fn seen(feed: &Feed) -> Vec { + feed.script().eval::>("return Seen").unwrap() +} + +/// The reference parks a line that asked the item cache for a name in a list with no timer or +/// count (`0x6293a0`), and only the answer (`0x6294cc`-`0x62959c`) or shutdown (`0x629a90`) +/// removes it, so a record that lands late still writes its line. +#[test] +fn a_line_waiting_on_an_item_name_waits_until_the_cache_answers() { + let _data = benilla_formats::wow_data_or_skip!(); + const LINEN: u32 = 2589; + let mut feed = Feed::new(); + spy(&feed, super::event::event_name(K::SpellTradeskills)); + feed.world.resource_mut::().0 = Some(ME); + let line = combat::queue( + K::SpellTradeskills, + combat::TRADESKILL_LOG, + (ME, UnitClass::Me), + (ME, UnitClass::Me), + Fills::default(), + Named::Item(LINEN), + ) + .unwrap(); + feed.world + .resource_mut::() + .push_combat(line); + for _ in 0..300 { + feed.drain(); + } + assert!(seen(&feed).is_empty(), "nothing to name it with yet"); + feed.world + .resource_mut::() + .insert_template(LINEN, Some(crate::items::test_template("Linen Cloth"))); + feed.drain(); + assert_eq!(seen(&feed), ["You create Linen Cloth."]); + feed.drain(); + assert_eq!(seen(&feed).len(), 1, "written once"); +} + +/// `GetCombatLogName` (`0x6264e0`) names a held object by its type mask: a game object by its +/// record (`0x626547` → `0x5f8100`), an item by the item cache without asking (`0x62656e` → +/// `0x55ba30`), and a name the caches lack is `UNKNOWNOBJECT`. +#[test] +fn a_game_object_or_item_endpoint_is_named_from_its_record() { + let _data = benilla_formats::wow_data_or_skip!(); + const TRAP: u64 = 0xf110_0000_0000_0007; + const BARE_TRAP: u64 = 0xf110_0000_0000_0008; + const VIAL: u64 = 0x4000_0000_0000_0042; + let mut feed = Feed::new(); + let kind = K::SpellCreatureVsSelfDamage; + spy(&feed, super::event::event_name(kind)); + for (guid, mask, entry) in [ + (TRAP, 0x21, 1731), + (BARE_TRAP, 0x21, 1732), + (VIAL, 0x3, 2589), + ] { + let e = feed + .world + .spawn(crate::net::ObjectStore( + benilla_protocol::ObjectFields::from_pairs(&[ + (2, mask), + (FIELD_OBJECT_ENTRY, entry), + ]), + )) + .id(); + feed.world + .resource_mut::() + .0 + .insert(guid, e); + } + feed.world + .init_resource::(); + feed.world + .resource_mut::() + .insert(1731, 6, "Venom Trap".into(), &[0; 24]); + feed.world + .resource_mut::() + .insert_template(2589, Some(crate::items::test_template("Poison Vial"))); + for caster in [TRAP, VIAL, BARE_TRAP] { + let line = combat::queue( + kind, + combat::SIMPLECAST, + (caster, UnitClass::Creature), + (ME, UnitClass::Me), + Fills { + spell: "Poison".into(), + ..Default::default() + }, + Named::Ready, + ) + .unwrap(); + feed.world + .resource_mut::() + .push_combat(line); + } + feed.drain(); + assert_eq!( + seen(&feed), + [ + "Venom Trap casts Poison on you.", + "Poison Vial casts Poison on you.", + "Unknown casts Poison on you.", + ] + ); +} + +/// A kill's XP line follows the packet's group float (`0x637cd0`, `0x637ac0`): `ftol(xp / float)` +/// against `xp` is equal for the plain line, below for `_GROUP` ("+N group bonus") and above for +/// `_RAID`, N the difference; a rested kill does the same on its base XP, appending `_GROUP` or +/// `_RAID` to the state's key (`0x637b70`-`0x637bd5`). `ftol` truncates and wraps as `__ftol` +/// does (`0x40a2b0`). +#[test] +fn a_kills_group_float_words_the_group_or_raid_form() { + let get = |key: &str| { + Some( + match key { + "COMBATLOG_XPGAIN_FIRSTPERSON" => "%s dies, you gain %d experience.", + "COMBATLOG_XPGAIN_FIRSTPERSON_GROUP" => { + "%s dies, you gain %d experience. (+%d group bonus)" + } + "COMBATLOG_XPGAIN_FIRSTPERSON_RAID" => { + "%s dies, you gain %d experience. (-%d raid penalty)" + } + "COMBATLOG_XPGAIN_EXHAUSTION1" => { + "%s dies, you gain %d experience. (%s exp %s bonus)" + } + "COMBATLOG_XPGAIN_EXHAUSTION1_GROUP" => { + "%s dies, you gain %d experience. (%s exp %s bonus, +%d group bonus)" + } + "COMBATLOG_XPGAIN_EXHAUSTION1_RAID" => { + "%s dies, you gain %d experience. (%s exp %s bonus, -%d raid penalty)" + } + _ => return None, + } + .to_string(), + ) + }; + let plain = |total, group| { + xp_gain_line( + Some("Defias Thug"), + total, + total, + group, + Some(RestState { + state: 2, + row: Some(("Normal", 1.0)), + }), + &get, + ) + }; + let rested = |total, base, group| { + xp_gain_line( + Some("Defias Thug"), + total, + base, + group, + Some(RestState { + state: 1, + row: Some(("Rested", 2.0)), + }), + &get, + ) + }; + let dies = "Defias Thug dies, you gain"; + assert_eq!( + plain(60, 1.0).as_deref(), + Some(format!("{dies} 60 experience.").as_str()) + ); + // 60 / 1.5 = 40, below 60: the group bonus is the 20 between. + assert_eq!( + plain(60, 1.5).as_deref(), + Some(format!("{dies} 60 experience. (+20 group bonus)").as_str()) + ); + // 30 / 0.5 = 60, above 30: a raid penalty of 30. + assert_eq!( + plain(30, 0.5).as_deref(), + Some(format!("{dies} 30 experience. (-30 raid penalty)").as_str()) + ); + // 60 / 1.2f = 49.999998…, which `__ftol` truncates to 49. + assert_eq!( + plain(60, 1.2).as_deref(), + Some(format!("{dies} 60 experience. (+11 group bonus)").as_str()) + ); + // A float of 0 divides to infinity, which `__ftol` stores as 0: all 60 is bonus. + assert_eq!( + plain(60, 0.0).as_deref(), + Some(format!("{dies} 60 experience. (+60 group bonus)").as_str()) + ); + // The rested forms compare on the base XP (40 → 52 with the 12 of bonus). + assert_eq!( + rested(52, 40, 1.0).as_deref(), + Some(format!("{dies} 52 experience. (+12 exp Rested bonus)").as_str()) + ); + assert_eq!( + rested(52, 40, 2.0).as_deref(), + Some(format!("{dies} 52 experience. (+12 exp Rested bonus, +20 group bonus)").as_str()) + ); + assert_eq!( + rested(52, 40, 0.5).as_deref(), + Some(format!("{dies} 52 experience. (+12 exp Rested bonus, -40 raid penalty)").as_str()) + ); +} diff --git a/crates/benilla-app/src/ui_chat/feed.rs b/crates/benilla-app/src/ui_chat/feed.rs index 90b6d54a9..669682756 100644 --- a/crates/benilla-app/src/ui_chat/feed.rs +++ b/crates/benilla-app/src/ui_chat/feed.rs @@ -72,8 +72,14 @@ enum Pending { guid: u64, tries: u16, }, - /// An XP award; `victim` 0 is the unnamed form. - XpGain { victim: u64, total: u32, base: u32 }, + /// An XP award; `victim` 0 is the unnamed form. `group` is the packet's float, 1.0 for the + /// forms that never read one. + XpGain { + victim: u64, + total: u32, + base: u32, + group: f32, + }, /// An XP loss, `total` as the packet carries it. XpLoss { total: u32 }, /// An honor award; `rank` (0 none) becomes a title at the drain, on the victim's `side` (0 @@ -103,7 +109,7 @@ enum Pending { female: bool, }, /// One combat-log line, classified at the packet; it waits only on an item's name, as the - /// reference's deferred queue (`0xc4e208`) does. + /// reference's deferred queue (`0xc4e208`) does, until the cache answers. Combat(Box), /// A ready event (client-composed lines; name-carrying notices). Event(ChatEvent), @@ -271,11 +277,12 @@ impl ChatLog { } /// Queue an XP gain's line (`SMSG_LOG_XPGAIN`); `victim` 0 is the unnamed form. - pub(crate) fn push_xp_gain(&mut self, victim: u64, total: u32, base: u32) { + pub(crate) fn push_xp_gain(&mut self, victim: u64, total: u32, base: u32, group: f32) { self.pending.push(Pending::XpGain { victim, total, base, + group, }); } @@ -383,9 +390,10 @@ impl ChatLog { .collect() } - /// The parked XP lines as `(victim, total, base)`, in order; victim 0 is the unnamed form. + /// The parked XP lines as `(victim, total, base, group)`, in order; victim 0 is the unnamed + /// form. #[cfg(test)] - pub(crate) fn pending_xp(&self) -> Vec<(u64, u32, u32)> { + pub(crate) fn pending_xp(&self) -> Vec<(u64, u32, u32, f32)> { self.pending .iter() .filter_map(|p| match *p { @@ -393,7 +401,8 @@ impl ChatLog { victim, total, base, - } => Some((victim, total, base)), + group, + } => Some((victim, total, base, group)), _ => None, }) .collect() @@ -509,24 +518,26 @@ pub(super) struct RestState<'a> { const XP_FACTOR_EPSILON: f64 = 1.0 / 4_194_304.0; /// The XP line, `0x637ac0` (a named kill) and `0x637cd0` (the plain forms). No victim is -/// `COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED`. A named kill needs the active player (`0x637b06`; -/// `rest` `None` writes nothing), and is plain `COMBATLOG_XPGAIN_FIRSTPERSON` unless its rest -/// state has a row whose factor is neither 0 nor 1 (`0x637b3e`-`0x637b6a`). Then it is that -/// state's key in the table `0x864330`, `COMBATLOG_XPGAIN_EXHAUSTION`, with the signed -/// bonus, `total - base` prefixed `+` unless negative (`0x637c07`-`0x637c25`), and the row's name -/// as the state word (`0x637c31`). The table has no entry 0 and ends at 5: a row there writes -/// nothing. State 3's entry names the global `NULL`, which 1.12 does not define: `GetText` answers -/// the empty string for it (`0x703c02`) and `0x637bef` tests only for null, so the reference -/// formats that line from an empty template, which `keyed` drops. No shipped row reaches it: -/// `Exhaustion.dbc` gives state 3 a factor of 1, the plain form. +/// `COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED`, which no float reaches: its callers pass 1.0 +/// (`0x637f90`) or find the victim they stored the gain on. A named kill needs the active player +/// (`0x637b06`; `rest` `None` writes nothing), and is plain `COMBATLOG_XPGAIN_FIRSTPERSON` unless +/// its rest state has a row whose factor is neither 0 nor 1 (`0x637b3e`-`0x637b6a`). Then it is +/// that state's key in the table `0x864330`, `COMBATLOG_XPGAIN_EXHAUSTION`, with the +/// signed bonus, `total - base` prefixed `+` unless negative (`0x637c07`-`0x637c25`), and the +/// row's name as the state word (`0x637c31`). The table has no entry 0 and ends at 5: a row there +/// writes nothing. State 3's entry names the global `NULL`, which 1.12 does not define: `GetText` +/// answers the empty string for it (`0x703c02`) and `0x637bef` tests only for null, so the +/// reference formats that line from an empty template, which `keyed` drops. No shipped row +/// reaches it: `Exhaustion.dbc` gives state 3 a factor of 1, the plain form. /// -/// The group float the packet carries (vmangos always 1.0, `Player.cpp:3039`) picks the `_GROUP` -/// and `_RAID` forms (`0x637b70`-`0x637bd5`, `0x637cd0`); the parser drops it, so they are not -/// built. +/// The packet's group float ([`group_split`]) appends `_GROUP` or `_RAID` to the named key and +/// adds the difference as the last number (`0x637b70`-`0x637bd5`, `0x637d33`-`0x637d67`); a +/// rested kill compares on its base XP. pub(super) fn xp_gain_line( victim: Option<&str>, total: u32, base: u32, + group: f32, rest: Option, get: &dyn Fn(&str) -> Option, ) -> Option { @@ -540,11 +551,16 @@ pub(super) fn xp_gain_line( }; let rest = rest?; let plain = || { - keyed( - get, - "COMBATLOG_XPGAIN_FIRSTPERSON", - &[Arg::S(name), Arg::D(i64::from(total))], - ) + let (suffix, diff) = group_split(total, group); + let named = [Arg::S(name), Arg::D(i64::from(total))]; + match suffix { + None => keyed(get, "COMBATLOG_XPGAIN_FIRSTPERSON", &named), + Some(suffix) => keyed( + get, + &format!("COMBATLOG_XPGAIN_FIRSTPERSON{suffix}"), + &[named[0], named[1], Arg::D(i64::from(diff))], + ), + } }; let Some((state_word, factor)) = rest.row else { return plain(); @@ -563,16 +579,37 @@ pub(super) fn xp_gain_line( // `sub`, `jns`: the 32-bit difference's sign. let bonus = total.wrapping_sub(base) as i32; let sign = if bonus >= 0 { "+" } else { "" }; - keyed( - get, - key, - &[ - Arg::S(name), - Arg::D(i64::from(total)), - Arg::S(&format!("{sign}{bonus}")), - Arg::S(state_word), - ], - ) + let bonus = format!("{sign}{bonus}"); + let (suffix, diff) = group_split(base, group); + let args = [ + Arg::S(name), + Arg::D(i64::from(total)), + Arg::S(&bonus), + Arg::S(state_word), + ]; + match suffix { + None => keyed(get, key, &args), + Some(suffix) => keyed( + get, + &format!("{key}{suffix}"), + &[args[0], args[1], args[2], args[3], Arg::D(i64::from(diff))], + ), + } +} + +/// How the packet's group float moves a kill's XP (`0x637cdb`-`0x637d3a`, `0x637b70`-`0x637bbc`): +/// `__ftol(xp / group)` against `xp`, both as signed 32-bit values. Equal is no suffix; below is +/// `_GROUP`, the bonus; above is `_RAID`, the penalty. The second number is the absolute +/// difference (`cdq`, `xor`, `sub`), which wraps like the reference's. +fn group_split(xp: u32, group: f32) -> (Option<&'static str>, i32) { + let xp = xp as i32; + let scaled = benilla_ui::script::ftol(f64::from(xp) / f64::from(group)); + let diff = xp.wrapping_sub(scaled).wrapping_abs(); + match scaled.cmp(&xp) { + std::cmp::Ordering::Equal => (None, 0), + std::cmp::Ordering::Less => (Some("_GROUP"), diff), + std::cmp::Ordering::Greater => (Some("_RAID"), diff), + } } /// The XP loss line, `COMBATLOG_XPLOSS_FIRSTPERSON_UNNAMED` with the packet's XP negated as a @@ -848,8 +885,12 @@ pub(super) fn feed_chat( states: Res, // The language gate: the word pool, this character's fluency and the GM bit. langs: Res, - // Item names for `TRADESKILL_LOG`, `FEEDPET_LOG`, `ITEMENCHANTMENT*`, `SPELLDURABILITYDAMAGE`. - items: Res, + // Item names for `TRADESKILL_LOG`, `FEEDPET_LOG`, `ITEMENCHANTMENT*`, `SPELLDURABILITYDAMAGE`, + // and with the game object records the names of a combat line's held objects. + (items, gameobjects): ( + Res, + Res, + ), unit_names: crate::ui_unit::NameTables, // The spam and profanity filters, which run in the reference's display function `0x49a870`. mut text_filter: crate::text_filter::ChatTextFilter, @@ -1141,12 +1182,13 @@ pub(super) fn feed_chat( victim, total, base, + group, } => { // A victim's name never waits: each template names it through `GetUnitName` // (`0x609210`, from `0x637ac0`), whose miss without `UNKNOWNOBJECT` is the literal // "Unknown Being", where `GetObjectName`'s is `UKNOWNOBJECT`. let name = (victim != 0).then(|| { - super::combat::object_name( + super::combat::unit_name( victim, guids.0.get(&victim).and_then(|e| stores.get(*e).ok()), &names, @@ -1164,7 +1206,8 @@ pub(super) fn feed_chat( state, row: row.as_ref().map(|(n, f)| (n.as_str(), *f)), }); - let line = xp_gain_line(name.as_deref(), total, base, rest, &globals(&script)); + let line = + xp_gain_line(name.as_deref(), total, base, group, rest, &globals(&script)); if let Some(text) = line { route( &mut script, @@ -1194,7 +1237,7 @@ pub(super) fn feed_chat( // (`0x612bf0`, `0x625374`), whose gender `0x5ed5b0` reads from `PLAYER_BYTES_3` // byte 0; a dishonorable kill's template names no rank. let name = (victim != 0).then(|| { - super::combat::object_name( + super::combat::unit_name( victim, guids.0.get(&victim).and_then(|e| stores.get(*e).ok()), &names, @@ -1267,14 +1310,22 @@ pub(super) fn feed_chat( } Pending::Combat(mut line) => { // Names looked up with a callback as the line's (`0x6265a7`, `0x6265e0`), and - // asked again only on its first drain; a line waits on an item alone. + // asked again only on its first drain; a line waits on an item alone, and as long + // as the cache takes to answer: the reference's list has no timer or count, and + // only the answer or the session's end removes an entry (`0x6293a0`, `0x6294cc`, + // `0x629a90`). let ask = Ask::at(line.tries == 0, &commands); + let sources = super::combat::NameSources { + names: &names, + gameobjects: &gameobjects, + items: &items, + }; let ready = line.fill_names( |guid| { super::combat::logged_name( guid, guids.0.get(&guid).and_then(|e| stores.get(*e).ok()), - &names, + &sources, ask, &script, ) @@ -1288,10 +1339,8 @@ pub(super) fn feed_chat( }, ); if !ready { - if line.tries < NAME_MAX_TRIES { - line.tries += 1; - still.push(Pending::Combat(line)); - } + line.tries = line.tries.saturating_add(1); + still.push(Pending::Combat(line)); continue; } write_combat_line(&mut script, &mut windows, &line); diff --git a/crates/benilla-app/src/ui_chat/notice_tests.rs b/crates/benilla-app/src/ui_chat/notice_tests.rs index fafc9e950..3f235a226 100644 --- a/crates/benilla-app/src/ui_chat/notice_tests.rs +++ b/crates/benilla-app/src/ui_chat/notice_tests.rs @@ -66,6 +66,7 @@ impl Feed { world.insert_resource(crate::world_state::WorldStates::default()); world.insert_resource(super::language::ChatLanguages::default()); world.insert_resource(crate::items::Items::default()); + world.insert_resource(crate::go_templates::GameObjectTemplates::default()); world.insert_resource(crate::text_filter::TextFilter::default()); world.insert_resource(crate::text_filter::TextFilterSwitches::default()); Feed { world, sent } diff --git a/crates/benilla-app/src/ui_chat/tests.rs b/crates/benilla-app/src/ui_chat/tests.rs index b88086273..caddf4d07 100644 --- a/crates/benilla-app/src/ui_chat/tests.rs +++ b/crates/benilla-app/src/ui_chat/tests.rs @@ -305,15 +305,15 @@ fn xp_gain_lines_pick_the_reference_form() { // `COMBATLOG_XPGAIN_FIRSTPERSON`, `COMBATLOG_XPGAIN_EXHAUSTION1` (rested) and // `COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED` (`GlobalStrings.lua:801`, `:789`, `:804`). assert_eq!( - with_strings(|g| xp_gain_line(Some("Kobold Vermin"), 35, 35, normal(), g)).as_deref(), + with_strings(|g| xp_gain_line(Some("Kobold Vermin"), 35, 35, 1.0, normal(), g)).as_deref(), Some("Kobold Vermin dies, you gain 35 experience.") ); assert_eq!( - with_strings(|g| xp_gain_line(Some("Kobold Vermin"), 52, 35, rested(), g)).as_deref(), + with_strings(|g| xp_gain_line(Some("Kobold Vermin"), 52, 35, 1.0, rested(), g)).as_deref(), Some("Kobold Vermin dies, you gain 52 experience. (+17 exp Rested bonus)") ); assert_eq!( - with_strings(|g| xp_gain_line(None, 120, 120, None, g)).as_deref(), + with_strings(|g| xp_gain_line(None, 120, 120, 1.0, None, g)).as_deref(), Some("You gain 120 experience.") ); // The shipped lavender, 0x6F6FFF, chat-cache row 46. @@ -349,6 +349,7 @@ fn the_xp_line_follows_the_rest_states_exhaustion_row() { Some("Defias Thug"), total, base, + 1.0, Some(RestState { state, row }), &get, ) @@ -380,9 +381,12 @@ fn the_xp_line_follows_the_rest_states_exhaustion_row() { // State 3's key is `NULL`, no global: an empty template, and no empty line. assert_eq!(line(60, 40, 3, Some(("Tired", 0.75))), None); // A named kill with no active player writes nothing; the unnamed form needs none. - assert_eq!(xp_gain_line(Some("Defias Thug"), 60, 40, None, &get), None); assert_eq!( - xp_gain_line(None, 60, 40, None, &get).as_deref(), + xp_gain_line(Some("Defias Thug"), 60, 40, 1.0, None, &get), + None + ); + assert_eq!( + xp_gain_line(None, 60, 40, 1.0, None, &get).as_deref(), Some("You gain 60 experience.") ); // An XP loss prints the packet's value negated as a signed 32-bit number (`0x637f70`). @@ -3315,7 +3319,7 @@ fn unit_combat_fires_at_its_place_in_the_drain() { { let mut log = feed.world.resource_mut::(); log.push_unit_combat(flash(7, "DODGE")); - log.push_xp_gain(0, 10, 10); + log.push_xp_gain(0, 10, 10, 1.0); log.push_unit_combat(flash(7, "PARRY")); log.push_unit_combat(flash(8, "MISS")); } @@ -3420,7 +3424,7 @@ fn a_kills_unnamed_victim_is_the_unit_getters_miss() { feed.world.resource_mut::().0 = Some(ME); { let mut log = feed.world.resource_mut::(); - log.push_xp_gain(VICTIM, 60, 60); + log.push_xp_gain(VICTIM, 60, 60, 1.0); log.push_pvp_credit(30, VICTIM, 8, 0); } feed.drain(); diff --git a/crates/benilla-protocol/src/messages/progression.rs b/crates/benilla-protocol/src/messages/progression.rs index 82da9e0f7..f179aa3f7 100644 --- a/crates/benilla-protocol/src/messages/progression.rs +++ b/crates/benilla-protocol/src/messages/progression.rs @@ -5,7 +5,7 @@ use std::io::{self, Read}; use crate::wire::{read_f32_le, read_i32_le, read_u32_le, read_u64_le, read_u8}; /// `SMSG_LOG_XPGAIN`: an XP award; `victim` is 0 for non-kill XP (vmangos `Misc.cpp:512-522`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq)] pub struct XpGain { pub victim: u64, pub total: u32, @@ -13,26 +13,30 @@ pub struct XpGain { /// `total - base` is the chat line's "(+N exp Rested bonus)". pub base: u32, pub kill: bool, + /// The group float after the base XP (`0x637e83`-`0x637e96`); only a kill carries it, else + /// 1.0, the handler's own initial value (`0x637e7c`). vmangos always sends 1.0 + /// (`Player.cpp:3039`). + pub group: f32, } /// Read `SMSG_LOG_XPGAIN`: `u64 victim, u32 total, u8 type` (0 kill, 1 other), then for a kill -/// `u32 base, f32 groupBonus`. The group bonus is read and dropped, its chat line not built; -/// vmangos always sends 1.0, meaning none (`Player.cpp:3039`). +/// `u32 base, f32 group`. pub(super) fn read_xp_gain(r: &mut impl Read) -> io::Result { let victim = read_u64_le(r)?; let total = read_u32_le(r)?; let xp_type = read_u8(r)?; let kill = xp_type == 0; - let mut base = total; + let (mut base, mut group) = (total, 1.0); if kill { base = read_u32_le(r)?; - let _group_bonus = read_f32_le(r)?; + group = read_f32_le(r)?; } Ok(XpGain { victim, total, base, kill, + group, }) } diff --git a/crates/benilla-protocol/tests/spells.rs b/crates/benilla-protocol/tests/spells.rs index 9c9735b28..ec4e13fb7 100644 --- a/crates/benilla-protocol/tests/spells.rs +++ b/crates/benilla-protocol/tests/spells.rs @@ -948,7 +948,7 @@ fn combat_log_wire_golden() { body.extend_from_slice(&250u32.to_le_bytes()); // total body.push(0); // xpType: kill body.extend_from_slice(&200u32.to_le_bytes()); // base xp (kept: rested bonus = total − base) - body.extend_from_slice(&1.25f32.to_le_bytes()); // group bonus (dropped) + body.extend_from_slice(&1.25f32.to_le_bytes()); // group float let packet = messages::parse_server(messages::opcode::SMSG_LOG_XPGAIN, &body).unwrap(); match &packet { ServerPacket::XpGain(x) => { @@ -959,6 +959,7 @@ fn combat_log_wire_golden() { total: 250, base: 200, kill: true, + group: 1.25, } ); } @@ -982,6 +983,7 @@ fn combat_log_wire_golden() { total: 50, base: 50, // non-kill carries no base on the wire; base = total kill: false, + group: 1.0, // nor a float: the handler's own 1.0 } ); } diff --git a/crates/benilla-ui/src/strings.rs b/crates/benilla-ui/src/strings.rs index 00613864e..fc26f3280 100644 --- a/crates/benilla-ui/src/strings.rs +++ b/crates/benilla-ui/src/strings.rs @@ -1,9 +1,14 @@ //! Fills the `%` holes of a `GlobalStrings.lua` or `GlueStrings.lua` template read at runtime, as -//! the client's `SStrPrintf` does: `%s`, `%d`, `%c`, `%f` and `%g` take the next argument left to -//! right, `%N$s` takes argument N without moving that cursor (`DUEL_WINNER_RETREAT` reorders its -//! two names), `%%` is `%`, and the precision is the template's. A hole with no argument, or one -//! this does not know, is copied through literally so a mis-modelled template shows. Reals are the -//! MSVC CRT's behind `SStrPrintf` ([`crt_float`]). +//! the client's `SStrPrintf` does. Storm's ordered formatter `vsnoprintf` (`0x6697d0`), which +//! `ClientMain` switches on (`0x402141`), binds each hole to an argument before it prints: a plain +//! hole takes the running index, `%N$` sets that index to N - 1 (`0x669af7`-`0x669b0b`, N = 0 gives +//! 0), and after any hole that takes an argument the running index is its index plus one +//! (`0x669892`-`0x669895`). So `%2$s` then `%s` takes arguments 2 and 3 (`DUEL_WINNER_RETREAT` +//! reorders its two names). An argument no hole names is skipped. `%s`, `%d`, `%c`, `%f` and `%g` +//! print their argument, `%%` is `%`, and the precision is the template's. [`fill`] copies a hole +//! with no argument, or one this does not know, through literally so a mis-modelled template +//! shows; [`fill_exact`] refuses the line instead. Reals are the MSVC CRT's behind `SStrPrintf` +//! ([`crt_float`]). use std::fmt::Write as _; @@ -143,6 +148,14 @@ impl From for Arg<'_> { } impl Arg<'_> { + /// Whether this is the kind a `conv` hole prints as itself, for [`fill_exact`]. + fn fits(&self, conv: char) -> bool { + matches!( + (conv, self), + ('s' | 'c', Arg::S(_)) | ('d', Arg::D(_)) | ('f' | 'g', Arg::F(_)) + ) + } + /// `%s` and `%c`. fn as_s(&self, out: &mut String) { match self { @@ -289,10 +302,26 @@ pub fn plural( /// Fill a reference template, by the rules in the module doc. pub fn fill(template: &str, args: &[Arg<'_>]) -> String { + run(template, args, false).unwrap_or_default() +} + +/// [`fill`] for a caller whose arguments are the template's by construction: `None`, for no line, +/// when a hole has no argument, meets one of another kind (`%s` and `%c` take text, `%d` a +/// number, `%f` and `%g` a real) or is one this does not know. The reference reads each argument +/// by its hole's kind up to the highest index a hole names (`0x6698b5`-`0x669919`), with no check +/// against the arguments it was given, so such a template has no sentence to match: a defect to +/// show. An argument no hole names is not one. +pub fn fill_exact(template: &str, args: &[Arg<'_>]) -> Option { + run(template, args, true) +} + +/// The walk both fills share; `exact` picks the refusal over the literal copy. +fn run(template: &str, args: &[Arg<'_>], exact: bool) -> Option { let mut out = String::with_capacity(template.len() + 16); let chars: Vec = template.chars().collect(); let mut i = 0; - let mut next = 0usize; // the sequential cursor + // The running index, `[ebp-0x8]` of `0x6697d0`. + let mut next = 0usize; while i < chars.len() { if chars[i] != '%' { out.push(chars[i]); @@ -305,34 +334,31 @@ pub fn fill(template: &str, args: &[Arg<'_>]) -> String { continue; } let Some(spec) = parse_spec(&chars, i + 1) else { + if exact { + return None; + } // Unknown: copy the `%` and rescan from the next char, so `50% off` survives. out.push('%'); i += 1; continue; }; - // A positional does not move the sequential cursor. - let idx = match spec.positional { - Some(n) => n.checked_sub(1), - None => Some(next), - }; - match idx.and_then(|k| args.get(k)) { - Some(a) => { - match spec.conv { - 's' | 'c' => a.as_s(&mut out), - 'd' => a.as_d(&mut out), - 'f' => a.as_f(spec.precision, &mut out), - _ => a.as_g(spec.precision, &mut out), - } - if spec.positional.is_none() { - next += 1; - } - } + let idx = spec.positional.map_or(next, |n| n.saturating_sub(1)); + next = idx + 1; + match args.get(idx) { + Some(a) if exact && !a.fits(spec.conv) => return None, + Some(a) => match spec.conv { + 's' | 'c' => a.as_s(&mut out), + 'd' => a.as_d(&mut out), + 'f' => a.as_f(spec.precision, &mut out), + _ => a.as_g(spec.precision, &mut out), + }, + None if exact => return None, // Starved: copy the specifier through so a mis-modelled template shows. None => out.extend(&chars[i..spec.end]), } i = spec.end; } - out + Some(out) } #[cfg(test)] @@ -425,7 +451,7 @@ mod tests { /// The duel pair, `GlobalStrings.lua:958-959`. #[test] - fn positional_specifiers_reorder_rather_than_consume() { + fn positional_specifiers_reorder_the_arguments() { let (a, b) = (Arg::S("Alice"), Arg::S("Bob")); assert_eq!( fill("%1$s has defeated %2$s in a duel", &[a, b]), @@ -438,6 +464,51 @@ mod tests { assert_eq!(fill("%1$s vs %1$s", &[a]), "Alice vs Alice"); } + /// `vsnoprintf` binds each hole before it prints (`0x6697d0`): after a hole that takes an + /// argument the running index is that hole's index plus one (`0x669892`), so a plain hole + /// after `%N$` takes argument N + 1, and `%0$` is the first argument (`0x669afa`-`0x669b0b`). + #[test] + fn a_plain_hole_after_a_positional_takes_the_next_argument() { + let (a, b, c) = (Arg::S("A"), Arg::S("B"), Arg::S("C")); + assert_eq!(fill("%2$s then %s", &[a, b, c]), "B then C"); + assert_eq!(fill("%1$s then %s", &[a, b]), "A then B"); + assert_eq!(fill("%s, %s, %1$s, %s", &[a, b, c]), "A, B, A, B"); + assert_eq!(fill("%0$s", &[a]), "A"); + // A hole with no argument still moves the index: the plain hole after it is starved too. + assert_eq!(fill("%3$s %s", &[a, b]), "%3$s %s"); + } + + /// [`fill_exact`] binds as [`fill`] does and skips an argument no hole names + /// (`0x6698b5`-`0x669919`), but refuses a hole it cannot fill: none left, of another kind, or + /// one it does not know. + #[test] + fn an_exact_fill_skips_unnamed_arguments_and_refuses_a_hole_it_cannot_fill() { + let (name, number) = (Arg::S("Ragnaros"), Arg::D(12)); + let exact = |template| fill_exact(template, &[name, number]); + assert_eq!( + exact("You hit %s for %d.").as_deref(), + Some("You hit Ragnaros for 12.") + ); + assert_eq!( + exact("For %2$d.").as_deref(), + Some("For 12."), + "the name is unused" + ); + assert_eq!( + exact("%2$d, %1$s: 100%%").as_deref(), + Some("12, Ragnaros: 100%") + ); + assert_eq!( + exact("%1$s hits you for %d.").as_deref(), + Some("Ragnaros hits you for 12.") + ); + assert_eq!(exact("%3$s"), None, "no third argument"); + assert_eq!(exact("%1$d"), None, "text in a number's hole"); + assert_eq!(exact("%2$s"), None, "a number in a text hole"); + assert_eq!(exact("50% off"), None, "a hole it does not know"); + assert_eq!(exact("%s %d %d"), None, "starved after two"); + } + #[test] fn each_hole_takes_its_own_argument() { assert_eq!( diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 462ba09eb..235f0bd1a 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -309,7 +309,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### ui_chat -- Not run on benilla's same-character reconnect, which the reference lacks (it returns to the login screen), so the window keeps its scrollback there. ([`src/ui_chat.rs:216`](../crates/benilla-app/src/ui_chat.rs#L216)) +- Not run on benilla's same-character reconnect, which the reference lacks (it returns to the login screen), so the window keeps its scrollback there. ([`src/ui_chat.rs:218`](../crates/benilla-app/src/ui_chat.rs#L218)) - A missing global prints nothing, where the reference prints an empty line (`0x703c02`), because benilla's other `DisplayError` routes do the same. ([`src/ui_chat/broadcast.rs:152`](../crates/benilla-app/src/ui_chat/broadcast.rs#L152)) - With a blank city word the reference composes `"Trade - "` (its capital arm checks the row pointer, not the string, `0x49a2d0`-`0x49a2f6`); we decline, because a wrong channel name is joined silently and for good. ([`src/ui_chat/channels.rs:150`](../crates/benilla-app/src/ui_chat/channels.rs#L150)) - A probe's bare `/assist` assists the live selection, where the stock handler (`ChatFrame.lua:740`) resolves a selected player's name through `AssistByName`, because a name resolve can land on a different player. ([`src/ui_chat/input/mod.rs:631`](../crates/benilla-app/src/ui_chat/input/mod.rs#L631))