# animation/action (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/animation/action/

Action. (a script-style sequence that runs steps in order)
- A port of the original animation/action.js. Stack wait / condition / call / repeat / forever / loop steps,
  then call step every frame after start and they run in order.
- Usage:
  ```text
    let mut action: Action<WorldNode> = Action::new()
        .wait(1.0, ActionCallbacks::new().updated(|progress, node: &mut WorldNode| node.set_local_opacity(progress)))
        .condition(|node: &WorldNode| node.is_active(), ActionConditionCallbacks::new())
        .call(|node: &mut WorldNode| node.set_local_scale(Vector2::create(2.0, 2.0)))
        .repeat(3, Action::new().wait(0.5, ActionCallbacks::new()))
        .forever(Action::new().wait(2.0, ActionCallbacks::new()));
    action.start(&mut node_tree, Some(node_id));
    // every frame:
    action.step(&mut node_tree, time_delta);
  ```
- Differences from the original:
  - The original start(target) holds the target and passes it to callbacks on every step(timeDelta). Rust cannot hold a borrowed target,
    so a node target is held as a handle: start(tree, Some(node)) holds the target and step(tree, time) passes that node to the callbacks,
    get_target returns that node, and start(tree, None) restarts with the previous target like the original start().
  - The form that does not hold a target and passes it every time is start_with(target), step_with(target, time) in both engines. (original startWith, stepWith)
    Use T for a target that is not a node (several nodes, game state) and run it in this form. (the default of T is WorldNode)
    The inner actions of repeat, forever, and loop also run in this form in both engines and do not hold a target. (get_target of an inner action is unchanged)
  - Callback objects ({ started, updated, completed }): the wait step uses ActionCallbacks (updated takes (progress, target)),
    and the condition step uses ActionConditionCallbacks (updated takes (target)). The original is one object form that differs only in argument count,
    but Rust must fix the argument shape of a callback as a type, so it is split in two.
  - The conditional loop is repeat_while in both engines. (original repeatWhile; the reserved word loop is not used as a name)
  - When call steps follow one another, the original passes through recursion and the Rust version through a loop. (the result is the same)
- The condition function receives the target like the original (&T in Rust). wait finishes with progress 1 if duration is 0 or less.
  repeat skips without running if the count is 0. (same as the original)

## ActionCallbacks (struct) (Default)

Step callback set. (the original { started, updated, completed })
- Passed to a wait step. Chain started, updated and completed like a builder. Callbacks left empty are not called.

Example: Start, progress and completion callbacks of a wait step

```rust
use vanilla::{Action, ActionCallbacks};

let mut record: Vec<f64> = Vec::new();
let mut action: Action<Vec<f64>> = Action::new()
	.wait(1.0, ActionCallbacks::new()
		.started(|record: &mut Vec<f64>| record.push(-1.0))
		.updated(|progress, record: &mut Vec<f64>| record.push(progress))
		.completed(|record: &mut Vec<f64>| record.push(2.0)));
action.start_with(&mut record);
action.step_with(&mut record, 0.5);
action.step_with(&mut record, 0.5);
assert_eq!(record, vec![-1.0, 0.5, 1.0, 2.0]);
assert!(action.is_done());
```

- `pub fn new() -> ActionCallbacks<T>` (constructor, since 0.3.2): Constructor. (all empty, the original {})
  - returns ActionCallbacks<T>: A set with no callbacks.
- `pub fn started(mut self, callback: impl FnMut(&mut T) + 'static) -> ActionCallbacks<T>` (method, since 0.3.2): Callback called when the step starts. ((target))
  - `callback` impl FnMut(&mut T) + 'static: Function called once when the step starts. (takes the target) Replaces any existing start callback.
  - returns ActionCallbacks<T>: The set with the start callback added. (for chaining)
- `pub fn updated(mut self, callback: impl FnMut(f64, &mut T) + 'static) -> ActionCallbacks<T>` (method, since 0.3.2): Callback called every frame. ((progress 0 ~ 1, target). progress is 0 for condition steps)
  - `callback` impl FnMut(f64, &mut T) + 'static: Function called on every step while the step runs. (takes progress 0 ~ 1 and the target, 1 on the last frame) Replaces any existing update callback.
  - returns ActionCallbacks<T>: The set with the update callback added. (for chaining)
