forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.rs
More file actions
102 lines (90 loc) · 2.93 KB
/
plugin.rs
File metadata and controls
102 lines (90 loc) · 2.93 KB
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
use std::sync::Arc;
use anyhow::bail;
use feather_common::Game;
use quill_plugin_format::{PluginFile, PluginMetadata, PluginTarget, Triple};
use crate::{
context::{PluginContext, PluginPtrMut},
PluginId, PluginManager,
};
mod native;
mod wasm;
pub struct Plugin {
inner: Inner,
context: Arc<PluginContext>,
metadata: PluginMetadata,
}
impl Plugin {
/// Loads a plugin from the given plugin file.
///
/// Does not enable the plugin.
pub fn load(manager: &PluginManager, file: &PluginFile, id: PluginId) -> anyhow::Result<Self> {
let plugin_type = match &file.metadata().target {
PluginTarget::Wasm => "WebAssembly",
PluginTarget::Native { .. } => "native",
};
log::info!(
"Loading {} plugin {} version {}",
plugin_type,
file.metadata().name,
file.metadata().version
);
let (inner, context) = match &file.metadata().target {
PluginTarget::Wasm => {
let context = Arc::new(PluginContext::new_wasm(id));
let plugin =
wasm::WasmPlugin::load(manager, &context, file.module(), file.metadata())?;
(Inner::Wasm(plugin), context)
}
PluginTarget::Native { target_triple } => {
if target_triple != &Triple::host() {
bail!(
"native plguin was built for {}, but this system has target {}",
target_triple,
Triple::host()
);
}
let plugin = native::NativePlugin::load(file.module())?;
let context = PluginContext::new_native(id);
(Inner::Native(plugin), Arc::new(context))
}
};
Ok(Self {
inner,
context,
metadata: file.metadata().clone(),
})
}
/// Enables the plugin.
///
/// # Panics
/// Panics if called more than once.
pub fn enable(&mut self, game: &mut Game) -> anyhow::Result<()> {
let context = Arc::clone(&self.context);
self.context.enter(game, || match &self.inner {
Inner::Wasm(w) => w.enable(),
Inner::Native(n) => {
n.enable(context);
Ok(())
}
})?;
log::info!("Enabled plugin {} ", self.metadata.name);
Ok(())
}
/// Runs a plugin system.
///
/// `data` must be the data pointer passed
/// to the `register_system` host call.
pub fn run_system(&self, game: &mut Game, data: PluginPtrMut<u8>) -> anyhow::Result<()> {
self.context.enter(game, || match &self.inner {
Inner::Wasm(w) => w.run_system(data),
Inner::Native(n) => {
n.run_system(data);
Ok(())
}
})
}
}
enum Inner {
Wasm(wasm::WasmPlugin),
Native(native::NativePlugin),
}