# animation/timeline (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/animation/timeline/

타임라인.

## Timeline extends Object

타임라인.
- 문서(서술)는 무대 노드 목록 + 트랙(대상 이름 / 속성 / 키) + 마커로 이루어진 JSON 이며 타임라인 편집기가 저장한다.
- buildStage() 로 무대 노드를 만들거나, bind() 로 기존 노드 트리에 이름으로 붙인다.
- 키의 easing 은 그 키에서 다음 키까지 구간에 적용된다.
- 사용:
    const timeline = await Timeline.loadFromUrl("./assets/intro.timeline.json");
    timeline.buildStage(stageNode, (imageName) => imageTable[imageName]);
    timeline.play();
    // 매 프레임: timeline.tick(timeDelta);

예제: 문서를 읽어 무대를 짓고 재생하기

```js
import { Engine, EngineConfiguration, Scene, Timeline, Vector2 } from "./build/vanilla.js";

const emblemImage = new Image();
emblemImage.src = "examples/timelineshowcase/assets/emblem.png";
await emblemImage.decode();
const timeline = await Timeline.loadFromUrl("examples/timelineshowcase/assets/logo.timeline.json");
timeline.setMarkerHandler((markerName) => {
	console.log("marker", markerName);
});

class TimelineScene extends Scene {
	async load(engine) {
		await super.load(engine);
		const root = this.getRoot();
		timeline.buildStage(root, (imageName) => {
			return imageName === "emblem.png" ? emblemImage : null;
		});
		timeline.play();
	}

	tick(timeDelta) {
		super.tick(timeDelta);
		timeline.tick(timeDelta);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(960, 540);
const engine = new Engine(engineConfiguration);
engine.run(new TimelineScene());
```

- `constructor(description = null)` (constructor, since 0.3.0): 생성.
  - `description` object | null: 타임라인 문서. (null 이면 createEmptyDescription 의 빈 문서)
- `static createEmptyDescription()` (static, since 0.3.0): 빈 서술 생성. (정적)
  - returns object: 빈 타임라인 문서. (3 초, 30 프레임, 반복, 960x540 무대)
- `static async loadFromUrl(url)` (static, since 0.3.0): 주소에서 읽기. (정적)
  - `url` string: 타임라인 문서(*.timeline.json) 주소.
  - returns Promise<Timeline>: 읽은 문서로 만든 타임라인. (실패 응답(404 등)이나 JSON 이 아니면 거부된다)
- `static loadFromText(text)` (static, since 0.4.0): JSON 글에서 만들기. (정적)
  - `text` string: 타임라인 문서 JSON 글.
  - returns Timeline: 만든 타임라인.
- `static createFromJsonAsset(jsonAsset)` (static, since 0.4.0): 읽은 JsonAsset 에서 만들기. (정적, 아직 안 읽혔거나 실패했으면 null. 문서는 복사해 쓴다)
  - `jsonAsset` JsonAsset: 타임라인 문서를 읽은 JsonAsset.
  - returns Timeline | null: 만든 타임라인. 아직 안 읽혔거나 실패했으면 null.

  예제: JsonAsset 으로 읽은 문서에서 만들기

  ```js
  import { JsonAsset, Timeline } from "./build/vanilla.js";
  
  const jsonAsset = new JsonAsset();
  await jsonAsset.load("examples/timelineshowcase/assets/title.timeline.json");
  const timeline = Timeline.createFromJsonAsset(jsonAsset);
  console.log(timeline.getDuration(), timeline.getFrameRate(), timeline.isLoop());
  ```

- `setDescription(description)` (method, since 0.3.0): 서술 설정. (참조를 그대로 쓴다, 편집기가 고친 뒤 invalidate() 로 다시 컴파일)
  - `description` object: 타임라인 문서. (빠진 stage, tracks, markers 는 채워 넣는다)
- `getDescription()` (method, since 0.3.0): 서술 반환.
  - returns object: 타임라인 문서. (복사본이 아니다)
- `invalidate()` (method, since 0.3.0): 다시 컴파일 요청. (트랙 / 키가 바뀌었을 때)
- `compile()` (method, since 0.3.0): 컴파일. (키를 시간순으로 정렬하고 대상 / 속성 정의를 붙인다)
- `collectParticleSystems()` (method, since 0.3.0): 대상 노드의 파티클 시스템 수집. (수동 틱으로 바꿔 타임라인 시간으로만 진행하고, 시드를 줘서 되감을 때마다 같은 결과가 나오게 한다)
- `simulateParticles(timeDelta)` (method, since 0.3.0): 파티클 시간 진행. (재생 중 매 프레임)
  - `timeDelta` number: 흘릴 시간. (초, 0 이하이면 아무것도 하지 않는다)
