spritesheet.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*!
  2. * @pixi/spritesheet - v6.5.10
  3. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  4. *
  5. * @pixi/spritesheet is licensed under the MIT License.
  6. * http://www.opensource.org/licenses/mit-license
  7. */
  8. import { Rectangle } from '@pixi/math';
  9. import { Texture, BaseTexture, ExtensionType } from '@pixi/core';
  10. import { getResolutionOfUrl, deprecation, url } from '@pixi/utils';
  11. import { LoaderResource } from '@pixi/loaders';
  12. /**
  13. * Utility class for maintaining reference to a collection
  14. * of Textures on a single Spritesheet.
  15. *
  16. * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader:
  17. *
  18. * ```js
  19. * PIXI.Loader.shared.add("images/spritesheet.json").load(setup);
  20. *
  21. * function setup() {
  22. * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet;
  23. * ...
  24. * }
  25. * ```
  26. *
  27. * Alternately, you may circumvent the loader by instantiating the Spritesheet directly:
  28. * ```js
  29. * const sheet = new PIXI.Spritesheet(texture, spritesheetData);
  30. * await sheet.parse();
  31. * console.log('Spritesheet ready to use!');
  32. * ```
  33. *
  34. * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite.
  35. *
  36. * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
  37. * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
  38. * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only
  39. * supported by TexturePacker.
  40. * @memberof PIXI
  41. */
  42. var Spritesheet = /** @class */ (function () {
  43. /**
  44. * @param texture - Reference to the source BaseTexture object.
  45. * @param {object} data - Spritesheet image data.
  46. * @param resolutionFilename - The filename to consider when determining
  47. * the resolution of the spritesheet. If not provided, the imageUrl will
  48. * be used on the BaseTexture.
  49. */
  50. function Spritesheet(texture, data, resolutionFilename) {
  51. if (resolutionFilename === void 0) { resolutionFilename = null; }
  52. /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */
  53. this.linkedSheets = [];
  54. this._texture = texture instanceof Texture ? texture : null;
  55. this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture;
  56. this.textures = {};
  57. this.animations = {};
  58. this.data = data;
  59. var resource = this.baseTexture.resource;
  60. this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null));
  61. this._frames = this.data.frames;
  62. this._frameKeys = Object.keys(this._frames);
  63. this._batchIndex = 0;
  64. this._callback = null;
  65. }
  66. /**
  67. * Generate the resolution from the filename or fallback
  68. * to the meta.scale field of the JSON data.
  69. * @param resolutionFilename - The filename to use for resolving
  70. * the default resolution.
  71. * @returns Resolution to use for spritesheet.
  72. */
  73. Spritesheet.prototype._updateResolution = function (resolutionFilename) {
  74. if (resolutionFilename === void 0) { resolutionFilename = null; }
  75. var scale = this.data.meta.scale;
  76. // Use a defaultValue of `null` to check if a url-based resolution is set
  77. var resolution = getResolutionOfUrl(resolutionFilename, null);
  78. // No resolution found via URL
  79. if (resolution === null) {
  80. // Use the scale value or default to 1
  81. resolution = scale !== undefined ? parseFloat(scale) : 1;
  82. }
  83. // For non-1 resolutions, update baseTexture
  84. if (resolution !== 1) {
  85. this.baseTexture.setResolution(resolution);
  86. }
  87. return resolution;
  88. };
  89. /** @ignore */
  90. Spritesheet.prototype.parse = function (callback) {
  91. var _this = this;
  92. if (callback) {
  93. deprecation('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.');
  94. }
  95. return new Promise(function (resolve) {
  96. _this._callback = function (textures) {
  97. callback === null || callback === void 0 ? void 0 : callback(textures);
  98. resolve(textures);
  99. };
  100. _this._batchIndex = 0;
  101. if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) {
  102. _this._processFrames(0);
  103. _this._processAnimations();
  104. _this._parseComplete();
  105. }
  106. else {
  107. _this._nextBatch();
  108. }
  109. });
  110. };
  111. /**
  112. * Process a batch of frames
  113. * @param initialFrameIndex - The index of frame to start.
  114. */
  115. Spritesheet.prototype._processFrames = function (initialFrameIndex) {
  116. var frameIndex = initialFrameIndex;
  117. var maxFrames = Spritesheet.BATCH_SIZE;
  118. while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) {
  119. var i = this._frameKeys[frameIndex];
  120. var data = this._frames[i];
  121. var rect = data.frame;
  122. if (rect) {
  123. var frame = null;
  124. var trim = null;
  125. var sourceSize = data.trimmed !== false && data.sourceSize
  126. ? data.sourceSize : data.frame;
  127. var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution);
  128. if (data.rotated) {
  129. frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution);
  130. }
  131. else {
  132. frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  133. }
  134. // Check to see if the sprite is trimmed
  135. if (data.trimmed !== false && data.spriteSourceSize) {
  136. trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  137. }
  138. this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor);
  139. // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions
  140. Texture.addToCache(this.textures[i], i);
  141. }
  142. frameIndex++;
  143. }
  144. };
  145. /** Parse animations config. */
  146. Spritesheet.prototype._processAnimations = function () {
  147. var animations = this.data.animations || {};
  148. for (var animName in animations) {
  149. this.animations[animName] = [];
  150. for (var i = 0; i < animations[animName].length; i++) {
  151. var frameName = animations[animName][i];
  152. this.animations[animName].push(this.textures[frameName]);
  153. }
  154. }
  155. };
  156. /** The parse has completed. */
  157. Spritesheet.prototype._parseComplete = function () {
  158. var callback = this._callback;
  159. this._callback = null;
  160. this._batchIndex = 0;
  161. callback.call(this, this.textures);
  162. };
  163. /** Begin the next batch of textures. */
  164. Spritesheet.prototype._nextBatch = function () {
  165. var _this = this;
  166. this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE);
  167. this._batchIndex++;
  168. setTimeout(function () {
  169. if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) {
  170. _this._nextBatch();
  171. }
  172. else {
  173. _this._processAnimations();
  174. _this._parseComplete();
  175. }
  176. }, 0);
  177. };
  178. /**
  179. * Destroy Spritesheet and don't use after this.
  180. * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
  181. */
  182. Spritesheet.prototype.destroy = function (destroyBase) {
  183. var _a;
  184. if (destroyBase === void 0) { destroyBase = false; }
  185. for (var i in this.textures) {
  186. this.textures[i].destroy();
  187. }
  188. this._frames = null;
  189. this._frameKeys = null;
  190. this.data = null;
  191. this.textures = null;
  192. if (destroyBase) {
  193. (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy();
  194. this.baseTexture.destroy();
  195. }
  196. this._texture = null;
  197. this.baseTexture = null;
  198. this.linkedSheets = [];
  199. };
  200. /** The maximum number of Textures to build per process. */
  201. Spritesheet.BATCH_SIZE = 1000;
  202. return Spritesheet;
  203. }());
  204. /**
  205. * Reference to Spritesheet object created.
  206. * @member {PIXI.Spritesheet} spritesheet
  207. * @memberof PIXI.LoaderResource
  208. * @instance
  209. */
  210. /**
  211. * Dictionary of textures from Spritesheet.
  212. * @member {Object<string, PIXI.Texture>} textures
  213. * @memberof PIXI.LoaderResource
  214. * @instance
  215. */
  216. /**
  217. * {@link PIXI.Loader} middleware for loading texture atlases that have been created with
  218. * TexturePacker or similar JSON-based spritesheet.
  219. *
  220. * This middleware automatically generates Texture resources.
  221. *
  222. * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON,
  223. * use the {@link PIXI.Spritesheet} class to directly parse the JSON.
  224. *
  225. * The Loader's image Resource name is automatically appended with `"_image"`.
  226. * If a Resource with this name is already loaded, the Loader will skip parsing the
  227. * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`.
  228. * @example
  229. * loader.add('myatlas', 'path/to/myatlas.json');
  230. * loader.load(() => {
  231. * loader.resources.myatlas; // atlas JSON resource
  232. * loader.resources.myatlas_image; // atlas Image resource
  233. * });
  234. * @memberof PIXI
  235. */
  236. var SpritesheetLoader = /** @class */ (function () {
  237. function SpritesheetLoader() {
  238. }
  239. /**
  240. * Called after a resource is loaded.
  241. * @see PIXI.Loader.loaderMiddleware
  242. * @param resource
  243. * @param next
  244. */
  245. SpritesheetLoader.use = function (resource, next) {
  246. var _a, _b;
  247. // because this is middleware, it execute in loader context. `this` = loader
  248. var loader = this;
  249. var imageResourceName = resource.name + "_image";
  250. // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
  251. if (!resource.data
  252. || resource.type !== LoaderResource.TYPE.JSON
  253. || !resource.data.frames
  254. || loader.resources[imageResourceName]) {
  255. next();
  256. return;
  257. }
  258. // Check and add the multi atlas
  259. // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js
  260. // eslint-disable-next-line camelcase
  261. var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs;
  262. if (Array.isArray(multiPacks)) {
  263. var _loop_1 = function (item) {
  264. if (typeof item !== 'string') {
  265. return "continue";
  266. }
  267. var itemName = item.replace('.json', '');
  268. var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item);
  269. // Check if the file wasn't already added as multipacks are redundant
  270. if (loader.resources[itemName]
  271. || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) {
  272. return "continue";
  273. }
  274. var options = {
  275. crossOrigin: resource.crossOrigin,
  276. loadType: LoaderResource.LOAD_TYPE.XHR,
  277. xhrType: LoaderResource.XHR_RESPONSE_TYPE.JSON,
  278. parentResource: resource,
  279. metadata: resource.metadata
  280. };
  281. loader.add(itemName, itemUrl, options);
  282. };
  283. for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) {
  284. var item = multiPacks_1[_i];
  285. _loop_1(item);
  286. }
  287. }
  288. var loadOptions = {
  289. crossOrigin: resource.crossOrigin,
  290. metadata: resource.metadata.imageMetadata,
  291. parentResource: resource,
  292. };
  293. var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl);
  294. // load the image for this sheet
  295. loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) {
  296. if (res.error) {
  297. next(res.error);
  298. return;
  299. }
  300. var spritesheet = new Spritesheet(res.texture, resource.data, resource.url);
  301. spritesheet.parse().then(function () {
  302. resource.spritesheet = spritesheet;
  303. resource.textures = spritesheet.textures;
  304. next();
  305. });
  306. });
  307. };
  308. /**
  309. * Get the spritesheets root path
  310. * @param resource - Resource to check path
  311. * @param baseUrl - Base root url
  312. */
  313. SpritesheetLoader.getResourcePath = function (resource, baseUrl) {
  314. // Prepend url path unless the resource image is a data url
  315. if (resource.isDataUrl) {
  316. return resource.data.meta.image;
  317. }
  318. return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
  319. };
  320. /** @ignore */
  321. SpritesheetLoader.extension = ExtensionType.Loader;
  322. return SpritesheetLoader;
  323. }());
  324. export { Spritesheet, SpritesheetLoader };
  325. //# sourceMappingURL=spritesheet.mjs.map