openstranded-common-items 0.1.1

OpenStranded item domain types: ItemDef, ItemGroup, Material, ItemStack
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Category of an item.
///
/// Mapped from the `group=` field in `.inf` files.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ItemGroup {
    /// Raw materials (wood, stone, ore, …).
    Material,
    /// Edible items (meat, fruit, herbs, …).
    Food,
    /// Miscellaneous items (bags, quest items, decorations, …).
    Stuff,
    /// Tools (hammer, fishing rod, axe, …).
    Tool,
    /// Weapons (swords, bows, spears, …).
    Weapon,
    /// Ammunition (arrows, bullets, …).
    Ammo,
    /// Potions and drinkable liquids.
    Potion,
    /// Any other group not covered by the standard categories.
    #[serde(untagged)]
    Custom(String),
}

impl ItemGroup {
    /// Parse a group string from `.inf` files.
    #[must_use]
    pub fn from_inf(s: &str) -> Self {
        match s.trim() {
            "material" => Self::Material,
            "food" => Self::Food,
            "stuff" => Self::Stuff,
            "tool" => Self::Tool,
            "weapon" => Self::Weapon,
            "ammo" => Self::Ammo,
            "potion" => Self::Potion,
            other => Self::Custom(other.to_owned()),
        }
    }

    /// Return the canonical string representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Material => "material",
            Self::Food => "food",
            Self::Stuff => "stuff",
            Self::Tool => "tool",
            Self::Weapon => "weapon",
            Self::Ammo => "ammo",
            Self::Potion => "potion",
            Self::Custom(s) => s.as_str(),
        }
    }
}

/// Material type of an item.
///
/// Used for interactions (cutting wood, mining stone),
/// damage types, and crafting filters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Material {
    /// Wood / plant fibre.
    Wood,
    /// Stone / rock.
    Stone,
    /// Metal / ore.
    Metal,
    /// Flesh / meat / organic animal tissue.
    Flesh,
    /// Fruit / plant produce.
    Fruit,
    /// Leaf / foliage.
    Leaf,
    /// Glass / brittle.
    Glass,
    /// Dust / powder / grain.
    Dust,
    /// Water / liquid.
    Water,
    /// Dirt / soil / mud.
    Dirt,
    /// Cloth / fabric / wool.
    Cloth,
    /// No particular material / unknown.
    #[serde(rename = "none")]
    None,
    /// Any other material not covered by the standard set.
    #[serde(untagged)]
    Custom(String),
}

impl Material {
    /// Parse a material string from `.inf` files.
    #[must_use]
    pub fn from_inf(s: &str) -> Self {
        match s.trim() {
            "wood" => Self::Wood,
            "stone" => Self::Stone,
            "metal" => Self::Metal,
            "flesh" => Self::Flesh,
            "fruit" => Self::Fruit,
            "leaf" => Self::Leaf,
            "glass" => Self::Glass,
            "dust" => Self::Dust,
            "water" => Self::Water,
            "dirt" => Self::Dirt,
            "cloth" | "wool" => Self::Cloth,
            "none" => Self::None,
            other => Self::Custom(other.to_owned()),
        }
    }

    /// Return the canonical string representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Wood => "wood",
            Self::Stone => "stone",
            Self::Metal => "metal",
            Self::Flesh => "flesh",
            Self::Fruit => "fruit",
            Self::Leaf => "leaf",
            Self::Glass => "glass",
            Self::Dust => "dust",
            Self::Water => "water",
            Self::Dirt => "dirt",
            Self::Cloth => "cloth",
            Self::None => "none",
            Self::Custom(s) => s.as_str(),
        }
    }
}

// ── Defaults ───────────────────────────────────────────────────────

impl Default for ItemGroup {
    fn default() -> Self {
        Self::Material
    }
}

impl Default for Material {
    fn default() -> Self {
        Self::None
    }
}

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

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

