Merge pull request #67 from juliandescottes/add-renderingloop

Add renderingloop
This commit is contained in:
Julian Descottes 2012-09-10 15:55:33 -07:00
commit e9c61285af
22 changed files with 414 additions and 451 deletions

3
.travis.yml Normal file
View File

@ -0,0 +1,3 @@
language: node_js
node_js:
- 0.6

2
Makefile Normal file
View File

@ -0,0 +1,2 @@
test:
jshint js/*.js

View File

@ -3,7 +3,6 @@ Events = {
TOOL_SELECTED : "TOOL_SELECTED", TOOL_SELECTED : "TOOL_SELECTED",
TOOL_RELEASED : "TOOL_RELEASED", TOOL_RELEASED : "TOOL_RELEASED",
COLOR_SELECTED: "COLOR_SELECTED", COLOR_SELECTED: "COLOR_SELECTED",
COLOR_USED: "COLOR_USED",
/** /**
* When this event is emitted, a request is sent to the localstorage * When this event is emitted, a request is sent to the localstorage
@ -13,7 +12,6 @@ Events = {
LOCALSTORAGE_REQUEST: "LOCALSTORAGE_REQUEST", LOCALSTORAGE_REQUEST: "LOCALSTORAGE_REQUEST",
CANVAS_RIGHT_CLICKED: "CANVAS_RIGHT_CLICKED", CANVAS_RIGHT_CLICKED: "CANVAS_RIGHT_CLICKED",
CANVAS_RIGHT_CLICK_RELEASED: "CANVAS_RIGHT_CLICK_RELEASED",
/** /**
* Event to request a refresh of the display. * Event to request a refresh of the display.

View File

@ -1,6 +1,8 @@
(function () { (function () {
var ns = $.namespace("pskl"); var ns = $.namespace("pskl");
ns.HistoryManager = function () {}; ns.HistoryManager = function (framesheet) {
this.framesheet = framesheet;
};
ns.HistoryManager.prototype.init = function () { ns.HistoryManager.prototype.init = function () {
document.body.addEventListener('keyup', this.onKeyup.bind(this)); document.body.addEventListener('keyup', this.onKeyup.bind(this));
@ -8,7 +10,7 @@
}; };
ns.HistoryManager.prototype.saveState = function () { ns.HistoryManager.prototype.saveState = function () {
piskel.getCurrentFrame().saveState(); this.framesheet.getCurrentFrame().saveState();
}; };
ns.HistoryManager.prototype.onKeyup = function (evt) { ns.HistoryManager.prototype.onKeyup = function (evt) {
@ -22,19 +24,17 @@
}; };
ns.HistoryManager.prototype.undo = function () { ns.HistoryManager.prototype.undo = function () {
piskel.getCurrentFrame().loadPreviousState(); this.framesheet.getCurrentFrame().loadPreviousState();
this.redraw(); this.redraw();
}; };
ns.HistoryManager.prototype.redo = function () { ns.HistoryManager.prototype.redo = function () {
piskel.getCurrentFrame().loadNextState(); this.framesheet.getCurrentFrame().loadNextState();
this.redraw(); this.redraw();
}; };
ns.HistoryManager.prototype.redraw = function () { ns.HistoryManager.prototype.redraw = function () {
piskel.drawingController.renderFrame(); this.framesheet.drawingController.renderFrame();
piskel.previewsController.createPreviews(); this.framesheet.previewsController.createPreviews();
}; };
ns.HistoryManager = new ns.HistoryManager();
})(); })();

View File

@ -21,7 +21,7 @@ pskl.LocalStorageService = (function() {
var persistToLocalStorageRequest_ = function() { var persistToLocalStorageRequest_ = function() {
// Persist to localStorage when drawing. We throttle localStorage accesses // Persist to localStorage when drawing. We throttle localStorage accesses
// for high frequency drawing (eg mousemove). // for high frequency drawing (eg mousemove).
if(localStorageThrottler_ != null) { if(localStorageThrottler_ !== null) {
window.clearTimeout(localStorageThrottler_); window.clearTimeout(localStorageThrottler_);
} }
localStorageThrottler_ = window.setTimeout(function() { localStorageThrottler_ = window.setTimeout(function() {
@ -34,32 +34,30 @@ pskl.LocalStorageService = (function() {
* @private * @private
*/ */
var persistToLocalStorage_ = function() { var persistToLocalStorage_ = function() {
console.log('[LocalStorage service]: Snapshot stored') console.log('[LocalStorage service]: Snapshot stored');
window.localStorage['snapShot'] = frameSheet_.serialize(); window.localStorage.snapShot = frameSheet_.serialize();
}; };
/** /**
* @private * @private
*/ */
var restoreFromLocalStorage_ = function() { var restoreFromLocalStorage_ = function() {
frameSheet_.deserialize(window.localStorage['snapShot']); frameSheet_.deserialize(window.localStorage.snapShot);
// Model updated, redraw everything:
$.publish(Events.REFRESH);
}; };
/** /**
* @private * @private
*/ */
var cleanLocalStorage_ = function() { var cleanLocalStorage_ = function() {
console.log('[LocalStorage service]: Snapshot removed') console.log('[LocalStorage service]: Snapshot removed');
delete window.localStorage['snapShot']; delete window.localStorage.snapShot;
}; };
return { return {
init: function(frameSheet) { init: function(frameSheet) {
if(frameSheet == undefined) { if(frameSheet === undefined) {
throw "Bad LocalStorageService initialization: <undefined frameSheet>" throw "Bad LocalStorageService initialization: <undefined frameSheet>";
} }
frameSheet_ = frameSheet; frameSheet_ = frameSheet;
@ -68,7 +66,7 @@ pskl.LocalStorageService = (function() {
// TODO(vincz): Find a good place to put this UI rendering, a service should not render UI. // TODO(vincz): Find a good place to put this UI rendering, a service should not render UI.
displayRestoreNotification: function() { displayRestoreNotification: function() {
if(window.localStorage && window.localStorage['snapShot']) { if(window.localStorage && window.localStorage.snapShot) {
var reloadLink = "<a href='#' class='localstorage-restore onclick='piskel.restoreFromLocalStorage()'>reload</a>"; var reloadLink = "<a href='#' class='localstorage-restore onclick='piskel.restoreFromLocalStorage()'>reload</a>";
var discardLink = "<a href='#' class='localstorage-discard' onclick='piskel.cleanLocalStorage()'>discard</a>"; var discardLink = "<a href='#' class='localstorage-discard' onclick='piskel.cleanLocalStorage()'>discard</a>";
var content = "Non saved version found. " + reloadLink + " or " + discardLink; var content = "Non saved version found. " + reloadLink + " or " + discardLink;

View File

@ -77,7 +77,7 @@ pskl.Palette = (function() {
} else { } else {
colorPicker[0].color.fromString(color); colorPicker[0].color.fromString(color);
} }
} };
return { return {
init: function(framesheet) { init: function(framesheet) {

View File

@ -20,16 +20,6 @@ pskl.ToolSelector = (function() {
var currentSelectedTool = toolInstances.simplePen; var currentSelectedTool = toolInstances.simplePen;
var previousSelectedTool = toolInstances.simplePen; var previousSelectedTool = toolInstances.simplePen;
var selectTool_ = function(tool) {
var maincontainer = $("body");
var previousSelectedToolClass = maincontainer.data("selected-tool-class");
if(previousSelectedToolClass) {
maincontainer.removeClass(previousSelectedToolClass);
}
maincontainer.addClass(toolBehavior.toolId);
$("#drawing-canvas-container").data("selected-tool-class", toolBehavior.toolId);
};
var activateToolOnStage_ = function(tool) { var activateToolOnStage_ = function(tool) {
var stage = $("body"); var stage = $("body");
var previousSelectedToolClass = stage.data("selected-tool-class"); var previousSelectedToolClass = stage.data("selected-tool-class");
@ -56,7 +46,7 @@ pskl.ToolSelector = (function() {
if(clickedTool.length) { if(clickedTool.length) {
for(var tool in toolInstances) { for(var tool in toolInstances) {
if (toolInstances[tool].toolId == clickedTool.data()["toolId"]) { if (toolInstances[tool].toolId == clickedTool.data().toolId) {
selectTool_(toolInstances[tool]); selectTool_(toolInstances[tool]);
// Show tool as selected: // Show tool as selected:
@ -88,10 +78,10 @@ pskl.ToolSelector = (function() {
$("#tools-container").click(onToolIconClicked_); $("#tools-container").click(onToolIconClicked_);
// Show/hide the grid on drawing canvas: // Show/hide the grid on drawing canvas:
$.publish(Events.GRID_DISPLAY_STATE_CHANGED, [isShowGridChecked_()]) $.publish(Events.GRID_DISPLAY_STATE_CHANGED, [isShowGridChecked_()]);
$('#show-grid').change(function(evt) { $('#show-grid').change(function(evt) {
var checked = isShowGridChecked_(); var checked = isShowGridChecked_();
$.publish(Events.GRID_DISPLAY_STATE_CHANGED, [checked]) $.publish(Events.GRID_DISPLAY_STATE_CHANGED, [checked]);
}); });
} }
}; };

View File

@ -1,8 +1,6 @@
(function () { (function () {
var ns = $.namespace("pskl.controller"); var ns = $.namespace("pskl.controller");
ns.DrawingController = function (frame, container, dpi) { ns.DrawingController = function (framesheet, container, dpi) {
this.dpi = dpi;
// TODO(vincz): Store user prefs in a localstorage string ? // TODO(vincz): Store user prefs in a localstorage string ?
var renderingOptions = { var renderingOptions = {
"dpi": dpi, "dpi": dpi,
@ -12,29 +10,22 @@
/** /**
* @public * @public
*/ */
this.frame = frame; this.framesheet = framesheet;
/** /**
* @public * @public
*/ */
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(frame); this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(framesheet.getCurrentFrame());
/** /**
* @private * @private
*/ */
this.container = container; this.container = container;
this.renderer = new pskl.rendering.FrameRenderer( this.renderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "drawing-canvas");
this.container, this.overlayRenderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "canvas-overlay");
renderingOptions,
"drawing-canvas");
this.overlayRenderer = new pskl.rendering.FrameRenderer( this.renderer.init(framesheet.getCurrentFrame());
this.container,
renderingOptions,
"canvas-overlay");
this.renderer.init(this.frame);
this.overlayRenderer.init(this.overlayFrame); this.overlayRenderer.init(this.overlayFrame);
// State of drawing controller: // State of drawing controller:
@ -48,7 +39,6 @@
this.initMouseBehavior(); this.initMouseBehavior();
$.subscribe(Events.TOOL_SELECTED, $.proxy(function(evt, toolBehavior) { $.subscribe(Events.TOOL_SELECTED, $.proxy(function(evt, toolBehavior) {
console.log("Tool selected: ", toolBehavior); console.log("Tool selected: ", toolBehavior);
this.currentToolBehavior = toolBehavior; this.currentToolBehavior = toolBehavior;
}, this)); }, this));
@ -84,14 +74,13 @@
$.publish(Events.CANVAS_RIGHT_CLICKED); $.publish(Events.CANVAS_RIGHT_CLICKED);
} }
var spriteCoordinate = this.getSpriteCoordinate(event); var coords = this.getSpriteCoordinates(event);
//console.log("mousedown: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
this.currentToolBehavior.applyToolAt( this.currentToolBehavior.applyToolAt(
spriteCoordinate.col, coords.col, coords.row,
spriteCoordinate.row,
this.getCurrentColor_(), this.getCurrentColor_(),
this this.framesheet.getCurrentFrame(),
this.overlayFrame
); );
$.publish(Events.LOCALSTORAGE_REQUEST); $.publish(Events.LOCALSTORAGE_REQUEST);
@ -104,27 +93,20 @@
var currentTime = new Date().getTime(); var currentTime = new Date().getTime();
// Throttling of the mousemove event: // Throttling of the mousemove event:
if ((currentTime - this.previousMousemoveTime) > 40 ) { if ((currentTime - this.previousMousemoveTime) > 40 ) {
var spriteCoordinate = this.getSpriteCoordinate(event); var coords = this.getSpriteCoordinates(event);
if (this.isClicked) { if (this.isClicked) {
this.currentToolBehavior.moveToolAt( this.currentToolBehavior.moveToolAt(
spriteCoordinate.col, coords.col, coords.row,
spriteCoordinate.row,
this.getCurrentColor_(), this.getCurrentColor_(),
this this.framesheet.getCurrentFrame(),
this.overlayFrame
); );
//console.log("mousemove: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
// TODO(vincz): Find a way to move that to the model instead of being at the interaction level. // TODO(vincz): Find a way to move that to the model instead of being at the interaction level.
// Eg when drawing, it may make sense to have it here. However for a non drawing tool, // Eg when drawing, it may make sense to have it here. However for a non drawing tool,
// you don't need to draw anything when mousemoving and you request useless localStorage. // you don't need to draw anything when mousemoving and you request useless localStorage.
$.publish(Events.LOCALSTORAGE_REQUEST); $.publish(Events.LOCALSTORAGE_REQUEST);
} else {
// debug mode to see the selected pixel
// this.clearOverlay();
// this.overlayFrame.setPixel( spriteCoordinate.col,spriteCoordinate.row, "#ff0000");
// this.renderOverlay();
} }
this.previousMousemoveTime = currentTime; this.previousMousemoveTime = currentTime;
} }
@ -139,26 +121,20 @@
// the user was probably drawing on the canvas. // the user was probably drawing on the canvas.
// Note: The mousemove movement (and the mouseup) may end up outside // Note: The mousemove movement (and the mouseup) may end up outside
// of the drawing canvas. // of the drawing canvas.
if(this.isRightClicked) {
$.publish(Events.CANVAS_RIGHT_CLICK_RELEASED);
}
this.isClicked = false; this.isClicked = false;
this.isRightClicked = false; this.isRightClicked = false;
var spriteCoordinate = this.getSpriteCoordinate(event);
var coords = this.getSpriteCoordinates(event);
//console.log("mousemove: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row); //console.log("mousemove: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
this.currentToolBehavior.releaseToolAt( this.currentToolBehavior.releaseToolAt(
spriteCoordinate.col, coords.col, coords.row,
spriteCoordinate.row,
this.getCurrentColor_(), this.getCurrentColor_(),
this this.framesheet.getCurrentFrame(),
this.overlayFrame
); );
$.publish(Events.TOOL_RELEASED); $.publish(Events.TOOL_RELEASED);
// TODO: Remove that when we have the centralized redraw loop
$.publish(Events.REDRAW_PREVIEWFILM);
} }
}, },
@ -176,7 +152,7 @@
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.getSpriteCoordinate = function(event) { ns.DrawingController.prototype.getSpriteCoordinates = function(event) {
var coords = this.getRelativeCoordinates(event.clientX, event.clientY); var coords = this.getRelativeCoordinates(event.clientX, event.clientY);
return this.renderer.convertPixelCoordinatesIntoSpriteCoordinate(coords); return this.renderer.convertPixelCoordinatesIntoSpriteCoordinate(coords);
}; };
@ -219,17 +195,14 @@
}; };
ns.DrawingController.prototype.renderFrame = function () { ns.DrawingController.prototype.renderFrame = function () {
var serializedFrame = this.frame.serialize(); var frame = this.framesheet.getCurrentFrame();
var serializedFrame = frame.serialize();
if (this.serializedFrame != serializedFrame) { if (this.serializedFrame != serializedFrame) {
this.serializedFrame = serializedFrame this.serializedFrame = serializedFrame
this.renderer.render(this.frame); this.renderer.render(frame);
} }
}; };
ns.DrawingController.prototype.renderFramePixel = function (col, row) {
this.renderer.drawPixel(col, row, this.frame);
};
ns.DrawingController.prototype.renderOverlay = function () { ns.DrawingController.prototype.renderOverlay = function () {
var serializedOverlay = this.overlayFrame.serialize(); var serializedOverlay = this.overlayFrame.serialize();
if (this.serializedOverlay != serializedOverlay) { if (this.serializedOverlay != serializedOverlay) {
@ -237,8 +210,4 @@
this.overlayRenderer.render(this.overlayFrame); this.overlayRenderer.render(this.overlayFrame);
} }
}; };
ns.DrawingController.prototype.clearOverlay = function () {
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(this.frame);
};
})(); })();

View File

@ -6,11 +6,10 @@
this.framesheet = framesheet; this.framesheet = framesheet;
this.container = container; this.container = container;
this.dirty = false; this.redrawFlag = false;
$.subscribe(Events.REDRAW_PREVIEWFILM, $.proxy(function(evt) { $.subscribe(Events.TOOL_RELEASED, this.flagForRedraw_.bind(this));
this.dirty = true; $.subscribe(Events.FRAMESHEET_RESET, this.flagForRedraw_.bind(this));
}, this));
}; };
ns.PreviewFilmController.prototype.init = function() { ns.PreviewFilmController.prototype.init = function() {
@ -20,19 +19,29 @@
ns.PreviewFilmController.prototype.addFrame = function () { ns.PreviewFilmController.prototype.addFrame = function () {
this.framesheet.addEmptyFrame(); this.framesheet.addEmptyFrame();
piskel.setActiveFrame(this.framesheet.getFrameCount() - 1); this.framesheet.setCurrentFrameIndex(this.framesheet.getFrameCount() - 1);
};
ns.PreviewFilmController.prototype.flagForRedraw_ = function () {
this.redrawFlag = true;
}; };
ns.PreviewFilmController.prototype.render = function () { ns.PreviewFilmController.prototype.render = function () {
if (!this.dirty) return if (this.redrawFlag) {
// TODO(vincz): Full redraw on any drawing modification, optimize. // TODO(vincz): Full redraw on any drawing modification, optimize.
this.createPreviews_();
this.redrawFlag = false;
}
};
ns.PreviewFilmController.prototype.createPreviews_ = function () {
this.container.html(""); this.container.html("");
var frameCount = this.framesheet.getFrameCount(); var frameCount = this.framesheet.getFrameCount();
for (var i = 0, l = frameCount; i < l ; i++) { for (var i = 0, l = frameCount; i < l ; i++) {
this.container.append(this.createInterstitialTile_(i)); this.container.append(this.createInterstitialTile_(i));
this.container.append(this.createPreviewTile_(i, this.framesheet)); this.container.append(this.createPreviewTile_(i));
} }
this.container.append(this.createInterstitialTile_(frameCount)); this.container.append(this.createInterstitialTile_(frameCount));
@ -40,19 +49,18 @@
if(needDragndropBehavior) { if(needDragndropBehavior) {
this.initDragndropBehavior_(); this.initDragndropBehavior_();
} }
this.dirty = false;
}; };
/** /**
* @private * @private
*/ */
ns.PreviewFilmController.prototype.createInterstitialTile_ = function (tileNumber) { ns.PreviewFilmController.prototype.createInterstitialTile_ = function (tileNumber) {
var initerstitialTile = document.createElement("div"); var interstitialTile = document.createElement("div");
initerstitialTile.className = "interstitial-tile" interstitialTile.className = "interstitial-tile"
initerstitialTile.setAttribute("data-tile-type", "interstitial"); interstitialTile.setAttribute("data-tile-type", "interstitial");
initerstitialTile.setAttribute("data-inject-drop-tile-at", tileNumber); interstitialTile.setAttribute("data-inject-drop-tile-at", tileNumber);
return initerstitialTile; return interstitialTile;
}; };
/** /**
@ -101,8 +109,8 @@
// inside the drag target. We normalize that by taking the correct ancestor: // inside the drag target. We normalize that by taking the correct ancestor:
var originTile = $(event.srcElement).closest(".preview-tile"); var originTile = $(event.srcElement).closest(".preview-tile");
var originFrameId = parseInt(originTile.data("tile-number"), 10); var originFrameId = parseInt(originTile.data("tile-number"), 10);
var dropTarget = $(event.target);
var dropTarget = $(event.target);
if(dropTarget.data("tile-type") == "interstitial") { if(dropTarget.data("tile-type") == "interstitial") {
var targetInsertionId = parseInt(dropTarget.data("inject-drop-tile-at"), 10); var targetInsertionId = parseInt(dropTarget.data("inject-drop-tile-at"), 10);
// In case we drop outside of the tile container // In case we drop outside of the tile container
@ -120,8 +128,7 @@
if(activeFrame > (this.framesheet.getFrameCount() - 1)) { if(activeFrame > (this.framesheet.getFrameCount() - 1)) {
activeFrame = targetInsertionId - 1; activeFrame = targetInsertionId - 1;
} }
} } else {
else {
var targetSwapId = parseInt(dropTarget.data("tile-number"), 10); var targetSwapId = parseInt(dropTarget.data("tile-number"), 10);
// In case we drop outside of the tile container // In case we drop outside of the tile container
if(isNaN(originFrameId) || isNaN(targetSwapId)) { if(isNaN(originFrameId) || isNaN(targetSwapId)) {
@ -135,26 +142,24 @@
$('#preview-list').removeClass("show-interstitial-tiles"); $('#preview-list').removeClass("show-interstitial-tiles");
// TODO(vincz): deprecate. this.framesheet.setCurrentFrameIndex(activeFrame);
piskel.setActiveFrame(activeFrame);
// TODO(vincz): move localstorage request to the model layer? // TODO(vincz): move localstorage request to the model layer?
$.publish(Events.LOCALSTORAGE_REQUEST); $.publish(Events.LOCALSTORAGE_REQUEST);
}; };
/** /**
* @private * @private
* TODO(vincz): clean this giant rendering function & remove listeners. * TODO(vincz): clean this giant rendering function & remove listeners.
*/ */
ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber, framesheet) { ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber) {
var currentFrame = this.framesheet.getFrameByIndex(tileNumber); var currentFrame = this.framesheet.getFrameByIndex(tileNumber);
var previewTileRoot = document.createElement("li"); var previewTileRoot = document.createElement("li");
var classname = "preview-tile"; var classname = "preview-tile";
previewTileRoot.setAttribute("data-tile-number", tileNumber); previewTileRoot.setAttribute("data-tile-number", tileNumber);
if (piskel.getActiveFrameIndex() == tileNumber) { if (this.framesheet.getCurrentFrame() == currentFrame) {
classname += " selected"; classname += " selected";
} }
previewTileRoot.className = classname; previewTileRoot.className = classname;
@ -166,24 +171,13 @@
canvasBackground.className = "canvas-background"; canvasBackground.className = "canvas-background";
canvasContainer.appendChild(canvasBackground); canvasContainer.appendChild(canvasBackground);
previewTileRoot.addEventListener('click', function(evt) { previewTileRoot.addEventListener('click', this.onPreviewClick_.bind(this, tileNumber));
// has not class tile-action:
if(!evt.target.classList.contains('tile-action')) {
piskel.setActiveFrame(tileNumber);
}
});
var canvasPreviewDuplicateAction = document.createElement("button"); var canvasPreviewDuplicateAction = document.createElement("button");
canvasPreviewDuplicateAction.className = "tile-action" canvasPreviewDuplicateAction.className = "tile-action"
canvasPreviewDuplicateAction.innerHTML = "dup" canvasPreviewDuplicateAction.innerHTML = "dup"
canvasPreviewDuplicateAction.addEventListener('click', function(evt) { canvasPreviewDuplicateAction.addEventListener('click', this.onAddButtonClick_.bind(this, tileNumber));
framesheet.duplicateFrameByIndex(tileNumber);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
$.publish('SET_ACTIVE_FRAME', [tileNumber + 1]);
});
//this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview);
// TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim // TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim
// is to make this update function (#createPreviewTile) less aggressive. // is to make this update function (#createPreviewTile) less aggressive.
@ -198,14 +192,29 @@
var canvasPreviewDeleteAction = document.createElement("button"); var canvasPreviewDeleteAction = document.createElement("button");
canvasPreviewDeleteAction.className = "tile-action" canvasPreviewDeleteAction.className = "tile-action"
canvasPreviewDeleteAction.innerHTML = "del" canvasPreviewDeleteAction.innerHTML = "del"
canvasPreviewDeleteAction.addEventListener('click', function(evt) { canvasPreviewDeleteAction.addEventListener('click', this.onDeleteButtonClick_.bind(this, tileNumber));
framesheet.removeFrameByIndex(tileNumber);
$.publish(Events.FRAMESHEET_RESET);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
});
previewTileRoot.appendChild(canvasPreviewDeleteAction); previewTileRoot.appendChild(canvasPreviewDeleteAction);
} }
return previewTileRoot; return previewTileRoot;
}; };
ns.PreviewFilmController.prototype.onPreviewClick_ = function (index, evt) {
// has not class tile-action:
if(!evt.target.classList.contains('tile-action')) {
this.framesheet.setCurrentFrameIndex(index);
}
};
ns.PreviewFilmController.prototype.onDeleteButtonClick_ = function (index, evt) {
this.framesheet.removeFrameByIndex(index);
$.publish(Events.FRAMESHEET_RESET);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
};
ns.PreviewFilmController.prototype.onAddButtonClick_ = function (index, evt) {
this.framesheet.duplicateFrameByIndex(index);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
this.framesheet.setCurrentFrameIndex(index + 1);
};
})(); })();

View File

@ -8,11 +8,11 @@
ns.BaseTool = function() {}; ns.BaseTool = function() {};
ns.BaseTool.prototype.applyToolAt = function(col, row, frame) {}; ns.BaseTool.prototype.applyToolAt = function(col, row, color, frame, overlay) {};
ns.BaseTool.prototype.moveToolAt = function(col, row, frame) {}; ns.BaseTool.prototype.moveToolAt = function(col, row, color, frame, overlay) {};
ns.BaseTool.prototype.releaseToolAt = function(col, row, frame) {}; ns.BaseTool.prototype.releaseToolAt = function(col, row, color, frame, overlay) {};
/** /**
* Bresenham line algorihtm: Get an array of pixels from * Bresenham line algorihtm: Get an array of pixels from

View File

@ -16,7 +16,7 @@
/** /**
* @override * @override
*/ */
ns.Eraser.prototype.applyToolAt = function(col, row, color, drawer) { ns.Eraser.prototype.applyToolAt = function(col, row, color, frame, overlay) {
this.superclass.applyToolAt.call(this, col, row, Constants.TRANSPARENT_COLOR, drawer); this.superclass.applyToolAt.call(this, col, row, Constants.TRANSPARENT_COLOR, frame, overlay);
}; };
})(); })();

View File

@ -19,16 +19,16 @@
/** /**
* @override * @override
*/ */
ns.Move.prototype.applyToolAt = function(col, row, color, drawer) { ns.Move.prototype.applyToolAt = function(col, row, color, frame, overlay) {
this.startCol = col; this.startCol = col;
this.startRow = row; this.startRow = row;
this.frameClone = drawer.frame.clone(); this.frameClone = frame.clone();
}; };
ns.Move.prototype.moveToolAt = function(col, row, color, drawer) { ns.Move.prototype.moveToolAt = function(col, row, color, frame, overlay) {
var colDiff = col - this.startCol, rowDiff = row - this.startRow; var colDiff = col - this.startCol, rowDiff = row - this.startRow;
if (colDiff != 0 || rowDiff != 0) { if (colDiff != 0 || rowDiff != 0) {
this.shiftFrame(colDiff, rowDiff, drawer.frame, this.frameClone); this.shiftFrame(colDiff, rowDiff, frame, this.frameClone);
} }
}; };
@ -49,7 +49,7 @@
/** /**
* @override * @override
*/ */
ns.Move.prototype.releaseToolAt = function(col, row, color, drawer) { ns.Move.prototype.releaseToolAt = function(col, row, color, frame, overlay) {
this.moveToolAt(col, row, color, drawer); this.moveToolAt(col, row, color, frame, overlay);
}; };
})(); })();

