feo-oop-engine 0.0.5

An Object Oriented game engine for rust.
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
//! [![github]](https://github.com/littleTitan/feo-oop-engine) [![crates-io]](https://crates.io/crates/feo-oop-engine) [![docs-rs]](crate)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K
//!
//! Feo OOP Engine is an object oriented game engine.
//! > procedural macros: [feo-oop-engine-proc-macros](https://docs.rs/feo-oop-engine-proc-macros)
//! ## Compatibility
//!
//! |  OS     | Compatible |
//! | :-----: | :--------: |
//! | Windows | Issue id:1 |
//! | Linux   | Yes        |
//! | OSX     | Yes        |
//!
//! See issue [#1](/../../issues/1) for Windows
//! ## Description
//! The FeO OOP engine is a library I created to help me learn about 3D engines. This 
//! project is composed of two parts. [feo-math](https://github.com/littleTitan/feo-math), 
//! the math boilerplate; and the feo-oop-engine. The engine is built on the 
//! [vulkano](https://vulkano.rs) framework. This program is designed to facilitate 3D 
//! application development. Please note however that this program has its own unique 
//! workflow. Features of the engine include [scripts](###scripts), object oriented 
//! programming (or OOP for short), textures, materials, lights, game objects, and obj
//! and mtl processing.
//! 
//! ## Example
//! 
//! ### Building the Scene
//! 
//! First create a new scene.
//! ```no_run
//! use feo_oop_engine::scene::Scene;
//! 
//! let scene = Scene::new(None);
//! ```
//! This is where all of your game-objects will directly or indirectly exist on. 
//!
//! ### Initialize the Engine With the Scene
//! To create an engine use the `FeoEngine::init(scene, specify_hardware)`. This will create a feo_engine object.
//! ```no_run
//! use feo_oop_engine::FeoEngine;
//! # let scene = feo_oop_engine::scene::Scene::new(None);
//! let mut engine = FeoEngine::init(scene, Some(1));
//! ```
//!
//! ### Build Objects
//! To build objects use the `::new()` constructor for the object you wish to build. You might want to build a light and a camera to be able to see the scene.
//! ```no_run
//! use feo_oop_engine::scene::game_object::obj::Obj;
//! # let scene = feo_oop_engine::scene::Scene::new(None);
//! # let mut engine = feo_oop_engine::FeoEngine::init(scene, Some(1));
//! let obj = Obj::from_obj(
//!    Some("cube"), 
//!    "assets/standard-assets/models/shapes/cube.obj",
//!    None,
//!    None,
//!    None,
//!    None,
//!    true,
//!    engine.globals.clone(),
//!    None
//! );
//! ```
//!
//! ### Pass Objects to Scene
//! Use the `add_child()` function to add the object you created to the scene within the engine.
//! ```no_run
//! use feo_oop_engine::registration::relation::Parent;
//! # let scene = feo_oop_engine::scene::Scene::new(None);
//! # let mut engine = feo_oop_engine::FeoEngine::init(scene, Some(1));
//! # let obj = feo_oop_engine::scene::game_object::obj::Obj::from_obj( Some("cube"), 
//! #    "assets/standard-assets/models/shapes/cube.obj", None, None, None, None,
//! #    true, engine.globals.clone(), None );
//! engine.scene.write().unwrap().add_child(obj.unwrap());
//! ```
//!
//! ### Running the Engine
//! When all the game_objects have been created you can use the run() function of feo_engine to start the engine.
//! ```ignore
//! engine.run()
//! ```
#[macro_use] extern crate lazy_static;

#[macro_use] extern crate feo_oop_engine_proc_macros;

pub mod scene;
pub mod components;
pub mod scripting;
pub mod event;
pub mod graphics;
pub mod registration;

pub mod shaders;
pub mod macros;

pub(crate) mod term_ui;

use {
    self::{
        graphics::frame_system::FrameSystem,
        event::UserEvent,
        scripting::globals::EngineGlobals,
        scene::Scene,
        components::texture::Texture,
        registration::id::IDSystem
    },
    std::{
        sync::{
            Arc,
            RwLock,
        },
        any::Any,
    },
    vulkano::{
        device::{
            Device, 
            DeviceExtensions, 
            Queue
        },
        image::{
            view::ImageView,
            ImageUsage
        }, 
        instance::{
            Instance,
        },
        swapchain::{
            self, 
            AcquireError, 
            ColorSpace, 
            FullscreenExclusive, 
            PresentMode, 
            Surface, 
            SurfaceTransform, 
            Swapchain, 
            SwapchainCreationError
        }, 
        sync::{
            self, 
            FlushError, 
            GpuFuture
        }
    },
    vulkano_win::VkSurfaceBuild,
    winit::{
        dpi::PhysicalSize, 
        event::{
            Event, 
            WindowEvent
        }, 
        event_loop::{
            ControlFlow, 
            EventLoop
        },
        platform::run_return::EventLoopExtRunReturn, 
        window::{
            Window, 
            WindowBuilder
        }
    }
};

