# resource/spriteatlas (vanilla.js 0.4.0)

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

List of atlases to search. (SpriteAtlas.findFrame searches from the front)

## SpriteAtlas extends Object

Sprite atlas. (retrieves by name the images gathered into a few page images)
- Sprites that use the same page image are batched by the engine and drawn at once. (Graphic.setBatchingEnabled)
- Two JSON formats are read:
  1. Made by tools/atlas.cjs. { images: { "name.png": { x, y, width, height, page } }, meta: { imageFileName, pages: [{ imageFileName }] } }
     If page is absent it is page 0, and if meta.pages is absent it is the single image meta.imageFileName.
  2. Page paths and a [page, x, y, width, height] table. { pagePaths: ["path"], frames: { "name": [page, x, y, width, height] } }
- Images are found by the name with the extension removed. ("icon-close.png" is found as either "icon-close" or "icon-close.png")
- If a page path has no slash (/), it is read relative to the folder containing the JSON, and if it has one, it is read as written.
- If several atlases are added with addSearchAtlas, findFrame and applyFrame (static) search them in the order added. (earlier ones win)

Example: Add to the search atlases and set a frame on a sprite

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

const spriteAtlas = new SpriteAtlas();
await spriteAtlas.loadData({
	pagePaths: ["examples/assets/spritesheet.png"],
	frames: {
		"walk-0.png": [0, 0, 0, 200, 200],
		"walk-1.png": [0, 200, 0, 200, 200],
	},
});
SpriteAtlas.addSearchAtlas(spriteAtlas);

class MainScene extends Scene {
	initialize(engine) {
		super.initialize(engine);
		const node = new WorldNode();
		node.setContentSize(Vector2.create(200, 200));
		node.setLocalPosition(Vector2.create(100, 100));
		const root = this.getRoot();
		root.addChild(node);
		const sprite = node.addComponent(Sprite);
		const isFound = SpriteAtlas.applySearchFrame(sprite, "walk-1");
		console.log(isFound);
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.4.0): Constructor.
- `async load(jsonPath)` (method, since 0.4.0): Loads the atlas JSON and the page images. (the page images are fetched all at once)
  - `jsonPath` string: Atlas JSON path.
  - returns Promise<void>: A promise resolved when fully loaded. (reports and resolves if the JSON cannot be read, rejects if a page image cannot be loaded)
- `async loadData(atlasData, baseDirectory = "")` (method, since 0.4.0): Loads from atlas data. (an object read from JSON or an object of the same shape kept in code, baseDirectory is prepended if a page path has no slash)
  - `atlasData` object: Atlas data. (the tools/atlas.cjs form or the pagePaths, frames form, reports and does nothing for any other form)
  - `baseDirectory` string: Folder prepended to page paths without a slash. (including the trailing slash, default empty string)
  - returns Promise<void>: A promise resolved when all page images are loaded. (rejects if one cannot be loaded)

  Example: Load from atlas data kept in code

  ```js
  import { SpriteAtlas } from "./build/vanilla.js";
  
  const spriteAtlas = new SpriteAtlas();
  await spriteAtlas.loadData({
  	pagePaths: ["examples/assets/spritesheet.png"],
  	frames: {
  		"walk-0.png": [0, 0, 0, 200, 200],
  		"walk-1.png": [0, 200, 0, 200, 200],
  	},
  });
  const frame = spriteAtlas.readFrame("walk-1");
  const imageRect = frame.getImageRect();
  console.log(spriteAtlas.getPageCount(), spriteAtlas.getFrameNames(), imageRect.x, spriteAtlas.hasFrame("walk-1.png"));
  ```

- `readFrame(frameName)` (method, since 0.4.0): Reads a frame. (null if absent)
  - `frameName` string: Image name. (the extension may be dropped)
  - returns Frame | null: Frame. (null if none)
- `hasFrame(frameName)` (method, since 0.4.0): Whether the frame exists.
  - `frameName` string: Image name.
  - returns boolean: True if present.
- `applyFrame(sprite, frameName)` (method, since 0.4.0): Applies a frame to a sprite. (if the name does not exist, clears the image and returns false)
  - `sprite` Sprite: Sprite to set the frame on.
  - `frameName` string: Image name.
  - returns boolean: True if found and set.
- `getPageImages()` (method, since 0.4.0): Returns the list of page images.
  - returns HTMLImageElement[]: Page image list. (in page index order)
- `getPageCount()` (method, since 0.4.0): Number of pages.
  - returns number: Number of pages.
- `getFrameNames()` (method, since 0.4.0): Returns the list of names. (contains both the names without extensions and the file names)
  - returns string[]: Name list.
- `isLoaded()` (method, since 0.4.0): Whether it has loaded.
  - returns boolean: True if loaded.
- `static addSearchAtlas(spriteAtlas)` (static, since 0.4.0): Adds an atlas to search. (static, appended to the end, unchanged if already present)
  - `spriteAtlas` SpriteAtlas: Atlas to add.
- `static removeSearchAtlas(spriteAtlas)` (static, since 0.4.0): Removes an atlas to search. (static)
  - `spriteAtlas` SpriteAtlas: Atlas to remove. (does nothing if not in the list)
- `static clearSearchAtlases()` (static, since 0.4.0): Removes all atlases to search. (static)
- `static findFrame(frameName)` (static, since 0.4.0): Finds a frame in the search atlases. (static, in the order added, null if absent)
  - `frameName` string: Image name.
  - returns Frame | null: The first frame found. (null if none)
- `static applySearchFrame(sprite, frameName)` (static, since 0.4.0): Applies the frame found in the search atlases to a sprite. (static, clears the image and returns false if absent)
  - `sprite` Sprite: Sprite to set the frame on.
  - `frameName` string: Image name.
  - returns boolean: True if found and set.
- `static findFrameInOrder(atlasList, frameName)` (static, since 0.4.0): Finds a frame in the given atlases in order. (static, earlier ones win, null if absent, does not use the search atlas list)
  - `atlasList` SpriteAtlas[]: List of atlases to search. (earlier ones win)
  - `frameName` string: Image name.
  - returns Frame | null: The first frame found. (null if none)

  Example: Search a seasonal atlas before the base atlas

  ```js
  import { SpriteAtlas } from "./build/vanilla.js";
  
  const baseAtlas = new SpriteAtlas();
  await baseAtlas.loadData({
  	pagePaths: ["examples/assets/spritesheet.png"],
  	frames: {
  		"walk-0.png": [0, 0, 0, 200, 200],
  		"walk-1.png": [0, 200, 0, 200, 200],
  	},
  });
  const seasonAtlas = new SpriteAtlas();
  await seasonAtlas.loadData({
  	pagePaths: ["examples/assets/spritesheet.png"],
  	frames: {
  		"walk-0": [0, 400, 400, 200, 200],
  	},
  });
  const frame = SpriteAtlas.findFrameInOrder([seasonAtlas, baseAtlas], "walk-0");
  const imageRect = frame.getImageRect();
  const fallbackFrame = SpriteAtlas.findFrameInOrder([seasonAtlas, baseAtlas], "walk-1");
  const fallbackRect = fallbackFrame.getImageRect();
  console.log(imageRect.x, fallbackRect.x);
  ```

- `static applyFrameInOrder(atlasList, sprite, frameName)` (static, since 0.4.0): Applies the frame found in order in the given atlases to a sprite. (static, clears the image and returns false if absent)
  - `atlasList` SpriteAtlas[]: List of atlases to search. (earlier ones win)
  - `sprite` Sprite: Sprite to set the frame on.
  - `frameName` string: Image name.
  - returns boolean: True if found and set.