- `resimulateParticles(time)` (method, since 0.3.0): 파티클 재시뮬레이션. (스크럽 / 되감기, 비운 뒤 0초부터 이벤트를 다시 밟으며 진행)
  - `time` number: 맞출 타임라인 시간. (초)
- `resolveTarget(targetName)` (method, since 0.3.0): 대상 해석. (무대 노드 표 → 사용자 해석기)
  - `targetName` string: 트랙의 대상 이름.
  - returns object | null: 찾은 대상. 없으면 null.
- `setTargetResolver(targetResolver)` (method, since 0.3.0): 대상 해석기 설정. (이름 → 객체. 노드가 아니어도 setTimelineProperty(이름, 값) 이 있으면 된다)
  - `targetResolver` Function | null: 대상 이름을 받아 객체를 돌려주는 함수. (null 이면 끈다)
- `setTarget(targetName, target)` (method, since 0.3.0): 대상 직접 등록.
  - `targetName` string: 트랙의 대상 이름.
  - `target` object: 노드, 또는 setTimelineProperty(이름, 값) 이 있는 객체.

  예제: 노드가 아닌 객체에 트랙 걸기

  ```js
  import { Timeline } from "./build/vanilla.js";
  
  const description = Timeline.createEmptyDescription();
  description.duration = 2;
  description.loop = false;
  description.tracks.push({
  	target: "meter",
  	property: "level",
  	keys: [
  		{ time: 0, value: 0, easing: "quadratic.out" },
  		{ time: 2, value: 100 }
  	]
  });
  const timeline = new Timeline(description);
  const meter = { level: 0 };
  meter.setTimelineProperty = (name, value) => {
  	meter[name] = value;
  };
  timeline.setTarget("meter", meter);
  timeline.seek(1);
  console.log(timeline.getTime(), meter.level);
  ```

- `getTarget(targetName)` (method, since 0.3.0): 대상 반환.
  - `targetName` string: 트랙의 대상 이름.
  - returns object | null: 등록된 대상. 없으면 null. (해석기는 보지 않는다)
- `bind(rootNode)` (method, since 0.3.0): 노드 트리에 이름으로 붙이기. (무대를 직접 만든 경우)
  - `rootNode` WorldNode: 이름으로 찾을 노드 트리의 뿌리. (뿌리 자신도 본다. 이미 등록된 이름은 건너뛴다)
- `buildStage(parentNode, imageResolver = null)` (method, since 0.3.0): 무대 노드 생성. (서술의 stage.nodes 를 노드 트리로 만들고 대상으로 등록)
  - 같은 이름의 노드가 둘이면 모두 붙이고, 이름 표에는 뒤의 것이 남는다.
  - 부모가 자기 자신이거나 고리가 되면 parentNode 에 붙인다.
  - `parentNode` WorldNode: 무대 노드를 붙일 부모 노드. (서술에 부모가 없는 노드가 여기 붙는다)
  - `imageResolver` Function | null: (이미지 이름) → HTMLImageElement | HTMLCanvasElement | null
  - returns System.Map: 이름 → 노드
- `static isAncestorOrSelf(ancestorNode, node)` (static, since 0.4.0): ancestorNode 가 node 자신이거나 그 조상인지. (정적)
  - `ancestorNode` WorldNode: 조상인지 볼 노드.
  - `node` WorldNode: 부모를 거슬러 올라갈 노드.
  - returns boolean: ancestorNode 가 node 자신이거나 그 조상이면 참.
- `static createStageNode(nodeDescription, imageResolver = null)` (static, since 0.3.0): 무대 노드 한 개 생성. (정적)
  - `nodeDescription` object: 무대 노드 서술. (빠진 값은 TIMELINE_NODE_DEFAULTS 로 채운다)
  - `imageResolver` Function | null: 이미지 이름을 받아 그림을 돌려주는 함수. (없거나 null 을 돌려주면 data: 주소만 스스로 읽는다)
  - returns WorldNode: 서술의 이름을 단 새 노드.
- `static applyStageNodeDescription(node, nodeDescription, imageResolver = null)` (static, since 0.3.0): 노드에 서술 반영. (정적, 편집기가 값을 고칠 때도 쓴다)
  - `node` WorldNode: 서술을 반영할 노드. (종류에 맞는 컴포넌트가 없으면 더한다)
  - `nodeDescription` object: 무대 노드 서술. (빠진 값은 TIMELINE_NODE_DEFAULTS 로 채운다)
  - `imageResolver` Function | null: 이미지 이름을 받아 그림을 돌려주는 함수. (없거나 null 을 돌려주면 data: 주소만 스스로 읽는다)
