# resource/assetloader (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/resource/assetloader/

애셋 함께 받기.

## AssetLoader extends Object

애셋 함께 받기.
- 그림, JSON, 글, 바이너리, 소리, 글꼴, 직접 만든 받기(addTask)를 목록에 넣고 load() 로 한꺼번에 받는다.
  동시에 받는 수는 setConcurrency 로 정한다. (하나씩 기다리면 받기와 풀기가 줄지어 늦어진다)
- 실패한 것도 끝난 것으로 쳐서 멈추지 않는다. 실패는 getFailedList() 에 { path, error } 로 남는다.
- 진행률은 끝난 수 / 전체 수다. (getProgress, 받은 수 getLoadedCount, 끝난 수 getFinishedCount, 전체 getTotalCount)
  바뀔 때마다 setProgressHandler 로 건 함수를, 다 끝나면 setCompleteHandler 로 건 함수를 부른다.
- 받는 동안 더 넣은 것도 같은 load 가 받는다. (일꾼이 동시에 받는 수보다 적게 돌고 있으면 그만큼 더 띄운다) 다 끝난 뒤 더 넣으면 load() 를 다시 부른다.
- 쓰기:
    const assetLoader = new AssetLoader();
    assetLoader.setConcurrency(8);
    const titleImageAsset = assetLoader.addImage("assets/title.png");
    const stageJsonAsset = assetLoader.addJson("assets/stage.json");
    gameScene.trackAssetLoader(assetLoader);     // GameScene 로딩 막대가 진행률을 따라간다
    await assetLoader.load();

예제: 그림, JSON, 소리, 글꼴을 함께 받기

```js
import { AssetLoader } from "./build/vanilla.js";

const assetLoader = new AssetLoader();
assetLoader.setConcurrency(4);
const imageAsset = assetLoader.addImage("examples/assets/spritesheet.png");
const jsonAsset = assetLoader.addJson("examples/timelineshowcase/assets/combo.timeline.json");
const audioAsset = assetLoader.addAudio("examples/assets/beep.wav");
const fontAsset = assetLoader.addFont("DOSGothic", "examples/assets/DOSGothic.woff");
assetLoader.setProgressHandler((progress, finishedCount, totalCount) => {
	console.log(progress, finishedCount, totalCount);
});
const failedList = await assetLoader.load();
console.log(failedList.length, imageAsset.isLoaded(), jsonAsset.isLoaded(), audioAsset.getDuration(), fontAsset.family);
```

- `constructor()` (constructor, since 0.4.0): 생성.
- `setConcurrency(concurrency)` (method, since 0.4.0): 동시에 받는 수 설정. (1 이상, 소수는 버린다. 받는 중에 바꾸면 다음 load 부터)
  - `concurrency` number: 동시에 받는 수. (유한한 숫자가 아니면 무시한다)
- `getConcurrency()` (method, since 0.4.0): 동시에 받는 수 반환.
  - returns number: 동시에 받는 수. (기본 6)
- `addImage(path)` (method, since 0.4.0): 그림 넣기.
  - `path` string: 그림 파일 경로.
  - returns ImageAsset: 넣은 그림 애셋. (load 가 끝나면 읽혀 있다)
- `addJson(path)` (method, since 0.4.0): JSON 넣기.
  - `path` string: JSON 파일 경로.
  - returns JsonAsset: 넣은 JSON 애셋.
- `addText(path)` (method, since 0.4.0): 글 넣기.
  - `path` string: 글 파일 경로.
  - returns TextAsset: 넣은 글 애셋.
- `addBlob(path)` (method, since 0.4.0): 바이너리 넣기.
  - `path` string: 파일 경로.
  - returns BlobAsset: 넣은 블롭 애셋.
- `addAudio(path)` (method, since 0.4.0): 소리 넣기. (AudioContext 가 없는 브라우저에서는 실패로 친다)
  - `path` string: 소리 파일 경로.
  - returns AudioAsset: 넣은 소리 애셋.
- `addFont(family, path, descriptors)` (method, since 0.4.0): 글꼴 넣기. (받으면 document.fonts 에 family 이름으로 오른다, FontAsset.loadFont)
  - `family` string: 등록할 글꼴 패밀리 이름.
  - `path` string: 글꼴 파일 경로.
  - `descriptors` object: FontFace 서술자. (weight, style 등, 없으면 생략)
  - returns FontAsset: 넣은 글꼴 애셋.
- `addAsset(asset, path)` (method, since 0.4.0): 애셋 넣기. (asset.load(path) 로 받는 Asset 파생, 다 받은 뒤 isLoaded() 가 거짓이면 실패로 친다)
  - `asset` object: asset.load(path) 로 받는 애셋.
  - `path` string: 받을 경로.
  - returns object: 넣은 애셋.
