openstranded-common-building 0.1.0

OpenStranded building domain types: BuildingDef, BuildingGroup, BuildSpace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Category of a building recipe.
///
/// Mapped from the `group=` field in `buildings.inf`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuildingGroup {
    /// Regular buildings (huts, fences, shelters, …).
    Building,
    /// Storage containers (chests, shelves, …).
    Storage,
    /// Production facilities (furnace, workbench, still, …).
    Production,
    /// Any other group not covered by the standard categories.
    #[serde(untagged)]
    Custom(String),
}

impl BuildingGroup {
    /// Parse a group string from `.inf` files.
    #[must_use]
    pub fn from_inf(s: &str) -> Self {
        match s.trim() {
            "building" => Self::Building,
            "storage" => Self::Storage,
            "production" => Self::Production,
            other => Self::Custom(other.to_owned()),
        }
    }

    /// Return the canonical string representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Building => "building",
            Self::Storage => "storage",
            Self::Production => "production",
            Self::Custom(s) => s.as_str(),
        }
    }
}

impl Default for BuildingGroup {
    fn default() -> Self {
        Self::Building
    }
}

impl std::fmt::Display for BuildingGroup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where a building can be placed.
///
/// Mapped from the `buildspace=` field in `buildings.inf`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuildSpace {
    /// Solid ground (the default).
    Land,
    /// Both on land and in water.
    LandAndWater,
    /// In deep water.
    Water,
    /// On the shoreline.
    Shore,
    /// On a hill.
    Hill,
    /// In shallow water.
    ShallowWater,
    /// Next to a specific object type (`atobject=` defines which).
    AtObject,
}

impl BuildSpace {
    /// Parse a build space string from `.inf` files.
    #[must_use]
    pub fn from_inf(s: &str) -> Option<Self> {
        match s.trim() {
            "land" => Some(Self::Land),
            "land and water" => Some(Self::LandAndWater),
            "water" => Some(Self::Water),
            "shore" => Some(Self::Shore),
            "hill" => Some(Self::Hill),
            "shallow water" => Some(Self::ShallowWater),
            "at object" => Some(Self::AtObject),
            _ => None,
        }
    }
}

/// A single material requirement for a building recipe.
///
/// # `.inf` format
///
/// ```text
/// req=item_id[,count]
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildingRequirement {
    /// Item type ID (matches `ItemDef.id`).
    pub item_id: u32,

    /// Number of items required (default 1).
    #[serde(default = "default_count")]
    pub count: u32,
}

const fn default_count() -> u32 {
    1
}

impl BuildingRequirement {
    /// Parse a requirement from a raw `req=` value string.
    #[must_use]
    pub fn from_inf_value(s: &str) -> Self {
        let parts: Vec<&str> = s.splitn(2, ',').collect();
        let item_id = parts.first().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
        let count = parts
            .get(1)
            .and_then(|p| p.trim().parse().ok())
            .unwrap_or(1);
        Self { item_id, count }
    }
}

/// A single building recipe definition.
///
/// Represents one entry from a `buildings*.inf` file.
///
/// # `.inf` structure
///
/// ```text
/// id=N
/// group=...
/// objectid=N       (or unitid=N for units)
/// req=item_id,count
/// buildspace=...
/// atobject=N
/// buildingsite=N
/// script=start
///     ...
/// script=end
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildingDef {
    /// Unique numeric identifier for this building recipe.
    pub id: u32,

    /// Category group.
    #[serde(default)]
    pub group: BuildingGroup,

    /// Object type ID that will be created when built.
    /// Mutually exclusive with [`unit_id`](Self::unit_id).
    #[serde(default)]
    pub object_id: Option<u32>,

    /// Unit type ID that will be created when built.
    /// Mutually exclusive with [`object_id`](Self::object_id).
    #[serde(default)]
    pub unit_id: Option<u32>,

    /// Materials required to build this structure.
    #[serde(default)]
    pub requirements: Vec<BuildingRequirement>,

    /// Where this building can be placed.
    #[serde(default)]
    pub build_space: Option<BuildSpace>,

    /// Object type ID of the building site (buildplace) to use.
    #[serde(default)]
    pub building_site: Option<u32>,

    /// Object type IDs that must exist nearby for construction.
    #[serde(default)]
    pub at_objects: Vec<u32>,

    /// Optional script executed when the building is finished.
    #[serde(default)]
    pub script: Option<String>,
}

