# misc/spriteanimator (vanilla-engine 0.4.0)

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

스프라이트 애니메이터 컴포넌트.
- 원본 misc/spriteanimator.js 를 옮긴 것이다. 이름을 붙인 클립(프레임 시퀀스)을 등록해 두고 play("run") 으로 바꾼다.
- 같은 클립을 다시 play 해도 처음부터 하지 않는다. (restart_if_same 으로 바꿀 수 있다)
- 클립이 끝나면 on_complete 콜백으로 다음 상태를 이어 간다. (FSM 과 묶어 쓴다)
- 같은 노드의 Sprite 컴포넌트에 지금 프레임(이미지 + 영역)을 넣는다. 원본 findSprite 처럼 한 번 찾으면 기억한다. (find_sprite)
- 사용:
  ```text
    let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
    animator.add_clip("idle", image.clone(), &idleRects, 10.0, true);
    animator.add_clip("attack", image.clone(), &attackRects, 12.0, false);
    SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
        animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
    }));
  ```
- play 는 원본처럼 그 자리에서 Sprite 에 첫 프레임을 넣는다. 러스트 컴포넌트는 자기 노드를 가리키지 않아(노드는 NodeTree 가 든다) 노드를 받는다.
    SpriteAnimator::play(&mut node, "run", 옵션)
  노드 없이 애니메이터만 있을 때(완료 콜백 안)는 play_clip 이다. 완료 콜백 뒤에는 같은 tick 에 프레임을 넣어 원본처럼 바로 바뀐다.
- 원본과 다른 점:
  on_complete 는 애니메이터를 받는 한 번짜리 콜백(FnOnce(&mut SpriteAnimator))이다. 원본은 클로저가 애니메이터를 붙잡아 썼다.
  fps 는 이름을 줄이지 않아 frame_per_second 다. 기본값(10, 반복)은 DEFAULT_FRAME_PER_SECOND 와 true 를 넘긴다.
  아틀라스 JSON 은 serde_json::Value 로 받는다.
  원본 findSprite 는 찾은 Sprite 를 들고 있는다. 러스트 컴포넌트는 형제 컴포넌트의 참조를 들 수 없어(빌림이 tick 을 넘어 살 수 없다) Sprite 가 든 노드의 NodeId 를 기억하고,
    SpriteAnimator::find_sprite(&mut node_tree, 노드) 가 그 노드에서 꺼낸다. 밖에서는 apply_current_frame(sprite) 에 Sprite 를 넘길 수도 있다.

## SpriteAnimatorPlayOptions (struct) (Default)

재생 설정. (원본 options = { on_complete?, restart_if_same = false })
- 기본값은 콜백 없음, 같은 클립이면 다시 틀지 않음.

예제: 같은 클립이어도 처음부터 다시 틀기

```rust
use vanilla::{Image, Rect, SpriteAnimator, SpriteAnimatorPlayOptions};

let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
let frame_rects = [Rect::create(0.0, 0.0, 16.0, 16.0), Rect::create(16.0, 0.0, 16.0, 16.0)];
let mut animator = SpriteAnimator::new();
animator.add_clip("idle", image, &frame_rects, 10.0, true);
assert!(animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
assert!(!animator.play_clip("idle", SpriteAnimatorPlayOptions::default()));
let restart_options = SpriteAnimatorPlayOptions {
	restart_if_same: true,
	..SpriteAnimatorPlayOptions::default()
};
assert!(animator.play_clip("idle", restart_options));
```

- `pub on_complete: Option<SpriteAnimatorCompleteEvent>` (field, since 0.3.2): 클립이 끝났을 때 한 번 불린다. (반복하지 않는 클립만 끝난다)
  - returns Option<SpriteAnimatorCompleteEvent>
- `pub restart_if_same: bool` (field, since 0.3.2): 같은 클립이 도는 중이어도 처음부터 다시 틀지.
  - returns bool
- `pub fn create_with_on_complete(on_complete: impl FnOnce(&mut SpriteAnimator) + 'static) -> SpriteAnimatorPlayOptions` (static, since 0.3.2): 완료 콜백만 정한 설정.
  - `on_complete` impl FnOnce(&mut SpriteAnimator) + 'static: 클립이 끝났을 때 한 번 부를 함수. 애니메이터를 받아 다음 클립을 틀 수 있다.
  - returns SpriteAnimatorPlayOptions: on_complete 를 담고 restart_if_same 이 false 인 설정.

## SpriteAnimator (struct) (Default, Component)

스프라이트 애니메이터 컴포넌트.
- 같은 노드에 Sprite 를 함께 붙여 쓴다. tick 마다 지금 프레임을 그 Sprite 에 넣는다.

예제: 공격 클립이 끝나면 대기 클립으로

