@image/packer
Version:
image packer
99 lines (98 loc) • 3.73 kB
JavaScript
var Spritesheet = (function () {
function Spritesheet(atlasGroup, bin, exportConfig, cache, imageProcessor) {
this.bin = bin;
this.exportConfig = exportConfig;
this.cache = cache;
this.hash = this.calculateHash(atlasGroup);
this.imageProcessor = imageProcessor;
}
Spritesheet.prototype.createImage = function (cachedImagePath) {
this.width = this.bin.width;
this.height = this.bin.height;
var images = this.bin.rects.map(function (rect) {
var filePath = rect.data.data.path;
return {
width: rect.width,
height: rect.height,
x: rect.x,
y: rect.y,
filePath: filePath
};
});
return this.imageProcessor.combine(images, this.width, this.height, cachedImagePath, this.exportConfig);
};
Spritesheet.prototype.createLoadingInformation = function () {
return this.bin.rects.map(function (rect) {
var scaledSprite = rect.data.data;
var sprite = scaledSprite.sprite;
var result = {
path: sprite.path,
position: {
x: rect.x,
y: rect.y
},
dimension: {
w: scaledSprite.width,
h: scaledSprite.height
},
trim: null
};
if (scaledSprite.trim) {
result.trim = {
x: scaledSprite.trim.x,
y: scaledSprite.trim.y,
w: scaledSprite.trim.width,
h: scaledSprite.trim.height
};
}
return result;
});
};
Spritesheet.prototype.cacheMiss = function () {
var _this = this;
var cachedImagePath = this.cache.getCachePath(this.basename);
return this.createImage(cachedImagePath)
.then(function () {
return Promise.all([
_this.createLoadingInformation()
]);
})
.then(function (results) {
var loadingInformation = results[0];
return {
cachedImagePath: cachedImagePath, loadingInformation: loadingInformation,
width: _this.width,
height: _this.height
};
});
};
Spritesheet.prototype.cacheInterpret = function (data) {
this.cachedImagePath = data.cachedImagePath;
this.loadingInformation = data.loadingInformation;
this.width = data.width;
this.height = data.height;
};
Object.defineProperty(Spritesheet.prototype, "basename", {
get: function () {
return this.hash + '.' + (this.exportConfig.ext ? this.exportConfig.ext : 'png');
},
enumerable: true,
configurable: true
});
Spritesheet.prototype.calculateHash = function (atlasGroup) {
var str = atlasGroup.hash;
str += this.bin.rects.map(function (rect) {
return rect.data.data.path + '_' + rect.x + '_' + rect.y;
}).sort().join(' ') + '_';
str += JSON.stringify(this.exportConfig, null, 2);
return this.cache.createHash(str);
};
Spritesheet.prototype.process = function () {
var _this = this;
return this.cache.lookup('spritesheet', this.hash, this.cacheMiss.bind(this), 3)
.then(this.cacheInterpret.bind(this))
.then(function () { return _this; });
};
return Spritesheet;
}());
export default Spritesheet;