# core/globalengine (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/globalengine/

The global engine. (in place of System.vanillaEngine of the original Engine.getEngine(). The same form as Unreal's GEngine and Godot's Engine singleton)
- The engine is created once and never removed. Engine::new puts the engine in a place that lives until the program ends ('static) and gives &'static Engine.
  That place is written in a thread slot, so right after creation Engine::get_engine() gives the same engine anywhere: scene functions, draw, components, widget callbacks, inside async tasks.
  Like the original, it gives the last created engine.
- All public engine functions are &self. The fields they change use interior mutability (Cell, RefCell). (the form of singletons and Gd's bind, bind_mut in godot-rust, Godot's Rust binding)
  So the engine argument a scene function receives and Engine::get_engine() can use the same engine at the same time without breaking Rust's borrowing rules.
- The managers (time, view, input, pointer, sound, graphic) are inside RefCell. get_x gives Ref and get_x_mut gives RefMut.
  Borrowing the same manager again (get_x or get_x_mut) while holding it as RefMut stops with a panic that names the function and the manager.
  Use what you borrow within one statement and let it go. (do not hold it long with let while calling other engine functions)
- Called from another thread it is Err(EngineAccessError::OtherThread). (the engine belongs to the thread that created it. Engine is not Sync, so &Engine cannot be sent to another thread. The web has one thread)

Example: Take out the same engine anywhere right after it is created

```rust
use vanilla::{Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let global_engine = Engine::get_engine().unwrap();
assert!(std::ptr::eq(engine, global_engine));
```

## EngineAccessError (enum) (Clone, Copy, Debug, PartialEq, Eq, fmt::Display, std::error::Error)

The reason the global engine could not be taken. (Engine::get_engine)

- `NotCreated`: No engine was ever created. (where the original getEngine is undefined)
- `OtherThread`: The engine is on another thread (the main thread that created the engine). The engine is taken only on that thread.