- `pub fn completed(mut self, callback: impl FnMut(&mut T) + 'static) -> ActionCallbacks<T>` (method, since 0.3.2): Callback called when the step completes. ((target))
  - `callback` impl FnMut(&mut T) + 'static: Function called once when the step ends. (right after the last update callback, takes the target) Replaces any existing completion callback.
  - returns ActionCallbacks<T>: The set with the completion callback added. (for chaining)

## ActionConditionCallbacks (struct) (Default)

Condition step callback set. (the original { started, updated, completed }, updated takes only (target))
- Passed to a condition step. Chain like a builder; callbacks left empty are not called.

Example: Count the frames waited until the door opens

```rust
use vanilla::{Action, ActionConditionCallbacks};

struct Door {
	is_open: bool,
	waited_frame_count: u32,
	is_passed: bool,
}

let mut door = Door { is_open: false, waited_frame_count: 0, is_passed: false };
let mut action: Action<Door> = Action::new()
	.condition(|door: &Door| door.is_open, ActionConditionCallbacks::new()
		.updated(|door: &mut Door| door.waited_frame_count += 1)
		.completed(|door: &mut Door| door.is_passed = true));
action.start_with(&mut door);
action.step_with(&mut door, 0.016);
action.step_with(&mut door, 0.016);
assert!(!door.is_passed);
door.is_open = true;
action.step_with(&mut door, 0.016);
assert_eq!(door.waited_frame_count, 3);
assert!(door.is_passed);
assert!(action.is_done());
```

- `pub fn new() -> ActionConditionCallbacks<T>` (constructor, since 0.4.0): Constructor. (all empty, the original {})
  - returns ActionConditionCallbacks<T>: A set with no callbacks.
- `pub fn started(mut self, callback: impl FnMut(&mut T) + 'static) -> ActionConditionCallbacks<T>` (method, since 0.4.0): Callback called when the step starts. ((target))
  - `callback` impl FnMut(&mut T) + 'static: Function called once when the step starts. (takes the target) Replaces any existing start callback.
  - returns ActionConditionCallbacks<T>: The set with the start callback added. (for chaining)
- `pub fn updated(mut self, callback: impl FnMut(&mut T) + 'static) -> ActionConditionCallbacks<T>` (method, since 0.4.0): Callback called every frame before the condition is met. ((target))
  - `callback` impl FnMut(&mut T) + 'static: Function called on every step before checking the condition. (takes the target, also called once on the frame the condition becomes true) Replaces any existing update callback.
  - returns ActionConditionCallbacks<T>: The set with the update callback added. (for chaining)
- `pub fn completed(mut self, callback: impl FnMut(&mut T) + 'static) -> ActionConditionCallbacks<T>` (method, since 0.4.0): Callback called when the condition is met. ((target))
  - `callback` impl FnMut(&mut T) + 'static: Function called once on the frame the condition becomes true. (takes the target) Replaces any existing completion callback.
  - returns ActionConditionCallbacks<T>: The set with the completion callback added. (for chaining)

## Action (struct) (Default)

Action.
- Stack steps like a builder, and after start, calling step every frame runs them in order. (to pass the target every time, use start_with, step_with) The target type T defaults to WorldNode.

Example: Fade in a node, check whether it is active, scale it up, then wait repeatedly

```rust
use vanilla::{Action, ActionCallbacks, ActionConditionCallbacks, Vector2, WorldNode};

let mut node = WorldNode::new("hero");
let mut action: Action<WorldNode> = Action::new()
	.wait(1.0, ActionCallbacks::new().updated(|progress, node: &mut WorldNode| node.set_local_opacity(progress)))
	.condition(|node: &WorldNode| node.is_active(), ActionConditionCallbacks::new())
	.call(|node: &mut WorldNode| node.set_local_scale(Vector2::create(2.0, 2.0)))
	.repeat(3, Action::new().wait(0.5, ActionCallbacks::new()))
	.forever(Action::new().wait(2.0, ActionCallbacks::new()));
action.start_with(&mut node);
action.step_with(&mut node, 0.5);
assert_eq!(node.get_local_opacity(), 0.5);
action.step_with(&mut node, 0.5);
assert_eq!(node.get_local_opacity(), 1.0);
action.step_with(&mut node, 0.0);
assert_eq!(node.get_local_scale(), Vector2::create(2.0, 2.0));
for _ in 0..10 {
	action.step_with(&mut node, 0.5);
}
assert!(action.is_running());
assert!(!action.is_done());
```