// ── Field parsing helpers ──────────────────────────────────────────

fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
    fields.get(key)?.first().map(String::as_str)
}

fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
    first_str(fields, key).map(ToOwned::to_owned)
}

fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
    first_str(fields, key)?.parse().ok()
}

fn parse_requirements(fields: &HashMap<String, Vec<String>>) -> Vec<BuildingRequirement> {
    fields
        .get("req")
        .map(|vals| {
            vals.iter()
                .map(|v| BuildingRequirement::from_inf_value(v))
                .collect()
        })
        .unwrap_or_default()
}

fn parse_u32_list(fields: &HashMap<String, Vec<String>>, key: &str) -> Vec<u32> {
    fields
        .get(key)
        .map(|vals| {
            vals.iter()
                .filter_map(|v| v.trim().parse().ok())
                .collect()
        })
        .unwrap_or_default()
}

impl BuildingDef {
    /// Construct a `BuildingDef` from the raw fields of a parsed `.inf`
    /// entry.
    ///
    /// Unknown or unparseable fields are silently ignored; missing
    /// required fields (`id`) return `None`.
    #[must_use]
    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
        let id = first_u32(fields, "id")?;

        let group = first_str(fields, "group")
            .map(BuildingGroup::from_inf)
            .unwrap_or_default();

        let object_id = first_u32(fields, "objectid");
        let unit_id = first_u32(fields, "unitid");

        let requirements = parse_requirements(fields);

        let build_space = first_str(fields, "buildspace").and_then(BuildSpace::from_inf);

        let building_site = first_u32(fields, "buildingsite");

        let at_objects = parse_u32_list(fields, "atobject");

        // Script is usually in a block; we leave it as None and let
        // the caller attach it via `with_script()`.
        let script = None;

        Some(Self {
            id,
            group,
            object_id,
            unit_id,
            requirements,
            build_space,
            building_site,
            at_objects,
            script,
        })
    }

    /// Attach a script to this building recipe (builder-style).
    #[must_use]
    pub fn with_script(mut self, script: Option<String>) -> Self {
        self.script = script;
        self
    }
}

