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 register_type_chars(registry);
350
351 load_script_pack(registry, &pack_dir.join("script.pack"));
353
354 load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
358}
359
360fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
364 let text = match fs::read_to_string(path) {
365 Ok(t) => t,
366 Err(_) => return,
367 };
368 for line in text.lines() {
369 let line = line.trim();
370 if line.is_empty() {
371 continue;
372 }
373 let (id_str, rest) = match line.split_once('=') {
374 Some(pair) => pair,
375 None => continue,
376 };
377 let id: i32 = match id_str.parse() {
378 Ok(v) => v,
379 Err(_) => continue,
380 };
381 let rest = rest.trim();
382 if !rest.starts_with('[') || !rest.ends_with(']') {
383 continue;
384 }
385 let inner = &rest[1..rest.len() - 1];
386 let (_trigger, name) = match inner.split_once(',') {
387 Some(pair) => pair,
388 None => continue,
389 };
390 if name.is_empty() {
391 continue;
392 }
393 registry.script_ids.insert(name.to_string(), id);
394 registry
395 .trigger_script_ids
396 .insert(format!("clientscript:{}", name), id);
397 }
398}
399
400fn load_commands(registry: &mut SymbolRegistry, path: &Path) {
407 let text = match fs::read_to_string(path) {
408 Ok(t) => t,
409 Err(_) => return,
410 };
411 for line in text.lines() {
412 let line = line.trim();
413 if line.is_empty() {
414 continue;
415 }
416 let (id_str, name) = match line.split_once('=') {
417 Some(pair) => pair,
418 None => continue,
419 };
420 let opcode: i32 = match id_str.parse() {
421 Ok(v) => v,
422 Err(_) => continue,
423 };
424 let name = name.trim().to_string();
425 if name.is_empty() {
426 continue;
427 }
428 registry.register_command(name, opcode, Vec::new(), Vec::new());
429 }
430}
431
432fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
433 let text = match fs::read_to_string(path) {
434 Ok(t) => t,
435 Err(_) => return,
436 };
437 for line in text.lines() {
438 let line = line.trim();
439 if line.is_empty() {
440 continue;
441 }
442 let (id_str, name) = match line.split_once('=') {
443 Some(pair) => pair,
444 None => continue,
445 };
446 let idx: i32 = match id_str.parse() {
447 Ok(v) => v,
448 Err(_) => continue,
449 };
450 let name = name.trim().to_string();
451 if name.is_empty() {
452 continue;
453 }
454 registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
458 registry.register_game_var(name, Type::Int, idx, category.to_string());
459 }
460}
461
462pub fn load_dbtable_configs(
475 registry: &mut SymbolRegistry,
476 scripts_dir: &Path,
477 dbtable_ids: &std::collections::HashMap<String, u16>,
478) {
479 let mut dbtable_files: Vec<std::path::PathBuf> = Vec::new();
480 collect_files_by_ext(scripts_dir, "dbtable", &mut dbtable_files);
481 dbtable_files.sort();
482
483 for path in &dbtable_files {
484 let Ok(text) = fs::read_to_string(path) else {
485 continue;
486 };
487 let lines = strip_comments(&text);
488
489 let mut current_table: Option<String> = None;
490 let mut col_idx: u16 = 0;
491 for line in &lines {
492 if line.starts_with('[') && line.ends_with(']') {
494 let name = line[1..line.len() - 1].trim().to_string();
495 current_table = Some(name);
496 col_idx = 0;
497 continue;
498 }
499 let Some(rest) = line.strip_prefix("column=") else {
501 continue;
502 };
503 let Some(table_name) = current_table.as_deref() else {
504 continue;
505 };
506 let Some(&table_id) = dbtable_ids.get(table_name) else {
507 continue;
508 };
509
510 let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
511 if parts.is_empty() {
512 continue;
513 }
514 let col_name = parts[0];
515 if col_name.is_empty() {
516 continue;
517 }
518
519 let types: Vec<Type> = parts[1..]
521 .iter()
522 .filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
523 .filter_map(|s| Type::from_name(s))
524 .collect();
525
526 let compound = format!("{}:{}", table_name, col_name);
527 let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
528
529 registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
531
532 if types.len() > 1 {
534 for (i, _) in types.iter().enumerate() {
535 let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
536 let slot_packed = packed | (((i as i32) + 1) & 0xF);
537 registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
538 }
539 }
540
541 if let Some(first_type) = types.first().copied() {
543 registry.dbcolumn_types.insert(compound, first_type);
544 }
545
546 col_idx += 1;
547 }
548 }
549}
550
551pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
553 let mut out = std::collections::HashMap::new();
554 let Ok(text) = fs::read_to_string(path) else {
555 return out;
556 };
557 for line in text.lines() {
558 let line = line.trim();
559 if line.is_empty() {
560 continue;
561 }
562 let Some((id_str, name)) = line.split_once('=') else {
563 continue;
564 };
565 let Ok(id) = id_str.parse::<u16>() else {
566 continue;
567 };
568 let name = name.trim();
569 if name.is_empty() {
570 continue;
571 }
572 out.insert(name.to_string(), id);
573 }
574 out
575}
576
577pub fn load_constant_files(registry: &mut SymbolRegistry, scripts_dir: &Path) {
582 let mut constant_files: Vec<std::path::PathBuf> = Vec::new();
583 collect_files_by_ext(scripts_dir, "constant", &mut constant_files);
584 constant_files.sort();
585
586 for path in &constant_files {
587 let text = match fs::read_to_string(path) {
588 Ok(t) => t,
589 Err(_) => continue,
590 };
591 let lines = strip_comments(&text);
592 for line in &lines {
593 let eq_pos = match line.find('=') {
595 Some(i) => i,
596 None => continue,
597 };
598 let mut name = line[..eq_pos].trim();
599 let value = line[eq_pos + 1..].trim();
600
601 if let Some(stripped) = name.strip_prefix('^') {
603 name = stripped;
604 }
605
606 if name.is_empty() {
607 continue;
608 }
609
610 let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
612 &value[1..value.len() - 1]
613 } else {
614 value
615 };
616
617 register_constant_value(registry, name.to_string(), val_str);
618 }
619 }
620}
621
622fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
624 if let Ok(i) = val_str.parse::<i32>() {
625 registry.register_constant(name, Type::Int, Some(i), None);
626 } else if let Some(hex_str) = val_str
627 .strip_prefix("0x")
628 .or_else(|| val_str.strip_prefix("0X"))
629 {
630 let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
631 registry.register_constant(name, Type::Int, Some(v), None);
632 } else if let Some(packed) = parse_coord_string(val_str) {
633 registry.register_constant(name, Type::Coord, Some(packed), None);
634 } else {
635 registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
636 }
637}
638
639fn strip_comments(text: &str) -> Vec<String> {
642 let mut result = Vec::new();
643 let mut multi_depth: usize = 0;
644
645 for line in text.lines() {
646 let mut line = line.trim().to_string();
647
648 if multi_depth > 0 {
650 while let Some(start) = line.find("/*") {
651 line = line[start + 2..].trim_start().to_string();
652 multi_depth += 1;
653 }
654 while let Some(end) = line.find("*/") {
655 line = line[end + 2..].trim_start().to_string();
656 multi_depth -= 1;
657 if multi_depth == 0 {
658 break;
659 }
660 }
661 if multi_depth > 0 {
662 continue;
663 }
664 }
665
666 if line.is_empty() {
667 continue;
668 }
669
670 if let Some(idx) = line.find("//") {
672 line = line[..idx].trim_end().to_string();
673 if line.is_empty() {
674 continue;
675 }
676 }
677
678 if let Some(start) = line.find("/*") {
680 if let Some(end) = line.find("*/") {
681 line = format!("{}{}", &line[..start], &line[end + 2..]);
682 } else {
683 line = line[..start].to_string();
684 multi_depth += 1;
685 }
686 if line.is_empty() {
687 continue;
688 }
689 }
690
691 result.push(line);
692 }
693
694 result
695}
696
697pub fn load_game_var_types(registry: &mut SymbolRegistry, scripts_dir: &Path) {
702 let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
704 for ext in &["varp", "varn", "vars", "varbit"] {
705 let max_id = registry
707 .game_vars
708 .values()
709 .filter_map(|sym| {
710 if let crate::symbol::SymbolKind::GameVar {
711 var_id, category, ..
712 } = &sym.kind
713 {
714 if category == *ext {
715 Some(*var_id)
716 } else {
717 None
718 }
719 } else {
720 None
721 }
722 })
723 .max()
724 .unwrap_or(-1);
725 next_auto_id.insert(ext.to_string(), max_id + 1);
726 }
727
728 for ext in &["varp", "varn", "vars", "varbit"] {
729 let mut files = Vec::new();
730 collect_files_by_ext(scripts_dir, ext, &mut files);
731 for path in &files {
732 let Ok(text) = fs::read_to_string(path) else {
733 continue;
734 };
735 let mut current_name: Option<String> = None;
736 for line in text.lines() {
737 let line = line.trim();
738 if line.is_empty() || line.starts_with("//") {
739 continue;
740 }
741 if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
742 let name = inner.trim().to_string();
743 if !registry.game_vars.contains_key(&name) {
745 let id = next_auto_id.get_mut(*ext).unwrap();
746 let auto_id = *id;
747 *id += 1;
748 registry.register_game_var(
749 name.clone(),
750 Type::Int,
751 auto_id,
752 ext.to_string(),
753 );
754 registry.register_game_var(
755 format!(".{}", name),
756 Type::Int,
757 auto_id,
758 ext.to_string(),
759 );
760 }
761 current_name = Some(name);
762 continue;
763 }
764 let Some(name) = current_name.as_ref() else {
765 continue;
766 };
767 if let Some((k, v)) = line.split_once('=')
768 && k.trim() == "type"
769 {
770 let type_name = v.trim();
771 if let Some(ty) = Type::from_name(type_name) {
772 if let Some(sym) = registry.game_vars.get_mut(name)
773 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
774 &mut sym.kind
775 {
776 *var_type = ty;
777 }
778 let dot_name = format!(".{}", name);
779 if let Some(sym) = registry.game_vars.get_mut(&dot_name)
780 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
781 &mut sym.kind
782 {
783 *var_type = ty;
784 }
785 }
786 }
787 }
788 }
789 }
790}
791
792fn collect_files_by_ext(dir: &Path, ext: &str, out: &mut Vec<std::path::PathBuf>) {
794 let entries = match fs::read_dir(dir) {
795 Ok(e) => e,
796 Err(_) => return,
797 };
798 for entry in entries.flatten() {
799 let path = entry.path();
800 if path.is_dir() {
801 collect_files_by_ext(&path, ext, out);
802 } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
803 out.push(path);
804 }
805 }
806}
807
808fn parse_coord_string(s: &str) -> Option<i32> {
811 let parts: Vec<&str> = s.split('_').collect();
812 if parts.len() != 5 {
813 return None;
814 }
815 let y: i32 = parts[0].parse().ok()?;
816 let bx: i32 = parts[1].parse().ok()?;
817 let bz: i32 = parts[2].parse().ok()?;
818 let lx: i32 = parts[3].parse().ok()?;
819 let lz: i32 = parts[4].parse().ok()?;
820 let x = bx * 64 + lx;
821 let z = bz * 64 + lz;
822 Some((y << 28) | (x << 14) | z)
823}
824
825fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
839 let text = match fs::read_to_string(path) {
840 Ok(t) => t,
841 Err(_) => return,
842 };
843
844 let is_interface_pack = entity_type == Type::Interface;
845
846 let mut iface_id_to_name: std::collections::HashMap<i32, String> =
849 std::collections::HashMap::new();
850
851 for line in text.lines() {
852 let line = line.trim();
853 if line.is_empty() {
854 continue;
855 }
856 let (id_str, name) = match line.split_once('=') {
857 Some(pair) => pair,
858 None => continue,
859 };
860 let name = name.trim();
861 if name.is_empty() || name == "null" {
862 continue;
863 }
864
865 if is_interface_pack
866 && !id_str.contains(':')
867 && !name.contains(':')
868 && let Ok(id) = id_str.parse::<i32>()
869 {
870 registry.interface_ids.insert(name.to_string(), id);
871 iface_id_to_name.insert(id, name.to_string());
872 }
873 }
874
875 for line in text.lines() {
877 let line = line.trim();
878 if line.is_empty() {
879 continue;
880 }
881 let (id_str, name) = match line.split_once('=') {
882 Some(pair) => pair,
883 None => continue,
884 };
885 let name = name.trim();
886 if name.is_empty() || name == "null" {
887 continue;
888 }
889
890 let (idx, component_key, register_name): (i32, Option<String>, String) =
893 if let Some((iface_str, comp_str)) = id_str.split_once(':') {
894 let iface: i32 = match iface_str.parse() {
896 Ok(v) => v,
897 Err(_) => continue,
898 };
899 let comp: i32 = match comp_str.parse() {
900 Ok(v) => v,
901 Err(_) => continue,
902 };
903 let packed = (iface << 16) | comp;
904 let key = iface_id_to_name
905 .get(&iface)
906 .map(|iface_name| format!("{}:{}", iface_name, name));
907 (packed, key, name.to_string())
908 } else if is_interface_pack {
909 let flat_id: i32 = match id_str.parse() {
910 Ok(v) => v,
911 Err(_) => continue,
912 };
913 if name.contains(':') {
914 (flat_id, Some(name.to_string()), name.to_string())
916 } else {
917 (flat_id, None, name.to_string())
919 }
920 } else {
921 let id: i32 = match id_str.parse() {
923 Ok(v) => v,
924 Err(_) => continue,
925 };
926 (id, None, name.to_string())
927 };
928
929 let actual_type = if is_interface_pack && component_key.is_some() {
932 Type::Component
933 } else {
934 entity_type
935 };
936
937 let normalized = register_name.to_lowercase().replace(' ', "_");
940 registry.register_entity_id(normalized, actual_type, idx);
941
942 if is_interface_pack && let Some(key) = component_key {
943 let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
944 format!(
945 "{}:{}",
946 iface_part,
947 crate::symbol::normalize_comp_name(comp_part)
948 )
949 } else {
950 key
951 };
952 registry.components.insert(normalized_key, idx);
953 }
954 }
955}
956
957fn register_type_chars(registry: &mut SymbolRegistry) {
961 let type_chars: &[(&str, i32)] = &[
962 ("int", b'i' as i32), ("string", b's' as i32), ("boolean", b'1' as i32), ("bool", b'1' as i32),
966 ("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),
973 ("npcuid", b'u' as i32), ("npc_uid", b'u' as i32),
975 ("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),
982 ("overlayinterface", b'a' as i32),
983 ("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),
989 ("category", b'y' as i32), ("varp", b'V' as i32), ("npc_stat", 0xFE), ("npcstat", 0xFE),
993 ("idkit", b'K' as i32), ("idk", b'K' as i32),
995 ];
996 for (name, val) in type_chars {
997 registry.type_chars.insert(name.to_string(), *val);
998 }
999}
1000
1001fn register_engine_constants(registry: &mut SymbolRegistry) {
1005 let npc_modes: &[(&str, i32)] = &[
1007 ("null", -1),
1008 ("none", 0),
1009 ("wander", 1),
1010 ("patrol", 2),
1011 ("playerescape", 3),
1012 ("playerfollow", 4),
1013 ("playerface", 5),
1014 ("playerfaceclose", 6),
1015 ("opplayer1", 7),
1016 ("opplayer2", 8),
1017 ("opplayer3", 9),
1018 ("opplayer4", 10),
1019 ("opplayer5", 11),
1020 ("applayer1", 12),
1021 ("applayer2", 13),
1022 ("applayer3", 14),
1023 ("applayer4", 15),
1024 ("applayer5", 16),
1025 ("oploc1", 17),
1026 ("oploc2", 18),
1027 ("oploc3", 19),
1028 ("oploc4", 20),
1029 ("oploc5", 21),
1030 ("aploc1", 22),
1031 ("aploc2", 23),
1032 ("aploc3", 24),
1033 ("aploc4", 25),
1034 ("aploc5", 26),
1035 ("opobj1", 27),
1036 ("opobj2", 28),
1037 ("opobj3", 29),
1038 ("opobj4", 30),
1039 ("opobj5", 31),
1040 ("apobj1", 32),
1041 ("apobj2", 33),
1042 ("apobj3", 34),
1043 ("apobj4", 35),
1044 ("apobj5", 36),
1045 ("opnpc1", 37),
1046 ("opnpc2", 38),
1047 ("opnpc3", 39),
1048 ("opnpc4", 40),
1049 ("opnpc5", 41),
1050 ("apnpc1", 42),
1051 ("apnpc2", 43),
1052 ("apnpc3", 44),
1053 ("apnpc4", 45),
1054 ("apnpc5", 46),
1055 ("queue1", 47),
1056 ("queue2", 48),
1057 ("queue3", 49),
1058 ("queue4", 50),
1059 ("queue5", 51),
1060 ("queue6", 52),
1061 ("queue7", 53),
1062 ("queue8", 54),
1063 ("queue9", 55),
1064 ("queue10", 56),
1065 ("queue11", 57),
1066 ("queue12", 58),
1067 ("queue13", 59),
1068 ("queue14", 60),
1069 ("queue15", 61),
1070 ("queue16", 62),
1071 ("queue17", 63),
1072 ("queue18", 64),
1073 ("queue19", 65),
1074 ("queue20", 66),
1075 ];
1076 for &(name, id) in npc_modes {
1077 registry.register_entity_id(name.to_string(), Type::NpcMode, id);
1078 }
1079
1080 let npc_stats: &[(&str, i32)] = &[
1082 ("attack", 0),
1083 ("defence", 1),
1084 ("strength", 2),
1085 ("hitpoints", 3),
1086 ("ranged", 4),
1087 ("magic", 5),
1088 ];
1089 for &(name, id) in npc_stats {
1090 registry.register_entity_id(name.to_string(), Type::NpcStat, id);
1091 }
1092
1093 let stats: &[(&str, i32)] = &[
1096 ("attack", 0),
1097 ("defence", 1),
1098 ("strength", 2),
1099 ("hitpoints", 3),
1100 ("ranged", 4),
1101 ("prayer", 5),
1102 ("magic", 6),
1103 ("cooking", 7),
1104 ("woodcutting", 8),
1105 ("fletching", 9),
1106 ("fishing", 10),
1107 ("firemaking", 11),
1108 ("crafting", 12),
1109 ("smithing", 13),
1110 ("mining", 14),
1111 ("herblore", 15),
1112 ("agility", 16),
1113 ("thieving", 17),
1114 ("slayer", 18),
1115 ("stat18", 18),
1116 ("farming", 19),
1117 ("stat19", 19),
1118 ("runecraft", 20),
1119 ("hunter", 21),
1120 ("construction", 22),
1121 ("summoning", 23),
1122 ("dungeoneering", 24),
1123 ];
1124 for &(name, id) in stats {
1125 registry.register_entity_id(name.to_string(), Type::Stat, id);
1126 }
1127
1128 let fontmetrics: &[(&str, i32)] = &[
1130 ("p11", 0),
1131 ("p12", 1),
1132 ("b12", 2),
1133 ("q8", 3),
1134 ("p11_full", 0),
1135 ("p12_full", 1),
1136 ("b12_full", 2),
1137 ("q8_full", 3),
1138 ];
1139 for &(name, id) in fontmetrics {
1140 registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
1141 }
1142
1143 let locshapes: &[(&str, i32)] = &[
1145 ("wall_straight", 0),
1146 ("wall_diagonalcorner", 1),
1147 ("wall_l", 2),
1148 ("wall_squarecorner", 3),
1149 ("walldecor_straight_nooffset", 4),
1150 ("walldecor_straight_offset", 5),
1151 ("walldecor_diagonal_offset", 6),
1152 ("walldecor_diagonal_nooffset", 7),
1153 ("walldecor_diagonal_both", 8),
1154 ("wall_diagonal", 9),
1155 ("centrepiece_straight", 10),
1156 ("centrepiece_diagonal", 11),
1157 ("roof_straight", 12),
1158 ("roof_diagonal_with_roofedge", 13),
1159 ("roof_diagonal", 14),
1160 ("roof_l_concave", 15),
1161 ("roof_l_convex", 16),
1162 ("roof_flat", 17),
1163 ("roofedge_straight", 18),
1164 ("roofedge_diagonalcorner", 19),
1165 ("roofedge_l", 20),
1166 ("roofedge_squarecorner", 21),
1167 ("grounddecor", 22),
1168 ];
1169 for &(name, id) in locshapes {
1170 registry.register_entity_id(name.to_string(), Type::LocShape, id);
1171 }
1172}
1173
1174#[cfg(test)]
1175mod tests {
1176 use super::*;
1177 use crate::symbol::SymbolRegistry;
1178 use crate::types::Type;
1179 use std::io::Write;
1180 use std::path::PathBuf;
1181
1182 fn write_temp_pack(name: &str, content: &str) -> PathBuf {
1183 let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1184 .join("target")
1185 .join("test-symloader");
1186 fs::create_dir_all(&dir).unwrap();
1187 let path = dir.join(name);
1188 let mut f = fs::File::create(&path).unwrap();
1189 f.write_all(content.as_bytes()).unwrap();
1190 path
1191 }
1192
1193 #[test]
1197 fn load_647_style_registers_components() {
1198 let pack = write_temp_pack(
1199 "interface_647.pack",
1200 "\
1201228=multi2\n\
1202228:0=com0\n\
1203228:1=com1\n\
1204228:2=com2\n\
1205228:3=com3\n\
1206228:6=thin_swords\n\
1207228:9=wide_swords\n",
1208 );
1209 let mut r = SymbolRegistry::new();
1210 load_entity_ids(&mut r, &pack, Type::Interface);
1211
1212 assert_eq!(r.interface_ids.get("multi2"), Some(&228));
1214
1215 assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
1217 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1218 assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
1219
1220 assert_eq!(
1222 r.lookup_component("multi2", "thin_swords"),
1223 Some((228 << 16) | 6)
1224 );
1225 assert_eq!(
1226 r.lookup_component("multi2", "wide_swords"),
1227 Some((228 << 16) | 9)
1228 );
1229 }
1230
1231 #[test]
1232 fn load_647_style_resolves_225_references() {
1233 let pack = write_temp_pack(
1234 "interface_647_cross.pack",
1235 "\
1236228=multi2\n\
1237228:0=com0\n\
1238228:1=com1\n\
1239228:2=com2\n",
1240 );
1241 let mut r = SymbolRegistry::new();
1242 load_entity_ids(&mut r, &pack, Type::Interface);
1243
1244 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1246 assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
1247 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1248 }
1249
1250 #[test]
1254 fn load_225_style_registers_components() {
1255 let pack = write_temp_pack(
1256 "interface_225.pack",
1257 "\
12582459=multi2\n\
12592460=multi2:com_0\n\
12602461=multi2:com_1\n\
12612462=multi2:com_2\n\
12622463=multi2:com_4\n\
12632464=multi2:com_5\n",
1264 );
1265 let mut r = SymbolRegistry::new();
1266 load_entity_ids(&mut r, &pack, Type::Interface);
1267
1268 assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
1270
1271 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
1273 assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
1274 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1275 }
1276
1277 #[test]
1278 fn load_225_style_resolves_647_references() {
1279 let pack = write_temp_pack(
1280 "interface_225_cross.pack",
1281 "\
12822459=multi2\n\
12832460=multi2:com_0\n\
12842461=multi2:com_1\n\
12852462=multi2:com_2\n",
1286 );
1287 let mut r = SymbolRegistry::new();
1288 load_entity_ids(&mut r, &pack, Type::Interface);
1289
1290 assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
1292 assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
1293 assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
1294 }
1295
1296 #[test]
1299 fn components_register_as_component_type() {
1300 let pack = write_temp_pack(
1301 "interface_types.pack",
1302 "\
1303228=multi2\n\
1304228:0=com0\n",
1305 );
1306 let mut r = SymbolRegistry::new();
1307 load_entity_ids(&mut r, &pack, Type::Interface);
1308
1309 assert!(
1311 r.lookup_entity_id_typed("multi2", Type::Interface)
1312 .is_some()
1313 );
1314 assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
1315 assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
1316 }
1317}