View File

@ -15,12 +15,11 @@
/** /**
* @override * @override
*/ */
ns.PaintBucket.prototype.applyToolAt = function(col, row, color, drawer) { ns.PaintBucket.prototype.applyToolAt = function(col, row, color, frame, overlay) {
// Change model: // Change model:
var targetColor = drawer.frame.getPixel(col, row); var targetColor = frame.getPixel(col, row);
//this.recursiveFloodFill_(frame, col, row, targetColor, color); this.queueLinearFloodFill_(frame, col, row, targetColor, color);
this.queueLinearFloodFill_(drawer.frame, col, row, targetColor, color);
}; };
/** /**

View File

@ -19,17 +19,16 @@
/** /**
* @override * @override
*/ */
ns.Rectangle.prototype.applyToolAt = function(col, row, color, drawer) { ns.Rectangle.prototype.applyToolAt = function(col, row, color, frame, overlay) {
this.startCol = col; this.startCol = col;
this.startRow = row; this.startRow = row;
// Drawing the first point of the rectangle in the fake overlay canvas: // Drawing the first point of the rectangle in the fake overlay canvas:
drawer.overlayFrame.setPixel(col, row, color); overlay.setPixel(col, row, color);
}; };
ns.Rectangle.prototype.moveToolAt = function(col, row, color, drawer) { ns.Rectangle.prototype.moveToolAt = function(col, row, color, frame, overlay) {
// Clean overlay canvas: overlay.clear();
drawer.clearOverlay();
// When the user moussemove (before releasing), we dynamically compute the // When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay : // pixel to draw the line and draw this line in the overlay :
@ -41,21 +40,21 @@
if(color == Constants.TRANSPARENT_COLOR) { if(color == Constants.TRANSPARENT_COLOR) {
color = Constants.SELECTION_TRANSPARENT_COLOR; color = Constants.SELECTION_TRANSPARENT_COLOR;
} }
drawer.overlayFrame.setPixel(strokePoints[i].col, strokePoints[i].row, color); overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
}; };
/** /**
* @override * @override
*/ */
ns.Rectangle.prototype.releaseToolAt = function(col, row, color, drawer) { ns.Rectangle.prototype.releaseToolAt = function(col, row, color, frame, overlay) {
drawer.clearOverlay(); overlay.clear();
// If the stroke tool is released outside of the canvas, we cancel the stroke: // If the stroke tool is released outside of the canvas, we cancel the stroke:
if(drawer.frame.containsPixel(col, row)) { if(frame.containsPixel(col, row)) {
var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row); var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row);
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
// Change model: // Change model:
drawer.frame.setPixel(strokePoints[i].col, strokePoints[i].row, color); frame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
// The user released the tool to draw a line. We will compute the pixel coordinate, impact // The user released the tool to draw a line. We will compute the pixel coordinate, impact
// the model and draw them in the drawing canvas (not the fake overlay anymore) // the model and draw them in the drawing canvas (not the fake overlay anymore)

View File

@ -18,27 +18,27 @@
/** /**
* @override * @override
*/ */
ns.SimplePen.prototype.applyToolAt = function(col, row, color, drawer) { ns.SimplePen.prototype.applyToolAt = function(col, row, color, frame, overlay) {
if (drawer.frame.containsPixel(col, row)) { if (frame.containsPixel(col, row)) {
this.previousCol = col; this.previousCol = col;
this.previousRow = row; this.previousRow = row;
drawer.frame.setPixel(col, row, color); frame.setPixel(col, row, color);
} }
}; };
ns.SimplePen.prototype.moveToolAt = function(col, row, color, drawer) { ns.SimplePen.prototype.moveToolAt = function(col, row, color, frame, overlay) {
if((Math.abs(col - this.previousCol) > 1) || (Math.abs(row - this.previousRow) > 1)) { if((Math.abs(col - this.previousCol) > 1) || (Math.abs(row - this.previousRow) > 1)) {
// The pen movement is too fast for the mousemove frequency, there is a gap between the // The pen movement is too fast for the mousemove frequency, there is a gap between the
// current point and the previously drawn one. // current point and the previously drawn one.
// We fill the gap by calculating missing dots (simple linear interpolation) and draw them. // We fill the gap by calculating missing dots (simple linear interpolation) and draw them.
var interpolatedPixels = this.getLinePixels_(col, this.previousCol, row, this.previousRow); var interpolatedPixels = this.getLinePixels_(col, this.previousCol, row, this.previousRow);
for(var i=0, l=interpolatedPixels.length; i<l; i++) { for(var i=0, l=interpolatedPixels.length; i<l; i++) {
this.applyToolAt(interpolatedPixels[i].col, interpolatedPixels[i].row, color, drawer); var coords = interpolatedPixels[i];
this.applyToolAt(coords.col, coords.row, color, frame, overlay);
} }
} }
else { else {
this.applyToolAt(col, row, color, drawer); this.applyToolAt(col, row, color, frame, overlay);
} }
this.previousCol = col; this.previousCol = col;

View File

@ -12,8 +12,6 @@
// Stroke's first point coordinates (set in applyToolAt) // Stroke's first point coordinates (set in applyToolAt)
this.startCol = null; this.startCol = null;
this.startRow = null; this.startRow = null;
this.canvasOverlay = null;
}; };
pskl.utils.inherit(ns.Stroke, ns.BaseTool); pskl.utils.inherit(ns.Stroke, ns.BaseTool);
@ -21,7 +19,7 @@
/** /**
* @override * @override
*/ */
ns.Stroke.prototype.applyToolAt = function(col, row, color, drawer) { ns.Stroke.prototype.applyToolAt = function(col, row, color, frame, overlay) {
this.startCol = col; this.startCol = col;
this.startRow = row; this.startRow = row;
@ -34,11 +32,11 @@
// The fake canvas where we will draw the preview of the stroke: // The fake canvas where we will draw the preview of the stroke:
// Drawing the first point of the stroke in the fake overlay canvas: // Drawing the first point of the stroke in the fake overlay canvas:
drawer.overlayFrame.setPixel(col, row, color); overlay.setPixel(col, row, color);
}; };
ns.Stroke.prototype.moveToolAt = function(col, row, color, drawer) { ns.Stroke.prototype.moveToolAt = function(col, row, color, frame, overlay) {
drawer.clearOverlay(); overlay.clear();
// When the user moussemove (before releasing), we dynamically compute the // When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay canvas: // pixel to draw the line and draw this line in the overlay canvas:
@ -56,28 +54,26 @@
// eg deleting the equivalent of a stroke. // eg deleting the equivalent of a stroke.
color = Constants.SELECTION_TRANSPARENT_COLOR; color = Constants.SELECTION_TRANSPARENT_COLOR;
} }
drawer.overlayFrame.setPixel(strokePoints[i].col, strokePoints[i].row, color); overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
}; };
/** /**
* @override * @override
*/ */
ns.Stroke.prototype.releaseToolAt = function(col, row, color, drawer) { ns.Stroke.prototype.releaseToolAt = function(col, row, color, frame, overlay) {
// If the stroke tool is released outside of the canvas, we cancel the stroke: // If the stroke tool is released outside of the canvas, we cancel the stroke:
// TODO: Mutualize this check in common method // TODO: Mutualize this check in common method
if(drawer.frame.containsPixel(col, row)) { if(frame.containsPixel(col, row)) {
// The user released the tool to draw a line. We will compute the pixel coordinate, impact // The user released the tool to draw a line. We will compute the pixel coordinate, impact
// the model and draw them in the drawing canvas (not the fake overlay anymore) // the model and draw them in the drawing canvas (not the fake overlay anymore)
var strokePoints = this.getLinePixels_(this.startCol, col, this.startRow, row); var strokePoints = this.getLinePixels_(this.startCol, col, this.startRow, row);
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
// Change model: // Change model:
drawer.frame.setPixel(strokePoints[i].col, strokePoints[i].row, color); frame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
// Draw in canvas:
// TODO: Remove that when we have the centralized redraw loop
} }
// For now, we are done with the stroke tool and don't need an overlay anymore: // For now, we are done with the stroke tool and don't need an overlay anymore:
drawer.clearOverlay(); overlay.clear();
}; };
})(); })();

