Skip to main content

openstranded_common_units/
unit_def.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// A single animation frame range.
6///
7/// Defines which frames of the 3D model's animation sequence to use
8/// and how fast to play them.
9///
10/// # `.inf` format
11///
12/// ```text
13/// ani_xxx=start_frame,end_frame,speed
14/// ```
15#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
16pub struct AnimFrame {
17    /// First frame of the animation.
18    pub start: u32,
19    /// Last frame of the animation.
20    pub end: u32,
21    /// Playback speed multiplier.
22    pub speed: f32,
23}
24
25impl AnimFrame {
26    /// Parse from a comma-separated string `"start,end,speed"`.
27    #[must_use]
28    pub fn from_inf(s: &str) -> Option<Self> {
29        let parts: Vec<&str> = s.split(',').collect();
30        if parts.len() != 3 {
31            return None;
32        }
33        Some(Self {
34            start: parts[0].trim().parse().ok()?,
35            end: parts[1].trim().parse().ok()?,
36            speed: parts[2].trim().parse().ok()?,
37        })
38    }
39}
40
41/// All animation slots for a unit type.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct UnitAnimations {
44    /// First idle animation.
45    pub idle1: Option<AnimFrame>,
46    /// Second idle animation.
47    pub idle2: Option<AnimFrame>,
48    /// Third idle animation.
49    pub idle3: Option<AnimFrame>,
50    /// Movement / walk / run animation.
51    pub move_: Option<AnimFrame>,
52    /// Attack animation.
53    pub attack: Option<AnimFrame>,
54    /// Use / interact animation.
55    pub use_: Option<AnimFrame>,
56    /// Death animation.
57    pub die: Option<AnimFrame>,
58    /// Special animation.
59    pub special: Option<AnimFrame>,
60}
61
62impl Default for UnitAnimations {
63    fn default() -> Self {
64        Self {
65            idle1: None,
66            idle2: None,
67            idle3: None,
68            move_: None,
69            attack: None,
70            use_: None,
71            die: None,
72            special: None,
73        }
74    }
75}
76
77/// A single loot-drop entry.
78///
79/// Each entry defines what item can be looted from a unit and the
80/// maximum quantity.
81///
82/// # `.inf` format
83///
84/// ```text
85/// loot=item_id,max_count
86/// ```
87#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
88pub struct LootEntry {
89    /// Item type ID to drop.
90    pub item_id: u32,
91    /// Maximum number of items (at least 1).
92    pub max_count: u32,
93}
94
95impl LootEntry {
96    /// Parse from a comma-separated string `"item_id,max_count"`.
97    #[must_use]
98    pub fn from_inf(s: &str) -> Self {
99        let parts: Vec<&str> = s.split(',').collect();
100        let item_id = parts.first().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
101        let max_count = parts
102            .get(1)
103            .and_then(|p| p.trim().parse().ok())
104            .unwrap_or(1);
105        let max_count = if max_count <= 1 { 1 } else { max_count };
106        Self { item_id, max_count }
107    }
108}
109
110/// Vehicle-specific physics parameters.
111///
112/// These are present only for rideable units (boats, rafts, vehicles).
113#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
114pub struct VehicleParams {
115    /// Acceleration rate.
116    pub acceleration: f32,
117    /// Friction / deceleration.
118    pub friction: f32,
119    /// Steering sensitivity.
120    pub steering: u32,
121    /// Maximum dive/depth (for submarines/boats).
122    pub max_depth: u32,
123    /// Flying speed (for flying vehicles).
124    pub fly_speed: f32,
125}
126
127impl Default for VehicleParams {
128    fn default() -> Self {
129        Self {
130            acceleration: 0.03,
131            friction: 0.04,
132            steering: 2,
133            max_depth: 3,
134            fly_speed: 3.0,
135        }
136    }
137}
138
139/// Full definition of a single unit type (creature, NPC, player, vehicle).
140///
141/// Represents one entry from a `units*.inf` file.
142///
143/// # `.inf` fields mapped
144///
145/// | Field | Struct field | Notes |
146/// |-------|-------------|-------|
147/// | `id` | [`id`](Self::id) | Required |
148/// | `name` | [`name`](Self::name) | Required |
149/// | `group` | [`group`](Self::group) | |
150/// | `icon` | [`icon`](Self::icon) | |
151/// | `model` | [`model`](Self::model) | |
152/// | `behaviour` | [`behaviour`](Self::behaviour) | AI behaviour name |
153/// | `col` | [`collision_mode`](Self::collision_mode) | |
154/// | `colxr` | [`collision_x_radius`](Self::collision_x_radius) | |
155/// | `colyr` | [`collision_y_radius`](Self::collision_y_radius) | |
156/// | `health` | [`health`](Self::health) | |
157/// | `healthchange` | [`health_change`](Self::health_change) | |
158/// | `mat` | [`material`](Self::material) | |
159/// | `damage` | [`damage`](Self::damage) | |
160/// | `speed` | [`speed`](Self::speed) | |
161/// | `turnspeed` | [`turn_speed`](Self::turn_speed) | |
162/// | `eyes` | [`eye_height`](Self::eye_height) | |
163/// | `store` | [`store`](Self::store) | Hunger/thirst capacity |
164/// | `maxweight` | [`max_weight`](Self::max_weight) | |
165/// | `range` | [`perception_range`](Self::perception_range) | |
166/// | `attackrange` | [`attack_range`](Self::attack_range) | |
167/// | `territory` | [`territory`](Self::territory) | |
168/// | `searchratio` | [`search_ratio`](Self::search_ratio) | |
169/// | `loot` | [`loot`](Self::loot) | Multiple values |
170/// | `sfx` | [`sfx`](Self::sfx) | Sound set name |
171/// | `state` | [`state`](Self::state) | |
172/// | `align` | [`align`](Self::align) | |
173/// | `scale` | [`scale`](Self::scale) | |
174/// | `fx` | [`fx`](Self::fx) | |
175/// | `color` | [`color`](Self::color) | |
176/// | `alpha` | [`alpha`](Self::alpha) | |
177/// | `shine` | [`shininess`](Self::shininess) | |
178/// | `autofade` | [`auto_fade`](Self::auto_fade) | |
179/// | `rideoffset` | [`ride_offset`](Self::ride_offset) | |
180/// | `acceleration` | [`vehicle`](Self::vehicle) | |
181/// | `friction` | [`vehicle`](Self::vehicle) | |
182/// | `steering` | [`vehicle`](Self::vehicle) | |
183/// | `maxdepth` | [`vehicle`](Self::vehicle) | |
184/// | `flyspeed` | [`vehicle`](Self::vehicle) | |
185/// | `ani_idle1`…`ani_special` | [`animations`](Self::animations) | |
186/// | `loopmoveani` | [`loop_move_anim`](Self::loop_move_anim) | |
187/// | `script` | [`script`](Self::script) | Block |
188/// | `description` | [`description`](Self::description) | Block |
189/// | `editor` | [`in_editor`](Self::in_editor) | |
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub struct UnitDef {
192    // ── Identity ────────────────────────────────────────────────────
193    /// Unique numeric identifier.
194    pub id: u32,
195
196    /// Display name.
197    pub name: String,
198
199    /// Group / category (e.g. `"animal"`, `"human"`).
200    #[serde(default)]
201    pub group: String,
202
203    // ── Visual ──────────────────────────────────────────────────────
204    /// Path to the icon texture.
205    #[serde(default)]
206    pub icon: Option<String>,
207
208    /// Path to the 3D animated model.
209    #[serde(default)]
210    pub model: Option<String>,
211
212    /// Uniform scale factor.
213    #[serde(default = "default_scale")]
214    pub scale: f32,
215
216    /// Blitz3D FX flags.
217    #[serde(default)]
218    pub fx: Option<u32>,
219
220    /// RGB colour tint.
221    #[serde(default)]
222    pub color: Option<[u8; 3]>,
223
224    /// Alpha transparency.
225    #[serde(default = "default_alpha")]
226    pub alpha: f32,
227
228    /// Shininess / specular.
229    #[serde(default)]
230    pub shininess: Option<f32>,
231
232    /// Auto-fade distance.
233    #[serde(default = "default_autofade")]
234    pub auto_fade: u32,
235
236    // ── Physics / collision ─────────────────────────────────────────
237    /// Collision mode.
238    #[serde(default = "default_col")]
239    pub collision_mode: u32,
240
241    /// Collision X radius.
242    #[serde(default = "default_col_radius")]
243    pub collision_x_radius: f32,
244
245    /// Collision Y radius.
246    #[serde(default = "default_col_radius")]
247    pub collision_y_radius: f32,
248
249    // ── Gameplay stats ──────────────────────────────────────────────
250    /// Material type.
251    #[serde(default = "default_mat")]
252    pub material: String,
253
254    /// Maximum hit points.
255    #[serde(default = "default_unit_health")]
256    pub health: f32,
257
258    /// Health change per tick.
259    #[serde(default)]
260    pub health_change: Option<f32>,
261
262    /// Attack damage.
263    #[serde(default = "default_damage")]
264    pub damage: f32,
265
266    /// Movement speed.
267    #[serde(default = "default_speed")]
268    pub speed: f32,
269
270    /// Rotation speed.
271    #[serde(default = "default_turn_speed")]
272    pub turn_speed: f32,
273
274    /// Eye height (camera position for the player).
275    #[serde(default)]
276    pub eye_height: f32,
277
278    /// Maximum storable food/water capacity (hunger/thirst).
279    #[serde(default = "default_store")]
280    pub store: f32,
281
282    /// Maximum carry weight.
283    #[serde(default = "default_max_weight")]
284    pub max_weight: u32,
285
286    // ── AI behaviour ────────────────────────────────────────────────
287    /// Behaviour name (e.g. `"raptor"`, `"crab"`, `"fish"`).
288    #[serde(default)]
289    pub behaviour: Option<String>,
290
291    /// Perception / detection range.
292    #[serde(default = "default_range")]
293    pub perception_range: u32,
294
295    /// Attack range.
296    #[serde(default = "default_attack_range")]
297    pub attack_range: u32,
298
299    /// Territory radius.
300    #[serde(default)]
301    pub territory: u32,
302
303    /// Item search ratio.
304    #[serde(default)]
305    pub search_ratio: f32,
306
307    // ── Loot ────────────────────────────────────────────────────────
308    /// Items that can be looted from this unit.
309    #[serde(default)]
310    pub loot: Vec<LootEntry>,
311
312    // ── Sound ───────────────────────────────────────────────────────
313    /// Sound set name.
314    #[serde(default)]
315    pub sfx: Option<String>,
316
317    // ── State ───────────────────────────────────────────────────────
318    /// State mode (same as objects: random or fixed offsets).
319    #[serde(default)]
320    pub state: UnitState,
321
322    /// Alignment (0 = normal, 1 = water surface, …).
323    #[serde(default)]
324    pub align: u32,
325
326    // ── Vehicle / ride ──────────────────────────────────────────────
327    /// Vertical offset for the rider's position.
328    #[serde(default = "default_ride_offset")]
329    pub ride_offset: f32,
330
331    /// Vehicle physics parameters (only for rideable units).
332    #[serde(default)]
333    pub vehicle: Option<VehicleParams>,
334
335    // ── Animation ───────────────────────────────────────────────────
336    /// All animation slots.
337    #[serde(default)]
338    pub animations: UnitAnimations,
339
340    /// Whether to loop the move animation.
341    #[serde(default)]
342    pub loop_move_anim: bool,
343
344    // ── Scripting ───────────────────────────────────────────────────
345    /// Script attached to this unit.
346    #[serde(default)]
347    pub script: Option<String>,
348
349    /// Editor description text.
350    #[serde(default)]
351    pub description: Option<String>,
352
353    /// Whether this unit appears in the map editor.
354    #[serde(default = "default_true")]
355    pub in_editor: bool,
356}
357
358// ── State mode (reused from objects) ───────────────────────────────
359
360/// State offset mode for units.
361#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
362#[serde(rename_all = "snake_case")]
363pub enum UnitState {
364    /// Random offset.
365    Random,
366    /// Fixed offsets.
367    Fixed(f32, f32, f32),
368}
369
370impl Default for UnitState {
371    fn default() -> Self {
372        Self::Random
373    }
374}
375
376// ── Defaults matching Blitz3D code ─────────────────────────────────
377
378const fn default_scale() -> f32 {
379    1.0
380}
381
382const fn default_alpha() -> f32 {
383    1.0
384}
385
386const fn default_autofade() -> u32 {
387    500
388}
389
390const fn default_col() -> u32 {
391    1
392}
393
394const fn default_col_radius() -> f32 {
395    1.0
396}
397
398fn default_mat() -> String {
399    "flesh".to_owned()
400}
401
402const fn default_unit_health() -> f32 {
403    5.0
404}
405
406const fn default_damage() -> f32 {
407    1.0
408}
409
410const fn default_speed() -> f32 {
411    2.0
412}
413
414const fn default_turn_speed() -> f32 {
415    2.0
416}
417
418const fn default_store() -> f32 {
419    100.0
420}
421
422const fn default_max_weight() -> u32 {
423    100000
424}
425
426const fn default_range() -> u32 {
427    300
428}
429
430const fn default_attack_range() -> u32 {
431    50
432}
433
434const fn default_ride_offset() -> f32 {
435    30.0
436}
437
438const fn default_true() -> bool {
439    true
440}
441
442// ── Parsing helpers ────────────────────────────────────────────────
443
444fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
445    fields.get(key)?.first().map(String::as_str)
446}
447
448fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
449    first_str(fields, key).map(ToOwned::to_owned)
450}
451
452fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
453    first_str(fields, key)?.parse().ok()
454}
455
456fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
457    first_str(fields, key)?.parse().ok()
458}
459
460fn parse_color(s: &str) -> Option<[u8; 3]> {
461    let parts: Vec<&str> = s.split(',').collect();
462    if parts.len() != 3 {
463        return None;
464    }
465    Some([
466        parts[0].trim().parse().ok()?,
467        parts[1].trim().parse().ok()?,
468        parts[2].trim().parse().ok()?,
469    ])
470}
471
472fn parse_loot(fields: &HashMap<String, Vec<String>>) -> Vec<LootEntry> {
473    fields
474        .get("loot")
475        .map(|vals| vals.iter().map(|v| LootEntry::from_inf(v)).collect())
476        .unwrap_or_default()
477}
478
479impl UnitDef {
480    /// Construct a `UnitDef` from raw `.inf` fields.
481    ///
482    /// Returns `None` if required fields (`id`, `name`) are missing.
483    #[must_use]
484    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
485        let id = first_u32(fields, "id")?;
486        let name = first_string(fields, "name")?;
487
488        let group = first_string(fields, "group").unwrap_or_default();
489        let icon = first_string(fields, "icon");
490        let model = first_string(fields, "model");
491        let behaviour = first_string(fields, "behaviour");
492
493        // Visual
494        let scale = first_f32(fields, "scale").unwrap_or(1.0);
495        let fx = first_u32(fields, "fx");
496        let color = first_str(fields, "color").and_then(parse_color).or_else(|| {
497            let r = first_u32(fields, "r")? as u8;
498            let g = first_u32(fields, "g")? as u8;
499            let b = first_u32(fields, "b")? as u8;
500            Some([r, g, b])
501        });
502        let alpha = first_f32(fields, "alpha").unwrap_or(1.0);
503        let shininess = first_f32(fields, "shine");
504        let auto_fade = first_u32(fields, "autofade").unwrap_or(500);
505
506        // Collision
507        let collision_mode = first_u32(fields, "col").unwrap_or(1);
508        let collision_x_radius = first_f32(fields, "colxr").unwrap_or(1.0);
509        let collision_y_radius = first_f32(fields, "colyr").unwrap_or(1.0);
510
511        // Stats
512        let material = first_string(fields, "mat").unwrap_or_else(|| "flesh".to_owned());
513        let health = first_f32(fields, "health").unwrap_or(5.0);
514        let health_change = first_f32(fields, "healthchange");
515        let damage = first_f32(fields, "damage").unwrap_or(1.0);
516        let speed = first_f32(fields, "speed").unwrap_or(2.0);
517        let turn_speed = first_f32(fields, "turnspeed").unwrap_or(2.0);
518        let eye_height = first_f32(fields, "eyes").unwrap_or(0.0);
519        let store = first_f32(fields, "store").unwrap_or(100.0);
520        let max_weight = first_u32(fields, "maxweight").unwrap_or(100000);
521
522        // AI
523        let perception_range = first_u32(fields, "range").unwrap_or(300);
524        let attack_range = first_u32(fields, "attackrange").unwrap_or(50);
525        let territory = first_u32(fields, "territory").unwrap_or(0);
526        let search_ratio = first_f32(fields, "searchratio").unwrap_or(0.0);
527
528        // Loot
529        let loot = parse_loot(fields);
530
531        // Sound
532        let sfx = first_string(fields, "sfx");
533
534        // State
535        let state = match first_str(fields, "state") {
536            Some("random") | None => UnitState::Random,
537            Some(s) => {
538                let parts: Vec<&str> = s.split(',').collect();
539                if parts.len() == 3 {
540                    if let (Ok(a), Ok(b), Ok(c)) = (
541                        parts[0].trim().parse(),
542                        parts[1].trim().parse(),
543                        parts[2].trim().parse(),
544                    ) {
545                        UnitState::Fixed(a, b, c)
546                    } else {
547                        UnitState::Random
548                    }
549                } else {
550                    UnitState::Random
551                }
552            }
553        };
554        let align = first_u32(fields, "align").unwrap_or(0);
555
556        // Vehicle / ride
557        let ride_offset = first_f32(fields, "rideoffset").unwrap_or(30.0);
558
559        let has_any_vehicle_field = first_f32(fields, "acceleration").is_some()
560            || first_f32(fields, "friction").is_some()
561            || first_u32(fields, "steering").is_some()
562            || first_u32(fields, "maxdepth").is_some()
563            || first_f32(fields, "flyspeed").is_some();
564
565        let vehicle = if has_any_vehicle_field {
566            Some(VehicleParams {
567                acceleration: first_f32(fields, "acceleration").unwrap_or(0.03),
568                friction: first_f32(fields, "friction").unwrap_or(0.04),
569                steering: first_u32(fields, "steering").unwrap_or(2),
570                max_depth: first_u32(fields, "maxdepth").unwrap_or(3),
571                fly_speed: first_f32(fields, "flyspeed").unwrap_or(3.0),
572            })
573        } else {
574            None
575        };
576
577        // Animations
578        let animations = UnitAnimations {
579            idle1: first_str(fields, "ani_idle1").and_then(AnimFrame::from_inf),
580            idle2: first_str(fields, "ani_idle2").and_then(AnimFrame::from_inf),
581            idle3: first_str(fields, "ani_idle3").and_then(AnimFrame::from_inf),
582            move_: first_str(fields, "ani_move").and_then(AnimFrame::from_inf),
583            attack: first_str(fields, "ani_attack").and_then(AnimFrame::from_inf),
584            use_: first_str(fields, "ani_use").and_then(AnimFrame::from_inf),
585            die: first_str(fields, "ani_die").and_then(AnimFrame::from_inf),
586            special: first_str(fields, "ani_special").and_then(AnimFrame::from_inf),
587        };
588
589        let loop_move_anim = first_u32(fields, "loopmoveani").unwrap_or(0) != 0;
590
591        // Editor
592        let in_editor = first_u32(fields, "editor").map_or(true, |v| v != 0);
593
594        // Script and description are block-based
595        let script = None;
596        let description = None;
597
598        Some(Self {
599            id,
600            name,
601            group,
602            icon,
603            model,
604            scale,
605            fx,
606            color,
607            alpha,
608            shininess,
609            auto_fade,
610            collision_mode,
611            collision_x_radius,
612            collision_y_radius,
613            material,
614            health,
615            health_change,
616            damage,
617            speed,
618            turn_speed,
619            eye_height,
620            store,
621            max_weight,
622            behaviour,
623            perception_range,
624            attack_range,
625            territory,
626            search_ratio,
627            loot,
628            sfx,
629            state,
630            align,
631            ride_offset,
632            vehicle,
633            animations,
634            loop_move_anim,
635            script,
636            description,
637            in_editor,
638        })
639    }
640
641    /// Attach a script (builder-style).
642    #[must_use]
643    pub fn with_script(mut self, script: Option<String>) -> Self {
644        self.script = script;
645        self
646    }
647
648    /// Attach a description (builder-style).
649    #[must_use]
650    pub fn with_description(mut self, description: Option<String>) -> Self {
651        self.description = description;
652        self
653    }
654}
655
656// ── Tests ──────────────────────────────────────────────────────────
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661
662    // ── AnimFrame ───────────────────────────────────────────────────
663
664    #[test]
665    fn test_anim_frame_from_inf() {
666        let frame = AnimFrame::from_inf("2,3,0.06").unwrap();
667        assert_eq!(frame.start, 2);
668        assert_eq!(frame.end, 3);
669        assert!((frame.speed - 0.06).abs() < 1e-6);
670    }
671
672    #[test]
673    fn test_anim_frame_invalid() {
674        assert!(AnimFrame::from_inf("2,3").is_none());
675        assert!(AnimFrame::from_inf("").is_none());
676    }
677
678    // ── LootEntry ───────────────────────────────────────────────────
679
680    #[test]
681    fn test_loot_entry_from_inf() {
682        let loot = LootEntry::from_inf("9,3");
683        assert_eq!(loot.item_id, 9);
684        assert_eq!(loot.max_count, 3);
685    }
686
687    #[test]
688    fn test_loot_entry_minimal() {
689        let loot = LootEntry::from_inf("11");
690        assert_eq!(loot.item_id, 11);
691        assert_eq!(loot.max_count, 1);
692    }
693
694    #[test]
695    fn test_loot_entry_clamp() {
696        let loot = LootEntry::from_inf("5,0");
697        assert_eq!(loot.item_id, 5);
698        assert_eq!(loot.max_count, 1);
699    }
700
701    // ── UnitDef ─────────────────────────────────────────────────────
702
703    #[test]
704    fn test_unit_from_inf_minimal() {
705        let mut fields = HashMap::new();
706        fields.insert("id".into(), vec!["1".into()]);
707        fields.insert("name".into(), vec!["Player".into()]);
708
709        let unit = UnitDef::from_inf_fields(&fields).unwrap();
710        assert_eq!(unit.id, 1);
711        assert_eq!(unit.name, "Player");
712        assert_eq!(unit.group, "");
713        assert!((unit.health - 5.0).abs() < 1e-6);
714        assert_eq!(unit.material, "flesh");
715        assert!(unit.in_editor);
716    }
717
718    #[test]
719    fn test_unit_from_inf_full() {
720        let mut fields = HashMap::new();
721        fields.insert("id".into(), vec!["2".into()]);
722        fields.insert("name".into(), vec!["Raptor".into()]);
723        fields.insert("group".into(), vec!["animal".into()]);
724        fields.insert("icon".into(), vec!["gfx/raptor.png".into()]);
725        fields.insert("model".into(), vec!["gfx/raptor.glb".into()]);
726        fields.insert("behaviour".into(), vec!["raptor".into()]);
727        fields.insert("col".into(), vec!["1".into()]);
728        fields.insert("colxr".into(), vec!["15".into()]);
729        fields.insert("colyr".into(), vec!["30".into()]);
730        fields.insert("health".into(), vec!["110".into()]);
731        fields.insert("mat".into(), vec!["flesh".into()]);
732        fields.insert("damage".into(), vec!["24".into()]);
733        fields.insert("speed".into(), vec!["2.5".into()]);
734        fields.insert("turnspeed".into(), vec!["3.0".into()]);
735        fields.insert("eyes".into(), vec!["10".into()]);
736        fields.insert("store".into(), vec!["100".into()]);
737        fields.insert("maxweight".into(), vec!["25000".into()]);
738        fields.insert("range".into(), vec!["300".into()]);
739        fields.insert("attackrange".into(), vec!["65".into()]);
740        fields.insert("loot".into(), vec!["9,3".into(), "94,8".into()]);
741        fields.insert("sfx".into(), vec!["raptor".into()]);
742        fields.insert("scale".into(), vec!["0.5".into()]);
743        fields.insert("fx".into(), vec!["16".into()]);
744        fields.insert("ani_move".into(), vec!["2,3,0.06".into()]);
745        fields.insert("ani_attack".into(), vec!["12,16,0.07".into()]);
746        fields.insert("ani_idle1".into(), vec!["4,8,0.02".into()]);
747        fields.insert("ani_die".into(), vec!["8,11,0.05".into()]);
748
749        let unit = UnitDef::from_inf_fields(&fields).unwrap();
750        assert_eq!(unit.id, 2);
751        assert_eq!(unit.name, "Raptor");
752        assert_eq!(unit.group, "animal");
753        assert_eq!(unit.behaviour.as_deref(), Some("raptor"));
754        assert!((unit.health - 110.0).abs() < 1e-6);
755        assert!((unit.damage - 24.0).abs() < 1e-6);
756        assert!((unit.speed - 2.5).abs() < 1e-6);
757        assert!((unit.turn_speed - 3.0).abs() < 1e-6);
758        assert!((unit.eye_height - 10.0).abs() < 1e-6);
759        assert!((unit.scale - 0.5).abs() < 1e-6);
760        assert_eq!(unit.loot.len(), 2);
761        assert_eq!(unit.loot[0].item_id, 9);
762        assert_eq!(unit.loot[0].max_count, 3);
763        assert_eq!(unit.sfx.as_deref(), Some("raptor"));
764
765        // Animations
766        let anim = unit.animations.move_.unwrap();
767        assert_eq!(anim.start, 2);
768        assert_eq!(anim.end, 3);
769    }
770
771    #[test]
772    fn test_unit_missing_id() {
773        let fields = HashMap::new();
774        assert!(UnitDef::from_inf_fields(&fields).is_none());
775    }
776
777    #[test]
778    fn test_unit_with_vehicle_params() {
779        let mut fields = HashMap::new();
780        fields.insert("id".into(), vec!["10".into()]);
781        fields.insert("name".into(), vec!["Boat".into()]);
782        fields.insert("acceleration".into(), vec!["0.05".into()]);
783        fields.insert("friction".into(), vec!["0.02".into()]);
784        fields.insert("steering".into(), vec!["3".into()]);
785        fields.insert("maxdepth".into(), vec!["10".into()]);
786        fields.insert("flyspeed".into(), vec!["0".into()]);
787        fields.insert("rideoffset".into(), vec!["5".into()]);
788
789        let unit = UnitDef::from_inf_fields(&fields).unwrap();
790        let v = unit.vehicle.unwrap();
791        assert!((v.acceleration - 0.05).abs() < 1e-6);
792        assert!((v.friction - 0.02).abs() < 1e-6);
793        assert_eq!(v.steering, 3);
794        assert_eq!(v.max_depth, 10);
795        assert!((unit.ride_offset - 5.0).abs() < 1e-6);
796    }
797
798    #[test]
799    fn test_unit_with_regular_fields_no_vehicle() {
800        let mut fields = HashMap::new();
801        fields.insert("id".into(), vec!["3".into()]);
802        fields.insert("name".into(), vec!["Crab".into()]);
803        fields.insert("health".into(), vec!["40".into()]);
804
805        let unit = UnitDef::from_inf_fields(&fields).unwrap();
806        assert!(unit.vehicle.is_none());
807    }
808
809    #[test]
810    fn test_unit_with_script_and_description() {
811        let mut fields = HashMap::new();
812        fields.insert("id".into(), vec!["1".into()]);
813        fields.insert("name".into(), vec!["Player".into()]);
814
815        let unit = UnitDef::from_inf_fields(&fields)
816            .unwrap()
817            .with_script(Some("on:start { msg \"Hello\"; }".into()))
818            .with_description(Some("The player character".into()));
819
820        assert_eq!(
821            unit.script.as_deref(),
822            Some("on:start { msg \"Hello\"; }")
823        );
824        assert_eq!(unit.description.as_deref(), Some("The player character"));
825    }
826
827    #[test]
828    fn test_state_serde_derives_compile() {
829        let unit = UnitDef {
830            id: 1,
831            name: "test".into(),
832            group: String::new(),
833            icon: None,
834            model: None,
835            scale: 1.0,
836            fx: None,
837            color: None,
838            alpha: 1.0,
839            shininess: None,
840            auto_fade: 500,
841            collision_mode: 1,
842            collision_x_radius: 1.0,
843            collision_y_radius: 1.0,
844            material: "flesh".into(),
845            health: 5.0,
846            health_change: None,
847            damage: 1.0,
848            speed: 2.0,
849            turn_speed: 2.0,
850            eye_height: 0.0,
851            store: 100.0,
852            max_weight: 100000,
853            behaviour: None,
854            perception_range: 300,
855            attack_range: 50,
856            territory: 0,
857            search_ratio: 0.0,
858            loot: vec![],
859            sfx: None,
860            state: UnitState::Random,
861            align: 0,
862            ride_offset: 30.0,
863            vehicle: None,
864            animations: UnitAnimations::default(),
865            loop_move_anim: false,
866            script: None,
867            description: None,
868            in_editor: true,
869        };
870        assert_eq!(unit.id, 1);
871    }
872}