/// Full definition of a single item type.
///
/// Represents one entry from an item `.inf` file, serialisable to/from
/// RON, JSON, or any serde-compatible format.
///
/// Most fields are optional and default to `None` — only the identity
/// fields (`id`, `name`, `icon`) are required for construction via
/// [`from_inf_fields`](ItemDef::from_inf_fields).
///
/// # Construction from `.inf` fields
///
/// ```rust
/// use std::collections::HashMap;
/// use openstranded_common_items::ItemDef;
///
/// let mut fields = HashMap::new();
/// fields.insert("id".into(), vec!["2".into()]);
/// fields.insert("name".into(), vec!["small Crystal".into()]);
/// fields.insert("icon".into(), vec!["gfx\\crystal01.bmp".into()]);
/// fields.insert("group".into(), vec!["material".into()]);
/// fields.insert("mat".into(), vec!["stone".into()]);
/// fields.insert("weight".into(), vec!["200".into()]);
///
/// let item = ItemDef::from_inf_fields(&fields).unwrap();
/// assert_eq!(item.id, 2);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemDef {
    // ── Identity ────────────────────────────────────────────────────
    /// Unique numeric identifier.
    pub id: u32,

    /// Display name.
    pub name: String,

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

    /// Path to the icon texture (`.png` after conversion).
    pub icon: String,

    /// Path to the 3D model (`.glb` after conversion).
    #[serde(default)]
    pub model: Option<String>,

    /// Base material type.
    #[serde(default)]
    pub material: Material,

    /// Weight in grams.
    #[serde(default)]
    pub weight: u32,

    /// Short description / info text.
    #[serde(default)]
    pub description: Option<String>,

    // ── Visual properties ──────────────────────────────────────────
    /// RGB colour tint.
    #[serde(default)]
    pub color: Option<[u8; 3]>,

    /// Uniform scale factor.
    #[serde(default)]
    pub scale: Option<f32>,

    /// Blitz3D FX flags.
    #[serde(default)]
    pub fx: Option<u32>,

    /// Alpha transparency.
    #[serde(default)]
    pub alpha: Option<f32>,

    /// Shininess / specular intensity.
    #[serde(default)]
    pub shininess: Option<f32>,

    /// Blend mode.
    #[serde(default)]
    pub blend: Option<u32>,

    // ── Gameplay properties ─────────────────────────────────────────
    /// Item durability / hit points.
    #[serde(default)]
    pub durability: Option<f32>,

    /// Health change when consumed.
    #[serde(default)]
    pub health_change: Option<f32>,

    /// Behaviour type string (e.g. `"throw"`, `"blade"`, `"ammo:51"`).
    #[serde(default)]
    pub behaviour: Option<String>,

    /// Damage value (number or formula string).
    #[serde(default)]
    pub damage: Option<String>,

    /// Projectile speed or weapon range.
    #[serde(default)]
    pub speed: Option<f32>,

    /// Air drag for projectiles.
    #[serde(default)]
    pub drag: Option<f32>,

    /// Fire rate / use cooldown in milliseconds.
    #[serde(default)]
    pub rate: Option<u32>,

    /// Weapon state effect (e.g. `"intoxication"`).
    #[serde(default)]
    pub weapon_state: Option<String>,

    // ── Physics / collision ─────────────────────────────────────────
    /// Pick radius for collision.
    #[serde(default)]
    pub radius: Option<f32>,

    /// Collision type index.
    #[serde(default)]
    pub collision: Option<u32>,
}

// ── .inf field parsing helpers ─────────────────────────────────────

/// Parse a colour string `"R,G,B"` into `[R, G, B]`.
fn parse_color(s: &str) -> Option<[u8; 3]> {
    let parts: Vec<&str> = s.split(',').collect();
    if parts.len() != 3 {
        return None;
    }
    Some([
        parts[0].trim().parse().ok()?,
        parts[1].trim().parse().ok()?,
        parts[2].trim().parse().ok()?,
    ])
}

/// Get the first value of a field as `&str`, if present.
fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
    fields.get(key)?.first().map(String::as_str)
}

/// Get the first value of a field parsed as `u32`.
fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
    first_str(fields, key)?.parse().ok()
}

/// Get the first value of a field parsed as `f32`.
fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
    first_str(fields, key)?.parse().ok()
}

/// Get the first value of a field as an owned `String`.
fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
    first_str(fields, key).map(ToOwned::to_owned)
}