/// The Engine
pub struct FeoEngine {
    event_loop: EventLoop<UserEvent<Arc<dyn Any + 'static + Send + Sync>>>,
    surface: Arc<Surface<Window>>,
    queue: Arc<Queue>,

    pub scene: Arc<RwLock<Scene>>,

    pub id_system: IDSystem,

    pub globals: EngineGlobals
}

impl FeoEngine {
    /// Initialize a FeoEngine.
    /// 
    /// # Arguments
    /// * `scene` - The scene in which GameObjects exist.
    /// * `index` - The optional device id. The default (None) displays available devices and prompts for the selection of one. 
    /// # Examples
    /// ```no_run
    /// # use feo_oop_engine::FeoEngine;
    /// # let scene = feo_oop_engine::scene::Scene::new(None);
    /// FeoEngine::init(scene, Some(1)); // Uses the device with id of 1
    /// ```
    pub fn init(scene: Arc<RwLock<Scene>>, index: Option<usize>) -> FeoEngine {
        // Vulkano Instance
        let instance = Instance::new(None, &vulkano_win::required_extensions(), None).unwrap();

        // Physical Device
        let physical = term_ui::prompt_physical_device(&instance, index);

        // event loop
        let event_loop = EventLoop::<UserEvent<Arc<dyn Any + Send + Sync>>>::with_user_event();

        // surface
        let surface = {
            let mut builder = WindowBuilder::new();
            builder.window.inner_size = Some(PhysicalSize::new(1024_u32, 512_u32).into());
            builder.build_vk_surface(&event_loop, instance.clone()).unwrap()
        };

        // get access to the device and get graphics queue
        let (_device, queue) = {
            let queue_family = physical
                .queue_families()
                .find(|&q| q.supports_graphics() && surface.is_supported(q).unwrap_or(false))
                .unwrap();

            let device_ext = DeviceExtensions {
                khr_swapchain: true,
                khr_storage_buffer_storage_class: true,
                ..DeviceExtensions::none()
            };

            let features = physical.supported_features();
            // TODO assertions
            
            let (device, mut queues) = Device::new(
                physical,
                features,
                &device_ext,
                [(queue_family, 0.5)].iter().cloned(),
            ).unwrap();

            (device, queues.next().unwrap())
        };

        Texture::default(queue.clone());

        let id_system = IDSystem::default();
        
        FeoEngine {
            globals: EngineGlobals{ // todo fix
                queue: queue.clone(),
                surface: surface.clone(),
                scene: scene.clone(),
                event_loop_proxy: Arc::new(futures::lock::Mutex::new(event_loop.create_proxy())),
                id_system: id_system.clone()
            },

            //instance,
            event_loop,
            surface,
            queue,

            scene,

            id_system,
        }
    }

