fyrox_impl/plugin/mod.rs
1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Everything related to plugins. See [`Plugin`] docs for more info.
22
23#![warn(missing_docs)]
24
25pub mod dylib;
26
27use crate::{
28 asset::manager::ResourceManager,
29 core::{
30 pool::Handle,
31 reflect::Reflect,
32 visitor::{Visit, VisitError},
33 Downcast,
34 },
35 engine::{
36 task::TaskPoolHandler, AsyncSceneLoader, GraphicsContext, PerformanceStatistics,
37 ScriptProcessor, SerializationContext,
38 },
39 event::Event,
40 gui::{
41 constructor::WidgetConstructorContainer,
42 inspector::editors::PropertyEditorDefinitionContainer, message::UiMessage, UiContainer,
43 },
44 scene::{Scene, SceneContainer},
45};
46use std::{
47 ops::{Deref, DerefMut},
48 path::Path,
49 sync::Arc,
50};
51use winit::event_loop::EventLoopWindowTarget;
52
53/// A wrapper for various plugin types.
54pub enum PluginContainer {
55 /// Statically linked plugin. Such plugins are meant to be used in final builds, to maximize
56 /// performance of the game.
57 Static(Box<dyn Plugin>),
58 /// Dynamically linked plugin. Such plugins are meant to be used in development mode for rapid
59 /// prototyping.
60 Dynamic(Box<dyn DynamicPlugin>),
61}
62
63/// Abstraction over different kind of plugins that can be reloaded on the fly (whatever it mean).
64/// The instance is polled by engine with `is_reload_needed_now()` time to time. if it returns true,
65/// then engine serializes current plugin state, then calls `unload()` and then calls `load()`
66pub trait DynamicPlugin {
67 /// returns human-redable short description of the plugin
68 fn display_name(&self) -> String;
69
70 /// engine polls is time to time to determine if it's time to reload plugin
71 fn is_reload_needed_now(&self) -> bool;
72
73 /// panics if not loaded
74 fn as_loaded_ref(&self) -> &dyn Plugin;
75
76 /// panics if not loaded
77 fn as_loaded_mut(&mut self) -> &mut dyn Plugin;
78
79 /// returns false if something bad happends during `reload`.
80 /// has no much use except prevention of error spamming
81 fn is_loaded(&self) -> bool;
82
83 /// called before saving state and detaching related objects
84 fn prepare_to_reload(&mut self) {}
85
86 /// called after plugin-related objects are detached
87 /// `fill_and_register` callback exposes plugin instance to engine to register constructors and restore the state
88 /// callback approach allows plugins to do some necessary actions right after plugin is registed
89 fn reload(
90 &mut self,
91 fill_and_register: &mut dyn FnMut(&mut dyn Plugin) -> Result<(), String>,
92 ) -> Result<(), String>;
93}
94
95impl Deref for PluginContainer {
96 type Target = dyn Plugin;
97
98 fn deref(&self) -> &Self::Target {
99 match self {
100 PluginContainer::Static(plugin) => &**plugin,
101 PluginContainer::Dynamic(plugin) => plugin.as_loaded_ref(),
102 }
103 }
104}
105
106impl DerefMut for PluginContainer {
107 fn deref_mut(&mut self) -> &mut Self::Target {
108 match self {
109 PluginContainer::Static(plugin) => &mut **plugin,
110 PluginContainer::Dynamic(plugin) => plugin.as_loaded_mut(),
111 }
112 }
113}
114
115/// Contains plugin environment for the registration stage.
116pub struct PluginRegistrationContext<'a> {
117 /// A reference to serialization context of the engine. See [`SerializationContext`] for more
118 /// info.
119 pub serialization_context: &'a Arc<SerializationContext>,
120 /// A reference to serialization context of the engine. See [`WidgetConstructorContainer`] for more
121 /// info.
122 pub widget_constructors: &'a Arc<WidgetConstructorContainer>,
123 /// A reference to the resource manager instance of the engine. Could be used to register resource loaders.
124 pub resource_manager: &'a ResourceManager,
125}
126
127/// Contains plugin environment.
128pub struct PluginContext<'a, 'b> {
129 /// A reference to scene container of the engine. You can add new scenes from [`Plugin`] methods
130 /// by using [`SceneContainer::add`].
131 pub scenes: &'a mut SceneContainer,
132
133 /// A reference to the resource manager, it can be used to load various resources and manage
134 /// them. See [`ResourceManager`] docs for more info.
135 pub resource_manager: &'a ResourceManager,
136
137 /// A reference to user interface container of the engine. The engine guarantees that there's
138 /// at least one user interface exists. Use `context.user_interfaces.first()/first_mut()` to
139 /// get a reference to it.
140 pub user_interfaces: &'a mut UiContainer,
141
142 /// A reference to the graphics_context, it contains a reference to the window and the current renderer.
143 /// It could be [`GraphicsContext::Uninitialized`] if your application is suspended (possible only on
144 /// Android; it is safe to call [`GraphicsContext::as_initialized_ref`] or [`GraphicsContext::as_initialized_mut`]
145 /// on every other platform).
146 pub graphics_context: &'a mut GraphicsContext,
147
148 /// The time (in seconds) that passed since last call of a method in which the context was
149 /// passed. It has fixed value that is defined by a caller (in most cases it is `Executor`).
150 pub dt: f32,
151
152 /// A reference to time accumulator, that holds remaining amount of time that should be used
153 /// to update a plugin. A caller splits `lag` into multiple sub-steps using `dt` and thus
154 /// stabilizes update rate. The main use of this variable, is to be able to reset `lag` when
155 /// you doing some heavy calculations in a your game loop (i.e. loading a new level) so the
156 /// engine won't try to "catch up" with all the time that was spent in heavy calculation.
157 pub lag: &'b mut f32,
158
159 /// A reference to serialization context of the engine. See [`SerializationContext`] for more
160 /// info.
161 pub serialization_context: &'a Arc<SerializationContext>,
162
163 /// A reference to serialization context of the engine. See [`WidgetConstructorContainer`] for more
164 /// info.
165 pub widget_constructors: &'a Arc<WidgetConstructorContainer>,
166
167 /// Performance statistics from the last frame.
168 pub performance_statistics: &'a PerformanceStatistics,
169
170 /// Amount of time (in seconds) that passed from creation of the engine. Keep in mind, that
171 /// this value is **not** guaranteed to match real time. A user can change delta time with
172 /// which the engine "ticks" and this delta time affects elapsed time.
173 pub elapsed_time: f32,
174
175 /// Script processor is used to run script methods in a strict order.
176 pub script_processor: &'a ScriptProcessor,
177
178 /// Asynchronous scene loader. It is used to request scene loading. See [`AsyncSceneLoader`] docs
179 /// for usage example.
180 pub async_scene_loader: &'a mut AsyncSceneLoader,
181
182 /// Special field that associates main application event loop (not game loop) with OS-specific
183 /// windows. It also can be used to alternate control flow of the application.
184 pub window_target: Option<&'b EventLoopWindowTarget<()>>,
185
186 /// Task pool for asynchronous task management.
187 pub task_pool: &'a mut TaskPoolHandler,
188}
189
190impl dyn Plugin {
191 /// Performs downcasting to a particular type.
192 pub fn cast<T: Plugin>(&self) -> Option<&T> {
193 Downcast::as_any(self).downcast_ref::<T>()
194 }
195
196 /// Performs downcasting to a particular type.
197 pub fn cast_mut<T: Plugin>(&mut self) -> Option<&mut T> {
198 Downcast::as_any_mut(self).downcast_mut::<T>()
199 }
200}
201
202/// Plugin is a convenient interface that allow you to extend engine's functionality.
203///
204/// # Static vs dynamic plugins
205///
206/// Every plugin must be linked statically to ensure that everything is memory safe. There was some
207/// long research about hot reloading and dynamic plugins (in DLLs) and it turned out that they're
208/// not guaranteed to be memory safe because Rust does not have stable ABI. When a plugin compiled
209/// into DLL, Rust compiler is free to reorder struct members in any way it needs to. It is not
210/// guaranteed that two projects that uses the same library will have compatible ABI. This fact
211/// indicates that you either have to use static linking of your plugins or provide C interface
212/// to every part of the engine and "communicate" with plugin using C interface with C ABI (which
213/// is standardized and guaranteed to be compatible). The main problem with C interface is
214/// boilerplate code and the need to mark every structure "visible" through C interface with
215/// `#[repr(C)]` attribute which is not always easy and even possible (because some structures could
216/// be re-exported from dependencies). These are the main reasons why the engine uses static plugins.
217///
218/// # Example
219///
220/// ```rust
221/// # use fyrox_impl::{
222/// # core::{pool::Handle}, core::visitor::prelude::*, core::reflect::prelude::*,
223/// # plugin::{Plugin, PluginContext, PluginRegistrationContext},
224/// # scene::Scene,
225/// # event::Event
226/// # };
227/// # use std::str::FromStr;
228///
229/// #[derive(Default, Visit, Reflect, Debug)]
230/// struct MyPlugin {}
231///
232/// impl Plugin for MyPlugin {
233/// fn on_deinit(&mut self, context: PluginContext) {
234/// // The method is called when the plugin is disabling.
235/// // The implementation is optional.
236/// }
237///
238/// fn update(&mut self, context: &mut PluginContext) {
239/// // The method is called on every frame, it is guaranteed to have fixed update rate.
240/// // The implementation is optional.
241/// }
242///
243/// fn on_os_event(&mut self, event: &Event<()>, context: PluginContext) {
244/// // The method is called when the main window receives an event from the OS.
245/// }
246/// }
247/// ```
248pub trait Plugin: Downcast + Visit + Reflect {
249 /// The method is called when the plugin constructor was just registered in the engine. The main
250 /// use of this method is to register scripts and custom scene graph nodes in [`SerializationContext`].
251 fn register(&self, #[allow(unused_variables)] context: PluginRegistrationContext) {}
252
253 /// This method is used to register property editors for your game types; to make them editable
254 /// in the editor.
255 fn register_property_editors(&self) -> PropertyEditorDefinitionContainer {
256 PropertyEditorDefinitionContainer::empty()
257 }
258
259 /// This method is used to initialize your plugin.
260 fn init(
261 &mut self,
262 #[allow(unused_variables)] scene_path: Option<&str>,
263 #[allow(unused_variables)] context: PluginContext,
264 ) {
265 }
266
267 /// This method is called when your plugin was re-loaded from a dynamic library. It could be used
268 /// to restore some runtime state, that cannot be serialized. This method is called **only for
269 /// dynamic plugins!** It is guaranteed to be called after all plugins were constructed, so the
270 /// cross-plugins interactions are possible.
271 fn on_loaded(&mut self, #[allow(unused_variables)] context: PluginContext) {}
272
273 /// The method is called before plugin will be disabled. It should be used for clean up, or some
274 /// additional actions.
275 fn on_deinit(&mut self, #[allow(unused_variables)] context: PluginContext) {}
276
277 /// Updates the plugin internals at fixed rate (see [`PluginContext::dt`] parameter for more
278 /// info).
279 fn update(&mut self, #[allow(unused_variables)] context: &mut PluginContext) {}
280
281 /// called after all Plugin and Script updates
282 fn post_update(&mut self, #[allow(unused_variables)] context: &mut PluginContext) {}
283
284 /// The method is called when the main window receives an event from the OS. The main use of
285 /// the method is to respond to some external events, for example an event from keyboard or
286 /// gamepad. See [`Event`] docs for more info.
287 fn on_os_event(
288 &mut self,
289 #[allow(unused_variables)] event: &Event<()>,
290 #[allow(unused_variables)] context: PluginContext,
291 ) {
292 }
293
294 /// The method is called when a graphics context was successfully created. It could be useful
295 /// to catch the moment when it was just created and do something in response.
296 fn on_graphics_context_initialized(
297 &mut self,
298 #[allow(unused_variables)] context: PluginContext,
299 ) {
300 }
301
302 /// The method is called before the actual frame rendering. It could be useful to render off-screen
303 /// data (render something to texture, that can be used later in the main frame).
304 fn before_rendering(&mut self, #[allow(unused_variables)] context: PluginContext) {}
305
306 /// The method is called when the current graphics context was destroyed.
307 fn on_graphics_context_destroyed(&mut self, #[allow(unused_variables)] context: PluginContext) {
308 }
309
310 /// The method will be called when there is any message from main user interface instance
311 /// of the engine.
312 fn on_ui_message(
313 &mut self,
314 #[allow(unused_variables)] context: &mut PluginContext,
315 #[allow(unused_variables)] message: &UiMessage,
316 ) {
317 }
318
319 /// This method is called when the engine starts loading a scene from the given `path`. It could
320 /// be used to "catch" the moment when the scene is about to be loaded; to show a progress bar
321 /// for example. See [`AsyncSceneLoader`] docs for usage example.
322 fn on_scene_begin_loading(
323 &mut self,
324 #[allow(unused_variables)] path: &Path,
325 #[allow(unused_variables)] context: &mut PluginContext,
326 ) {
327 }
328
329 /// This method is called when the engine finishes loading a scene from the given `path`. Use
330 /// this method if you need do something with a newly loaded scene. See [`AsyncSceneLoader`] docs
331 /// for usage example.
332 fn on_scene_loaded(
333 &mut self,
334 #[allow(unused_variables)] path: &Path,
335 #[allow(unused_variables)] scene: Handle<Scene>,
336 #[allow(unused_variables)] data: &[u8],
337 #[allow(unused_variables)] context: &mut PluginContext,
338 ) {
339 }
340
341 /// This method is called when the engine finishes loading a scene from the given `path` with
342 /// some error. This method could be used to report any issues to a user.
343 fn on_scene_loading_failed(
344 &mut self,
345 #[allow(unused_variables)] path: &Path,
346 #[allow(unused_variables)] error: &VisitError,
347 #[allow(unused_variables)] context: &mut PluginContext,
348 ) {
349 }
350}