1use std::fs;
7use std::path::Path;
8
9use tracing::{info, warn};
10
11use crate::clientscript::{self, hooks};
12use crate::symbol::{SymbolKind, SymbolRegistry};
13use crate::types::Type;
14
15pub fn load_engine_command_params(registry: &mut SymbolRegistry, engine_rs2: &Path) {
20 let text = match fs::read_to_string(engine_rs2) {
21 Ok(t) => t,
22 Err(_) => return,
23 };
24 for line in text.lines() {
25 let line = line.trim();
26 if !line.starts_with("[command,") {
28 continue;
29 }
30 let rest = &line["[command,".len()..];
32 let name_end = match rest.find(']') {
33 Some(i) => i,
34 None => continue,
35 };
36 let name = rest[..name_end].trim().to_string();
37
38 let after_bracket = &rest[name_end + 1..];
40 let params_start = match after_bracket.find('(') {
41 Some(i) => i + 1,
42 None => {
43 registry.command_param_types.insert(name, Vec::new());
45 continue;
46 }
47 };
48 let params_end = match after_bracket[params_start..].find(')') {
49 Some(i) => params_start + i,
50 None => continue,
51 };
52 let params_str = &after_bracket[params_start..params_end];
53
54 let mut param_types: Vec<Type> = Vec::new();
55 for param in params_str.split(',') {
56 let param = param.trim();
57 if param.is_empty() {
58 continue;
59 }
60 let type_name = param.split_whitespace().next().unwrap_or(param);
62 if let Some(t) = Type::from_name(type_name) {
63 param_types.push(t);
64 } else {
65 param_types.push(Type::Int);
67 }
68 }
69 registry
70 .command_param_types
71 .insert(name.clone(), param_types.clone());
72
73 if let Some(sym) = registry.commands.get_mut(&name)
74 && let SymbolKind::Command {
75 param_types: ref mut pt,
76 ..
77 } = sym.kind
78 {
79 *pt = param_types;
80 }
81
82 let after_params = &after_bracket[params_end + 1..];
84 if let Some(ret_start) = after_params.find('(')
85 && let Some(ret_end) = after_params[ret_start + 1..].find(')')
86 {
87 let ret_str = &after_params[ret_start + 1..ret_start + 1 + ret_end];
88 let mut return_types: Vec<Type> = Vec::new();
89 for ret in ret_str.split(',') {
90 let ret = ret.trim();
91 if ret.is_empty() {
92 continue;
93 }
94 if let Some(t) = Type::from_name(ret) {
95 return_types.push(t);
96 }
97 }
98 if !return_types.is_empty() {
99 if let Some(sym) = registry.commands.get_mut(&name)
101 && let SymbolKind::Command {
102 return_types: ref mut rt,
103 ..
104 } = sym.kind
105 {
106 *rt = return_types;
107 }
108 }
109 }
110 }
111}
112
113pub fn patch_command_return_types(registry: &mut SymbolRegistry) {
117 let patches: &[(&str, Vec<Type>)] = &[
118 ("db_find_with_count", vec![Type::Int]),
119 ("db_find_refine_with_count", vec![Type::Int]),
120 ("db_listall_with_count", vec![Type::Int]),
121 ];
122 for (name, ret_types) in patches {
123 if let Some(sym) = registry.commands.get_mut(*name)
124 && let SymbolKind::Command { return_types, .. } = &mut sym.kind
125 && return_types.is_empty()
126 {
127 *return_types = ret_types.clone();
128 }
129 }
130}
131
132fn load_script_pack(registry: &mut SymbolRegistry, path: &Path) {
135 let text = match fs::read_to_string(path) {
136 Ok(t) => t,
137 Err(_) => return,
138 };
139 for line in text.lines() {
140 let line = line.trim();
141 if line.is_empty() {
142 continue;
143 }
144 let (id_str, rest) = match line.split_once('=') {
145 Some(pair) => pair,
146 None => continue,
147 };
148 let id: i32 = match id_str.parse() {
149 Ok(v) => v,
150 Err(_) => continue,
151 };
152 let rest = rest.trim();
153 if !rest.starts_with('[') || !rest.ends_with(']') {
155 continue;
156 }
157 let inner = &rest[1..rest.len() - 1];
158 let comma = match inner.find(',') {
159 Some(i) => i,
160 None => continue,
161 };
162 let trigger = &inner[..comma];
163 let name = &inner[comma + 1..];
164 if trigger.is_empty() || name.is_empty() {
165 continue;
166 }
167 let key = format!("{}:{}", trigger, name);
168 registry.preloaded_script_ids.insert(key, id);
169 }
170}
171
172pub fn generate_script_pack(
175 scripts_dir: &Path,
176 pack_dir: &Path,
177 sources: &std::collections::HashMap<std::path::PathBuf, std::sync::Arc<String>>,
178) {
179 use std::collections::BTreeMap;
180
181 let pack_path = pack_dir.join("script.pack");
182
183 let mut id_to_name: BTreeMap<i32, String> = BTreeMap::new();
185 let mut name_to_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
186 let mut max_id: i32 = 0;
187
188 if let Ok(text) = fs::read_to_string(&pack_path) {
189 for line in text.lines() {
190 let line = line.trim();
191 if line.is_empty() {
192 continue;
193 }
194 if let Some((id_str, name)) = line.split_once('=')
195 && let Ok(id) = id_str.parse::<i32>()
196 {
197 let name = name.trim().to_string();
198 name_to_id.insert(name.clone(), id);
199 id_to_name.insert(id, name);
200 if id >= max_id {
201 max_id = id + 1;
202 }
203 }
204 }
205 }
206
207 let rs2_files = crate::sources::script_files(scripts_dir, "rs2").unwrap_or_default();
209
210 for path in &rs2_files {
211 if path.file_name().and_then(|n| n.to_str()) == Some("engine.rs2") {
213 continue;
214 }
215 let fallback;
219 let text: &str = if let Some(rc) = sources.get(path) {
220 rc
221 } else {
222 fallback = match fs::read_to_string(path) {
223 Ok(t) => t,
224 Err(_) => continue,
225 };
226 &fallback
227 };
228 for line in text.lines() {
229 let line = line.split("//").next().unwrap_or("").trim();
230 if !line.starts_with('[') {
231 continue;
232 }
233 let bracket_end = match line.find(']') {
234 Some(i) => i,
235 None => continue,
236 };
237 let full_name = &line[..bracket_end + 1]; let inner = &line[1..bracket_end];
239 let comma = match inner.find(',') {
240 Some(i) => i,
241 None => continue,
242 };
243 let trigger = &inner[..comma];
244 if trigger == "command" {
246 continue;
247 }
248
249 if !name_to_id.contains_key(full_name) {
250 name_to_id.insert(full_name.to_string(), max_id);
251 id_to_name.insert(max_id, full_name.to_string());
252 max_id += 1;
253 }
254 }
255 }
256
257 if let Err(e) = std::fs::create_dir_all(pack_dir) {
259 warn!(target: "runec", "Failed to create pack dir: {}", e);
260 return;
261 }
262 let mut out = String::new();
263 for (id, name) in &id_to_name {
264 out.push_str(&format!("{}={}\n", id, name));
265 }
266 if let Err(e) = fs::write(&pack_path, &out) {
267 warn!(target: "runec", "Failed to write script.pack: {}", e);
268 } else {
269 info!(target: "runec", "script.pack: {} entries", id_to_name.len());
270 }
271}
272
273pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) {
278 if !pack_dir.exists() {
279 return;
280 }
281
282 register_engine_constants(registry);
285
286 load_commands(registry, &pack_dir.join("command.pack"));
287
288 load_game_vars(registry, &pack_dir.join("varp.pack"), "varp");
289 load_game_vars(registry, &pack_dir.join("varn.pack"), "varn");
290 load_game_vars(registry, &pack_dir.join("vars.pack"), "vars");
291 load_game_vars(registry, &pack_dir.join("varbit.pack"), "varbit");
292
293 for (file, type_hint) in &[
308 ("area.pack", Type::Area),
311 ("bas.pack", Type::Bas),
312 ("billboard.pack", Type::Billboard),
313 ("particleeffector.pack", Type::ParticleEffector),
314 ("particleemitter.pack", Type::ParticleEmitter),
315 ("cursor.pack", Type::Cursor),
316 ("flo.pack", Type::Flo),
317 ("flu.pack", Type::Flu),
318 ("hitmark.pack", Type::Hitmark),
319 ("itemcode.pack", Type::ItemCode),
320 ("light.pack", Type::Light),
321 ("mel.pack", Type::MapElement),
322 ("msi.pack", Type::Msi),
323 ("quest.pack", Type::Quest),
324 ("varclan.pack", Type::VarClan),
325 ("varcon.pack", Type::VarCon),
326 ("config44.pack", Type::Config44),
327 ("varnbit.pack", Type::VarNBit),
328 ("varobj.pack", Type::VarObj),
329 ("category.pack", Type::Category),
330 ("idk.pack", Type::IdKit),
332 ("interface.pack", Type::Interface), ("overlayinterface.pack", Type::OverlayInterface),
334 ("struct.pack", Type::Struct),
336 ("dbrow.pack", Type::DbRow),
337 ("dbtable.pack", Type::DbTable),
338 ("dbcolumn.pack", Type::DbColumn),
339 ("param.pack", Type::Param),
340 ("model.pack", Type::Model),
342 ("sprites.pack", Type::Graphic),
343 ("texture.pack", Type::Texture),
344 ("wma.pack", Type::MapArea),
345 ("mapelement.pack", Type::MapElement),
346 ("fontmetrics.pack", Type::FontMetrics),
347 ("chatcat.pack", Type::ChatCat),
348 ("chatphrase.pack", Type::ChatPhrase),
349 ("mesanim.pack", Type::MesAnim),
350 ("jingle.pack", Type::Jingle),
351 ("midi.pack", Type::Midi),
352 ("synth.pack", Type::Synth),
353 ("vorbis.pack", Type::Vorbis),
354 ("spotanim.pack", Type::Spotanim),
355 ("seq.pack", Type::Seq),
356 ("locshape.pack", Type::LocShape),
358 ("hunt.pack", Type::Hunt),
359 ("npc_mode.pack", Type::NpcMode),
360 ("enum.pack", Type::Enum),
361 ("writeinv.pack", Type::WriteinvObj),
362 ("inv.pack", Type::Inv),
363 ("loc.pack", Type::Loc),
364 ("npc_stat.pack", Type::NpcStat),
365 ("stat.pack", Type::Stat),
366 ("npc.pack", Type::Npc),
367 ("obj.pack", Type::Obj),
368 ("controller.pack", Type::Controller),
369 ] {
370 load_entity_ids(registry, &pack_dir.join(file), *type_hint);
371 }
372
373 load_entity_ids_typed_only(registry, &pack_dir.join("obj.pack"), Type::NamedObj);
377
378 register_type_chars(registry);
380}
381
382pub fn load_script_ids(registry: &mut SymbolRegistry, pack_dir: &Path) {
387 load_script_pack(registry, &pack_dir.join("script.pack"));
389
390 load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
394}
395
396pub(crate) fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
400 let text = match fs::read_to_string(path) {
401 Ok(t) => t,
402 Err(_) => return,
403 };
404 for line in text.lines() {
405 let line = line.trim();
406 if line.is_empty() {
407 continue;
408 }
409 let (id_str, rest) = match line.split_once('=') {
410 Some(pair) => pair,
411 None => continue,
412 };
413 let id: i32 = match id_str.parse() {
414 Ok(v) => v,
415 Err(_) => continue,
416 };
417 let rest = rest.trim();
418 if !rest.starts_with('[') || !rest.ends_with(']') {
419 continue;
420 }
421 let inner = &rest[1..rest.len() - 1];
422 let (trigger, name) = match inner.split_once(',') {
423 Some(pair) => pair,
424 None => continue,
425 };
426 if name.is_empty() {
427 continue;
428 }
429 if trigger == "clientscript" {
430 registry.script_ids.insert(name.to_string(), id);
431 registry
432 .trigger_script_ids
433 .insert(format!("clientscript:{name}"), id);
434 } else {
435 registry.script_ids.entry(name.to_string()).or_insert(id);
436 registry
437 .trigger_script_ids
438 .entry(format!("clientscript:{name}"))
439 .or_insert(id);
440 }
441 }
442}
443
444pub(crate) fn load_clientscript_signatures(registry: &mut SymbolRegistry, dir: &Path) {
445 let Ok(files) = crate::sources::script_files(dir, "cs2") else {
446 return;
447 };
448 let mut sources = Vec::new();
449 for path in files
450 .into_iter()
451 .filter(|path| path.extension().is_some_and(|ext| ext == "cs2"))
452 {
453 let Ok(text) = fs::read_to_string(&path) else {
454 continue;
455 };
456 if let Ok(file) = clientscript::parse(&text, &path) {
457 sources.push(file);
458 }
459 }
460 hooks::register_callbacks(registry, sources.iter().flat_map(|file| &file.scripts));
461}
462
463fn load_commands(registry: &mut SymbolRegistry, path: &Path) {
470 let text = match fs::read_to_string(path) {
471 Ok(t) => t,
472 Err(_) => return,
473 };
474 for line in text.lines() {
475 let line = line.trim();
476 if line.is_empty() {
477 continue;
478 }
479 let (id_str, name) = match line.split_once('=') {
480 Some(pair) => pair,
481 None => continue,
482 };
483 let opcode: i32 = match id_str.parse() {
484 Ok(v) => v,
485 Err(_) => continue,
486 };
487 let name = name.trim().to_string();
488 if name.is_empty() {
489 continue;
490 }
491 registry.register_command(name, opcode, Vec::new(), Vec::new());
492 }
493}
494
495fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
496 let text = match fs::read_to_string(path) {
497 Ok(t) => t,
498 Err(_) => return,
499 };
500 for line in text.lines() {
501 let line = line.trim();
502 if line.is_empty() {
503 continue;
504 }
505 let (id_str, name) = match line.split_once('=') {
506 Some(pair) => pair,
507 None => continue,
508 };
509 let idx: i32 = match id_str.parse() {
510 Ok(v) => v,
511 Err(_) => continue,
512 };
513 let name = name.trim().to_string();
514 if name.is_empty() {
515 continue;
516 }
517 registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
521 registry.register_game_var(name, Type::Int, idx, category.to_string());
522 }
523}
524
525pub fn load_dbtable_configs(
538 registry: &mut SymbolRegistry,
539 files: &[std::path::PathBuf],
540 dbtable_ids: &std::collections::HashMap<String, u16>,
541) {
542 let mut dbtable_files: Vec<&std::path::PathBuf> = files
543 .iter()
544 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("dbtable"))
545 .collect();
546 dbtable_files.sort();
547
548 for path in dbtable_files {
549 let Ok(text) = fs::read_to_string(path) else {
550 continue;
551 };
552 let lines = strip_comments(&text);
553
554 let mut current_table: Option<String> = None;
555 let mut col_idx: u16 = 0;
556 for line in lines {
557 if line.starts_with('[') && line.ends_with(']') {
559 let name = line[1..line.len() - 1].trim().to_string();
560 current_table = Some(name);
561 col_idx = 0;
562 continue;
563 }
564 let Some(rest) = line.strip_prefix("column=") else {
566 continue;
567 };
568 let Some(table_name) = current_table.as_deref() else {
569 continue;
570 };
571 let Some(&table_id) = dbtable_ids.get(table_name) else {
572 continue;
573 };
574
575 let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
576 if parts.is_empty() {
577 continue;
578 }
579 let col_name = parts[0];
580 if col_name.is_empty() {
581 continue;
582 }
583
584 let types: Vec<Type> = parts[1..]
586 .iter()
587 .filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
588 .filter_map(|s| Type::from_name(s))
589 .collect();
590
591 let compound = format!("{}:{}", table_name, col_name);
592 let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
593
594 registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
596
597 if types.len() > 1 {
599 for (i, _) in types.iter().enumerate() {
600 let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
601 let slot_packed = packed | (((i as i32) + 1) & 0xF);
602 registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
603 }
604 }
605
606 if let Some(first_type) = types.first().copied() {
608 registry.dbcolumn_types.insert(compound, first_type);
609 }
610
611 col_idx += 1;
612 }
613 }
614}
615
616pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
618 let mut out = std::collections::HashMap::new();
619 let Ok(text) = fs::read_to_string(path) else {
620 return out;
621 };
622 for line in text.lines() {
623 let line = line.trim();
624 if line.is_empty() {
625 continue;
626 }
627 let Some((id_str, name)) = line.split_once('=') else {
628 continue;
629 };
630 let Ok(id) = id_str.parse::<u16>() else {
631 continue;
632 };
633 let name = name.trim();
634 if name.is_empty() {
635 continue;
636 }
637 out.insert(name.to_string(), id);
638 }
639 out
640}
641
642pub fn load_constant_files(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
647 let mut constant_files: Vec<&std::path::PathBuf> = files
648 .iter()
649 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("constant"))
650 .collect();
651 constant_files.sort();
652
653 for path in constant_files {
654 let text = match fs::read_to_string(path) {
655 Ok(t) => t,
656 Err(_) => continue,
657 };
658 let lines = strip_comments(&text);
659 for line in lines {
660 let eq_pos = match line.find('=') {
662 Some(i) => i,
663 None => continue,
664 };
665 let mut name = line[..eq_pos].trim();
666 let value = line[eq_pos + 1..].trim();
667
668 if let Some(stripped) = name.strip_prefix('^') {
670 name = stripped;
671 }
672
673 if name.is_empty() {
674 continue;
675 }
676
677 let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
679 &value[1..value.len() - 1]
680 } else {
681 value
682 };
683
684 register_constant_value(registry, name.to_string(), val_str);
685 }
686 }
687}
688
689fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
691 if let Ok(i) = val_str.parse::<i32>() {
692 registry.register_constant(name, Type::Int, Some(i), None);
693 } else if let Some(hex_str) = val_str
694 .strip_prefix("0x")
695 .or_else(|| val_str.strip_prefix("0X"))
696 {
697 let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
698 registry.register_constant(name, Type::Int, Some(v), None);
699 } else if let Some(packed) = parse_coord_string(val_str) {
700 registry.register_constant(name, Type::Coord, Some(packed), None);
701 } else {
702 registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
703 }
704}
705
706pub(crate) fn strip_comments(text: &str) -> impl Iterator<Item = std::borrow::Cow<'_, str>> {
709 let mut comments = Comments::default();
710 text.lines().filter_map(move |line| comments.line(line))
711}
712
713#[derive(Default)]
714pub(crate) struct Comments {
715 depth: usize,
716}
717
718impl Comments {
719 pub(crate) fn line<'a>(&mut self, raw: &'a str) -> Option<std::borrow::Cow<'a, str>> {
720 use std::borrow::Cow;
721 let line = raw.trim();
722 if self.depth == 0 && !line.contains("//") && !line.contains("/*") {
723 return (!line.is_empty()).then_some(Cow::Borrowed(line));
724 }
725 let bytes = line.as_bytes();
726 let mut output = Cow::Borrowed("");
727 let mut start = 0;
728 let mut i = 0;
729 let mut quoted = false;
730 let append = |output: &mut Cow<'_, str>, part: &str| {
731 output.to_mut().push_str(part);
732 };
733 while i < bytes.len() {
734 if self.depth > 0 {
735 if bytes[i..].starts_with(b"/*") {
736 self.depth += 1;
737 i += 2;
738 } else if bytes[i..].starts_with(b"*/") {
739 self.depth -= 1;
740 i += 2;
741 } else {
742 i += 1;
743 }
744 start = i;
745 } else if quoted {
746 if bytes[i] == b'\\' {
747 i = (i + 2).min(bytes.len());
748 } else {
749 if bytes[i] == b'"' {
750 quoted = false;
751 }
752 i += 1;
753 }
754 } else if bytes[i] == b'"' {
755 quoted = true;
756 i += 1;
757 } else if bytes[i..].starts_with(b"//") {
758 if output.is_empty() {
759 output = Cow::Borrowed(&line[start..i]);
760 } else {
761 append(&mut output, &line[start..i]);
762 }
763 start = bytes.len();
764 break;
765 } else if bytes[i..].starts_with(b"/*") {
766 if output.is_empty() {
767 output = Cow::Borrowed(&line[start..i]);
768 } else {
769 append(&mut output, &line[start..i]);
770 }
771 self.depth = 1;
772 i += 2;
773 start = i;
774 } else {
775 i += 1;
776 }
777 }
778 if self.depth == 0 && start < bytes.len() {
779 if output.is_empty() {
780 output = Cow::Borrowed(&line[start..]);
781 } else {
782 append(&mut output, &line[start..]);
783 }
784 }
785 match output {
786 Cow::Borrowed(value) => (!value.trim().is_empty()).then(|| Cow::Borrowed(value.trim())),
787 Cow::Owned(value) => {
788 (!value.trim().is_empty()).then(|| Cow::Owned(value.trim().to_owned()))
789 }
790 }
791 }
792}
793
794pub fn load_game_var_types(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
799 let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
801 for ext in &["varp", "varn", "vars", "varbit"] {
802 let max_id = registry
804 .game_vars
805 .values()
806 .filter_map(|sym| {
807 if let crate::symbol::SymbolKind::GameVar {
808 var_id, category, ..
809 } = &sym.kind
810 {
811 if category == *ext {
812 Some(*var_id)
813 } else {
814 None
815 }
816 } else {
817 None
818 }
819 })
820 .max()
821 .unwrap_or(-1);
822 next_auto_id.insert(ext.to_string(), max_id + 1);
823 }
824
825 for ext in &["varp", "varn", "vars", "varbit"] {
826 let ext_files = files
827 .iter()
828 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(*ext));
829 for path in ext_files {
830 let Ok(text) = fs::read_to_string(path) else {
831 continue;
832 };
833 let mut current_name: Option<String> = None;
834 for line in text.lines() {
835 let line = line.trim();
836 if line.is_empty() || line.starts_with("//") {
837 continue;
838 }
839 if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
840 let name = inner.trim().to_string();
841 if !registry.game_vars.contains_key(&name) {
843 let id = next_auto_id.get_mut(*ext).unwrap();
844 let auto_id = *id;
845 *id += 1;
846 registry.register_game_var(
847 name.clone(),
848 Type::Int,
849 auto_id,
850 ext.to_string(),
851 );
852 registry.register_game_var(
853 format!(".{}", name),
854 Type::Int,
855 auto_id,
856 ext.to_string(),
857 );
858 }
859 current_name = Some(name);
860 continue;
861 }
862 let Some(name) = current_name.as_ref() else {
863 continue;
864 };
865 if let Some((k, v)) = line.split_once('=')
866 && k.trim() == "type"
867 {
868 let type_name = v.trim();
869 if let Some(ty) = Type::from_name(type_name) {
870 if let Some(sym) = registry.game_vars.get_mut(name)
871 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
872 &mut sym.kind
873 {
874 *var_type = ty;
875 }
876 let dot_name = format!(".{}", name);
877 if let Some(sym) = registry.game_vars.get_mut(&dot_name)
878 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
879 &mut sym.kind
880 {
881 *var_type = ty;
882 }
883 }
884 }
885 }
886 }
887 }
888}
889
890pub(crate) fn entry_is_dir(entry: &fs::DirEntry, path: &Path) -> bool {
898 match entry.file_type() {
899 Ok(ft) if !ft.is_symlink() => ft.is_dir(),
900 _ => path.is_dir(),
901 }
902}
903
904pub fn collect_all_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
917 let entries = match fs::read_dir(dir) {
918 Ok(e) => e,
919 Err(_) => return,
920 };
921 for entry in entries.flatten() {
922 let path = entry.path();
923 if entry_is_dir(&entry, &path) {
924 collect_all_files(&path, out);
925 } else {
926 out.push(path);
927 }
928 }
929}
930
931fn parse_coord_string(s: &str) -> Option<i32> {
934 let parts: Vec<&str> = s.split('_').collect();
935 if parts.len() != 5 {
936 return None;
937 }
938 let y: i32 = parts[0].parse().ok()?;
939 let bx: i32 = parts[1].parse().ok()?;
940 let bz: i32 = parts[2].parse().ok()?;
941 let lx: i32 = parts[3].parse().ok()?;
942 let lz: i32 = parts[4].parse().ok()?;
943 let x = bx * 64 + lx;
944 let z = bz * 64 + lz;
945 Some((y << 28) | (x << 14) | z)
946}
947
948fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
962 let text = match fs::read_to_string(path) {
963 Ok(t) => t,
964 Err(_) => return,
965 };
966
967 let is_interface_pack = entity_type == Type::Interface;
968
969 let mut iface_id_to_name: std::collections::HashMap<i32, String> =
972 std::collections::HashMap::new();
973
974 for line in text.lines() {
975 let line = line.trim();
976 if line.is_empty() {
977 continue;
978 }
979 let (id_str, name) = match line.split_once('=') {
980 Some(pair) => pair,
981 None => continue,
982 };
983 let name = name.trim();
984 if name.is_empty() || name == "null" {
985 continue;
986 }
987
988 if is_interface_pack
989 && !id_str.contains(':')
990 && !name.contains(':')
991 && let Ok(id) = id_str.parse::<i32>()
992 {
993 registry.interface_ids.insert(name.to_string(), id);
994 iface_id_to_name.insert(id, name.to_string());
995 }
996 }
997
998 for line in text.lines() {
1000 let line = line.trim();
1001 if line.is_empty() {
1002 continue;
1003 }
1004 let (id_str, name) = match line.split_once('=') {
1005 Some(pair) => pair,
1006 None => continue,
1007 };
1008 let name = name.trim();
1009 if name.is_empty() || name == "null" {
1010 continue;
1011 }
1012
1013 let (idx, component_key, register_name): (i32, Option<String>, String) =
1016 if let Some((iface_str, comp_str)) = id_str.split_once(':') {
1017 let iface: i32 = match iface_str.parse() {
1019 Ok(v) => v,
1020 Err(_) => continue,
1021 };
1022 let comp: i32 = match comp_str.parse() {
1023 Ok(v) => v,
1024 Err(_) => continue,
1025 };
1026 let packed = (iface << 16) | comp;
1027 let key = iface_id_to_name
1028 .get(&iface)
1029 .map(|iface_name| format!("{}:{}", iface_name, name));
1030 (packed, key, name.to_string())
1031 } else if is_interface_pack {
1032 let flat_id: i32 = match id_str.parse() {
1033 Ok(v) => v,
1034 Err(_) => continue,
1035 };
1036 if name.contains(':') {
1037 (flat_id, Some(name.to_string()), name.to_string())
1039 } else {
1040 (flat_id, None, name.to_string())
1042 }
1043 } else {
1044 let id: i32 = match id_str.parse() {
1046 Ok(v) => v,
1047 Err(_) => continue,
1048 };
1049 (id, None, name.to_string())
1050 };
1051
1052 let actual_type = if is_interface_pack && component_key.is_some() {
1055 Type::Component
1056 } else {
1057 entity_type
1058 };
1059
1060 let normalized = register_name.to_lowercase().replace(' ', "_");
1063 registry.register_entity_id(normalized, actual_type, idx);
1064
1065 if is_interface_pack && let Some(key) = component_key {
1066 let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
1067 format!(
1068 "{}:{}",
1069 iface_part,
1070 crate::symbol::normalize_comp_name(comp_part)
1071 )
1072 } else {
1073 key
1074 };
1075 registry.components.insert(normalized_key, idx);
1076 }
1077 }
1078}
1079
1080fn load_entity_ids_typed_only(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
1084 let text = match fs::read_to_string(path) {
1085 Ok(t) => t,
1086 Err(_) => return,
1087 };
1088 for line in text.lines() {
1089 let line = line.trim();
1090 if line.is_empty() {
1091 continue;
1092 }
1093 let (id_str, name) = match line.split_once('=') {
1094 Some(pair) => pair,
1095 None => continue,
1096 };
1097 let name = name.trim();
1098 if name.is_empty() || name == "null" {
1099 continue;
1100 }
1101 let id: i32 = match id_str.parse() {
1102 Ok(v) => v,
1103 Err(_) => continue,
1104 };
1105 let normalized = name.to_lowercase().replace(' ', "_");
1106 registry.register_entity_id_typed_only(normalized, entity_type, id);
1107 }
1108}
1109
1110fn register_type_chars(registry: &mut SymbolRegistry) {
1114 let type_chars: &[(&str, i32)] = &[
1115 ("int", b'i' as i32), ("string", b's' as i32), ("boolean", b'1' as i32), ("bool", b'1' as i32),
1119 ("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),
1126 ("npcuid", b'u' as i32), ("npc_uid", b'u' as i32),
1128 ("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),
1135 ("overlayinterface", b'a' as i32),
1136 ("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),
1142 ("category", b'y' as i32), ("varp", b'V' as i32), ("npc_stat", 0xFE), ("npcstat", 0xFE),
1146 ("idkit", b'K' as i32), ("idk", b'K' as i32),
1148 ];
1149 for (name, val) in type_chars {
1150 registry.type_chars.insert(name.to_string(), *val);
1151 }
1152 for ch in Type::CHARS.chars() {
1153 if let Some(ty) = Type::from_char(ch) {
1154 registry
1155 .type_chars
1156 .entry(ty.name().to_string())
1157 .or_insert(ch as i32);
1158 }
1159 }
1160}
1161
1162fn register_engine_constants(registry: &mut SymbolRegistry) {
1166 let npc_modes: &[(&str, i32)] = &[
1168 ("null", -1),
1169 ("none", 0),
1170 ("wander", 1),
1171 ("patrol", 2),
1172 ("playerescape", 3),
1173 ("playerfollow", 4),
1174 ("playerface", 5),
1175 ("playerfaceclose", 6),
1176 ("opplayer1", 7),
1177 ("opplayer2", 8),
1178 ("opplayer3", 9),
1179 ("opplayer4", 10),
1180 ("opplayer5", 11),
1181 ("applayer1", 12),
1182 ("applayer2", 13),
1183 ("applayer3", 14),
1184 ("applayer4", 15),
1185 ("applayer5", 16),
1186 ("oploc1", 17),
1187 ("oploc2", 18),
1188 ("oploc3", 19),
1189 ("oploc4", 20),
1190 ("oploc5", 21),
1191 ("aploc1", 22),
1192 ("aploc2", 23),
1193 ("aploc3", 24),
1194 ("aploc4", 25),
1195 ("aploc5", 26),
1196 ("opobj1", 27),
1197 ("opobj2", 28),
1198 ("opobj3", 29),
1199 ("opobj4", 30),
1200 ("opobj5", 31),
1201 ("apobj1", 32),
1202 ("apobj2", 33),
1203 ("apobj3", 34),
1204 ("apobj4", 35),
1205 ("apobj5", 36),
1206 ("opnpc1", 37),
1207 ("opnpc2", 38),
1208 ("opnpc3", 39),
1209 ("opnpc4", 40),
1210 ("opnpc5", 41),
1211 ("apnpc1", 42),
1212 ("apnpc2", 43),
1213 ("apnpc3", 44),
1214 ("apnpc4", 45),
1215 ("apnpc5", 46),
1216 ("queue1", 47),
1217 ("queue2", 48),
1218 ("queue3", 49),
1219 ("queue4", 50),
1220 ("queue5", 51),
1221 ("queue6", 52),
1222 ("queue7", 53),
1223 ("queue8", 54),
1224 ("queue9", 55),
1225 ("queue10", 56),
1226 ("queue11", 57),
1227 ("queue12", 58),
1228 ("queue13", 59),
1229 ("queue14", 60),
1230 ("queue15", 61),
1231 ("queue16", 62),
1232 ("queue17", 63),
1233 ("queue18", 64),
1234 ("queue19", 65),
1235 ("queue20", 66),
1236 ];
1237 fn is_trigger_collision(name: &str) -> bool {
1248 matches!(
1249 name,
1250 "oploc1"
1251 | "oploc2"
1252 | "oploc3"
1253 | "oploc4"
1254 | "oploc5"
1255 | "aploc1"
1256 | "aploc2"
1257 | "aploc3"
1258 | "aploc4"
1259 | "aploc5"
1260 | "opnpc1"
1261 | "opnpc2"
1262 | "opnpc3"
1263 | "opnpc4"
1264 | "opnpc5"
1265 | "apnpc1"
1266 | "apnpc2"
1267 | "apnpc3"
1268 | "apnpc4"
1269 | "apnpc5"
1270 | "opobj1"
1271 | "opobj2"
1272 | "opobj3"
1273 | "opobj4"
1274 | "opobj5"
1275 | "apobj1"
1276 | "apobj2"
1277 | "apobj3"
1278 | "apobj4"
1279 | "apobj5"
1280 | "opplayer1"
1281 | "opplayer2"
1282 | "opplayer3"
1283 | "opplayer4"
1284 | "opplayer5"
1285 | "applayer1"
1286 | "applayer2"
1287 | "applayer3"
1288 | "applayer4"
1289 | "applayer5"
1290 | "queue1"
1291 | "queue2"
1292 | "queue3"
1293 | "queue4"
1294 | "queue5"
1295 | "queue6"
1296 | "queue7"
1297 | "queue8"
1298 | "queue9"
1299 | "queue10"
1300 | "queue11"
1301 | "queue12"
1302 | "queue13"
1303 | "queue14"
1304 | "queue15"
1305 | "queue16"
1306 | "queue17"
1307 | "queue18"
1308 | "queue19"
1309 | "queue20"
1310 )
1311 }
1312 for &(name, id) in npc_modes {
1313 if is_trigger_collision(name) {
1314 registry.register_entity_id_typed_only(name.to_string(), Type::NpcMode, id);
1315 } else {
1316 registry.register_entity_id(name.to_string(), Type::NpcMode, id);
1317 }
1318 }
1319
1320 let npc_stats: &[(&str, i32)] = &[
1322 ("attack", 0),
1323 ("defence", 1),
1324 ("strength", 2),
1325 ("hitpoints", 3),
1326 ("ranged", 4),
1327 ("magic", 5),
1328 ];
1329 for &(name, id) in npc_stats {
1330 registry.register_entity_id(name.to_string(), Type::NpcStat, id);
1331 }
1332
1333 let stats: &[(&str, i32)] = &[
1336 ("attack", 0),
1337 ("defence", 1),
1338 ("strength", 2),
1339 ("hitpoints", 3),
1340 ("ranged", 4),
1341 ("prayer", 5),
1342 ("magic", 6),
1343 ("cooking", 7),
1344 ("woodcutting", 8),
1345 ("fletching", 9),
1346 ("fishing", 10),
1347 ("firemaking", 11),
1348 ("crafting", 12),
1349 ("smithing", 13),
1350 ("mining", 14),
1351 ("herblore", 15),
1352 ("agility", 16),
1353 ("thieving", 17),
1354 ("slayer", 18),
1355 ("stat18", 18),
1356 ("farming", 19),
1357 ("stat19", 19),
1358 ("runecraft", 20),
1359 ("hunter", 21),
1360 ("construction", 22),
1361 ("summoning", 23),
1362 ("dungeoneering", 24),
1363 ];
1364 for &(name, id) in stats {
1365 registry.register_entity_id(name.to_string(), Type::Stat, id);
1366 }
1367
1368 let fontmetrics: &[(&str, i32)] = &[
1370 ("p11", 0),
1371 ("p12", 1),
1372 ("b12", 2),
1373 ("q8", 3),
1374 ("p11_full", 0),
1375 ("p12_full", 1),
1376 ("b12_full", 2),
1377 ("q8_full", 3),
1378 ];
1379 for &(name, id) in fontmetrics {
1380 registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
1381 }
1382
1383 let locshapes: &[(&str, i32)] = &[
1385 ("wall_straight", 0),
1386 ("wall_diagonalcorner", 1),
1387 ("wall_l", 2),
1388 ("wall_squarecorner", 3),
1389 ("walldecor_straight_nooffset", 4),
1390 ("walldecor_straight_offset", 5),
1391 ("walldecor_diagonal_offset", 6),
1392 ("walldecor_diagonal_nooffset", 7),
1393 ("walldecor_diagonal_both", 8),
1394 ("wall_diagonal", 9),
1395 ("centrepiece_straight", 10),
1396 ("centrepiece_diagonal", 11),
1397 ("roof_straight", 12),
1398 ("roof_diagonal_with_roofedge", 13),
1399 ("roof_diagonal", 14),
1400 ("roof_l_concave", 15),
1401 ("roof_l_convex", 16),
1402 ("roof_flat", 17),
1403 ("roofedge_straight", 18),
1404 ("roofedge_diagonalcorner", 19),
1405 ("roofedge_l", 20),
1406 ("roofedge_squarecorner", 21),
1407 ("grounddecor", 22),
1408 ];
1409 for &(name, id) in locshapes {
1410 registry.register_entity_id(name.to_string(), Type::LocShape, id);
1411 }
1412}
1413
1414#[cfg(test)]
1415mod tests {
1416 use super::*;
1417 use crate::symbol::SymbolRegistry;
1418 use crate::types::Type;
1419 use std::io::Write;
1420 use std::path::PathBuf;
1421
1422 fn write_temp_pack(name: &str, content: &str) -> PathBuf {
1423 let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1424 .join("target")
1425 .join("test-symloader");
1426 fs::create_dir_all(&dir).unwrap();
1427 let path = dir.join(name);
1428 let mut f = fs::File::create(&path).unwrap();
1429 f.write_all(content.as_bytes()).unwrap();
1430 path
1431 }
1432
1433 #[test]
1437 fn load_647_style_registers_components() {
1438 let pack = write_temp_pack(
1439 "interface_647.pack",
1440 "\
1441228=multi2\n\
1442228:0=com0\n\
1443228:1=com1\n\
1444228:2=com2\n\
1445228:3=com3\n\
1446228:6=thin_swords\n\
1447228:9=wide_swords\n",
1448 );
1449 let mut r = SymbolRegistry::new();
1450 load_entity_ids(&mut r, &pack, Type::Interface);
1451
1452 assert_eq!(r.interface_ids.get("multi2"), Some(&228));
1454
1455 assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
1457 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1458 assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
1459
1460 assert_eq!(
1462 r.lookup_component("multi2", "thin_swords"),
1463 Some((228 << 16) | 6)
1464 );
1465 assert_eq!(
1466 r.lookup_component("multi2", "wide_swords"),
1467 Some((228 << 16) | 9)
1468 );
1469 }
1470
1471 #[test]
1472 fn load_647_style_resolves_225_references() {
1473 let pack = write_temp_pack(
1474 "interface_647_cross.pack",
1475 "\
1476228=multi2\n\
1477228:0=com0\n\
1478228:1=com1\n\
1479228:2=com2\n",
1480 );
1481 let mut r = SymbolRegistry::new();
1482 load_entity_ids(&mut r, &pack, Type::Interface);
1483
1484 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1486 assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
1487 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1488 }
1489
1490 #[test]
1494 fn load_225_style_registers_components() {
1495 let pack = write_temp_pack(
1496 "interface_225.pack",
1497 "\
14982459=multi2\n\
14992460=multi2:com_0\n\
15002461=multi2:com_1\n\
15012462=multi2:com_2\n\
15022463=multi2:com_4\n\
15032464=multi2:com_5\n",
1504 );
1505 let mut r = SymbolRegistry::new();
1506 load_entity_ids(&mut r, &pack, Type::Interface);
1507
1508 assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
1510
1511 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
1513 assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
1514 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1515 }
1516
1517 #[test]
1518 fn load_225_style_resolves_647_references() {
1519 let pack = write_temp_pack(
1520 "interface_225_cross.pack",
1521 "\
15222459=multi2\n\
15232460=multi2:com_0\n\
15242461=multi2:com_1\n\
15252462=multi2:com_2\n",
1526 );
1527 let mut r = SymbolRegistry::new();
1528 load_entity_ids(&mut r, &pack, Type::Interface);
1529
1530 assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
1532 assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
1533 assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
1534 }
1535
1536 #[test]
1539 fn components_register_as_component_type() {
1540 let pack = write_temp_pack(
1541 "interface_types.pack",
1542 "\
1543228=multi2\n\
1544228:0=com0\n",
1545 );
1546 let mut r = SymbolRegistry::new();
1547 load_entity_ids(&mut r, &pack, Type::Interface);
1548
1549 assert!(
1551 r.lookup_entity_id_typed("multi2", Type::Interface)
1552 .is_some()
1553 );
1554 assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
1555 assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
1556 }
1557}