bevy_modloader 0.1.2

A library allowing you to load and unload Bevy mods
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use std::hash::Hash;
use std::{cmp::Ordering, fmt::Debug};

use bevy_app::App;
use bevy_config_system::{ConfigKey, ConfigValue};
use bevy_ecs::{
    system::Commands,
    world::{CommandQueue, World},
};
use bevy_reflect::Reflect;
use bevy_utils::{HashMap, HashSet};

#[derive(Debug, Clone, PartialEq, Eq, Reflect)]
pub enum ModDependency {
    Required {
        name: String,
        version: ModVersionRequirement,
    },
    Optional {
        name: String,
        version: ModVersionRequirement,
    },
    Conflict(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Reflect, Copy, Default)]
pub struct ModVersion {
    pub major: u16,
    pub minor: u16,
    pub patch: u16,
}
impl ModVersion {
    pub fn from_str(version: &str) -> Self {
        let parts: Vec<&str> = version.split('.').collect();
        let major = parts
            .get(0)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(0);
        let minor = parts
            .get(1)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(0);
        let patch = parts
            .get(2)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(0);
        Self {
            major,
            minor,
            patch,
        }
    }
    fn from_str_end(version: &str) -> Self {
        let parts: Vec<&str> = version.split('.').collect();
        let major = parts
            .get(0)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(u16::MAX);
        let minor = parts
            .get(1)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(u16::MAX);
        let patch = parts
            .get(2)
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(u16::MAX);
        Self {
            major,
            minor,
            patch,
        }
    }
}

impl From<&str> for ModVersion {
    fn from(version: &str) -> Self {
        Self::from_str(version)
    }
}
impl PartialOrd for ModVersion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for ModVersion {
    fn cmp(&self, other: &Self) -> Ordering {
        if self.major != other.major {
            return self.major.cmp(&other.major);
        }
        if self.minor != other.minor {
            return self.minor.cmp(&other.minor);
        }
        self.patch.cmp(&other.patch)
    }
}
impl ToString for ModVersion {
    fn to_string(&self) -> String {
        format!("{}.{}.{}", self.major, self.minor, self.patch)
    }
}
impl Hash for ModVersion {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.major.hash(state);
        self.minor.hash(state);
        self.patch.hash(state);
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Reflect, Copy)]
pub enum ModVersionRequirement {
    GreaterThan(ModVersion),
    Range(ModVersion, ModVersion),
    Exact(ModVersion),
}

impl ModVersionRequirement {
    pub fn from_str(version: &str) -> Self {
        match version {
            v if v.starts_with(">=") => {
                let version = v[2..].trim();
                ModVersionRequirement::GreaterThan(ModVersion::from_str(version))
            }
            v if v.contains("-") => {
                let versions: Vec<&str> = v.split('-').collect();
                if versions.len() == 2 {
                    let start = ModVersion::from_str(versions[0]);
                    let end = ModVersion::from_str(versions[1]);
                    assert!(
                        start <= end,
                        "Invalid version range: {} - {}",
                        start.to_string(),
                        end.to_string()
                    );
                    ModVersionRequirement::Range(start, end)
                } else {
                    panic!("Invalid version range: {}", v);
                }
            }
            v => {
                if version.split('.').count() == 3 {
                    ModVersionRequirement::Exact(ModVersion::from_str(v))
                } else {
                    ModVersionRequirement::Range(
                        ModVersion::from_str(v),
                        ModVersion::from_str_end(v),
                    )
                }
            }
        }
    }
    pub fn matches(&self, version: &ModVersion) -> bool {
        match &self {
            ModVersionRequirement::GreaterThan(v) => version > v,
            ModVersionRequirement::Range(start, end) => version >= start && version <= end,
            ModVersionRequirement::Exact(v) => version == v,
        }
    }
}

impl ToString for ModVersionRequirement {
    fn to_string(&self) -> String {
        match self {
            ModVersionRequirement::GreaterThan(v) => format!(">={}", v.to_string()),
            ModVersionRequirement::Range(start, end) => {
                format!("{}-{}", start.to_string(), end.to_string())
            }
            ModVersionRequirement::Exact(v) => v.to_string(),
        }
    }
}
impl Hash for ModVersionRequirement {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.to_string().hash(state);
    }
}