impl ItemDef {
    /// Construct an `ItemDef` from the raw fields of a parsed `.inf` entry.
    ///
    /// This is the main entry point for WASM plugins that receive
    /// registry data in the `InfEntry` format and want to convert it
    /// to a strongly-typed `ItemDef`.
    ///
    /// Unknown or unparseable fields are silently ignored; missing
    /// required fields (`id`, `name`, `icon`) return `None`.
    #[must_use]
    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
        let id = first_u32(fields, "id")?;
        let name = first_string(fields, "name")?;
        let icon = first_string(fields, "icon")?;

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

        let model = first_string(fields, "model");

        let material = first_str(fields, "mat")
            .map(Material::from_inf)
            .unwrap_or_default();

        let weight = first_u32(fields, "weight")
            .or_else(|| first_u32(fields, "w"))
            .unwrap_or(0);

        let description = first_string(fields, "info");

        // Visuals
        let color = first_str(fields, "color").and_then(parse_color);
        let scale = first_f32(fields, "scale");
        let fx = first_u32(fields, "fx");
        let alpha = first_f32(fields, "alpha");
        let shininess = first_f32(fields, "shine");
        let blend = first_u32(fields, "blend");

        // Gameplay
        let durability = first_f32(fields, "health");
        let health_change = first_f32(fields, "healthchange");
        let behaviour = first_string(fields, "behaviour");
        let damage = first_string(fields, "damage");
        let speed = first_f32(fields, "speed").or_else(|| first_f32(fields, "range"));
        let drag = first_f32(fields, "drag");
        let rate = first_u32(fields, "rate");
        let weapon_state = first_string(fields, "weaponstate");

        // Physics
        let radius = first_f32(fields, "radius");
        let collision = first_u32(fields, "col");