    /// Allows the engine to commence excecution.
    pub fn run(&mut self) {
        // get swapchain and images
        let dimensions: [u32; 2] = self.surface.window().inner_size().into();
        let (mut swapchain, _) = {
            let caps = self.surface.capabilities(self.queue.device().physical_device()).unwrap();
            let format = caps.supported_formats[0].0;
            let alpha = caps.supported_composite_alpha.iter().next().unwrap();

            let (swapchain, images) = Swapchain::new(
                self.queue.device().clone(),
                self.surface.clone(),
                caps.min_image_count,
                format,
                dimensions,
                1,
                ImageUsage::color_attachment(),
                &self.queue,
                SurfaceTransform::Identity,
                alpha,
                PresentMode::Fifo,
                FullscreenExclusive::Default,
                true,
                ColorSpace::SrgbNonLinear,
            ).unwrap();

            let images = images
                .into_iter()
                .map(|image| ImageView::new(image).unwrap())
                .collect::<Vec<_>>();
            
            (swapchain, images)
        };

        // Deferred system
        let mut frame_system = FrameSystem::new(self.queue.clone(), swapchain.format(), dimensions);
        
        // Frame Future
        let mut previous_frame_end = Some(sync::now(self.queue.device().clone()).boxed());

        // Event Loop proxy
        let proxy = self.event_loop.create_proxy();
        
        // Self pointer
        let local_self: *mut Self = self;

        self.event_loop.run_return(move | mut event, _, control_flow| {
            // a mutable reference to self
            let local_self = unsafe {&mut *local_self};
    
            // Deal with Event Redundancy
            while let Event::UserEvent(UserEvent::WinitEvent(inner_event)) = event {
                event = match inner_event {
                    Event::UserEvent(boxed_user_event) => Event::UserEvent(*boxed_user_event),
                    Event::NewEvents(start_case) => Event::NewEvents(start_case),
                    Event::WindowEvent { window_id, event } => Event::WindowEvent { window_id, event },
                    Event::DeviceEvent { device_id, event } => Event::DeviceEvent { device_id, event },
                    Event::Suspended => Event::Suspended,
                    Event::Resumed => Event::Resumed,
                    Event::MainEventsCleared => Event::MainEventsCleared,
                    Event::RedrawRequested(window_id) => Event::RedrawRequested(window_id),
                    Event::RedrawEventsCleared => Event::RedrawEventsCleared,
                    Event::LoopDestroyed => Event::LoopDestroyed,
                };
            }

            // Static Event
            let event: Event<'static, UserEvent<Arc<dyn Any + Send + Sync>>> = event.to_static().unwrap();
            
            // Executor for Object event handlers
            let h_executor = {
                let (executor, spawner) = scripting::new_executor_and_spawner(local_self.globals.clone());
                local_self.scene.read().unwrap().spawn_script_handlers(spawner, event.clone());
                executor
            };
            
            match event {
                Event::WindowEvent {
                    event: WindowEvent::CloseRequested,
                    ..
                } => {
                    *control_flow = ControlFlow::Exit;
                },
                Event::UserEvent( UserEvent::RebuildSwapchain ) | 
                Event::WindowEvent {
                    event: WindowEvent::Resized(_),
                    ..
                } => { 
                    // resizing is slower however because no dynamic viewports are used rendering is faster
                    let dimensions: [u32; 2] = local_self.surface.window().inner_size().into();

                    let (new_swapchain, new_images) = 
                        match swapchain.recreate_with_dimensions(dimensions) {
                            Ok(r) => r,
                            Err(SwapchainCreationError::UnsupportedDimensions) => return,
                            Err(e) => panic!("Failed to recreate swapchain: {:?}", e),
                        };

                    let new_images = new_images
                        .into_iter()
                        .map(|image| ImageView::new(image).unwrap())
                        .collect::<Vec<_>>();
                        
                    swapchain = new_swapchain;

                    frame_system.rebuild_dims(&new_images[..]);
                },
                Event::RedrawEventsCleared => {
                    // Clear buffer pool
                    previous_frame_end.as_mut().unwrap().cleanup_finished();

                    // Generate Executor and Spawner for scripts
                    let (executor, spawner) = scripting::new_executor_and_spawner(local_self.globals.clone());
                    local_self.scene.read().unwrap().spawn_script_cores(spawner);

                    // Get the next image
                    let (image_num, suboptimal, acquire_future) =
                        match swapchain::acquire_next_image(swapchain.clone(), None) {
                            Ok(r) => r,
                            Err(AcquireError::OutOfDate) => {
                                proxy.send_event(UserEvent::RebuildSwapchain).unwrap();
                                return;
                            }
                            Err(e) => panic!("Failed to acquire next image: {:?}", e),
                        };
                    
                    // rebuild swapchain if suboptimal
                    if suboptimal { proxy.send_event(UserEvent::RebuildSwapchain).unwrap(); }
                    
                    // Run scripts to completion
                    executor.run(local_self.scene.clone()); // TODO: merge future with other future and start scripts mvd
                    
                    let future = local_self.scene.read().unwrap()
                        .render(local_self.scene.clone(), &mut frame_system, image_num, acquire_future, &mut previous_frame_end)
                        .then_swapchain_present(local_self.queue.clone(), swapchain.clone(), image_num)
                        .then_signal_fence_and_flush();

                    match future {
                        Ok(future) => {
                            previous_frame_end = Some(future.boxed());
                        },
                        Err(FlushError::OutOfDate) => {
                            proxy.send_event(UserEvent::RebuildSwapchain).unwrap();
                            previous_frame_end = Some(sync::now(local_self.queue.device().clone()).boxed());
                        },
                        Err(e) => {
                            println!("Failed to flush future: {:?}", e);
                            previous_frame_end = Some(sync::now(local_self.queue.device().clone()).boxed());
                        }
                    }
                    
                },
                _ => {},
            }
            
            // Force event handlers to Completion
            h_executor.run(local_self.scene.clone());
        });
    }
}