# core/tween (vanilla-engine 0.4.0)

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

트윈.
- 원본 core/tween.js 를 옮긴 것이다. 시작값 묶음(이름 → 숫자 또는 Vector2)과 목표값 묶음 사이를
  대기(delay) 뒤 duration 초 동안 이징 함수로 보간하고, tick 마다 보간한 값 묶음을 갱신 콜백에 넘긴다.
  다 가면 멈추고 완료 콜백을 부른다. 반복이나 요요는 원본에 없어서 옮기지 않았다.
- 원본의 Tween.easingFunction.back.easeOut 은 easing_function::back::ease_out 이다.
  이름은 두 엔진 모두 ease_in, ease_out, ease_in_out 이다. (원본 easeIn, easeOut, easeInOut, 예약어 in 을 이름으로 쓰지 않는다)
- 원본의 콜백은 노드 객체를 붙잡고 node.set_position(...) 을 부른다. 러스트 판은 노드가 씬의 NodeTree 에 있어서
  갱신 콜백과 완료 콜백이 &mut NodeTree 를 함께 받는다. (붙잡아 둔 NodeId 로 노드를 꺼내 쓴다)
- set_target(node_id): 값 이름이 노드 속성 이름(TweenProperty, 예: "localPosition")이면 tick 마다 그 노드에 바로 쓴다.
  대상 노드가 지워지면 콜백 없이 조용히 끝난다. create_node_tween 은 그것의 줄임이다. (원본 setTarget(node), createNodeTween)
  원본처럼 처음 돈 때의 노드 트리에서 떨어지면(맨 위 노드가 달라지면) 끝난다. 러스트 판은 destroy_node 로 지워져도 끝난다.
- 이징은 원본과 같은 공식이다. (원본 base/math.js 의 pow 도 내장 거듭제곱이라 exponential, elastic 값이 같다)
- duration 이 0 이하이면 바로 끝(진행률 1)으로 친다. (원본도 같다)
- 씬은 SceneBase::start_tween 으로 트윈을 넘겨받아 들고, 노드 tick → 터치 다음에 돌리며 끝난 트윈을 뺀다.
  원본은 트윈 객체를 들고 stop_tween(tween) 으로 가리키지만, 러스트 판은 씬이 트윈을 가져가므로(소유권이 넘어간다)
  start_tween 이 돌려준 TweenId 로 가리킨다. get_tween / get_tween_mut 은 그 때문에 있다.

## TweenValues (struct) (Clone, Debug, Default)

트윈 값 묶음. (원본의 { x: 0, y: 0 } 같은 객체 자리, 넣은 순서를 지킨다)
- 이름은 보통 문자열 상수("x")를 쓴다. 상수 이름은 복사할 때 메모리를 새로 잡지 않는다.

예제: 숫자와 Vector2 를 담고 꺼내기

```rust
use vanilla::{TweenValue, TweenValues, Vector2};

let mut values = TweenValues::new()
	.with("alpha", 0.0)
	.with("position", Vector2::create(10.0, 20.0));
values.set("alpha", 1.0);
assert_eq!(values.get_count(), 2);
assert_eq!(values.get_number("alpha"), Some(1.0));
assert_eq!(values.get("position"), Some(TweenValue::Vector2(Vector2::create(10.0, 20.0))));
assert_eq!(values.get_number("position"), None);
assert_eq!(values.get_vector2("missing"), None);
```

- `pub fn new() -> TweenValues` (constructor, since 0.3.2): 생성. (비어 있다)
  - returns TweenValues: 빈 묶음.
- `pub fn with(mut self, name: impl Into<Cow<'static, str>>, value: impl Into<TweenValue>) -> TweenValues` (method, since 0.3.2): 값을 넣고 자신을 돌려준다. (이어 쓰기용, 같은 이름이 있으면 바꾼다)
  - `name` impl Into<Cow<'static, str>>: 값 이름. (보통 문자열 상수, TweenProperty 이름이면 대상 노드의 그 속성에 쓴다)
  - `value` impl Into<TweenValue>: 값. (f64 또는 Vector2)
  - returns TweenValues: 값을 넣은 자신.
- `pub fn set(&mut self, name: impl Into<Cow<'static, str>>, value: impl Into<TweenValue>)` (method, since 0.3.2): 값 설정. (같은 이름이 있으면 바꾸고, 없으면 뒤에 붙인다)
  - `name` impl Into<Cow<'static, str>>: 값 이름.
  - `value` impl Into<TweenValue>: 값. (f64 또는 Vector2, 같은 이름의 값을 다른 종류로 바꿀 수도 있다)