        Some(Self {
            id,
            name,
            group,
            icon,
            model,
            material,
            weight,
            description,
            color,
            scale,
            fx,
            alpha,
            shininess,
            blend,
            durability,
            health_change,
            behaviour,
            damage,
            speed,
            drag,
            rate,
            weapon_state,
            radius,
            collision,
        })
    }
}

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

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

    #[test]
    fn test_item_group_from_inf() {
        assert_eq!(ItemGroup::from_inf("material"), ItemGroup::Material);
        assert_eq!(ItemGroup::from_inf("food"), ItemGroup::Food);
        assert_eq!(ItemGroup::from_inf("custom"), ItemGroup::Custom("custom".into()));
    }

    #[test]
    fn test_item_group_as_str() {
        assert_eq!(ItemGroup::Material.as_str(), "material");
        assert_eq!(ItemGroup::Custom("quest".into()).as_str(), "quest");
    }

    #[test]
    fn test_material_from_inf() {
        assert_eq!(Material::from_inf("wood"), Material::Wood);
        assert_eq!(Material::from_inf("stone"), Material::Stone);
        assert_eq!(Material::from_inf("wool"), Material::Cloth);
        assert_eq!(Material::from_inf("none"), Material::None);
        assert_eq!(Material::from_inf("plastic"), Material::Custom("plastic".into()));
    }

    #[test]
    fn test_material_as_str() {
        assert_eq!(Material::Wood.as_str(), "wood");
        assert_eq!(Material::Custom("rubber".into()).as_str(), "rubber");
    }

    #[test]
    fn test_from_inf_fields_minimal() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("name".into(), vec!["Bag".into()]);
        fields.insert("icon".into(), vec!["gfx\\bag.bmp".into()]);

        let item = ItemDef::from_inf_fields(&fields).unwrap();
        assert_eq!(item.id, 1);
        assert_eq!(item.name, "Bag");
        assert_eq!(item.group, ItemGroup::Material);
        assert_eq!(item.material, Material::None);
        assert_eq!(item.weight, 0);
        assert!(item.model.is_none());
    }

    #[test]
    fn test_from_inf_fields_full() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["2".into()]);
        fields.insert("name".into(), vec!["small Crystal".into()]);
        fields.insert("group".into(), vec!["material".into()]);
        fields.insert("icon".into(), vec!["gfx\\crystal01.bmp".into()]);
        fields.insert("model".into(), vec!["gfx\\crystal01.b3d".into()]);
        fields.insert("color".into(), vec!["0,255,0".into()]);
        fields.insert("shine".into(), vec!["1".into()]);
        fields.insert("blend".into(), vec!["3".into()]);
        fields.insert("scale".into(), vec!["2".into()]);
        fields.insert("mat".into(), vec!["stone".into()]);
        fields.insert("weight".into(), vec!["200".into()]);
        fields.insert("info".into(), vec!["a small crystal".into()]);
        fields.insert("healthchange".into(), vec!["0".into()]);

        let item = ItemDef::from_inf_fields(&fields).unwrap();
        assert_eq!(item.id, 2);
        assert_eq!(item.name, "small Crystal");
        assert_eq!(item.group, ItemGroup::Material);
        assert_eq!(item.icon, "gfx\\crystal01.bmp");
        assert_eq!(item.model.as_deref(), Some("gfx\\crystal01.b3d"));
        assert_eq!(item.color, Some([0, 255, 0]));
        assert_eq!(item.shininess, Some(1.0));
        assert_eq!(item.blend, Some(3));
        assert_eq!(item.scale, Some(2.0));
        assert_eq!(item.material, Material::Stone);
        assert_eq!(item.weight, 200);
        assert_eq!(item.description.as_deref(), Some("a small crystal"));
        assert_eq!(item.health_change, Some(0.0));
    }

    #[test]
    fn test_from_inf_fields_missing_id() {
        let mut fields = HashMap::new();
        fields.insert("name".into(), vec!["No ID".into()]);
        fields.insert("icon".into(), vec!["icon.bmp".into()]);
        assert!(ItemDef::from_inf_fields(&fields).is_none());
    }

    #[test]
    fn test_parse_color() {
        assert_eq!(parse_color("255,0,128"), Some([255, 0, 128]));
        assert_eq!(parse_color("0,0,0"), Some([0, 0, 0]));
        assert_eq!(parse_color("invalid"), None);
        assert_eq!(parse_color("1,2"), None);
    }

    #[test]
    fn test_from_inf_weapon_fields() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["28".into()]);
        fields.insert("name".into(), vec!["Machete".into()]);
        fields.insert("group".into(), vec!["weapon".into()]);
        fields.insert("icon".into(), vec!["gfx\\matchet.bmp".into()]);
        fields.insert("model".into(), vec!["gfx\\matchet.b3d".into()]);
        fields.insert("scale".into(), vec!["0.2".into()]);
        fields.insert("behaviour".into(), vec!["blade".into()]);
        fields.insert("mat".into(), vec!["metal".into()]);
        fields.insert("weight".into(), vec!["1000".into()]);
        fields.insert("damage".into(), vec!["9".into()]);

        let item = ItemDef::from_inf_fields(&fields).unwrap();
        assert_eq!(item.id, 28);
        assert_eq!(item.group, ItemGroup::Weapon);
        assert_eq!(item.behaviour.as_deref(), Some("blade"));
        assert_eq!(item.damage.as_deref(), Some("9"));
        assert_eq!(item.material, Material::Metal);
    }

    #[test]
    fn test_display() {
        assert_eq!(ItemGroup::Tool.to_string(), "tool");
        assert_eq!(Material::Flesh.to_string(), "flesh");
    }

    /// Verify that ItemDef derives Serialize + Deserialize by running
    /// them through a serde_json-simulated buffer.
    /// This only compiles if both derives are well-formed.
    #[test]
    fn test_serde_derives_compile() {
        // The derives themselves are checked at compile time.
        // This test ensures the struct is constructible and the
        // serde impls don't panic on the default values.
        let _ = ItemDef {
            id: 1,
            name: "test".into(),
            group: ItemGroup::Material,
            icon: "test.png".into(),
            model: None,
            material: Material::None,
            weight: 0,
            description: None,
            color: None,
            scale: None,
            fx: None,
            alpha: None,
            shininess: None,
            blend: None,
            durability: None,
            health_change: None,
            behaviour: None,
            damage: None,
            speed: None,
            drag: None,
            rate: None,
            weapon_state: None,
            radius: None,
            collision: None,
        };
    }
}