- `addTask(path, loadFunction)` (method, since 0.4.0): 직접 만든 받기 넣기. (loadFunction 은 Promise 를 돌려주는 함수, 예외를 내면 실패로 친다)
  - `path` string: 실패 목록과 진행에 보일 이름.
  - `loadFunction` () => Promise<any>: 받기 함수. (Promise 를 돌려준다, 거부되면 실패로 친다)

  예제: 애셋이 아닌 받기를 함께 받기

  ```js
  import { AssetLoader } from "./build/vanilla.js";
  
  const assetLoader = new AssetLoader();
  const timelineList = [];
  assetLoader.addTask("logo.timeline.json", async () => {
  	const response = await fetch("examples/timelineshowcase/assets/logo.timeline.json");
  	const timeline = await response.json();
  	timelineList.push(timeline);
  });
  assetLoader.setCompleteHandler((failedList) => {
  	console.log(failedList.length, timelineList.length);
  });
  await assetLoader.load();
  ```

- `addEntry(path, loadFunction, asset)` (method, since 0.4.0): 목록에 넣기.
  - `path` string: 실패 목록과 진행에 보일 이름.
  - `loadFunction` () => Promise<any>: 받기 함수. (Promise 를 돌려준다)
  - `asset` object | null: 받은 뒤 isLoaded() 로 성공을 확인할 애셋. (null 이면 확인하지 않는다)
- `load()` (method, since 0.4.0): 받기. (넣은 것을 모두 받을 때까지 기다린다. 실패해도 예외를 내지 않고 실패 목록을 돌려준다)
  - returns Promise<Array<{ path: string, error: any }>>: 다 끝나면 실패 목록으로 풀리는 프로미스. (실패가 없으면 빈 배열, 받는 중에 다시 부르면 같은 프로미스)
- `async runWorkers()` (method, since 0.4.0): 받는 일꾼들 돌리기. (동시에 받는 수만큼 일꾼이 목록의 다음 것을 집어 받는다)
  - returns Promise<Array<object>>: 다 끝나면 실패 목록으로 풀리는 프로미스.
- `startWorkers()` (method, since 0.4.0): 일꾼 띄우기. (돌고 있는 일꾼이 동시에 받는 수보다 적으면, 아직 아무도 집지 않은 것만큼 더 띄운다)
- `async runWorker()` (method, since 0.4.0): 일꾼 하나. (목록이 빌 때까지 하나씩 집어 받는다)
  - returns Promise<void>: 목록이 비면 풀리는 프로미스.
- `notifyProgress()` (method, since 0.4.0): 진행 알리기.
- `setProgressHandler(progressHandler)` (method, since 0.4.0): 진행 알림 함수 설정. ((progress, finishedCount, totalCount) => void, null 이면 끔)
  - `progressHandler` ((progress: number, finishedCount: number, totalCount: number) => void) | null: 진행이 바뀔 때마다 진행률(0 ~ 1), 끝난 수, 전체 수를 받는 함수. (null 이면 끔)
- `setCompleteHandler(completeHandler)` (method, since 0.4.0): 다 받음 알림 함수 설정. ((failedList) => void, null 이면 끔)
  - `completeHandler` ((failedList: Array<object>) => void) | null: 다 끝나면 실패 목록을 받는 함수. (null 이면 끔)
- `getProgress()` (method, since 0.4.0): 진행률. (끝난 수 / 전체 수, 넣은 것이 없으면 1)
  - returns number: 0 ~ 1
- `getTotalCount()` (method, since 0.4.0): 전체 수.
  - returns number: 넣은 수.
- `getFinishedCount()` (method, since 0.4.0): 끝난 수. (받은 것과 실패한 것)
  - returns number: 끝난 수.
- `getLoadedCount()` (method, since 0.4.0): 받은 수. (실패한 것은 빼고)
  - returns number: 받은 수.
- `getFailedList()` (method, since 0.4.0): 실패 목록. ({ path, error } 의 복사본)
  - returns Array<{ path: string, error: any }>: 실패 목록의 복사본.
- `getInFlightCount()` (method, since 0.4.0): 지금 받는 중인 수. (일꾼이 집어 받기 시작했고 아직 끝나지 않은 것)
  - returns number: 받는 중인 수.
- `isFinished()` (method, since 0.4.0): 넣은 것을 모두 받았는지. (실패 포함, 넣은 것이 없으면 true)
  - returns boolean: 모두 끝났으면 참.