impl Hash for ModDependency {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            ModDependency::Required { name, version } => {
                name.hash(state);
                version.hash(state);
            }
            ModDependency::Optional { name, version } => {
                name.hash(state);
                version.hash(state);
            }
            ModDependency::Conflict(name) => {
                name.hash(state);
            }
        };
    }
}
/*
impl PartialOrd for ModDependency {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ModDependency {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (ModDependency::Required {name: n1, version: v1}, ModDependency::Required {name: n2, version: v2}) =>
                n1.cmp(n2)
                .then_with(|| v1.cmp(v2)),
            (ModDependency::Required {..}, _) => Ordering::Greater,
            (ModDependency::Optional{name: n1, version: v1}, ModDependency::Optional {name: n2, version: v2}) => n1.cmp(n2)
                .then_with(|| v1.cmp(v2)),
            (ModDependency::Optional {..}, ModDependency::Required {..}) => Ordering::Less,
            (ModDependency::Optional {..}, _) => Ordering::Greater,
            (ModDependency::Conflict(name1), ModDependency::Conflict(name2)) => name1.cmp(name2),
            (ModDependency::Conflict(_), _) => Ordering::Less,
        }
    }
}
*/
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Copy)]
#[repr(u8)]
pub enum ModType {
    Reserved,
    Modification,
    Library,
}

impl TryFrom<&str> for ModType {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "modification" => Ok(ModType::Modification),
            "library" => Ok(ModType::Library),
            _ => Err(format!("Invalid mod type: {}", value)),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Default, Copy)]
#[repr(u8)]
pub enum ModState {
    #[default]
    Unloaded,
    Prototype,
    Data,
    Modify,
    Loaded,
}

impl ModState {
    pub fn consecutive(self) -> Self {
        match self {
            ModState::Unloaded => ModState::Prototype,
            ModState::Prototype => ModState::Data,
            ModState::Data => ModState::Modify,
            ModState::Modify => ModState::Loaded,
            _ => ModState::Loaded,
        }
    }
}

impl PartialOrd for ModState {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ModState {
    fn cmp(&self, other: &Self) -> Ordering {
        (*self as u8).cmp(&(*other as u8))
    }
}

pub type ModConfig = HashMap<ConfigKey, ConfigValue>;

pub type GlobalModConfig = HashMap<String, ModConfig>;

pub trait ModLoaderInterface: Send + Sync {
    /// Whether the mod shall be loaded exclusively.
    fn exclusive(&self) -> bool;

    /// Is the mod able to be unloaded?
    fn unloadable(&self) -> bool {
        false
    }

    /// Get the keys for the mod's config.
    /// This is used to generate the config UI.
    fn get_config_keys(&self) -> HashSet<ConfigKey>;

    /// Loads the mod in a parallel fashion.
    /// **Panics**: if the mod requires exclusive access.
    fn load(
        &mut self,
        mod_state: ModState,
        config: &ModConfig,
        commands: Commands,
        world: &World,
    ) -> Result<(), String>;
    /// Loads the mod with exclusive access.
    fn load_exclusive(
        &mut self,
        mod_state: ModState,
        config: &ModConfig,
        world: &mut World,
    ) -> Result<(), String> {
        let mut queue = CommandQueue::default();
        let commands = Commands::new(&mut queue, world);
        let res = self.load(mod_state, config, commands, world);
        queue.apply(world);
        res
    }
    /// Unloads the mod in a parallel fashion.
    /// **Panics**: if the mod requires exclusive access.
    #[allow(unused_variables)]
    fn unload(
        &mut self,
        mod_state: ModState,
        config: &ModConfig,
        commands: Commands,
        world: &World,
    ) -> Result<(), String> {
        unimplemented!("unload not supported");
    }
    /// Unloads the mod with exclusive access.
    fn unload_exclusive(
        &mut self,
        mod_state: ModState,
        config: &ModConfig,
        world: &mut World,
    ) -> Result<(), String> {
        let mut queue = CommandQueue::default();
        let commands = Commands::new(&mut queue, world);
        let res = self.unload(mod_state, config, commands, world);
        queue.apply(world);
        res
    }

