Skip to main content

openstranded_common_objects/
object_def.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// Collision mode for a world object.
6///
7/// Determines how the player and units interact with the object.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10pub enum CollisionMode {
11    /// No collision — the object can be walked through.
12    None = 0,
13    /// Normal solid collision.
14    Normal = 1,
15    /// Climbable surface (ladders, vines, …).
16    Climbable = 2,
17    /// Wall collision (blocks movement, but projectiles pass?).
18    Wall = 3,
19}
20
21impl CollisionMode {
22    /// Parse from an integer value (0–3).
23    #[must_use]
24    pub fn from_inf(n: u32) -> Self {
25        match n {
26            0 => Self::None,
27            2 => Self::Climbable,
28            3 => Self::Wall,
29            _ => Self::Normal,
30        }
31    }
32}
33
34impl Default for CollisionMode {
35    fn default() -> Self {
36        Self::Normal
37    }
38}
39
40/// Per-axis scale factors for the object's 3D model.
41#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
42pub struct ObjectScale {
43    /// X-axis scale.
44    pub x: f32,
45    /// Y-axis scale.
46    pub y: f32,
47    /// Z-axis scale.
48    pub z: f32,
49}
50
51impl ObjectScale {
52    /// Create a uniform scale (same value on all axes).
53    #[must_use]
54    pub const fn uniform(v: f32) -> Self {
55        Self { x: v, y: v, z: v }
56    }
57}
58
59impl Default for ObjectScale {
60    fn default() -> Self {
61        Self::uniform(1.0)
62    }
63}
64
65/// How the object's state (animation/growth offset) is determined.
66#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum ObjectState {
69    /// Random offset (default). Corresponds to `state=random`.
70    Random,
71    /// Fixed offsets provided as three floats.
72    Fixed(f32, f32, f32),
73}
74
75impl Default for ObjectState {
76    fn default() -> Self {
77        Self::Random
78    }
79}
80
81/// Periodic item-spawn configuration.
82///
83/// Defines what items an object periodically spawns into the world.
84///
85/// # `.inf` format
86///
87/// ```text
88/// spawn=item_id,rate_days,xz_radius,y_radius,y_offset,limit,count
89/// ```
90#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
91pub struct SpawnDef {
92    /// Item type ID to spawn.
93    pub item_id: u32,
94    /// Spawn interval in days.
95    pub rate_days: u32,
96    /// Horizontal spawn radius.
97    pub xz_radius: f32,
98    /// Vertical spawn radius.
99    pub y_radius: f32,
100    /// Vertical spawn offset.
101    pub y_offset: f32,
102    /// Maximum number of spawned items at once.
103    pub limit: u32,
104    /// Number of items per spawn event.
105    pub count: u32,
106}
107
108impl SpawnDef {
109    /// Parse from a comma-separated string.
110    ///
111    /// Format: `item_id,rate_days,xz_radius,y_radius,y_offset,limit,count`
112    #[must_use]
113    pub fn from_inf(s: &str) -> Option<Self> {
114        let parts: Vec<&str> = s.split(',').collect();
115        if parts.len() != 7 {
116            return None;
117        }
118        Some(Self {
119            item_id: parts[0].trim().parse().ok()?,
120            rate_days: parts[1].trim().parse().ok()?,
121            xz_radius: parts[2].trim().parse().ok()?,
122            y_radius: parts[3].trim().parse().ok()?,
123            y_offset: parts[4].trim().parse().ok()?,
124            limit: parts[5].trim().parse().ok()?,
125            count: parts[6].trim().parse().ok()?,
126        })
127    }
128}
129
130/// Item-harvest / search configuration.
131///
132/// Defines what items can be found when searching this object.
133///
134/// # `.inf` format
135///
136/// ```text
137/// find=item_type,ratio,max[,min[,required_item_type]]
138/// ```
139#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
140pub struct HarvestDef {
141    /// Item type ID that can be found.
142    pub item_id: u32,
143    /// Search ratio / frequency weight.
144    pub ratio: u32,
145    /// Maximum number of items that can be found.
146    pub max: u32,
147    /// Minimum number of items (default 1).
148    pub min: u32,
149    /// Required tool/item type to find this (0 = no requirement).
150    pub required_item: u32,
151}
152
153impl HarvestDef {
154    /// Parse from a comma-separated string.
155    ///
156    /// Accepts 3, 4, or 5 components:
157    /// - `item_id,ratio,max`
158    /// - `item_id,ratio,max,min`
159    /// - `item_id,ratio,max,min,required_item`
160    #[must_use]
161    pub fn from_inf(s: &str) -> Self {
162        let parts: Vec<&str> = s.split(',').collect();
163        let item_id = parts.first().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
164        let ratio = parts.get(1).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
165        let max = parts.get(2).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
166        let min = parts.get(3).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
167        let required_item = parts.get(4).and_then(|p| p.trim().parse().ok()).unwrap_or(0);
168
169        // Apply the same clamping as the original Blitz3D code
170        let ratio = if ratio <= 0 { 1 } else { ratio };
171        let max = if max <= 1 { 1 } else { max };
172        let min = if min <= 1 { 1 } else { min };
173        let min = if min >= max { max } else { min };
174
175        Self {
176            item_id,
177            ratio,
178            max,
179            min,
180            required_item,
181        }
182    }
183}
184
185/// Full definition of a single world-object type.
186///
187/// Represents one entry from an `objects*.inf` file.
188///
189/// # `.inf` fields mapped
190///
191/// | `.inf` field | Struct field | Notes |
192/// |-------------|--------------|-------|
193/// | `id` | [`id`](Self::id) | Required |
194/// | `name` | [`name`](Self::name) | Required |
195/// | `group` | [`group`](Self::group) | |
196/// | `icon` | [`icon`](Self::icon) | |
197/// | `model` | [`model`](Self::model) | |
198/// | `behaviour` | [`behaviour`](Self::behaviour) | |
199/// | `col` | [`collision_mode`](Self::collision_mode) | 0–3 |
200/// | `health` | [`health`](Self::health) | |
201/// | `healthchange` | [`health_change`](Self::health_change) | |
202/// | `mat` | [`material`](Self::material) | |
203/// | `fx` | [`fx`](Self::fx) | Blitz3D FX flags |
204/// | `scale` / `x` / `y` / `z` | [`scale`](Self::scale) | |
205/// | `color` / `r` / `g` / `b` | [`color`](Self::color) | |
206/// | `alpha` | [`alpha`](Self::alpha) | |
207/// | `shine` | [`shininess`](Self::shininess) | |
208/// | `swayspeed` | [`sway_speed`](Self::sway_speed) | |
209/// | `swaypower` | [`sway_power`](Self::sway_power) | |
210/// | `maxweight` | [`max_weight`](Self::max_weight) | |
211/// | `state` | [`state`](Self::state) | |
212/// | `align` | [`align`](Self::align) | |
213/// | `autofade` | [`auto_fade`](Self::auto_fade) | |
214/// | `detailtex` | [`detail_tex`](Self::detail_tex) | |
215/// | `searchratio` / `findratio` | [`search_ratio`](Self::search_ratio) | |
216/// | `growtime` | [`grow_time`](Self::grow_time) | |
217/// | `spawn` | [`spawn`](Self::spawn) | |
218/// | `find` | [`harvest`](Self::harvest) | Multiple values |
219/// | `script` | [`script`](Self::script) | Block |
220/// | `description` | [`description`](Self::description) | Block |
221/// | `editor` | [`in_editor`](Self::in_editor) | |
222#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
223pub struct ObjectDef {
224    // ── Identity ────────────────────────────────────────────────────
225    /// Unique numeric identifier.
226    pub id: u32,
227
228    /// Display name.
229    pub name: String,
230
231    /// Group / category string (e.g. `"palm"`, `"tree"`, `"stone"`, `"building"`).
232    #[serde(default)]
233    pub group: String,
234
235    // ── Visual ──────────────────────────────────────────────────────
236    /// Path to the icon texture.
237    #[serde(default)]
238    pub icon: Option<String>,
239
240    /// Path to the 3D model.
241    #[serde(default)]
242    pub model: Option<String>,
243
244    /// Behaviour type string (e.g. `"tree"`, `"cover"`, `"buildingsite"`, …).
245    #[serde(default)]
246    pub behaviour: Option<String>,
247
248    /// 3D model scale.
249    #[serde(default)]
250    pub scale: ObjectScale,
251
252    /// RGB colour tint.
253    #[serde(default)]
254    pub color: Option<[u8; 3]>,
255
256    /// Blitz3D FX flags.
257    #[serde(default)]
258    pub fx: Option<u32>,
259
260    /// Alpha transparency (0–1).
261    #[serde(default = "default_alpha")]
262    pub alpha: f32,
263
264    /// Shininess / specular intensity.
265    #[serde(default)]
266    pub shininess: Option<f32>,
267
268    /// Auto-fade distance in Blitz3D units.
269    #[serde(default = "default_autofade")]
270    pub auto_fade: u32,
271
272    /// Detail texture path.
273    #[serde(default)]
274    pub detail_tex: Option<String>,
275
276    // ── Physics / collision ─────────────────────────────────────────
277    /// Collision mode.
278    #[serde(default)]
279    pub collision_mode: CollisionMode,
280
281    /// Material type string (e.g. `"wood"`, `"stone"`, `"flesh"`).
282    #[serde(default)]
283    pub material: String,
284
285    // ── Gameplay ────────────────────────────────────────────────────
286    /// Maximum hit points.
287    #[serde(default = "default_health")]
288    pub health: f32,
289
290    /// Health change per interaction tick.
291    #[serde(default)]
292    pub health_change: Option<f32>,
293
294    /// Object sway speed (animation).
295    #[serde(default)]
296    pub sway_speed: Option<f32>,
297
298    /// Object sway power (animation amplitude).
299    #[serde(default = "default_sway_power")]
300    pub sway_power: f32,
301
302    /// Maximum inventory weight this object can store.
303    #[serde(default = "default_max_weight")]
304    pub max_weight: u32,
305
306    /// State mode (random animation offset or fixed values).
307    #[serde(default)]
308    pub state: ObjectState,
309
310    /// Alignment mode (0 = normal, 1 = water surface, 2 = water pipe).
311    #[serde(default)]
312    pub align: u32,
313
314    /// Item search / find ratio.
315    #[serde(default = "default_search_ratio")]
316    pub search_ratio: f32,
317
318    /// Days to grow to full size.
319    #[serde(default = "default_grow_time")]
320    pub grow_time: u32,
321
322    /// Periodic item-spawn configuration.
323    #[serde(default)]
324    pub spawn: Option<SpawnDef>,
325
326    /// Items that can be harvested from this object.
327    #[serde(default)]
328    pub harvest: Vec<HarvestDef>,
329
330    // ── Scripting ───────────────────────────────────────────────────
331    /// Script code attached to this object.
332    #[serde(default)]
333    pub script: Option<String>,
334
335    /// Description text for the editor / tooltip.
336    #[serde(default)]
337    pub description: Option<String>,
338
339    /// Whether this object appears in the map editor.
340    #[serde(default = "default_true")]
341    pub in_editor: bool,
342}
343
344// ── Default values matching the original Blitz3D code ──────────────
345
346const fn default_alpha() -> f32 {
347    1.0
348}
349
350const fn default_autofade() -> u32 {
351    500
352}
353
354const fn default_health() -> f32 {
355    500.0
356}
357
358const fn default_sway_power() -> f32 {
359    1.0
360}
361
362const fn default_max_weight() -> u32 {
363    100000
364}
365
366const fn default_search_ratio() -> f32 {
367    30.0
368}
369
370const fn default_grow_time() -> u32 {
371    10
372}
373
374const fn default_true() -> bool {
375    true
376}
377
378// ── Parsing helpers ────────────────────────────────────────────────
379
380fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
381    fields.get(key)?.first().map(String::as_str)
382}
383
384fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
385    first_str(fields, key).map(ToOwned::to_owned)
386}
387
388fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
389    first_str(fields, key)?.parse().ok()
390}
391
392fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
393    first_str(fields, key)?.parse().ok()
394}
395
396fn parse_color(s: &str) -> Option<[u8; 3]> {
397    let parts: Vec<&str> = s.split(',').collect();
398    if parts.len() != 3 {
399        return None;
400    }
401    Some([
402        parts[0].trim().parse().ok()?,
403        parts[1].trim().parse().ok()?,
404        parts[2].trim().parse().ok()?,
405    ])
406}
407
408fn parse_harvest(fields: &HashMap<String, Vec<String>>) -> Vec<HarvestDef> {
409    fields
410        .get("find")
411        .map(|vals| vals.iter().map(|v| HarvestDef::from_inf(v)).collect())
412        .unwrap_or_default()
413}
414
415impl ObjectDef {
416    /// Construct an `ObjectDef` from raw `.inf` fields.
417    ///
418    /// Returns `None` if required fields (`id`, `name`) are missing.
419    #[must_use]
420    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
421        let id = first_u32(fields, "id")?;
422        let name = first_string(fields, "name")?;
423
424        let group = first_string(fields, "group").unwrap_or_default();
425        let icon = first_string(fields, "icon");
426        let model = first_string(fields, "model");
427        let behaviour = first_string(fields, "behaviour");
428        let material = first_string(fields, "mat").unwrap_or_default();
429
430        // Scale
431        let scale_uniform = first_f32(fields, "scale");
432        let scale_x = first_f32(fields, "x");
433        let scale_y = first_f32(fields, "y");
434        let scale_z = first_f32(fields, "z");
435        let scale = ObjectScale {
436            x: scale_x.or(scale_uniform).unwrap_or(1.0),
437            y: scale_y.or(scale_uniform).unwrap_or(1.0),
438            z: scale_z.or(scale_uniform).unwrap_or(1.0),
439        };
440
441        // Color
442        let color = first_str(fields, "color")
443            .and_then(parse_color)
444            .or_else(|| {
445                let r = first_u32(fields, "r")? as u8;
446                let g = first_u32(fields, "g")? as u8;
447                let b = first_u32(fields, "b")? as u8;
448                Some([r, g, b])
449            });
450
451        let fx = first_u32(fields, "fx");
452        let alpha = first_f32(fields, "alpha").unwrap_or(1.0);
453        let shininess = first_f32(fields, "shine");
454        let auto_fade = first_u32(fields, "autofade").unwrap_or(500);
455        let detail_tex = first_string(fields, "detailtex");
456
457        let collision_mode = first_u32(fields, "col")
458            .map(CollisionMode::from_inf)
459            .unwrap_or_default();
460
461        let health = first_f32(fields, "health").unwrap_or(500.0);
462        let health_change = first_f32(fields, "healthchange");
463
464        let sway_speed = first_f32(fields, "swayspeed");
465        let sway_power = first_f32(fields, "swaypower").unwrap_or(1.0);
466
467        let max_weight = first_u32(fields, "maxweight").unwrap_or(100000);
468
469        // State
470        let state = match first_str(fields, "state") {
471            Some("random") | None => ObjectState::Random,
472            Some(s) => {
473                let parts: Vec<&str> = s.split(',').collect();
474                if parts.len() == 3 {
475                    if let (Ok(a), Ok(b), Ok(c)) = (
476                        parts[0].trim().parse(),
477                        parts[1].trim().parse(),
478                        parts[2].trim().parse(),
479                    ) {
480                        ObjectState::Fixed(a, b, c)
481                    } else {
482                        ObjectState::Random
483                    }
484                } else {
485                    ObjectState::Random
486                }
487            }
488        };
489
490        let align = first_u32(fields, "align").unwrap_or(0);
491        let search_ratio = first_f32(fields, "searchratio")
492            .or_else(|| first_f32(fields, "findratio"))
493            .unwrap_or(30.0);
494        let grow_time = first_u32(fields, "growtime").unwrap_or(10);
495
496        // Spawn
497        let spawn = first_str(fields, "spawn").and_then(SpawnDef::from_inf);
498
499        // Harvest (find)
500        let harvest = parse_harvest(fields);
501
502        // In editor
503        let in_editor = first_u32(fields, "editor").map_or(true, |v| v != 0);
504
505        // Script and description are block-based; leave as None
506        let script = None;
507        let description = None;
508
509        Some(Self {
510            id,
511            name,
512            group,
513            icon,
514            model,
515            behaviour,
516            scale,
517            color,
518            fx,
519            alpha,
520            shininess,
521            auto_fade,
522            detail_tex,
523            collision_mode,
524            material,
525            health,
526            health_change,
527            sway_speed,
528            sway_power,
529            max_weight,
530            state,
531            align,
532            search_ratio,
533            grow_time,
534            spawn,
535            harvest,
536            script,
537            description,
538            in_editor,
539        })
540    }
541
542    /// Attach a script (builder-style).
543    #[must_use]
544    pub fn with_script(mut self, script: Option<String>) -> Self {
545        self.script = script;
546        self
547    }
548
549    /// Attach a description (builder-style).
550    #[must_use]
551    pub fn with_description(mut self, description: Option<String>) -> Self {
552        self.description = description;
553        self
554    }
555}
556
557// ── Tests ──────────────────────────────────────────────────────────
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562
563    #[test]
564    fn test_collision_mode_from_inf() {
565        assert_eq!(CollisionMode::from_inf(0), CollisionMode::None);
566        assert_eq!(CollisionMode::from_inf(1), CollisionMode::Normal);
567        assert_eq!(CollisionMode::from_inf(2), CollisionMode::Climbable);
568        assert_eq!(CollisionMode::from_inf(3), CollisionMode::Wall);
569        assert_eq!(CollisionMode::from_inf(99), CollisionMode::Normal);
570    }
571
572    #[test]
573    fn test_object_scale_uniform() {
574        let s = ObjectScale::uniform(2.5);
575        assert!((s.x - 2.5).abs() < 1e-6);
576        assert!((s.y - 2.5).abs() < 1e-6);
577        assert!((s.z - 2.5).abs() < 1e-6);
578    }
579
580    #[test]
581    fn test_spawn_def_from_inf() {
582        let spawn = SpawnDef::from_inf("14,3,15,3,125,3,1").unwrap();
583        assert_eq!(spawn.item_id, 14);
584        assert_eq!(spawn.rate_days, 3);
585        assert!((spawn.xz_radius - 15.0).abs() < 1e-6);
586        assert!((spawn.y_radius - 3.0).abs() < 1e-6);
587        assert!((spawn.y_offset - 125.0).abs() < 1e-6);
588        assert_eq!(spawn.limit, 3);
589        assert_eq!(spawn.count, 1);
590    }
591
592    #[test]
593    fn test_spawn_def_invalid() {
594        assert!(SpawnDef::from_inf("14,3").is_none());
595        assert!(SpawnDef::from_inf("").is_none());
596    }
597
598    #[test]
599    fn test_harvest_def_minimal() {
600        let h = HarvestDef::from_inf("15,15,3");
601        assert_eq!(h.item_id, 15);
602        assert_eq!(h.ratio, 15);
603        assert_eq!(h.max, 3);
604        assert_eq!(h.min, 1);
605        assert_eq!(h.required_item, 0);
606    }
607
608    #[test]
609    fn test_harvest_def_full() {
610        let h = HarvestDef::from_inf("107,150,3,1,28");
611        assert_eq!(h.item_id, 107);
612        assert_eq!(h.ratio, 150);
613        assert_eq!(h.max, 3);
614        assert_eq!(h.min, 1);
615        assert_eq!(h.required_item, 28);
616    }
617
618    #[test]
619    fn test_object_from_inf_minimal() {
620        let mut fields = HashMap::new();
621        fields.insert("id".into(), vec!["1".into()]);
622        fields.insert("name".into(), vec!["Palm".into()]);
623
624        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
625        assert_eq!(obj.id, 1);
626        assert_eq!(obj.name, "Palm");
627        assert_eq!(obj.group, "");
628        assert_eq!(obj.collision_mode, CollisionMode::Normal);
629        assert!((obj.health - 500.0).abs() < 1e-6);
630        assert_eq!(obj.state, ObjectState::Random);
631        assert!(obj.in_editor);
632    }
633
634    #[test]
635    fn test_object_from_inf_full() {
636        let mut fields = HashMap::new();
637        fields.insert("id".into(), vec!["8".into()]);
638        fields.insert("name".into(), vec!["Banana Palm".into()]);
639        fields.insert("group".into(), vec!["palm".into()]);
640        fields.insert("icon".into(), vec!["gfx/bananapalm.png".into()]);
641        fields.insert("model".into(), vec!["gfx/bananapalm.glb".into()]);
642        fields.insert("behaviour".into(), vec!["tree".into()]);
643        fields.insert("col".into(), vec!["1".into()]);
644        fields.insert("health".into(), vec!["300".into()]);
645        fields.insert("mat".into(), vec!["wood".into()]);
646        fields.insert("fx".into(), vec!["16".into()]);
647        fields.insert("scale".into(), vec!["2.5".into()]);
648        fields.insert("swayspeed".into(), vec!["1.5".into()]);
649        fields.insert("swaypower".into(), vec!["2".into()]);
650        fields.insert("spawn".into(), vec!["14,3,15,3,125,3,1".into()]);
651        fields.insert("find".into(), vec!["15,15,3".into()]);
652
653        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
654        assert_eq!(obj.id, 8);
655        assert_eq!(obj.name, "Banana Palm");
656        assert_eq!(obj.group, "palm");
657        assert_eq!(obj.behaviour.as_deref(), Some("tree"));
658        assert!((obj.scale.x - 2.5).abs() < 1e-6);
659        assert!((obj.scale.y - 2.5).abs() < 1e-6);
660        assert!((obj.scale.z - 2.5).abs() < 1e-6);
661        assert!((obj.health - 300.0).abs() < 1e-6);
662        assert_eq!(obj.material, "wood");
663        assert_eq!(obj.fx, Some(16));
664        assert_eq!(obj.spawn.unwrap().item_id, 14);
665        assert_eq!(obj.harvest.len(), 1);
666        assert_eq!(obj.harvest[0].item_id, 15);
667    }
668
669    #[test]
670    fn test_object_missing_id() {
671        let fields = HashMap::new();
672        assert!(ObjectDef::from_inf_fields(&fields).is_none());
673    }
674
675    #[test]
676    fn test_object_with_color() {
677        let mut fields = HashMap::new();
678        fields.insert("id".into(), vec!["5".into()]);
679        fields.insert("name".into(), vec!["Red Flower".into()]);
680        fields.insert("color".into(), vec!["255,0,0".into()]);
681
682        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
683        assert_eq!(obj.color, Some([255, 0, 0]));
684    }
685
686    #[test]
687    fn test_object_with_individual_color() {
688        let mut fields = HashMap::new();
689        fields.insert("id".into(), vec!["5".into()]);
690        fields.insert("name".into(), vec!["Colored".into()]);
691        fields.insert("r".into(), vec!["128".into()]);
692        fields.insert("g".into(), vec!["64".into()]);
693        fields.insert("b".into(), vec!["32".into()]);
694
695        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
696        assert_eq!(obj.color, Some([128, 64, 32]));
697    }
698
699    #[test]
700    fn test_object_with_individual_scale() {
701        let mut fields = HashMap::new();
702        fields.insert("id".into(), vec!["1".into()]);
703        fields.insert("name".into(), vec!["Stretched".into()]);
704        fields.insert("x".into(), vec!["2".into()]);
705        fields.insert("y".into(), vec!["3".into()]);
706        fields.insert("z".into(), vec!["4".into()]);
707
708        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
709        assert!((obj.scale.x - 2.0).abs() < 1e-6);
710        assert!((obj.scale.y - 3.0).abs() < 1e-6);
711        assert!((obj.scale.z - 4.0).abs() < 1e-6);
712    }
713
714    #[test]
715    fn test_object_state_random() {
716        let mut fields = HashMap::new();
717        fields.insert("id".into(), vec!["1".into()]);
718        fields.insert("name".into(), vec!["Random".into()]);
719        fields.insert("state".into(), vec!["random".into()]);
720
721        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
722        assert_eq!(obj.state, ObjectState::Random);
723    }
724
725    #[test]
726    fn test_object_state_fixed() {
727        let mut fields = HashMap::new();
728        fields.insert("id".into(), vec!["1".into()]);
729        fields.insert("name".into(), vec!["Fixed".into()]);
730        fields.insert("state".into(), vec!["10,20,30".into()]);
731
732        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
733        assert_eq!(obj.state, ObjectState::Fixed(10.0, 20.0, 30.0));
734    }
735
736    #[test]
737    fn test_object_with_script_and_description() {
738        let mut fields = HashMap::new();
739        fields.insert("id".into(), vec!["150".into()]);
740        fields.insert("name".into(), vec!["Building Site".into()]);
741
742        let obj = ObjectDef::from_inf_fields(&fields)
743            .unwrap()
744            .with_script(Some("on:hit { msg \"test\"; }".into()))
745            .with_description(Some("A place to build".into()));
746
747        assert_eq!(
748            obj.script.as_deref(),
749            Some("on:hit { msg \"test\"; }")
750        );
751        assert_eq!(obj.description.as_deref(), Some("A place to build"));
752    }
753
754    #[test]
755    fn test_serde_derives_compile() {
756        let obj = ObjectDef {
757            id: 1,
758            name: "test".into(),
759            group: "test".into(),
760            icon: None,
761            model: None,
762            behaviour: None,
763            scale: ObjectScale::default(),
764            color: None,
765            fx: None,
766            alpha: 1.0,
767            shininess: None,
768            auto_fade: 500,
769            detail_tex: None,
770            collision_mode: CollisionMode::Normal,
771            material: "wood".into(),
772            health: 100.0,
773            health_change: None,
774            sway_speed: None,
775            sway_power: 1.0,
776            max_weight: 100000,
777            state: ObjectState::Random,
778            align: 0,
779            search_ratio: 30.0,
780            grow_time: 10,
781            spawn: None,
782            harvest: vec![],
783            script: None,
784            description: None,
785            in_editor: true,
786        };
787        assert_eq!(obj.id, 1);
788    }
789}