openstranded-common-objects 0.1.0

OpenStranded object domain types: ObjectDef, CollisionMode, SpawnDef, HarvestDef
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Collision mode for a world object.
///
/// Determines how the player and units interact with the object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CollisionMode {
    /// No collision — the object can be walked through.
    None = 0,
    /// Normal solid collision.
    Normal = 1,
    /// Climbable surface (ladders, vines, …).
    Climbable = 2,
    /// Wall collision (blocks movement, but projectiles pass?).
    Wall = 3,
}

impl CollisionMode {
    /// Parse from an integer value (0–3).
    #[must_use]
    pub fn from_inf(n: u32) -> Self {
        match n {
            0 => Self::None,
            2 => Self::Climbable,
            3 => Self::Wall,
            _ => Self::Normal,
        }
    }
}

impl Default for CollisionMode {
    fn default() -> Self {
        Self::Normal
    }
}

/// Per-axis scale factors for the object's 3D model.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ObjectScale {
    /// X-axis scale.
    pub x: f32,
    /// Y-axis scale.
    pub y: f32,
    /// Z-axis scale.
    pub z: f32,
}

impl ObjectScale {
    /// Create a uniform scale (same value on all axes).
    #[must_use]
    pub const fn uniform(v: f32) -> Self {
        Self { x: v, y: v, z: v }
    }
}

impl Default for ObjectScale {
    fn default() -> Self {
        Self::uniform(1.0)
    }
}

/// How the object's state (animation/growth offset) is determined.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ObjectState {
    /// Random offset (default). Corresponds to `state=random`.
    Random,
    /// Fixed offsets provided as three floats.
    Fixed(f32, f32, f32),
}

impl Default for ObjectState {
    fn default() -> Self {
        Self::Random
    }
}

/// Periodic item-spawn configuration.
///
/// Defines what items an object periodically spawns into the world.
///
/// # `.inf` format
///
/// ```text
/// spawn=item_id,rate_days,xz_radius,y_radius,y_offset,limit,count
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SpawnDef {
    /// Item type ID to spawn.
    pub item_id: u32,
    /// Spawn interval in days.
    pub rate_days: u32,
    /// Horizontal spawn radius.
    pub xz_radius: f32,
    /// Vertical spawn radius.
    pub y_radius: f32,
    /// Vertical spawn offset.
    pub y_offset: f32,
    /// Maximum number of spawned items at once.
    pub limit: u32,
    /// Number of items per spawn event.
    pub count: u32,
}

impl SpawnDef {
    /// Parse from a comma-separated string.
    ///
    /// Format: `item_id,rate_days,xz_radius,y_radius,y_offset,limit,count`
    #[must_use]
    pub fn from_inf(s: &str) -> Option<Self> {
        let parts: Vec<&str> = s.split(',').collect();
        if parts.len() != 7 {
            return None;
        }
        Some(Self {
            item_id: parts[0].trim().parse().ok()?,
            rate_days: parts[1].trim().parse().ok()?,
            xz_radius: parts[2].trim().parse().ok()?,
            y_radius: parts[3].trim().parse().ok()?,
            y_offset: parts[4].trim().parse().ok()?,
            limit: parts[5].trim().parse().ok()?,
            count: parts[6].trim().parse().ok()?,
        })
    }
}

/// Item-harvest / search configuration.
///
/// Defines what items can be found when searching this object.
///
/// # `.inf` format
///
/// ```text
/// find=item_type,ratio,max[,min[,required_item_type]]
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct HarvestDef {
    /// Item type ID that can be found.
    pub item_id: u32,
    /// Search ratio / frequency weight.
    pub ratio: u32,
    /// Maximum number of items that can be found.
    pub max: u32,
    /// Minimum number of items (default 1).
    pub min: u32,
    /// Required tool/item type to find this (0 = no requirement).
    pub required_item: u32,
}

impl HarvestDef {
    /// Parse from a comma-separated string.
    ///
    /// Accepts 3, 4, or 5 components:
    /// - `item_id,ratio,max`
    /// - `item_id,ratio,max,min`
    /// - `item_id,ratio,max,min,required_item`
    #[must_use]
    pub fn from_inf(s: &str) -> Self {
        let parts: Vec<&str> = s.split(',').collect();
        let item_id = parts.first().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
        let ratio = parts.get(1).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
        let max = parts.get(2).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
        let min = parts.get(3).and_then(|p| p.trim().parse().ok()).unwrap_or(1);
        let required_item = parts.get(4).and_then(|p| p.trim().parse().ok()).unwrap_or(0);

        // Apply the same clamping as the original Blitz3D code
        let ratio = if ratio <= 0 { 1 } else { ratio };
        let max = if max <= 1 { 1 } else { max };
        let min = if min <= 1 { 1 } else { min };
        let min = if min >= max { max } else { min };

        Self {
            item_id,
            ratio,
            max,
            min,
            required_item,
        }
    }
}