```rust
use vanilla::{Engine, EngineConfiguration, Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};

let engine = Engine::new(EngineConfiguration::new());
let image = Image::create_from_pixels(128, 16, vec![0u8; 128 * 16 * 4]);
let idle_rects: Vec<Rect> = (0..2).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();
let attack_rects: Vec<Rect> = (4..7).map(|column| Rect::create(column as f64 * 16.0, 0.0, 16.0, 16.0)).collect();

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let hero_id = node_tree.create_child(root_id, "hero");
node_tree[hero_id].add_component(Sprite::new());
let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
animator.add_clip("idle", image.clone(), &idle_rects, 10.0, true);
animator.add_clip("attack", image.clone(), &attack_rects, 12.0, false);
SpriteAnimator::play(&mut node_tree[hero_id], "attack", SpriteAnimatorPlayOptions::create_with_on_complete(|animator| {
	animator.play_clip("idle", SpriteAnimatorPlayOptions::default());
}));
assert_eq!(node_tree[hero_id].get_component::<Sprite>().unwrap().get_image_rect(), Rect::create(64.0, 0.0, 16.0, 16.0));

for _ in 0..30 {
	node_tree.tick(&engine, 1.0 / 60.0);
}
assert_eq!(node_tree[hero_id].get_component::<SpriteAnimator>().unwrap().get_clip_name(), Some("idle"));
```

- `pub const DEFAULT_FRAME_PER_SECOND: f64 = 10.0` (static, since 0.3.2): 클립의 기본 초당 프레임 수. (원본 fps = 10)
  - returns f64
- `pub fn new() -> SpriteAnimator` (constructor, since 0.3.2): 생성.
  - returns SpriteAnimator: 클립이 없고 틀지 않은 새 애니메이터.
- `pub fn add_clip(&mut self, clip_name: &str, image: Rc<Image>, frame_rects: &[Rect], frame_per_second: f64, is_loop: bool)` (method, since 0.3.2): 클립 등록. (같은 이름이 있으면 바꾼다)
  - `clip_name` &str: 클립 이름. (play 에 넘길 이름)
  - `image` Rc<Image>: 프레임을 뗄 시트 이미지.
  - `frame_rects` &[Rect]: 시트 안의 프레임 영역 목록. (픽셀, 차례대로 넘긴다. 복사해 둔다)
  - `frame_per_second` f64: 초당 프레임 수. (0 이하면 넘기지 않는다, 원본 기본값은 DEFAULT_FRAME_PER_SECOND)
  - `is_loop` bool: true 면 반복, false 면 마지막 프레임에서 멈추고 완료 콜백을 부른다.
- `pub fn add_clip_from_atlas(&mut self, clip_name: &str, image: Rc<Image>, atlas_json: &serde_json::Value, frame_ids: &[&str], frame_per_second: f64, is_loop: bool)` (method, since 0.3.2): 아틀라스 JSON 으로 클립 등록. (TexturePacker 꼴 { frames: { 이름: { frame: { x, y, w, h } } } }, 없는 칸 이름은 건너뛴다)
  - frame 칸이 없으면 칸 자체에서 x, y, w(width), h(height) 를 읽는다. 없는 숫자는 0 이다.
  - `clip_name` &str: 클립 이름.
  - `image` Rc<Image>: 아틀라스 이미지.
  - `atlas_json` &serde_json::Value: 아틀라스 JSON 값.
  - `frame_ids` &[&str]: frames 안의 칸 이름 목록. (이 차례로 프레임이 된다)
  - `frame_per_second` f64: 초당 프레임 수.
  - `is_loop` bool: true 면 반복.

  예제: JSON 의 칸 이름으로 클립 만들기

  ```rust
  use vanilla::{Image, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(64, 64, vec![0u8; 64 * 64 * 4]);
  let atlas_json = serde_json::json!({
  	"frames": {
  		"run_0": { "frame": { "x": 0, "y": 0, "w": 16, "h": 20 } },
  		"run_1": { "frame": { "x": 16, "y": 0, "w": 16, "h": 20 } }
  	}
  });
  let mut animator = SpriteAnimator::new();
  animator.add_clip_from_atlas("run", image, &atlas_json, &["run_0", "run_1"], SpriteAnimator::DEFAULT_FRAME_PER_SECOND, true);
  assert!(animator.has_clip("run"));
  assert!(animator.play_clip("run", SpriteAnimatorPlayOptions::default()));
  ```

- `pub fn play_clip(&mut self, clip_name: &str, options: SpriteAnimatorPlayOptions) -> bool` (method, since 0.4.0): 애니메이터만으로 재생. (처음부터 틀었으면 true)
  - 같은 클립이 이미 도는 중이면 다시 틀지 않고 완료 콜백만 바꾼다. (restart_if_same 이면 처음부터)
  - 노드가 없을 때(완료 콜백 안처럼) 쓴다. Sprite 에는 다음 프레임 넣기(tick, 완료 콜백 뒤의 같은 tick, apply_current_frame)에 들어간다.
    노드가 있으면 그 자리에서 첫 프레임까지 넣는 SpriteAnimator::play 를 쓴다.
  - `clip_name` &str: 틀 클립 이름.
  - `options` SpriteAnimatorPlayOptions: 완료 콜백과 같은 클립 다시 틀기.
  - returns bool: 처음부터 틀었으면 true. 없는 클립이거나 같은 클립이 도는 중이라 다시 틀지 않았으면 false.