View File

@ -8,6 +8,11 @@
}; };
ns.Frame.createEmpty = function (width, height) { ns.Frame.createEmpty = function (width, height) {
var pixels = ns.Frame.createEmptyPixelGrid_(width, height);
return new ns.Frame(pixels);
};
ns.Frame.createEmptyPixelGrid_ = function (width, height) {
var pixels = []; //new Array(width); var pixels = []; //new Array(width);
for (var columnIndex=0; columnIndex < width; columnIndex++) { for (var columnIndex=0; columnIndex < width; columnIndex++) {
var columnArray = []; var columnArray = [];
@ -16,7 +21,7 @@
} }
pixels[columnIndex] = columnArray; pixels[columnIndex] = columnArray;
} }
return new ns.Frame(pixels); return pixels;
}; };
ns.Frame.createEmptyFromFrame = function (frame) { ns.Frame.createEmptyFromFrame = function (frame) {
@ -41,6 +46,13 @@
this.pixels = this.clonePixels_(pixels); this.pixels = this.clonePixels_(pixels);
}; };
ns.Frame.prototype.clear = function () {
var pixels = ns.Frame.createEmptyPixelGrid_(this.getWidth(), this.getHeight());
this.setPixels(pixels);
};
/** /**
* Clone a set of pixels. Should be static utility method * Clone a set of pixels. Should be static utility method
* @private * @private

View File

@ -4,10 +4,7 @@
this.width = width; this.width = width;
this.height = height; this.height = height;
this.frames = []; this.frames = [];
}; this.currentFrameIndex = 0;
ns.FrameSheet.prototype.validate = function () {
throw "FrameSheet.prototype.validate not implemented"
}; };
ns.FrameSheet.prototype.addEmptyFrame = function () { ns.FrameSheet.prototype.addEmptyFrame = function () {
@ -22,6 +19,15 @@
return this.frames.length; return this.frames.length;
}; };
ns.FrameSheet.prototype.getCurrentFrame = function () {
return this.frames[this.currentFrameIndex];
};
ns.FrameSheet.prototype.setCurrentFrameIndex = function (index) {
this.currentFrameIndex = index;
$.publish(Events.FRAMESHEET_RESET);
};
ns.FrameSheet.prototype.getUsedColors = function() { ns.FrameSheet.prototype.getUsedColors = function() {
var colors = {}; var colors = {};
for (var frameIndex=0; frameIndex < this.frames.length; frameIndex++) { for (var frameIndex=0; frameIndex < this.frames.length; frameIndex++) {

View File

@ -22,10 +22,7 @@ $.namespace("pskl");
// Canvas preview film canvases: // Canvas preview film canvases:
previewTileCanvasDpi = 4, previewTileCanvasDpi = 4,
// Animated canvas preview: // Animated canvas preview:
previewAnimationCanvasDpi = 8, previewAnimationCanvasDpi = 8;
activeFrameIndex = -1,
currentFrame = null;
/** /**
* Main application controller * Main application controller
@ -33,21 +30,17 @@ $.namespace("pskl");
var piskel = { var piskel = {
init : function () { init : function () {
piskel.initDPIs_(); piskel.initDPIs_();
frameSheet = new pskl.model.FrameSheet(framePixelWidth, framePixelHeight); frameSheet = new pskl.model.FrameSheet(framePixelWidth, framePixelHeight);
frameSheet.addEmptyFrame(); frameSheet.addEmptyFrame();
this.drawingController = new pskl.controller.DrawingController( this.drawingController = new pskl.controller.DrawingController(
frameSheet.getFrameByIndex(0), frameSheet,
$('#drawing-canvas-container'), $('#drawing-canvas-container'),
drawingCanvasDpi drawingCanvasDpi
); );
this.setActiveFrame(0);
this.animationController = new pskl.controller.AnimatedPreviewController( this.animationController = new pskl.controller.AnimatedPreviewController(
frameSheet, frameSheet,
$('#preview-canvas-container'), $('#preview-canvas-container'),
@ -64,7 +57,9 @@ $.namespace("pskl");
this.animationController.init(); this.animationController.init();
this.previewsController.init(); this.previewsController.init();
pskl.HistoryManager.init(); this.historyManager = new pskl.HistoryManager(frameSheet);
this.historyManager.init();
pskl.NotificationService.init(); pskl.NotificationService.init();
pskl.LocalStorageService.init(frameSheet); pskl.LocalStorageService.init(frameSheet);
@ -79,12 +74,9 @@ $.namespace("pskl");
} }
$.subscribe('SET_ACTIVE_FRAME', function(evt, frameId) { $.subscribe('SET_ACTIVE_FRAME', function(evt, frameId) {
piskel.setActiveFrame(frameId); frameSheet.setCurrentFrameIndex(frameId);
}); });
$.subscribe('FRAMESHEET_RESET', function(evt, frameId) {
piskel.render();
});
var drawingLoop = new pskl.rendering.DrawingLoop(); var drawingLoop = new pskl.rendering.DrawingLoop();
drawingLoop.addCallback(this.render, this); drawingLoop.addCallback(this.render, this);
drawingLoop.start(); drawingLoop.start();
@ -101,7 +93,6 @@ $.namespace("pskl");
* @private * @private
*/ */
initDPIs_ : function() { initDPIs_ : function() {
drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_(); drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_();
// TODO(vincz): Add throttling on window.resize event. // TODO(vincz): Add throttling on window.resize event.
$(window).resize($.proxy(function() { $(window).resize($.proxy(function() {
@ -144,13 +135,6 @@ $.namespace("pskl");
}, },
finishInit : function () { finishInit : function () {
$.subscribe(Events.REFRESH, function() {
piskel.setActiveFrame(0);
});
pskl.ToolSelector.init(); pskl.ToolSelector.init();
pskl.Palette.init(frameSheet); pskl.Palette.init(frameSheet);
}, },
@ -171,7 +155,6 @@ $.namespace("pskl");
xhr.onload = function(e) { xhr.onload = function(e) {
frameSheet.deserialize(this.responseText); frameSheet.deserialize(this.responseText);
piskel.setActiveFrame(0);
$.publish(Events.HIDE_NOTIFICATION); $.publish(Events.HIDE_NOTIFICATION);
piskel.finishInit(); piskel.finishInit();
}; };
@ -179,27 +162,11 @@ $.namespace("pskl");
xhr.onerror = function () { xhr.onerror = function () {
$.publish(Events.HIDE_NOTIFICATION); $.publish(Events.HIDE_NOTIFICATION);
piskel.finishInit(); piskel.finishInit();
piskel.setActiveFrame(0);
}; };
xhr.send(); xhr.send();
}, },
setActiveFrame: function(index) {
activeFrameIndex = index;
this.drawingController.frame = this.getCurrentFrame();
},
getActiveFrameIndex: function() {
if(-1 == activeFrameIndex) {
throw "Bad active frame initialization."
}
return activeFrameIndex;
},
getCurrentFrame : function () {
return frameSheet.getFrameByIndex(activeFrameIndex);
},
// TODO(julz): Create package ? // TODO(julz): Create package ?
storeSheet : function (event) { storeSheet : function (event) {
// TODO Refactor using jquery ? // TODO Refactor using jquery ?

View File

@ -16,7 +16,7 @@ jQuery.namespace = function() {
* *
* @require Constants * @require Constants
*/ */
(function(ns) { // namespace: pskl.utils (function() { // namespace: pskl.utils
var ns = $.namespace("pskl.utils"); var ns = $.namespace("pskl.utils");
@ -35,5 +35,5 @@ jQuery.namespace = function() {
//prototypeskl.ToolBehavior.Eraser.prototype.constructor = pskl.ToolBehavior.Eraser; //prototypeskl.ToolBehavior.Eraser.prototype.constructor = pskl.ToolBehavior.Eraser;
}; };
})() })();

15
package.json Normal file
View File

@ -0,0 +1,15 @@
{
"author": "People",
"name": "piskel",
"description": "Web based 2d animations editor",
"version": "0.0.1",
"homepage": "http://github.com/juliandescottes/piskel",
"repository": {
"type": "git",
"url": "http://github.com/juliandescottes/piskel.git"
},
"scripts": { "test": "make test" },
"devDependencies": {
"jshint": "0.6.1"
}
}