/// Full definition of a single world-object type.
///
/// Represents one entry from an `objects*.inf` file.
///
/// # `.inf` fields mapped
///
/// | `.inf` field | Struct field | Notes |
/// |-------------|--------------|-------|
/// | `id` | [`id`](Self::id) | Required |
/// | `name` | [`name`](Self::name) | Required |
/// | `group` | [`group`](Self::group) | |
/// | `icon` | [`icon`](Self::icon) | |
/// | `model` | [`model`](Self::model) | |
/// | `behaviour` | [`behaviour`](Self::behaviour) | |
/// | `col` | [`collision_mode`](Self::collision_mode) | 0–3 |
/// | `health` | [`health`](Self::health) | |
/// | `healthchange` | [`health_change`](Self::health_change) | |
/// | `mat` | [`material`](Self::material) | |
/// | `fx` | [`fx`](Self::fx) | Blitz3D FX flags |
/// | `scale` / `x` / `y` / `z` | [`scale`](Self::scale) | |
/// | `color` / `r` / `g` / `b` | [`color`](Self::color) | |
/// | `alpha` | [`alpha`](Self::alpha) | |
/// | `shine` | [`shininess`](Self::shininess) | |
/// | `swayspeed` | [`sway_speed`](Self::sway_speed) | |
/// | `swaypower` | [`sway_power`](Self::sway_power) | |
/// | `maxweight` | [`max_weight`](Self::max_weight) | |
/// | `state` | [`state`](Self::state) | |
/// | `align` | [`align`](Self::align) | |
/// | `autofade` | [`auto_fade`](Self::auto_fade) | |
/// | `detailtex` | [`detail_tex`](Self::detail_tex) | |
/// | `searchratio` / `findratio` | [`search_ratio`](Self::search_ratio) | |
/// | `growtime` | [`grow_time`](Self::grow_time) | |
/// | `spawn` | [`spawn`](Self::spawn) | |
/// | `find` | [`harvest`](Self::harvest) | Multiple values |
/// | `script` | [`script`](Self::script) | Block |
/// | `description` | [`description`](Self::description) | Block |
/// | `editor` | [`in_editor`](Self::in_editor) | |
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObjectDef {
    // ── Identity ────────────────────────────────────────────────────
    /// Unique numeric identifier.
    pub id: u32,

    /// Display name.
    pub name: String,

    /// Group / category string (e.g. `"palm"`, `"tree"`, `"stone"`, `"building"`).
    #[serde(default)]
    pub group: String,

    // ── Visual ──────────────────────────────────────────────────────
    /// Path to the icon texture.
    #[serde(default)]
    pub icon: Option<String>,

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

    /// Behaviour type string (e.g. `"tree"`, `"cover"`, `"buildingsite"`, …).
    #[serde(default)]
    pub behaviour: Option<String>,

    /// 3D model scale.
    #[serde(default)]
    pub scale: ObjectScale,

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

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

    /// Alpha transparency (0–1).
    #[serde(default = "default_alpha")]
    pub alpha: f32,

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

    /// Auto-fade distance in Blitz3D units.
    #[serde(default = "default_autofade")]
    pub auto_fade: u32,

    /// Detail texture path.
    #[serde(default)]
    pub detail_tex: Option<String>,

    // ── Physics / collision ─────────────────────────────────────────
    /// Collision mode.
    #[serde(default)]
    pub collision_mode: CollisionMode,

    /// Material type string (e.g. `"wood"`, `"stone"`, `"flesh"`).
    #[serde(default)]
    pub material: String,

    // ── Gameplay ────────────────────────────────────────────────────
    /// Maximum hit points.
    #[serde(default = "default_health")]
    pub health: f32,

    /// Health change per interaction tick.
    #[serde(default)]
    pub health_change: Option<f32>,

    /// Object sway speed (animation).
    #[serde(default)]
    pub sway_speed: Option<f32>,

    /// Object sway power (animation amplitude).
    #[serde(default = "default_sway_power")]
    pub sway_power: f32,

    /// Maximum inventory weight this object can store.
    #[serde(default = "default_max_weight")]
    pub max_weight: u32,

    /// State mode (random animation offset or fixed values).
    #[serde(default)]
    pub state: ObjectState,

    /// Alignment mode (0 = normal, 1 = water surface, 2 = water pipe).
    #[serde(default)]
    pub align: u32,

    /// Item search / find ratio.
    #[serde(default = "default_search_ratio")]
    pub search_ratio: f32,

    /// Days to grow to full size.
    #[serde(default = "default_grow_time")]
    pub grow_time: u32,

    /// Periodic item-spawn configuration.
    #[serde(default)]
    pub spawn: Option<SpawnDef>,

    /// Items that can be harvested from this object.
    #[serde(default)]
    pub harvest: Vec<HarvestDef>,

    // ── Scripting ───────────────────────────────────────────────────
    /// Script code attached to this object.
    #[serde(default)]
    pub script: Option<String>,

    /// Description text for the editor / tooltip.
    #[serde(default)]
    pub description: Option<String>,

    /// Whether this object appears in the map editor.
    #[serde(default = "default_true")]
    pub in_editor: bool,
}