- `pub fn play(node: &mut WorldNode, clip_name: &str, options: SpriteAnimatorPlayOptions) -> bool` (static, since 0.3.2): 재생. (원본 play, 노드의 애니메이터로 틀고 같은 노드의 Sprite 에 그 자리에서 첫 프레임을 넣는다)
  - 같은 클립이 이미 도는 중이면 다시 틀지 않고 완료 콜백만 바꾼다. (restart_if_same 이면 처음부터)
  - 애니메이터가 없으면 false.
  - `node` &mut WorldNode: SpriteAnimator 가 붙은 노드. (Sprite 가 없으면 프레임은 넣지 않고 재생만 한다)
  - `clip_name` &str: 틀 클립 이름.
  - `options` SpriteAnimatorPlayOptions: 완료 콜백과 같은 클립 다시 틀기.
  - returns bool: 처음부터 틀었으면 true. 없는 클립이거나 같은 클립이 도는 중이라 다시 틀지 않았거나 노드에 애니메이터가 없으면 false.
- `pub fn stop(&mut self)` (method, since 0.3.2): 정지. (첫 프레임으로 되돌리고, 완료 콜백은 부르지 않는다)
- `pub fn apply_current_frame(&self, sprite: &mut Sprite)` (method, since 0.3.2): 지금 프레임을 스프라이트에 넣기. (프레임이 없으면 아무것도 하지 않는다)
  - `sprite` &mut Sprite: 이미지와 이미지 영역을 넣을 스프라이트.

  예제: 노드 밖의 Sprite 에 첫 프레임 넣기

  ```rust
  use vanilla::{Image, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(32, 16, vec![0u8; 32 * 16 * 4]);
  let mut animator = SpriteAnimator::new();
  animator.add_clip("blink", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
  animator.play_clip("blink", SpriteAnimatorPlayOptions::default());
  let mut sprite = Sprite::new();
  animator.apply_current_frame(&mut sprite);
  assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));
  ```

- `pub fn get_clip_name(&self) -> Option<&str>` (method, since 0.3.2): 지금 클립 이름 반환. (아직 틀지 않았으면 None)
  - returns Option<&str>: 마지막으로 처음부터 튼 클립 이름. 아직 틀지 않았으면 None. (stop 해도 남는다)
- `pub fn is_playing(&self) -> bool` (method, since 0.3.2): 재생 중인지.
  - returns bool: 프레임을 넘기는 중이면 true. 반복하지 않는 클립이 끝났거나 stop 했으면 false.
- `pub fn has_clip(&self, clip_name: &str) -> bool` (method, since 0.3.2): 클립이 있는지.
  - `clip_name` &str: 찾을 클립 이름.
  - returns bool: 그 이름으로 등록한 클립이 있으면 true.
- `pub fn get_current_frame_index(&self) -> usize` (method, since 0.3.2): 지금 프레임 번호.
  - returns usize: 지금 클립 안의 프레임 번호. (0 부터)
- `pub fn find_sprite(node_tree: &mut NodeTree, node_id: NodeId) -> Option<&mut Sprite>` (static, since 0.4.0): 같은 노드의 스프라이트 찾기. (원본 findSprite, 한 번 찾으면 기억한다)
  - 원본은 찾은 Sprite 를 들고 있는다. 러스트는 형제 컴포넌트의 참조를 들 수 없어 Sprite 가 든 노드의 NodeId 를 애니메이터에 기억하고 트리에서 꺼낸다.
  - tick 에서 찾았어도 기억한다. 기억한 노드에서 Sprite 를 뺐으면 None 이다.
  - `node_tree` &mut NodeTree: 노드가 든 트리.
  - `node_id` NodeId: SpriteAnimator 가 붙은 노드.
  - returns Option<&mut Sprite>: 같은 노드의 첫 Sprite. 노드가 없거나, 노드에 SpriteAnimator 나 Sprite 가 없으면 None.

  예제: 애니메이터가 넣는 스프라이트 꺼내기

  ```rust
  use vanilla::{Image, NodeTree, Rect, Sprite, SpriteAnimator, SpriteAnimatorPlayOptions};
  
  let image = Image::create_from_pixels(64, 16, vec![0u8; 64 * 16 * 4]);
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let hero_id = node_tree.create_child(root_id, "hero");
  node_tree[hero_id].add_component(Sprite::new());
  let animator = node_tree[hero_id].add_component(SpriteAnimator::new());
  animator.add_clip("run", image, &[Rect::create(16.0, 0.0, 16.0, 16.0)], 10.0, true);
  SpriteAnimator::play(&mut node_tree[hero_id], "run", SpriteAnimatorPlayOptions::default());
  let sprite = SpriteAnimator::find_sprite(&mut node_tree, hero_id).expect("sprite");
  assert_eq!(sprite.get_image_rect(), Rect::create(16.0, 0.0, 16.0, 16.0));
  ```