- `pub fn new() -> Action<T>` (constructor, since 0.3.2): Constructor. (no steps, stopped)
  - returns Action<T>: An action with no steps that is not running. (start without steps ends immediately)
- `pub fn wait(mut self, duration: f64, callbacks: ActionCallbacks<T>) -> Action<T>` (method, since 0.3.2): Waits for a set time. (started(target), updated(progress 0 ~ 1, target) every frame, completed(target))
  - `duration` f64: Time to wait. (seconds, measured by adding the time_delta passed to step) If 0 or less, ends with progress 1 on the first step.
  - `callbacks` ActionCallbacks<T>: Start, update and completion callback set.
  - returns Action<T>: The action with a wait step appended. (for chaining)
- `pub fn condition(mut self, condition_function: impl FnMut(&T) -> bool + 'static, callbacks: ActionConditionCallbacks<T>) -> Action<T>` (method, since 0.3.2): Waits until the condition becomes true. (started(target), updated(target) every frame before the condition is met, completed(target))
  - `condition_function` impl FnMut(&T) -> bool + 'static: Function that takes the target and moves on if true. (not checked in start, checked on every step)
  - `callbacks` ActionConditionCallbacks<T>: Start, update and completion callback set.
  - returns Action<T>: The action with a condition step appended. (for chaining)
- `pub fn call(mut self, function: impl FnMut(&mut T) + 'static) -> Action<T>` (method, since 0.3.2): Calls a callback immediately.
  - `function` impl FnMut(&mut T) + 'static: Function called as soon as this step is reached. (takes the target, moves to the next step in the same frame)
  - returns Action<T>: The action with a call step appended. (for chaining)
- `pub fn repeat(mut self, times: u32, inner_action: Action<T>) -> Action<T>` (method, since 0.3.2): Repeats the inner action times times. (moves on without running if 0)
  - `times` u32: Repeat count. If 0, moves on without starting the inner action.
  - `inner_action` Action<T>: Action to repeat. (started again from the beginning each time it ends)
  - returns Action<T>: The action with a repeat step appended. (for chaining)

  Example: Wait 0.5 seconds three times

  ```rust
  use vanilla::{Action, ActionCallbacks};
  
  let mut count: u32 = 0;
  let inner_action: Action<u32> = Action::new().wait(0.5, ActionCallbacks::new().completed(|count: &mut u32| *count += 1));
  let mut action: Action<u32> = Action::new().repeat(3, inner_action);
  action.start_with(&mut count);
  for _ in 0..3 {
  	action.step_with(&mut count, 0.5);
  }
  assert_eq!(count, 3);
  assert!(action.is_done());
  ```

- `pub fn forever(mut self, inner_action: Action<T>) -> Action<T>` (method, since 0.3.2): Repeats the inner action forever.
  - `inner_action` Action<T>: Action to repeat. (started again from the beginning each time it ends)
  - returns Action<T>: The action with a forever step appended. (for chaining, steps after this are never reached. Use stop to halt)
- `pub fn repeat_while(mut self, condition_function: impl FnMut(&T) -> bool + 'static, inner_action: Action<T>) -> Action<T>` (method, since 0.4.0): Repeats the inner action while the condition is true. (asks at the start and each time the inner one finishes)
  - `condition_function` impl FnMut(&T) -> bool + 'static: Function that takes the target and runs the inner action (again) if true. If false from the start, the inner action is skipped.
  - `inner_action` Action<T>: Action to repeat.
  - returns Action<T>: The action with a loop step appended. (for chaining)

  Example: Raise a value by one every 0.1 seconds until it reaches 3

  ```rust
  use vanilla::{Action, ActionCallbacks};
  
  let mut count: u32 = 0;
  let inner_action: Action<u32> = Action::new().wait(0.1, ActionCallbacks::new().completed(|count: &mut u32| *count += 1));
  let mut action: Action<u32> = Action::new().repeat_while(|count: &u32| *count < 3, inner_action);
  action.start_with(&mut count);
  for _ in 0..10 {
  	action.step_with(&mut count, 0.1);
  }
  assert_eq!(count, 3);
  assert!(action.is_done());
  ```

