From 034f6ed267d43def6610258c89223570c0d7e3b0 Mon Sep 17 00:00:00 2001 From: cha0s Date: Wed, 4 May 2022 08:08:37 -0500 Subject: [PATCH] refactor: Pictured --- packages/graphics/src/atlas.js | 9 ++++++-- packages/graphics/src/traits/pictured.js | 29 ++++++++++++++---------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/packages/graphics/src/atlas.js b/packages/graphics/src/atlas.js index 6f5a8b2..ae10a92 100644 --- a/packages/graphics/src/atlas.js +++ b/packages/graphics/src/atlas.js @@ -22,6 +22,10 @@ export default class Atlas extends JsonResource { return this.$$image; } + get size() { + return this.$$size; + } + async load(json = {}) { await super.load(json); this.destroy(); @@ -32,9 +36,10 @@ export default class Atlas extends JsonResource { this.$$image = await Image.load(imageUri); switch (type) { case 'grid': { - const {size} = json; + let {size} = json; + this.$$size = size; if (Vector.isNull(size)) { - return; + ({size} = this.$$image); } const grid = Vector.div(this.$$image.size, size); const rectangle = Rectangle.compose([0, 0], size); diff --git a/packages/graphics/src/traits/pictured.js b/packages/graphics/src/traits/pictured.js index 7e9fa51..8f924f6 100644 --- a/packages/graphics/src/traits/pictured.js +++ b/packages/graphics/src/traits/pictured.js @@ -2,7 +2,7 @@ import {mapValuesAsync} from '@avocado/core'; import {Rectangle, Vector} from '@avocado/math'; import {compose} from '@flecks/core'; -import Image from '../image'; +import Atlas from '../atlas'; import Sprite from '../sprite'; export default (flecks) => { @@ -32,6 +32,7 @@ export default (flecks) => { static defaultParams() { return { + atlas: {}, images: {}, }; } @@ -135,18 +136,22 @@ export default (flecks) => { async load(json = {}) { await super.load(json); - const images = Object.fromEntries( - Object.entries({ - ...this.params.images, - default: { - uri: this.entity.uri?.replace('.entity.json', '.png'), - ...(this.params.images.default || {}), - }, - }) - .filter(([, {uri}]) => !!uri), - ); + const images = {}; + const atlas = await Atlas.load({ + imageUri: this.entity.uri?.replace('.entity.json', '.png'), + ...this.params.atlas, + }); + const keys = Object.keys(this.params.images); + if (0 === keys.length) { + images.default = atlas.subimage(0); + } + else { + for (let i = 0; i < keys.length; ++i) { + images[keys[i]] = atlas.subimage(i); + } + } this.$$currentImage = this.state.currentImage; - this.$$images = await mapValuesAsync(images, ({uri}) => Image.load(uri)); + this.$$images = images; this.$$sprites = await mapValuesAsync(this.$$images, async (image) => new Sprite(image)); Object.keys(this.$$sprites).forEach((key) => { // eslint-disable-next-line no-param-reassign