- `pub fn get(&self, name: &str) -> Option<TweenValue>` (method, since 0.3.2): 값 반환. (없으면 None)
  - `name` &str: 찾을 값 이름.
  - returns Option<TweenValue>: 그 이름의 값. 없으면 None.
- `pub fn get_number(&self, name: &str) -> Option<f64>` (method, since 0.3.2): 숫자 값 반환. (없거나 숫자가 아니면 None)
  - `name` &str: 찾을 값 이름.
  - returns Option<f64>: 그 이름의 숫자. 없거나 Vector2 면 None.
- `pub fn get_vector2(&self, name: &str) -> Option<Vector2>` (method, since 0.3.2): Vector2 값 반환. (없거나 Vector2 가 아니면 None)
  - `name` &str: 찾을 값 이름.
  - returns Option<Vector2>: 그 이름의 Vector2. 없거나 숫자면 None.
- `pub fn get_count(&self) -> usize` (method, since 0.3.2): 값 수.
  - returns usize: 든 값의 수.

## TweenId (struct) (Clone, Copy, Debug, PartialEq, Eq, Hash)

트윈 핸들. (SceneBase::start_tween 이 돌려주고, stop_tween / get_tween 에 넘긴다)
- 트윈을 만들 때 정해지고 트윈마다 다르다. 씬이 트윈을 가져간 뒤에는 이것으로 가리킨다.

예제: 씬에 맡긴 트윈을 핸들로 찾고 멈추기

```rust
use vanilla::{SceneBase, Tween, TweenValues};

let mut scene_base = SceneBase::new();
let tween = Tween::new(TweenValues::new().with("value", 0.0)).to(TweenValues::new().with("value", 1.0), 2.0);
let tween_id = scene_base.start_tween(tween);
assert_eq!(scene_base.get_tween(tween_id).unwrap().get_tween_id(), tween_id);

scene_base.stop_tween(tween_id);
assert!(scene_base.get_tween(tween_id).is_none());
```

## Tween (struct)

트윈.
- 시작값 묶음과 목표값 묶음 사이를 대기 뒤 길이(초) 동안 이징 함수로 보간한다. tick 마다 보간한 값을 갱신 콜백에 넘기고, 다 가면 완료 콜백을 부른다.
- 만든 뒤 to, delay, easing, set_update, set_complete, set_target 을 이어 붙여 정하고, start 한 뒤 tick 을 부른다. (씬은 SceneBase::start_tween 이 start 와 tick 을 맡는다)

예제: 대기 뒤 0 에서 10 으로

```rust
use vanilla::{easing_function, NodeTree, Tween, TweenValues};
use std::cell::Cell;
use std::rc::Rc;

let mut node_tree = NodeTree::new();
let last_value = Rc::new(Cell::new(-1.0f64));
let last_value_in_callback = last_value.clone();
let mut tween = Tween::new(TweenValues::new().with("value", 0.0))
	.to(TweenValues::new().with("value", 10.0), 1.0)
	.delay(0.5)
	.easing(easing_function::linear)
	.set_update(move |values, _node_tree| {
		last_value_in_callback.set(values.get_number("value").unwrap());
	});
tween.start();
tween.tick(&mut node_tree, 0.25);
assert_eq!(last_value.get(), -1.0);
tween.tick(&mut node_tree, 0.75);
assert_eq!(last_value.get(), 5.0);
tween.tick(&mut node_tree, 0.5);
assert_eq!(last_value.get(), 10.0);
assert!(tween.is_finished());
```

- `pub fn new(initial_values: TweenValues) -> Tween` (constructor, since 0.3.2): 생성. (시작값 묶음을 받는다. 길이 1초, 대기 0, linear)
  - `initial_values` TweenValues: 시작값 묶음. (목표값에 같은 이름이 있는 값만 보간한다)
  - returns Tween: 목표값이 비고 멈춘 새 트윈. (start 해야 돈다)
