1use std::fs;
7use std::path::Path;
8
9use tracing::{info, warn};
10
11use crate::symbol::{SymbolKind, SymbolRegistry};
12use crate::types::Type;
13
14pub fn load_engine_command_params(registry: &mut SymbolRegistry, engine_rs2: &Path) {
19 let text = match fs::read_to_string(engine_rs2) {
20 Ok(t) => t,
21 Err(_) => return,
22 };
23 for line in text.lines() {
24 let line = line.trim();
25 if !line.starts_with("[command,") {
27 continue;
28 }
29 let rest = &line["[command,".len()..];
31 let name_end = match rest.find(']') {
32 Some(i) => i,
33 None => continue,
34 };
35 let name = rest[..name_end].trim().to_string();
36
37 let after_bracket = &rest[name_end + 1..];
39 let params_start = match after_bracket.find('(') {
40 Some(i) => i + 1,
41 None => {
42 registry.command_param_types.insert(name, Vec::new());
44 continue;
45 }
46 };
47 let params_end = match after_bracket[params_start..].find(')') {
48 Some(i) => params_start + i,
49 None => continue,
50 };
51 let params_str = &after_bracket[params_start..params_end];
52
53 let mut param_types: Vec<Type> = Vec::new();
54 for param in params_str.split(',') {
55 let param = param.trim();
56 if param.is_empty() {
57 continue;
58 }
59 let type_name = param.split_whitespace().next().unwrap_or(param);
61 if let Some(t) = Type::from_name(type_name) {
62 param_types.push(t);
63 } else {
64 param_types.push(Type::Int);
66 }
67 }
68 registry
69 .command_param_types
70 .insert(name.clone(), param_types.clone());
71
72 if let Some(sym) = registry.commands.get_mut(&name)
73 && let SymbolKind::Command {
74 param_types: ref mut pt,
75 ..
76 } = sym.kind
77 {
78 *pt = param_types;
79 }
80
81 let after_params = &after_bracket[params_end + 1..];
83 if let Some(ret_start) = after_params.find('(')
84 && let Some(ret_end) = after_params[ret_start + 1..].find(')')
85 {
86 let ret_str = &after_params[ret_start + 1..ret_start + 1 + ret_end];
87 let mut return_types: Vec<Type> = Vec::new();
88 for ret in ret_str.split(',') {
89 let ret = ret.trim();
90 if ret.is_empty() {
91 continue;
92 }
93 if let Some(t) = Type::from_name(ret) {
94 return_types.push(t);
95 }
96 }
97 if !return_types.is_empty() {
98 if let Some(sym) = registry.commands.get_mut(&name)
100 && let SymbolKind::Command {
101 return_types: ref mut rt,
102 ..
103 } = sym.kind
104 {
105 *rt = return_types;
106 }
107 }
108 }
109 }
110}
111
112pub fn patch_command_return_types(registry: &mut SymbolRegistry) {
116 let patches: &[(&str, Vec<Type>)] = &[
117 ("db_find_with_count", vec![Type::Int]),
118 ("db_find_refine_with_count", vec![Type::Int]),
119 ("db_listall_with_count", vec![Type::Int]),
120 ];
121 for (name, ret_types) in patches {
122 if let Some(sym) = registry.commands.get_mut(*name)
123 && let SymbolKind::Command { return_types, .. } = &mut sym.kind
124 && return_types.is_empty()
125 {
126 *return_types = ret_types.clone();
127 }
128 }
129}
130
131fn load_script_pack(registry: &mut SymbolRegistry, path: &Path) {
134 let text = match fs::read_to_string(path) {
135 Ok(t) => t,
136 Err(_) => return,
137 };
138 for line in text.lines() {
139 let line = line.trim();
140 if line.is_empty() {
141 continue;
142 }
143 let (id_str, rest) = match line.split_once('=') {
144 Some(pair) => pair,
145 None => continue,
146 };
147 let id: i32 = match id_str.parse() {
148 Ok(v) => v,
149 Err(_) => continue,
150 };
151 let rest = rest.trim();
152 if !rest.starts_with('[') || !rest.ends_with(']') {
154 continue;
155 }
156 let inner = &rest[1..rest.len() - 1];
157 let comma = match inner.find(',') {
158 Some(i) => i,
159 None => continue,
160 };
161 let trigger = &inner[..comma];
162 let name = &inner[comma + 1..];
163 if trigger.is_empty() || name.is_empty() {
164 continue;
165 }
166 let key = format!("{}:{}", trigger, name);
167 registry.preloaded_script_ids.insert(key, id);
168 }
169}
170
171pub fn generate_script_pack(scripts_dir: &Path, pack_dir: &Path) {
174 use std::collections::BTreeMap;
175
176 let pack_path = pack_dir.join("script.pack");
177
178 let mut id_to_name: BTreeMap<i32, String> = BTreeMap::new();
180 let mut name_to_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
181 let mut max_id: i32 = 0;
182
183 if let Ok(text) = fs::read_to_string(&pack_path) {
184 for line in text.lines() {
185 let line = line.trim();
186 if line.is_empty() {
187 continue;
188 }
189 if let Some((id_str, name)) = line.split_once('=')
190 && let Ok(id) = id_str.parse::<i32>()
191 {
192 let name = name.trim().to_string();
193 name_to_id.insert(name.clone(), id);
194 id_to_name.insert(id, name);
195 if id >= max_id {
196 max_id = id + 1;
197 }
198 }
199 }
200 }
201
202 let mut rs2_files = Vec::new();
204 collect_rs2_files(scripts_dir, &mut rs2_files);
205 rs2_files.sort();
206
207 for path in &rs2_files {
208 if path.file_name().and_then(|n| n.to_str()) == Some("engine.rs2") {
210 continue;
211 }
212 let Ok(text) = fs::read_to_string(path) else {
213 continue;
214 };
215 for line in text.lines() {
216 let line = line.split("//").next().unwrap_or("").trim();
217 if !line.starts_with('[') {
218 continue;
219 }
220 let bracket_end = match line.find(']') {
221 Some(i) => i,
222 None => continue,
223 };
224 let full_name = &line[..bracket_end + 1]; let inner = &line[1..bracket_end];
226 let comma = match inner.find(',') {
227 Some(i) => i,
228 None => continue,
229 };
230 let trigger = &inner[..comma];
231 if trigger == "command" {
233 continue;
234 }
235
236 if !name_to_id.contains_key(full_name) {
237 name_to_id.insert(full_name.to_string(), max_id);
238 id_to_name.insert(max_id, full_name.to_string());
239 max_id += 1;
240 }
241 }
242 }
243
244 if let Err(e) = std::fs::create_dir_all(pack_dir) {
246 warn!(target: "runec", "Failed to create pack dir: {}", e);
247 return;
248 }
249 let mut out = String::new();
250 for (id, name) in &id_to_name {
251 out.push_str(&format!("{}={}\n", id, name));
252 }
253 if let Err(e) = fs::write(&pack_path, &out) {
254 warn!(target: "runec", "Failed to write script.pack: {}", e);
255 } else {
256 info!(target: "runec", "script.pack: {} entries", id_to_name.len());
257 }
258}
259
260fn collect_rs2_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
261 let Ok(entries) = fs::read_dir(dir) else {
262 return;
263 };
264 let mut sorted: Vec<std::path::PathBuf> = entries.flatten().map(|e| e.path()).collect();
265 sorted.sort();
266 for path in sorted {
267 if path.is_dir() {
268 collect_rs2_files(&path, out);
269 } else if path.extension().and_then(|e| e.to_str()) == Some("rs2") {
270 out.push(path);
271 }
272 }
273}
274
275pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) {
280 if !pack_dir.exists() {
281 return;
282 }
283
284 register_engine_constants(registry);
287
288 load_commands(registry, &pack_dir.join("command.pack"));
289
290 load_game_vars(registry, &pack_dir.join("varp.pack"), "varp");
291 load_game_vars(registry, &pack_dir.join("varn.pack"), "varn");
292 load_game_vars(registry, &pack_dir.join("vars.pack"), "vars");
293 load_game_vars(registry, &pack_dir.join("varbit.pack"), "varbit");
294
295 for (file, type_hint) in &[
310 ("category.pack", Type::Category),
312 ("idk.pack", Type::IdKit),
314 ("interface.pack", Type::Interface), ("overlayinterface.pack", Type::OverlayInterface),
316 ("struct.pack", Type::Struct),
318 ("dbrow.pack", Type::DbRow),
319 ("dbtable.pack", Type::DbTable),
320 ("dbcolumn.pack", Type::DbColumn),
321 ("param.pack", Type::Param),
322 ("model.pack", Type::Model),
324 ("fontmetrics.pack", Type::FontMetrics),
325 ("mesanim.pack", Type::MesAnim),
326 ("jingle.pack", Type::Jingle),
327 ("midi.pack", Type::Midi),
328 ("synth.pack", Type::Synth),
329 ("spotanim.pack", Type::Spotanim),
330 ("seq.pack", Type::Seq),
331 ("locshape.pack", Type::LocShape),
333 ("hunt.pack", Type::Hunt),
334 ("npc_mode.pack", Type::NpcMode),
335 ("enum.pack", Type::Enum),
336 ("writeinv.pack", Type::WriteinvObj),
337 ("inv.pack", Type::Inv),
338 ("loc.pack", Type::Loc),
339 ("npc_stat.pack", Type::NpcStat),
340 ("stat.pack", Type::Stat),
341 ("npc.pack", Type::Npc),
342 ("obj.pack", Type::Obj),
343 ("controller.pack", Type::Controller),
344 ] {
345 load_entity_ids(registry, &pack_dir.join(file), *type_hint);
346 }
347
348 load_entity_ids_typed_only(registry, &pack_dir.join("obj.pack"), Type::NamedObj);
352
353 register_type_chars(registry);
355
356 load_script_pack(registry, &pack_dir.join("script.pack"));
358
359 load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
363}
364
365fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
369 let text = match fs::read_to_string(path) {
370 Ok(t) => t,
371 Err(_) => return,
372 };
373 for line in text.lines() {
374 let line = line.trim();
375 if line.is_empty() {
376 continue;
377 }
378 let (id_str, rest) = match line.split_once('=') {
379 Some(pair) => pair,
380 None => continue,
381 };
382 let id: i32 = match id_str.parse() {
383 Ok(v) => v,
384 Err(_) => continue,
385 };
386 let rest = rest.trim();
387 if !rest.starts_with('[') || !rest.ends_with(']') {
388 continue;
389 }
390 let inner = &rest[1..rest.len() - 1];
391 let (_trigger, name) = match inner.split_once(',') {
392 Some(pair) => pair,
393 None => continue,
394 };
395 if name.is_empty() {
396 continue;
397 }
398 registry.script_ids.insert(name.to_string(), id);
399 registry
400 .trigger_script_ids
401 .insert(format!("clientscript:{}", name), id);
402 }
403}
404
405fn load_commands(registry: &mut SymbolRegistry, path: &Path) {
412 let text = match fs::read_to_string(path) {
413 Ok(t) => t,
414 Err(_) => return,
415 };
416 for line in text.lines() {
417 let line = line.trim();
418 if line.is_empty() {
419 continue;
420 }
421 let (id_str, name) = match line.split_once('=') {
422 Some(pair) => pair,
423 None => continue,
424 };
425 let opcode: i32 = match id_str.parse() {
426 Ok(v) => v,
427 Err(_) => continue,
428 };
429 let name = name.trim().to_string();
430 if name.is_empty() {
431 continue;
432 }
433 registry.register_command(name, opcode, Vec::new(), Vec::new());
434 }
435}
436
437fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
438 let text = match fs::read_to_string(path) {
439 Ok(t) => t,
440 Err(_) => return,
441 };
442 for line in text.lines() {
443 let line = line.trim();
444 if line.is_empty() {
445 continue;
446 }
447 let (id_str, name) = match line.split_once('=') {
448 Some(pair) => pair,
449 None => continue,
450 };
451 let idx: i32 = match id_str.parse() {
452 Ok(v) => v,
453 Err(_) => continue,
454 };
455 let name = name.trim().to_string();
456 if name.is_empty() {
457 continue;
458 }
459 registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
463 registry.register_game_var(name, Type::Int, idx, category.to_string());
464 }
465}
466
467pub fn load_dbtable_configs(
480 registry: &mut SymbolRegistry,
481 scripts_dir: &Path,
482 dbtable_ids: &std::collections::HashMap<String, u16>,
483) {
484 let mut dbtable_files: Vec<std::path::PathBuf> = Vec::new();
485 collect_files_by_ext(scripts_dir, "dbtable", &mut dbtable_files);
486 dbtable_files.sort();
487
488 for path in &dbtable_files {
489 let Ok(text) = fs::read_to_string(path) else {
490 continue;
491 };
492 let lines = strip_comments(&text);
493
494 let mut current_table: Option<String> = None;
495 let mut col_idx: u16 = 0;
496 for line in &lines {
497 if line.starts_with('[') && line.ends_with(']') {
499 let name = line[1..line.len() - 1].trim().to_string();
500 current_table = Some(name);
501 col_idx = 0;
502 continue;
503 }
504 let Some(rest) = line.strip_prefix("column=") else {
506 continue;
507 };
508 let Some(table_name) = current_table.as_deref() else {
509 continue;
510 };
511 let Some(&table_id) = dbtable_ids.get(table_name) else {
512 continue;
513 };
514
515 let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
516 if parts.is_empty() {
517 continue;
518 }
519 let col_name = parts[0];
520 if col_name.is_empty() {
521 continue;
522 }
523
524 let types: Vec<Type> = parts[1..]
526 .iter()
527 .filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
528 .filter_map(|s| Type::from_name(s))
529 .collect();
530
531 let compound = format!("{}:{}", table_name, col_name);
532 let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
533
534 registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
536
537 if types.len() > 1 {
539 for (i, _) in types.iter().enumerate() {
540 let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
541 let slot_packed = packed | (((i as i32) + 1) & 0xF);
542 registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
543 }
544 }
545
546 if let Some(first_type) = types.first().copied() {
548 registry.dbcolumn_types.insert(compound, first_type);
549 }
550
551 col_idx += 1;
552 }
553 }
554}
555
556pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
558 let mut out = std::collections::HashMap::new();
559 let Ok(text) = fs::read_to_string(path) else {
560 return out;
561 };
562 for line in text.lines() {
563 let line = line.trim();
564 if line.is_empty() {
565 continue;
566 }
567 let Some((id_str, name)) = line.split_once('=') else {
568 continue;
569 };
570 let Ok(id) = id_str.parse::<u16>() else {
571 continue;
572 };
573 let name = name.trim();
574 if name.is_empty() {
575 continue;
576 }
577 out.insert(name.to_string(), id);
578 }
579 out
580}
581
582pub fn load_constant_files(registry: &mut SymbolRegistry, scripts_dir: &Path) {
587 let mut constant_files: Vec<std::path::PathBuf> = Vec::new();
588 collect_files_by_ext(scripts_dir, "constant", &mut constant_files);
589 constant_files.sort();
590
591 for path in &constant_files {
592 let text = match fs::read_to_string(path) {
593 Ok(t) => t,
594 Err(_) => continue,
595 };
596 let lines = strip_comments(&text);
597 for line in &lines {
598 let eq_pos = match line.find('=') {
600 Some(i) => i,
601 None => continue,
602 };
603 let mut name = line[..eq_pos].trim();
604 let value = line[eq_pos + 1..].trim();
605
606 if let Some(stripped) = name.strip_prefix('^') {
608 name = stripped;
609 }
610
611 if name.is_empty() {
612 continue;
613 }
614
615 let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
617 &value[1..value.len() - 1]
618 } else {
619 value
620 };
621
622 register_constant_value(registry, name.to_string(), val_str);
623 }
624 }
625}
626
627fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
629 if let Ok(i) = val_str.parse::<i32>() {
630 registry.register_constant(name, Type::Int, Some(i), None);
631 } else if let Some(hex_str) = val_str
632 .strip_prefix("0x")
633 .or_else(|| val_str.strip_prefix("0X"))
634 {
635 let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
636 registry.register_constant(name, Type::Int, Some(v), None);
637 } else if let Some(packed) = parse_coord_string(val_str) {
638 registry.register_constant(name, Type::Coord, Some(packed), None);
639 } else {
640 registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
641 }
642}
643
644fn strip_comments(text: &str) -> Vec<String> {
647 let mut result = Vec::new();
648 let mut multi_depth: usize = 0;
649
650 for line in text.lines() {
651 let mut line = line.trim().to_string();
652
653 if multi_depth > 0 {
655 while let Some(start) = line.find("/*") {
656 line = line[start + 2..].trim_start().to_string();
657 multi_depth += 1;
658 }
659 while let Some(end) = line.find("*/") {
660 line = line[end + 2..].trim_start().to_string();
661 multi_depth -= 1;
662 if multi_depth == 0 {
663 break;
664 }
665 }
666 if multi_depth > 0 {
667 continue;
668 }
669 }
670
671 if line.is_empty() {
672 continue;
673 }
674
675 if let Some(idx) = line.find("//") {
677 line = line[..idx].trim_end().to_string();
678 if line.is_empty() {
679 continue;
680 }
681 }
682
683 if let Some(start) = line.find("/*") {
685 if let Some(end) = line.find("*/") {
686 line = format!("{}{}", &line[..start], &line[end + 2..]);
687 } else {
688 line = line[..start].to_string();
689 multi_depth += 1;
690 }
691 if line.is_empty() {
692 continue;
693 }
694 }
695
696 result.push(line);
697 }
698
699 result
700}
701
702pub fn load_game_var_types(registry: &mut SymbolRegistry, scripts_dir: &Path) {
707 let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
709 for ext in &["varp", "varn", "vars", "varbit"] {
710 let max_id = registry
712 .game_vars
713 .values()
714 .filter_map(|sym| {
715 if let crate::symbol::SymbolKind::GameVar {
716 var_id, category, ..
717 } = &sym.kind
718 {
719 if category == *ext {
720 Some(*var_id)
721 } else {
722 None
723 }
724 } else {
725 None
726 }
727 })
728 .max()
729 .unwrap_or(-1);
730 next_auto_id.insert(ext.to_string(), max_id + 1);
731 }
732
733 for ext in &["varp", "varn", "vars", "varbit"] {
734 let mut files = Vec::new();
735 collect_files_by_ext(scripts_dir, ext, &mut files);
736 for path in &files {
737 let Ok(text) = fs::read_to_string(path) else {
738 continue;
739 };
740 let mut current_name: Option<String> = None;
741 for line in text.lines() {
742 let line = line.trim();
743 if line.is_empty() || line.starts_with("//") {
744 continue;
745 }
746 if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
747 let name = inner.trim().to_string();
748 if !registry.game_vars.contains_key(&name) {
750 let id = next_auto_id.get_mut(*ext).unwrap();
751 let auto_id = *id;
752 *id += 1;
753 registry.register_game_var(
754 name.clone(),
755 Type::Int,
756 auto_id,
757 ext.to_string(),
758 );
759 registry.register_game_var(
760 format!(".{}", name),
761 Type::Int,
762 auto_id,
763 ext.to_string(),
764 );
765 }
766 current_name = Some(name);
767 continue;
768 }
769 let Some(name) = current_name.as_ref() else {
770 continue;
771 };
772 if let Some((k, v)) = line.split_once('=')
773 && k.trim() == "type"
774 {
775 let type_name = v.trim();
776 if let Some(ty) = Type::from_name(type_name) {
777 if let Some(sym) = registry.game_vars.get_mut(name)
778 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
779 &mut sym.kind
780 {
781 *var_type = ty;
782 }
783 let dot_name = format!(".{}", name);
784 if let Some(sym) = registry.game_vars.get_mut(&dot_name)
785 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
786 &mut sym.kind
787 {
788 *var_type = ty;
789 }
790 }
791 }
792 }
793 }
794 }
795}
796
797fn collect_files_by_ext(dir: &Path, ext: &str, out: &mut Vec<std::path::PathBuf>) {
799 let entries = match fs::read_dir(dir) {
800 Ok(e) => e,
801 Err(_) => return,
802 };
803 for entry in entries.flatten() {
804 let path = entry.path();
805 if path.is_dir() {
806 collect_files_by_ext(&path, ext, out);
807 } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
808 out.push(path);
809 }
810 }
811}
812
813fn parse_coord_string(s: &str) -> Option<i32> {
816 let parts: Vec<&str> = s.split('_').collect();
817 if parts.len() != 5 {
818 return None;
819 }
820 let y: i32 = parts[0].parse().ok()?;
821 let bx: i32 = parts[1].parse().ok()?;
822 let bz: i32 = parts[2].parse().ok()?;
823 let lx: i32 = parts[3].parse().ok()?;
824 let lz: i32 = parts[4].parse().ok()?;
825 let x = bx * 64 + lx;
826 let z = bz * 64 + lz;
827 Some((y << 28) | (x << 14) | z)
828}
829
830fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
844 let text = match fs::read_to_string(path) {
845 Ok(t) => t,
846 Err(_) => return,
847 };
848
849 let is_interface_pack = entity_type == Type::Interface;
850
851 let mut iface_id_to_name: std::collections::HashMap<i32, String> =
854 std::collections::HashMap::new();
855
856 for line in text.lines() {
857 let line = line.trim();
858 if line.is_empty() {
859 continue;
860 }
861 let (id_str, name) = match line.split_once('=') {
862 Some(pair) => pair,
863 None => continue,
864 };
865 let name = name.trim();
866 if name.is_empty() || name == "null" {
867 continue;
868 }
869
870 if is_interface_pack
871 && !id_str.contains(':')
872 && !name.contains(':')
873 && let Ok(id) = id_str.parse::<i32>()
874 {
875 registry.interface_ids.insert(name.to_string(), id);
876 iface_id_to_name.insert(id, name.to_string());
877 }
878 }
879
880 for line in text.lines() {
882 let line = line.trim();
883 if line.is_empty() {
884 continue;
885 }
886 let (id_str, name) = match line.split_once('=') {
887 Some(pair) => pair,
888 None => continue,
889 };
890 let name = name.trim();
891 if name.is_empty() || name == "null" {
892 continue;
893 }
894
895 let (idx, component_key, register_name): (i32, Option<String>, String) =
898 if let Some((iface_str, comp_str)) = id_str.split_once(':') {
899 let iface: i32 = match iface_str.parse() {
901 Ok(v) => v,
902 Err(_) => continue,
903 };
904 let comp: i32 = match comp_str.parse() {
905 Ok(v) => v,
906 Err(_) => continue,
907 };
908 let packed = (iface << 16) | comp;
909 let key = iface_id_to_name
910 .get(&iface)
911 .map(|iface_name| format!("{}:{}", iface_name, name));
912 (packed, key, name.to_string())
913 } else if is_interface_pack {
914 let flat_id: i32 = match id_str.parse() {
915 Ok(v) => v,
916 Err(_) => continue,
917 };
918 if name.contains(':') {
919 (flat_id, Some(name.to_string()), name.to_string())
921 } else {
922 (flat_id, None, name.to_string())
924 }
925 } else {
926 let id: i32 = match id_str.parse() {
928 Ok(v) => v,
929 Err(_) => continue,
930 };
931 (id, None, name.to_string())
932 };
933
934 let actual_type = if is_interface_pack && component_key.is_some() {
937 Type::Component
938 } else {
939 entity_type
940 };
941
942 let normalized = register_name.to_lowercase().replace(' ', "_");
945 registry.register_entity_id(normalized, actual_type, idx);
946
947 if is_interface_pack && let Some(key) = component_key {
948 let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
949 format!(
950 "{}:{}",
951 iface_part,
952 crate::symbol::normalize_comp_name(comp_part)
953 )
954 } else {
955 key
956 };
957 registry.components.insert(normalized_key, idx);
958 }
959 }
960}
961
962fn load_entity_ids_typed_only(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
966 let text = match fs::read_to_string(path) {
967 Ok(t) => t,
968 Err(_) => return,
969 };
970 for line in text.lines() {
971 let line = line.trim();
972 if line.is_empty() {
973 continue;
974 }
975 let (id_str, name) = match line.split_once('=') {
976 Some(pair) => pair,
977 None => continue,
978 };
979 let name = name.trim();
980 if name.is_empty() || name == "null" {
981 continue;
982 }
983 let id: i32 = match id_str.parse() {
984 Ok(v) => v,
985 Err(_) => continue,
986 };
987 let normalized = name.to_lowercase().replace(' ', "_");
988 registry.register_entity_id_typed_only(normalized, entity_type, id);
989 }
990}
991
992fn register_type_chars(registry: &mut SymbolRegistry) {
996 let type_chars: &[(&str, i32)] = &[
997 ("int", b'i' as i32), ("string", b's' as i32), ("boolean", b'1' as i32), ("bool", b'1' as i32),
1001 ("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),
1008 ("npcuid", b'u' as i32), ("npc_uid", b'u' as i32),
1010 ("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),
1017 ("overlayinterface", b'a' as i32),
1018 ("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),
1024 ("category", b'y' as i32), ("varp", b'V' as i32), ("npc_stat", 0xFE), ("npcstat", 0xFE),
1028 ("idkit", b'K' as i32), ("idk", b'K' as i32),
1030 ];
1031 for (name, val) in type_chars {
1032 registry.type_chars.insert(name.to_string(), *val);
1033 }
1034}
1035
1036fn register_engine_constants(registry: &mut SymbolRegistry) {
1040 let npc_modes: &[(&str, i32)] = &[
1042 ("null", -1),
1043 ("none", 0),
1044 ("wander", 1),
1045 ("patrol", 2),
1046 ("playerescape", 3),
1047 ("playerfollow", 4),
1048 ("playerface", 5),
1049 ("playerfaceclose", 6),
1050 ("opplayer1", 7),
1051 ("opplayer2", 8),
1052 ("opplayer3", 9),
1053 ("opplayer4", 10),
1054 ("opplayer5", 11),
1055 ("applayer1", 12),
1056 ("applayer2", 13),
1057 ("applayer3", 14),
1058 ("applayer4", 15),
1059 ("applayer5", 16),
1060 ("oploc1", 17),
1061 ("oploc2", 18),
1062 ("oploc3", 19),
1063 ("oploc4", 20),
1064 ("oploc5", 21),
1065 ("aploc1", 22),
1066 ("aploc2", 23),
1067 ("aploc3", 24),
1068 ("aploc4", 25),
1069 ("aploc5", 26),
1070 ("opobj1", 27),
1071 ("opobj2", 28),
1072 ("opobj3", 29),
1073 ("opobj4", 30),
1074 ("opobj5", 31),
1075 ("apobj1", 32),
1076 ("apobj2", 33),
1077 ("apobj3", 34),
1078 ("apobj4", 35),
1079 ("apobj5", 36),
1080 ("opnpc1", 37),
1081 ("opnpc2", 38),
1082 ("opnpc3", 39),
1083 ("opnpc4", 40),
1084 ("opnpc5", 41),
1085 ("apnpc1", 42),
1086 ("apnpc2", 43),
1087 ("apnpc3", 44),
1088 ("apnpc4", 45),
1089 ("apnpc5", 46),
1090 ("queue1", 47),
1091 ("queue2", 48),
1092 ("queue3", 49),
1093 ("queue4", 50),
1094 ("queue5", 51),
1095 ("queue6", 52),
1096 ("queue7", 53),
1097 ("queue8", 54),
1098 ("queue9", 55),
1099 ("queue10", 56),
1100 ("queue11", 57),
1101 ("queue12", 58),
1102 ("queue13", 59),
1103 ("queue14", 60),
1104 ("queue15", 61),
1105 ("queue16", 62),
1106 ("queue17", 63),
1107 ("queue18", 64),
1108 ("queue19", 65),
1109 ("queue20", 66),
1110 ];
1111 fn is_trigger_collision(name: &str) -> bool {
1122 matches!(
1123 name,
1124 "oploc1"
1125 | "oploc2"
1126 | "oploc3"
1127 | "oploc4"
1128 | "oploc5"
1129 | "aploc1"
1130 | "aploc2"
1131 | "aploc3"
1132 | "aploc4"
1133 | "aploc5"
1134 | "opnpc1"
1135 | "opnpc2"
1136 | "opnpc3"
1137 | "opnpc4"
1138 | "opnpc5"
1139 | "apnpc1"
1140 | "apnpc2"
1141 | "apnpc3"
1142 | "apnpc4"
1143 | "apnpc5"
1144 | "opobj1"
1145 | "opobj2"
1146 | "opobj3"
1147 | "opobj4"
1148 | "opobj5"
1149 | "apobj1"
1150 | "apobj2"
1151 | "apobj3"
1152 | "apobj4"
1153 | "apobj5"
1154 | "opplayer1"
1155 | "opplayer2"
1156 | "opplayer3"
1157 | "opplayer4"
1158 | "opplayer5"
1159 | "applayer1"
1160 | "applayer2"
1161 | "applayer3"
1162 | "applayer4"
1163 | "applayer5"
1164 | "queue1"
1165 | "queue2"
1166 | "queue3"
1167 | "queue4"
1168 | "queue5"
1169 | "queue6"
1170 | "queue7"
1171 | "queue8"
1172 | "queue9"
1173 | "queue10"
1174 | "queue11"
1175 | "queue12"
1176 | "queue13"
1177 | "queue14"
1178 | "queue15"
1179 | "queue16"
1180 | "queue17"
1181 | "queue18"
1182 | "queue19"
1183 | "queue20"
1184 )
1185 }
1186 for &(name, id) in npc_modes {
1187 if is_trigger_collision(name) {
1188 registry.register_entity_id_typed_only(name.to_string(), Type::NpcMode, id);
1189 } else {
1190 registry.register_entity_id(name.to_string(), Type::NpcMode, id);
1191 }
1192 }
1193
1194 let npc_stats: &[(&str, i32)] = &[
1196 ("attack", 0),
1197 ("defence", 1),
1198 ("strength", 2),
1199 ("hitpoints", 3),
1200 ("ranged", 4),
1201 ("magic", 5),
1202 ];
1203 for &(name, id) in npc_stats {
1204 registry.register_entity_id(name.to_string(), Type::NpcStat, id);
1205 }
1206
1207 let stats: &[(&str, i32)] = &[
1210 ("attack", 0),
1211 ("defence", 1),
1212 ("strength", 2),
1213 ("hitpoints", 3),
1214 ("ranged", 4),
1215 ("prayer", 5),
1216 ("magic", 6),
1217 ("cooking", 7),
1218 ("woodcutting", 8),
1219 ("fletching", 9),
1220 ("fishing", 10),
1221 ("firemaking", 11),
1222 ("crafting", 12),
1223 ("smithing", 13),
1224 ("mining", 14),
1225 ("herblore", 15),
1226 ("agility", 16),
1227 ("thieving", 17),
1228 ("slayer", 18),
1229 ("stat18", 18),
1230 ("farming", 19),
1231 ("stat19", 19),
1232 ("runecraft", 20),
1233 ("hunter", 21),
1234 ("construction", 22),
1235 ("summoning", 23),
1236 ("dungeoneering", 24),
1237 ];
1238 for &(name, id) in stats {
1239 registry.register_entity_id(name.to_string(), Type::Stat, id);
1240 }
1241
1242 let fontmetrics: &[(&str, i32)] = &[
1244 ("p11", 0),
1245 ("p12", 1),
1246 ("b12", 2),
1247 ("q8", 3),
1248 ("p11_full", 0),
1249 ("p12_full", 1),
1250 ("b12_full", 2),
1251 ("q8_full", 3),
1252 ];
1253 for &(name, id) in fontmetrics {
1254 registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
1255 }
1256
1257 let locshapes: &[(&str, i32)] = &[
1259 ("wall_straight", 0),
1260 ("wall_diagonalcorner", 1),
1261 ("wall_l", 2),
1262 ("wall_squarecorner", 3),
1263 ("walldecor_straight_nooffset", 4),
1264 ("walldecor_straight_offset", 5),
1265 ("walldecor_diagonal_offset", 6),
1266 ("walldecor_diagonal_nooffset", 7),
1267 ("walldecor_diagonal_both", 8),
1268 ("wall_diagonal", 9),
1269 ("centrepiece_straight", 10),
1270 ("centrepiece_diagonal", 11),
1271 ("roof_straight", 12),
1272 ("roof_diagonal_with_roofedge", 13),
1273 ("roof_diagonal", 14),
1274 ("roof_l_concave", 15),
1275 ("roof_l_convex", 16),
1276 ("roof_flat", 17),
1277 ("roofedge_straight", 18),
1278 ("roofedge_diagonalcorner", 19),
1279 ("roofedge_l", 20),
1280 ("roofedge_squarecorner", 21),
1281 ("grounddecor", 22),
1282 ];
1283 for &(name, id) in locshapes {
1284 registry.register_entity_id(name.to_string(), Type::LocShape, id);
1285 }
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290 use super::*;
1291 use crate::symbol::SymbolRegistry;
1292 use crate::types::Type;
1293 use std::io::Write;
1294 use std::path::PathBuf;
1295
1296 fn write_temp_pack(name: &str, content: &str) -> PathBuf {
1297 let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1298 .join("target")
1299 .join("test-symloader");
1300 fs::create_dir_all(&dir).unwrap();
1301 let path = dir.join(name);
1302 let mut f = fs::File::create(&path).unwrap();
1303 f.write_all(content.as_bytes()).unwrap();
1304 path
1305 }
1306
1307 #[test]
1311 fn load_647_style_registers_components() {
1312 let pack = write_temp_pack(
1313 "interface_647.pack",
1314 "\
1315228=multi2\n\
1316228:0=com0\n\
1317228:1=com1\n\
1318228:2=com2\n\
1319228:3=com3\n\
1320228:6=thin_swords\n\
1321228:9=wide_swords\n",
1322 );
1323 let mut r = SymbolRegistry::new();
1324 load_entity_ids(&mut r, &pack, Type::Interface);
1325
1326 assert_eq!(r.interface_ids.get("multi2"), Some(&228));
1328
1329 assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
1331 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1332 assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
1333
1334 assert_eq!(
1336 r.lookup_component("multi2", "thin_swords"),
1337 Some((228 << 16) | 6)
1338 );
1339 assert_eq!(
1340 r.lookup_component("multi2", "wide_swords"),
1341 Some((228 << 16) | 9)
1342 );
1343 }
1344
1345 #[test]
1346 fn load_647_style_resolves_225_references() {
1347 let pack = write_temp_pack(
1348 "interface_647_cross.pack",
1349 "\
1350228=multi2\n\
1351228:0=com0\n\
1352228:1=com1\n\
1353228:2=com2\n",
1354 );
1355 let mut r = SymbolRegistry::new();
1356 load_entity_ids(&mut r, &pack, Type::Interface);
1357
1358 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1360 assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
1361 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1362 }
1363
1364 #[test]
1368 fn load_225_style_registers_components() {
1369 let pack = write_temp_pack(
1370 "interface_225.pack",
1371 "\
13722459=multi2\n\
13732460=multi2:com_0\n\
13742461=multi2:com_1\n\
13752462=multi2:com_2\n\
13762463=multi2:com_4\n\
13772464=multi2:com_5\n",
1378 );
1379 let mut r = SymbolRegistry::new();
1380 load_entity_ids(&mut r, &pack, Type::Interface);
1381
1382 assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
1384
1385 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
1387 assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
1388 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1389 }
1390
1391 #[test]
1392 fn load_225_style_resolves_647_references() {
1393 let pack = write_temp_pack(
1394 "interface_225_cross.pack",
1395 "\
13962459=multi2\n\
13972460=multi2:com_0\n\
13982461=multi2:com_1\n\
13992462=multi2:com_2\n",
1400 );
1401 let mut r = SymbolRegistry::new();
1402 load_entity_ids(&mut r, &pack, Type::Interface);
1403
1404 assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
1406 assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
1407 assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
1408 }
1409
1410 #[test]
1413 fn components_register_as_component_type() {
1414 let pack = write_temp_pack(
1415 "interface_types.pack",
1416 "\
1417228=multi2\n\
1418228:0=com0\n",
1419 );
1420 let mut r = SymbolRegistry::new();
1421 load_entity_ids(&mut r, &pack, Type::Interface);
1422
1423 assert!(
1425 r.lookup_entity_id_typed("multi2", Type::Interface)
1426 .is_some()
1427 );
1428 assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
1429 assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
1430 }
1431}