Skip to content

Commit

Permalink
Issue #414: part10: support opacity in preview renderers
Browse files Browse the repository at this point in the history
  • Loading branch information
juliandescottes committed Mar 24, 2016
1 parent 99b00bc commit 327df53
Show file tree
Hide file tree
Showing 14 changed files with 189 additions and 79 deletions.
11 changes: 8 additions & 3 deletions src/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,14 @@
},

getFirstFrameAsPng : function () {
var firstFrame = this.piskelController.getMergedFrameAt(0);
var firstFrameCanvas = pskl.utils.FrameUtils.toImage(firstFrame);
return firstFrameCanvas.toDataURL('image/png');
var frame = pskl.utils.LayerUtils.mergeFrameAt(this.piskelController.getLayers(), 0);
var canvas;
if (frame instanceof pskl.model.frame.RenderedFrame) {
canvas = pskl.utils.CanvasUtils.createFromImage(frame.getRenderedFrame());
} else {
canvas = pskl.utils.FrameUtils.toImage(frame);
}
return canvas.toDataURL('image/png');
},

getFramesheetAsPng : function () {
Expand Down
13 changes: 3 additions & 10 deletions src/js/controller/piskel/PiskelController.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,10 @@
return this.piskel;
};

ns.PiskelController.prototype.getMergedFrameAt = function (index) {
var hash = [];
var frames = this.getLayers().map(function (l) {
var frame = l.getFrameAt(index);
hash.push(frame.getHash());
return frame;
ns.PiskelController.prototype.isTransparent = function () {
return this.getLayers().some(function (l) {
return l.isTransparent();
});
var mergedFrame = pskl.utils.FrameUtils.merge(frames);
mergedFrame.id = hash.join('-');
mergedFrame.version = 0;
return mergedFrame;
};

ns.PiskelController.prototype.renderFrameAt = function (index, preserveOpacity) {
Expand Down
6 changes: 3 additions & 3 deletions src/js/controller/preview/PreviewController.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,9 @@
ns.PreviewController.prototype.render = function (delta) {
this.elapsedTime += delta;
var index = this.getNextIndex_(delta);
if (this.shoudlRender_() || this.currentIndex != index) {
if (this.shouldRender_() || this.currentIndex != index) {
this.currentIndex = index;
var frame = this.piskelController.getMergedFrameAt(this.currentIndex);
var frame = pskl.utils.LayerUtils.mergeFrameAt(this.piskelController.getLayers(), index);
this.renderer.render(frame);
this.renderFlag = false;

Expand Down Expand Up @@ -240,7 +240,7 @@
this.renderFlag = bool;
};

ns.PreviewController.prototype.shoudlRender_ = function () {
ns.PreviewController.prototype.shouldRender_ = function () {
return this.renderFlag || this.popupPreviewController.renderFlag;
};

Expand Down
8 changes: 3 additions & 5 deletions src/js/controller/settings/exportimage/GifExportController.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,9 @@
ns.GifExportController.prototype.renderAsImageDataAnimatedGIF = function(zoom, fps, cb) {
var currentColors = pskl.app.currentColorsService.getCurrentColors();

var hasTransparency = this.piskelController.getLayers().some(function (l) {
var opacity = l.getOpacity();
return opacity > 0 && opacity < 1;
});
var preserveColors = !hasTransparency && currentColors.length < MAX_GIF_COLORS;
var layers = this.piskelController.getLayers();
var isTransparent = layers.some(function (l) {return l.isTransparent();});
var preserveColors = !isTransparent && currentColors.length < MAX_GIF_COLORS;

var transparentColor, transparent;
// transparency only supported if preserveColors is true, see Issue #357
Expand Down
4 changes: 4 additions & 0 deletions src/js/model/Layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
this.opacity = opacity;
};

ns.Layer.prototype.isTransparent = function () {
return this.opacity > 0 && this.opacity < 1;
};

ns.Layer.prototype.getFrames = function () {
return this.frames;
};
Expand Down
4 changes: 4 additions & 0 deletions src/js/model/frame/AsyncCachedFrameProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
var key1 = frame.getHash();
if (cache[key1]) {
processedFrame = cache[key1];
} else if (frame instanceof pskl.model.frame.RenderedFrame) {
// Cannot use 2nd level cache with rendered frames
var callbackFirstLvlCacheOnly = this.onProcessorComplete_.bind(this, deferred, cache, key1, key1);
this.frameProcessor(frame, callbackFirstLvlCacheOnly);
} else {
var framePixels = JSON.stringify(frame.getPixels());
var key2 = pskl.utils.hashCode(framePixels);
Expand Down
4 changes: 4 additions & 0 deletions src/js/model/frame/CachedFrameProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@
var cacheKey = frame.getHash();
if (cache[cacheKey]) {
processedFrame = cache[cacheKey];
} else if (frame instanceof pskl.model.frame.RenderedFrame) {
// Cannot use 2nd level cache with rendered frames
processedFrame = this.frameProcessor(frame);
cache[cacheKey] = processedFrame;
} else {
var framePixels = JSON.stringify(frame.getPixels());
var frameAsString = pskl.utils.hashCode(framePixels);
Expand Down
49 changes: 49 additions & 0 deletions src/js/model/frame/RenderedFrame.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
(function () {
var ns = $.namespace('pskl.model.frame');

/**
* Create a frame instance that provides an image getter. Can be faster
* to use after merging using transparency. Transparent frames are merged to
* an image and this allows to reuse the image rather than retransform into
* a frame before calling the renderers.
*
* This rendered frame should only be used with renderers that support it.
*
* @param {Function} imageFn getter that will create the image
* @param {Number} width image width in pixels
* @param {Number} height image height in pixels
* @param {String} id will be used as hash, so should be as unique as possible
*/
ns.RenderedFrame = function (renderFn, width, height, id) {
this.width = width;
this.height = height;
this.id = id;
this.renderFn = renderFn;
};

ns.RenderedFrame.prototype.getRenderedFrame = function () {
return this.renderFn();
};

ns.RenderedFrame.prototype.getHash = function () {
return this.id;
};

ns.RenderedFrame.prototype.getWidth = function () {
return this.width;
};

ns.RenderedFrame.prototype.getHeight = function () {
return this.height;
};

ns.RenderedFrame.prototype.getPixels = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.containsPixel = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.isSameSize = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.clone = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.setPixels = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.clear = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.setPixel = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.getPixel = Constants.ABSTRACT_FUNCTION;
ns.RenderedFrame.prototype.forEachPixel = Constants.ABSTRACT_FUNCTION;
})();
7 changes: 6 additions & 1 deletion src/js/rendering/frame/BackgroundImageFrameRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
};

ns.BackgroundImageFrameRenderer.prototype.frameToDataUrl_ = function (frame) {
var canvas = new pskl.utils.FrameUtils.toImage(frame, this.zoom);
var canvas;
if (frame instanceof pskl.model.frame.RenderedFrame) {
canvas = pskl.utils.ImageResizer.scale(frame.getRenderedFrame(), this.zoom);
} else {
canvas = pskl.utils.FrameUtils.toImage(frame, this.zoom);
}
return canvas.toDataURL('image/png');
};

Expand Down
30 changes: 8 additions & 22 deletions src/js/rendering/layer/LayersRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@
var offset = this.getOffset();
var size = this.getDisplaySize();
var layers = this.piskelController.getLayers();
var currentFrameIndex = this.piskelController.getCurrentFrameIndex();
var currentLayerIndex = this.piskelController.getCurrentLayerIndex();
var frameIndex = this.piskelController.getCurrentFrameIndex();
var layerIndex = this.piskelController.getCurrentLayerIndex();

var belowLayers = layers.slice(0, currentLayerIndex);
var aboveLayers = layers.slice(currentLayerIndex + 1, layers.length);
var belowLayers = layers.slice(0, layerIndex);
var aboveLayers = layers.slice(layerIndex + 1, layers.length);

var serializedRendering = [
this.getZoom(),
Expand All @@ -45,8 +45,8 @@
offset.y,
size.width,
size.height,
this.getHashForLayersAt_(currentFrameIndex, belowLayers),
this.getHashForLayersAt_(currentFrameIndex, aboveLayers),
pskl.utils.LayerUtils.getFrameHashAt(belowLayers, frameIndex),
pskl.utils.LayerUtils.getFrameHashAt(aboveLayers, frameIndex),
layers.length
].join('-');

Expand All @@ -56,12 +56,12 @@
this.clear();

if (belowLayers.length > 0) {
var belowFrame = this.getFrameForLayersAt_(currentFrameIndex, belowLayers);
var belowFrame = pskl.utils.LayerUtils.mergeFrameAt(belowLayers, frameIndex);
this.belowRenderer.render(belowFrame);
}

if (aboveLayers.length > 0) {
var aboveFrame = this.getFrameForLayersAt_(currentFrameIndex, aboveLayers);
var aboveFrame = pskl.utils.LayerUtils.mergeFrameAt(aboveLayers, frameIndex);
this.aboveRenderer.render(aboveFrame);
}
}
Expand All @@ -80,20 +80,6 @@
}
};

ns.LayersRenderer.prototype.getFrameForLayersAt_ = function (frameIndex, layers) {
var frames = layers.map(function (l) {
return l.getFrameAt(frameIndex);
});
return pskl.utils.FrameUtils.merge(frames);
};

ns.LayersRenderer.prototype.getHashForLayersAt_ = function (frameIndex, layers) {
var hash = layers.map(function (l) {
return l.getFrameAt(frameIndex).getHash();
});
return hash.join('-');
};

ns.LayersRenderer.prototype.onUserSettingsChange_ = function (evt, settingsName, settingsValue) {
if (settingsName == pskl.UserSettings.LAYER_OPACITY) {
this.updateLayersCanvasOpacity_(settingsValue);
Expand Down
78 changes: 48 additions & 30 deletions src/js/utils/FrameUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,43 @@
/**
* Draw the provided frame in a 2d canvas
*
* @param {Frame} frame the frame to draw
* @param {Frame|RenderedFrame} frame the frame to draw
* @param {Canvas} canvas the canvas target
* @param {String} transparentColor (optional) color to use to represent transparent pixels.
* @param {String} opacity (optional) global frame opacity
* @param {String} globalAlpha (optional) global frame opacity
*/
drawToCanvas : function (frame, canvas, transparentColor, opacity) {
drawToCanvas : function (frame, canvas, transparentColor, globalAlpha) {
var context = canvas.getContext('2d');
opacity = isNaN(opacity) ? 1 : opacity;
context.globalAlpha = opacity;

globalAlpha = isNaN(globalAlpha) ? 1 : globalAlpha;
context.globalAlpha = globalAlpha;
transparentColor = transparentColor || Constants.TRANSPARENT_COLOR;
for (var x = 0, width = frame.getWidth() ; x < width ; x++) {
for (var y = 0, height = frame.getHeight() ; y < height ; y++) {
var color = frame.getPixel(x, y);

// accumulate all the pixels of the same color to speed up rendering
// by reducting fillRect calls
var w = 1;
while (color === frame.getPixel(x, y + w) && (y + w) < height) {
w++;
}

if (color == Constants.TRANSPARENT_COLOR) {
color = transparentColor;
if (frame instanceof pskl.model.frame.RenderedFrame) {
context.fillRect(transparentColor, 0, 0, frame.getWidth(), frame.getHeight());
context.drawImage(frame.getRenderedFrame(), 0, 0);
} else {
for (var x = 0, width = frame.getWidth() ; x < width ; x++) {
for (var y = 0, height = frame.getHeight() ; y < height ; y++) {
var color = frame.getPixel(x, y);

// accumulate all the pixels of the same color to speed up rendering
// by reducting fillRect calls
var w = 1;
while (color === frame.getPixel(x, y + w) && (y + w) < height) {
w++;
}

if (color == Constants.TRANSPARENT_COLOR) {
color = transparentColor;
}

pskl.utils.FrameUtils.renderLine_(color, x, y, w, context);
y = y + w - 1;
}

pskl.utils.FrameUtils.renderLine_(color, x, y, w, context);
y = y + w - 1;
}

context.globalAlpha = 1;
}
context.globalAlpha = 1;
},

/**
Expand Down Expand Up @@ -98,23 +104,27 @@
},

/*
* Create a pskl.model.Frame from an Image object.
* Transparent pixels will either be converted to completely opaque or completely transparent pixels.
* Create a pskl.model.Frame from an Image object. By default transparent
* pixels will be converted to completely opaque or completely transparent
* pixels. If preserveOpacity is true the actual opacity of the pixel will
* be used and the generated frame will contain rgba pixels.
*
* @param {Image} image source image
* @param {boolean} preserveOpacity set to true to preserve the opacity
* @return {pskl.model.Frame} corresponding frame
*/
createFromImage : function (image) {
createFromImage : function (image, preserveOpacity) {
var w = image.width;
var h = image.height;
var canvas = pskl.utils.CanvasUtils.createCanvas(w, h);
var context = canvas.getContext('2d');

context.drawImage(image, 0, 0, w, h, 0, 0, w, h);
var imgData = context.getImageData(0, 0, w, h).data;
return pskl.utils.FrameUtils.createFromImageData_(imgData, w, h);
return pskl.utils.FrameUtils.createFromImageData_(imgData, w, h, preserveOpacity);
},

createFromImageData_ : function (imageData, width, height) {
createFromImageData_ : function (imageData, width, height, preserveOpacity) {
// Draw the zoomed-up pixels to a different canvas context
var grid = [];
for (var x = 0 ; x < width ; x++) {
Expand All @@ -126,10 +136,18 @@
var g = imageData[i + 1];
var b = imageData[i + 2];
var a = imageData[i + 3];
if (a < 125) {
grid[x][y] = Constants.TRANSPARENT_COLOR;
if (preserveOpacity) {
if (a === 0) {
grid[x][y] = Constants.TRANSPARENT_COLOR;
} else {
grid[x][y] = 'rgba(' + [r, g, b, a / 255].join(',') + ')';
}
} else {
grid[x][y] = pskl.utils.rgbToHex(r, g, b);
if (a < 125) {
grid[x][y] = Constants.TRANSPARENT_COLOR;
} else {
grid[x][y] = pskl.utils.rgbToHex(r, g, b);
}
}
}
}
Expand Down
Loading

0 comments on commit 327df53

Please sign in to comment.