- `pub fn start_with(&mut self, target: &mut T)` (method, since 0.4.0): Starts running without holding the target. (the original startWith(target), from the first step)
  - Leading call steps run right here. If it was running, it starts over. The target is not held. (get_target stays as it was)
  - `target` &mut T: Target passed to the callbacks. (calls up to the first step's start callback right here)
- `pub fn stop(&mut self)` (method, since 0.3.2): Stops running. (counts as finished)
- `pub fn step_with(&mut self, target: &mut T, time_delta: f64)` (method, since 0.4.0): Updates with a given target. (the original stepWith(target, timeDelta), call every frame)
  - Does nothing before start or after it is done. Advances only one step at a time, and call steps after a finished step run in the same frame.
  - `target` &mut T: Target passed to the callbacks.
  - `time_delta` f64: Time elapsed since the last frame. (seconds, wait steps add this up)

  Example: Run an action in the scene tick

  ```rust
  use vanilla::{Action, ActionCallbacks, WorldNode};
  
  struct FadeIn {
  	node: WorldNode,
  	action: Action,
  }
  
  impl FadeIn {
  	fn new() -> FadeIn {
  		let mut fade_in = FadeIn {
  			node: WorldNode::new("logo"),
  			action: Action::new().wait(2.0, ActionCallbacks::new().updated(|progress, node: &mut WorldNode| node.set_local_opacity(progress))),
  		};
  		fade_in.action.start_with(&mut fade_in.node);
  		fade_in
  	}
  
  	fn tick(&mut self, time_delta: f64) {
  		self.action.step_with(&mut self.node, time_delta);
  	}
  }
  
  let mut fade_in = FadeIn::new();
  fade_in.tick(1.0);
  assert_eq!(fade_in.node.get_local_opacity(), 0.5);
  fade_in.tick(1.0);
  assert!(fade_in.action.is_done());
  ```

- `pub fn is_done(&self) -> bool` (method, since 0.3.2): Returns whether it is complete.
  - returns bool: true if every step has finished or stop was called. (false before start, false for forever until stop)
- `pub fn is_running(&self) -> bool` (method, since 0.3.2): Returns whether it is running.
  - returns bool: true if started and not yet finished.
- `pub fn start(&mut self, node_tree: &mut NodeTree, node_id: Option<NodeId>) -> bool` (method, since 0.3.2): Starts running with a node as the target. (the original start(target), from the first step)
  - Holds the target as a node handle, so step passes that node to the callbacks and get_target returns it.
  - If `node_id` is None, restarts with the previous target (the node given to start before) like the original.
  - `node_tree` &mut NodeTree: The tree that holds the target node.
  - `node_id` Option<NodeId>: The target node. (None means the previous target)
  - returns bool: true if it started. false if there is no target or that node was removed. (it does not start then)

  Example: Run with a node target, then restart without giving a target

  ```rust
  use vanilla::{Action, ActionCallbacks, NodeTree, WorldNode};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let logo_id = node_tree.create_child(root_id, "logo");
  let mut action: Action = Action::new().wait(2.0, ActionCallbacks::new().updated(|progress, node: &mut WorldNode| node.set_local_opacity(progress)));
  assert!(action.start(&mut node_tree, Some(logo_id)));
  assert_eq!(action.get_target(), Some(logo_id));
  action.step(&mut node_tree, 1.0);
  assert_eq!(node_tree[logo_id].get_local_opacity(), 0.5);
  
  assert!(action.start(&mut node_tree, None));
  action.step(&mut node_tree, 0.5);
  assert_eq!(node_tree[logo_id].get_local_opacity(), 0.25);
  ```

- `pub fn step(&mut self, node_tree: &mut NodeTree, time_delta: f64)` (method, since 0.3.2): Updates with the target node. (the original step(timeDelta), call every frame)
  - Passes the node given to start to the callbacks. Does nothing if there is no target or that node was removed.
  - `node_tree` &mut NodeTree: The tree that holds the target node.
  - `time_delta` f64: Time elapsed since the last frame. (seconds)
- `pub fn get_target(&self) -> Option<NodeId>` (method, since 0.4.0): Returns the target. (the original getTarget)
  - returns Option<NodeId>: The target node given to start. None if there is none. (a target lent with start_with(&mut node) is not held)