// ── Tests ──────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── BuildingGroup ────────────────────────────────────────────────

    #[test]
    fn test_building_group_from_inf() {
        assert_eq!(BuildingGroup::from_inf("building"), BuildingGroup::Building);
        assert_eq!(BuildingGroup::from_inf("storage"), BuildingGroup::Storage);
        assert_eq!(BuildingGroup::from_inf("production"), BuildingGroup::Production);
        assert_eq!(
            BuildingGroup::from_inf("custom"),
            BuildingGroup::Custom("custom".into())
        );
    }

    #[test]
    fn test_building_group_as_str() {
        assert_eq!(BuildingGroup::Building.as_str(), "building");
        assert_eq!(BuildingGroup::Custom("fort".into()).as_str(), "fort");
    }

    #[test]
    fn test_building_group_display() {
        assert_eq!(BuildingGroup::Storage.to_string(), "storage");
    }

    // ── BuildSpace ───────────────────────────────────────────────────

    #[test]
    fn test_build_space_from_inf() {
        assert_eq!(BuildSpace::from_inf("land"), Some(BuildSpace::Land));
        assert_eq!(
            BuildSpace::from_inf("land and water"),
            Some(BuildSpace::LandAndWater)
        );
        assert_eq!(BuildSpace::from_inf("water"), Some(BuildSpace::Water));
        assert_eq!(BuildSpace::from_inf("shore"), Some(BuildSpace::Shore));
        assert_eq!(BuildSpace::from_inf("hill"), Some(BuildSpace::Hill));
        assert_eq!(
            BuildSpace::from_inf("shallow water"),
            Some(BuildSpace::ShallowWater)
        );
        assert_eq!(
            BuildSpace::from_inf("at object"),
            Some(BuildSpace::AtObject)
        );
        assert_eq!(BuildSpace::from_inf("invalid"), None);
    }

    // ── BuildingRequirement ──────────────────────────────────────────

    #[test]
    fn test_building_req_minimal() {
        let req = BuildingRequirement::from_inf_value("24");
        assert_eq!(req.item_id, 24);
        assert_eq!(req.count, 1);
    }

    #[test]
    fn test_building_req_with_count() {
        let req = BuildingRequirement::from_inf_value("24,5");
        assert_eq!(req.item_id, 24);
        assert_eq!(req.count, 5);
    }

    // ── BuildingDef ──────────────────────────────────────────────────

    #[test]
    fn test_building_from_inf_fields_minimal() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("group".into(), vec!["building".into()]);
        fields.insert("objectid".into(), vec!["184".into()]);

        let def = BuildingDef::from_inf_fields(&fields).unwrap();
        assert_eq!(def.id, 1);
        assert_eq!(def.group, BuildingGroup::Building);
        assert_eq!(def.object_id, Some(184));
        assert!(def.unit_id.is_none());
        assert!(def.requirements.is_empty());
    }

    #[test]
    fn test_building_with_requirements() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["8".into()]);
        fields.insert("group".into(), vec!["building".into()]);
        fields.insert("objectid".into(), vec!["190".into()]);
        fields.insert(
            "req".into(),
            vec!["7,10".into(), "24,25".into(), "26,30".into()],
        );
        fields.insert("buildspace".into(), vec!["at object".into()]);
        fields.insert("atobject".into(), vec!["13".into(), "16".into(), "17".into()]);

        let def = BuildingDef::from_inf_fields(&fields).unwrap();
        assert_eq!(def.requirements.len(), 3);
        assert_eq!(def.requirements[0].item_id, 7);
        assert_eq!(def.requirements[0].count, 10);
        assert_eq!(def.build_space, Some(BuildSpace::AtObject));
        assert_eq!(def.at_objects, vec![13, 16, 17]);
    }

    #[test]
    fn test_building_with_unitid() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["5".into()]);
        fields.insert("group".into(), vec!["production".into()]);
        fields.insert("unitid".into(), vec!["10".into()]);

        let def = BuildingDef::from_inf_fields(&fields).unwrap();
        assert_eq!(def.unit_id, Some(10));
        assert!(def.object_id.is_none());
        assert_eq!(def.group, BuildingGroup::Production);
    }

    #[test]
    fn test_building_missing_id() {
        let fields = HashMap::new();
        assert!(BuildingDef::from_inf_fields(&fields).is_none());
    }

    #[test]
    fn test_building_with_script() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["2".into()]);
        fields.insert("objectid".into(), vec!["165".into()]);
        fields.insert("req".into(), vec!["24,20".into(), "15,30".into()]);

        let def = BuildingDef::from_inf_fields(&fields)
            .unwrap()
            .with_script(Some("msg \"Built!\";".into()));
        assert_eq!(def.script.as_deref(), Some("msg \"Built!\";"));
    }

    #[test]
    fn test_building_with_buildingsite() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("objectid".into(), vec!["150".into()]);
        fields.insert("buildingsite".into(), vec!["150".into()]);

        let def = BuildingDef::from_inf_fields(&fields).unwrap();
        assert_eq!(def.building_site, Some(150));
    }

    #[test]
    fn test_building_serde_derives_compile() {
        let def = BuildingDef {
            id: 1,
            group: BuildingGroup::Building,
            object_id: Some(184),
            unit_id: None,
            requirements: vec![],
            build_space: None,
            building_site: None,
            at_objects: vec![],
            script: None,
        };
        assert_eq!(def.id, 1);
    }
}