veloren_common/comp/inventory/
loadout_builder.rs

1use crate::{
2    assets::{self, AssetExt, Ron},
3    calendar::{Calendar, CalendarEvent},
4    comp::{
5        Body, arthropod, biped_large, biped_small, bird_large, bird_medium, crustacean, golem,
6        inventory::{
7            loadout::Loadout,
8            slot::{ArmorSlot, EquipSlot},
9        },
10        item::{self, Item},
11        object, quadruped_low, quadruped_medium, quadruped_small, theropod,
12    },
13    match_some,
14    resources::{Time, TimeOfDay},
15    trade::SiteInformation,
16};
17use rand::{self, Rng, prelude::IndexedRandom, seq::WeightError};
18use serde::{Deserialize, Serialize};
19use strum::EnumIter;
20use tracing::warn;
21
22type Weight = u8;
23
24#[derive(Debug)]
25pub enum SpecError {
26    LoadoutAssetError(assets::Error),
27    ItemAssetError(assets::Error),
28    ItemChoiceError(WeightError),
29    BaseChoiceError(WeightError),
30    ModularWeaponCreationError(item::modular::ModularWeaponCreationError),
31}
32
33#[derive(Debug)]
34#[cfg(test)]
35pub enum ValidationError {
36    ItemAssetError(assets::Error),
37    LoadoutAssetError(assets::Error),
38    Loop(Vec<String>),
39    ModularWeaponCreationError(item::modular::ModularWeaponCreationError),
40}
41
42#[derive(Debug, Deserialize, Clone)]
43pub enum ItemSpec {
44    Item(String),
45    /// Parameters in this variant are used to randomly create a modular weapon
46    /// that meets the provided parameters
47    ModularWeapon {
48        tool: item::tool::ToolKind,
49        material: item::Material,
50        hands: Option<item::tool::Hands>,
51    },
52    Choice(Vec<(Weight, Option<ItemSpec>)>),
53    Seasonal(Vec<(Option<CalendarEvent>, ItemSpec)>),
54}
55
56impl ItemSpec {
57    fn try_to_item(
58        &self,
59        rng: &mut impl Rng,
60        time: Option<&(TimeOfDay, Calendar)>,
61    ) -> Result<Option<Item>, SpecError> {
62        match self {
63            ItemSpec::Item(item_asset) => {
64                let item = Item::new_from_asset(item_asset).map_err(SpecError::ItemAssetError)?;
65                Ok(Some(item))
66            },
67            ItemSpec::Choice(items) => {
68                let (_, item_spec) = items
69                    .choose_weighted(rng, |(weight, _)| *weight)
70                    .map_err(SpecError::ItemChoiceError)?;
71
72                let item = if let Some(item_spec) = item_spec {
73                    item_spec.try_to_item(rng, time)?
74                } else {
75                    None
76                };
77                Ok(item)
78            },
79            ItemSpec::ModularWeapon {
80                tool,
81                material,
82                hands,
83            } => item::modular::random_weapon(*tool, *material, *hands, rng)
84                .map(Some)
85                .map_err(SpecError::ModularWeaponCreationError),
86            ItemSpec::Seasonal(specs) => specs
87                .iter()
88                .find_map(|(season, spec)| match (season, time) {
89                    (Some(season), Some((_time, calendar))) => {
90                        if calendar.is_event(*season) {
91                            Some(spec.try_to_item(rng, time))
92                        } else {
93                            None
94                        }
95                    },
96                    (Some(_season), None) => None,
97                    (None, _) => Some(spec.try_to_item(rng, time)),
98                })
99                .unwrap_or(Ok(None)),
100        }
101    }
102
103    // Check if ItemSpec is valid and can be turned into Item
104    #[cfg(test)]
105    fn validate(&self) -> Result<(), ValidationError> {
106        let mut rng = rand::rng();
107        match self {
108            ItemSpec::Item(item_asset) => Item::new_from_asset(item_asset)
109                .map(drop)
110                .map_err(ValidationError::ItemAssetError),
111            ItemSpec::Choice(choices) => {
112                // TODO: check for sanity of weights?
113                for (_weight, choice) in choices {
114                    if let Some(item) = choice {
115                        item.validate()?;
116                    }
117                }
118                Ok(())
119            },
120            ItemSpec::ModularWeapon {
121                tool,
122                material,
123                hands,
124            } => item::modular::random_weapon(*tool, *material, *hands, &mut rng)
125                .map(drop)
126                .map_err(ValidationError::ModularWeaponCreationError),
127            ItemSpec::Seasonal(specs) => {
128                specs.iter().try_for_each(|(_season, spec)| spec.validate())
129            },
130        }
131    }
132}
133
134#[derive(Debug, Deserialize, Clone)]
135pub enum Hands {
136    /// Allows to specify one pair
137    InHands((Option<ItemSpec>, Option<ItemSpec>)),
138    /// Allows specify range of choices
139    Choice(Vec<(Weight, Hands)>),
140}
141
142impl Hands {
143    fn try_to_pair(
144        &self,
145        rng: &mut impl Rng,
146        time: Option<&(TimeOfDay, Calendar)>,
147    ) -> Result<(Option<Item>, Option<Item>), SpecError> {
148        match self {
149            Hands::InHands((mainhand, offhand)) => {
150                let mut from_spec = |i: &ItemSpec| i.try_to_item(rng, time);
151
152                let mainhand = mainhand.as_ref().map(&mut from_spec).transpose()?.flatten();
153                let offhand = offhand.as_ref().map(&mut from_spec).transpose()?.flatten();
154                Ok((mainhand, offhand))
155            },
156            Hands::Choice(pairs) => {
157                let (_, pair_spec) = pairs
158                    .choose_weighted(rng, |(weight, _)| *weight)
159                    .map_err(SpecError::ItemChoiceError)?;
160
161                pair_spec.try_to_pair(rng, time)
162            },
163        }
164    }
165
166    // Check if items in Hand are valid and can be turned into Item
167    #[cfg(test)]
168    fn validate(&self) -> Result<(), ValidationError> {
169        match self {
170            Self::InHands((left, right)) => {
171                if let Some(hand) = left {
172                    hand.validate()?;
173                }
174                if let Some(hand) = right {
175                    hand.validate()?;
176                }
177                Ok(())
178            },
179            Self::Choice(choices) => {
180                // TODO: check for sanity of weights?
181                for (_weight, choice) in choices {
182                    choice.validate()?;
183                }
184                Ok(())
185            },
186        }
187    }
188}
189
190#[derive(Debug, Deserialize, Clone)]
191pub enum Base {
192    Asset(String),
193    /// NOTE: If you have the same item in multiple configs,
194    /// *first* one will have the priority
195    Combine(Vec<Base>),
196    Choice(Vec<(Weight, Base)>),
197}
198
199impl Base {
200    // Turns Base to LoadoutSpec
201    //
202    // NOTE: Don't expect it to be fully evaluated, but in some cases
203    // it may be so.
204    fn to_spec(&self, rng: &mut impl Rng) -> Result<LoadoutSpec, SpecError> {
205        match self {
206            Base::Asset(asset_specifier) => Ok(Ron::load_cloned(asset_specifier)
207                .map_err(SpecError::LoadoutAssetError)?
208                .into_inner()),
209            Base::Combine(bases) => {
210                let bases = bases.iter().map(|b| b.to_spec(rng)?.eval(rng));
211                // Get first base of combined
212                let mut current = LoadoutSpec::default();
213                for base in bases {
214                    current = current.merge(base?);
215                }
216
217                Ok(current)
218            },
219            Base::Choice(choice) => {
220                let (_, base) = choice
221                    .choose_weighted(rng, |(weight, _)| *weight)
222                    .map_err(SpecError::BaseChoiceError)?;
223
224                base.to_spec(rng)
225            },
226        }
227    }
228}
229
230// TODO: remove clone
231/// Core struct of loadout asset.
232///
233/// If you want programing API of loadout creation,
234/// use `LoadoutBuilder` instead.
235///
236/// For examples of assets, see `assets/test/loadout/ok` folder.
237#[derive(Debug, Deserialize, Clone, Default)]
238#[serde(deny_unknown_fields)]
239pub struct LoadoutSpec {
240    // Meta fields
241    pub inherit: Option<Base>,
242    // Armor
243    pub head: Option<ItemSpec>,
244    pub neck: Option<ItemSpec>,
245    pub shoulders: Option<ItemSpec>,
246    pub chest: Option<ItemSpec>,
247    pub gloves: Option<ItemSpec>,
248    pub ring1: Option<ItemSpec>,
249    pub ring2: Option<ItemSpec>,
250    pub back: Option<ItemSpec>,
251    pub belt: Option<ItemSpec>,
252    pub legs: Option<ItemSpec>,
253    pub feet: Option<ItemSpec>,
254    pub tabard: Option<ItemSpec>,
255    pub bag1: Option<ItemSpec>,
256    pub bag2: Option<ItemSpec>,
257    pub bag3: Option<ItemSpec>,
258    pub bag4: Option<ItemSpec>,
259    pub lantern: Option<ItemSpec>,
260    pub glider: Option<ItemSpec>,
261    // Weapons
262    pub active_hands: Option<Hands>,
263    pub inactive_hands: Option<Hands>,
264}
265
266impl LoadoutSpec {
267    /// Merges `self` with `base`.
268    /// If some field exists in `self` it will be used,
269    /// if no, it will be taken from `base`.
270    ///
271    /// NOTE: it uses only inheritance chain from `base`
272    /// without evaluating it.
273    /// Inheritance chain from `self` is discarded.
274    ///
275    /// # Examples
276    /// 1)
277    /// You have your asset, let's call it "a". In this asset, you have
278    /// inheritance from "b". In asset "b" you inherit from "c".
279    ///
280    /// If you load your "a" into LoadoutSpec A, and "b" into LoadoutSpec B,
281    /// and then merge A into B, you will get new LoadoutSpec that will inherit
282    /// from "c".
283    ///
284    /// 2)
285    /// You have two assets, let's call them "a" and "b".
286    /// "a" inherits from "n",
287    /// "b" inherits from "m".
288    ///
289    /// If you load "a" into A, "b" into B and then will try to merge them
290    /// you will get new LoadoutSpec that will inherit from "m".
291    /// It's error, because chain to "n" is lost!!!
292    ///
293    /// Correct way to do this will be first evaluating at least "a" and then
294    /// merge this new LoadoutSpec with "b".
295    fn merge(self, base: Self) -> Self {
296        Self {
297            inherit: base.inherit,
298            head: self.head.or(base.head),
299            neck: self.neck.or(base.neck),
300            shoulders: self.shoulders.or(base.shoulders),
301            chest: self.chest.or(base.chest),
302            gloves: self.gloves.or(base.gloves),
303            ring1: self.ring1.or(base.ring1),
304            ring2: self.ring2.or(base.ring2),
305            back: self.back.or(base.back),
306            belt: self.belt.or(base.belt),
307            legs: self.legs.or(base.legs),
308            feet: self.feet.or(base.feet),
309            tabard: self.tabard.or(base.tabard),
310            bag1: self.bag1.or(base.bag1),
311            bag2: self.bag2.or(base.bag2),
312            bag3: self.bag3.or(base.bag3),
313            bag4: self.bag4.or(base.bag4),
314            lantern: self.lantern.or(base.lantern),
315            glider: self.glider.or(base.glider),
316            active_hands: self.active_hands.or(base.active_hands),
317            inactive_hands: self.inactive_hands.or(base.inactive_hands),
318        }
319    }
320
321    /// Recursively evaluate all inheritance chain.
322    /// For example with following structure.
323    ///
324    /// ```text
325    /// A
326    /// inherit: B,
327    /// gloves: a,
328    ///
329    /// B
330    /// inherit: C,
331    /// ring1: b,
332    ///
333    /// C
334    /// inherit: None,
335    /// ring2: c
336    /// ```
337    ///
338    /// result will be
339    ///
340    /// ```text
341    /// inherit: None,
342    /// gloves: a,
343    /// ring1: b,
344    /// ring2: c,
345    /// ```
346    fn eval(self, rng: &mut impl Rng) -> Result<Self, SpecError> {
347        // Iherit loadout if needed
348        if let Some(ref base) = self.inherit {
349            let base = base.to_spec(rng)?.eval(rng);
350            Ok(self.merge(base?))
351        } else {
352            Ok(self)
353        }
354    }
355
356    // Validate loadout spec and check that it can be turned into real loadout.
357    // Checks for possible loops too.
358    //
359    // NOTE: It is stricter than needed, it will check all items
360    // even if they are overwritten.
361    // We can avoid these redundant checks by building set of all possible
362    // specs and then check them.
363    // This algorithm will be much more complex and require more memory,
364    // because if we Combine multiple Choice-s we will need to create
365    // cartesian product of specs.
366    //
367    // Also we probably don't want garbage entries anyway, even if they are
368    // unused.
369    #[cfg(test)]
370    pub fn validate(&self, history: Vec<String>) -> Result<(), ValidationError> {
371        // Helper function to traverse base.
372        //
373        // Important invariant to hold.
374        // Each time it finds new asset it appends it to history
375        // and calls spec.validate()
376        fn validate_base(base: &Base, mut history: Vec<String>) -> Result<(), ValidationError> {
377            match base {
378                Base::Asset(asset) => {
379                    // read the spec
380                    let based: LoadoutSpec = Ron::load_cloned(asset)
381                        .map_err(ValidationError::LoadoutAssetError)?
382                        .into_inner();
383
384                    // expand history
385                    history.push(asset.to_owned());
386
387                    // validate our spec
388                    based.validate(history)
389                },
390                Base::Combine(bases) => {
391                    for base in bases {
392                        validate_base(base, history.clone())?;
393                    }
394                    Ok(())
395                },
396                Base::Choice(choices) => {
397                    // TODO: check for sanity of weights?
398                    for (_weight, base) in choices {
399                        validate_base(base, history.clone())?;
400                    }
401                    Ok(())
402                },
403            }
404        }
405
406        // Scarry logic
407        //
408        // We check for duplicates on each append, and because we append on each
409        // call we can be sure we don't have any duplicates unless it's a last
410        // element.
411        // So we can check for duplicates by comparing
412        // all elements with last element.
413        // And if we found duplicate in our history we found a loop.
414        if let Some((last, tail)) = history.split_last() {
415            for asset in tail {
416                if last == asset {
417                    return Err(ValidationError::Loop(history));
418                }
419            }
420        }
421
422        if let Some(base) = &self.inherit {
423            validate_base(base, history)?
424        }
425
426        self.validate_entries()
427    }
428
429    // Validate entries in loadout spec.
430    //
431    // NOTE: this only check for items, we assume that base
432    // is validated separately.
433    //
434    // TODO: add some intelligent checks,
435    // e.g. that `head` key corresponds to Item with ItemKind::Head(_)
436    #[cfg(test)]
437    fn validate_entries(&self) -> Result<(), ValidationError> {
438        // Armor
439        if let Some(item) = &self.head {
440            item.validate()?;
441        }
442        if let Some(item) = &self.neck {
443            item.validate()?;
444        }
445        if let Some(item) = &self.shoulders {
446            item.validate()?;
447        }
448        if let Some(item) = &self.chest {
449            item.validate()?;
450        }
451        if let Some(item) = &self.gloves {
452            item.validate()?;
453        }
454        if let Some(item) = &self.ring1 {
455            item.validate()?;
456        }
457        if let Some(item) = &self.ring2 {
458            item.validate()?;
459        }
460        if let Some(item) = &self.back {
461            item.validate()?;
462        }
463        if let Some(item) = &self.belt {
464            item.validate()?;
465        }
466        if let Some(item) = &self.legs {
467            item.validate()?;
468        }
469        if let Some(item) = &self.feet {
470            item.validate()?;
471        }
472        if let Some(item) = &self.tabard {
473            item.validate()?;
474        }
475        // Misc
476        if let Some(item) = &self.bag1 {
477            item.validate()?;
478        }
479        if let Some(item) = &self.bag2 {
480            item.validate()?;
481        }
482        if let Some(item) = &self.bag3 {
483            item.validate()?;
484        }
485        if let Some(item) = &self.bag4 {
486            item.validate()?;
487        }
488        if let Some(item) = &self.lantern {
489            item.validate()?;
490        }
491        if let Some(item) = &self.glider {
492            item.validate()?;
493        }
494        // Hands, tools and weapons
495        if let Some(hands) = &self.active_hands {
496            hands.validate()?;
497        }
498        if let Some(hands) = &self.inactive_hands {
499            hands.validate()?;
500        }
501
502        Ok(())
503    }
504}
505
506#[must_use]
507pub fn make_potion_bag(quantity: u32) -> Item {
508    let mut bag = Item::new_from_asset_expect("common.items.armor.misc.bag.tiny_leather_pouch");
509    if let Some(i) = bag.slots_mut().iter_mut().next() {
510        let mut potions = Item::new_from_asset_expect("common.items.consumable.potion_big");
511        if let Err(e) = potions.set_amount(quantity) {
512            warn!("Failed to set potion quantity: {:?}", e);
513        }
514        *i = Some(potions);
515    }
516    bag
517}
518
519#[must_use]
520pub fn make_food_bag(quantity: u32) -> Item {
521    let mut bag = Item::new_from_asset_expect("common.items.armor.misc.bag.tiny_leather_pouch");
522    if let Some(i) = bag.slots_mut().iter_mut().next() {
523        let mut food = Item::new_from_asset_expect("common.items.food.apple_stick");
524        if let Err(e) = food.set_amount(quantity) {
525            warn!("Failed to set food quantity: {:?}", e);
526        }
527        *i = Some(food);
528    }
529    bag
530}
531
532#[must_use]
533pub fn default_chest(body: &Body) -> Option<&'static str> {
534    match body {
535        Body::BipedLarge(body) => match_some!(body.species,
536            biped_large::Species::Mindflayer => "common.items.npc_armor.biped_large.mindflayer",
537            biped_large::Species::Minotaur => "common.items.npc_armor.biped_large.minotaur",
538            biped_large::Species::Tidalwarrior => "common.items.npc_armor.biped_large.tidal_warrior",
539            biped_large::Species::Yeti => "common.items.npc_armor.biped_large.yeti",
540            biped_large::Species::Harvester => "common.items.npc_armor.biped_large.harvester",
541            biped_large::Species::Ogre
542            | biped_large::Species::Blueoni
543            | biped_large::Species::Redoni
544            | biped_large::Species::Cavetroll
545            | biped_large::Species::Mountaintroll
546            | biped_large::Species::Swamptroll
547            | biped_large::Species::Wendigo => "common.items.npc_armor.biped_large.generic",
548            biped_large::Species::Cyclops => "common.items.npc_armor.biped_large.cyclops",
549            biped_large::Species::Dullahan => "common.items.npc_armor.biped_large.dullahan",
550            biped_large::Species::Tursus => "common.items.npc_armor.biped_large.tursus",
551            biped_large::Species::Cultistwarlord => "common.items.npc_armor.biped_large.warlord",
552            biped_large::Species::Cultistwarlock => "common.items.npc_armor.biped_large.warlock",
553            biped_large::Species::Gigasfrost => "common.items.npc_armor.biped_large.gigas_frost",
554            biped_large::Species::Gigasfire => "common.items.npc_armor.biped_large.gigas_fire",
555            biped_large::Species::HaniwaGeneral => "common.items.npc_armor.biped_large.haniwageneral",
556            biped_large::Species::TerracottaBesieger
557            | biped_large::Species::TerracottaDemolisher
558            | biped_large::Species::TerracottaPunisher
559            | biped_large::Species::TerracottaPursuer
560            | biped_large::Species::Cursekeeper => "common.items.npc_armor.biped_large.terracotta",
561            biped_large::Species::Forgemaster => "common.items.npc_armor.biped_large.forgemaster",
562        ),
563        Body::BirdLarge(body) => match_some!(body.species,
564            bird_large::Species::FlameWyvern
565            | bird_large::Species::FrostWyvern
566            | bird_large::Species::CloudWyvern
567            | bird_large::Species::SeaWyvern
568            | bird_large::Species::WealdWyvern => "common.items.npc_armor.bird_large.wyvern",
569            bird_large::Species::Phoenix => "common.items.npc_armor.bird_large.phoenix",
570        ),
571        Body::BirdMedium(body) => match_some!(body.species,
572            bird_medium::Species::BloodmoonBat => "common.items.npc_armor.bird_medium.bloodmoon_bat",
573        ),
574        Body::Golem(body) => match_some!(body.species,
575            golem::Species::ClayGolem => "common.items.npc_armor.golem.claygolem",
576            golem::Species::Gravewarden => "common.items.npc_armor.golem.gravewarden",
577            golem::Species::WoodGolem => "common.items.npc_armor.golem.woodgolem",
578            golem::Species::AncientEffigy => "common.items.npc_armor.golem.ancienteffigy",
579            golem::Species::Mogwai => "common.items.npc_armor.golem.mogwai",
580            golem::Species::IronGolem => "common.items.npc_armor.golem.irongolem",
581        ),
582        Body::QuadrupedLow(body) => match_some!(body.species,
583            quadruped_low::Species::Sandshark
584            | quadruped_low::Species::Alligator
585            | quadruped_low::Species::Crocodile
586            | quadruped_low::Species::SeaCrocodile
587            | quadruped_low::Species::Icedrake
588            | quadruped_low::Species::Lavadrake
589            | quadruped_low::Species::Mossdrake => "common.items.npc_armor.generic",
590            quadruped_low::Species::Reefsnapper
591            | quadruped_low::Species::Rocksnapper
592            | quadruped_low::Species::Rootsnapper
593            | quadruped_low::Species::Tortoise
594            | quadruped_low::Species::Basilisk
595            | quadruped_low::Species::Hydra => "common.items.npc_armor.generic_high",
596            quadruped_low::Species::Dagon => "common.items.npc_armor.quadruped_low.dagon",
597        ),
598        Body::QuadrupedMedium(body) => match_some!(body.species,
599            quadruped_medium::Species::Bonerattler => "common.items.npc_armor.generic",
600            quadruped_medium::Species::Tarasque => "common.items.npc_armor.generic_high",
601            quadruped_medium::Species::ClaySteed => "common.items.npc_armor.quadruped_medium.claysteed",
602        ),
603        Body::Theropod(body) => match_some!(body.species,
604            theropod::Species::Archaeos | theropod::Species::Ntouka => "common.items.npc_armor.generic",
605            theropod::Species::Dodarock => "common.items.npc_armor.generic_high",
606        ),
607        // TODO: Check over
608        Body::Arthropod(body) => match body.species {
609            arthropod::Species::Blackwidow
610            | arthropod::Species::Cavespider
611            | arthropod::Species::Emberfly
612            | arthropod::Species::Moltencrawler
613            | arthropod::Species::Mosscrawler
614            | arthropod::Species::Sandcrawler
615            | arthropod::Species::Tarantula => None,
616            _ => Some("common.items.npc_armor.generic"),
617        },
618        Body::QuadrupedSmall(body) => match_some!(body.species,
619            quadruped_small::Species::Turtle
620            | quadruped_small::Species::Holladon
621            | quadruped_small::Species::TreantSapling
622            | quadruped_small::Species::MossySnail => "common.items.npc_armor.generic",
623        ),
624        Body::Crustacean(body) => match_some!(body.species,
625            crustacean::Species::Karkatha => "common.items.npc_armor.crustacean.karkatha",
626        ),
627        _ => None,
628    }
629}
630
631#[must_use]
632// We have many species so this function is long
633// Also we are using default tools for un-specified species so
634// it's fine to have wildcards
635#[expect(clippy::too_many_lines)]
636pub fn default_main_tool(body: &Body) -> Option<&'static str> {
637    match body {
638        Body::Golem(golem) => match_some!(golem.species,
639            golem::Species::StoneGolem => "common.items.npc_weapons.unique.stone_golems_fist",
640            golem::Species::ClayGolem => "common.items.npc_weapons.unique.clay_golem_fist",
641            golem::Species::Gravewarden => "common.items.npc_weapons.unique.gravewarden_fist",
642            golem::Species::WoodGolem => "common.items.npc_weapons.unique.wood_golem_fist",
643            golem::Species::CoralGolem => "common.items.npc_weapons.unique.coral_golem_fist",
644            golem::Species::AncientEffigy => "common.items.npc_weapons.unique.ancient_effigy_eyes",
645            golem::Species::Mogwai => "common.items.npc_weapons.unique.mogwai",
646            golem::Species::IronGolem => "common.items.npc_weapons.unique.iron_golem_fist",
647        ),
648        Body::QuadrupedMedium(quadruped_medium) => match quadruped_medium.species {
649            quadruped_medium::Species::Wolf => {
650                Some("common.items.npc_weapons.unique.quadruped_medium.wolf")
651            },
652            // Below uniques still follow quadmedhoof just with stat alterations
653            quadruped_medium::Species::Alpaca | quadruped_medium::Species::Llama => {
654                Some("common.items.npc_weapons.unique.quadruped_medium.alpaca")
655            },
656            quadruped_medium::Species::Antelope | quadruped_medium::Species::Deer => {
657                Some("common.items.npc_weapons.unique.quadruped_medium.antelope")
658            },
659            quadruped_medium::Species::Donkey | quadruped_medium::Species::Zebra => {
660                Some("common.items.npc_weapons.unique.quadruped_medium.donkey")
661            },
662            // Provide Kelpie with unique water-centered abilities
663            quadruped_medium::Species::Horse | quadruped_medium::Species::Kelpie => {
664                Some("common.items.npc_weapons.unique.quadruped_medium.horse")
665            },
666            quadruped_medium::Species::ClaySteed => {
667                Some("common.items.npc_weapons.unique.claysteed")
668            },
669            quadruped_medium::Species::Saber
670            | quadruped_medium::Species::Bonerattler
671            | quadruped_medium::Species::Lion
672            | quadruped_medium::Species::Snowleopard => {
673                Some("common.items.npc_weapons.unique.quadmedjump")
674            },
675            quadruped_medium::Species::Darkhound => {
676                Some("common.items.npc_weapons.unique.darkhound")
677            },
678            // Below uniques still follow quadmedcharge just with stat alterations
679            quadruped_medium::Species::Moose | quadruped_medium::Species::Tuskram => {
680                Some("common.items.npc_weapons.unique.quadruped_medium.moose")
681            },
682            quadruped_medium::Species::Mouflon => {
683                Some("common.items.npc_weapons.unique.quadruped_medium.mouflon")
684            },
685            quadruped_medium::Species::Akhlut
686            | quadruped_medium::Species::Dreadhorn
687            | quadruped_medium::Species::Mammoth
688            | quadruped_medium::Species::Ngoubou => {
689                Some("common.items.npc_weapons.unique.quadmedcharge")
690            },
691            quadruped_medium::Species::Grolgar => {
692                Some("common.items.npc_weapons.unique.quadruped_medium.grolgar")
693            },
694            quadruped_medium::Species::Roshwalr => Some("common.items.npc_weapons.unique.roshwalr"),
695            quadruped_medium::Species::Cattle => {
696                Some("common.items.npc_weapons.unique.quadmedbasicgentle")
697            },
698            quadruped_medium::Species::Highland | quadruped_medium::Species::Yak => {
699                Some("common.items.npc_weapons.unique.quadruped_medium.highland")
700            },
701            quadruped_medium::Species::Frostfang => {
702                Some("common.items.npc_weapons.unique.frostfang")
703            },
704            _ => Some("common.items.npc_weapons.unique.quadmedbasic"),
705        },
706        Body::QuadrupedLow(quadruped_low) => match quadruped_low.species {
707            quadruped_low::Species::Maneater => {
708                Some("common.items.npc_weapons.unique.quadruped_low.maneater")
709            },
710            quadruped_low::Species::Asp => {
711                Some("common.items.npc_weapons.unique.quadruped_low.asp")
712            },
713            quadruped_low::Species::Dagon => Some("common.items.npc_weapons.unique.dagon"),
714            quadruped_low::Species::Snaretongue => {
715                Some("common.items.npc_weapons.unique.snaretongue")
716            },
717            quadruped_low::Species::Crocodile
718            | quadruped_low::Species::SeaCrocodile
719            | quadruped_low::Species::Alligator
720            | quadruped_low::Species::Salamander
721            | quadruped_low::Species::Elbst => Some("common.items.npc_weapons.unique.quadlowtail"),
722            quadruped_low::Species::Monitor | quadruped_low::Species::Pangolin => {
723                Some("common.items.npc_weapons.unique.quadlowquick")
724            },
725            quadruped_low::Species::Lavadrake => {
726                Some("common.items.npc_weapons.unique.quadruped_low.lavadrake")
727            },
728            quadruped_low::Species::Deadwood => {
729                Some("common.items.npc_weapons.unique.quadruped_low.deadwood")
730            },
731            quadruped_low::Species::Basilisk => {
732                Some("common.items.npc_weapons.unique.quadruped_low.basilisk")
733            },
734            quadruped_low::Species::Icedrake => {
735                Some("common.items.npc_weapons.unique.quadruped_low.icedrake")
736            },
737            quadruped_low::Species::Hakulaq => {
738                Some("common.items.npc_weapons.unique.quadruped_low.hakulaq")
739            },
740            quadruped_low::Species::Tortoise => {
741                Some("common.items.npc_weapons.unique.quadruped_low.tortoise")
742            },
743            quadruped_low::Species::Driggle => Some("common.items.npc_weapons.unique.driggle"),
744            quadruped_low::Species::Rocksnapper => {
745                Some("common.items.npc_weapons.unique.rocksnapper")
746            },
747            quadruped_low::Species::Hydra => {
748                Some("common.items.npc_weapons.unique.quadruped_low.hydra")
749            },
750            _ => Some("common.items.npc_weapons.unique.quadlowbasic"),
751        },
752        Body::QuadrupedSmall(quadruped_small) => match quadruped_small.species {
753            quadruped_small::Species::TreantSapling => {
754                Some("common.items.npc_weapons.unique.treantsapling")
755            },
756            quadruped_small::Species::MossySnail => {
757                Some("common.items.npc_weapons.unique.mossysnail")
758            },
759            quadruped_small::Species::Boar | quadruped_small::Species::Truffler => {
760                Some("common.items.npc_weapons.unique.quadruped_small.boar")
761            },
762            quadruped_small::Species::Hyena => {
763                Some("common.items.npc_weapons.unique.quadruped_small.hyena")
764            },
765            quadruped_small::Species::Beaver
766            | quadruped_small::Species::Dog
767            | quadruped_small::Species::Cat
768            | quadruped_small::Species::Goat
769            | quadruped_small::Species::Holladon
770            | quadruped_small::Species::Sheep
771            | quadruped_small::Species::Seal => {
772                Some("common.items.npc_weapons.unique.quadsmallbasic")
773            },
774            _ => Some("common.items.npc_weapons.unique.quadruped_small.rodent"),
775        },
776        Body::Theropod(theropod) => match theropod.species {
777            theropod::Species::Sandraptor
778            | theropod::Species::Snowraptor
779            | theropod::Species::Woodraptor
780            | theropod::Species::Axebeak
781            | theropod::Species::Sunlizard => Some("common.items.npc_weapons.unique.theropodbird"),
782            theropod::Species::Yale => Some("common.items.npc_weapons.unique.theropod.yale"),
783            theropod::Species::Dodarock => Some("common.items.npc_weapons.unique.theropodsmall"),
784            _ => Some("common.items.npc_weapons.unique.theropodbasic"),
785        },
786        Body::Arthropod(arthropod) => match arthropod.species {
787            arthropod::Species::Hornbeetle | arthropod::Species::Stagbeetle => {
788                Some("common.items.npc_weapons.unique.arthropods.hornbeetle")
789            },
790            arthropod::Species::Emberfly => Some("common.items.npc_weapons.unique.emberfly"),
791            arthropod::Species::Cavespider => {
792                Some("common.items.npc_weapons.unique.arthropods.cavespider")
793            },
794            arthropod::Species::Sandcrawler | arthropod::Species::Mosscrawler => {
795                Some("common.items.npc_weapons.unique.arthropods.mosscrawler")
796            },
797            arthropod::Species::Moltencrawler => {
798                Some("common.items.npc_weapons.unique.arthropods.moltencrawler")
799            },
800            arthropod::Species::Weevil => Some("common.items.npc_weapons.unique.arthropods.weevil"),
801            arthropod::Species::Blackwidow => {
802                Some("common.items.npc_weapons.unique.arthropods.blackwidow")
803            },
804            arthropod::Species::Tarantula => {
805                Some("common.items.npc_weapons.unique.arthropods.tarantula")
806            },
807            arthropod::Species::Antlion => {
808                Some("common.items.npc_weapons.unique.arthropods.antlion")
809            },
810            arthropod::Species::Dagonite => {
811                Some("common.items.npc_weapons.unique.arthropods.dagonite")
812            },
813            arthropod::Species::Leafbeetle => {
814                Some("common.items.npc_weapons.unique.arthropods.leafbeetle")
815            },
816        },
817        Body::BipedLarge(biped_large) => match (biped_large.species, biped_large.body_type) {
818            (biped_large::Species::Occultsaurok, _) => {
819                Some("common.items.npc_weapons.staff.saurok_staff")
820            },
821            (biped_large::Species::Mightysaurok, _) => {
822                Some("common.items.npc_weapons.sword.saurok_sword")
823            },
824            (biped_large::Species::Slysaurok, _) => Some("common.items.npc_weapons.bow.saurok_bow"),
825            (biped_large::Species::Ogre, biped_large::BodyType::Male) => {
826                Some("common.items.npc_weapons.hammer.ogre_hammer")
827            },
828            (biped_large::Species::Ogre, biped_large::BodyType::Female) => {
829                Some("common.items.npc_weapons.staff.ogre_staff")
830            },
831            (
832                biped_large::Species::Mountaintroll
833                | biped_large::Species::Swamptroll
834                | biped_large::Species::Cavetroll,
835                _,
836            ) => Some("common.items.npc_weapons.hammer.troll_hammer"),
837            (biped_large::Species::Wendigo, _) => {
838                Some("common.items.npc_weapons.unique.wendigo_magic")
839            },
840            (biped_large::Species::Werewolf, _) => {
841                Some("common.items.npc_weapons.unique.beast_claws")
842            },
843            (biped_large::Species::Tursus, _) => {
844                Some("common.items.npc_weapons.unique.tursus_claws")
845            },
846            (biped_large::Species::Cyclops, _) => {
847                Some("common.items.npc_weapons.hammer.cyclops_hammer")
848            },
849            (biped_large::Species::Dullahan, _) => {
850                Some("common.items.npc_weapons.sword.dullahan_sword")
851            },
852            (biped_large::Species::Mindflayer, _) => {
853                Some("common.items.npc_weapons.staff.mindflayer_staff")
854            },
855            (biped_large::Species::Minotaur, _) => {
856                Some("common.items.npc_weapons.axe.minotaur_axe")
857            },
858            (biped_large::Species::Tidalwarrior, _) => {
859                Some("common.items.npc_weapons.unique.tidal_spear")
860            },
861            (biped_large::Species::Yeti, _) => Some("common.items.npc_weapons.hammer.yeti_hammer"),
862            (biped_large::Species::Harvester, _) => {
863                Some("common.items.npc_weapons.hammer.harvester_scythe")
864            },
865            (biped_large::Species::Blueoni, _) => Some("common.items.npc_weapons.axe.oni_blue_axe"),
866            (biped_large::Species::Redoni, _) => {
867                Some("common.items.npc_weapons.hammer.oni_red_hammer")
868            },
869            (biped_large::Species::Cultistwarlord, _) => {
870                Some("common.items.npc_weapons.sword.bipedlarge-cultist")
871            },
872            (biped_large::Species::Cultistwarlock, _) => {
873                Some("common.items.npc_weapons.staff.bipedlarge-cultist")
874            },
875            (biped_large::Species::Huskbrute, _) => {
876                Some("common.items.npc_weapons.unique.husk_brute")
877            },
878            (biped_large::Species::Strigoi, _) => {
879                Some("common.items.npc_weapons.unique.strigoi_claws")
880            },
881            (biped_large::Species::Executioner, _) => {
882                Some("common.items.npc_weapons.axe.executioner_axe")
883            },
884            (biped_large::Species::Gigasfrost, _) => {
885                Some("common.items.npc_weapons.axe.gigas_frost_axe")
886            },
887            (biped_large::Species::Gigasfire, _) => {
888                Some("common.items.npc_weapons.sword.gigas_fire_sword")
889            },
890            (biped_large::Species::AdletElder, _) => {
891                Some("common.items.npc_weapons.sword.adlet_elder_sword")
892            },
893            (biped_large::Species::SeaBishop, _) => {
894                Some("common.items.npc_weapons.unique.sea_bishop_sceptre")
895            },
896            (biped_large::Species::HaniwaGeneral, _) => {
897                Some("common.items.npc_weapons.sword.haniwa_general_sword")
898            },
899            (biped_large::Species::TerracottaBesieger, _) => {
900                Some("common.items.npc_weapons.bow.terracotta_besieger_bow")
901            },
902            (biped_large::Species::TerracottaDemolisher, _) => {
903                Some("common.items.npc_weapons.unique.terracotta_demolisher_fist")
904            },
905            (biped_large::Species::TerracottaPunisher, _) => {
906                Some("common.items.npc_weapons.hammer.terracotta_punisher_club")
907            },
908            (biped_large::Species::TerracottaPursuer, _) => {
909                Some("common.items.npc_weapons.sword.terracotta_pursuer_sword")
910            },
911            (biped_large::Species::Cursekeeper, _) => {
912                Some("common.items.npc_weapons.unique.cursekeeper_sceptre")
913            },
914            (biped_large::Species::Forgemaster, _) => {
915                Some("common.items.npc_weapons.hammer.forgemaster_hammer")
916            },
917        },
918        Body::Object(body) => match_some!(body,
919            object::Body::Crossbow => "common.items.npc_weapons.unique.turret",
920            object::Body::Flamethrower | object::Body::Lavathrower => {
921                "common.items.npc_weapons.unique.flamethrower"
922            },
923            object::Body::BarrelOrgan => "common.items.npc_weapons.unique.organ",
924            object::Body::TerracottaStatue => "common.items.npc_weapons.unique.terracotta_statue",
925            object::Body::HaniwaSentry => "common.items.npc_weapons.unique.haniwa_sentry",
926            object::Body::SeaLantern => "common.items.npc_weapons.unique.tidal_totem",
927            object::Body::Tornado => "common.items.npc_weapons.unique.tornado",
928            object::Body::FieryTornado => "common.items.npc_weapons.unique.fiery_tornado",
929            object::Body::GnarlingTotemRed => "common.items.npc_weapons.biped_small.gnarling.redtotem",
930            object::Body::GnarlingTotemGreen => "common.items.npc_weapons.biped_small.gnarling.greentotem",
931            object::Body::GnarlingTotemWhite => "common.items.npc_weapons.biped_small.gnarling.whitetotem",
932        ),
933        Body::BipedSmall(biped_small) => match (biped_small.species, biped_small.body_type) {
934            (biped_small::Species::Gnome, _) => {
935                Some("common.items.npc_weapons.biped_small.adlet.tracker")
936            },
937            (biped_small::Species::Bushly, _) => Some("common.items.npc_weapons.unique.bushly"),
938            (biped_small::Species::Cactid, _) => Some("common.items.npc_weapons.unique.cactid"),
939            (biped_small::Species::Irrwurz, _) => Some("common.items.npc_weapons.unique.irrwurz"),
940            (biped_small::Species::Husk, _) => Some("common.items.npc_weapons.unique.husk"),
941            (biped_small::Species::Flamekeeper, _) => {
942                Some("common.items.npc_weapons.unique.flamekeeper_staff")
943            },
944            (biped_small::Species::IronDwarf, _) => {
945                Some("common.items.npc_weapons.unique.iron_dwarf")
946            },
947            (biped_small::Species::ShamanicSpirit, _) => {
948                Some("common.items.npc_weapons.unique.shamanic_spirit")
949            },
950            (biped_small::Species::Jiangshi, _) => Some("common.items.npc_weapons.unique.jiangshi"),
951            (biped_small::Species::BloodmoonHeiress, _) => {
952                Some("common.items.npc_weapons.biped_small.vampire.bloodmoon_heiress_sword")
953            },
954            (biped_small::Species::Bloodservant, _) => {
955                Some("common.items.npc_weapons.biped_small.vampire.bloodservant_axe")
956            },
957            (biped_small::Species::Harlequin, _) => {
958                Some("common.items.npc_weapons.biped_small.vampire.harlequin_dagger")
959            },
960            (biped_small::Species::GoblinThug, _) => {
961                Some("common.items.npc_weapons.unique.goblin_thug_club")
962            },
963            (biped_small::Species::GoblinChucker, _) => {
964                Some("common.items.npc_weapons.unique.goblin_chucker")
965            },
966            (biped_small::Species::GoblinRuffian, _) => {
967                Some("common.items.npc_weapons.unique.goblin_ruffian_knife")
968            },
969            (biped_small::Species::GreenLegoom, _) => {
970                Some("common.items.npc_weapons.unique.green_legoom_rake")
971            },
972            (biped_small::Species::OchreLegoom, _) => {
973                Some("common.items.npc_weapons.unique.ochre_legoom_spade")
974            },
975            (biped_small::Species::PurpleLegoom, _) => {
976                Some("common.items.npc_weapons.unique.purple_legoom_pitchfork")
977            },
978            (biped_small::Species::RedLegoom, _) => {
979                Some("common.items.npc_weapons.unique.red_legoom_hoe")
980            },
981            _ => Some("common.items.npc_weapons.biped_small.adlet.hunter"),
982        },
983        Body::BirdLarge(bird_large) => match (bird_large.species, bird_large.body_type) {
984            (bird_large::Species::Cockatrice, _) => {
985                Some("common.items.npc_weapons.unique.birdlargebreathe")
986            },
987            (bird_large::Species::Phoenix, _) => {
988                Some("common.items.npc_weapons.unique.birdlargefire")
989            },
990            (bird_large::Species::Roc, _) => Some("common.items.npc_weapons.unique.birdlargebasic"),
991            (bird_large::Species::FlameWyvern, _) => {
992                Some("common.items.npc_weapons.unique.flamewyvern")
993            },
994            (bird_large::Species::FrostWyvern, _) => {
995                Some("common.items.npc_weapons.unique.frostwyvern")
996            },
997            (bird_large::Species::CloudWyvern, _) => {
998                Some("common.items.npc_weapons.unique.cloudwyvern")
999            },
1000            (bird_large::Species::SeaWyvern, _) => {
1001                Some("common.items.npc_weapons.unique.seawyvern")
1002            },
1003            (bird_large::Species::WealdWyvern, _) => {
1004                Some("common.items.npc_weapons.unique.wealdwyvern")
1005            },
1006        },
1007        Body::BirdMedium(bird_medium) => match bird_medium.species {
1008            bird_medium::Species::Cockatiel
1009            | bird_medium::Species::Bat
1010            | bird_medium::Species::Parrot
1011            | bird_medium::Species::Crow
1012            | bird_medium::Species::Parakeet => {
1013                Some("common.items.npc_weapons.unique.simpleflyingbasic")
1014            },
1015            bird_medium::Species::VampireBat => Some("common.items.npc_weapons.unique.vampire_bat"),
1016            bird_medium::Species::BloodmoonBat => {
1017                Some("common.items.npc_weapons.unique.bloodmoon_bat")
1018            },
1019            _ => Some("common.items.npc_weapons.unique.birdmediumbasic"),
1020        },
1021        Body::Crustacean(crustacean) => match crustacean.species {
1022            crustacean::Species::Crab | crustacean::Species::SoldierCrab => {
1023                Some("common.items.npc_weapons.unique.crab_pincer")
1024            },
1025            crustacean::Species::Karkatha => {
1026                Some("common.items.npc_weapons.unique.karkatha_pincer")
1027            },
1028        },
1029        _ => None,
1030    }
1031}
1032
1033/// Builder for character Loadouts, containing weapon and armour items belonging
1034/// to a character, along with some helper methods for loading `Item`-s and
1035/// `ItemConfig`
1036///
1037/// ```
1038/// use veloren_common::{LoadoutBuilder, comp::Item};
1039///
1040/// // Build a loadout with character starter defaults
1041/// // and a specific sword with default sword abilities
1042/// let sword = Item::new_from_asset_expect("common.items.weapons.sword.starter");
1043/// let loadout = LoadoutBuilder::empty()
1044///     .defaults()
1045///     .active_mainhand(Some(sword))
1046///     .build();
1047/// ```
1048#[derive(Clone)]
1049pub struct LoadoutBuilder(Loadout);
1050
1051#[derive(Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Debug, EnumIter)]
1052pub enum Preset {
1053    HuskSummon,
1054    BorealSummon,
1055    AshenSummon,
1056    IronDwarfSummon,
1057    ShamanicSpiritSummon,
1058    JiangshiSummon,
1059    BloodservantSummon,
1060}
1061
1062impl LoadoutBuilder {
1063    #[must_use]
1064    pub fn empty() -> Self { Self(Loadout::new_empty()) }
1065
1066    #[must_use]
1067    /// Construct new `LoadoutBuilder` from `asset_specifier`
1068    /// Will panic if asset is broken
1069    pub fn from_asset_expect(
1070        asset_specifier: &str,
1071        rng: &mut impl Rng,
1072        time: Option<&(TimeOfDay, Calendar)>,
1073    ) -> Self {
1074        Self::from_asset(asset_specifier, rng, time).expect("failed to load loadut config")
1075    }
1076
1077    /// Construct new `LoadoutBuilder` from `asset_specifier`
1078    pub fn from_asset(
1079        asset_specifier: &str,
1080        rng: &mut impl Rng,
1081        time: Option<&(TimeOfDay, Calendar)>,
1082    ) -> Result<Self, SpecError> {
1083        let loadout = Self::empty();
1084        loadout.with_asset(asset_specifier, rng, time)
1085    }
1086
1087    #[must_use]
1088    /// Construct new default `LoadoutBuilder` for corresponding `body`
1089    ///
1090    /// NOTE: make sure that you check what is default for this body
1091    /// Use it if you don't care much about it, for example in "/spawn" command
1092    pub fn from_default(body: &Body) -> Self {
1093        let loadout = Self::empty();
1094        loadout
1095            .with_default_maintool(body)
1096            .with_default_equipment(body)
1097    }
1098
1099    /// Construct new `LoadoutBuilder` from `asset_specifier`
1100    pub fn from_loadout_spec(
1101        loadout_spec: LoadoutSpec,
1102        rng: &mut impl Rng,
1103        time: Option<&(TimeOfDay, Calendar)>,
1104    ) -> Result<Self, SpecError> {
1105        let loadout = Self::empty();
1106        loadout.with_loadout_spec(loadout_spec, rng, time)
1107    }
1108
1109    #[must_use]
1110    /// Construct new `LoadoutBuilder` from `asset_specifier`
1111    ///
1112    /// Will panic if asset is broken
1113    pub fn from_loadout_spec_expect(
1114        loadout_spec: LoadoutSpec,
1115        rng: &mut impl Rng,
1116        time: Option<&(TimeOfDay, Calendar)>,
1117    ) -> Self {
1118        Self::from_loadout_spec(loadout_spec, rng, time).expect("failed to load loadout spec")
1119    }
1120
1121    #[must_use = "Method consumes builder and returns updated builder."]
1122    /// Set default active mainhand weapon based on `body`
1123    pub fn with_default_maintool(self, body: &Body) -> Self {
1124        self.active_mainhand(default_main_tool(body).map(Item::new_from_asset_expect))
1125    }
1126
1127    #[must_use = "Method consumes builder and returns updated builder."]
1128    /// Set default equipement based on `body`
1129    pub fn with_default_equipment(self, body: &Body) -> Self {
1130        let chest = default_chest(body);
1131
1132        if let Some(chest) = chest {
1133            self.chest(Some(Item::new_from_asset_expect(chest)))
1134        } else {
1135            self
1136        }
1137    }
1138
1139    #[must_use = "Method consumes builder and returns updated builder."]
1140    pub fn with_preset(mut self, preset: Preset) -> Self {
1141        let rng = &mut rand::rng();
1142        match preset {
1143            Preset::HuskSummon => {
1144                self = self.with_asset_expect("common.loadout.dungeon.cultist.husk", rng, None);
1145            },
1146            Preset::BorealSummon => {
1147                self =
1148                    self.with_asset_expect("common.loadout.world.boreal.boreal_warrior", rng, None);
1149            },
1150            Preset::AshenSummon => {
1151                self =
1152                    self.with_asset_expect("common.loadout.world.ashen.ashen_warrior", rng, None);
1153            },
1154            Preset::IronDwarfSummon => {
1155                self = self.with_asset_expect(
1156                    "common.loadout.dungeon.dwarven_quarry.iron_dwarf",
1157                    rng,
1158                    None,
1159                );
1160            },
1161            Preset::ShamanicSpiritSummon => {
1162                self = self.with_asset_expect(
1163                    "common.loadout.dungeon.terracotta.shamanic_spirit",
1164                    rng,
1165                    None,
1166                );
1167            },
1168            Preset::JiangshiSummon => {
1169                self =
1170                    self.with_asset_expect("common.loadout.dungeon.terracotta.jiangshi", rng, None);
1171            },
1172            Preset::BloodservantSummon => {
1173                self = self.with_asset_expect(
1174                    "common.loadout.dungeon.vampire.bloodservant",
1175                    rng,
1176                    None,
1177                );
1178            },
1179        }
1180
1181        self
1182    }
1183
1184    #[must_use = "Method consumes builder and returns updated builder."]
1185    pub fn with_creator(
1186        mut self,
1187        creator: fn(
1188            LoadoutBuilder,
1189            Option<&SiteInformation>,
1190            time: Option<&(TimeOfDay, Calendar)>,
1191        ) -> LoadoutBuilder,
1192        economy: Option<&SiteInformation>,
1193        time: Option<&(TimeOfDay, Calendar)>,
1194    ) -> LoadoutBuilder {
1195        self = creator(self, economy, time);
1196
1197        self
1198    }
1199
1200    #[must_use = "Method consumes builder and returns updated builder."]
1201    fn with_loadout_spec<R: Rng>(
1202        mut self,
1203        spec: LoadoutSpec,
1204        rng: &mut R,
1205        time: Option<&(TimeOfDay, Calendar)>,
1206    ) -> Result<Self, SpecError> {
1207        // Include any inheritance
1208        let spec = spec.eval(rng)?;
1209
1210        // Utility function to unwrap our itemspec
1211        let mut to_item = |maybe_item: Option<ItemSpec>| {
1212            if let Some(item) = maybe_item {
1213                item.try_to_item(rng, time)
1214            } else {
1215                Ok(None)
1216            }
1217        };
1218
1219        let to_pair = |maybe_hands: Option<Hands>, rng: &mut R| {
1220            if let Some(hands) = maybe_hands {
1221                hands.try_to_pair(rng, time)
1222            } else {
1223                Ok((None, None))
1224            }
1225        };
1226
1227        // Place every item
1228        if let Some(item) = to_item(spec.head)? {
1229            self = self.head(Some(item));
1230        }
1231        if let Some(item) = to_item(spec.neck)? {
1232            self = self.neck(Some(item));
1233        }
1234        if let Some(item) = to_item(spec.shoulders)? {
1235            self = self.shoulder(Some(item));
1236        }
1237        if let Some(item) = to_item(spec.chest)? {
1238            self = self.chest(Some(item));
1239        }
1240        if let Some(item) = to_item(spec.gloves)? {
1241            self = self.hands(Some(item));
1242        }
1243        if let Some(item) = to_item(spec.ring1)? {
1244            self = self.ring1(Some(item));
1245        }
1246        if let Some(item) = to_item(spec.ring2)? {
1247            self = self.ring2(Some(item));
1248        }
1249        if let Some(item) = to_item(spec.back)? {
1250            self = self.back(Some(item));
1251        }
1252        if let Some(item) = to_item(spec.belt)? {
1253            self = self.belt(Some(item));
1254        }
1255        if let Some(item) = to_item(spec.legs)? {
1256            self = self.pants(Some(item));
1257        }
1258        if let Some(item) = to_item(spec.feet)? {
1259            self = self.feet(Some(item));
1260        }
1261        if let Some(item) = to_item(spec.tabard)? {
1262            self = self.tabard(Some(item));
1263        }
1264        if let Some(item) = to_item(spec.bag1)? {
1265            self = self.bag(ArmorSlot::Bag1, Some(item));
1266        }
1267        if let Some(item) = to_item(spec.bag2)? {
1268            self = self.bag(ArmorSlot::Bag2, Some(item));
1269        }
1270        if let Some(item) = to_item(spec.bag3)? {
1271            self = self.bag(ArmorSlot::Bag3, Some(item));
1272        }
1273        if let Some(item) = to_item(spec.bag4)? {
1274            self = self.bag(ArmorSlot::Bag4, Some(item));
1275        }
1276        if let Some(item) = to_item(spec.lantern)? {
1277            self = self.lantern(Some(item));
1278        }
1279        if let Some(item) = to_item(spec.glider)? {
1280            self = self.glider(Some(item));
1281        }
1282        let (active_mainhand, active_offhand) = to_pair(spec.active_hands, rng)?;
1283        if let Some(item) = active_mainhand {
1284            self = self.active_mainhand(Some(item));
1285        }
1286        if let Some(item) = active_offhand {
1287            self = self.active_offhand(Some(item));
1288        }
1289        let (inactive_mainhand, inactive_offhand) = to_pair(spec.inactive_hands, rng)?;
1290        if let Some(item) = inactive_mainhand {
1291            self = self.inactive_mainhand(Some(item));
1292        }
1293        if let Some(item) = inactive_offhand {
1294            self = self.inactive_offhand(Some(item));
1295        }
1296
1297        Ok(self)
1298    }
1299
1300    #[must_use = "Method consumes builder and returns updated builder."]
1301    pub fn with_asset(
1302        self,
1303        asset_specifier: &str,
1304        rng: &mut impl Rng,
1305        time: Option<&(TimeOfDay, Calendar)>,
1306    ) -> Result<Self, SpecError> {
1307        let spec: LoadoutSpec = Ron::load_cloned(asset_specifier)
1308            .map_err(SpecError::LoadoutAssetError)?
1309            .into_inner();
1310        self.with_loadout_spec(spec, rng, time)
1311    }
1312
1313    /// # Usage
1314    /// Creates new `LoadoutBuilder` with all field replaced from
1315    /// `asset_specifier` which corresponds to loadout config
1316    ///
1317    /// # Panics
1318    /// 1) Will panic if there is no asset with such `asset_specifier`
1319    /// 2) Will panic if path to item specified in loadout file doesn't exist
1320    #[must_use = "Method consumes builder and returns updated builder."]
1321    pub fn with_asset_expect(
1322        self,
1323        asset_specifier: &str,
1324        rng: &mut impl Rng,
1325        time: Option<&(TimeOfDay, Calendar)>,
1326    ) -> Self {
1327        self.with_asset(asset_specifier, rng, time)
1328            .expect("failed loading loadout config")
1329    }
1330
1331    /// Set default armor items for the loadout. This may vary with game
1332    /// updates, but should be safe defaults for a new character.
1333    #[must_use = "Method consumes builder and returns updated builder."]
1334    pub fn defaults(self) -> Self {
1335        let rng = &mut rand::rng();
1336        self.with_asset_expect("common.loadout.default", rng, None)
1337    }
1338
1339    #[must_use = "Method consumes builder and returns updated builder."]
1340    fn with_equipment(mut self, equip_slot: EquipSlot, item: Option<Item>) -> Self {
1341        // Panic if item doesn't correspond to slot
1342        assert!(
1343            item.as_ref()
1344                .is_none_or(|item| equip_slot.can_hold(&item.kind()))
1345        );
1346
1347        // TODO: What if `with_equipment` is used twice for the same slot. Or defaults
1348        // include an item in this slot.
1349        // Used when creating a loadout, so time not needed as it is used to check when
1350        // stuff gets unequipped. A new loadout has never unequipped an item.
1351        let time = Time(0.0);
1352
1353        self.0.swap(equip_slot, item, time);
1354        self
1355    }
1356
1357    #[must_use = "Method consumes builder and returns updated builder."]
1358    fn with_armor(self, armor_slot: ArmorSlot, item: Option<Item>) -> Self {
1359        self.with_equipment(EquipSlot::Armor(armor_slot), item)
1360    }
1361
1362    #[must_use = "Method consumes builder and returns updated builder."]
1363    pub fn active_mainhand(self, item: Option<Item>) -> Self {
1364        self.with_equipment(EquipSlot::ActiveMainhand, item)
1365    }
1366
1367    #[must_use = "Method consumes builder and returns updated builder."]
1368    pub fn active_offhand(self, item: Option<Item>) -> Self {
1369        self.with_equipment(EquipSlot::ActiveOffhand, item)
1370    }
1371
1372    #[must_use = "Method consumes builder and returns updated builder."]
1373    pub fn inactive_mainhand(self, item: Option<Item>) -> Self {
1374        self.with_equipment(EquipSlot::InactiveMainhand, item)
1375    }
1376
1377    #[must_use = "Method consumes builder and returns updated builder."]
1378    pub fn inactive_offhand(self, item: Option<Item>) -> Self {
1379        self.with_equipment(EquipSlot::InactiveOffhand, item)
1380    }
1381
1382    #[must_use = "Method consumes builder and returns updated builder."]
1383    pub fn shoulder(self, item: Option<Item>) -> Self {
1384        self.with_armor(ArmorSlot::Shoulders, item)
1385    }
1386
1387    #[must_use = "Method consumes builder and returns updated builder."]
1388    pub fn chest(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Chest, item) }
1389
1390    #[must_use = "Method consumes builder and returns updated builder."]
1391    pub fn belt(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Belt, item) }
1392
1393    #[must_use = "Method consumes builder and returns updated builder."]
1394    pub fn hands(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Hands, item) }
1395
1396    #[must_use = "Method consumes builder and returns updated builder."]
1397    pub fn pants(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Legs, item) }
1398
1399    #[must_use = "Method consumes builder and returns updated builder."]
1400    pub fn feet(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Feet, item) }
1401
1402    #[must_use = "Method consumes builder and returns updated builder."]
1403    pub fn back(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Back, item) }
1404
1405    #[must_use = "Method consumes builder and returns updated builder."]
1406    pub fn ring1(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Ring1, item) }
1407
1408    #[must_use = "Method consumes builder and returns updated builder."]
1409    pub fn ring2(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Ring2, item) }
1410
1411    #[must_use = "Method consumes builder and returns updated builder."]
1412    pub fn neck(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Neck, item) }
1413
1414    #[must_use = "Method consumes builder and returns updated builder."]
1415    pub fn lantern(self, item: Option<Item>) -> Self {
1416        self.with_equipment(EquipSlot::Lantern, item)
1417    }
1418
1419    #[must_use = "Method consumes builder and returns updated builder."]
1420    pub fn glider(self, item: Option<Item>) -> Self { self.with_equipment(EquipSlot::Glider, item) }
1421
1422    #[must_use = "Method consumes builder and returns updated builder."]
1423    pub fn head(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Head, item) }
1424
1425    #[must_use = "Method consumes builder and returns updated builder."]
1426    pub fn tabard(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Tabard, item) }
1427
1428    #[must_use = "Method consumes builder and returns updated builder."]
1429    pub fn bag(self, which: ArmorSlot, item: Option<Item>) -> Self { self.with_armor(which, item) }
1430
1431    #[must_use]
1432    pub fn build(self) -> Loadout { self.0 }
1433}
1434
1435#[cfg(test)]
1436mod tests {
1437    use super::*;
1438    use crate::comp::Body;
1439    use strum::IntoEnumIterator;
1440
1441    // Testing different species
1442    //
1443    // Things that will be caught - invalid assets paths for
1444    // creating default main hand tool or equipment without config
1445    #[test]
1446    fn test_loadout_species() {
1447        for body in Body::iter() {
1448            std::mem::drop(LoadoutBuilder::from_default(&body))
1449        }
1450    }
1451
1452    // Testing all loadout presets
1453    //
1454    // Things that will be catched - invalid assets paths
1455    #[test]
1456    fn test_loadout_presets() {
1457        for preset in Preset::iter() {
1458            drop(LoadoutBuilder::empty().with_preset(preset));
1459        }
1460    }
1461
1462    // It just loads every loadout asset and tries to validate them
1463    //
1464    // TODO: optimize by caching checks
1465    // Because of nature of inheritance of loadout specs,
1466    // we will check some loadout assets at least two times.
1467    // One for asset itself and second if it serves as a base for other asset.
1468    #[test]
1469    fn validate_all_loadout_assets() {
1470        let loadouts = assets::load_rec_dir::<Ron<LoadoutSpec>>("common.loadout")
1471            .expect("failed to load loadout directory");
1472        for loadout_id in loadouts.read().ids() {
1473            let loadout: LoadoutSpec = Ron::load_cloned(loadout_id)
1474                .expect("failed to load loadout asset")
1475                .into_inner();
1476            loadout
1477                .validate(vec![loadout_id.to_string()])
1478                .unwrap_or_else(|e| panic!("{loadout_id} is broken: {e:?}"));
1479        }
1480    }
1481
1482    // Basically test that our validation tests don't have false-positives
1483    #[test]
1484    fn test_valid_assets() {
1485        let loadouts = assets::load_rec_dir::<Ron<LoadoutSpec>>("test.loadout.ok")
1486            .expect("failed to load loadout directory");
1487
1488        for loadout_id in loadouts.read().ids() {
1489            let loadout: LoadoutSpec = Ron::load_cloned(loadout_id)
1490                .expect("failed to load loadout asset")
1491                .into_inner();
1492            loadout
1493                .validate(vec![loadout_id.to_string()])
1494                .unwrap_or_else(|e| panic!("{loadout_id} is broken: {e:?}"));
1495        }
1496    }
1497}