Template caches persist between sessions, as 1.12.1's do (#2352)

Item, object, quest and text records are kept between sessions, as 1.12.1 keeps its template caches.

- **Which stores persist:** each store's constructor sets a persist byte at `+0x39`. The creature, game object, item name, item, NPC text, quest, page text and item text stores are saved. The name, guild, pet-name and petition stores are session-only and cleared at world entry (`0x555740`).
- **The file:** one per store per realm under `benilla-config/cache/`, in the reference's layout, header-checked (build, locale, record size), with a hit sending no query (`0x5586ca`). The records are the server's answer bytes, decoded on load by the live decoder.
- **The item-name store** answers `CMSG_ITEM_NAME_QUERY` (`0x559fe0`), and item-set member names read it.
- **Cleanup:** the old creature-only file is removed on load, and three comments that called the name caches persistent are corrected.

Tests cover every store across a session, header mismatches, eviction and the live packet path.

Fixes #85

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Sung
2026-10-24 20:34:38 +07:00
committed by GitHub
parent 965fda84f3
commit 359eff416a
33 changed files with 1675 additions and 608 deletions
+4 -5
View File
@@ -24,7 +24,6 @@ use crate::entities::EntitiesPlugin;
use crate::fishing_line::FishingLinePlugin;
use crate::footprints::FootprintsPlugin;
use crate::loading_screen::LoadingScreenPlugin;
use crate::name_persist::NamePersistPlugin;
use crate::net::NetPlugin;
use crate::player::PlayerPlugin;
use crate::portrait::PortraitPlugin;
@@ -232,7 +231,8 @@ impl PluginGroup for GamePlugins {
.add(UiTradePlugin)
.add(UiItemTextPlugin)
.add(UiSavedPlugin)
.add(NamePersistPlugin)
.add(crate::item_names::ItemNamesPlugin)
.add(crate::wdb::WdbPlugin)
.add(UiStablePlugin)
.add(TabardUiPlugin)
.add(UiTrainerPlugin)
@@ -976,9 +976,8 @@ pub(crate) mod schedule_tests {
/// against the 80 world systems no declared order places against it, which bevy lists with
/// no component. What they meet of the drain's (its lanes' firings, the VM with the call host,
/// and the unit edits it applies in place: every component a change writes, the cast events,
/// the precast tail's loot release) is the name cache alone, a pure cache, which the
/// persisted-name load writes; `lanes::guard_tests` checks that it stays so, and that no
/// exclusive system is among them. Commands a firing defers, which the drain applies after
/// the precast tail's loot release) is the name cache alone, a pure cache;
/// `lanes::guard_tests` checks that it stays so, and that no exclusive system is among them. Commands a firing defers, which the drain applies after
/// it, are outside that model;
/// - the minimap's draw (`minimap::emit_minimap`), which reads `QuestGiver`'s dialog statuses,
/// against `ui_panes::feed_character_panes`, which lends the call host, whose quest verbs
+9
View File
@@ -183,6 +183,15 @@ impl GameObjectTemplates {
.send(ClientCommand::GameObjectQuery { entry, guid });
}
/// The template store, the one [`crate::wdb`] saves.
pub(crate) fn template_store(&self) -> &QueryCache<u32, GoTemplate> {
&self.templates
}
pub(crate) fn template_store_mut(&mut self) -> &mut QueryCache<u32, GoTemplate> {
&mut self.templates
}
/// A refused entry (`SMSG_GAMEOBJECT_QUERY_RESPONSE` with the top bit set, `0x5588e0`): no
/// template, and the next lookup asks again ([`QueryCache::refuse`]).
pub(crate) fn refuse(&mut self, entry: u32) {
+73
View File
@@ -0,0 +1,73 @@
//! The item-name store (`0xc0e2dc`), apart from the item templates: `CMSG_ITEM_NAME_QUERY` asks
//! one item's name and `SMSG_ITEM_NAME_QUERY_RESPONSE` answers it (lookup `0x559fe0`, reader
//! `0x7c8dc0`). The reference reads an item set's member names through it (`0x52df5a`), never
//! through the template store, and saves it to `itemnamecache.wdb` ([`crate::wdb`]).
use benilla_protocol::{SessionEvent, SessionEventKind};
use bevy::prelude::*;
use crate::net::{ClientCommand, NetCommands, NetHandlerApp};
use crate::query_cache::{Ask, QueryCache};
/// Item names by entry, asked once while in flight.
#[derive(Resource, Default)]
pub(crate) struct ItemNames {
names: QueryCache<u32, String>,
}
impl crate::query_cache::AskOnce for ItemNames {
fn clear_pending(&mut self) {
self.names.clear_pending();
}
}
impl ItemNames {
/// The name of `entry`, read as `ask` says. The set tooltip's lookup passes a zero owner
/// (`0x52df41`-`0x52df44`), so the query's guid is 0.
pub(crate) fn name(&self, entry: u32, ask: Ask<'_>) -> Option<&str> {
self.names
.read(entry, ask, |commands: &NetCommands| {
debug!("item names: asking item {entry}");
let _ = commands
.0
.send(ClientCommand::ItemNameQuery { entry, guid: 0 });
})
.map(String::as_str)
}
/// Files an answer; `None` is the store's refusal (`0x556e67`).
pub(crate) fn file(&mut self, entry: u32, name: Option<String>) {
match name {
Some(name) => self.names.insert(entry, name),
None => {
self.names.refuse(entry);
}
}
}
/// The name store, the one [`crate::wdb`] saves.
pub(crate) fn store(&self) -> &QueryCache<u32, String> {
&self.names
}
pub(crate) fn store_mut(&mut self) -> &mut QueryCache<u32, String> {
&mut self.names
}
}
pub(crate) struct ItemNamesPlugin;
impl Plugin for ItemNamesPlugin {
fn build(&self, app: &mut App) {
crate::query_cache::register::<ItemNames>(app);
app.init_resource::<ItemNames>()
.net_handler(SessionEventKind::ItemName, on_item_name);
}
}
/// `SMSG_ITEM_NAME_QUERY_RESPONSE`: the record lands, or the refusal frees the key.
fn on_item_name(In(ev): In<SessionEvent>, mut names: ResMut<ItemNames>) {
if let SessionEvent::ItemName { entry, name } = ev {
names.file(entry, name);
}
}
+18
View File
@@ -665,6 +665,24 @@ impl Items {
}
}
/// The template store, the one [`crate::wdb`] saves.
pub(crate) fn template_store(&self) -> &QueryCache<u32, ItemInfo> {
&self.templates
}
pub(crate) fn template_store_mut(&mut self) -> &mut QueryCache<u32, ItemInfo> {
&mut self.templates
}
/// Drops every template, which the interface's copy drops too: another realm's file replaces
/// them.
pub(crate) fn forget_templates(&mut self) {
self.dropped
.extend(self.templates.iter().map(|(&entry, _)| entry));
self.fresh.clear();
self.templates.clear();
}
/// Bumped by every landed answer, for consumers besides the drain; the stand-in for the
/// reference's `DBCACHECALLBACK` redisplay (`0x6e29b0`).
pub(crate) fn template_epoch(&self) -> u64 {
+2 -2
View File
@@ -576,8 +576,8 @@ const READS_FRAME_FINAL: &[(&str, &[&str])] = &[
"ui_petition::PetitionRecords"]),
("::ui_items::feed::feed_item_stats", &["items::Items", "net::HomeBind", "net::ObjectStore",
"spell::mods::SpellModifiers"]),
("::ui_items::feed::feed_item_sets", &["items::Items", "net::ObjectStore",
"spell::mods::SpellModifiers"]),
("::ui_items::feed::feed_item_sets", &["item_names::ItemNames", "items::Items",
"net::ObjectStore", "spell::mods::SpellModifiers"]),
("::ui_items::feed::ask_item_build_lookups", &["items::Countdowns", "names::NameCache",
"net::GuidIndex", "net::ObjectStore", "ui_petition::PetitionRecords"]),
("::ui_items::feed::feed_player_req", &["net::ObjectStore", "net::Proficiencies",
+2 -1
View File
@@ -64,6 +64,7 @@ mod go_templates;
#[cfg(feature = "dev")]
mod hover_log;
mod item_lane;
mod item_names;
mod item_watch;
mod items;
mod lanes;
@@ -98,7 +99,6 @@ mod script_calls;
mod shaders;
mod game_tip;
mod name_persist;
mod opaque2d;
/// Where "the client is going down" is observed, in `Last`; every system that persists state on the
/// way out registers through it.
@@ -188,6 +188,7 @@ mod ui_world_map;
mod video;
mod vm_pass;
mod vplates;
mod wdb;
mod weapon_trail;
mod world_backdrop;
mod world_console;
+15 -6
View File
@@ -354,12 +354,21 @@ pub(crate) fn move_character_state(realm: &str, old: &str, new: &str) {
}
}
/// `benilla-config/cache/<realm>.tsv`: the player, creature and pet names the server has answered,
/// one file for the reference's `WDB/namecache.wdb`, `creaturecache.wdb` and `petnamecache.wdb`.
///
/// Realm-scoped, where the reference's is not: guids, creature entries and pet numbers are
/// realm-local, so one shared file would serve a realm another realm's names.
pub(crate) fn name_cache_path(realm: &str) -> Option<PathBuf> {
/// `benilla-config/cache/<realm>/<store>.bin`: one saved template store ([`crate::wdb`]), the
/// reference's `WDB/<store>.wdb`. Realm-scoped, where the reference's is not: a template key is
/// the server's, so another realm may hold another template under it.
pub(crate) fn template_cache_path(realm: &str, store: &str) -> Option<PathBuf> {
Some(
home()?
.join("cache")
.join(file_token(realm))
.join(format!("{store}.bin")),
)
}
/// `benilla-config/cache/<realm>.tsv`: the creature names an earlier build kept, which the
/// realm's saved stores replace; [`crate::wdb`] removes it.
pub(crate) fn retired_name_cache_path(realm: &str) -> Option<PathBuf> {
Some(
home()?
.join("cache")
-249
View File
@@ -1,249 +0,0 @@
//! The creature-template half of [`crate::names::NameCache`], kept across sessions: benilla's
//! `creaturecache.wdb`.
//!
//! The reference persists only `'WNPC'`; `'WNAM'` and `'WPNM'` (player and pet names) are built
//! with persistence off (`0x554cd0`) and cleared at world-session start
//! ([`NameCache::clear_world_session`]). A template entry keeps its meaning, while a player guid
//! or pet number can come to name another character or spawn.
//!
//! From `DBCache.cpp` (`0x554b00`-`0x5738c0`): the 20-byte header
//! `[FourCC | build 0x16f3 | locale | recordSize | version 1]` is compared by equality, with no
//! checksum or TTL, and a mismatch discards the file ([`NameCache::to_tsv`] writes ours).
//! Eviction is explicit only: a high-bit key in a response, or `SMSG_INVALIDATE_PLAYER` (`0x31C`).
//!
//! Deviation: the file is `benilla-config/cache/<realm>.tsv` through [`crate::local_state`], not
//! `WDB/` in the install, because the install is read-only; and it is per realm, because another
//! server may hold a different template under the same entry.
use std::path::PathBuf;
use bevy::prelude::*;
use crate::glue_session::roster::Roster;
use crate::names::NameCache;
/// Seconds between writes: answers arrive in bursts on zone-in, and a crash costs only re-asking.
const SAVE_DEBOUNCE: f32 = 10.0;
pub(crate) struct NamePersistPlugin;
impl Plugin for NamePersistPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<NameCacheFile>()
.add_systems(Update, (load_name_cache, save_name_cache).chain());
// The exit write catches the last burst, which the debounce would not.
crate::shutdown::on_app_exit(app, save_on_exit.into_configs());
}
}
/// Where this realm's cache lives and what we last wrote there.
#[derive(Resource, Default)]
pub(crate) struct NameCacheFile {
/// The realm the loaded file belongs to; a change triggers a load.
realm: Option<String>,
path: Option<PathBuf>,
/// [`NameCache::generation`] at the last write: the dirty bit, which ticks on an answer.
saved_generation: u64,
since_save: f32,
}
/// Loads the realm's cache the first frame its identity is known, and on a realm change.
fn load_name_cache(
roster: Res<Roster>,
mut file: ResMut<NameCacheFile>,
mut names: ResMut<NameCache>,
) {
let Some((realm, _)) = crate::ui_macro::identity(&roster) else {
return;
};
if file.realm.as_deref() == Some(realm.as_str()) {
return;
}
let path = crate::local_state::name_cache_path(&realm);
file.realm = Some(realm.clone());
file.path = path.clone();
file.saved_generation = names.generation();
let Some(path) = path else {
return; // a hermetic capture, or no state folder: session-only
};
let Ok(text) = std::fs::read_to_string(&path) else {
return; // no cache yet
};
match NameCache::from_tsv(&text, &realm) {
Some(loaded) => {
let n = loaded.len();
// Install only the file's records: this runs as the pick is in flight, beside the
// login's clear and seed of our own name, and must not replace them.
names.install_persisted(loaded);
file.saved_generation = names.generation();
debug!(
"names: loaded {n} cached records for {realm} from {}",
path.display()
);
}
// A header mismatch discards the file, as the reference does; the first save overwrites it.
None => debug!(
"names: discarding {} — header is not this build/locale/format",
path.display()
),
}
}
/// Writes the cache when answers have landed and the debounce has elapsed.
fn save_name_cache(time: Res<Time>, mut file: ResMut<NameCacheFile>, names: Res<NameCache>) {
file.since_save += time.delta_secs();
if file.since_save < SAVE_DEBOUNCE {
return;
}
file.since_save = 0.0;
write_now(&mut file, &names);
}
/// The exit write, regardless of the debounce.
fn save_on_exit(mut file: ResMut<NameCacheFile>, names: Res<NameCache>) {
write_now(&mut file, &names);
}
fn write_now(file: &mut NameCacheFile, names: &NameCache) {
if names.generation() == file.saved_generation {
return; // nothing landed since the last write
}
let (Some(path), Some(realm)) = (file.path.clone(), file.realm.clone()) else {
return;
};
if let Some(dir) = path.parent() {
if let Err(e) = std::fs::create_dir_all(dir) {
warn!("names: cannot create {}: {e}", dir.display());
return;
}
}
match crate::local_state::write_atomic(&path, &names.to_tsv(&realm)) {
Ok(()) => {
file.saved_generation = names.generation();
debug!("names: wrote {} records to {}", names.len(), path.display());
}
Err(e) => warn!("names: cannot write {}: {e}", path.display()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::local_state::test_env::{EnvGuard, ENV_LOCK};
use crate::query_cache::Ask;
/// A roster with a pick in flight and no realm: [`crate::ui_macro::identity`] answers
/// `("Realm", <name>)`.
fn roster_with_pick(name: &str, guid: u64) -> Roster {
Roster::with_pending_pick(
vec![benilla_protocol::Character {
guid,
name: name.into(),
race: 1,
class: 1,
gender: 0,
skin: 0,
face: 0,
hair_style: 0,
hair_color: 0,
facial_hair: 0,
level: 1,
new_character: false,
zone: 0,
map: 0,
position: benilla_protocol::wire::Vector3d {
x: 0.0,
y: 0.0,
z: 0.0,
},
flags: 0,
equipment: [benilla_protocol::CharEnumItem::default(); 19],
pet_display_id: 0,
pet_level: 0,
pet_family: 0,
}],
guid,
)
}
/// The load runs after the login's seed of our own name, the order that would lose it, which
/// left `UnitName("player")` nil on the first login.
#[test]
fn the_disk_load_installs_templates_without_touching_the_live_session() {
use benilla_protocol::guid;
/// `counter | (entry << 24) | (high << 48)`, the server's composition.
fn compose(high: u16, entry: u32, counter: u32) -> u64 {
u64::from(counter) | (u64::from(entry) << 24) | (u64::from(high) << 48)
}
const CREATURE_ENTRY: u32 = 1234;
const PET_NUMBER: u32 = 7;
let me = compose(guid::HIGH_PLAYER, 0, 0x2A);
let pet = compose(guid::HIGH_PET, PET_NUMBER, 9);
let guard = compose(guid::HIGH_UNIT, CREATURE_ENTRY, 1);
let _l = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let tmp = std::env::temp_dir().join(format!("benilla-namecache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let _capture = EnvGuard::unset("WOW_CAPTURE");
let _home = EnvGuard::set("BENILLA_HOME", tmp.to_str().expect("utf-8 temp path"));
// A realm file with one creature template, written by the saver so the header matches.
let mut on_disk = NameCache::default();
on_disk.insert_creature(
CREATURE_ENTRY,
Some(crate::names::CreatureRecord {
name: "Stormwind Guard".into(),
subname: None,
creature_type: 7,
pet_family: 0,
rank: 0,
type_flags: 0,
pet_spell_list: 0,
civilian: false,
racial_leader: false,
display_id: 0,
}),
);
let path = crate::local_state::name_cache_path("Realm").expect("a state folder");
std::fs::create_dir_all(path.parent().expect("cache dir")).expect("cache dir");
std::fs::write(&path, on_disk.to_tsv("Realm")).expect("write the realm cache");
// The login has already seeded our own name and a pet's, as `net::session::connected` does.
let mut names = NameCache::default();
names.insert_player(me, "Nelprifour".into(), None);
names.insert_pet(PET_NUMBER, "Fluffy".into());
let before = names.generation();
let mut app = App::new();
app.insert_resource(roster_with_pick("Nelprifour", me))
.insert_resource(names)
.init_resource::<NameCacheFile>()
.add_systems(Update, load_name_cache);
app.update();
let names = app.world().resource::<NameCache>();
assert_eq!(
names.resolve_unit(me, None, Ask::Read),
Some("Nelprifour"),
"the login's seed of our own name must survive the disk load — losing it is the bug"
);
assert_eq!(
names.resolve_unit(pet, None, Ask::Read),
Some("Fluffy"),
"…and so must a pet name: the file carries neither, so neither is its to replace"
);
assert_eq!(
names.resolve_unit(guard, None, Ask::Read),
Some("Stormwind Guard"),
"the file's own records are what the load is for"
);
assert!(
names.generation() > before,
"a landed record moves the counter the gated feeds watch"
);
let _ = std::fs::remove_dir_all(&tmp);
}
}
+44 -299
View File
@@ -8,9 +8,9 @@
//! a reader that runs every frame uses: the reference's per-frame readers read the unit's cached
//! record (`[unit+0xb30]`, `0x60934b`), which only a lookup with a callback fills (`0x604660`).
//!
//! Creature templates persist, as the reference's `creaturecache.wdb` does, and a refusal never
//! does; player and pet names are never written to disk and are cleared at world-session start, as
//! the reference does.
//! Creature templates are kept on disk, as the reference's `creaturecache.wdb` is ([`crate::wdb`]);
//! player and pet names are never written to disk and are cleared at world entry, as the
//! reference's stores, built with persistence off, are (`0x554cd0`, `0x555740`).
use std::collections::HashMap;
@@ -311,14 +311,13 @@ impl NameCache {
self.generation = self.generation.wrapping_add(1);
}
/// Install the creature templates read off disk, replacing (not merging) the current ones and
/// touching nothing else: the load can land after the login has seeded our own name, which
/// must survive it.
pub(crate) fn install_persisted(&mut self, loaded: NameCache) {
self.creatures = loaded.creatures;
let entries: Vec<u32> = self.creatures.iter().map(|(&e, _)| e).collect();
self.creature_landings.extend(entries);
self.generation = self.generation.wrapping_add(1);
/// The creature-template store, the one [`crate::wdb`] saves.
pub(crate) fn creature_store(&self) -> &QueryCache<u32, CreatureRecord> {
&self.creatures
}
pub(crate) fn creature_store_mut(&mut self) -> &mut QueryCache<u32, CreatureRecord> {
&mut self.creatures
}
/// The landed-answer counter.
@@ -416,107 +415,7 @@ impl crate::query_cache::AskOnce for NameCache {
}
}
// ─────────────────────────────────────────────────────────────────────────────────────────────
// Persistence
// ─────────────────────────────────────────────────────────────────────────────────────────────
/// The file's first line; any field that differs on load discards the whole file, the
/// reference's rule for its `.wdb` header (`[FourCC | build 0x16f3 | locale | recordSize |
/// version 1]`, no checksum, no timestamp, no TTL).
const CACHE_MAGIC: &str = "benilla-namecache";
/// Our record-layout version; bump it when a column changes. Version 3 holds creature records
/// only, the pet spell list among them.
const CACHE_FORMAT: u32 = 3;
/// The client build, the reference's `0x16f3`.
const CACHE_BUILD: u32 = 5875;
/// The header's locale, the client's locale tag as each `.wdb` header carries it (`[0xc2a2a4]`,
/// written at `0x5567d9` and compared at `0x5573c6`): the server names creatures in the locale the
/// logon challenge sent, so a cache from another locale is discarded. Its four bytes as text,
/// `enGB`; empty for tag 0, an install with no `Wow.ini` locale.
fn cache_locale() -> String {
let tag = crate::ui_script::client_locale().tag().to_be_bytes();
String::from_utf8_lossy(&tag)
.trim_start_matches('\0')
.to_string()
}
impl NameCache {
/// Serialize as TSV: the header line, then one line per creature record. In-flight asks and
/// refusals are not written: the reference saves no freed node.
pub(crate) fn to_tsv(&self, realm: &str) -> String {
let locale = cache_locale();
let mut out = format!("{CACHE_MAGIC}\t{CACHE_FORMAT}\t{CACHE_BUILD}\t{locale}\t{realm}\n");
for (entry, r) in self.creatures.iter() {
out.push_str(&format!(
"C\t{entry}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
r.creature_type,
r.pet_family,
r.rank,
r.type_flags,
u8::from(r.civilian),
u8::from(r.racial_leader),
r.display_id,
r.pet_spell_list,
r.name,
r.subname.as_deref().unwrap_or("")
));
}
out
}
/// Rebuild a cache from [`Self::to_tsv`]'s output, `None` when the header differs; a
/// malformed line is skipped, and so is a `c` line, the negative an earlier build wrote.
pub(crate) fn from_tsv(text: &str, realm: &str) -> Option<Self> {
let mut lines = text.lines();
let header: Vec<&str> = lines.next()?.split('\t').collect();
if header.len() != 5
|| header[0] != CACHE_MAGIC
|| header[1] != CACHE_FORMAT.to_string()
|| header[2] != CACHE_BUILD.to_string()
|| header[3] != cache_locale()
|| header[4] != realm
{
return None;
}
let mut cache = NameCache::default();
for line in lines {
let f: Vec<&str> = line.split('\t').collect();
match f.first().copied() {
Some("C") if f.len() >= 12 => {
let Ok(entry) = f[1].parse::<u32>() else {
continue;
};
let (Ok(creature_type), Ok(pet_family), Ok(rank), Ok(type_flags)) =
(f[2].parse(), f[3].parse(), f[4].parse(), f[5].parse())
else {
continue;
};
let (Ok(display_id), Ok(pet_spell_list)) = (f[8].parse(), f[9].parse()) else {
continue;
};
cache.creatures.insert(
entry,
CreatureRecord {
name: f[10].to_string(),
// Empty is no subname, as in the wire decode.
subname: (!f[11].is_empty()).then(|| f[11].to_string()),
creature_type,
pet_family,
rank,
type_flags,
pet_spell_list,
civilian: f[6] == "1",
racial_leader: f[7] == "1",
display_id,
},
);
}
_ => {}
}
}
Some(cache)
}
/// Drop a player's cached name and traits so the next resolve re-asks: the reference's
/// remove-by-key for `SMSG_INVALIDATE_PLAYER` (`0x555600` into `0x560170`).
pub(crate) fn invalidate_player(&mut self, guid: u64) {
@@ -524,11 +423,6 @@ impl NameCache {
self.player_traits.remove(&guid);
self.generation = self.generation.wrapping_add(1);
}
/// How many records the cache holds.
pub(crate) fn len(&self) -> usize {
self.players.len() + self.creatures.len() + self.pets.len()
}
}
/// The three name-query answers and `SMSG_INVALIDATE_PLAYER`.
@@ -734,6 +628,40 @@ pub(crate) mod net {
names.invalidate_player(guid);
}
/// Files a `SMSG_CREATURE_QUERY_RESPONSE` read off disk ([`crate::wdb`]), as the handler files a
/// live one, with no unit waiting on it.
pub(crate) fn file_creature(ev: SessionEvent, names: &mut NameCache) {
if let SessionEvent::CreatureName {
entry,
name,
subname,
creature_type,
pet_family,
rank,
type_flags,
pet_spell_list,
display_id,
civilian,
racial_leader,
} = ev
{
creature_name(
entry,
name,
subname,
creature_type,
pet_family,
rank,
type_flags,
pet_spell_list,
civilian,
racial_leader,
display_id,
names,
);
}
}
/// `SMSG_CREATURE_QUERY_RESPONSE`; a `None` name is the server's "no such entry".
fn creature_name(
entry: u32,
@@ -1025,110 +953,6 @@ mod tests {
);
}
/// A refusal is not written, so an unknown entry is asked again at the next login.
#[test]
fn the_cache_round_trips_through_its_file_format() {
let mut cache = NameCache::default();
cache.insert_creature(
69,
Some(CreatureRecord {
name: "Stable Master Kitrik".into(),
subname: Some("Stable Master".into()),
creature_type: 7,
pet_family: 0,
rank: 1,
type_flags: 0x10,
pet_spell_list: 5796,
civilian: true,
racial_leader: false,
display_id: 533,
}),
);
cache.insert_creature(1234, None); // the server flagged the entry unknown
let text = cache.to_tsv("Hydraxian Waterlords");
assert!(
!text.lines().any(|l| l.split('\t').nth(1) == Some("1234")),
"a refusal is not a line of the file"
);
let back = NameCache::from_tsv(&text, "Hydraxian Waterlords").expect("header matches");
assert!(
!back.creatures.answered(1234),
"and so it does not come back"
);
let rec = back.creature_record(69).expect("creature survived");
assert_eq!(rec.name, "Stable Master Kitrik");
assert_eq!(rec.subname.as_deref(), Some("Stable Master"));
assert_eq!((rec.creature_type, rec.rank, rec.type_flags), (7, 1, 0x10));
assert_eq!((rec.civilian, rec.racial_leader), (true, false));
assert_eq!(rec.display_id, 533, "the model a stabled pet is drawn from");
assert_eq!(rec.pet_spell_list, 5796, "the studied block's abilities");
assert!(back.creature_record(1234).is_none());
assert_eq!(back.len(), 1);
// `Some("")` would paint an empty tooltip line.
cache.insert_creature(
70,
Some(CreatureRecord {
name: "Boar".into(),
subname: None,
creature_type: 1,
pet_family: 5,
rank: 0,
type_flags: 0,
pet_spell_list: 0,
civilian: false,
racial_leader: false,
display_id: 1,
}),
);
let back = NameCache::from_tsv(&cache.to_tsv("R"), "R").expect("header");
assert_eq!(back.creature_record(70).unwrap().subname, None);
}
/// The reference builds `'WNAM'` (ctor `0x554cd0`) and `'WPNM'` with persistence off; a 1.12
/// install's `WDB/` holds `creaturecache.wdb` and no `namecache.wdb`.
#[test]
fn the_file_keeps_creature_templates_and_no_identities() {
let mut cache = NameCache::default();
cache.insert_player(0x11, "Moamtester".into(), Some((1, 2, 0)));
cache.insert_pet(7, "Rex".into());
cache.insert_creature(
69,
Some(CreatureRecord {
name: "Stable Master Kitrik".into(),
subname: Some("Stable Master".into()),
creature_type: 7,
pet_family: 0,
rank: 1,
type_flags: 0x10,
pet_spell_list: 0,
civilian: true,
racial_leader: false,
display_id: 533,
}),
);
let text = cache.to_tsv("R");
assert!(
!text.contains("Moamtester") && !text.contains("Rex"),
"no guid- or spawn-keyed name may reach the disk:\n{text}"
);
let back = NameCache::from_tsv(&text, "R").expect("header matches");
assert_eq!(
back.resolve_unit(0x11, None, Ask::Read),
None,
"a player name never survives the file"
);
assert_eq!(back.player_traits(0x11), None);
assert_eq!(
back.creature_record(69).map(|r| r.name.as_str()),
Some("Stable Master Kitrik"),
"the template entry is the key that keeps meaning what it meant",
);
}
/// The reference's `0x555740` clears the stores whose `[cache+0x39]` byte is 0
/// (`0x55579f`-`0x5557ad` for the player cache at `0xc0e228`).
#[test]
@@ -1163,61 +987,6 @@ mod tests {
assert_eq!(cache.player_traits(0x7), None);
}
#[test]
fn a_header_that_differs_in_any_field_discards_the_whole_file() {
let mut cache = NameCache::default();
cache.insert_creature(1234, Some(record("Defias Thug")));
let good = cache.to_tsv("Hydraxian Waterlords");
assert!(NameCache::from_tsv(&good, "Hydraxian Waterlords").is_some());
// The realm: our field, not the reference's.
assert!(NameCache::from_tsv(&good, "Another Realm").is_none());
// The locale field is the client's tag, as the reference's `.wdb` header holds it.
let tag = crate::ui_script::client_locale().tag().to_be_bytes();
let spelled = String::from_utf8_lossy(&tag)
.trim_start_matches('\0')
.to_string();
assert_eq!(
good.lines().next().unwrap().split('\t').nth(3),
Some(&*spelled)
);
let head = good.lines().next().unwrap();
for (field, bad) in [
(0, "not-benilla"),
(1, "999"), // format version
(2, "5876"), // client build
(3, "frFR"), // locale
] {
let mut parts: Vec<&str> = head.split('\t').collect();
parts[field] = bad;
let text = format!("{}\n{}", parts.join("\t"), good.lines().nth(1).unwrap());
assert!(
NameCache::from_tsv(&text, "Hydraxian Waterlords").is_none(),
"header field {field} = {bad} must discard the file"
);
}
assert!(NameCache::from_tsv("", "R").is_none());
assert!(NameCache::from_tsv("nonsense", "R").is_none());
let text = format!(
"{}\nC\tnotanumber\t1\t2\t0\tX\nc\t1234\nC\t88\t7\t0\t1\t0\t0\t0\t5\t0\tGuard\t\n",
head
);
let back = NameCache::from_tsv(&text, "Hydraxian Waterlords").expect("header still good");
assert_eq!(back.len(), 1, "the bad line is skipped, the good one kept");
assert!(back.creature_record(88).is_some());
// A version-1 file, which held player names, is discarded whole.
let v1 = format!(
"{CACHE_MAGIC}\t1\t{CACHE_BUILD}\t{}\tHydraxian Waterlords\n\
P\t7\t1\t1\t0\tMoamtester\n",
cache_locale()
);
assert!(NameCache::from_tsv(&v1, "Hydraxian Waterlords").is_none());
}
#[test]
fn invalidating_a_player_makes_the_next_resolve_ask_again() {
let (cmds, rx) = commands();
@@ -1391,30 +1160,6 @@ mod tests {
assert_ne!(cache.generation(), before);
}
/// An earlier build wrote its refusals as `c` lines. They load as nothing, and the records
/// around them load.
#[test]
fn a_file_with_negative_lines_loads_without_them() {
let mut cache = NameCache::default();
cache.insert_creature(69, Some(record("Stable Master")));
let written = cache.to_tsv("R");
let (header, rest) = written.split_once('\n').expect("a header line");
let old = format!("{header}\nc\t1234\n{rest}c\t77\n");
let back = NameCache::from_tsv(&old, "R").expect("the header is this build's");
assert!(!back.creatures.answered(1234), "a negative line is dropped");
assert!(!back.creatures.answered(77));
assert_eq!(back.len(), 1);
assert_eq!(
back.creature_record(69).map(|r| r.name.as_str()),
Some("Stable Master")
);
assert!(
!back.to_tsv("R").contains("1234"),
"and the next save does not bring it back"
);
}
#[test]
fn clear_pending_allows_a_reconnect_reask() {
let (cmds, rx) = commands();
+5
View File
@@ -1032,6 +1032,11 @@ pub(crate) enum ClientCommand {
pet_number: u32,
guid: u64,
},
/// `CMSG_ITEM_NAME_QUERY`, sent only by [`crate::item_names::ItemNames`]' lookups.
ItemNameQuery {
entry: u32,
guid: u64,
},
/// `CMSG_ITEM_QUERY_SINGLE` (`guid` 0 for template-only), sent only by
/// [`crate::items::Items`]' ask-once resolve.
ItemQuery {
+16 -1
View File
@@ -950,6 +950,18 @@ enum StreamEnd {
Back(&'static str),
}
/// A packet's events in the order the app hears them. A saved store's answer sends its bytes
/// ([`SessionEvent::SavedAnswer`]) ahead of its decoded record, so a store never holds a record
/// whose bytes are still on the way.
pub(crate) fn inbound(opcode: u16, events: Vec<SessionEvent>, body: Vec<u8>) -> Vec<SessionEvent> {
if !crate::wdb::is_saved_answer(opcode) {
return events;
}
std::iter::once(SessionEvent::SavedAnswer { opcode, body })
.chain(events)
.collect()
}
/// The world stream: every packet off the socket into [`SessionEvent`]s until a logout or a refused
/// character login ends the world session, the socket fails or the app exits.
fn stream(
@@ -989,7 +1001,7 @@ fn stream(
&wire_trace::in_line(opcode, events.len(), &body),
);
}
for ev in events {
for ev in inbound(opcode, events, body) {
// The pong bypass: the reference's `OnData` (`0x537b10`) hands `SMSG_PONG` to
// `HandlePong` (`0x537d60`) inline, not onto the game thread's queue, so it is
// timed and consumed here.
@@ -1327,6 +1339,9 @@ pub(super) fn writer_loop(
w.pet_name_query(pet_number, guid)
}
ClientCommand::ItemQuery { entry, guid } => w.item_query(entry, guid),
ClientCommand::ItemNameQuery { entry, guid } => {
w.item_name_query(entry, guid)
}
ClientCommand::UseItem {
bag_index,
slot,
+2
View File
@@ -269,6 +269,7 @@ impl<K: Copy + Eq + Hash + Default, V> QueryCache<K, V> {
self.answered.iter()
}
#[cfg(test)]
/// How many records it holds.
pub(crate) fn len(&self) -> usize {
self.answered.len()
@@ -320,6 +321,7 @@ pub(crate) fn queries(
| C::CreatureQuery { .. }
| C::PetNameQuery { .. }
| C::ItemQuery { .. }
| C::ItemNameQuery { .. }
| C::NpcTextQuery { .. }
| C::GameObjectQuery { .. }
| C::PageTextQuery { .. }
+13 -5
View File
@@ -3,8 +3,6 @@
//! slots ([`GossipVerbs`]), and so does `CloseGossip`'s close core.
//! As in the reference's `0x4e2010`, a menu opens only once its greeting is drawn.
use std::collections::HashMap;
use benilla_protocol::messages::{select_greeting, GossipOption, NpcTextBlock};
use bevy::prelude::*;
@@ -12,7 +10,7 @@ use benilla_ui::script::{GossipMenu, GossipOptionView, GossipQuestRow};
use crate::names::NameCache;
use crate::net::{Guid, NetCommands, ObjectStore, SelfPlayer};
use crate::query_cache::Ask;
use crate::query_cache::{Ask, QueryCache};
use crate::ui_quest::row_is_active;
use crate::ui_script::{SweepApp, SweepLeg, UiFeed};
use crate::ui_session::{LatchApp, LatchedWindow, NpcWindow};
@@ -30,7 +28,8 @@ pub(crate) struct GossipState {
/// because `GetGossipAvailableQuests` and `GetGossipActiveQuests` return `(title, level)`
/// pairs, walked in twos by stock `GossipFrame.lua` (lines 66 and 90).
pub(crate) quests: Vec<(u32, u32, u32, String)>,
records: HashMap<u32, Vec<NpcTextBlock>>,
/// The NPC-text store (`0xc0e264`), which [`crate::wdb`] saves; the menu sends its own query.
records: QueryCache<u32, Vec<NpcTextBlock>>,
/// The drawn record had no line for the NPC's gender: the close core is owed.
missing_text: bool,
/// The reference's text-pending latch `[0xbbb670]`: set on the text's cache miss
@@ -42,7 +41,16 @@ pub(crate) struct GossipState {
impl GossipState {
pub(crate) fn cached_record(&self, text_id: u32) -> Option<&[NpcTextBlock]> {
self.records.get(&text_id).map(Vec::as_slice)
self.records.get(text_id).map(Vec::as_slice)
}
/// The NPC-text store, the one [`crate::wdb`] saves.
pub(crate) fn record_store(&self) -> &QueryCache<u32, Vec<NpcTextBlock>> {
&self.records
}
pub(crate) fn record_store_mut(&mut self) -> &mut QueryCache<u32, Vec<NpcTextBlock>> {
&mut self.records
}
pub(crate) fn remember_record(&mut self, text_id: u32, blocks: Vec<NpcTextBlock>) {
+11 -3
View File
@@ -220,6 +220,15 @@ impl crate::query_cache::AskOnce for GuildState {
}
impl GuildState {
/// The world entry's clear ([`crate::wdb`]): the guild store is built with persistence off
/// (`0x554d20`), so `0x555740` clears it (`0x5557c0`), the callbacks of its pending records
/// with it.
pub(crate) fn clear_world_session(&mut self) {
self.identities.clear();
self.waiters.clear();
self.identity_generation = self.identity_generation.wrapping_add(1);
}
/// `IsInGuild`: our own `PLAYER_GUILDID` is set, known before any guild packet.
pub(crate) fn in_guild(&self) -> bool {
self.guild_id != 0
@@ -747,9 +756,8 @@ pub(crate) mod net {
}
}
/// Reset at session end: the next login may be another character. Deviation: the identity
/// cache goes too, where the reference keeps it in `guildcache.wdb`, because a renamed guild
/// would otherwise show its old name.
/// Reset at session end: the next login may be another character. The identity store goes
/// too, which the next world entry would clear anyway (`0x5557c0`).
fn on_session_end(
In(_): In<SessionEvent>,
mut guild: ResMut<GuildState>,
+10 -1
View File
@@ -56,8 +56,17 @@ impl PageTexts {
self.pages.insert(page_id, PageText { text, next });
}
/// The page store, the one [`crate::wdb`] saves.
pub(crate) fn page_store(&self) -> &QueryCache<u32, PageText> {
&self.pages
}
pub(crate) fn page_store_mut(&mut self) -> &mut QueryCache<u32, PageText> {
&mut self.pages
}
/// The cached page, read as `ask` says; `guid` is the reading object, which vmangos discards.
fn page(&self, page_id: u32, guid: u64, ask: Ask<'_>) -> Option<&PageText> {
pub(crate) fn page(&self, page_id: u32, guid: u64, ask: Ask<'_>) -> Option<&PageText> {
self.pages.read(page_id, ask, |commands| {
debug!("page text: asking page {page_id} (object {guid:#x})");
let _ = commands
+50 -6
View File
@@ -358,13 +358,14 @@ fn taught_spell(
})
}
/// Answers the engine's set-id asks from `ItemSet.dbc`: member names from the template cache, each
/// Answers the engine's set-id asks from `ItemSet.dbc`: member names from the item-name store, each
/// miss queried as the reference queries set members, and bonus text from the `$`-engine. A set
/// stays pending, re-pushing, until every member resolves.
pub(super) fn feed_item_sets(
mut hosted_vm: crate::script_calls::HostedVm,
sets: Option<Res<super::ItemSets>>,
items: Res<Items>,
item_names: Res<crate::item_names::ItemNames>,
commands: Res<NetCommands>,
spells: Option<Res<crate::ui_action::Spells>>,
spell_mods: Res<crate::spell::SpellModifiers>,
@@ -454,11 +455,7 @@ pub(super) fn feed_item_sets(
} else {
Ask::Read
};
let members: Vec<(u32, Option<String>)> = row
.items
.iter()
.map(|&id| (id, items.template(id, 0, ask).map(|t| t.name.clone())))
.collect();
let members = set_members(&row.items, &item_names, ask);
let view = benilla_ui::script::ItemSetView {
name: row.name.clone(),
bonuses: row
@@ -505,6 +502,18 @@ pub(super) fn feed_item_sets(
})
}
/// An item set's member names, each read as `ask` says from the item-name store, as the tooltip's
/// set block reads them (`0x52df5a` on `0xc0e2dc`), not from the template store.
pub(super) fn set_members(
ids: &[u32],
names: &crate::item_names::ItemNames,
ask: Ask<'_>,
) -> Vec<(u32, Option<String>)> {
ids.iter()
.map(|&id| (id, names.name(id, ask).map(str::to_string)))
.collect()
}
/// Pushes the whole random-suffix table once per VM, when both catalogs are in, and the enchant
/// names once the enchant catalog is: their consumers are click-driven, and a chat-link tooltip
/// has no hover loop to repaint a late answer.
@@ -1730,6 +1739,41 @@ fn push_changed(
mod tests {
use super::{ask_build_lookups, push_containers, resolve_slot, ContainerSlot, FeedMemory};
/// A set's member names come from the item-name store (`0x52df5a` looks up `0xc0e2dc` with a
/// callback and a zero owner), asked with `CMSG_ITEM_NAME_QUERY`, never the template store.
#[test]
fn a_set_member_is_named_through_the_item_name_store() {
use crate::item_names::ItemNames;
use crate::net::{ClientCommand, NetCommands};
use crate::query_cache::Ask;
let (tx, rx) = crossbeam_channel::unbounded();
let commands = NetCommands(tx);
let mut names = ItemNames::default();
let members = super::set_members(&[16_866, 16_867], &names, Ask::Event(&commands));
assert_eq!(members, [(16_866, None), (16_867, None)]);
let asked = crate::query_cache::queries(&rx);
assert!(
matches!(
asked[..],
[
ClientCommand::ItemNameQuery {
entry: 16_866,
guid: 0
},
ClientCommand::ItemNameQuery {
entry: 16_867,
guid: 0
}
]
),
"{asked:?}"
);
names.file(16_866, Some("Helm of Wrath".into()));
let members = super::set_members(&[16_866], &names, Ask::Read);
assert_eq!(members, [(16_866, Some("Helm of Wrath".into()))]);
}
/// The view carries what `GetTradeSkillItemStats` reads beyond the tooltip: the item level, and
/// the five spell slots whose id names a `Spell.dbc` row with their charges, in slot order.
#[test]
+7 -5
View File
@@ -102,7 +102,7 @@ pub(crate) struct MailResult {
/// The mailbox session: the open mailbox's guid, the inbox rows as the wire sent them, the
/// letter-body cache and the result queues. A close forgets the guid and the queues and keeps the
/// rows, as the reference's close does (`0x4acd71`); the world-enter init (`0x4acb10`) and a
/// disconnect clear everything.
/// disconnect clear everything but the bodies.
#[derive(Resource, Default)]
pub(crate) struct MailOpen {
pub(crate) mailbox: Option<u64>,
@@ -174,13 +174,15 @@ impl MailOpen {
self.show_requested = false;
}
/// The world-enter init (`0x4acb10`) and a disconnect: no mailbox and no rows.
/// The world-enter init (`0x4acb10`) and a disconnect: no mailbox and no rows. The bodies
/// stay: the item-text store is saved (`0x554eb0`), and neither the init nor the world entry
/// (`0x555811`) clears it.
pub(crate) fn clear_session(&mut self) {
self.clear();
self.results.clear();
self.mails.clear();
self.auction_subjects.clear();
self.bodies.clear();
self.bodies.clear_pending();
self.request_resolved = false;
self.list_results = 0;
}
@@ -1185,7 +1187,7 @@ mod tests {
}
/// A close forgets the mailbox and keeps the rows (`0x4acd71`); the world-enter init and a
/// disconnect clear them (`0x4acb10`).
/// disconnect clear them (`0x4acb10`), and keep the saved item-text store.
#[test]
fn a_close_keeps_the_rows_and_the_session_end_clears_them() {
let mut m = MailOpen::default();
@@ -1198,7 +1200,7 @@ mod tests {
assert!(!m.bodies.is_empty());
m.clear_session();
assert!(m.mails.is_empty());
assert!(m.bodies.is_empty());
assert!(!m.bodies.is_empty());
}
/// No GlobalStrings in a unit test: every key misses.
+19
View File
@@ -242,6 +242,25 @@ impl PetitionRecords {
});
}
/// The world entry's clear ([`crate::wdb`]): the petition store is built with persistence off
/// (`0x554e60`), so `0x555740` clears it (`0x55580c`).
pub(crate) fn clear_world_session(&mut self) {
self.records.clear();
self.records_epoch = self.records_epoch.wrapping_add(1);
}
/// Files a record as its answer does, for a test elsewhere.
#[cfg(test)]
pub(crate) fn answer_for_test(&mut self, response: PetitionQueryResponse) {
self.apply_record(response);
}
/// Whether the store holds a record for `petition_id`, for a test elsewhere.
#[cfg(test)]
pub(crate) fn holds_for_test(&self, petition_id: u32) -> bool {
self.records.get(petition_id).is_some()
}
/// One step per landed or patched record.
pub(crate) fn records_epoch(&self) -> u64 {
self.records_epoch
+17 -2
View File
@@ -104,6 +104,15 @@ impl QuestLog {
}
}
/// The template store, the one [`crate::wdb`] saves.
pub(crate) fn template_store(&self) -> &QueryCache<u32, QuestTemplate> {
&self.templates
}
pub(crate) fn template_store_mut(&mut self) -> &mut QueryCache<u32, QuestTemplate> {
&mut self.templates
}
/// An `SMSG_SET_FACTION_STANDING` moved a faction's rank (`0x4d58a9`).
pub(crate) fn note_faction_rank_move(&mut self) {
self.faction_rank_moves += 1;
@@ -114,9 +123,15 @@ impl QuestLog {
self.folds = Default::default();
}
/// Disconnect: drops everything, the templates and the folds included.
/// Disconnect: drops everything but the templates, the folds included. The quest store is
/// saved (`0x554d70`), so the world entry keeps it (`0x5557c5`).
pub(crate) fn clear_session(&mut self) {
*self = Self::default();
let templates = std::mem::take(&mut self.templates);
*self = Self {
templates,
..Self::default()
};
self.templates.clear_pending();
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ fn list_stabled_pets(npc: u64, pets: &[StabledPet], names: &mut NameCache, num_s
);
// Seed the pet-name cache from the rows, the pair `SMSG_PET_NAME_QUERY_RESPONSE` would carry:
// stock `PetStable.lua:163` hands `UnitName("pet")` to a tooltip whose `SetText` raises on nil
// (`0x531b90`), and unlike the reference's `petnamecache.wdb` this cache starts empty.
// (`0x531b90`), and the pet-name store starts every world session empty (`0x5557f9`).
for pet in pets {
if !pet.name.is_empty() {
names.insert_pet(pet.pet_number, pet.name.clone());
+560
View File
@@ -0,0 +1,560 @@
//! The template caches kept between sessions, and the caches kept for one world session.
//!
//! The reference holds thirteen `DBCache` stores of one template, each built with a persist byte
//! (`[cache+0x39]`, stored at `0x55e770`), its constructor's last argument (`0x554b40` and its
//! kin). Its load (`0x5572b0` and kin, all run once at start-up by `0x554f50`) and its save (the
//! store's `_atexit` writer, `0x554b60` → `0x5566d0`) return at once when the byte is 0
//! (`0x55fa74`, `0x55ec7d`). A record lives until the server refuses its key, which frees the
//! node (a top-bit key, `0x556e67` → `0x556f35`; a quest's empty title, `0x563150`), or until the
//! file's header stops matching; nothing evicts by age or size, and a hit returns the record and
//! sends nothing (`0x5586ca` → `0x55876c`). The world entry (`CGGameUI::InitializeGame`, `0x48f586`
//! → `0x555740`) clears every store whose byte is 0.
//!
//! | store | reference file | here |
//! |---|---|---|
//! | creatures `0xc0e354` | `creaturecache.wdb` | saved, [`NameCache`] |
//! | game objects `0xc0e318` | `gameobjectcache.wdb` | saved, [`GameObjectTemplates`] |
//! | item names `0xc0e2dc` | `itemnamecache.wdb` | saved, [`ItemNames`] |
//! | items `0xc0e2a0` | `itemcache.wdb` | saved, [`Items`] |
//! | NPC text `0xc0e264` | `npccache.wdb` | saved, [`GossipState`] |
//! | quests `0xc0e1b0` | `questcache.wdb` | saved, [`QuestLog`] |
//! | page text `0xc0e174` | `pagetextcache.wdb` | saved, [`PageTexts`] |
//! | item text `0xc0e0c0` | `itemtextcache.wdb` | saved, [`MailOpen`] |
//! | `0xc0e084` | `wowcache.wdb` | none: it has no query (opcode 0) |
//! | player names `0xc0e228` | `namecache.wdb`, unused | world session, [`NameCache`] |
//! | guilds `0xc0e1ec` | `guildcache.wdb`, unused | world session, [`GuildState`] |
//! | pet names `0xc0e138` | `petnamecache.wdb`, unused | world session, [`NameCache`] |
//! | petitions `0xc0e0fc` | `petitioncache.wdb`, unused | world session, [`PetitionRecords`] |
//!
//! A file is the reference's layout (`0x5566d0`): a header, then `{key, size, record}` entries
//! ending in two zero dwords. The header is the store's tag, the build `0x16f3`, the locale tag
//! (`[0xc2a2a4]`, `0x5567d9`), our format and the realm, and a load that finds any of them
//! different keeps nothing, as the reference's does (`0x557390`-`0x55742e`). A record is the
//! server's answer as it came off the wire ([`SessionEvent::SavedAnswer`]), the key and then the
//! fields in the order the store's reader takes them (`0x7c8120` and its kin), and a load decodes
//! it with the live answer's decoder, so one mechanism serves every store and a decoder fix
//! reaches the records already on disk. A short read keeps nothing (`0x557665`).
//!
//! Deviation: the files are `benilla-config/cache/<realm>/<store>.bin` through
//! [`crate::local_state`], not `WDB/` in the install, which is read-only; they are per realm,
//! because another server may hold another template under the same key; and a store is written
//! ten seconds after an answer lands as well as at exit, so a crash costs only re-asking.
use std::collections::HashMap;
use std::marker::PhantomData;
use std::path::PathBuf;
use benilla_protocol::messages::opcode;
use benilla_protocol::{SessionEvent, SessionEventKind};
use bevy::prelude::*;
use crate::glue_session::roster::Roster;
use crate::go_templates::GameObjectTemplates;
use crate::item_names::ItemNames;
use crate::items::Items;
use crate::names::NameCache;
use crate::net::NetHandlerApp;
use crate::query_cache::QueryCache;
use crate::ui_gossip::GossipState;
use crate::ui_guild::GuildState;
use crate::ui_item_text::PageTexts;
use crate::ui_mail::MailOpen;
use crate::ui_petition::PetitionRecords;
use crate::ui_quest_log::QuestLog;
/// Seconds between writes: answers arrive in bursts on zone-in, and a crash costs only re-asking.
const SAVE_DEBOUNCE: f32 = 10.0;
/// The client build, the header's second dword (`0x5567cc`).
const BUILD: u32 = 0x16f3;
/// Our container's version, the header's fourth dword: bump it when the layout changes. The
/// records need none, being the wire's.
const FORMAT: u32 = 1;
/// A store the reference saves: the answer whose body is its record, and how a record read off
/// disk is filed.
pub(crate) trait SavedCache: Resource + Default {
/// The reference's file name, without `.wdb`.
const FILE: &'static str;
/// The reference's tag, the header's first dword (the constructor's first argument, `BOMW` for
/// creatures at `0x554b4d`).
const TAG: u32;
/// The answer whose body is the record.
const ANSWER: u16;
type Record;
fn store(&self) -> &QueryCache<u32, Self::Record>;
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record>;
/// Files one decoded answer read off disk the way its live handler files the record, with no
/// lookup waiting on it.
fn install(&mut self, answer: SessionEvent);
/// Drops every record, for another realm's file.
fn forget(&mut self) {
self.store_mut().clear();
}
}
impl SavedCache for NameCache {
const FILE: &'static str = "creaturecache";
const TAG: u32 = 0x574d_4f42;
const ANSWER: u16 = opcode::SMSG_CREATURE_QUERY_RESPONSE;
type Record = crate::names::CreatureRecord;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.creature_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.creature_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
crate::names::net::file_creature(answer, self);
}
}
impl SavedCache for GameObjectTemplates {
const FILE: &'static str = "gameobjectcache";
const TAG: u32 = 0x5747_4f42;
const ANSWER: u16 = opcode::SMSG_GAMEOBJECT_QUERY_RESPONSE;
type Record = crate::go_templates::GoTemplate;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.template_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.template_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::GameObjectInfo {
entry,
type_id,
name,
data,
..
} = answer
{
self.insert(entry, type_id, name, &data);
}
}
}
impl SavedCache for ItemNames {
const FILE: &'static str = "itemnamecache";
const TAG: u32 = 0x574e_4442;
const ANSWER: u16 = opcode::SMSG_ITEM_NAME_QUERY_RESPONSE;
type Record = String;
fn store(&self) -> &QueryCache<u32, Self::Record> {
ItemNames::store(self)
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
ItemNames::store_mut(self)
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::ItemName {
entry,
name: Some(name),
} = answer
{
self.file(entry, Some(name));
}
}
}
impl SavedCache for Items {
const FILE: &'static str = "itemcache";
const TAG: u32 = 0x5749_4442;
const ANSWER: u16 = opcode::SMSG_ITEM_QUERY_SINGLE_RESPONSE;
type Record = benilla_protocol::ItemInfo;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.template_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.template_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::ItemTemplate {
entry,
info: Some(info),
} = answer
{
self.insert_template(entry, Some(*info));
}
}
/// The interface's copy drops them too.
fn forget(&mut self) {
self.forget_templates();
}
}
impl SavedCache for GossipState {
const FILE: &'static str = "npccache";
const TAG: u32 = 0x574e_5043;
const ANSWER: u16 = opcode::SMSG_NPC_TEXT_UPDATE;
type Record = Vec<benilla_protocol::messages::NpcTextBlock>;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.record_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.record_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::NpcGreeting { text_id, blocks } = answer {
self.remember_record(text_id, blocks);
}
}
}
impl SavedCache for QuestLog {
const FILE: &'static str = "questcache";
const TAG: u32 = 0x5751_5354;
const ANSWER: u16 = opcode::SMSG_QUEST_QUERY_RESPONSE;
type Record = benilla_protocol::messages::QuestTemplate;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.template_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.template_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::QuestTemplate(template) = answer {
self.insert_template(*template);
}
}
}
impl SavedCache for PageTexts {
const FILE: &'static str = "pagetextcache";
const TAG: u32 = 0x5750_5458;
const ANSWER: u16 = opcode::SMSG_PAGE_TEXT_QUERY_RESPONSE;
type Record = crate::ui_item_text::PageText;
fn store(&self) -> &QueryCache<u32, Self::Record> {
self.page_store()
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
self.page_store_mut()
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::PageText {
page_id,
text,
next_page_id,
} = answer
{
self.insert(page_id, text, next_page_id);
}
}
}
impl SavedCache for MailOpen {
const FILE: &'static str = "itemtextcache";
const TAG: u32 = 0x5749_5458;
const ANSWER: u16 = opcode::SMSG_ITEM_TEXT_QUERY_RESPONSE;
type Record = String;
fn store(&self) -> &QueryCache<u32, Self::Record> {
&self.bodies
}
fn store_mut(&mut self) -> &mut QueryCache<u32, Self::Record> {
&mut self.bodies
}
fn install(&mut self, answer: SessionEvent) {
if let SessionEvent::MailItemText { text_id, text } = answer {
self.bodies.insert(text_id, text);
}
}
}
/// The answers whose bodies the IO thread hands on ([`SessionEvent::SavedAnswer`]).
const SAVED_ANSWERS: [u16; 8] = [
NameCache::ANSWER,
GameObjectTemplates::ANSWER,
ItemNames::ANSWER,
Items::ANSWER,
GossipState::ANSWER,
QuestLog::ANSWER,
PageTexts::ANSWER,
MailOpen::ANSWER,
];
/// Whether `opcode` answers a saved store's query.
pub(crate) fn is_saved_answer(opcode: u16) -> bool {
SAVED_ANSWERS.contains(&opcode)
}
pub(crate) struct WdbPlugin;
impl Plugin for WdbPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Roster>();
saved::<NameCache>(app);
saved::<GameObjectTemplates>(app);
saved::<ItemNames>(app);
saved::<Items>(app);
saved::<GossipState>(app);
saved::<QuestLog>(app);
saved::<PageTexts>(app);
saved::<MailOpen>(app);
app.init_resource::<GuildState>()
.init_resource::<PetitionRecords>()
.net_handler(SessionEventKind::SavedAnswer, keep_answer)
.net_handler(SessionEventKind::Connected, clear_session_stores);
}
}
/// A saved store's load and debounced write, ahead of `Update`'s readers, and its exit write.
fn saved<T: SavedCache>(app: &mut App) {
app.init_resource::<T>()
.init_resource::<WdbFile<T>>()
.add_systems(PreUpdate, (load::<T>, save::<T>).chain());
// The exit write catches the last burst, which the debounce would not.
crate::shutdown::on_app_exit(app, save_on_exit::<T>.into_configs());
}
/// The world entry's clear of the guild and petition stores, built with persistence off
/// (`0x554d20`, `0x554e60`; `0x5557c0`, `0x55580c`). The player and pet names clear in the world
/// entry's own handler, ahead of the seed of our own name (`crate::net`).
fn clear_session_stores(
In(ev): In<SessionEvent>,
mut guilds: ResMut<GuildState>,
mut petitions: ResMut<PetitionRecords>,
) {
if let SessionEvent::Connected { .. } = ev {
guilds.clear_world_session();
petitions.clear_world_session();
}
}
/// Every saved store's file, for the answer bytes' handler.
#[derive(bevy::ecs::system::SystemParam)]
struct Files<'w> {
creatures: ResMut<'w, WdbFile<NameCache>>,
game_objects: ResMut<'w, WdbFile<GameObjectTemplates>>,
item_names: ResMut<'w, WdbFile<ItemNames>>,
items: ResMut<'w, WdbFile<Items>>,
npc_text: ResMut<'w, WdbFile<GossipState>>,
quests: ResMut<'w, WdbFile<QuestLog>>,
pages: ResMut<'w, WdbFile<PageTexts>>,
item_text: ResMut<'w, WdbFile<MailOpen>>,
}
/// An answer's bytes, to the file of the store it answers.
fn keep_answer(In(ev): In<SessionEvent>, mut files: Files) {
let SessionEvent::SavedAnswer { opcode, body } = ev else {
return;
};
match opcode {
NameCache::ANSWER => files.creatures.keep(body),
GameObjectTemplates::ANSWER => files.game_objects.keep(body),
ItemNames::ANSWER => files.item_names.keep(body),
Items::ANSWER => files.items.keep(body),
GossipState::ANSWER => files.npc_text.keep(body),
QuestLog::ANSWER => files.quests.keep(body),
PageTexts::ANSWER => files.pages.keep(body),
MailOpen::ANSWER => files.item_text.keep(body),
_ => {}
}
}
/// One store's file: the realm it belongs to, the answer bytes of its records, and the dirty
/// mark.
#[derive(Resource)]
pub(crate) struct WdbFile<T> {
/// The realm the loaded file belongs to; a change saves the old one and loads the new.
realm: Option<String>,
path: Option<PathBuf>,
/// Each record's answer as it came off the wire, by key. A body whose record the store no
/// longer holds is not written.
bodies: HashMap<u32, Vec<u8>>,
/// The store's generation at the last write.
saved: u64,
/// Bytes have landed since the last write, which the generation does not count.
dirty: bool,
since_save: f32,
_store: PhantomData<T>,
}
impl<T> Default for WdbFile<T> {
fn default() -> Self {
Self {
realm: None,
path: None,
bodies: HashMap::new(),
saved: 0,
dirty: false,
since_save: 0.0,
_store: PhantomData,
}
}
}
/// The key a body opens with, which `Receive` reads first (`0x556e5b`).
fn body_key(body: &[u8]) -> Option<u32> {
Some(u32::from_le_bytes(body.get(..4)?.try_into().ok()?))
}
impl<T> WdbFile<T> {
/// Keeps an answer's bytes for its record; a refusal's top-bit key (`0x556e67`) drops them.
fn keep(&mut self, body: Vec<u8>) {
let Some(key) = body_key(&body) else {
return;
};
if key & 0x8000_0000 != 0 {
self.bodies.remove(&(key & 0x7fff_ffff));
} else {
self.bodies.insert(key, body);
}
self.dirty = true;
}
}
/// Loads the realm's file the first frame its identity is known, and on a realm change, after
/// saving the realm left.
fn load<T: SavedCache>(roster: Res<Roster>, mut file: ResMut<WdbFile<T>>, mut cache: ResMut<T>) {
let Some((realm, _)) = crate::ui_macro::identity(&roster) else {
return;
};
if file.realm.as_deref() == Some(realm.as_str()) {
return;
}
if file.realm.is_some() {
write_now(&mut file, &cache);
cache.forget();
file.bodies.clear();
file.dirty = false;
}
file.realm = Some(realm.clone());
file.path = crate::local_state::template_cache_path(&realm, T::FILE);
// An earlier build's creature names, which the creature store's file replaces.
if let Some(retired) = crate::local_state::retired_name_cache_path(&realm) {
let _ = std::fs::remove_file(retired);
}
file.saved = cache.store().generation();
let Some(path) = file.path.clone() else {
return; // a hermetic capture, or no state folder: session-only
};
let Ok(bytes) = std::fs::read(&path) else {
return; // no file yet
};
let Some(entries) = decode(&bytes, T::TAG, &realm) else {
// The first save overwrites it.
debug!(
"wdb: discarding {} — not this build, locale or realm",
path.display()
);
return;
};
let n = entries.len();
for (key, body) in entries {
// An answer that landed before the load is newer than the file's.
if cache.store().get(key).is_some() {
continue;
}
if let Ok(packet) = benilla_protocol::messages::parse_server(T::ANSWER, &body) {
for ev in benilla_protocol::decode(packet) {
cache.install(ev);
}
}
if cache.store().get(key).is_some() {
file.bodies.insert(key, body);
}
}
file.saved = cache.store().generation();
debug!("wdb: loaded {n} {} records for {realm}", T::FILE);
}
/// Writes the store when its records have changed and the debounce has elapsed.
fn save<T: SavedCache>(time: Res<Time>, mut file: ResMut<WdbFile<T>>, cache: Res<T>) {
file.since_save += time.delta_secs();
if file.since_save < SAVE_DEBOUNCE {
return;
}
file.since_save = 0.0;
write_now(&mut file, &cache);
}
/// The exit write, regardless of the debounce.
fn save_on_exit<T: SavedCache>(mut file: ResMut<WdbFile<T>>, cache: Res<T>) {
write_now(&mut file, &cache);
}
fn write_now<T: SavedCache>(file: &mut WdbFile<T>, cache: &T) {
let generation = cache.store().generation();
if generation == file.saved && !file.dirty {
return;
}
let (Some(path), Some(realm)) = (file.path.as_ref(), file.realm.as_ref()) else {
return;
};
let mut keys: Vec<u32> = cache.store().iter().map(|(&k, _)| k).collect();
keys.sort_unstable();
let entries = keys
.into_iter()
.filter_map(|k| file.bodies.get(&k).map(|b| (k, b.as_slice())));
let bytes = encode(T::TAG, realm, entries);
match crate::local_state::write_atomic_bytes(path, &bytes) {
Ok(()) => {
file.saved = generation;
file.dirty = false;
debug!("wdb: wrote {}", path.display());
}
Err(e) => warn!("wdb: cannot write {}: {e}", path.display()),
}
}
/// The header's locale, the client's locale tag as each `.wdb` header carries it (`[0xc2a2a4]`,
/// written at `0x5567d9` and compared at `0x5573c6`): the server answers in the locale the logon
/// challenge sent, so another locale's file is discarded.
fn locale_tag() -> u32 {
crate::ui_script::client_locale().tag()
}
/// A store's file: the header, each `{key, size, body}` entry, then two zero dwords.
fn encode<'a>(tag: u32, realm: &str, entries: impl Iterator<Item = (u32, &'a [u8])>) -> Vec<u8> {
let mut out = Vec::new();
for word in [tag, BUILD, locale_tag(), FORMAT, realm.len() as u32] {
out.extend_from_slice(&word.to_le_bytes());
}
out.extend_from_slice(realm.as_bytes());
for (key, body) in entries {
out.extend_from_slice(&key.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(body);
}
out.extend_from_slice(&[0; 8]);
out
}
/// The next little-endian dword of `r`, consumed.
fn take_u32(r: &mut &[u8]) -> Option<u32> {
let (head, rest) = r.split_first_chunk::<4>()?;
*r = rest;
Some(u32::from_le_bytes(*head))
}
/// [`encode`]'s entries, `None` when any header field differs or the file is cut short.
fn decode(bytes: &[u8], tag: u32, realm: &str) -> Option<Vec<(u32, Vec<u8>)>> {
let mut r = bytes;
let header = [
take_u32(&mut r)?,
take_u32(&mut r)?,
take_u32(&mut r)?,
take_u32(&mut r)?,
];
if header != [tag, BUILD, locale_tag(), FORMAT] {
return None;
}
let len = take_u32(&mut r)? as usize;
if r.get(..len)? != realm.as_bytes() {
return None;
}
r = &r[len..];
let mut entries = Vec::new();
loop {
let key = take_u32(&mut r)?;
let size = take_u32(&mut r)? as usize;
if key == 0 {
return Some(entries);
}
entries.push((key, r.get(..size)?.to_vec()));
r = &r[size..];
}
}
#[cfg(test)]
mod tests;
+693
View File
@@ -0,0 +1,693 @@
use bevy::ecs::system::RunSystemOnce;
use super::*;
use crate::local_state::test_env::{EnvGuard, ENV_LOCK};
use crate::net::{ClientCommand, NetCommands};
use crate::query_cache::Ask;
/// An answer's body, built field by field in the wire's order.
#[derive(Default)]
struct Body(Vec<u8>);
impl Body {
fn u32(mut self, v: u32) -> Self {
self.0.extend_from_slice(&v.to_le_bytes());
self
}
fn zeros(mut self, n: usize) -> Self {
self.0.extend(std::iter::repeat_n(0, 4 * n));
self
}
fn f32(self, v: f32) -> Self {
self.u32(v.to_bits())
}
fn i32(self, v: i32) -> Self {
self.u32(v as u32)
}
fn str(mut self, s: &str) -> Self {
self.0.extend_from_slice(s.as_bytes());
self.0.push(0);
self
}
fn u8(mut self, v: u8) -> Self {
self.0.push(v);
self
}
}
const CREATURE: u32 = 69;
const GAME_OBJECT: u32 = 1617;
const ITEM: u32 = 2589;
const NPC_TEXT: u32 = 4437;
const QUEST: u32 = 783;
const PAGE: u32 = 15;
const ITEM_TEXT: u32 = 301;
/// `SMSG_CREATURE_QUERY_RESPONSE`: the names, the subname, seven dwords and two flag bytes.
fn creature_answer(entry: u32) -> Vec<u8> {
Body::default()
.u32(entry)
.str("Stable Master Kitrik")
.str("")
.str("")
.str("")
.str("Stable Master")
.u32(0x10)
.u32(7)
.u32(0)
.u32(1)
.u32(0)
.u32(5796)
.u32(533)
.u8(1)
.u8(0)
.0
}
fn game_object_answer() -> Vec<u8> {
Body::default()
.u32(GAME_OBJECT)
.u32(3)
.u32(310)
.str("Copper Vein")
.str("")
.str("")
.str("")
.str("")
.i32(38)
.zeros(23)
.0
}
fn item_answer() -> Vec<u8> {
Body::default()
.u32(ITEM)
.u32(7)
.u32(5)
.str("Linen Cloth")
.str("")
.str("")
.str("")
// Display id through container slots, then the stats, damage and resistance blocks, the
// delay, ammo and range, five empty spell blocks and the bonding.
.zeros(96)
.str("")
.zeros(14)
.0
}
fn item_name_answer() -> Vec<u8> {
Body::default().u32(ITEM).str("Linen Cloth").0
}
fn npc_text_answer() -> Vec<u8> {
let mut b = Body::default()
.u32(NPC_TEXT)
.f32(1.0)
.str("Greetings, $N.")
.str("")
.zeros(7);
for _ in 1..8 {
b = b.f32(0.0).str("").str("").zeros(7);
}
b.0
}
fn quest_answer(title: &str) -> Vec<u8> {
Body::default()
.u32(QUEST)
.zeros(14 + 8 + 12 + 4)
.str(title)
.str("Kill the kobolds.")
.str("Details.")
.str("")
.zeros(16)
.str("")
.str("")
.str("")
.str("")
.0
}
fn page_answer() -> Vec<u8> {
Body::default().u32(PAGE).str("Page one.").u32(0).0
}
fn item_text_answer() -> Vec<u8> {
Body::default().u32(ITEM_TEXT).str("Dear $N,").0
}
/// A roster with a pick in flight on `realm`.
fn roster(realm: &str) -> Roster {
let mut roster = Roster::with_pending_pick(
vec![benilla_protocol::Character {
guid: 0x2a,
name: "Probeseven".into(),
race: 1,
class: 1,
gender: 0,
skin: 0,
face: 0,
hair_style: 0,
hair_color: 0,
facial_hair: 0,
level: 1,
new_character: false,
zone: 0,
map: 0,
position: benilla_protocol::wire::Vector3d {
x: 0.0,
y: 0.0,
z: 0.0,
},
flags: 0,
equipment: [benilla_protocol::CharEnumItem::default(); 19],
pet_display_id: 0,
pet_level: 0,
pet_family: 0,
}],
0x2a,
);
roster.realm = Some(benilla_protocol::RealmInfo {
name: realm.into(),
address: "localhost:8085".into(),
population: 0.0,
characters: 1,
realm_type: 0,
flags: 0,
category: 1,
id: 1,
});
roster
}
/// A state folder of the test's own, with the process's environment held still.
struct Home {
dir: std::path::PathBuf,
_home: EnvGuard,
_capture: EnvGuard,
_lock: std::sync::MutexGuard<'static, ()>,
}
impl Home {
fn new(name: &str) -> Self {
let lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = std::env::temp_dir().join(format!("benilla-wdb-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self {
_capture: EnvGuard::unset("WOW_CAPTURE"),
_home: EnvGuard::set("BENILLA_HOME", dir.to_str().expect("a utf-8 temp path")),
dir,
_lock: lock,
}
}
}
impl Drop for Home {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
/// One login's worth of a saved store: the store, its file and the realm it plays on.
struct Session<T: SavedCache> {
app: App,
_store: PhantomData<T>,
}
impl<T: SavedCache> Session<T> {
/// A fresh client process logging in on `realm`: the store starts empty and the realm's file
/// is loaded.
fn start(realm: &str) -> Self {
let mut app = App::new();
app.insert_resource(roster(realm))
.init_resource::<T>()
.init_resource::<WdbFile<T>>();
app.world_mut()
.run_system_once(load::<T>)
.expect("the load runs");
Self {
app,
_store: PhantomData,
}
}
/// An answer off the wire: its bytes, then its decoded events filed as the live handler files
/// them, the order the IO thread hands them on in.
fn answer(&mut self, body: Vec<u8>) {
let world = self.app.world_mut();
let packet = benilla_protocol::messages::parse_server(T::ANSWER, &body).expect("parses");
world.resource_mut::<WdbFile<T>>().keep(body);
for ev in benilla_protocol::decode(packet) {
world.resource_mut::<T>().install(ev);
}
}
/// A debounced write between frames.
fn save(&mut self) {
self.app
.world_mut()
.run_system_once(save_on_exit::<T>)
.expect("the write runs");
}
/// The process exits.
fn exit(mut self) {
self.app
.world_mut()
.run_system_once(save_on_exit::<T>)
.expect("the exit write runs");
}
fn store(&mut self) -> Mut<'_, T> {
self.app.world_mut().resource_mut::<T>()
}
}
/// The queries `read` sends against a store loaded in a new session, and whether it found the
/// record.
fn asks_in_next_session<T: SavedCache>(
body: Vec<u8>,
read: impl FnOnce(&mut T, &NetCommands) -> bool,
) -> (bool, Vec<ClientCommand>) {
let _home = Home::new(T::FILE);
let mut first = Session::<T>::start("Hydraxian Waterlords");
first.answer(body);
first.exit();
let mut next = Session::<T>::start("Hydraxian Waterlords");
let (tx, rx) = crossbeam_channel::unbounded();
let commands = NetCommands(tx);
let found = read(&mut next.store(), &commands);
(found, crate::query_cache::queries(&rx))
}
/// The reference saves these stores (`0x554b40` and kin push 1) and a hit sends nothing
/// (`0x5586ca`): a record answered in one session is served without a query in the next.
#[test]
fn an_answer_from_one_session_is_served_without_a_query_in_the_next() {
let (found, asked) = asks_in_next_session::<NameCache>(creature_answer(CREATURE), |n, c| {
n.resolve_creature(CREATURE, 0, Ask::Event(c)) == Some("Stable Master Kitrik")
});
assert!(found && asked.is_empty(), "creature: {asked:?}");
let (found, asked) =
asks_in_next_session::<GameObjectTemplates>(game_object_answer(), |g, c| {
g.resolve_name(GAME_OBJECT, Ask::Event(c)) == Some("Copper Vein")
});
assert!(found && asked.is_empty(), "game object: {asked:?}");
let (found, asked) = asks_in_next_session::<ItemNames>(item_name_answer(), |n, c| {
n.name(ITEM, Ask::Event(c)) == Some("Linen Cloth")
});
assert!(found && asked.is_empty(), "item name: {asked:?}");
let (found, asked) = asks_in_next_session::<Items>(item_answer(), |i, c| {
i.template(ITEM, 0, Ask::Event(c))
.is_some_and(|t| t.name == "Linen Cloth")
});
assert!(found && asked.is_empty(), "item: {asked:?}");
let (found, asked) = asks_in_next_session::<GossipState>(npc_text_answer(), |g, _| {
// `true` would owe the text query.
let owed = g.open_menu(0xf130_0000_0000_0001, NPC_TEXT, Vec::new(), Vec::new(), 0);
!owed && g.greeting.as_deref() == Some("Greetings, $N.")
});
assert!(found && asked.is_empty(), "npc text: {asked:?}");
let (found, asked) =
asks_in_next_session::<QuestLog>(quest_answer("The Kobold Menace"), |q, c| {
q.template(QUEST, Ask::Event(c))
.is_some_and(|t| t.title == "The Kobold Menace")
});
assert!(found && asked.is_empty(), "quest: {asked:?}");
let (found, asked) = asks_in_next_session::<PageTexts>(page_answer(), |p, c| {
p.page(PAGE, 0, Ask::Event(c))
.is_some_and(|p| p.text == "Page one.")
});
assert!(found && asked.is_empty(), "page text: {asked:?}");
let (found, asked) = asks_in_next_session::<MailOpen>(item_text_answer(), |m, c| {
m.bodies
.lookup(ITEM_TEXT, || {
let _ = c.0.send(ClientCommand::ItemTextQuery {
text_id: ITEM_TEXT,
mail_id: 1,
});
})
.is_some_and(|t| t == "Dear $N,")
});
assert!(found && asked.is_empty(), "item text: {asked:?}");
}
/// The creature record survives whole, an absent subname included: `Some("")` would paint an
/// empty tooltip line.
#[test]
fn a_saved_creature_record_comes_back_field_for_field() {
let _home = Home::new("creature-fields");
let mut first = Session::<NameCache>::start("R");
first.answer(creature_answer(CREATURE));
let mut boar = creature_answer(70);
// The subname is the fifth string: blank it.
let at = boar
.windows(14)
.position(|w| w == b"Stable Master\0")
.expect("the subname");
boar.drain(at..at + 13);
first.answer(boar);
first.exit();
let mut next = Session::<NameCache>::start("R");
let names = next.store();
let rec = names.creature_record(CREATURE).expect("the record");
assert_eq!(rec.name, "Stable Master Kitrik");
assert_eq!(rec.subname.as_deref(), Some("Stable Master"));
assert_eq!((rec.creature_type, rec.rank, rec.type_flags), (7, 1, 0x10));
assert_eq!((rec.civilian, rec.racial_leader), (true, false));
assert_eq!((rec.display_id, rec.pet_spell_list), (533, 5796));
assert_eq!(names.creature_record(70).expect("the boar").subname, None);
}
/// No guid- or spawn-keyed name reaches the disk: the name and pet-name stores are built with
/// persistence off (`0x554cd0`, `0x554e10`).
#[test]
fn player_and_pet_names_are_never_saved() {
let _home = Home::new("identities");
let mut first = Session::<NameCache>::start("R");
first.answer(creature_answer(CREATURE));
first
.store()
.insert_player(0x11, "Moamtester".into(), Some((1, 2, 0)));
first.store().insert_pet(7, "Rexpet".into());
first.exit();
let path = crate::local_state::template_cache_path("R", NameCache::FILE).expect("a path");
let bytes = std::fs::read(&path).expect("the file");
let has = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);
assert!(has(b"Stable Master Kitrik"));
assert!(!has(b"Moamtester") && !has(b"Rexpet"));
let mut next = Session::<NameCache>::start("R");
assert_eq!(next.store().resolve_unit(0x11, None, Ask::Read), None);
}
/// The load compares every header field and keeps nothing on a difference (`0x557390`-
/// `0x55742e`); the realm is ours.
#[test]
fn a_header_from_another_realm_build_locale_or_format_discards_the_file() {
let body = creature_answer(CREATURE);
let tag = NameCache::TAG;
let good = encode(
tag,
"Hydraxian Waterlords",
[(CREATURE, body.as_slice())].into_iter(),
);
assert_eq!(
decode(&good, tag, "Hydraxian Waterlords"),
Some(vec![(CREATURE, body.clone())])
);
assert_eq!(decode(&good, tag, "Another Realm"), None, "another realm");
assert_eq!(
decode(&good, GameObjectTemplates::TAG, "Hydraxian Waterlords"),
None
);
for (dword, what) in [(0, "tag"), (1, "build"), (2, "locale"), (3, "format")] {
let mut bad = good.clone();
bad[4 * dword] ^= 1;
assert_eq!(
decode(&bad, tag, "Hydraxian Waterlords"),
None,
"another {what}"
);
}
assert_eq!(
good[4..8],
0x16f3u32.to_le_bytes(),
"the build the header carries"
);
// A short read keeps nothing (`0x557665`).
assert_eq!(
decode(&good[..good.len() - 12], tag, "Hydraxian Waterlords"),
None
);
assert_eq!(decode(&[], tag, "Hydraxian Waterlords"), None);
// At the load: the other realm's file is left, and its records are not served.
let _home = Home::new("realm");
let mut there = Session::<NameCache>::start("Hydraxian Waterlords");
there.answer(creature_answer(CREATURE));
there.exit();
let elsewhere =
crate::local_state::template_cache_path("Hydraxian Waterlords", "creaturecache")
.expect("a path");
let here =
crate::local_state::template_cache_path("Lightbringer", "creaturecache").expect("a path");
std::fs::create_dir_all(here.parent().unwrap()).unwrap();
std::fs::copy(&elsewhere, &here).unwrap();
let mut next = Session::<NameCache>::start("Lightbringer");
assert!(next.store().creature_record(CREATURE).is_none());
}
/// A realm change in one process saves the realm left and serves none of its records on the new
/// one.
#[test]
fn a_realm_change_saves_the_old_realm_and_starts_from_the_new_ones_file() {
let _home = Home::new("realm-change");
let mut session = Session::<NameCache>::start("Hydraxian Waterlords");
session.answer(creature_answer(CREATURE));
session.app.insert_resource(roster("Lightbringer"));
session
.app
.world_mut()
.run_system_once(load::<NameCache>)
.expect("the load runs");
assert!(session.store().creature_record(CREATURE).is_none());
session.exit();
let mut back = Session::<NameCache>::start("Hydraxian Waterlords");
assert!(back.store().creature_record(CREATURE).is_some());
}
/// A refusal frees the record (`0x556f35`), so it is not saved and the next session asks again.
#[test]
fn an_eviction_re_asks_in_the_next_session() {
let _home = Home::new("eviction");
let mut first = Session::<NameCache>::start("R");
first.answer(creature_answer(CREATURE));
first.exit();
let mut second = Session::<NameCache>::start("R");
assert!(second.store().creature_record(CREATURE).is_some());
second.answer(Body::default().u32(CREATURE | 0x8000_0000).0);
assert!(second.store().creature_record(CREATURE).is_none());
second.exit();
let mut third = Session::<NameCache>::start("R");
let (tx, rx) = crossbeam_channel::unbounded();
let commands = NetCommands(tx);
assert_eq!(
third
.store()
.resolve_creature(CREATURE, 0, Ask::Event(&commands)),
None
);
assert!(matches!(
crate::query_cache::queries(&rx)[..],
[ClientCommand::CreatureQuery {
entry: CREATURE,
..
}]
));
}
/// A quest's empty title is a refusal (`0x563150`): it frees a saved record too.
#[test]
fn a_quest_refused_with_an_empty_title_is_dropped_from_the_file() {
let _home = Home::new("quest-refusal");
let mut first = Session::<QuestLog>::start("R");
first.answer(quest_answer("The Kobold Menace"));
first.exit();
let mut second = Session::<QuestLog>::start("R");
assert!(second.store().template(QUEST, Ask::Read).is_some());
second.answer(quest_answer(""));
second.exit();
let mut third = Session::<QuestLog>::start("R");
assert!(third.store().template(QUEST, Ask::Read).is_none());
}
/// The saved stores outlive a disconnect and the world entry's mail init (`0x4acb10`), which
/// touch no `DBCache`; only a store with persistence off is cleared (`0x555740`).
#[test]
fn a_disconnect_keeps_the_saved_quest_and_item_text_records() {
let mut quests = QuestLog::default();
let template = benilla_protocol::messages::parse_server(
QuestLog::ANSWER,
&quest_answer("The Kobold Menace"),
)
.expect("parses");
for ev in benilla_protocol::decode(template) {
quests.install(ev);
}
quests.clear_session();
assert!(quests.template(QUEST, Ask::Read).is_some());
let mut mail = MailOpen::default();
mail.bodies.insert(ITEM_TEXT, "Dear $N,".into());
mail.clear_session();
assert_eq!(
mail.bodies.get(ITEM_TEXT).map(String::as_str),
Some("Dear $N,")
);
}
/// The guild and petition stores are built with persistence off (`0x554d20`, `0x554e60`), so the
/// world entry clears them (`0x5557c0`, `0x55580c`).
#[test]
fn the_session_only_stores_are_empty_after_world_entry() {
let mut app = App::new();
app.init_resource::<Time>().add_plugins(WdbPlugin);
app.world_mut()
.resource_mut::<GuildState>()
.land_for_test(9, "Wardens");
app.world_mut()
.resource_mut::<PetitionRecords>()
.answer_for_test(benilla_protocol::messages::PetitionQueryResponse {
petition_id: 7,
name: "Legacy".into(),
..Default::default()
});
assert!(app.world().resource::<GuildState>().identity_known(9));
assert!(app.world().resource::<PetitionRecords>().holds_for_test(7));
crate::net::handlers::dispatch(
app.world_mut(),
vec![SessionEvent::Connected {
self_guid: 0x2a,
name: "Probeseven".into(),
billing: Default::default(),
tutorial_flags: None,
addon_info: None,
}],
);
assert!(!app.world().resource::<GuildState>().identity_known(9));
assert!(!app.world().resource::<PetitionRecords>().holds_for_test(7));
}
/// The IO thread hands on the bytes of exactly the saved stores' answers.
#[test]
fn the_saved_answers_are_the_saved_stores_answers() {
for opcode in [0x61, 0x5f, 0x2c5, 0x58, 0x180, 0x5d, 0x5b, 0x244] {
assert!(is_saved_answer(opcode), "{opcode:#x}");
}
// The names, guild, pet-name and petition answers.
for opcode in [0x51, 0x55, 0x53, 0x1c7] {
assert!(!is_saved_answer(opcode), "{opcode:#x}");
}
}
/// An answer's record and its bytes drained in two frames, with a write between: the bytes still
/// reach the file.
#[test]
fn bytes_that_land_after_a_write_still_reach_the_file() {
let _home = Home::new("split");
let mut first = Session::<NameCache>::start("R");
let body = creature_answer(CREATURE);
let packet = benilla_protocol::messages::parse_server(NameCache::ANSWER, &body).unwrap();
for ev in benilla_protocol::decode(packet) {
first.store().install(ev);
}
first.save();
first
.app
.world_mut()
.resource_mut::<WdbFile<NameCache>>()
.keep(body);
first.exit();
let mut next = Session::<NameCache>::start("R");
assert!(next.store().creature_record(CREATURE).is_some());
}
/// The creature names an earlier build kept in `cache/<realm>.tsv` go when the realm's stores
/// load.
#[test]
fn the_load_removes_the_earlier_creature_file() {
let home = Home::new("tsv");
let old = home.dir.join("cache").join("Hydraxian_Waterlords.tsv");
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
std::fs::write(
&old,
"benilla-namecache\t3\t5875\tenGB\tHydraxian Waterlords\n",
)
.unwrap();
let _session = Session::<NameCache>::start("Hydraxian Waterlords");
assert!(!old.exists());
}
/// Whether a fresh process on realm `R` holds `key` in the store `T` loads.
fn held_next_session<T: SavedCache>(key: u32) -> bool {
Session::<T>::start("R").store().store().get(key).is_some()
}
/// Every saved answer from its packet through the IO thread's emission ([`crate::net::io::inbound`])
/// and the live client's handler table to the store's file, and back in the next process.
#[test]
fn each_answer_reaches_its_own_stores_file_through_the_live_handlers() {
let _home = Home::new("live");
let answers = [
(NameCache::ANSWER, creature_answer(CREATURE)),
(GameObjectTemplates::ANSWER, game_object_answer()),
(ItemNames::ANSWER, item_name_answer()),
(Items::ANSWER, item_answer()),
(GossipState::ANSWER, npc_text_answer()),
(QuestLog::ANSWER, quest_answer("The Kobold Menace")),
(PageTexts::ANSWER, page_answer()),
(MailOpen::ANSWER, item_text_answer()),
];
let mut app = crate::game_plugins::schedule_tests::headless_client_unrun();
app.insert_resource(roster("R"));
fn load_all(world: &mut World) {
world.run_system_once(load::<NameCache>).unwrap();
world.run_system_once(load::<GameObjectTemplates>).unwrap();
world.run_system_once(load::<ItemNames>).unwrap();
world.run_system_once(load::<Items>).unwrap();
world.run_system_once(load::<GossipState>).unwrap();
world.run_system_once(load::<QuestLog>).unwrap();
world.run_system_once(load::<PageTexts>).unwrap();
world.run_system_once(load::<MailOpen>).unwrap();
}
load_all(app.world_mut());
for (opcode, body) in answers {
let packet = benilla_protocol::messages::parse_server(opcode, &body).expect("parses");
let events = crate::net::io::inbound(opcode, benilla_protocol::decode(packet), body);
crate::net::handlers::dispatch(app.world_mut(), events);
}
let world = app.world_mut();
world.run_system_once(save_on_exit::<NameCache>).unwrap();
world
.run_system_once(save_on_exit::<GameObjectTemplates>)
.unwrap();
world.run_system_once(save_on_exit::<ItemNames>).unwrap();
world.run_system_once(save_on_exit::<Items>).unwrap();
world.run_system_once(save_on_exit::<GossipState>).unwrap();
world.run_system_once(save_on_exit::<QuestLog>).unwrap();
world.run_system_once(save_on_exit::<PageTexts>).unwrap();
world.run_system_once(save_on_exit::<MailOpen>).unwrap();
drop(app);
assert!(held_next_session::<NameCache>(CREATURE), "creature");
assert!(
held_next_session::<GameObjectTemplates>(GAME_OBJECT),
"game object"
);
assert!(held_next_session::<ItemNames>(ITEM), "item name");
assert!(held_next_session::<Items>(ITEM), "item");
assert!(held_next_session::<GossipState>(NPC_TEXT), "npc text");
assert!(held_next_session::<QuestLog>(QUEST), "quest");
assert!(held_next_session::<PageTexts>(PAGE), "page text");
assert!(held_next_session::<MailOpen>(ITEM_TEXT), "item text");
}
+6
View File
@@ -237,6 +237,10 @@ pub enum SessionEvent {
/// The world session ended, and with [`SessionEnd::Lost`] the link with it; `reason` is
/// human-readable.
Disconnected { reason: String, end: SessionEnd },
/// The body of an answer whose record the 1.12 client saves to disk, as it came off the wire,
/// its key the first dword (`0x556e5b`): emitted by the IO thread ahead of the answer's
/// decoded events, never wire-decoded, for the app's on-disk template caches.
SavedAnswer { opcode: u16, body: Vec<u8> },
/// A placed object entered view, its spawn identity decoded per object type.
ObjectCreate {
guid: u64,
@@ -584,6 +588,8 @@ pub enum SessionEvent {
PetActionSound { pet_guid: u64, talk: u32 },
/// A dismissed pet's sound (`SMSG_PET_DISMISS_SOUND`): the `CreatureModelData` column-29 kit.
PetDismissSound { model_id: u32, position: [f32; 3] },
/// `SMSG_ITEM_NAME_QUERY_RESPONSE`, by entry; `None` is unknown.
ItemName { entry: u32, name: Option<String> },
/// `SMSG_ITEM_QUERY_SINGLE_RESPONSE`, by entry; `None` is unknown. Boxed, being wide.
ItemTemplate {
entry: u32,
@@ -131,6 +131,9 @@ pub fn decode(packet: ServerPacket) -> Vec<SessionEvent> {
position: [position.x, position.y, position.z],
}]
}
ServerPacket::ItemNameQueryResponse { entry, name } => {
vec![SessionEvent::ItemName { entry, name }]
}
ServerPacket::ItemQueryResponse { entry, info } => {
vec![SessionEvent::ItemTemplate { entry, info }]
}
@@ -434,6 +434,27 @@ pub(super) fn read_item_query_response(r: &mut &[u8]) -> io::Result<(u32, Option
))
}
/// Body of `CMSG_ITEM_NAME_QUERY`: the item entry, then the asker's guid, which the 1.12 client
/// puts because the store's owner flag is set (`0x559fe0`; its query send matches `0x558648`) and
/// vmangos skips (`ItemNameQuery::ReadFromWorldPacket`).
pub fn item_name_query(entry: u32, guid: u64) -> Vec<u8> {
let mut body = Vec::with_capacity(12);
body.extend_from_slice(&entry.to_le_bytes());
body.extend_from_slice(&guid.to_le_bytes());
body
}
/// Read `SMSG_ITEM_NAME_QUERY_RESPONSE`: the entry, then the name, the one string the store's
/// reader takes (`0x7c8dc0`); vmangos writes the same pair (`ItemNameQueryResponse::AppendBodyTo`).
/// A top-bit entry is the store's refusal (`0x556e67`), with nothing after it.
pub(super) fn read_item_name_query_response(r: &mut &[u8]) -> io::Result<(u32, Option<String>)> {
let entry = read_u32_le(r)?;
if entry & 0x8000_0000 != 0 {
return Ok((entry & 0x7FFF_FFFF, None));
}
Ok((entry, Some(read_cstring(r)?)))
}
/// Body of `CMSG_ITEM_QUERY_SINGLE`: entry, then a full item guid (0 with no instance in hand).
pub fn item_query(entry: u32, guid: u64) -> Vec<u8> {
let mut body = Vec::with_capacity(12);
+2 -2
View File
@@ -151,8 +151,8 @@ pub use instance::{
RaidInstanceWarning,
};
pub use items::{
auto_equip_item, auto_store_bag_item, destroy_item, item_query, open_item, set_ammo,
split_item, swap_inv_item, swap_item, use_item, wrap_item, ItemDamage, ItemInfo,
auto_equip_item, auto_store_bag_item, destroy_item, item_name_query, item_query, open_item,
set_ammo, split_item, swap_inv_item, swap_item, use_item, wrap_item, ItemDamage, ItemInfo,
ItemSpellEntry, ItemUseSpell, UseItemTarget, BAG_PLAYER_INVENTORY, ITEM_DYNFLAG_UNLOCKED,
ITEM_DYNFLAG_WRAPPED, ITEM_FLAG_LOOTABLE, ITEM_FLAG_PLAYERCAST, ITEM_FLAG_WRAPPER,
SLOT_BAG_FIRST, SLOT_PACK_FIRST,
@@ -345,6 +345,11 @@ pub const CMSG_GAMEOBJECT_QUERY: u16 = 0x005E; // 94
/// Ask for a quest's template; answered by [`SMSG_QUEST_QUERY_RESPONSE`].
pub const CMSG_QUEST_QUERY: u16 = 0x005C; // 92
pub const CMSG_ITEM_QUERY_SINGLE: u16 = 0x0056; // 86
/// Ask for an item's name alone, the item-name store's query (`0x559fe0`); answered by
/// [`SMSG_ITEM_NAME_QUERY_RESPONSE`].
pub const CMSG_ITEM_NAME_QUERY: u16 = 0x02C4; // 708
/// Answers `CMSG_ITEM_NAME_QUERY`; vmangos sends nothing for an unknown item.
pub const SMSG_ITEM_NAME_QUERY_RESPONSE: u16 = 0x02C5; // 709
pub const CMSG_USE_ITEM: u16 = 0x00AB; // 171
/// Open an openable item (a clam, a lockbox, a gift) by bag position; the loot that answers names
/// the item's own guid (`HandleOpenItemOpcode`).
@@ -348,7 +348,7 @@ pub enum ServerPacket {
info: Option<CreatureQueryInfo>,
},
/// `SMSG_PET_NAME_QUERY_RESPONSE`: keyed by pet number, as the client's pet-name cache is; the
/// `nameTimestamp` tail, which only ages that on-disk cache, is read and dropped.
/// `nameTimestamp` tail is read and dropped.
PetNameQueryResponse {
pet_number: u32,
name: String,
@@ -430,6 +430,11 @@ pub enum ServerPacket {
guid: u64,
emote_id: u32,
},
/// `SMSG_ITEM_NAME_QUERY_RESPONSE`: an item's name by entry; `None` is a refusal.
ItemNameQueryResponse {
entry: u32,
name: Option<String>,
},
/// `SMSG_ITEM_QUERY_SINGLE_RESPONSE`: the full item template, boxed for size; `None` is a miss.
ItemQueryResponse {
entry: u32,
@@ -1399,6 +1404,7 @@ impl ServerPacket {
ServerPacket::TextEmote { .. } => "SMSG_TEXT_EMOTE".into(),
ServerPacket::Emote { .. } => "SMSG_EMOTE".into(),
ServerPacket::ItemQueryResponse { .. } => "SMSG_ITEM_QUERY_SINGLE_RESPONSE".into(),
ServerPacket::ItemNameQueryResponse { .. } => "SMSG_ITEM_NAME_QUERY_RESPONSE".into(),
ServerPacket::InventoryChangeFailure { .. } => "SMSG_INVENTORY_CHANGE_FAILURE".into(),
ServerPacket::MessageChat(_) => "SMSG_MESSAGECHAT".into(),
ServerPacket::ChannelNotify(_) => "SMSG_CHANNEL_NOTIFY".into(),
@@ -626,6 +626,10 @@ fn parse_server_body(
let guid = read_u64_le(&mut r)?;
ServerPacket::Emote { guid, emote_id }
}
opcode::SMSG_ITEM_NAME_QUERY_RESPONSE => {
let (entry, name) = items::read_item_name_query_response(&mut r)?;
ServerPacket::ItemNameQueryResponse { entry, name }
}
opcode::SMSG_ITEM_QUERY_SINGLE_RESPONSE => {
let (entry, info) = items::read_item_query_response(&mut r)?;
ServerPacket::ItemQueryResponse {
@@ -1287,8 +1291,8 @@ fn parse_server_body(
}
}
}
// `u32 petNumber, cstring name, u32 nameTimestamp` (`Pet.cpp:79-84`); the timestamp only
// ages the reference's on-disk pet-name cache.
// `u32 petNumber, cstring name, u32 nameTimestamp` (`Pet.cpp:79-84`); the timestamp is
// read and dropped.
opcode::SMSG_PET_NAME_QUERY_RESPONSE => {
let pet_number = read_u32_le(&mut r)?;
let name = read_cstring(&mut r)?;
@@ -16,6 +16,14 @@ impl WorldWriter {
)
}
/// `CMSG_ITEM_NAME_QUERY`: an item's name by entry; `guid` is the asker's, 0 for none.
pub fn item_name_query(&mut self, entry: u32, guid: u64) -> Result<()> {
self.send(
opcode::CMSG_ITEM_NAME_QUERY,
&messages::item_name_query(entry, guid),
)
}
/// `CMSG_USE_ITEM`: use the item at a bag position; a GameObject `target` is how a key opens a
/// locked door. Refused with `SMSG_CAST_RESULT`.
pub fn use_item(
+30
View File
@@ -546,3 +546,33 @@ fn item_query_response_miss() {
_ => panic!("item query miss event"),
}
}
/// `CMSG_ITEM_NAME_QUERY` is the entry and the asker's guid; the answer is the entry and the
/// name, and a top-bit entry refuses.
#[test]
fn item_name_query_wire() {
assert_eq!(
messages::item_name_query(2589, 0),
hx("1d0a00000000000000000000")
);
let hit = messages::parse_server(
messages::opcode::SMSG_ITEM_NAME_QUERY_RESPONSE,
&hx("1d0a00004c696e656e20436c6f746800"),
)
.unwrap();
match decode(hit).pop().unwrap() {
SessionEvent::ItemName { entry, name } => {
assert_eq!((entry, name.as_deref()), (2589, Some("Linen Cloth")));
}
_ => panic!("item name event"),
}
let miss = messages::parse_server(
messages::opcode::SMSG_ITEM_NAME_QUERY_RESPONSE,
&hx("1d0a0080"),
)
.unwrap();
match decode(miss).pop().unwrap() {
SessionEvent::ItemName { entry, name } => assert_eq!((entry, name), (2589, None)),
_ => panic!("item name refusal event"),
}
}
+14 -15
View File
@@ -29,7 +29,7 @@ A setting boots at the reference's default unless it is listed here (`docs/METHO
Each entry is the first sentence of a `Deviation:` comment, linking to where it lives.
- [benilla-app](#benilla-app): 243
- [benilla-app](#benilla-app): 242
- [benilla-assets](#benilla-assets): 6
- [benilla-blp](#benilla-blp): 1
- [benilla-formats](#benilla-formats): 22
@@ -155,16 +155,12 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
#### local_state
- The reference writes `Screenshots\\` inside the install, which benilla never writes to; the folder keeps the reference's name. ([`src/local_state.rs:383`](../crates/benilla-app/src/local_state.rs#L383))
- The reference writes `Screenshots\\` inside the install, which benilla never writes to; the folder keeps the reference's name. ([`src/local_state.rs:392`](../crates/benilla-app/src/local_state.rs#L392))
#### minimap
- Dots re-project every frame, where the reference draws coordinates about 1 s stale, because that staleness is a throttle quirk. ([`src/minimap/blips/mod.rs:28`](../crates/benilla-app/src/minimap/blips/mod.rs#L28))
#### name_persist
- The file is `benilla-config/cache/<realm>.tsv` through `crate::local_state`, not `WDB/` in the install, because the install is read-only; and it is per realm, because another server may hold a different template under the same entry. ([`src/name_persist.rs:14`](../crates/benilla-app/src/name_persist.rs#L14))
#### nameplates
- `AlphaMode::Blend` writes no depth where the reference does, because overlapping names resolving by sort order look the same. ([`src/nameplates.rs:4`](../crates/benilla-app/src/nameplates.rs#L4))
@@ -181,7 +177,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
- UTC days, where `mktime` reads the host's local time zone, because the app has no time zone source (`benilla_ui::civil` has the same). ([`src/net/game_time.rs:354`](../crates/benilla-app/src/net/game_time.rs#L354))
- The reference loads the world first and logs in after: the entry's first frame starts the load at the record's map and position (`0x401570`, called at `0x46c236`), and a later one, once its file reader is idle (`0x46c247`), sends the login (`0x46c272`). ([`src/net/io.rs:10`](../crates/benilla-app/src/net/io.rs#L10))
- The reference re-dials only from `RequestRealmList`, and only when the link is down (`[CLoginMgr+5]` clear, `0x5ab857` → `0x5b2200`), with the reconnect challenge (`0x5b2134`, `[Logon+0xc]`); the connect's query sends only on a link in state 6 (`0x5bc14c`) and otherwise nothing, leaving the screen on its connecting dialog for good. ([`src/net/io.rs:407`](../crates/benilla-app/src/net/io.rs#L407))
- The reference's guard at `0x537e85` sends 0 whenever the write index is 0, one ping in sixteen; we send 0 only before the first pong, because the rest is an artefact of its index arithmetic that only the server stores. ([`src/net/io.rs:1172`](../crates/benilla-app/src/net/io.rs#L1172))
- The reference's guard at `0x537e85` sends 0 whenever the write index is 0, one ping in sixteen; we send 0 only before the first pong, because the rest is an artefact of its index arithmetic that only the server stores. ([`src/net/io.rs:1184`](../crates/benilla-app/src/net/io.rs#L1184))
- The reference places collision and culling by the raw facing, ours follow the display facing, because a capsule and a sphere barely change under rotation. ([`src/net/motion/facing.rs:9`](../crates/benilla-app/src/net/motion/facing.rs#L9))
- The reference paces a self move through the same replay chain as a remote's, which would only delay a correction to our own pose. ([`src/net/motion/remote.rs:84`](../crates/benilla-app/src/net/motion/remote.rs#L84))
- Its rate-limited hover climb (`0x636fa1`, 7 yd/s) is not reproduced, because the cache gate needs a pure function; it converges to this answer. ([`src/net/motion/spline.rs:568`](../crates/benilla-app/src/net/motion/spline.rs#L568))
@@ -343,14 +339,13 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
#### ui_gossip
- 14 (a NULL, pushed as `nil`) and 15 up (a read past the table's end) give `"gossip"`, because the reference's behaviour there is a missing bounds check. ([`src/ui_gossip/mod.rs:214`](../crates/benilla-app/src/ui_gossip/mod.rs#L214))
- 14 (a NULL, pushed as `nil`) and 15 up (a read past the table's end) give `"gossip"`, because the reference's behaviour there is a missing bounds check. ([`src/ui_gossip/mod.rs:222`](../crates/benilla-app/src/ui_gossip/mod.rs#L222))
#### ui_guild
- A script's 16-letter name, which the reference's bindings pass (1 to 16 units, `0x4d20d0`, `0x4d2210`), is dropped rather than sent or truncated, because vmangos would kick the session. ([`src/ui_guild/feed.rs:281`](../crates/benilla-app/src/ui_guild/feed.rs#L281))
- Bounded at the ten slots, because the reference's read (`0x4c93e7`) runs past its array. ([`src/ui_guild/mod.rs:50`](../crates/benilla-app/src/ui_guild/mod.rs#L50))
- Clamped to ten, because the reference's unbounded loop (`0x4d0bb0`) overruns its ten-slot array on a hostile `rankCount >= 12`. ([`src/ui_guild/mod.rs:432`](../crates/benilla-app/src/ui_guild/mod.rs#L432))
- The identity cache goes too, where the reference keeps it in `guildcache.wdb`, because a renamed guild would otherwise show its old name. ([`src/ui_guild/mod.rs:750`](../crates/benilla-app/src/ui_guild/mod.rs#L750))
- Clamped to ten, because the reference's unbounded loop (`0x4d0bb0`) overruns its ten-slot array on a hostile `rankCount >= 12`. ([`src/ui_guild/mod.rs:441`](../crates/benilla-app/src/ui_guild/mod.rs#L441))
- An exact tie is `Equal` where the reference answers ±1, and a NaN has a place (`total_cmp`), because Rust's sort requires a total order. ([`src/ui_guild/sort.rs:72`](../crates/benilla-app/src/ui_guild/sort.rs#L72))
- The reference ties a miss with a hit (`0x4d0e27`, `0x4d0ea1`), no total order. ([`src/ui_guild/sort.rs:89`](../crates/benilla-app/src/ui_guild/sort.rs#L89))
@@ -499,6 +494,10 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
- A constant one-logical-pixel shadow, not the reference's 0.001 gx, which draws 2 px thick and too heavy at larger windows. ([`src/vplates.rs:656`](../crates/benilla-app/src/vplates.rs#L656))
- The reference magnifies the 128 × 32 `Interface\Tooltips\Nameplate-Border` art with `GL_LINEAR` (`0x770200`, filter `[0x878cf0]` = 1), smearing its 1 px bevel once the plate is larger than native; we resample the same pixels to the plate's physical size with sharp bilinear and draw it 1:1, because the chosen look is the same art with a crisp bevel. `super::drive_vplates` regenerates it when the physical size changes. ([`src/vplates/border.rs:3`](../crates/benilla-app/src/vplates/border.rs#L3))
#### wdb
- The files are `benilla-config/cache/<realm>/<store>.bin` through `crate::local_state`, not `WDB/` in the install, which is read-only; they are per realm, because another server may hold another template under the same key; and a store is written ten seconds after an answer lands as well as at exit, so a crash costs only re-asking. ([`src/wdb.rs:38`](../crates/benilla-app/src/wdb.rs#L38))
#### world_console
- A float the scan leaves unread is 0.0, where the reference reads whatever its uninitialised stack slot holds. ([`src/world_console.rs:217`](../crates/benilla-app/src/world_console.rs#L217))
@@ -635,9 +634,9 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
#### events
- `benilla::spell_mods` refuses an out-of-range pair, because the reference would overrun it. ([`src/events.rs:725`](../crates/benilla-protocol/src/events.rs#L725))
- An out-of-range list past the first block reads no body in the write passes (`0x466076`), which misread every block behind it, while the notify pass reads past it (`0x465fd0`) and stays in step; benilla reads the list and drops it, keeping the blocks behind it whole. ([`src/events/decode.rs:1130`](../crates/benilla-protocol/src/events/decode.rs#L1130))
- The flagged pass reads a movement block's guid as 8 raw bytes (`0x467140`, `0x46714d`) where the wire packs it, so unless the packed guid happens to be 8 bytes the reference misreads the rest of that pass; benilla reads the block once, packed, as pass 0 does (`0x467080`). ([`src/events/decode.rs:1147`](../crates/benilla-protocol/src/events/decode.rs#L1147))
- `benilla::spell_mods` refuses an out-of-range pair, because the reference would overrun it. ([`src/events.rs:731`](../crates/benilla-protocol/src/events.rs#L731))
- An out-of-range list past the first block reads no body in the write passes (`0x466076`), which misread every block behind it, while the notify pass reads past it (`0x465fd0`) and stays in step; benilla reads the list and drops it, keeping the blocks behind it whole. ([`src/events/decode.rs:1133`](../crates/benilla-protocol/src/events/decode.rs#L1133))
- The flagged pass reads a movement block's guid as 8 raw bytes (`0x467140`, `0x46714d`) where the wire packs it, so unless the packed guid happens to be 8 bytes the reference misreads the rest of that pass; benilla reads the block once, packed, as pass 0 does (`0x467080`). ([`src/events/decode.rs:1150`](../crates/benilla-protocol/src/events/decode.rs#L1150))
#### examples
@@ -653,8 +652,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
- Zone and position are kept, not set to the viewer's zone and the object's position, because nothing in benilla reads them. ([`src/messages/group.rs:256`](../crates/benilla-protocol/src/messages/group.rs#L256))
- String reads are unbounded. The reference `0x4191b0` caps each field, counting the NUL (roster name `0x30`, notes `0x80`, MOTD `0x200`, info `0x7d0`, guild name `0x60`, rank name `0x40`), and on overflow empties it and no-ops every later read in the packet. ([`src/messages/guild.rs:4`](../crates/benilla-protocol/src/messages/guild.rs#L4))
- A reason of 3 or more is silent, where the reference prints an uninitialized stack buffer, because 3 is the server's `INSTANCERESET_FAIL_SILENTLY`. ([`src/messages/instance.rs:70`](../crates/benilla-protocol/src/messages/instance.rs#L70))
- 2 or more prints nothing, because the reference prints an uninitialized buffer. ([`src/messages/opcode.rs:1036`](../crates/benilla-protocol/src/messages/opcode.rs#L1036))
- The consumer refuses 64 and up, because there the reference's store overruns its table. ([`src/messages/packet.rs:632`](../crates/benilla-protocol/src/messages/packet.rs#L632))
- 2 or more prints nothing, because the reference prints an uninitialized buffer. ([`src/messages/opcode.rs:1041`](../crates/benilla-protocol/src/messages/opcode.rs#L1041))
- The consumer refuses 64 and up, because there the reference's store overruns its table. ([`src/messages/packet.rs:637`](../crates/benilla-protocol/src/messages/packet.rs#L637))
- A body too short for the position gives `None` where the client redisplays a stale global, because showing a stale queue position as current is a client bug. ([`src/messages/parse.rs:285`](../crates/benilla-protocol/src/messages/parse.rs#L285))
- A type outside 1-7 reads as nothing rather than the reference's default arm, which under-pushes its returns. ([`src/messages/pet.rs:71`](../crates/benilla-protocol/src/messages/pet.rs#L71))
- Both are read, told apart exactly by the tail length (`12n` vs `1 + 14n`), since the 1.12 client mis-parses vmangos's. ([`src/messages/pet.rs:191`](../crates/benilla-protocol/src/messages/pet.rs#L191))
+2 -2
View File
@@ -107,7 +107,7 @@
## Modules (top-level, per crate)
- **benilla-adt** (lib.rs): combined_alpha
- **benilla-app** (lib.rs): addon_harness area area_poi area_trigger asset_churn aura_visual bindings blob_shadow bowstring camera_shake capture chat_bubble chr_classes cinematic client_state combat_log combat_text console crash creature_anim creature_type cursor cvars death debug_panel dev devtools doodad_events entities field_watch fishing_line footprints game_plugins game_tip glue_session go_anim go_templates hover_log item_lane item_watch items lanes loading_screen local_state minimap name_persist nameplates names net no_install npc_text opaque2d perf pipe_warm player player_commands poi_marker portrait preflight probe_shield query_cache quest_markers raid_marks ranged_flex realmlist run_mode screen_fade screenshot script_calls shaders shutdown smart_rect sound spell swing_refusal target test_support text_filter textinput transport tutorial ui_action ui_auction ui_aura ui_bank ui_battlefield ui_battlefield_positions ui_battlefield_score ui_billing ui_bind_confirm ui_binder ui_cast ui_char ui_chat ui_craft ui_dialog_verbs ui_dressup ui_duel ui_follow ui_gamma ui_gm_ticket ui_gossip ui_guild ui_honor ui_inspect ui_instance ui_item_text ui_items ui_layout ui_logout ui_loot ui_loot_roll ui_macro ui_mail ui_memory ui_merchant ui_mirror ui_models ui_net ui_panes ui_party ui_pass ui_pet ui_pet_book ui_pet_stats ui_petition ui_quest ui_quest_log ui_quest_share ui_reputation ui_saved ui_script ui_session ui_shapeshift ui_social ui_spellbook ui_stable ui_summon ui_tabard ui_talent ui_talent_wipe ui_taxi ui_text ui_tooltip ui_trade ui_tradeskill ui_trainer ui_unit ui_world_map video vm_pass vplates weapon_trail world_backdrop world_console world_state world_state_ui
- **benilla-app** (lib.rs): addon_harness area area_poi area_trigger asset_churn aura_visual bindings blob_shadow bowstring camera_shake capture chat_bubble chr_classes cinematic client_state combat_log combat_text console crash creature_anim creature_type cursor cvars death debug_panel dev devtools doodad_events entities field_watch fishing_line footprints game_plugins game_tip glue_session go_anim go_templates hover_log item_lane item_names item_watch items lanes loading_screen local_state minimap nameplates names net no_install npc_text opaque2d perf pipe_warm player player_commands poi_marker portrait preflight probe_shield query_cache quest_markers raid_marks ranged_flex realmlist run_mode screen_fade screenshot script_calls shaders shutdown smart_rect sound spell swing_refusal target test_support text_filter textinput transport tutorial ui_action ui_auction ui_aura ui_bank ui_battlefield ui_battlefield_positions ui_battlefield_score ui_billing ui_bind_confirm ui_binder ui_cast ui_char ui_chat ui_craft ui_dialog_verbs ui_dressup ui_duel ui_follow ui_gamma ui_gm_ticket ui_gossip ui_guild ui_honor ui_inspect ui_instance ui_item_text ui_items ui_layout ui_logout ui_loot ui_loot_roll ui_macro ui_mail ui_memory ui_merchant ui_mirror ui_models ui_net ui_panes ui_party ui_pass ui_pet ui_pet_book ui_pet_stats ui_petition ui_quest ui_quest_log ui_quest_share ui_reputation ui_saved ui_script ui_session ui_shapeshift ui_social ui_spellbook ui_stable ui_summon ui_tabard ui_talent ui_talent_wipe ui_taxi ui_text ui_tooltip ui_trade ui_tradeskill ui_trainer ui_unit ui_world_map video vm_pass vplates wdb weapon_trail world_backdrop world_console world_state world_state_ui
- **benilla-assets** (lib.rs): adt anim_rng blp column_grid coords gpu_blp m2 materials minimap_grid model spatial_cache terrain tex_filter trace wdt wmo world_assets
- **benilla-formats** (lib.rs): anim_data area_poi area_sound area_table area_trigger auction_house bank_bag_slot_prices camera_shakes cfg_categories cfg_configs chain characters chat_channels chr_classes chr_races cinematics creature_families creature_sound creature_spell_data creature_types creatures dbc death_thud durability elevators emit_timing emote_text emotes environmental_damage exhaustion factions footsteps game_tips gameobjects garble gm_survey gm_ticket_category ground_effects install item_random_properties item_sounds item_visuals itembagfamily itemclass items itemsets itemsubclass languages lfg_dungeons light liquid loading_route loading_screen locale locale_routing lock lock_type loose macro_icons mail_template maps material minimap_translate models npc_greeting packages page_text_material particles pet_stats quest_headers quest_info race_creature_type race_pvp_team race_sound resistances ribbons server_messages sheathe skill_lines skill_tiers sound_entries sound_provider sound_water spell_focus spell_mechanic spell_visual spells stable_slot_prices stationery talents taxi taxi_nodes taxi_path terrain text_filter_lists tga transports unit_blood value_track vocal_ui_sounds wdl weapon_impact weapon_swing wmo_area world_map_area world_map_continent world_map_overlay world_state_ui wow_ini zone_map
- **benilla-lua** (lib.rs): api cfmt compile heap lex lib_base lib_math lib_string lib_table number parse pools proto reload table value vm
@@ -180,7 +180,7 @@
- `WOW_BOOTH_LOG` — benilla-app/src/portrait/mod.rs
- `WOW_CAM_CHANGED` — benilla-app/src/perf/mod.rs
- `WOW_CAM_DUMP` — benilla-app/src/player/camera.rs
- `WOW_CAPTURE` — benilla-app/src/capture/mod.rs, benilla-app/src/capture/scenarios.rs, benilla-app/src/cvars/mod.rs, benilla-app/src/glue_session/login.rs, benilla-app/src/lib.rs, benilla-app/src/local_state.rs, benilla-app/src/name_persist.rs, benilla-app/src/net.rs, benilla-app/src/player/camera_saved.rs, benilla-app/src/run_mode.rs, benilla-app/src/sound/mod.rs, benilla-app/src/ui_chat/settings.rs, benilla-app/src/ui_chat/tests.rs, benilla-app/src/ui_macro/tests.rs, benilla-app/src/ui_saved.rs, benilla-app/src/ui_script/addons.rs, benilla-app/src/ui_script/layer_tests.rs, benilla-app/src/ui_script/lifecycle.rs, benilla-app/src/ui_script/mod.rs, benilla-app/src/ui_script/world_entry_tests.rs, benilla-app/src/video.rs, benilla-world/src/bgwin.rs, benilla-world/src/clouds/mod.rs, benilla-world/src/dev_state.rs
- `WOW_CAPTURE` — benilla-app/src/capture/mod.rs, benilla-app/src/capture/scenarios.rs, benilla-app/src/cvars/mod.rs, benilla-app/src/glue_session/login.rs, benilla-app/src/lib.rs, benilla-app/src/local_state.rs, benilla-app/src/net.rs, benilla-app/src/player/camera_saved.rs, benilla-app/src/run_mode.rs, benilla-app/src/sound/mod.rs, benilla-app/src/ui_chat/settings.rs, benilla-app/src/ui_chat/tests.rs, benilla-app/src/ui_macro/tests.rs, benilla-app/src/ui_saved.rs, benilla-app/src/ui_script/addons.rs, benilla-app/src/ui_script/layer_tests.rs, benilla-app/src/ui_script/lifecycle.rs, benilla-app/src/ui_script/mod.rs, benilla-app/src/ui_script/world_entry_tests.rs, benilla-app/src/video.rs, benilla-app/src/wdb/tests.rs, benilla-world/src/bgwin.rs, benilla-world/src/clouds/mod.rs, benilla-world/src/dev_state.rs
- `WOW_CAPTURE_AGE` — benilla-app/src/capture/mod.rs
- `WOW_CAPTURE_DEADLINE` — benilla-app/src/capture/mod.rs
- `WOW_CAPTURE_OUT` — benilla-app/src/capture/mod.rs