    /// If the mod requires to restart the game before loading.
    fn requires_build(&self) -> bool {
        false
    }

    #[allow(unused_variables)]
    /// Corresponds to App::finish
    fn build(&mut self, app: &mut App) {}

    #[allow(unused_variables)]
    /// Corresponds to App::cleanup
    fn build_cleanup(&mut self, app: &mut App) {}
}

#[derive(Debug, Clone, PartialEq, Eq, Reflect)]
pub struct ModInfo {
    pub name: String,
    pub version: ModVersion,
    pub description: String,
    pub author: String,
    pub dependencies: HashSet<ModDependency>,
    pub mod_type: ModType,
}

impl Default for ModInfo {
    fn default() -> Self {
        Self {
            name: "mod".into(),
            version: ModVersion::default(),
            description: "".into(),
            mod_type: ModType::Modification,
            author: "unknown".into(),
            dependencies: HashSet::default(),
        }
    }
}

impl Hash for ModInfo {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.version.hash(state);
    }
}

impl Debug for Box<dyn ModLoaderInterface> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(format!("Box<dyn ModLoaderInterface @{:p}>", self.as_ref()).as_str())
    }
}

impl Clone for Mod {
    fn clone(&self) -> Self {
        unimplemented!()
    }
}

#[allow(unused)]
// impl_from_reflect_opaque!(Mod); recursively expanded
const _: () = {
    #[allow(unused_mut)]
    impl bevy_reflect::GetTypeRegistration for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        fn get_type_registration() -> bevy_reflect::TypeRegistration {
            let mut registration = bevy_reflect::TypeRegistration::of::<Self>();
            registration.insert:: <bevy_reflect::ReflectFromPtr>(bevy_reflect::FromType:: <Self> ::from_type());
            registration.insert::<bevy_reflect::ReflectFromReflect>(
                bevy_reflect::FromType::<Self>::from_type(),
            );
            registration
        }
    }
    const _: () = {
        mod private_scope {
            type AssertIsPrimitive = crate::mod_object::Mod;
        }
    };
    impl bevy_reflect::TypePath for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        fn type_path() -> &'static str {
            "Mod"
        }
        fn short_type_path() -> &'static str {
            "Mod"
        }
        fn type_ident() -> Option<&'static str> {
            ::core::option::Option::Some("Mod")
        }
        fn crate_name() -> Option<&'static str> {
            ::core::option::Option::None
        }
        fn module_path() -> Option<&'static str> {
            ::core::option::Option::None
        }
    }
    impl bevy_reflect::Typed for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        #[inline]
        fn type_info() -> &'static bevy_reflect::TypeInfo {
            static CELL: bevy_reflect::utility::NonGenericTypeInfoCell =
                bevy_reflect::utility::NonGenericTypeInfoCell::new();
            CELL.get_or_set(|| {
                let info = bevy_reflect::OpaqueInfo::new::<Self>();
                bevy_reflect::TypeInfo::Opaque(info)
            })
        }
    }
    impl bevy_reflect::Reflect for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        #[inline]
        fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn ::core::any::Any> {
            self
        }
        #[inline]
        fn as_any(&self) -> &dyn ::core::any::Any {
            self
        }
        #[inline]
        fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any {
            self
        }
        #[inline]
        fn into_reflect(
            self: ::std::boxed::Box<Self>,
        ) -> ::std::boxed::Box<dyn bevy_reflect::Reflect> {
            self
        }
        #[inline]
        fn as_reflect(&self) -> &dyn bevy_reflect::Reflect {
            self
        }
        #[inline]
        fn as_reflect_mut(&mut self) -> &mut dyn bevy_reflect::Reflect {
            self
        }
        #[inline]
        fn set(
            &mut self,
            value: ::std::boxed::Box<dyn bevy_reflect::Reflect>,
        ) -> ::core::result::Result<(), ::std::boxed::Box<dyn bevy_reflect::Reflect>> {
            *self = <dyn bevy_reflect::Reflect>::take(value)?;
            ::core::result::Result::Ok(())
        }
    }
    impl bevy_reflect::PartialReflect for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        #[inline]
        fn get_represented_type_info(
            &self,
        ) -> ::core::option::Option<&'static bevy_reflect::TypeInfo> {
            ::core::option::Option::Some(<Self as bevy_reflect::Typed>::type_info())
        }
        #[inline]
        fn clone_value(&self) -> ::std::boxed::Box<dyn bevy_reflect::PartialReflect> {
            ::std::boxed::Box::new(::core::clone::Clone::clone(self))
        }
        #[inline]
        fn try_apply(
            &mut self,
            value: &dyn bevy_reflect::PartialReflect,
        ) -> ::core::result::Result<(), bevy_reflect::ApplyError> {
            if let ::core::option::Option::Some(value) =
                <dyn bevy_reflect::PartialReflect>::try_downcast_ref::<Self>(value)
            {
                *self = ::core::clone::Clone::clone(value);
                return ::core::result::Result::Ok(());
            }
            ::core::result::Result::Err(bevy_reflect::ApplyError::MismatchedTypes {
                from_type: ::core::convert::Into::into(
                    bevy_reflect::DynamicTypePath::reflect_type_path(value),
                ),
                to_type: ::core::convert::Into::into(<Self as bevy_reflect::TypePath>::type_path()),
            })
        }
        #[inline]
        fn reflect_kind(&self) -> bevy_reflect::ReflectKind {
            bevy_reflect::ReflectKind::Opaque
        }
        #[inline]
        fn reflect_ref(&self) -> bevy_reflect::ReflectRef {
            bevy_reflect::ReflectRef::Opaque(self)
        }
        #[inline]
        fn reflect_mut(&mut self) -> bevy_reflect::ReflectMut {
            bevy_reflect::ReflectMut::Opaque(self)
        }
        #[inline]
        fn reflect_owned(self: ::std::boxed::Box<Self>) -> bevy_reflect::ReflectOwned {
            bevy_reflect::ReflectOwned::Opaque(self)
        }
        #[inline]
        fn try_into_reflect(
            self: ::std::boxed::Box<Self>,
        ) -> ::core::result::Result<
            ::std::boxed::Box<dyn bevy_reflect::Reflect>,
            ::std::boxed::Box<dyn bevy_reflect::PartialReflect>,
        > {
            ::core::result::Result::Ok(self)
        }
        #[inline]
        fn try_as_reflect(&self) -> ::core::option::Option<&dyn bevy_reflect::Reflect> {
            ::core::option::Option::Some(self)
        }
        #[inline]
        fn try_as_reflect_mut(&mut self) -> ::core::option::Option<&mut dyn bevy_reflect::Reflect> {
            ::core::option::Option::Some(self)
        }
        #[inline]
        fn into_partial_reflect(
            self: ::std::boxed::Box<Self>,
        ) -> ::std::boxed::Box<dyn bevy_reflect::PartialReflect> {
            self
        }
        #[inline]
        fn as_partial_reflect(&self) -> &dyn bevy_reflect::PartialReflect {
            self
        }
        #[inline]
        fn as_partial_reflect_mut(&mut self) -> &mut dyn bevy_reflect::PartialReflect {
            self
        }
    }
    impl bevy_reflect::FromReflect for Mod
    where
        Mod: ::core::any::Any + ::core::marker::Send + ::core::marker::Sync,
    {
        fn from_reflect(
            reflect: &dyn bevy_reflect::PartialReflect,
        ) -> ::core::option::Option<Self> {
            ::core::option::Option::Some(::core::clone::Clone::clone(
                <dyn bevy_reflect::PartialReflect>::try_downcast_ref::<Mod>(reflect)?,
            ))
        }
    }
};

#[derive(Debug)]
pub struct Mod {
    pub info: ModInfo,
    pub mod_state: ModState,
    pub mod_loader: Box<dyn ModLoaderInterface>,
}

impl Hash for Mod {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.info.hash(state);
    }
}

impl PartialEq for Mod {
    fn eq(&self, other: &Self) -> bool {
        self.info == other.info
    }
}
impl Eq for Mod {}

impl Ord for Mod {
    fn cmp(&self, other: &Self) -> Ordering {
        self.info.name.cmp(&other.info.name)
    }
}
impl PartialOrd for Mod {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}