- `pub fn create_node_tween(node_id: NodeId, tween_property: TweenProperty, start_value: impl Into<TweenValue>, end_value: impl Into<TweenValue>, duration: f64) -> Tween` (static, since 0.3.2): 노드 속성 하나를 움직이는 트윈 생성.
  - Tween::new(시작값).to(목표값, duration).set_target(node_id) 와 같다. 값 이름은 속성 이름이다.
  - `node_id` NodeId: 움직일 노드.
  - `tween_property` TweenProperty: 움직일 노드 속성.
  - `start_value` impl Into<TweenValue>: 시작값. (f64 또는 Vector2, Vector2 속성에 숫자를 주면 두 축에 같이 쓴다)
  - `end_value` impl Into<TweenValue>: 목표값. (start_value 와 같은 종류)
  - `duration` f64: 길이. (초, 0 이하면 첫 tick 에 끝난다)
  - returns Tween: 대상 노드가 정해진 멈춘 새 트윈. (start 하거나 SceneBase::start_tween 에 넘긴다)

  예제: 노드를 1 초 동안 오른쪽 아래로

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "Mover");
  let mut tween = Tween::create_node_tween(node_id, TweenProperty::LocalPosition, Vector2::zero(), Vector2::create(100.0, 50.0), 1.0);
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_position(), Vector2::create(50.0, 25.0));
  ```

- `pub fn find_root_node(node_tree: &NodeTree, node_id: NodeId) -> NodeId` (static, since 0.4.0): 노드의 맨 위 노드 반환. (부모를 따라 올라간다, 원본 Tween.findRootNode)
  - `node_tree` &NodeTree: 노드가 든 트리.
  - `node_id` NodeId: 올라가기 시작할 노드.
  - returns NodeId: 부모가 없는 맨 위 노드. (node_id 에 부모가 없으면 node_id 그대로)

  예제: 루트에 붙은 노드와 떨어진 노드

  ```rust
  use vanilla::{NodeTree, Tween};
  
  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");
  assert_eq!(Tween::find_root_node(&node_tree, child_id), root_id);
  
  let loose_id = node_tree.create_node("Loose");
  assert_eq!(Tween::find_root_node(&node_tree, loose_id), loose_id);
  ```

- `pub fn tick(&mut self, node_tree: &mut NodeTree, time_delta: f64)` (method, since 0.3.2): 갱신.
  - 대기 시간이 지나면 진행률(0 ~ 1)에 이징을 걸어 목표값 이름 순서로 보간한다.
    시작값에 없는 이름, 시작값과 종류(숫자 / Vector2)가 다른 이름은 건너뛴다. (원본과 같음)
  - 대상 노드가 있으면 노드 속성 이름의 값을 그 노드에 쓰고, 갱신 콜백을 부른다.
  - 진행률이 1 이 되면 멈추고 완료 콜백을 부른다.
  - start 전이나 끝난 뒤에는 아무것도 하지 않는다. 대상 노드가 지워졌거나 처음 돈 때의 맨 위 노드에서 떨어졌으면 콜백 없이 끝낸다.
  - `node_tree` &mut NodeTree: 대상 노드에 쓰고 콜백에 넘길 노드 트리.
  - `time_delta` f64: 지난 시간. (초)

  예제: 노드를 흐리게 하다가 노드가 지워지면 조용히 끝나기

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = node_tree.create_child(root_id, "Fader");
  let mut tween = Tween::create_node_tween(node_id, TweenProperty::LocalOpacity, 1.0, 0.0, 1.0);
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_opacity(), 1.0);
  
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert_eq!(node_tree[node_id].get_local_opacity(), 0.5);
  
  node_tree.destroy_node(node_id);
  tween.tick(&mut node_tree, 0.5);
  assert!(tween.is_finished());
  ```

- `pub fn to(mut self, properties: TweenValues, duration: f64) -> Tween` (method, since 0.3.2): 목표값 설정. (길이도 함께 정한다)
  - `properties` TweenValues: 목표값 묶음. (이 묶음의 순서로 보간해 갱신 콜백에 넘긴다)
  - `duration` f64: 길이. (초, 대기 시간은 빼고, 0 이하면 첫 tick 에 끝난다)
  - returns Tween: 목표값을 정한 자신.
- `pub fn delay(mut self, amount: f64) -> Tween` (method, since 0.3.2): 시작 전 대기 시간 설정. (초)
  - `amount` f64: start 한 뒤 보간을 시작하기까지 기다릴 시간. (초, 처음 0)
  - returns Tween: 대기 시간을 정한 자신.