// ── Default values matching the original Blitz3D code ──────────────

const fn default_alpha() -> f32 {
    1.0
}

const fn default_autofade() -> u32 {
    500
}

const fn default_health() -> f32 {
    500.0
}

const fn default_sway_power() -> f32 {
    1.0
}

const fn default_max_weight() -> u32 {
    100000
}

const fn default_search_ratio() -> f32 {
    30.0
}

const fn default_grow_time() -> u32 {
    10
}

const fn default_true() -> bool {
    true
}

// ── 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 first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
    first_str(fields, key)?.parse().ok()
}

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()?,
    ])
}

fn parse_harvest(fields: &HashMap<String, Vec<String>>) -> Vec<HarvestDef> {
    fields
        .get("find")
        .map(|vals| vals.iter().map(|v| HarvestDef::from_inf(v)).collect())
        .unwrap_or_default()
}

impl ObjectDef {
    /// Construct an `ObjectDef` from raw `.inf` fields.
    ///
    /// Returns `None` if required fields (`id`, `name`) are missing.
    #[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 group = first_string(fields, "group").unwrap_or_default();
        let icon = first_string(fields, "icon");
        let model = first_string(fields, "model");
        let behaviour = first_string(fields, "behaviour");
        let material = first_string(fields, "mat").unwrap_or_default();

        // Scale
        let scale_uniform = first_f32(fields, "scale");
        let scale_x = first_f32(fields, "x");
        let scale_y = first_f32(fields, "y");
        let scale_z = first_f32(fields, "z");
        let scale = ObjectScale {
            x: scale_x.or(scale_uniform).unwrap_or(1.0),
            y: scale_y.or(scale_uniform).unwrap_or(1.0),
            z: scale_z.or(scale_uniform).unwrap_or(1.0),
        };

        // Color
        let color = first_str(fields, "color")
            .and_then(parse_color)
            .or_else(|| {
                let r = first_u32(fields, "r")? as u8;
                let g = first_u32(fields, "g")? as u8;
                let b = first_u32(fields, "b")? as u8;
                Some([r, g, b])
            });

        let fx = first_u32(fields, "fx");
        let alpha = first_f32(fields, "alpha").unwrap_or(1.0);
        let shininess = first_f32(fields, "shine");
        let auto_fade = first_u32(fields, "autofade").unwrap_or(500);
        let detail_tex = first_string(fields, "detailtex");

        let collision_mode = first_u32(fields, "col")
            .map(CollisionMode::from_inf)
            .unwrap_or_default();

        let health = first_f32(fields, "health").unwrap_or(500.0);
        let health_change = first_f32(fields, "healthchange");

        let sway_speed = first_f32(fields, "swayspeed");
        let sway_power = first_f32(fields, "swaypower").unwrap_or(1.0);

        let max_weight = first_u32(fields, "maxweight").unwrap_or(100000);

        // State
        let state = match first_str(fields, "state") {
            Some("random") | None => ObjectState::Random,
            Some(s) => {
                let parts: Vec<&str> = s.split(',').collect();
                if parts.len() == 3 {
                    if let (Ok(a), Ok(b), Ok(c)) = (
                        parts[0].trim().parse(),
                        parts[1].trim().parse(),
                        parts[2].trim().parse(),
                    ) {
                        ObjectState::Fixed(a, b, c)
                    } else {
                        ObjectState::Random
                    }
                } else {
                    ObjectState::Random
                }
            }
        };

