use std::collections::HashMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::types::InfEntry;
#[derive(Debug, Clone)]
pub enum RegistryError {
MissingField(String),
NotACombi,
}
impl fmt::Display for RegistryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingField(field) => write!(f, "missing required field '{field}'"),
Self::NotACombi => write!(f, "entry is not a combination block"),
}
}
}
impl std::error::Error for RegistryError {}
fn get_one(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
fields.get(key).and_then(|v| v.first().cloned())
}
fn get_many(fields: &HashMap<String, Vec<String>>, key: &str) -> Vec<String> {
fields.get(key).cloned().unwrap_or_default()
}
fn get_script(entry: &InfEntry) -> Option<String> {
entry.script.clone()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItemDef {
pub id: String,
pub name: String,
pub group: String,
pub icon: String,
pub model: String,
pub scale: Option<String>,
pub mat: Option<String>,
pub weight: Option<String>,
pub info: Option<String>,
pub behaviour: Option<String>,
pub damage: Option<String>,
pub speed: Option<String>,
pub drag: Option<String>,
pub rate: Option<String>,
pub color: Option<String>,
pub shine: Option<String>,
pub blend: Option<String>,
pub healthchange: Option<String>,
pub script: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub raw_extra: HashMap<String, Vec<String>>,
}
impl TryFrom<&InfEntry> for ItemDef {
type Error = RegistryError;
fn try_from(entry: &InfEntry) -> Result<Self, Self::Error> {
let id = get_one(&entry.fields, "id")
.ok_or_else(|| RegistryError::MissingField("id".into()))?;
let name = get_one(&entry.fields, "name")
.ok_or_else(|| RegistryError::MissingField("name".into()))?;
let group = get_one(&entry.fields, "group")
.ok_or_else(|| RegistryError::MissingField("group".into()))?;
let icon = get_one(&entry.fields, "icon")
.ok_or_else(|| RegistryError::MissingField("icon".into()))?;
let model = get_one(&entry.fields, "model")
.ok_or_else(|| RegistryError::MissingField("model".into()))?;
const KNOWN: &[&str] = &[
"id", "name", "group", "icon", "model", "scale", "mat", "weight",
"info", "behaviour", "damage", "speed", "drag", "rate",
"color", "shine", "blend", "healthchange",
];
let raw_extra = extract_extra(&entry.fields, KNOWN);
Ok(ItemDef {
id,
name,
group,
icon,
model,
scale: get_one(&entry.fields, "scale"),
mat: get_one(&entry.fields, "mat"),
weight: get_one(&entry.fields, "weight"),
info: get_one(&entry.fields, "info"),
behaviour: get_one(&entry.fields, "behaviour"),
damage: get_one(&entry.fields, "damage"),
speed: get_one(&entry.fields, "speed"),
drag: get_one(&entry.fields, "drag"),
rate: get_one(&entry.fields, "rate"),
color: get_one(&entry.fields, "color"),
shine: get_one(&entry.fields, "shine"),
blend: get_one(&entry.fields, "blend"),
healthchange: get_one(&entry.fields, "healthchange"),
script: get_script(entry),
raw_extra,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectDef {
pub id: String,
pub name: String,
pub group: String,
pub icon: String,
pub model: String,
pub mat: Option<String>,
pub scale: Option<String>,
pub health: Option<String>,
pub healthchange: Option<String>,
pub behaviour: Option<String>,
pub swayspeed: Option<String>,
pub swaypower: Option<String>,
pub fx: Option<String>,
pub find: Vec<String>,
pub script: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub raw_extra: HashMap<String, Vec<String>>,
}
impl TryFrom<&InfEntry> for ObjectDef {
type Error = RegistryError;
fn try_from(entry: &InfEntry) -> Result<Self, Self::Error> {
let id = get_one(&entry.fields, "id")
.ok_or_else(|| RegistryError::MissingField("id".into()))?;
let name = get_one(&entry.fields, "name")
.ok_or_else(|| RegistryError::MissingField("name".into()))?;
let group = get_one(&entry.fields, "group")
.ok_or_else(|| RegistryError::MissingField("group".into()))?;
let icon = get_one(&entry.fields, "icon")
.ok_or_else(|| RegistryError::MissingField("icon".into()))?;
let model = get_one(&entry.fields, "model")
.ok_or_else(|| RegistryError::MissingField("model".into()))?;
const KNOWN: &[&str] = &[
"id", "name", "group", "icon", "model", "mat", "scale",
"health", "healthchange", "behaviour", "swayspeed", "swaypower",
"fx", "find",
];
let raw_extra = extract_extra(&entry.fields, KNOWN);
Ok(ObjectDef {
id,
name,
group,
icon,
model,
mat: get_one(&entry.fields, "mat"),
scale: get_one(&entry.fields, "scale"),
health: get_one(&entry.fields, "health"),
healthchange: get_one(&entry.fields, "healthchange"),
behaviour: get_one(&entry.fields, "behaviour"),
swayspeed: get_one(&entry.fields, "swayspeed"),
swaypower: get_one(&entry.fields, "swaypower"),
fx: get_one(&entry.fields, "fx"),
find: get_many(&entry.fields, "find"),
script: get_script(entry),
raw_extra,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnitDef {
pub id: String,
pub name: String,
pub group: String,
pub icon: String,
pub model: String,
pub scale: Option<String>,
pub colxr: Option<String>,
pub colyr: Option<String>,
pub speed: Option<String>,
pub eyes: Option<String>,
pub store: Option<String>,
pub health: Option<String>,
pub damage: Option<String>,
pub attackrange: Option<String>,
pub maxweight: Option<String>,
pub healthchange: Option<String>,
pub behaviour: Option<String>,
pub script: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub raw_extra: HashMap<String, Vec<String>>,
}
impl TryFrom<&InfEntry> for UnitDef {
type Error = RegistryError;
fn try_from(entry: &InfEntry) -> Result<Self, Self::Error> {
let id = get_one(&entry.fields, "id")
.ok_or_else(|| RegistryError::MissingField("id".into()))?;
let name = get_one(&entry.fields, "name")
.ok_or_else(|| RegistryError::MissingField("name".into()))?;
let group = get_one(&entry.fields, "group")
.ok_or_else(|| RegistryError::MissingField("group".into()))?;
let icon = get_one(&entry.fields, "icon")
.ok_or_else(|| RegistryError::MissingField("icon".into()))?;
let model = get_one(&entry.fields, "model")
.ok_or_else(|| RegistryError::MissingField("model".into()))?;
const KNOWN: &[&str] = &[
"id", "name", "group", "icon", "model", "scale",
"colxr", "colyr", "speed", "eyes", "store", "health",
"damage", "attackrange", "maxweight", "healthchange", "behaviour",
];
let raw_extra = extract_extra(&entry.fields, KNOWN);
Ok(UnitDef {
id,
name,
group,
icon,
model,
scale: get_one(&entry.fields, "scale"),
colxr: get_one(&entry.fields, "colxr"),
colyr: get_one(&entry.fields, "colyr"),
speed: get_one(&entry.fields, "speed"),
eyes: get_one(&entry.fields, "eyes"),
store: get_one(&entry.fields, "store"),
health: get_one(&entry.fields, "health"),
damage: get_one(&entry.fields, "damage"),
attackrange: get_one(&entry.fields, "attackrange"),
maxweight: get_one(&entry.fields, "maxweight"),
healthchange: get_one(&entry.fields, "healthchange"),
behaviour: get_one(&entry.fields, "behaviour"),
script: get_script(entry),
raw_extra,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildingDef {
pub id: String,
pub group: String,
pub objectid: Option<String>,
pub req: Vec<String>,
pub buildspace: Option<String>,
pub atobject: Vec<String>,
pub script: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub raw_extra: HashMap<String, Vec<String>>,
}
impl TryFrom<&InfEntry> for BuildingDef {
type Error = RegistryError;
fn try_from(entry: &InfEntry) -> Result<Self, Self::Error> {
let id = get_one(&entry.fields, "id")
.ok_or_else(|| RegistryError::MissingField("id".into()))?;
let group = get_one(&entry.fields, "group")
.ok_or_else(|| RegistryError::MissingField("group".into()))?;
const KNOWN: &[&str] = &[
"id", "group", "objectid", "req", "buildspace", "atobject",
];
let raw_extra = extract_extra(&entry.fields, KNOWN);
Ok(BuildingDef {
id,
group,
objectid: get_one(&entry.fields, "objectid"),
req: get_many(&entry.fields, "req"),
buildspace: get_one(&entry.fields, "buildspace"),
atobject: get_many(&entry.fields, "atobject"),
script: get_script(entry),
raw_extra,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CombiDef {
pub id: String,
pub req: Vec<String>,
pub r#gen: Vec<String>,
pub genname: Option<String>,
pub script: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub raw_extra: HashMap<String, Vec<String>>,
}
impl TryFrom<&InfEntry> for CombiDef {
type Error = RegistryError;
fn try_from(entry: &InfEntry) -> Result<Self, Self::Error> {
let combi = entry
.combi
.as_ref()
.ok_or(RegistryError::NotACombi)?;
let id = get_one(&combi.fields, "id")
.ok_or_else(|| RegistryError::MissingField("id".into()))?;
const KNOWN: &[&str] = &["id", "req", "gen", "genname"];
let raw_extra = extract_extra(&combi.fields, KNOWN);
Ok(CombiDef {
id,
req: get_many(&combi.fields, "req"),
r#gen: get_many(&combi.fields, "gen"),
genname: get_one(&combi.fields, "genname"),
script: combi.script.clone(),
raw_extra,
})
}
}
fn extract_extra(
fields: &HashMap<String, Vec<String>>,
known: &[&str],
) -> HashMap<String, Vec<String>> {
let mut extra = HashMap::new();
for (k, v) in fields {
if !known.contains(&k.as_str()) {
extra.insert(k.clone(), v.clone());
}
}
extra
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InfDomain {
Items,
Objects,
Units,
Buildings,
Combinations,
Infos,
Random,
States,
Groups,
Game,
Strings,
Keys,
Lightcycle,
Credits,
SkillInfo,
Unknown(String),
}
impl fmt::Display for InfDomain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Items => write!(f, "items"),
Self::Objects => write!(f, "objects"),
Self::Units => write!(f, "units"),
Self::Buildings => write!(f, "buildings"),
Self::Combinations => write!(f, "combinations"),
Self::Infos => write!(f, "infos"),
Self::Random => write!(f, "random"),
Self::States => write!(f, "states"),
Self::Groups => write!(f, "groups"),
Self::Game => write!(f, "game"),
Self::Strings => write!(f, "strings"),
Self::Keys => write!(f, "keys"),
Self::Lightcycle => write!(f, "lightcycle"),
Self::Credits => write!(f, "credits"),
Self::SkillInfo => write!(f, "skillinfo"),
Self::Unknown(name) => write!(f, "unknown({name})"),
}
}
}
pub fn classify_inf(filename: &str) -> InfDomain {
let name = filename.rsplit('/').next().unwrap_or(filename);
let name = name.rsplit('\\').next().unwrap_or(name);
let lower = name.to_lowercase();
if lower.starts_with("items_") || lower == "items.inf" {
InfDomain::Items
} else if lower.starts_with("objects_") || lower == "objects.inf" {
InfDomain::Objects
} else if lower == "units.inf" {
InfDomain::Units
} else if lower == "buildings.inf" {
InfDomain::Buildings
} else if lower.starts_with("combinations") {
InfDomain::Combinations
} else if lower == "infos.inf" {
InfDomain::Infos
} else if lower.starts_with("random_") {
InfDomain::Random
} else if lower == "states.inf" {
InfDomain::States
} else if lower == "groups.inf" {
InfDomain::Groups
} else if lower == "game.inf" {
InfDomain::Game
} else if lower == "strings.inf" {
InfDomain::Strings
} else if lower == "keys.inf" {
InfDomain::Keys
} else if lower == "lightcycle.inf" {
InfDomain::Lightcycle
} else if lower == "credits.inf" {
InfDomain::Credits
} else if lower.ends_with(".inf") && lower.contains("skillinfo") {
InfDomain::SkillInfo
} else {
InfDomain::Unknown(name.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::InfParser;
#[test]
fn test_convert_item() {
let input = r#"### Meat
id=9
name=Meat
group=food
icon=gfx\meat.bmp
model=gfx\meat.b3d
scale=0.15
mat=flesh
weight=500"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let item = ItemDef::try_from(&entries[0]).unwrap();
assert_eq!(item.id, "9");
assert_eq!(item.name, "Meat");
assert_eq!(item.group, "food");
assert_eq!(item.scale, Some("0.15".into()));
assert_eq!(item.mat, Some("flesh".into()));
assert_eq!(item.weight, Some("500".into()));
assert!(item.raw_extra.is_empty());
}
#[test]
fn test_convert_item_with_script() {
let input = r#"### Meat
id=9
name=Meat
group=food
icon=gfx\meat.bmp
model=gfx\meat.b3d
script=start
on:eat {
eat 5,20,10,0;
}
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
let item = ItemDef::try_from(&entries[0]).unwrap();
assert_eq!(item.id, "9");
assert!(item.script.as_ref().unwrap().contains("on:eat"));
}
#[test]
fn test_convert_object() {
let input = r#"### Tree
id=10
name=Tree
group=tree
icon=gfx\tree01.bmp
model=gfx\tree01.b3d
mat=wood
health=600
find=15,20,3
behaviour=tree"#;
let entries = InfParser::parse_str(input).unwrap();
let obj = ObjectDef::try_from(&entries[0]).unwrap();
assert_eq!(obj.id, "10");
assert_eq!(obj.find, vec!["15,20,3"]);
assert_eq!(obj.behaviour, Some("tree".into()));
}
#[test]
fn test_convert_unit() {
let input = r#"### Player
id=1
name=Player
group=human
icon=gfx\strandedguy.bmp
model=gfx\strandedguy.b3d
speed=1.6
health=100
damage=3"#;
let entries = InfParser::parse_str(input).unwrap();
let unit = UnitDef::try_from(&entries[0]).unwrap();
assert_eq!(unit.id, "1");
assert_eq!(unit.speed, Some("1.6".into()));
assert_eq!(unit.health, Some("100".into()));
}
#[test]
fn test_convert_building() {
let input = r#"### Tent
id=1
group=building
objectid=184
req=97"#;
let entries = InfParser::parse_str(input).unwrap();
let bld = BuildingDef::try_from(&entries[0]).unwrap();
assert_eq!(bld.id, "1");
assert_eq!(bld.objectid, Some("184".into()));
assert_eq!(bld.req, vec!["97"]);
}
#[test]
fn test_convert_combi() {
let input = r#"### Make fire
combi=start
id=makefire
req=107
req=24
gen=107
gen=24
genname=make fire
combi=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let combi = CombiDef::try_from(&entries[0]).unwrap();
assert_eq!(combi.id, "makefire");
assert_eq!(combi.req, vec!["107", "24"]);
assert_eq!(combi.r#gen, vec!["107", "24"]);
assert_eq!(combi.genname, Some("make fire".into()));
}
#[test]
fn test_classify_items() {
assert_eq!(classify_inf("items_edible.inf"), InfDomain::Items);
assert_eq!(classify_inf("items.inf"), InfDomain::Items);
assert_eq!(classify_inf("items_weapons.inf"), InfDomain::Items);
}
#[test]
fn test_classify_objects() {
assert_eq!(classify_inf("objects_trees.inf"), InfDomain::Objects);
assert_eq!(classify_inf("objects.inf"), InfDomain::Objects);
}
#[test]
fn test_classify_combinations() {
assert_eq!(
classify_inf("combinations_basic.inf"),
InfDomain::Combinations
);
assert_eq!(classify_inf("combinations.inf"), InfDomain::Combinations);
}
#[test]
fn test_classify_other() {
assert_eq!(classify_inf("units.inf"), InfDomain::Units);
assert_eq!(classify_inf("buildings.inf"), InfDomain::Buildings);
assert_eq!(classify_inf("infos.inf"), InfDomain::Infos);
assert_eq!(classify_inf("states.inf"), InfDomain::States);
assert_eq!(classify_inf("groups.inf"), InfDomain::Groups);
assert_eq!(classify_inf("random_01_endless_e.inf"), InfDomain::Random);
assert_eq!(classify_inf("random_05_raptors.inf"), InfDomain::Random);
}
#[test]
fn test_classify_unknown() {
assert_eq!(
classify_inf("game.inf"),
InfDomain::Game
);
assert_eq!(
classify_inf("strings.inf"),
InfDomain::Strings
);
assert_eq!(
classify_inf("keys.inf"),
InfDomain::Keys
);
assert_eq!(
classify_inf("lightcycle.inf"),
InfDomain::Lightcycle
);
assert_eq!(
classify_inf("credits.inf"),
InfDomain::Credits
);
assert_eq!(
classify_inf("settings.cfg"),
InfDomain::Unknown("settings.cfg".into())
);
}
#[test]
fn test_convert_item_unknown_field_in_raw_extra() {
let input = r#"### Custom item
id=999
name=Custom
group=misc
icon=gfx\custom.bmp
model=gfx\custom.b3d
mycustomfield=hello"#;
let entries = InfParser::parse_str(input).unwrap();
let item = ItemDef::try_from(&entries[0]).unwrap();
assert_eq!(item.raw_extra.get("mycustomfield").unwrap()[0], "hello");
}
}