- `pub fn easing(mut self, easing_function: impl Fn(f64) -> f64 + 'static) -> Tween` (method, since 0.3.2): 이징 함수 설정. (easing_function 모듈의 함수, 또는 진행률을 받아 비율을 돌려주는 아무 함수)
  - `easing_function` impl Fn(f64) -> f64 + 'static: 진행률(0 ~ 1)을 받아 보간 비율을 돌려주는 함수. (처음 easing_function::linear)
  - returns Tween: 이징 함수를 정한 자신.

  예제: 네 계단으로 끊어 움직이기

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues};
  use std::cell::Cell;
  use std::rc::Rc;
  
  let mut node_tree = NodeTree::new();
  let last_value = Rc::new(Cell::new(0.0f64));
  let last_value_in_callback = last_value.clone();
  let mut tween = Tween::new(TweenValues::new().with("value", 0.0))
  	.to(TweenValues::new().with("value", 8.0), 1.0)
  	.easing(|progress| (progress * 4.0).floor() / 4.0)
  	.set_update(move |values, _node_tree| {
  		last_value_in_callback.set(values.get_number("value").unwrap());
  	});
  tween.start();
  tween.tick(&mut node_tree, 0.3);
  assert_eq!(last_value.get(), 2.0);
  ```

- `pub fn set_update(mut self, callback: impl FnMut(&TweenValues, &mut NodeTree) + 'static) -> Tween` (method, since 0.3.2): 갱신 콜백 설정. (보간한 값 묶음과 노드 트리를 받는다)
  - `callback` impl FnMut(&TweenValues, &mut NodeTree) + 'static: 보간한 값 묶음과 노드 트리를 받는 함수. (대기가 끝난 뒤 tick 마다, 끝나는 tick 에도 불린다, 대상 노드에 쓴 다음에 불린다)
  - returns Tween: 갱신 콜백을 정한 자신.

  예제: 보간한 값으로 다른 노드 옮기기

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let label_id = node_tree.create_child(root_id, "Label");
  let mut tween = Tween::new(TweenValues::new().with("x", 0.0))
  	.to(TweenValues::new().with("x", 200.0), 2.0)
  	.set_update(move |values, node_tree| {
  		let position_x = values.get_number("x").unwrap();
  		node_tree[label_id].set_local_position(Vector2::create(position_x, 0.0));
  	});
  tween.start();
  tween.tick(&mut node_tree, 1.0);
  assert_eq!(node_tree[label_id].get_local_position(), Vector2::create(100.0, 0.0));
  ```

- `pub fn set_complete(mut self, callback: impl FnMut(&mut NodeTree) + 'static) -> Tween` (method, since 0.3.2): 완료 콜백 설정. (노드 트리를 받는다)
  - `callback` impl FnMut(&mut NodeTree) + 'static: 노드 트리를 받는 함수. (진행률이 1 이 된 tick 에 갱신 콜백 다음 한 번 불린다, stop 이나 대상 노드가 사라져 끝나면 불리지 않는다)
  - returns Tween: 완료 콜백을 정한 자신.

  예제: 다 흐려지면 노드 지우기

  ```rust
  use vanilla::{NodeTree, Tween, TweenProperty};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let toast_id = node_tree.create_child(root_id, "Toast");
  let mut tween = Tween::create_node_tween(toast_id, TweenProperty::LocalOpacity, 1.0, 0.0, 0.5)
  	.set_complete(move |node_tree| {
  		node_tree.destroy_node(toast_id);
  	});
  tween.start();
  tween.tick(&mut node_tree, 0.5);
  assert!(tween.is_finished());
  assert!(!node_tree.contains(toast_id));
  ```

- `pub fn set_target(mut self, node_id: NodeId) -> Tween` (method, since 0.3.2): 대상 노드 설정. (값 이름이 TweenProperty 이름이면 이 노드에 쓴다)
  - `node_id` NodeId: 대상 노드. (지워지거나 처음 돈 때의 맨 위 노드에서 떨어지면 트윈이 조용히 끝난다)
  - returns Tween: 대상 노드를 정한 자신.

  예제: 배율과 회전을 함께 움직이기

  ```rust
  use vanilla::{NodeTree, Tween, TweenValues, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let card_id = node_tree.create_child(root_id, "Card");
  let mut tween = Tween::new(TweenValues::new().with("localScale", 0.5).with("localRotation", 0.0))
  	.to(TweenValues::new().with("localScale", 1.0).with("localRotation", 90.0), 1.0)
  	.set_target(card_id);
  tween.start();
  tween.tick(&mut node_tree, 1.0);
  assert_eq!(node_tree[card_id].get_local_scale(), Vector2::create(1.0, 1.0));
  assert_eq!(node_tree[card_id].get_local_rotation(), 90.0);
  ```

- `pub fn start(&mut self)` (method, since 0.3.2): 시작. (이미 재생 중이면 아무것도 하지 않는다)
- `pub fn stop(&mut self)` (method, since 0.3.2): 정지. (완료 콜백은 부르지 않는다)
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): 완료 여부 반환.
  - returns bool: 끝났으면 true. (다 갔거나, stop 했거나, 대상 노드가 사라졌을 때, start 하면 다시 false)
- `pub fn get_tween_id(&self) -> TweenId` (method, since 0.3.2): 핸들 반환.
  - returns TweenId: 이 트윈의 핸들. (만들 때 정해진다)
- `pub fn get_target_node_id(&self) -> Option<NodeId>` (method, since 0.3.2): 대상 노드 핸들 반환. (set_target 을 하지 않았으면 None)
  - returns Option<NodeId>: 대상 노드. set_target 을 하지 않았으면 None.

## TweenValue (enum) (Clone, Copy, Debug, PartialEq, From<f64>, From<Vector2>)

트윈 값. (원본은 숫자와 Vector2 만 보간한다)

- `Number` = `Number(f64)`: 숫자 하나. (불투명도, 회전 같은 값)
- `Vector2` = `Vector2(Vector2)`: 2차원 벡터. (위치, 배율, 크기 같은 값, 두 축을 따로 보간한다)

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

트윈이 바로 쓰는 노드 속성. (set_target 으로 대상 노드를 정했을 때, 값 이름이 이 이름이면 그 노드에 쓴다)
- Vector2 속성에 숫자를 주면 두 축에 같이 쓴다. (원본 예제의 set_scale(Vector2.one().multiply(v.scale)) 자리)
- 숫자 속성에 Vector2 를 주면 쓰지 않는다.

- `LocalPosition`: 로컬 위치. (이름 "localPosition", Vector2 또는 두 축에 같이 쓸 숫자)
- `LocalScale`: 로컬 배율. (이름 "localScale", Vector2 또는 두 축에 같이 쓸 숫자)
- `LocalRotation`: 로컬 회전. (이름 "localRotation", 도, 숫자만)
- `LocalOpacity`: 로컬 불투명도. (이름 "localOpacity", 숫자만, 노드가 0 ~ 1 로 맞춘다)
- `ContentSize`: 내용 크기. (이름 "contentSize", Vector2 또는 두 축에 같이 쓸 숫자)

- `pub fn get_name(&self) -> &'static str` (method, since 0.3.2): 값 묶음에서 쓰는 이름. (enum 이름의 첫 글자를 소문자로 쓴 원본 속성 이름, localPosition 같은)
  - returns &'static str: 값 묶음에서 쓰는 속성 이름. ("localPosition" 처럼 첫 글자가 소문자)
- `pub fn find_by_name(name: &str) -> Option<TweenProperty>` (static, since 0.3.2): 이름으로 찾기. (노드 속성 이름이 아니면 None)
  - `name` &str: 값 이름. (get_name 이 돌려주는 이름과 견준다, 대소문자를 가린다)
  - returns Option<TweenProperty>: 그 이름의 속성. 노드 속성 이름이 아니면 None.

  예제: 속성 이름과 아닌 이름

  ```rust
  use vanilla::TweenProperty;
  
  assert_eq!(TweenProperty::find_by_name("localScale"), Some(TweenProperty::LocalScale));
  assert_eq!(TweenProperty::find_by_name("scale"), None);
  assert_eq!(TweenProperty::LocalScale.get_name(), "localScale");
  ```

- `pub fn apply_to_node(&self, node: &mut WorldNode, value: TweenValue)` (method, since 0.3.2): 노드에 값 쓰기.
  - Vector2 속성(위치, 배율, 내용 크기)에 숫자를 주면 두 축에 같이 쓴다. 숫자 속성(회전, 불투명도)에 Vector2 를 주면 쓰지 않는다.
  - `node` &mut WorldNode: 값을 쓸 노드.
  - `value` TweenValue: 쓸 값.

  예제: 숫자 하나로 두 축 배율 쓰기

  ```rust
  use vanilla::{TweenProperty, TweenValue, Vector2, WorldNode};
  
  let mut node = WorldNode::new("Node");
  TweenProperty::LocalScale.apply_to_node(&mut node, TweenValue::Number(2.0));
  assert_eq!(node.get_local_scale(), Vector2::create(2.0, 2.0));
  
  TweenProperty::LocalRotation.apply_to_node(&mut node, TweenValue::Vector2(Vector2::create(1.0, 1.0)));
  assert_eq!(node.get_local_rotation(), 0.0);
  ```