        let align = first_u32(fields, "align").unwrap_or(0);
        let search_ratio = first_f32(fields, "searchratio")
            .or_else(|| first_f32(fields, "findratio"))
            .unwrap_or(30.0);
        let grow_time = first_u32(fields, "growtime").unwrap_or(10);

        // Spawn
        let spawn = first_str(fields, "spawn").and_then(SpawnDef::from_inf);

        // Harvest (find)
        let harvest = parse_harvest(fields);

        // In editor
        let in_editor = first_u32(fields, "editor").map_or(true, |v| v != 0);

        // Script and description are block-based; leave as None
        let script = None;
        let description = None;

        Some(Self {
            id,
            name,
            group,
            icon,
            model,
            behaviour,
            scale,
            color,
            fx,
            alpha,
            shininess,
            auto_fade,
            detail_tex,
            collision_mode,
            material,
            health,
            health_change,
            sway_speed,
            sway_power,
            max_weight,
            state,
            align,
            search_ratio,
            grow_time,
            spawn,
            harvest,
            script,
            description,
            in_editor,
        })
    }

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

    /// Attach a description (builder-style).
    #[must_use]
    pub fn with_description(mut self, description: Option<String>) -> Self {
        self.description = description;
        self
    }
}

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

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

    #[test]
    fn test_collision_mode_from_inf() {
        assert_eq!(CollisionMode::from_inf(0), CollisionMode::None);
        assert_eq!(CollisionMode::from_inf(1), CollisionMode::Normal);
        assert_eq!(CollisionMode::from_inf(2), CollisionMode::Climbable);
        assert_eq!(CollisionMode::from_inf(3), CollisionMode::Wall);
        assert_eq!(CollisionMode::from_inf(99), CollisionMode::Normal);
    }

    #[test]
    fn test_object_scale_uniform() {
        let s = ObjectScale::uniform(2.5);
        assert!((s.x - 2.5).abs() < 1e-6);
        assert!((s.y - 2.5).abs() < 1e-6);
        assert!((s.z - 2.5).abs() < 1e-6);
    }

    #[test]
    fn test_spawn_def_from_inf() {
        let spawn = SpawnDef::from_inf("14,3,15,3,125,3,1").unwrap();
        assert_eq!(spawn.item_id, 14);
        assert_eq!(spawn.rate_days, 3);
        assert!((spawn.xz_radius - 15.0).abs() < 1e-6);
        assert!((spawn.y_radius - 3.0).abs() < 1e-6);
        assert!((spawn.y_offset - 125.0).abs() < 1e-6);
        assert_eq!(spawn.limit, 3);
        assert_eq!(spawn.count, 1);
    }

    #[test]
    fn test_spawn_def_invalid() {
        assert!(SpawnDef::from_inf("14,3").is_none());
        assert!(SpawnDef::from_inf("").is_none());
    }

    #[test]
    fn test_harvest_def_minimal() {
        let h = HarvestDef::from_inf("15,15,3");
        assert_eq!(h.item_id, 15);
        assert_eq!(h.ratio, 15);
        assert_eq!(h.max, 3);
        assert_eq!(h.min, 1);
        assert_eq!(h.required_item, 0);
    }

    #[test]
    fn test_harvest_def_full() {
        let h = HarvestDef::from_inf("107,150,3,1,28");
        assert_eq!(h.item_id, 107);
        assert_eq!(h.ratio, 150);
        assert_eq!(h.max, 3);
        assert_eq!(h.min, 1);
        assert_eq!(h.required_item, 28);
    }

    #[test]
    fn test_object_from_inf_minimal() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("name".into(), vec!["Palm".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.id, 1);
        assert_eq!(obj.name, "Palm");
        assert_eq!(obj.group, "");
        assert_eq!(obj.collision_mode, CollisionMode::Normal);
        assert!((obj.health - 500.0).abs() < 1e-6);
        assert_eq!(obj.state, ObjectState::Random);
        assert!(obj.in_editor);
    }

    #[test]
    fn test_object_from_inf_full() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["8".into()]);
        fields.insert("name".into(), vec!["Banana Palm".into()]);
        fields.insert("group".into(), vec!["palm".into()]);
        fields.insert("icon".into(), vec!["gfx/bananapalm.png".into()]);
        fields.insert("model".into(), vec!["gfx/bananapalm.glb".into()]);
        fields.insert("behaviour".into(), vec!["tree".into()]);
        fields.insert("col".into(), vec!["1".into()]);
        fields.insert("health".into(), vec!["300".into()]);
        fields.insert("mat".into(), vec!["wood".into()]);
        fields.insert("fx".into(), vec!["16".into()]);
        fields.insert("scale".into(), vec!["2.5".into()]);
        fields.insert("swayspeed".into(), vec!["1.5".into()]);
        fields.insert("swaypower".into(), vec!["2".into()]);
        fields.insert("spawn".into(), vec!["14,3,15,3,125,3,1".into()]);
        fields.insert("find".into(), vec!["15,15,3".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.id, 8);
        assert_eq!(obj.name, "Banana Palm");
        assert_eq!(obj.group, "palm");
        assert_eq!(obj.behaviour.as_deref(), Some("tree"));
        assert!((obj.scale.x - 2.5).abs() < 1e-6);
        assert!((obj.scale.y - 2.5).abs() < 1e-6);
        assert!((obj.scale.z - 2.5).abs() < 1e-6);
        assert!((obj.health - 300.0).abs() < 1e-6);
        assert_eq!(obj.material, "wood");
        assert_eq!(obj.fx, Some(16));
        assert_eq!(obj.spawn.unwrap().item_id, 14);
        assert_eq!(obj.harvest.len(), 1);
        assert_eq!(obj.harvest[0].item_id, 15);
    }

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

    #[test]
    fn test_object_with_color() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["5".into()]);
        fields.insert("name".into(), vec!["Red Flower".into()]);
        fields.insert("color".into(), vec!["255,0,0".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.color, Some([255, 0, 0]));
    }

    #[test]
    fn test_object_with_individual_color() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["5".into()]);
        fields.insert("name".into(), vec!["Colored".into()]);
        fields.insert("r".into(), vec!["128".into()]);
        fields.insert("g".into(), vec!["64".into()]);
        fields.insert("b".into(), vec!["32".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.color, Some([128, 64, 32]));
    }

    #[test]
    fn test_object_with_individual_scale() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("name".into(), vec!["Stretched".into()]);
        fields.insert("x".into(), vec!["2".into()]);
        fields.insert("y".into(), vec!["3".into()]);
        fields.insert("z".into(), vec!["4".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert!((obj.scale.x - 2.0).abs() < 1e-6);
        assert!((obj.scale.y - 3.0).abs() < 1e-6);
        assert!((obj.scale.z - 4.0).abs() < 1e-6);
    }

    #[test]
    fn test_object_state_random() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("name".into(), vec!["Random".into()]);
        fields.insert("state".into(), vec!["random".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.state, ObjectState::Random);
    }

    #[test]
    fn test_object_state_fixed() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["1".into()]);
        fields.insert("name".into(), vec!["Fixed".into()]);
        fields.insert("state".into(), vec!["10,20,30".into()]);

        let obj = ObjectDef::from_inf_fields(&fields).unwrap();
        assert_eq!(obj.state, ObjectState::Fixed(10.0, 20.0, 30.0));
    }

    #[test]
    fn test_object_with_script_and_description() {
        let mut fields = HashMap::new();
        fields.insert("id".into(), vec!["150".into()]);
        fields.insert("name".into(), vec!["Building Site".into()]);

        let obj = ObjectDef::from_inf_fields(&fields)
            .unwrap()
            .with_script(Some("on:hit { msg \"test\"; }".into()))
            .with_description(Some("A place to build".into()));

        assert_eq!(
            obj.script.as_deref(),
            Some("on:hit { msg \"test\"; }")
        );
        assert_eq!(obj.description.as_deref(), Some("A place to build"));
    }

    #[test]
    fn test_serde_derives_compile() {
        let obj = ObjectDef {
            id: 1,
            name: "test".into(),
            group: "test".into(),
            icon: None,
            model: None,
            behaviour: None,
            scale: ObjectScale::default(),
            color: None,
            fx: None,
            alpha: 1.0,
            shininess: None,
            auto_fade: 500,
            detail_tex: None,
            collision_mode: CollisionMode::Normal,
            material: "wood".into(),
            health: 100.0,
            health_change: None,
            sway_speed: None,
            sway_power: 1.0,
            max_weight: 100000,
            state: ObjectState::Random,
            align: 0,
            search_ratio: 30.0,
            grow_time: 10,
            spawn: None,
            harvest: vec![],
            script: None,
            description: None,
            in_editor: true,
        };
        assert_eq!(obj.id, 1);
    }
}