- `static setAudioManager(audioManager)` (static, since 0.3.0): 오디오 매니저 설정. (정적, 사운드 노드가 플레이어를 만들 때 쓴다)
  - `audioManager` object | null: 사운드 노드가 createAudioPlayer 로 플레이어를 만들 오디오 매니저. (null 이면 만들지 않는다)
- `static stopSound(node)` (static, since 0.3.0): 사운드 노드 정지. (정적, 편집기가 정지 / 되감기 때 부른다)
  - `node` WorldNode: 멈출 사운드 노드. (사운드 노드가 아니면 아무것도 하지 않는다)
- `play()` (method, since 0.3.0): 재생.
- `pause()` (method, since 0.3.0): 일시 정지.
- `stop()` (method, since 0.3.0): 정지. (처음으로)
- `seek(time)` (method, since 0.3.0): 시간 이동. (이벤트는 발생하지 않는다)
  - `time` number: 옮길 시간. (초, 0 ~ 길이로 자른다)
- `tick(timeDelta)` (method, since 0.3.0): 갱신. (시간을 흘리고 값을 적용, 지나친 이벤트 / 마커를 발생)
  - `timeDelta` number: 지난 프레임부터의 시간. (초, 속도를 곱해 흘린다. 재생 중이 아니면 아무것도 하지 않는다)

  예제: 재생하며 이벤트, 마커, 완료 받기

  ```js
  import { Timeline } from "./build/vanilla.js";
  
  const description = Timeline.createEmptyDescription();
  description.duration = 1;
  description.loop = false;
  description.tracks.push({
  	target: "hero",
  	property: "event",
  	keys: [
  		{ time: 0.5, value: "jump" }
  	]
  });
  description.markers.push({ time: 0.25, name: "quarter" });
  const timeline = new Timeline(description);
  timeline.setEventHandler((targetName, eventName) => {
  	console.log("event", targetName, eventName);
  });
  timeline.setMarkerHandler((markerName) => {
  	console.log("marker", markerName);
  });
  timeline.setCompleteHandler(() => {
  	console.log("complete", timeline.getTime());
  });
  timeline.play();
  for (let frame = 0; frame < 40; ++frame) {
  	timeline.tick(1 / 30);
  }
  ```

- `fireEventsBetween(fromTime, toTime)` (method, since 0.3.0): 구간 안의 이벤트 키 / 마커 발생. (fromTime 초과 ~ toTime 이하)
  - `fromTime` number: 구간 시작. (초, 이 시간의 키는 넣지 않는다)
  - `toTime` number: 구간 끝. (초, 이 시간의 키는 넣는다)
- `dispatchEvent(compiledTrack, key, isSilent = false)` (method, since 0.3.0): 이벤트 키 처리. (파티클 대상은 play / stop / emit:N 을 스스로 처리, 그 외는 핸들러)
  - `compiledTrack` object: 컴파일한 이벤트 트랙. (target 과 track 을 쓴다)
  - `key` object: 이벤트 키. (value 가 이벤트 이름)
  - `isSilent` boolean: 재시뮬레이션용. (사운드 / 사용자 핸들러는 부르지 않고 파티클만)
- `evaluate(time)` (method, since 0.3.0): 시간의 값 적용. (연속 속성만, 이벤트는 tick 에서만 발생)
  - `time` number: 값을 적용할 시간. (초)
- `static sampleKeys(sortedKeys, kind, time)` (static, since 0.3.0): 키 목록에서 시간의 값 표본. (정적, 편집기의 커브 그리기도 쓴다)
  - `sortedKeys` object[]: 시간 차례로 정렬한 키 목록. ({ time, value, easing, curve })
  - `kind` string: "number", "color", "string", "boolean" 가운데. (number 와 color 만 보간하고 나머지는 계단)
  - `time` number: 표본 시간. (초)
  - returns *: 그 시간의 값. (키가 없으면 number 는 0, 그 밖은 null)
- `static sampleTrack(track, time)` (static, since 0.3.0): 트랙의 시간 값 표본. (서술 트랙 그대로, 정렬은 여기서)
  - `track` object: 서술의 트랙. (property 로 종류를 정하고, 모르는 속성은 number)
  - `time` number: 표본 시간. (초)
  - returns *: 그 시간의 값.
- `getTime()` (method, since 0.3.0): 시간 반환.
  - returns number: 지금 시간. (초)
- `isPlaying()` (method, since 0.3.0): 재생 중 여부 반환.
  - returns boolean: 재생 중이면 참.
