# misc/devtools (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/devtools/

Developer tools. (DEVTools of the original misc/devtools.js)
- Shown and hidden with the F2 key. The panel appears docked at the bottom right in the window's inner logical coordinates (canvas native), regardless of the view scale mode.
- Four tabs: Statistics (engine, screen and time info), Node Hierarchy (tree on the left + inspector on the right), Local Storage (view, add, edit and remove keys and values),
  Settings (dim background, all gizmos, aspect ratio guide, FPS display. Saved to the local storage "hierarchy.settings" as the same JSON as the original)
- Drag the title bar to move, drag the edges and corners to resize, and drag the center divider to change the left and right ratio.
- Tree: expand and collapse, active (A) and gizmo (G) columns, selection, drag to scroll. Inspector: click a component header to expand and collapse its properties. (expanded by default)
- In the Rust version the scene holds DevTools and calls it in each function:
    dev_tools.tick(engine, node_tree, unscaled_time_delta) in tick, dev_tools.draw(engine, node_tree, graphic) in post_draw.
    If is_visible() && is_pointer_inside_panel(engine), the scene does not pass that input to the nodes. (original GameScene.isDevToolsCapturingInput)
- Differences from the original:
  - There is no original setEngine. (there is only one engine, so there is no separate engine to give) tick, draw and is_pointer_inside_panel take the engine.
  - Nodes are referred to by NodeId. The root list is set_root_nodes(`Vec<NodeId>`), expanded nodes are a set of NodeId, and collapsed components are a set of (NodeId, component index).
    Removed nodes drop out of the tree and the inspector, and if the selected node is removed it goes back to nothing selected.
  - setForceGizmosVisible, which the original calls in tick and on presses: press handling and set_visible take only &Engine and cannot change Graphic, so they record the desired value
    and tick applies it to the engine's graphic (get_graphic_mut) at its end. So, as in the original, it shows from that frame's drawing. (set_visible called outside tick is applied at the start of draw)
    The false applied by the original setEngine is applied on the first tick. (DevTools::new does not take the engine)
  - The only node type is WorldNode, so the tree's Type column and the inspector's type are the node type name from the held UIDocument (UIDocument::get_node_type_name). (in place of the original constructor.name: engine node types such as FloatingText registered in the initial document and types the game registered, otherwise "WorldNode")
  - The inspector's component properties call and show all get* and is* getters of the component, like the original getComponentProperties.
    The original scans prototypes at run time, and the Rust version uses the list built at compile time by the `#[reflect]` macro. (core/reflection.rs, attached to all engine components)
    Getters that take the tree (the original holds neighbor components directly) are called with the tree passed in drawing, and for components with &mut self getters, tick holds the tree and the values read there are shown.
    Names follow the original formatMethodName (getTextColor → textColor, kept as is if it starts with is), and values follow the original formatPropertyValue form.
    (numbers toFixed(2), Vector2 as (x, y), Rect as (x, y, width, height) toFixed(1), Color as rgba, null, nodes as `[WorldNode]`, arrays as `[Array]`, others as [type name])
    The list and order are the same as the original. (redefinitions in the Rust version not in the original class are left out, and getters named differently from the original are shown with the original name) The original getEngine is left out. (in the original it is the value given with setEngine, while the Rust UIView::get_engine is a function that takes the global engine)
  - Like the original, every component is reflected. Reflect is a supertrait of Component, so a game component without `#[reflect]` does not compile.
    Node type names (for values that point at nodes) are the names registered in the UIDocument. A document where the game registered its own types is set with set_ui_document. (or registered through get_ui_document_mut)
  - Key input, value editing and the remove confirmation in the Local Storage tab use the engine question dialogs Engine::prompt and Engine::confirm in both engines. (the original engine.prompt, engine.confirm) (core/modaldialog.rs)
    The question dialog drawn by the engine appears, the scene pauses until it is answered, and the answer is received on the next tick. (the same on the web and the desktop)
  - clientNativeSize in Statistics is ViewManager::get_client_native_size (the whole page size on the web, the window's inner logical size on desktop).
    Memory reads Chrome's performance.memory on the web like the original, and is "(N/A)" in browsers without it.
    The desktop has no JavaScript heap, so the same fields show values with the same meaning read through operating system APIs. In use and reserved are the heap of the system allocator Rust uses,
    and jsHeapSizeLimit is the upper bound the operating system allows for this process's heap. (platform/desktop.rs read_heap_usage, read_heap_size_limit)
    In both engines each field that cannot be obtained is "(N/A)". (All three if the heap cannot be read)
    viewScaleMode is written with the Rust enum name (StretchHeight and so on).
  - The aspect ratio guide does not rely on the coordinate system at the time like the original, but applies the view coordinate system (apply_view_rect) itself and draws. (same result as in the original GameScene)
- Turning on Show FPS in Settings draws the frame count of the last second at the top left of the window even when the panel is closed. (same as the original, canvas native coordinates, over the panel if the panel is visible)
- Not ported: none. (the try/catch ignoring draw errors, which nobody calls in the original, is not needed in Rust)

Example: Attach developer tools to a scene (input over the panel is not passed to nodes)

```rust
use vanilla::{DevTools, Engine, EngineConfiguration, Graphic, Scene, SceneBase};

struct MainScene {
	scene_base: SceneBase,
	dev_tools: DevTools,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, _engine: &Engine) {
		self.dev_tools.set_root_nodes(vec![self.scene_base.get_root_id()]);
	}

	fn tick(&mut self, time_delta: f64) {
		let engine = Engine::get_engine().unwrap();
		let is_capturing_input = self.dev_tools.is_visible() && self.dev_tools.is_pointer_inside_panel(engine);
		self.scene_base.get_node_tree_mut().tick(engine, time_delta);
		if !is_capturing_input {
			self.scene_base.tick_touch(time_delta);
		}
		self.scene_base.tick_tweens(time_delta);
		let unscaled_time_delta = engine.get_time_manager().get_unscale_delta_time();
		self.dev_tools.tick(engine, self.scene_base.get_node_tree_mut(), unscaled_time_delta);
	}

	fn post_draw(&mut self, graphic: &mut Graphic) {
		let engine = Engine::get_engine().unwrap();
		self.dev_tools.draw(engine, self.scene_base.get_node_tree(), graphic);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let main_scene = MainScene {
	scene_base: SceneBase::new(),
	dev_tools: DevTools::new(),
};
engine.run(Box::new(main_scene)).unwrap();
```

## DevTools (struct) (Default)

Developer tools panel.
- The scene holds it and calls tick, draw. Panel coordinates are the window's inner logical coordinates (canvas native).

Example: Inspecting a node opens the panel and selects that node

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

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(1280, 720, 1.0);
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let group_id = node_tree.create_child(root_id, "group");
let hero_id = node_tree.create_child(group_id, "hero");

let mut dev_tools = DevTools::new();
dev_tools.set_root_nodes(vec![root_id]);
dev_tools.inspect_node(&engine, &node_tree, hero_id);
assert!(dev_tools.is_visible());
assert_eq!(dev_tools.get_active_tab(), 1);
assert_eq!(dev_tools.get_selected_node(), Some(hero_id));
assert!(dev_tools.is_node_expanded(group_id));

let panel_rect = dev_tools.get_panel_rect();
assert_eq!(panel_rect.position.x + panel_rect.size.x, 1280.0);
assert_eq!(panel_rect.position.y + panel_rect.size.y, 720.0);
```

- `pub fn new() -> DevTools` (constructor, since 0.4.0): Constructor. (hidden, Node Hierarchy tab, reads the saved settings)
  - Panel 810x520, left column width 405. Settings are read from local storage "hierarchy.settings", and are the defaults if missing or the JSON is broken.
  - returns DevTools: New developer tools with no roots. (set the tree roots with set_root_nodes)
- `pub fn set_root_nodes(&mut self, root_ids: Vec<NodeId>)` (method, since 0.4.0): Sets the root node list. (roots stay expanded)
  - `root_ids` Vec<NodeId>: List of nodes shown at the top of the tree. (in order)
- `pub fn is_visible(&self) -> bool` (method, since 0.4.0): Returns the visibility.
  - returns bool: true if the panel is visible.
- `pub fn set_visible(&mut self, engine: &Engine, is_visible: bool)` (method, since 0.4.0): Shows and hides. (same as F2. When shown, docks the panel at the bottom right of the window and applies the all-gizmos setting)
  - Forced display of all gizmos is applied to Graphic at the end of tick or at the start of the next draw, whichever comes first. When hiding, closes a pending local storage question.
  - `engine` &Engine: Engine to read the window's inner logical size from.
  - `is_visible` bool: Shows if true, hides if false.
- `pub fn get_active_tab(&self) -> usize` (method, since 0.4.0): Returns the current tab. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings)
  - returns usize: Tab number. (0 ~ 3, initially 1)
- `pub fn set_active_tab(&mut self, tab_index: usize)` (method, since 0.4.0): Sets the tab. (ignored if no such tab)
  - `tab_index` usize: Tab number. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings, 4 or more is ignored)
- `pub fn get_selected_node(&self) -> Option<NodeId>` (method, since 0.4.0): Returns the selected node.
  - returns Option<NodeId>: The node shown in the inspector. None if nothing is selected. (becomes None on the next tick if the selected node is deleted)
- `pub fn set_selected_node(&mut self, node_id: Option<NodeId>)` (method, since 0.4.0): Selects a node. (inspector scroll goes to the top)
  - `node_id` Option<NodeId>: Node to select. None returns to no selection. (does not expand ancestors, use inspect_node to expand)
- `pub fn is_node_expanded(&self, node_id: NodeId) -> bool` (method, since 0.4.0): Whether a node is expanded in the tree.
  - `node_id` NodeId: Node to look at.
  - returns bool: true if expanded. (roots set with set_root_nodes start expanded)
- `pub fn set_node_expanded(&mut self, node_id: NodeId, is_expanded: bool)` (method, since 0.4.0): Expands and collapses a node in the tree.
  - `node_id` NodeId: Node to expand or collapse.
  - `is_expanded` bool: Expands if true, collapses if false.
- `pub fn set_ui_document(&mut self, ui_document: UIDocument)` (method, since 0.4.0): Sets the document the inspector reads component properties from. (setting a UIDocument in which the game registered its own components shows those components' properties too)
  - `ui_document` UIDocument: Document with component types registered. (replaces the held document)
- `pub fn get_ui_document_mut(&mut self) -> &mut UIDocument` (method, since 0.4.0): The document the inspector reads component properties from. (mutable, for registering more component types)
  - returns &mut UIDocument: Mutable reference to the held document. (at first UIDocument::new() with register_editor_types called)
- `pub fn get_panel_rect(&self) -> Rect` (method, since 0.4.0): Returns the panel area. (window inner logical coordinates)
  - returns Rect: Panel rectangle. (window inner logical pixels, the last position even when hidden)
- `pub fn is_pointer_inside_panel(&self, engine: &Engine) -> bool` (method, since 0.4.0): Returns whether the current touch position is inside the panel.
  - `engine` &Engine: Engine to read the input position (window inner logical coordinates) from.
  - returns bool: true if the panel is visible and the input position is inside the panel (boundary included). Always false when hidden.
- `pub fn tick(&mut self, engine: &Engine, node_tree: &mut NodeTree, _time_delta: f64)` (method, since 0.4.0): Update. (F2 toggle, tree list, touch)
  - If there is an inspect request (Inspect in the input field context menu), inspects that node first. When hidden, only checks F2.
  - When visible, removes deleted nodes from the selection, rereads the tree list and the &mut self getter values, receives the answer to the local storage question, and handles press, drag, and release.
  - At the end, applies a changed forced display of all gizmos to the engine's graphic. (as in the original it shows from that frame's drawing; without a graphic it is applied at the start of the next draw)
  - `engine` &Engine: Engine to read input and view from and to open question dialogs with.
  - `node_tree` &mut NodeTree: Node tree to show in the tree. (clicking the A, G columns toggles the node's active and gizmo)
  - `_time_delta` f64: Time elapsed since the last frame. (seconds, unused. As in the original, pass the value not scaled by the time scale)
- `pub fn inspect_node(&mut self, engine: &Engine, node_tree: &NodeTree, node_id: NodeId)` (method, since 0.4.0): Inspects a node. (shows the panel, switches to the Node Hierarchy tab, expands the ancestors, and selects that node)
  - `engine` &Engine: Engine to read the window size from when the panel is first shown.
  - `node_tree` &NodeTree: Node tree to find the ancestors in.
  - `node_id` NodeId: Node to inspect. (the node itself is not expanded)
- `pub fn draw(&mut self, engine: &Engine, node_tree: &NodeTree, graphic: &mut Graphic)` (method, since 0.4.0): Draws. (draws in the window's inner logical coordinates, and when done restores the drawing state it came in with)
  - First applies to Graphic a forced display of all gizmos that was changed outside tick and not applied yet. If hidden, draws only the FPS display and returns.
  - `engine` &Engine: Engine to read statistics and view info from.
  - `node_tree` &NodeTree: Node tree to show in the tree and the inspector.
  - `graphic` &mut Graphic: Graphic to draw to. (after everything else is drawn, like the scene's post_draw)
- `pub fn is_frame_per_second_visible(&self) -> bool` (method, since 0.4.0): Returns whether FPS is shown. (Show FPS in Settings, when on, draw draws the FPS at the top left of the window even when the panel is closed)
  - returns bool: true if the FPS display in the Settings tab is on. (DevTools does not draw it itself, the scene checks this and draws it)
