# core/node/nodetree (vanilla-engine 0.4.0)

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

Node tree.
- Holds the scene's nodes in one storage (slotmap) and links parents and children by handle (NodeId).
- Game code carries NodeIds around and takes nodes out with get_node / get_node_mut (or `tree[node_id]`).
  For the NodeId of a deleted node, get_node returns None. (in place of the original isDestroyed)
- In the original, a parent holds child objects in children[] and a child points back with parent.
  In Rust that form (`Rc<RefCell>`) brings runtime borrow checking costs and reference cycles, so it was changed to handles.
- When running tick / touch, only the one component being called is briefly taken out of its node (an empty placeholder is left in its place) and a ComponentContext (own node + whole tree + engine) is passed.
  So a component can find, change and create other nodes, and also find other components of the same node (siblings) with get_node_mut().`get_component_mut::<T>()`.
- Nodes deleted while running are left inactive in place and actually deleted after the run finishes.
- Sibling order (the original Node.setSiblingIndex, getSiblingIndex, getSiblings) and hierarchy checks (isActiveInHierarchy, TransformNode.isVisibleInHierarchy)
  need to look at the parent, so NodeTree does them taking a node handle. The original -1 and null are None.
  The original isVisible means active with opacity greater than 0. The Rust version also has a separate visibility flag (set_visible) that turns off drawing, and checks that too.
- The hierarchy functions of the original Node keep the same names. Where node objects are passed it is NodeId, and names ending in _id (_ids) are the counterparts that return handles.
  (getParent → get_parent_id, getChildren → get_child_ids, getSiblings → get_sibling_ids) Detaching from the parent (remove_child) does not delete the node.
- The original WorldNode.getPosition, setPosition, getWorldCorners, getWorldBounds are also done taking a node handle. The global position is, like the original, the position of the pivot point
  computed relative to the parent pivot, and the four corners are computed from that global position, global size and global rotation.

## NodeTree (struct) (Default, Index<NodeId>, IndexMut<NodeId>)

Node tree.
- Each scene holds one. (SceneBase::get_node_tree_mut) Nodes are fetched by NodeId, and `node_tree[node_id]` panics if the node was removed.

Example: Create, find and remove nodes under a layer node

```rust
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let layer_id = node_tree.create_child(root_id, "layer");
let player_id = node_tree.create_child(layer_id, "player");
assert_eq!(node_tree.find_descendant_by_name(root_id, "player"), Some(player_id));
assert_eq!(node_tree[player_id].get_parent_id(), Some(layer_id));
node_tree.destroy_node(layer_id);
assert!(node_tree.get_node(player_id).is_none());
assert_eq!(node_tree.get_node_count(), 1);
```

