use std::fs;
use std::path::Path;
use crate::clientscript::{self, hooks};
use crate::opcodes;
use crate::parallel::parallel_map;
use crate::symbol::{SymbolKind, SymbolRegistry, identifier_form, normalize_comp_name};
use crate::types::Type;
pub fn load_engine_command_params(registry: &mut SymbolRegistry, engine_rs2: &Path) {
let text = match fs::read_to_string(engine_rs2) {
Ok(t) => t,
Err(_) => return,
};
for line in text.lines() {
let line = line.trim();
if !line.starts_with("[command,") {
continue;
}
let rest = &line["[command,".len()..];
let name_end = match rest.find(']') {
Some(i) => i,
None => continue,
};
let name = rest[..name_end].trim().to_string();
let after_bracket = &rest[name_end + 1..];
let params_start = match after_bracket.find('(') {
Some(i) => i + 1,
None => {
registry.command_param_types.insert(name, Vec::new());
continue;
}
};
let params_end = match after_bracket[params_start..].find(')') {
Some(i) => params_start + i,
None => continue,
};
let params_str = &after_bracket[params_start..params_end];
let mut param_types: Vec<Type> = Vec::new();
for param in params_str.split(',') {
let param = param.trim();
if param.is_empty() {
continue;
}
let type_name = param.split_whitespace().next().unwrap_or(param);
if let Some(t) = Type::from_name(type_name) {
param_types.push(t);
} else {
param_types.push(Type::Int);
}
}
registry
.command_param_types
.insert(name.clone(), param_types.clone());
if let Some(sym) = registry.commands.get_mut(&name)
&& let SymbolKind::Command {
param_types: ref mut pt,
..
} = sym.kind
{
*pt = param_types;
}
let after_params = &after_bracket[params_end + 1..];
if let Some(ret_start) = after_params.find('(')
&& let Some(ret_end) = after_params[ret_start + 1..].find(')')
{
let ret_str = &after_params[ret_start + 1..ret_start + 1 + ret_end];
let mut return_types: Vec<Type> = Vec::new();
for ret in ret_str.split(',') {
let ret = ret.trim();
if ret.is_empty() {
continue;
}
if let Some(t) = Type::from_name(ret) {
return_types.push(t);
}
}
if !return_types.is_empty() {
if let Some(sym) = registry.commands.get_mut(&name)
&& let SymbolKind::Command {
return_types: ref mut rt,
..
} = sym.kind
{
*rt = return_types;
}
}
}
}
}
pub fn patch_command_return_types(registry: &mut SymbolRegistry) {
let patches: &[(&str, Vec<Type>)] = &[
("db_find_with_count", vec![Type::Int]),
("db_find_refine_with_count", vec![Type::Int]),
("db_listall_with_count", vec![Type::Int]),
];
for (name, ret_types) in patches {
if let Some(sym) = registry.commands.get_mut(*name)
&& let SymbolKind::Command { return_types, .. } = &mut sym.kind
&& return_types.is_empty()
{
*return_types = ret_types.clone();
}
}
}
pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) -> Result<(), String> {
load_packs_with_commands(registry, pack_dir, "command.pack")
}
pub(crate) fn load_packs_with_commands(
registry: &mut SymbolRegistry,
pack_dir: &Path,
commands: &str,
) -> Result<(), String> {
if !pack_dir.exists() {
return Ok(());
}
register_engine_constants(registry);
load_commands(registry, &pack_dir.join(commands))?;
load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
load_game_vars(registry, &pack_dir.join("varp.pack"), "varp");
load_game_vars(registry, &pack_dir.join("varn.pack"), "varn");
load_game_vars(registry, &pack_dir.join("vars.pack"), "vars");
load_game_vars(registry, &pack_dir.join("varpbit.pack"), "varpbit");
load_game_vars(registry, &pack_dir.join("varc.pack"), "varc");
load_game_vars(registry, &pack_dir.join("varcstr.pack"), "varcstr");
load_game_vars(registry, &pack_dir.join("varclan.pack"), "varclan");
load_game_vars(registry, &pack_dir.join("varobj.pack"), "varobj");
load_game_vars(registry, &pack_dir.join("varnbit.pack"), "varnbit");
load_game_vars(registry, &pack_dir.join("varcon.pack"), "varcon");
load_game_vars(registry, &pack_dir.join("varconbit.pack"), "varconbit");
for (file, type_hint) in &[
("area.pack", Type::Area),
("bas.pack", Type::Bas),
("billboard.pack", Type::Billboard),
("particleeffector.pack", Type::ParticleEffector),
("particleemitter.pack", Type::ParticleEmitter),
("cursor.pack", Type::Cursor),
("flo.pack", Type::Flo),
("flu.pack", Type::Flu),
("hitmark.pack", Type::Hitmark),
("itemcode.pack", Type::ItemCode),
("light.pack", Type::Light),
("mel.pack", Type::MapElement),
("msi.pack", Type::Msi),
("quest.pack", Type::Quest),
("varclan.pack", Type::VarClan),
("varcon.pack", Type::VarCon),
("varconbit.pack", Type::VarConBit),
("varnbit.pack", Type::VarnBit),
("varobj.pack", Type::VarObj),
("category.pack", Type::Category),
("idk.pack", Type::IdKit),
("interface.pack", Type::Interface), ("overlayinterface.pack", Type::OverlayInterface),
("struct.pack", Type::Struct),
("dbrow.pack", Type::DbRow),
("dbtable.pack", Type::DbTable),
("dbcolumn.pack", Type::DbColumn),
("param.pack", Type::Param),
("model.pack", Type::Model),
("sprites.pack", Type::Graphic),
("texture.pack", Type::Texture),
("wma.pack", Type::MapArea),
("mapelement.pack", Type::MapElement),
("fontmetrics.pack", Type::FontMetrics),
("chatcat.pack", Type::ChatCat),
("chatphrase.pack", Type::ChatPhrase),
("mesanim.pack", Type::MesAnim),
("jingle.pack", Type::Jingle),
("midi.pack", Type::Midi),
("synth.pack", Type::Synth),
("vorbis.pack", Type::Vorbis),
("spotanim.pack", Type::Spotanim),
("seq.pack", Type::Seq),
("locshape.pack", Type::LocShape),
("hunt.pack", Type::Hunt),
("npc_mode.pack", Type::NpcMode),
("enum.pack", Type::Enum),
("writeinv.pack", Type::WriteInv),
("inv.pack", Type::Inv),
("loc.pack", Type::Loc),
("npc_stat.pack", Type::NpcStat),
("stat.pack", Type::Stat),
("npc.pack", Type::Npc),
("obj.pack", Type::Obj),
("controller.pack", Type::Controller),
] {
load_entity_ids(registry, &pack_dir.join(file), *type_hint);
}
load_entity_ids_typed_only(registry, &pack_dir.join("obj.pack"), Type::NamedObj);
register_type_chars(registry);
Ok(())
}
pub(crate) fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (id_str, rest) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let id: i32 = match id_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
let rest = rest.trim();
if !rest.starts_with('[') || !rest.ends_with(']') {
continue;
}
let inner = &rest[1..rest.len() - 1];
let (trigger, name) = match inner.split_once(',') {
Some(pair) => pair,
None => continue,
};
if name.is_empty() {
continue;
}
if trigger == "clientscript" {
registry.script_ids.insert(name.to_string(), id);
registry
.trigger_script_ids
.insert(format!("clientscript:{name}"), id);
} else {
registry.script_ids.entry(name.to_string()).or_insert(id);
registry
.trigger_script_ids
.entry(format!("clientscript:{name}"))
.or_insert(id);
}
}
}
pub(crate) fn load_clientscript_signatures(registry: &mut SymbolRegistry, dir: &Path) {
let Ok(files) = crate::sources::script_files(dir, "cs2") else {
return;
};
let files: Vec<_> = files
.into_iter()
.filter(|path| path.extension().is_some_and(|ext| ext == "cs2"))
.collect();
let sources: Vec<_> = parallel_map(&files, |path| {
let text = fs::read_to_string(path).ok()?;
clientscript::parse(&text, path).ok()
})
.into_iter()
.flatten()
.collect();
hooks::register_callbacks(registry, sources.iter().flat_map(|file| &file.scripts));
}
fn load_commands(registry: &mut SymbolRegistry, path: &Path) -> Result<(), String> {
let Ok(text) = fs::read_to_string(path) else {
return Ok(());
};
let mut wrong = Vec::new();
for line in text.lines() {
let line = line.split("//").next().unwrap_or_default().trim();
let Some((code, name)) = line.split_once('=') else {
continue;
};
let (Ok(code), name) = (code.parse::<i32>(), name.trim()) else {
continue;
};
if name.is_empty() {
continue;
}
match opcodes::opcode(name) {
Some(opcode) if i32::from(opcode) == code => {}
Some(opcode) => wrong.push(format!("{name} at {code} (its opcode is {opcode})")),
None => wrong.push(format!("{name} at {code} (not a command)")),
}
registry.register_command(name.to_string(), code, Vec::new(), Vec::new());
}
if wrong.is_empty() {
Ok(())
} else {
Err(format!("{}: {}", path.display(), wrong.join(", ")))
}
}
fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (id_str, name) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let idx: i32 = match id_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
let name = name.trim().to_string();
if name.is_empty() {
continue;
}
registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
registry.register_game_var(name, Type::Int, idx, category.to_string());
}
}
pub fn load_dbtable_configs(
registry: &mut SymbolRegistry,
files: &[std::path::PathBuf],
dbtable_ids: &std::collections::HashMap<String, u16>,
) {
let mut dbtable_files: Vec<&std::path::PathBuf> = files
.iter()
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("dbtable"))
.collect();
dbtable_files.sort();
for path in dbtable_files {
let Ok(text) = fs::read_to_string(path) else {
continue;
};
let lines = strip_comments(&text);
let mut current_table: Option<String> = None;
let mut col_idx: u16 = 0;
for line in lines {
if line.starts_with('[') && line.ends_with(']') {
let name = line[1..line.len() - 1].trim().to_string();
current_table = Some(name);
col_idx = 0;
continue;
}
let Some(rest) = line.strip_prefix("column=") else {
continue;
};
let Some(table_name) = current_table.as_deref() else {
continue;
};
let Some(&table_id) = dbtable_ids.get(table_name) else {
continue;
};
let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
if parts.is_empty() {
continue;
}
let col_name = parts[0];
if col_name.is_empty() {
continue;
}
let types: Vec<Type> = parts[1..]
.iter()
.filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
.filter_map(|s| Type::from_name(s))
.collect();
let compound = format!("{}:{}", table_name, col_name);
let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
if types.len() > 1 {
for (i, _) in types.iter().enumerate() {
let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
let slot_packed = packed | (((i as i32) + 1) & 0xF);
registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
}
}
if !types.is_empty() {
registry.dbcolumn_types.insert(compound, types);
}
col_idx += 1;
}
}
}
pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
let mut out = std::collections::HashMap::new();
let Ok(text) = fs::read_to_string(path) else {
return out;
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let Some((id_str, name)) = line.split_once('=') else {
continue;
};
let Ok(id) = id_str.parse::<u16>() else {
continue;
};
let name = name.trim();
if name.is_empty() {
continue;
}
out.insert(name.to_string(), id);
}
out
}
pub fn load_constant_files(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
let mut constant_files: Vec<&std::path::PathBuf> = files
.iter()
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("constant"))
.collect();
constant_files.sort();
for path in constant_files {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => continue,
};
let lines = strip_comments(&text);
for line in lines {
let eq_pos = match line.find('=') {
Some(i) => i,
None => continue,
};
let mut name = line[..eq_pos].trim();
let value = line[eq_pos + 1..].trim();
if let Some(stripped) = name.strip_prefix('^') {
name = stripped;
}
if name.is_empty() {
continue;
}
let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
&value[1..value.len() - 1]
} else {
value
};
register_constant_value(registry, name.to_string(), val_str);
}
}
}
fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
if let Ok(i) = val_str.parse::<i32>() {
registry.register_constant(name, Type::Int, Some(i), None);
} else if let Some(hex_str) = val_str
.strip_prefix("0x")
.or_else(|| val_str.strip_prefix("0X"))
{
let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
registry.register_constant(name, Type::Int, Some(v), None);
} else if let Some(packed) = parse_coord_string(val_str) {
registry.register_constant(name, Type::Coord, Some(packed), None);
} else {
registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
}
}
pub(crate) fn strip_comments(text: &str) -> impl Iterator<Item = std::borrow::Cow<'_, str>> {
let mut comments = Comments::default();
text.lines().filter_map(move |line| comments.line(line))
}
#[derive(Default)]
pub(crate) struct Comments {
depth: usize,
}
impl Comments {
pub(crate) fn line<'a>(&mut self, raw: &'a str) -> Option<std::borrow::Cow<'a, str>> {
use std::borrow::Cow;
let line = raw.trim();
if self.depth == 0 && !line.contains("//") && !line.contains("/*") {
return (!line.is_empty()).then_some(Cow::Borrowed(line));
}
let bytes = line.as_bytes();
let mut output = Cow::Borrowed("");
let mut start = 0;
let mut i = 0;
let mut quoted = false;
let append = |output: &mut Cow<'_, str>, part: &str| {
output.to_mut().push_str(part);
};
while i < bytes.len() {
if self.depth > 0 {
if bytes[i..].starts_with(b"/*") {
self.depth += 1;
i += 2;
} else if bytes[i..].starts_with(b"*/") {
self.depth -= 1;
i += 2;
} else {
i += 1;
}
start = i;
} else if quoted {
if bytes[i] == b'\\' {
i = (i + 2).min(bytes.len());
} else {
if bytes[i] == b'"' {
quoted = false;
}
i += 1;
}
} else if bytes[i] == b'"' {
quoted = true;
i += 1;
} else if bytes[i..].starts_with(b"//") {
if output.is_empty() {
output = Cow::Borrowed(&line[start..i]);
} else {
append(&mut output, &line[start..i]);
}
start = bytes.len();
break;
} else if bytes[i..].starts_with(b"/*") {
if output.is_empty() {
output = Cow::Borrowed(&line[start..i]);
} else {
append(&mut output, &line[start..i]);
}
self.depth = 1;
i += 2;
start = i;
} else {
i += 1;
}
}
if self.depth == 0 && start < bytes.len() {
if output.is_empty() {
output = Cow::Borrowed(&line[start..]);
} else {
append(&mut output, &line[start..]);
}
}
match output {
Cow::Borrowed(value) => (!value.trim().is_empty()).then(|| Cow::Borrowed(value.trim())),
Cow::Owned(value) => {
(!value.trim().is_empty()).then(|| Cow::Owned(value.trim().to_owned()))
}
}
}
}
pub fn load_game_var_types(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
for ext in &["varp", "varn", "vars", "varpbit"] {
let max_id = registry
.game_vars
.values()
.filter_map(|sym| {
if let crate::symbol::SymbolKind::GameVar {
var_id, category, ..
} = &sym.kind
{
if category == *ext {
Some(*var_id)
} else {
None
}
} else {
None
}
})
.max()
.unwrap_or(-1);
next_auto_id.insert(ext.to_string(), max_id + 1);
}
for ext in &[
"varp",
"varn",
"vars",
"varpbit",
"varc",
"varclan",
"varobj",
"varnbit",
"varcon",
"varconbit",
] {
let ext_files = files
.iter()
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some(*ext));
for path in ext_files {
let Ok(text) = fs::read_to_string(path) else {
continue;
};
let mut current_name: Option<String> = None;
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with("//") {
continue;
}
if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
let name = inner.trim().to_string();
if matches!(*ext, "varp" | "varn" | "vars" | "varpbit")
&& !registry.game_vars.contains_key(&name)
{
let id = next_auto_id.get_mut(*ext).unwrap();
let auto_id = *id;
*id += 1;
registry.register_game_var(
name.clone(),
Type::Int,
auto_id,
ext.to_string(),
);
registry.register_game_var(
format!(".{}", name),
Type::Int,
auto_id,
ext.to_string(),
);
}
current_name = Some(name);
continue;
}
let Some(name) = current_name.as_ref() else {
continue;
};
if let Some((k, v)) = line.split_once('=')
&& k.trim() == "type"
{
let type_name = v.trim();
if let Some(ty) = Type::from_name(type_name) {
if let Some(sym) = registry.game_vars.get_mut(name)
&& let crate::symbol::SymbolKind::GameVar { var_type, .. } =
&mut sym.kind
{
*var_type = ty;
}
let dot_name = format!(".{}", name);
if let Some(sym) = registry.game_vars.get_mut(&dot_name)
&& let crate::symbol::SymbolKind::GameVar { var_type, .. } =
&mut sym.kind
{
*var_type = ty;
}
}
}
}
}
}
}
pub(crate) fn entry_is_dir(entry: &fs::DirEntry, path: &Path) -> bool {
match entry.file_type() {
Ok(ft) if !ft.is_symlink() => ft.is_dir(),
_ => path.is_dir(),
}
}
pub fn collect_all_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let path = entry.path();
if entry_is_dir(&entry, &path) {
collect_all_files(&path, out);
} else {
out.push(path);
}
}
}
fn parse_coord_string(s: &str) -> Option<i32> {
let parts: Vec<&str> = s.split('_').collect();
if parts.len() != 5 {
return None;
}
let y: i32 = parts[0].parse().ok()?;
let bx: i32 = parts[1].parse().ok()?;
let bz: i32 = parts[2].parse().ok()?;
let lx: i32 = parts[3].parse().ok()?;
let lz: i32 = parts[4].parse().ok()?;
let x = bx * 64 + lx;
let z = bz * 64 + lz;
Some((y << 28) | (x << 14) | z)
}
fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
};
let is_interface_pack = entity_type == Type::Interface;
let mut iface_id_to_name: std::collections::HashMap<i32, String> =
std::collections::HashMap::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (id_str, name) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let name = name.trim();
if name.is_empty() || name == "null" {
continue;
}
if is_interface_pack
&& !id_str.contains(':')
&& !name.contains(':')
&& let Ok(id) = id_str.parse::<i32>()
{
registry.interface_ids.insert(identifier_form(name), id);
iface_id_to_name.insert(id, identifier_form(name));
}
}
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (id_str, name) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let name = name.trim();
if name.is_empty() || name == "null" {
continue;
}
let (idx, component_key, register_name): (i32, Option<String>, String) =
if let Some((iface_str, comp_str)) = id_str.split_once(':') {
let iface: i32 = match iface_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
let comp: i32 = match comp_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
let packed = (iface << 16) | comp;
let key = iface_id_to_name
.get(&iface)
.map(|iface_name| format!("{}:{}", iface_name, name));
(packed, key, name.to_string())
} else if is_interface_pack {
let flat_id: i32 = match id_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
if name.contains(':') {
(flat_id, Some(name.to_string()), name.to_string())
} else {
(flat_id, None, name.to_string())
}
} else {
let id: i32 = match id_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
(id, None, name.to_string())
};
let actual_type = if is_interface_pack && component_key.is_some() {
Type::Component
} else {
entity_type
};
let normalized = if is_interface_pack {
identifier_form(®ister_name).to_lowercase()
} else {
register_name.to_lowercase().replace(' ', "_")
};
registry.register_entity_id(normalized, actual_type, idx);
if is_interface_pack && let Some(key) = component_key {
let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
format!(
"{}:{}",
identifier_form(iface_part),
normalize_comp_name(&identifier_form(comp_part))
)
} else {
key
};
registry.components.insert(normalized_key, idx);
}
}
}
fn load_entity_ids_typed_only(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (id_str, name) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let name = name.trim();
if name.is_empty() || name == "null" {
continue;
}
let id: i32 = match id_str.parse() {
Ok(v) => v,
Err(_) => continue,
};
let normalized = name.to_lowercase().replace(' ', "_");
registry.register_entity_id_typed_only(normalized, entity_type, id);
}
}
fn register_type_chars(registry: &mut SymbolRegistry) {
let type_chars: &[(&str, i32)] = &[
("int", b'i' as i32), ("string", b's' as i32), ("boolean", b'1' as i32), ("bool", b'1' as i32),
("coord", b'c' as i32), ("loc", b'l' as i32), ("npc", b'n' as i32), ("obj", b'o' as i32), ("namedobj", b'O' as i32), ("playeruid", b'p' as i32), ("player_uid", b'p' as i32),
("npcuid", b'u' as i32), ("npc_uid", b'u' as i32),
("seq", b'A' as i32), ("spotanim", b't' as i32), ("synth", b'P' as i32), ("stat", b'S' as i32), ("component", b'I' as i32), ("interface", b'a' as i32), ("toplevelinterface", b'a' as i32),
("overlayinterface", b'a' as i32),
("inv", b'v' as i32), ("enum", b'g' as i32), ("struct", b'J' as i32), ("dbrow", 0xD0), ("dbtable", b'i' as i32), ("dbcolumn", b'i' as i32),
("category", b'y' as i32), ("varp", b'V' as i32), ("npc_stat", 0xFE), ("npcstat", 0xFE),
("idkit", b'K' as i32), ("idk", b'K' as i32),
("wma", b'`' as i32),
];
for (name, val) in type_chars {
registry.type_chars.insert(name.to_string(), *val);
}
for ch in Type::CHARS.chars() {
if let Some(ty) = Type::from_char(ch) {
registry
.type_chars
.entry(ty.name().to_string())
.or_insert(ch as i32);
}
}
}
fn register_engine_constants(registry: &mut SymbolRegistry) {
let npc_modes: &[(&str, i32)] = &[
("null", -1),
("none", 0),
("wander", 1),
("patrol", 2),
("playerescape", 3),
("playerfollow", 4),
("playerface", 5),
("playerfaceclose", 6),
("opplayer1", 7),
("opplayer2", 8),
("opplayer3", 9),
("opplayer4", 10),
("opplayer5", 11),
("applayer1", 12),
("applayer2", 13),
("applayer3", 14),
("applayer4", 15),
("applayer5", 16),
("oploc1", 17),
("oploc2", 18),
("oploc3", 19),
("oploc4", 20),
("oploc5", 21),
("aploc1", 22),
("aploc2", 23),
("aploc3", 24),
("aploc4", 25),
("aploc5", 26),
("opobj1", 27),
("opobj2", 28),
("opobj3", 29),
("opobj4", 30),
("opobj5", 31),
("apobj1", 32),
("apobj2", 33),
("apobj3", 34),
("apobj4", 35),
("apobj5", 36),
("opnpc1", 37),
("opnpc2", 38),
("opnpc3", 39),
("opnpc4", 40),
("opnpc5", 41),
("apnpc1", 42),
("apnpc2", 43),
("apnpc3", 44),
("apnpc4", 45),
("apnpc5", 46),
("queue1", 47),
("queue2", 48),
("queue3", 49),
("queue4", 50),
("queue5", 51),
("queue6", 52),
("queue7", 53),
("queue8", 54),
("queue9", 55),
("queue10", 56),
("queue11", 57),
("queue12", 58),
("queue13", 59),
("queue14", 60),
("queue15", 61),
("queue16", 62),
("queue17", 63),
("queue18", 64),
("queue19", 65),
("queue20", 66),
];
fn is_trigger_collision(name: &str) -> bool {
matches!(
name,
"oploc1"
| "oploc2"
| "oploc3"
| "oploc4"
| "oploc5"
| "aploc1"
| "aploc2"
| "aploc3"
| "aploc4"
| "aploc5"
| "opnpc1"
| "opnpc2"
| "opnpc3"
| "opnpc4"
| "opnpc5"
| "apnpc1"
| "apnpc2"
| "apnpc3"
| "apnpc4"
| "apnpc5"
| "opobj1"
| "opobj2"
| "opobj3"
| "opobj4"
| "opobj5"
| "apobj1"
| "apobj2"
| "apobj3"
| "apobj4"
| "apobj5"
| "opplayer1"
| "opplayer2"
| "opplayer3"
| "opplayer4"
| "opplayer5"
| "applayer1"
| "applayer2"
| "applayer3"
| "applayer4"
| "applayer5"
| "queue1"
| "queue2"
| "queue3"
| "queue4"
| "queue5"
| "queue6"
| "queue7"
| "queue8"
| "queue9"
| "queue10"
| "queue11"
| "queue12"
| "queue13"
| "queue14"
| "queue15"
| "queue16"
| "queue17"
| "queue18"
| "queue19"
| "queue20"
)
}
for &(name, id) in npc_modes {
if is_trigger_collision(name) {
registry.register_entity_id_typed_only(name.to_string(), Type::NpcMode, id);
} else {
registry.register_entity_id(name.to_string(), Type::NpcMode, id);
}
}
let npc_stats: &[(&str, i32)] = &[
("attack", 0),
("defence", 1),
("strength", 2),
("hitpoints", 3),
("ranged", 4),
("magic", 5),
];
for &(name, id) in npc_stats {
registry.register_entity_id(name.to_string(), Type::NpcStat, id);
}
let stats: &[(&str, i32)] = &[
("attack", 0),
("defence", 1),
("strength", 2),
("hitpoints", 3),
("ranged", 4),
("prayer", 5),
("magic", 6),
("cooking", 7),
("woodcutting", 8),
("fletching", 9),
("fishing", 10),
("firemaking", 11),
("crafting", 12),
("smithing", 13),
("mining", 14),
("herblore", 15),
("agility", 16),
("thieving", 17),
("slayer", 18),
("stat18", 18),
("farming", 19),
("stat19", 19),
("runecraft", 20),
("hunter", 21),
("construction", 22),
("animallore", 23),
("rand", 24),
];
for &(name, id) in stats {
registry.register_entity_id(name.to_string(), Type::Stat, id);
}
let fontmetrics: &[(&str, i32)] = &[
("p11", 0),
("p12", 1),
("b12", 2),
("q8", 3),
("p11_full", 0),
("p12_full", 1),
("b12_full", 2),
("q8_full", 3),
];
for &(name, id) in fontmetrics {
registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
}
let locshapes: &[(&str, i32)] = &[
("wall_straight", 0),
("wall_diagonalcorner", 1),
("wall_l", 2),
("wall_squarecorner", 3),
("walldecor_straight_nooffset", 4),
("walldecor_straight_offset", 5),
("walldecor_diagonal_offset", 6),
("walldecor_diagonal_nooffset", 7),
("walldecor_diagonal_both", 8),
("wall_diagonal", 9),
("centrepiece_straight", 10),
("centrepiece_diagonal", 11),
("roof_straight", 12),
("roof_diagonal_with_roofedge", 13),
("roof_diagonal", 14),
("roof_l_concave", 15),
("roof_l_convex", 16),
("roof_flat", 17),
("roofedge_straight", 18),
("roofedge_diagonalcorner", 19),
("roofedge_l", 20),
("roofedge_squarecorner", 21),
("grounddecor", 22),
];
for &(name, id) in locshapes {
registry.register_entity_id(name.to_string(), Type::LocShape, id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::symbol::SymbolRegistry;
use crate::types::Type;
use std::io::Write;
use std::path::PathBuf;
fn write_temp_pack(name: &str, content: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("test-symloader");
fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
let mut f = fs::File::create(&path).unwrap();
f.write_all(content.as_bytes()).unwrap();
path
}
#[test]
fn command_pack_names_each_command_at_its_own_opcode() {
let pack = write_temp_pack(
"command_good.pack",
"2062=mes\n2093=queue* // 289's name\n2060=longqueuevararg\n",
);
let mut r = SymbolRegistry::new();
load_commands(&mut r, &pack).unwrap();
assert!(r.lookup_command("mes").is_some());
assert!(r.lookup_command("queue*").is_some());
let pack = write_temp_pack("command_bad.pack", "2063=mes\n9999=no_such_command\n");
let error = load_commands(&mut SymbolRegistry::new(), &pack).unwrap_err();
assert!(
error.contains("mes at 2063 (its opcode is 2062)"),
"{error}"
);
assert!(
error.contains("no_such_command at 9999 (not a command)"),
"{error}"
);
}
#[test]
fn load_647_style_registers_components() {
let pack = write_temp_pack(
"interface_647.pack",
"\
228=multi2\n\
228:0=com0\n\
228:1=com1\n\
228:2=com2\n\
228:3=com3\n\
228:6=thin_swords\n\
228:9=wide_swords\n",
);
let mut r = SymbolRegistry::new();
load_entity_ids(&mut r, &pack, Type::Interface);
assert_eq!(r.interface_ids.get("multi2"), Some(&228));
assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
assert_eq!(
r.lookup_component("multi2", "thin_swords"),
Some((228 << 16) | 6)
);
assert_eq!(
r.lookup_component("multi2", "wide_swords"),
Some((228 << 16) | 9)
);
}
#[test]
fn load_647_style_resolves_225_references() {
let pack = write_temp_pack(
"interface_647_cross.pack",
"\
228=multi2\n\
228:0=com0\n\
228:1=com1\n\
228:2=com2\n",
);
let mut r = SymbolRegistry::new();
load_entity_ids(&mut r, &pack, Type::Interface);
assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
}
#[test]
fn load_225_style_registers_components() {
let pack = write_temp_pack(
"interface_225.pack",
"\
2459=multi2\n\
2460=multi2:com_0\n\
2461=multi2:com_1\n\
2462=multi2:com_2\n\
2463=multi2:com_4\n\
2464=multi2:com_5\n",
);
let mut r = SymbolRegistry::new();
load_entity_ids(&mut r, &pack, Type::Interface);
assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
}
#[test]
fn load_225_style_resolves_647_references() {
let pack = write_temp_pack(
"interface_225_cross.pack",
"\
2459=multi2\n\
2460=multi2:com_0\n\
2461=multi2:com_1\n\
2462=multi2:com_2\n",
);
let mut r = SymbolRegistry::new();
load_entity_ids(&mut r, &pack, Type::Interface);
assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
}
#[test]
fn components_register_as_component_type() {
let pack = write_temp_pack(
"interface_types.pack",
"\
228=multi2\n\
228:0=com0\n",
);
let mut r = SymbolRegistry::new();
load_entity_ids(&mut r, &pack, Type::Interface);
assert!(
r.lookup_entity_id_typed("multi2", Type::Interface)
.is_some()
);
assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
}
}