- `setSpeed(speed)` (method, since 0.3.0): 속도 설정. (1 = 실시간)
  - `speed` number: 재생 속도 배율. (1 = 실시간, 음수면 0 초에서 멈춰 선다)
- `getSpeed()` (method, since 0.3.0): 속도 반환.
  - returns number: 재생 속도 배율.
- `setLoop(isLoop)` (method, since 0.3.0): 반복 설정.
  - `isLoop` boolean: 반복하면 참. (문서의 loop 에 쓴다)
- `isLoop()` (method, since 0.3.0): 반복 여부 반환.
  - returns boolean: 문서의 loop 가 true 면 참.
- `getDuration()` (method, since 0.3.0): 길이 반환. (초)
  - returns number: 길이. (초, 문서 값이 양수가 아니면 0)
- `getFrameRate()` (method, since 0.3.0): 초당 프레임 반환.
  - returns number: 초당 프레임. (문서 값이 양수가 아니면 30)
- `setEventHandler(eventHandler)` (method, since 0.3.0): 이벤트 핸들러 설정. ((대상 이름, 이벤트 이름, 키, 타임라인))
  - `eventHandler` Function | null: (대상 이름, 이벤트 이름, 키, 타임라인) 을 받는 함수. (null 이면 끈다)
- `setMarkerHandler(markerHandler)` (method, since 0.3.0): 마커 핸들러 설정. ((마커 이름, 마커, 타임라인))
  - `markerHandler` Function | null: (마커 이름, 마커, 타임라인) 을 받는 함수. (null 이면 끈다)
- `setCompleteHandler(completeHandler)` (method, since 0.3.0): 완료 핸들러 설정. (반복이 아닐 때 끝에 닿으면)
  - `completeHandler` Function | null: 타임라인을 받는 함수. (null 이면 끈다)

## Functions and constants

- `TIMELINE_EASING_NAMES` (field, since 0.3.0): 이징 이름 목록. ("linear" / "step" / "bezier" / "<종류>.<in|out|inOut>")
- `createBezierEasing(x1, y1, x2, y2)` (method, since 0.3.0): 3차 베지어 이징 생성. (CSS cubic-bezier 와 같은 제어점, x 는 0 ~ 1)
  - `x1` number: 첫 제어점 x. (0 ~ 1 로 자른다)
  - `y1` number: 첫 제어점 y.
  - `x2` number: 둘째 제어점 x. (0 ~ 1 로 자른다)
  - `y2` number: 둘째 제어점 y.
  - returns Function: 0 ~ 1 진행률을 받아 이징한 값을 돌려주는 함수.
- `resolveTimelineEasing(easingName, curve = null)` (method, since 0.3.0): 이징 함수 반환. (모르는 이름은 linear, "bezier" 는 curve [x1, y1, x2, y2] 를 쓴다)
  - `easingName` string: 이징 이름. (TIMELINE_EASING_NAMES 가운데, 비었으면 linear)
  - `curve` number[] | null: "bezier" 의 [x1, y1, x2, y2]. (넷이 안 되면 [0.42, 0, 0.58, 1])
  - returns Function: 0 ~ 1 진행률을 받아 이징한 값을 돌려주는 함수.

  예제: 이름과 제어점으로 이징 얻기

  ```js
  import { resolveTimelineEasing, createBezierEasing } from "./build/vanilla.js";
  
  const bounceOut = resolveTimelineEasing("bounce.out");
  const customCurve = resolveTimelineEasing("bezier", [0.25, 0.1, 0.25, 1]);
  const easeInOut = createBezierEasing(0.42, 0, 0.58, 1);
  console.log(bounceOut(0.5), customCurve(0.5), easeInOut(0.25));
  ```

- `parseTimelineColor(hexText)` (method, since 0.3.0): 색 문자열 ↔ 채널.
  - `hexText` string: "#rrggbb" 또는 "#rrggbbaa"
  - returns number[]: 0 ~ 1 의 [빨강, 초록, 파랑, 알파]. (읽지 못한 채널은 1)
- `composeTimelineColor(channels)` (method, since 0.3.0): 채널을 색 문자열로. ("#rrggbbaa")
  - `channels` number[]: 0 ~ 1 의 [빨강, 초록, 파랑, 알파]. (0 ~ 1 로 자르고, 알파가 없으면 1)
  - returns string: "#rrggbbaa" 색 문자열.
- `TIMELINE_PROPERTY_DEFINITIONS` (field, since 0.3.0): 애니메이션 속성 정의. (이름 → 종류 / 적용 함수)
  - kind: "number" 는 이징 보간, "color" 는 채널 보간, "string" / "boolean" 은 계단.
- `TIMELINE_NODE_DEFAULTS` (field, since 0.3.0): 서술 노드 기본값.