- `pub fn new() -> NodeTree` (constructor, since 0.3.2): Creates. (also creates the root node "root". The root's pivot is top-left)
  - returns NodeTree: A tree holding only the root node.
- `pub fn get_root_id(&self) -> NodeId` (method, since 0.3.2): Root node handle.
  - returns NodeId: Root node handle. (the root cannot be removed)
- `pub fn get_node_count(&self) -> usize` (method, since 0.3.2): Node count. (including the root and nodes not yet attached to the tree)
  - returns usize: Number of nodes held. (including the root and nodes not yet attached)
- `pub fn contains(&self, node_id: NodeId) -> bool` (method, since 0.3.2): Whether the node is alive.
  - `node_id` NodeId: Node to look at.
  - returns bool: True if the node has not been removed.
- `pub fn get_node(&self, node_id: NodeId) -> Option<&WorldNode>` (method, since 0.3.2): Returns the node.
  - `node_id` NodeId: Node to fetch.
  - returns Option<&WorldNode>: The node. None if removed or an unknown handle.
- `pub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut WorldNode>` (method, since 0.3.2): Returns the node. (mutable)
  - `node_id` NodeId: Node to fetch.
  - returns Option<&mut WorldNode>: The node. (mutable) None if removed or an unknown handle.
- `pub fn create_node(&mut self, name: &str) -> NodeId` (method, since 0.3.2): Creates a node. (not attached to any parent yet. It is drawn only after attaching with add_child)
  - `name` &str: Node name.
  - returns NodeId: New node handle.
- `pub fn create_child(&mut self, parent_id: NodeId, name: &str) -> NodeId` (method, since 0.3.2): Creates a child node. (creates it and attaches it as the last child of parent_id)
  - `parent_id` NodeId: Parent to attach to.
  - `name` &str: Node name.
  - returns NodeId: New node handle. (left unattached if parent_id is a missing node)
- `pub fn add_child(&mut self, parent_id: NodeId, child_id: NodeId) -> bool` (method, since 0.3.2): Adds a child. (at the end. If attached to another parent, detaches and moves it)
  - Does not attach under itself or its own ancestors. (false)
  - `parent_id` NodeId: Node that becomes the parent.
  - `child_id` NodeId: Node to attach.
  - returns bool: True if attached. False if either is missing, child_id is the root, or child_id is parent_id itself or its ancestor.
- `pub fn insert_child(&mut self, parent_id: NodeId, child_id: NodeId, child_index: usize) -> bool` (method, since 0.3.2): Inserts a child. (at child_index, at the end if greater than the child count)
  - `parent_id` NodeId: Node that becomes the parent.
  - `child_id` NodeId: Node to insert.
  - `child_index` usize: Position to insert at. (from 0, earlier is drawn first)
  - returns bool: True if inserted. Blocked in the same cases as add_child.

  Example: Insert at the front to draw first (underneath)

  ```rust
  use vanilla::NodeTree;
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let player_id = node_tree.create_child(root_id, "player");
  let background_id = node_tree.create_node("background");
  assert!(node_tree.insert_child(root_id, background_id, 0));
  assert_eq!(node_tree.get_child_ids(root_id), &[background_id, player_id]);
  assert!(!node_tree.insert_child(player_id, root_id, 0));
  ```

- `pub fn remove_from_parent(&mut self, child_id: NodeId)` (method, since 0.3.2): Detaches from the parent. (does not remove the node. It can be add_child'ed again)
  - `child_id` NodeId: Node to detach. (does nothing if it has no parent or is a missing node)
- `pub fn set_parent(&mut self, child_id: NodeId, parent_id: Option<NodeId>) -> bool` (method, since 0.4.0): Sets the parent. (detaches from the parent if None, does not attach under itself or its descendants, the original setParent)
  - `child_id` NodeId: Node to move.
  - `parent_id` Option<NodeId>: New parent. Detaches from the parent if None.
  - returns bool: True if attached, already a child of that parent (position unchanged), or detached. False in the cases add_child blocks.
- `pub fn remove_child(&mut self, parent_id: NodeId, child_id: NodeId)` (method, since 0.4.0): Removes a child. (only if it is a child of that parent, does not destroy the node, the original removeChild)
  - `parent_id` NodeId: Parent.
  - `child_id` NodeId: Child to detach. (does nothing if not a child of parent_id)
- `pub fn remove_child_at(&mut self, parent_id: NodeId, child_index: usize)` (method, since 0.4.0): Removes the child at that position. (the original removeChildAt)
  - `parent_id` NodeId: Parent.
  - `child_index` usize: Position of the child to detach. (from 0, does nothing if out of range)
- `pub fn remove_children(&mut self, parent_id: NodeId)` (method, since 0.4.0): Removes all children. (detaches only the direct children and keeps their hierarchies, the original removeChildren)
  - `parent_id` NodeId: Parent to detach children from.
- `pub fn remove_child_by_name(&mut self, parent_id: NodeId, name: &str)` (method, since 0.4.0): Removes a child by name. (the first direct child, the original removeChildByName)
  - `parent_id` NodeId: Parent.
  - `name` &str: Name of the child to detach.
- `pub fn destroy_node(&mut self, node_id: NodeId)` (method, since 0.3.2): Destroys a node. (including descendants. Does not destroy the root)
  - While tick / touch is iterating, deactivates it and destroys it after the iteration.
  - `node_id` NodeId: Node to destroy. (does nothing if it is the root or a missing node)
- `pub fn destroy_children(&mut self, parent_id: NodeId)` (method, since 0.3.2): Destroys all children.
  - Calls destroy_node for each direct child. (destroys descendants too)
  - `parent_id` NodeId: Parent whose children to destroy.
- `pub fn destroy_children_where(&mut self, parent_id: NodeId, predicate: impl Fn(&WorldNode) -> bool) -> usize` (method, since 0.3.2): Destroys children matching a condition. (count destroyed)
  - `parent_id` NodeId: Parent whose children to destroy.
  - `predicate` impl Fn(&WorldNode) -> bool: Condition called for each direct child that returns true for ones to destroy.
  - returns usize: Number of children destroyed.

  Example: Destroy only children named enemy

  ```rust
  use vanilla::NodeTree;
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  for name in ["enemy", "item", "enemy"] {
  	node_tree.create_child(root_id, name);
  }
  let destroyed_count = node_tree.destroy_children_where(root_id, |node| node.get_name() == "enemy");
  assert_eq!(destroyed_count, 2);
  assert_eq!(node_tree.get_child_count(root_id), 1);
  ```

- `pub fn get_parent_id(&self, node_id: NodeId) -> Option<NodeId>` (method, since 0.3.2): Parent handle.
  - `node_id` NodeId: Node to look at.
  - returns Option<NodeId>: Parent handle. None for the root, unattached nodes and missing nodes.
- `pub fn get_child_ids(&self, node_id: NodeId) -> &[NodeId]` (method, since 0.3.2): Child handle list. (draw order)
  - `node_id` NodeId: Node to look at.
  - returns &[NodeId]: Child handle list. (earlier is drawn first) An empty list if the node is missing.
- `pub fn get_child_count(&self, node_id: NodeId) -> usize` (method, since 0.3.2): Child count.
  - `node_id` NodeId: Node to look at.
  - returns usize: Number of direct children. 0 if the node is missing.
- `pub fn get_child_index(&self, parent_id: NodeId, child_id: NodeId) -> Option<usize>` (method, since 0.4.0): Position of the child. (index in draw order, None if not a child of parent_id)
  - `parent_id` NodeId: Parent.
  - `child_id` NodeId: Child to find.
  - returns Option<usize>: Index in draw order. (from 0) None if not a child of parent_id.
- `pub fn get_sibling_ids(&self, node_id: NodeId) -> Option<&[NodeId]>` (method, since 0.4.0): Sibling list. (the parent's child handles including itself, None if there is no parent)
  - `node_id` NodeId: Node to look at.
  - returns Option<&[NodeId]>: Sibling handle list including itself. (draw order) None if there is no parent.
- `pub fn get_sibling_index(&self, node_id: NodeId) -> Option<usize>` (method, since 0.4.0): Position among siblings. (None if there is no parent)
  - `node_id` NodeId: Node to look at.
  - returns Option<usize>: Index among siblings. (from 0) None if there is no parent.
- `pub fn set_sibling_index(&mut self, node_id: NodeId, child_index: usize)` (method, since 0.4.0): Sets the position among siblings. (clamps to child count - 1 and moves it there. Does nothing if there is no parent)
  - Earlier is drawn first and lies underneath.
  - `node_id` NodeId: Node to move.
  - `child_index` usize: New position. (from 0, at the end if over child count - 1)

  Example: Move to the front, then send to the back (drawn on top)

  ```rust
  use vanilla::NodeTree;
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let back_id = node_tree.create_child(root_id, "back");
  let front_id = node_tree.create_child(root_id, "front");
  node_tree.set_sibling_index(front_id, 0);
  assert_eq!(node_tree.get_child_ids(root_id), &[front_id, back_id]);
  node_tree.set_sibling_index(front_id, 100);
  assert_eq!(node_tree.get_sibling_index(front_id), Some(1));
  ```

- `pub fn is_active_in_hierarchy(&self, node_id: NodeId) -> bool` (method, since 0.4.0): Whether it and everything up to the root are active. (false if any is off, false for a missing node too)
  - `node_id` NodeId: Node to look at.
  - returns bool: True if it and all its ancestors are active.
- `pub fn is_visible_in_hierarchy(&self, node_id: NodeId) -> bool` (method, since 0.4.0): Whether it and everything up to the root are visible. (false if any of active, the visible flag, opacity > 0 fails, false for a missing node too)
  - `node_id` NodeId: Node to look at.
  - returns bool: True if it and all its ancestors are active, visible is on and opacity is greater than 0.
- `pub fn is_ancestor_or_self(&self, ancestor_id: NodeId, node_id: NodeId) -> bool` (method, since 0.3.2): Whether ancestor_id is node_id itself or its ancestor.
  - `ancestor_id` NodeId: Node to test as an ancestor.
  - `node_id` NodeId: Reference node.
  - returns bool: True if ancestor_id is node_id itself or its ancestor.
- `pub fn find_child(&self, parent_id: NodeId, predicate: impl Fn(&WorldNode) -> bool) -> Option<NodeId>` (method, since 0.4.0): Finds a child by condition. (direct children only, the first one, the original findChild)
  - `parent_id` NodeId: Parent to search.
  - `predicate` impl Fn(&WorldNode) -> bool: Condition that returns true for the node being searched for.
  - returns Option<NodeId>: The first matching direct child. None if none.
- `pub fn find_child_recursive(&self, parent_id: NodeId, predicate: &dyn Fn(&WorldNode) -> bool) -> Option<NodeId>` (method, since 0.4.0): Finds a descendant by condition. (depth first, the first one in draw order, the original findChildRecursive)
  - `parent_id` NodeId: Ancestor to search. (itself is not checked)
  - `predicate` &dyn Fn(&WorldNode) -> bool: Condition that returns true for the node being searched for. (pass it in `&|node| ...` form)
  - returns Option<NodeId>: The first matching descendant. None if none.

  Example: Find a descendant that receives touches

  ```rust
  use vanilla::NodeTree;
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let panel_id = node_tree.create_child(root_id, "panel");
  let button_id = node_tree.create_child(panel_id, "button");
  node_tree[button_id].set_interactable(true);
  assert_eq!(node_tree.find_child_recursive(root_id, &|node| node.is_interactable()), Some(button_id));
  assert_eq!(node_tree.find_child(root_id, |node| node.is_interactable()), None);
  ```

- `pub fn find_child_recursive_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>` (method, since 0.4.0): Finds a descendant by name. (the original findChildRecursiveByName, same as find_descendant_by_name)
  - `parent_id` NodeId: Ancestor to search. (itself is not checked)
  - `name` &str: Name to find.
  - returns Option<NodeId>: The first matching descendant. (depth first, draw order) None if none.
- `pub fn find_child_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>` (method, since 0.3.2): Finds a child by name. (direct children only, the first one)
  - `parent_id` NodeId: Parent to search.
  - `name` &str: Name to find.
  - returns Option<NodeId>: The first matching direct child. None if none.
- `pub fn find_descendant_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>` (method, since 0.3.2): Finds a descendant by name. (depth first, the first one in draw order)
  - `parent_id` NodeId: Ancestor to search. (itself is not checked)
  - `name` &str: Name to find.
  - returns Option<NodeId>: The first matching descendant. (depth first, draw order) None if none.
- `pub fn get_position(&self, node_id: NodeId) -> Vector2` (method, since 0.4.0): Global position. (global position of the pivot point, the original WorldNode.getPosition)
  - The local position is measured from the top-left of the parent's content area, so it is shifted to be relative to the parent pivot point (parent content size x parent pivot), then the parent's global rotation and scale are applied
    and it is added to the global position of the parent pivot point. (anchors are not included) Same place where the draw transform (calculate_world_matrix) puts the pivot point.
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns Vector2: Global position of the pivot point. (view coordinates for nodes under the root)

  Example: Read the global position and move to a global position

  ```rust
  use vanilla::{NodeTree, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let parent_id = node_tree.create_child(root_id, "parent");
  let child_id = node_tree.create_child(parent_id, "child");
  node_tree[parent_id].set_local_position(Vector2::create(100.0, 50.0));
  node_tree[child_id].set_local_position(Vector2::create(10.0, 20.0));
  assert_eq!(node_tree.get_position(child_id), Vector2::create(110.0, 70.0));
  node_tree.set_position(child_id, Vector2::create(200.0, 100.0));
  assert_eq!(node_tree[child_id].get_local_position(), Vector2::create(100.0, 50.0));
  ```

- `pub fn set_position(&mut self, node_id: NodeId, position: Vector2)` (method, since 0.4.0): Sets the global position. (the local position if there is no parent, the inverse of get_position. The original WorldNode.setPosition)
  - Takes the offset from the global position of the parent pivot point, undoes the parent's global rotation and scale to bring it back relative to the parent pivot point, and shifts it to be relative to the top-left of the parent's content area (local position).
  - On axes where the parent's global scale is 0, it is placed at the parent pivot point.
  - `node_id` NodeId: Node to move. (panics if the node is missing)
  - `position` Vector2: Global position the pivot point goes to.
- `pub fn get_scale(&self, node_id: NodeId) -> Vector2` (method, since 0.4.0): Global scale. (multiplies the parents' scales, the original TransformNode.getScale)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns Vector2: Global scale. (product of its own and its ancestors' local scales)
- `pub fn read_position(&self, node_id: NodeId, out: &mut Vector2)` (method, since 0.4.0): Writes the global position into out. (original WorldNode.readPosition, TransformNode.readPosition, the same value as get_position)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - `out` &mut Vector2: The place to write into.
- `pub fn read_scale(&self, node_id: NodeId, out: &mut Vector2)` (method, since 0.4.0): Writes the global scale into out. (original TransformNode.readScale, the same value as get_scale)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - `out` &mut Vector2: The place to write into.
- `pub fn set_scale(&mut self, node_id: NodeId, scale: Vector2)` (method, since 0.4.0): Sets the global scale. (divides by the parent's global scale, 0 if it is 0, the original TransformNode.setScale)
  - `node_id` NodeId: Node to change. (panics if the node is missing)
  - `scale` Vector2: Global scale.
- `pub fn get_rotation(&self, node_id: NodeId) -> f64` (method, since 0.4.0): Global rotation. (degrees, adds the parents' rotations, the original TransformNode.getRotation)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns f64: Global rotation. (degrees, sum of its own and its ancestors' local rotations)
- `pub fn set_rotation(&mut self, node_id: NodeId, rotation: f64)` (method, since 0.4.0): Sets the global rotation. (degrees, the original TransformNode.setRotation)
  - `node_id` NodeId: Node to change. (panics if the node is missing)
  - `rotation` f64: Global rotation. (degrees)
- `pub fn get_opacity(&self, node_id: NodeId) -> f64` (method, since 0.4.0): Global opacity. (multiplies the parents' opacities, the original TransformNode.getOpacity)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns f64: Global opacity. (0 ~ 1, product of its own and its ancestors' local opacities)
- `pub fn get_world_corners(&self, node_id: NodeId) -> [Vector2; 4]` (method, since 0.4.0): The four corners of the area actually drawn on screen. (the original WorldNode.getWorldCorners, OBB. top-left, top-right, bottom-right, bottom-left)
  - The size is multiplied by the absolute value of the global scale and rotated by the global rotation around the global position of the pivot point.
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns [Vector2; 4]: The four corners. (view coordinates, in top-left, top-right, bottom-right, bottom-left order)

  Example: Corners and bounding rectangle of a center-pivot node

  ```rust
  use vanilla::{NodeTree, Rect, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "box");
  node_tree[node_id].set_local_position(Vector2::create(100.0, 100.0));
  node_tree[node_id].set_content_size(Vector2::create(40.0, 20.0));
  let world_corners = node_tree.get_world_corners(node_id);
  assert_eq!(world_corners[0], Vector2::create(80.0, 90.0));
  assert_eq!(world_corners[2], Vector2::create(120.0, 110.0));
  assert_eq!(node_tree.get_world_bounds(node_id), Rect::create(80.0, 90.0, 40.0, 20.0));
  ```

- `pub fn get_world_bounds(&self, node_id: NodeId) -> Rect` (method, since 0.4.0): Rectangle enclosing the four corners. (the original WorldNode.getWorldBounds)
  - `node_id` NodeId: Node to read. (panics if the node is missing)
  - returns Rect: Axis-aligned rectangle enclosing the four corners. (view coordinates)
- `pub fn calculate_world_matrix(&self, node_id: NodeId) -> TransformMatrix` (method, since 0.3.2): World matrix. (product of the local matrices from the root to this node. The root's parent coordinate system = the view coordinate system)
  - `node_id` NodeId: Node to look at.
  - returns TransformMatrix: Matrix that maps a point in this node's content coordinates to view coordinates. The identity matrix if the node is missing.
- `pub fn convert_node_position_to_view_position(&self, node_id: NodeId, node_position: Vector2) -> Vector2` (method, since 0.3.2): Point in the node area → view coordinates.
  - `node_id` NodeId: Reference node.
  - `node_position` Vector2: Point in node content coordinates. (origin at the top-left of the content area)
  - returns Vector2: Point in view coordinates.
- `pub fn convert_view_position_to_node_position(&self, node_id: NodeId, view_position: Vector2) -> Option<Vector2>` (method, since 0.3.2): View coordinates → point in the node area. (None if the matrix is not invertible)
  - `node_id` NodeId: Reference node.
  - `view_position` Vector2: Point in view coordinates.
  - returns Option<Vector2>: Point in node content coordinates. None if the matrix cannot be inverted (scale 0).
- `pub fn convert_view_to_local(&self, node_id: NodeId, view_position: Vector2) -> Option<Vector2>` (method, since 0.4.0): View coordinates → node local coordinates. (origin at the top-left of the content area, goes through all parent transforms, the original WorldNode.convertViewToLocal)
  - Same as convert_view_position_to_node_position. None if the matrix is not invertible (scale 0).
  - `node_id` NodeId: Reference node.
  - `view_position` Vector2: Point in view coordinates.
  - returns Option<Vector2>: Point in node content coordinates. None if the matrix cannot be inverted (scale 0).

  Example: Convert a touch position to a position inside the panel

  ```rust
  use vanilla::{NodeTree, Pivot, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let panel_id = node_tree.create_child(root_id, "panel");
  node_tree[panel_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[panel_id].set_rect(100.0, 50.0, 200.0, 100.0);
  assert_eq!(node_tree.convert_view_to_local(panel_id, Vector2::create(110.0, 60.0)), Some(Vector2::create(10.0, 10.0)));
  node_tree[panel_id].set_local_scale(Vector2::zero());
  assert_eq!(node_tree.convert_view_to_local(panel_id, Vector2::create(110.0, 60.0)), None);
  ```

- `pub fn tick(&mut self, engine: &Engine, time_delta: f64)` (method, since 0.3.2): Periodic update. (depth first from the root: components → children, the original ComponentNode.tick)
  - Nodes destroyed during the iteration are destroyed after it finishes.
  - `engine` &Engine: Engine to pass to the component context.
  - `time_delta` f64: Time elapsed since the last tick. (seconds)
- `pub fn add_component<T: Component + 'static>(&mut self, node_id: NodeId, component: T) -> Option<&mut T>` (method, since 0.3.2): Adds a component. (calls attach then attach_to_tree so the component can create child nodes)
  - Components that create child nodes, like UIView, are added with this. Returns the added component.
  - Like the original addComponent, it takes its own slot first, and if a required component (require) is not on the node, attaches it the same way before attaching itself.
  - Required components and components attached together while attaching (like UIScrollView's Mask) come after it.
  - `node_id` NodeId: Node to attach.
  - `component` T: Component to add.
  - returns Option<&mut T>: The added component. (mutable) None if the node is missing.

  Example: Get the added component back, and nothing is attached to a destroyed node

  ```rust
  use vanilla::{NodeTree, Paint};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "panel");
  let paint = node_tree.add_component(node_id, Paint::new()).expect("node");
  paint.set_round_size(12.0);
  assert_eq!(node_tree[node_id].get_component::<Paint>().expect("paint").get_round_size(), 12.0);
  node_tree.destroy_node(node_id);
  assert!(node_tree.add_component(node_id, Paint::new()).is_none());
  ```

- `pub fn with_component_mut<T: Component + 'static, R>(&mut self, node_id: NodeId, action: impl FnOnce(&mut T, &mut NodeTree) -> R) -> Option<R>` (method, since 0.3.2): Calls with one component held together with the tree. (when scene code directly changes a component that also touches other nodes, like a widget)
  - Briefly takes out only the first T component of node node_id and passes that component and the tree to action. None if there is none.
  - Example: node_tree.`with_component_mut::<UIScrollView, _>`(scroll_id, |scroll_view, tree| scroll_view.set_scroll_offset_in_tree(tree, scroll_id, offset))
  - Nodes destroyed inside action are destroyed after action finishes.
  - `node_id` NodeId: Node the component is attached to.
  - `action` impl FnOnce(&mut T, &mut NodeTree) -> R: Function called with the taken-out component and the tree. (the component is out of the node meanwhile)
  - returns Option<R>: The value action returned. None if the node is missing or has no T component.

  Example: Create nodes in the tree while changing a component

  ```rust
  use vanilla::{NodeTree, Paint};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "panel");
  node_tree[node_id].add_component(Paint::new());
  let shadow_id = node_tree.with_component_mut::<Paint, _>(node_id, |paint, tree| {
  	paint.set_round_size(4.0);
  	tree.create_child(node_id, "shadow")
  }).expect("paint");
  assert_eq!(node_tree.get_parent_id(shadow_id), Some(node_id));
  assert_eq!(node_tree[node_id].get_component::<Paint>().expect("paint").get_round_size(), 4.0);
  ```

- `pub fn with_component_at_mut<R>(&mut self, node_id: NodeId, component_index: usize, action: impl FnOnce(&mut dyn Component, &mut NodeTree) -> R) -> Option<R>` (method, since 0.4.0): Calls with one component, by index, held together with the tree. (where the type is unknown, when UIDocument calls a reflection setter that takes the tree)
  - Briefly takes out the component_index-th component of node node_id and passes that component and the tree to action. None if there is none.
  - `node_id` NodeId: Node the component is attached to.
  - `component_index` usize: Component position. (order added, from 0)
  - `action` impl FnOnce(&mut dyn Component, &mut NodeTree) -> R: Function called with the taken-out component and the tree.
  - returns Option<R>: The value action returned. None if the node is missing or the position is out of range.

  Example: Read the name of the first component whose type is unknown

  ```rust
  use vanilla::{NodeTree, Paint};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "panel");
  node_tree[node_id].add_component(Paint::new());
  let component_type = node_tree.with_component_at_mut(node_id, 0, |component, _tree| component.get_component_type());
  assert_eq!(component_type, Some("Paint"));
  assert!(node_tree.with_component_at_mut(node_id, 1, |_component, _tree| ()).is_none());
  ```

- `pub fn draw(&mut self, graphic: &mut Graphic)` (method, since 0.3.2): Draws. (recursively from the root, the original Graphic.drawNode)
  - `graphic` &mut Graphic: Graphic to draw with. (adds the number of nodes skipped for being off screen)
- `pub fn draw_node(&mut self, node_id: NodeId, graphic: &mut Graphic)` (method, since 0.3.2): Draws one node and its descendants.
  - push_transform → the component's push_transform → (opacity layer begin) → components → (clip begin if Mask) → children → (clip end) → (opacity layer end) → gizmo → the component's pop_transform → pop_transform
  - `node_id` NodeId: Node to draw. (not drawn if missing or inactive)
  - `graphic` &mut Graphic: Graphic to draw with. (with the parent's transform applied)
- `pub fn draw_children(&mut self, node_id: NodeId, graphic: &mut Graphic)` (method, since 0.4.0): Draws the child list. (draw_node for each child in order, called by draw_node, original TransformNode.drawChildren)
  - With subtree culling on, narrows the visible child range by binary search with the visible rect in parent coordinates (Graphic::read_local_visible_bounds) and does not call the children before and after it.
    Children outside the range that would be counted when culled one by one are added with Graphic::add_culled_subtree_count. (the skipped subtree count is the same as culling one by one)
  - The current transform must be this node's content coordinates. (after push_transform)
  - `node_id` NodeId: Node whose children are drawn.
  - `graphic` &mut Graphic: Graphic to draw to.

  Example: Off-screen children are not called

  ```rust
  use vanilla::{NodeTree, Paint, Pivot};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let list_id = node_tree.create_child(root_id, "list");
  node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
  for row_index in 0..100 {
  	let row_id = node_tree.create_child(list_id, "row");
  	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
  	node_tree[row_id].set_rect(0.0, row_index as f64 * 40.0, 200.0, 36.0);
  	node_tree.add_component(row_id, Paint::new());
  }
  assert_eq!(node_tree.get_child_count(list_id), 100);
  ```

- `pub fn read_subtree_draw_bounds(&mut self, node_id: NodeId, graphic: &mut Graphic) -> Option<Rect>` (method, since 0.4.0): Reads the subtree draw bounds. (this node's content coordinates, the coordinates after push_transform, original TransformNode.readSubtreeDrawBounds)
  - The rect that holds everything this node and its enabled, visible descendants draw. Size 0 means nothing is drawn.
  - Recomputed only when something changed, otherwise the stored value is returned. The draw traversal skips the whole subtree when this rect is outside the screen and the clip.
  - Own drawing: calculate_drawn_rect of enabled drawing components (Component::is_draw_overridden). Components that draw only inside the content area count as the content area widened by one unit.
  - Children: bounding box in this node's content coordinates of each child's bounds moved by the child's transform (position, rotation, scale, pivot). Not reduced by a mask clip. (generous)
  - `node_id` NodeId: Node to read.
  - `graphic` &mut Graphic: Graphic used to compute the components' drawn rects. (text measuring)
  - returns Option<Rect>: Bounds. None if it holds something that draws somewhere unknown (a component that does not report its bounds, a node that draws gizmos) or the node does not exist.

  Example: Child bounds gather in parent coordinates

  ```rust
  use vanilla::{Graphic, NodeTree, Paint, Pivot, Rect};
  
  fn read_bounds(graphic: &mut Graphic) {
  	let mut node_tree = NodeTree::new();
  	let root_id = node_tree.get_root_id();
  	let list_id = node_tree.create_child(root_id, "list");
  	node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
  	let row_id = node_tree.create_child(list_id, "row");
  	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
  	node_tree[row_id].set_rect(10.0, 20.0, 100.0, 30.0);
  	node_tree.add_component(row_id, Paint::new());
  	let bounds = node_tree.read_subtree_draw_bounds(list_id, graphic).expect("known");
  	assert_eq!(bounds, Rect::create(9.0, 19.0, 102.0, 32.0));
  	assert_eq!(node_tree.read_parent_draw_bounds(row_id), Some(Rect::create(9.0, 19.0, 102.0, 32.0)));
  }
  ```

- `pub fn read_parent_draw_bounds(&self, node_id: NodeId) -> Option<Rect>` (method, since 0.4.0): Reads this node's subtree draw bounds stored by the parent. (parent's content coordinates, bounding box with this node's transform applied, original TransformNode.readParentDrawBounds)
  - The parent writes it for each child while computing its subtree bounds. When this node's transform or bounds change the parent recomputes, so it is used as is until then.
  - The draw traversal checks this rect first under the parent's transform and skips this node without applying its transform when it is outside the visible rect in parent coordinates.
  - `node_id` NodeId: Node to read.
  - returns Option<Rect>: Bounds in parent coordinates. None if the parent has not computed them yet, something changed since, or this node draws somewhere unknown. (size 0 if nothing is drawn)
- `pub fn find_topmost_interactable_node(&self, view_position: Vector2) -> Option<NodeId>` (method, since 0.3.2): Iterates in draw order to find the topmost interactable node under a point. (the original TouchRecognizer's target selection)
  - Inactive or invisible nodes and their descendants, and descendants outside a clipping (Mask) node, do not hit.
  - `view_position` Vector2: Point to check. (view coordinates)
  - returns Option<NodeId>: The touch-receiving node drawn last under the point. None if none.

  Example: Of two overlapping nodes, the one drawn later is hit

  ```rust
  use vanilla::{NodeTree, Pivot, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  for name in ["back", "front"] {
  	let node_id = node_tree.create_child(root_id, name);
  	node_tree[node_id].set_pivot(Pivot::TOP_LEFT);
  	node_tree[node_id].set_rect(0.0, 0.0, 100.0, 100.0);
  	node_tree[node_id].set_interactable(true);
  }
  let found_id = node_tree.find_topmost_interactable_node(Vector2::create(50.0, 50.0)).expect("node");
  assert_eq!(node_tree[found_id].get_name(), "front");
  assert_eq!(node_tree.find_topmost_interactable_node(Vector2::create(150.0, 50.0)), None);
  ```

- `pub fn dispatch_touch(&mut self, node_id: NodeId, engine: &Engine, touch_kind: TouchKind, view_input_position: Vector2)` (method, since 0.3.2): Dispatches a touch. (to the node's components)
  - Calls the enabled components in the order added, and nodes destroyed during the iteration are destroyed after it finishes.
  - `node_id` NodeId: Node to receive the touch.
  - `engine` &Engine: Engine to pass to the component context.
  - `touch_kind` TouchKind: Kind of touch function to call.
  - `view_input_position` Vector2: Touch position. (view coordinates)
- `pub fn find_wheel_target_node(&self, view_position: Vector2) -> Option<NodeId>` (method, since 0.4.0): Finds the node that receives the wheel at that position. (same draw order as find_topmost_interactable_node, None if none)
  - Among nodes containing that position, looks at pressable nodes and nodes of wheel-receiving panes (Component::is_wheel_receiver) and picks the frontmost (drawn last).
    If a scroll pane is frontmost, it is that pane's node. (the pane receives it even when scrolling over unpressable things in it like text or images)
  - If a pressable node is frontmost, it is that node. (dispatch_wheel asks upward toward the parents, a blocker or window covering a scroll pane blocks the wheel)
  - `view_position` Vector2: Point to check. (view coordinates)
  - returns Option<NodeId>: Node to receive the wheel. None if none.
- `pub fn dispatch_wheel_at(&mut self, view_position: Vector2, engine: &Engine, wheel_delta: Vector2) -> bool` (method, since 0.4.0): Dispatches the wheel at that position. (from the node found by find_wheel_target_node toward the parents, true if a component consumed it)
  - `view_position` Vector2: Position where the wheel was rolled. (view coordinates)
  - `engine` &Engine: Engine to pass to the component context.
  - `wheel_delta` Vector2: Wheel delta. (pixels, y is positive when scrolling the content down)
  - returns bool: True if a component consumed it. False if there is no node to receive it.
- `pub fn dispatch_wheel(&mut self, node_id: NodeId, engine: &Engine, wheel_delta: Vector2) -> bool` (method, since 0.3.2): Dispatches the wheel. (goes up from node_id itself toward the parents and stops at the first component that consumes it. The original touchWheel)
  - `node_id` NodeId: First node to ask.
  - `engine` &Engine: Engine to pass to the component context.
  - `wheel_delta` Vector2: Wheel delta. (pixels, y is positive when scrolling the content down)
  - returns bool: True if a component consumed it.

  Example: A list node's component receives the wheel scrolled over an item

  ```rust
  use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree, Vector2};
  
  struct Scroller {
  	component_base: ComponentBase,
  	scroll_offset: f64,
  }
  
  #[vanilla::reflect]
  impl Scroller {}
  
  #[vanilla::reflect]
  impl Component for Scroller {
  	fn wheel(&mut self, _context: &mut ComponentContext, wheel_delta: Vector2) -> bool {
  		self.scroll_offset += wheel_delta.y;
  		true
  	}
  }
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let list_id = node_tree.create_child(root_id, "list");
  node_tree[list_id].add_component(Scroller {
  	component_base: ComponentBase::new(),
  	scroll_offset: 0.0,
  });
  let item_id = node_tree.create_child(list_id, "item");
  assert!(node_tree.dispatch_wheel(item_id, &engine, Vector2::create(0.0, 40.0)));
  assert_eq!(node_tree[list_id].get_component::<Scroller>().expect("scroller").scroll_offset, 40.0);
  assert!(!node_tree.dispatch_wheel(root_id, &engine, Vector2::create(0.0, 40.0)));
  ```

- `pub fn get_local_bounds(&self, node_id: NodeId) -> Option<Rect>` (method, since 0.3.2): Node bounding rectangle relative to the parent area. (exact without rotation, for collision tests and such)
  - `node_id` NodeId: Node to look at.
  - returns Option<Rect>: Bounding rectangle in the parent's content coordinates. (NodeTransform::get_local_bounds) None if the node is missing.

## ComponentContext (struct)

Component context. (what a component receives on tick / touch: its own node, the whole tree, the engine)
- In place of the original component's get_node(), get_node().getParent(), Engine.get_engine().

Example: Find another node in the tree on tick and follow its position

```rust
use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree, Vector2};

struct Follower {
	component_base: ComponentBase,
}

#[vanilla::reflect]
impl Follower {}

#[vanilla::reflect]
impl Component for Follower {
	fn tick(&mut self, context: &mut ComponentContext, _time_delta: f64) {
		let node_tree = context.get_node_tree();
		let root_id = node_tree.get_root_id();
		if let Some(target_id) = node_tree.find_descendant_by_name(root_id, "target") {
			let target_position = node_tree[target_id].get_local_position();
			context.get_transform_mut().set_local_position(target_position);
		}
	}
}

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let target_id = node_tree.create_child(root_id, "target");
node_tree[target_id].set_local_position(Vector2::create(30.0, 40.0));
let follower_id = node_tree.create_child(root_id, "follower");
node_tree[follower_id].add_component(Follower {
	component_base: ComponentBase::new(),
});
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[follower_id].get_local_position(), Vector2::create(30.0, 40.0));
```

- `pub fn get_node_id(&self) -> NodeId` (method, since 0.3.2): Own node handle.
  - returns NodeId: Own node handle.
- `pub fn get_node(&self) -> &WorldNode` (method, since 0.3.2): Own node. (only the component being called is out of it, other components on the same node are found with get_component)
  - returns &WorldNode: Own node. (the component being called is out of it)
- `pub fn get_node_mut(&mut self) -> &mut WorldNode` (method, since 0.3.2): Own node. (mutable)
  - returns &mut WorldNode: Own node. (mutable, the component being called is out of it)
- `pub fn get_transform(&self) -> &NodeTransform` (method, since 0.3.2): Own node transform.
  - returns &NodeTransform: The own node's transform.
- `pub fn get_transform_mut(&mut self) -> &mut NodeTransform` (method, since 0.3.2): Own node transform. (mutable)
  - returns &mut NodeTransform: The own node's transform. (mutable)
- `pub fn get_node_tree(&self) -> &NodeTree` (method, since 0.3.2): The whole tree.
  - returns &NodeTree: The whole tree.
- `pub fn get_node_tree_mut(&mut self) -> &mut NodeTree` (method, since 0.3.2): The whole tree. (mutable. For changing, creating or destroying other nodes)
  - returns &mut NodeTree: The whole tree. (mutable, nodes destroyed during the iteration are destroyed after it finishes)
- `pub fn get_engine(&self) -> &'a Engine` (method, since 0.3.2): Engine. (input, time, view)
  - returns &'a Engine: Engine.
- `pub fn with_component_mut<T: Component + 'static, R>(&mut self, node_id: NodeId, action: impl FnOnce(&mut T, &mut ComponentContext) -> R) -> Option<R>` (method, since 0.3.2): Calls another node's (or its own node's) T component together with that node's context. (None if missing or currently taken out)
  - Used when a row button inside a widget calls the widget body: context.`with_component_mut::<UIDropdown, _>`(dropdown_id, |dropdown, dropdown_context| ...)
  - `node_id` NodeId: Node the T component is attached to.
  - `action` impl FnOnce(&mut T, &mut ComponentContext) -> R: Function called with the taken-out component and that node's context.
  - returns Option<R>: The value action returned. None if the node is missing, has no T component, or it is currently taken out.

  Example: A button node's component calls a counter component on another node

  ```rust
  use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree};
  
  struct Counter {
  	component_base: ComponentBase,
  	count: u32,
  }
  
  #[vanilla::reflect]
  impl Counter {}
  
  #[vanilla::reflect]
  impl Component for Counter {
  }
  
  struct Clicker {
  	component_base: ComponentBase,
  	counter_id: NodeId,
  }
  
  #[vanilla::reflect]
  impl Clicker {}
  
  #[vanilla::reflect]
  impl Component for Clicker {
  	fn tick(&mut self, context: &mut ComponentContext, _time_delta: f64) {
  		context.with_component_mut::<Counter, _>(self.counter_id, |counter, _counter_context| {
  			counter.count += 1;
  		});
  	}
  }
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let counter_id = node_tree.create_child(root_id, "counter");
  node_tree[counter_id].add_component(Counter {
  	component_base: ComponentBase::new(),
  	count: 0,
  });
  let clicker_id = node_tree.create_child(root_id, "clicker");
  node_tree[clicker_id].add_component(Clicker {
  	component_base: ComponentBase::new(),
  	counter_id,
  });
  node_tree.tick(&engine, 0.016);
  assert_eq!(node_tree[counter_id].get_component::<Counter>().expect("counter").count, 1);
  ```

## TouchKind (enum) (Clone, Copy, Debug, PartialEq, Eq)

Touch kind. (which component function NodeTree::dispatch_touch calls)

- `Press`: Press. (Component::touch_press)
- `Moved`: Move. (Component::touch_move)
- `Release`: Release. (Component::touch_release)
- `Cancel`: Cancel. (Component::touch_cancel)
