-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPixelEngine.hx
More file actions
655 lines (605 loc) · 25.4 KB
/
PixelEngine.hx
File metadata and controls
655 lines (605 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
package;
import js.Browser;
import js.html.CanvasElement;
import js.html.CanvasRenderingContext2D;
import js.html.MouseEvent;
import js.html.HTMLInputElement;
import js.html.HTMLAnchorElement;
import js.html.FileReader;
/**
* PixelEngine.hx
* - Change をクラスに置き換え(typedef 削除)
* - PNG エクスポートに加え、プロジェクト(JSON)をダウンロード/読み込みする機能を追加
* - Main.hx から new PixelEngine(w,h) で起動
*/
class PixelEngine {
// Change クラス(typedef の代替)
private class Change {
public var idx:Int;
public var oldC:UInt;
public var newC:UInt;
public function new(i:Int, o:UInt, n:UInt) {
idx = i; oldC = o; newC = n;
}
}
private class PixelBuffer {
public var width:Int;
public var height:Int;
public var data:Array<UInt>;
public function new(w:Int, h:Int) {
width = w; height = h;
data = [];
var n = w * h;
for (i in 0...n) data.push(0x00000000);
}
public inline function get(x:Int, y:Int):UInt return data[y * width + x];
public inline function set(x:Int, y:Int, c:UInt):Void data[y * width + x] = c;
public function clear(c:UInt):Void for (i in 0...data.length) data[i] = c;
}
private class Layer {
public var name:String;
public var buffer:PixelBuffer;
public var visible:Bool = true;
public var opacity:Float = 1.0;
public function new(w:Int, h:Int, n:String) {
name = n; buffer = new PixelBuffer(w, h);
}
}
private class Frame {
public var layers:Array<Layer> = [];
public function new(w:Int, h:Int) {
layers.push(new Layer(w, h, "Layer 0"));
}
}
private class HistoryEntry {
public var layerIdx:Int;
public var frameIdx:Int;
public var changes:Array<Change>;
public function new(l:Int, f:Int) {
layerIdx = l; frameIdx = f; changes = [];
}
}
// public state
public var width:Int;
public var height:Int;
public var frames:Array<Frame> = [];
public var currentFrame:Int = 0;
public var currentLayer:Int = 0;
public var primaryColor:UInt = 0xFF000000; // ARGB
public var scale:Int = 16;
public var showGrid:Bool = true;
// UI / rendering
private var canvas:CanvasElement;
private var ctx:CanvasRenderingContext2D;
private var previewCanvas:CanvasElement;
private var previewCtx:CanvasRenderingContext2D;
private var paletteDiv:Dynamic;
private var layersDiv:Dynamic;
// input / tool state
private var drawing:Bool = false;
private var lastX:Int = -1;
private var lastY:Int = -1;
private var activeHistory:HistoryEntry = null;
private var undoStack:Array<HistoryEntry> = [];
private var redoStack:Array<HistoryEntry> = [];
private var tool:String = "pen"; // pen, eraser, fill, line, rect
private var lineStart:Null<{x:Int,y:Int}> = null;
private var rectStart:Null<{x:Int,y:Int}> = null;
// palette
private var palette:Array<UInt> = [
0xFF000000,0xFFFFFFFF,0xFFFF0000,0xFF00FF00,0xFF0000FF,
0xFFFFFF00,0xFFFF00FF,0xFF00FFFF,0xFF7F7F7F,0xFFB5651D
];
public function new(w:Int, h:Int) {
width = w; height = h;
frames = []; frames.push(new Frame(w, h));
// root UI container(既存の canvas があれば利用)
var existing = Browser.document.getElementById("pixel-editor-root");
var root = if (existing != null) cast existing else {
var r = Browser.document.createElement("div");
r.id = "pixel-editor-root";
r.style.cssText = "display:flex;gap:12px;font-family:Arial,Helvetica,sans-serif;color:#eee";
Browser.document.body.appendChild(r);
r;
};
// left column
var left = Browser.document.createElement("div");
left.style.cssText = "display:flex;flex-direction:column;gap:8px";
root.appendChild(left);
// canvas
var c = Browser.document.getElementById("screen");
if (c == null) {
canvas = cast Browser.document.createElement("canvas");
canvas.id = "screen";
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.cssText = "border:1px solid #444; image-rendering: pixelated; background:#222";
left.appendChild(canvas);
} else {
canvas = cast c;
canvas.width = width * scale;
canvas.height = height * scale;
}
ctx = canvas.getContext2d();
// controls
var controls = Browser.document.createElement("div");
controls.style.cssText = "display:flex;gap:6px;align-items:center";
left.appendChild(controls);
controls.appendChild(makeButton("Pen","pen"));
controls.appendChild(makeButton("Eraser","eraser"));
controls.appendChild(makeButton("Fill","fill"));
controls.appendChild(makeButton("Line","line"));
controls.appendChild(makeButton("Rect","rect"));
var gridBtn = makeButton("Grid","grid");
gridBtn.onclick = _ -> { showGrid = !showGrid; render(); };
controls.appendChild(gridBtn);
var zoomIn = Browser.document.createElement("button");
zoomIn.innerText = "+";
zoomIn.onclick = _ -> { scale = Math.min(64, scale + 4); resizeCanvas(); render(); };
controls.appendChild(zoomIn);
var zoomOut = Browser.document.createElement("button");
zoomOut.innerText = "-";
zoomOut.onclick = _ -> { scale = Math.max(2, scale - 4); resizeCanvas(); render(); };
controls.appendChild(zoomOut);
var exportBtn = Browser.document.createElement("button");
exportBtn.innerText = "Export PNG";
exportBtn.onclick = _ -> exportPNG();
controls.appendChild(exportBtn);
// Save / Load project buttons
var saveBtn = Browser.document.createElement("button");
saveBtn.innerText = "Save Project";
saveBtn.onclick = _ -> saveProject();
controls.appendChild(saveBtn);
var loadInput = cast Browser.document.createElement("input");
loadInput.type = "file";
loadInput.accept = ".json";
loadInput.onchange = e -> {
var fi = cast e.target : HTMLInputElement;
if (fi.files != null && fi.files.length > 0) {
var f = fi.files.item(0);
loadProjectFile(f);
}
};
controls.appendChild(loadInput);
// right column
var right = Browser.document.createElement("div");
right.style.cssText = "display:flex;flex-direction:column;gap:8px;width:220px";
root.appendChild(right);
// palette
var palWrap = Browser.document.createElement("div");
palWrap.style.cssText = "background:#111;padding:8px;border-radius:6px;border:1px solid #333";
right.appendChild(palWrap);
var palTitle = Browser.document.createElement("div");
palTitle.innerText = "Palette";
palTitle.style.cssText = "font-weight:bold;margin-bottom:6px";
palWrap.appendChild(palTitle);
paletteDiv = Browser.document.createElement("div");
paletteDiv.style.cssText = "display:flex;flex-wrap:wrap;gap:6px";
palWrap.appendChild(paletteDiv);
buildPaletteUI();
// layers
var layersWrap = Browser.document.createElement("div");
layersWrap.style.cssText = "background:#111;padding:8px;border-radius:6px;border:1px solid #333";
right.appendChild(layersWrap);
var layersTitle = Browser.document.createElement("div");
layersTitle.innerText = "Layers";
layersTitle.style.cssText = "font-weight:bold;margin-bottom:6px";
layersWrap.appendChild(layersTitle);
layersDiv = Browser.document.createElement("div");
layersDiv.style.cssText = "display:flex;flex-direction:column;gap:6px";
layersWrap.appendChild(layersDiv);
buildLayersUI();
// preview
var previewWrap = Browser.document.createElement("div");
previewWrap.style.cssText = "background:#111;padding:8px;border-radius:6px;border:1px solid #333";
right.appendChild(previewWrap);
var previewTitle = Browser.document.createElement("div");
previewTitle.innerText = "Preview";
previewTitle.style.cssText = "font-weight:bold;margin-bottom:6px";
previewWrap.appendChild(previewTitle);
previewCanvas = cast Browser.document.createElement("canvas");
previewCanvas.width = width;
previewCanvas.height = height;
previewCanvas.style.cssText = "width:100%;border:1px solid #222;image-rendering:pixelated";
previewWrap.appendChild(previewCanvas);
previewCtx = previewCanvas.getContext2d();
// input & shortcuts
setupInput();
setupShortcuts();
// initial render
render();
updatePreview();
}
// UI helpers
private function makeButton(label:String, id:String) {
var b = Browser.document.createElement("button");
b.innerText = label;
b.id = "btn-" + id;
b.onclick = _ -> {
switch (id) {
case "pen": tool = "pen";
case "eraser": tool = "eraser";
case "fill": tool = "fill";
case "line": tool = "line";
case "rect": tool = "rect";
case "grid": /* handled elsewhere */;
}
};
return b;
}
private function buildPaletteUI():Void {
paletteDiv.innerHTML = "";
for (i in 0...palette.length) {
var c = palette[i];
var sw = Browser.document.createElement("div");
sw.style.cssText = "width:28px;height:20px;border:1px solid #222;cursor:pointer";
sw.style.background = colorToCss(c);
sw.onclick = _ -> { primaryColor = c; };
paletteDiv.appendChild(sw);
}
var input = cast Browser.document.createElement("input");
input.type = "color";
input.onchange = e -> {
var v = (cast e.target : HTMLInputElement).value;
var c = hexToUInt(v);
primaryColor = c;
palette.unshift(c);
if (palette.length > 32) palette.pop();
buildPaletteUI();
};
paletteDiv.appendChild(input);
}
private function buildLayersUI():Void {
layersDiv.innerHTML = "";
var layerList = frames[currentFrame].layers;
for (i in 0...layerList.length) {
var L = layerList[i];
var row = Browser.document.createElement("div");
row.style.cssText = "display:flex;align-items:center;gap:6px";
var vis = Browser.document.createElement("input");
vis.type = "checkbox";
vis.checked = L.visible;
vis.onchange = _ -> { L.visible = vis.checked; render(); updatePreview(); };
row.appendChild(vis);
var lbl = Browser.document.createElement("span");
lbl.innerText = L.name;
lbl.style.cssText = "flex:1";
row.appendChild(lbl);
var sel = Browser.document.createElement("button");
sel.innerText = "Select";
sel.onclick = _ -> { currentLayer = i; render(); };
row.appendChild(sel);
var del = Browser.document.createElement("button");
del.innerText = "Del";
del.onclick = _ -> {
if (layerList.length <= 1) return;
layerList.splice(i,1);
if (currentLayer >= layerList.length) currentLayer = layerList.length - 1;
buildLayersUI(); render(); updatePreview();
};
row.appendChild(del);
layersDiv.appendChild(row);
}
var add = Browser.document.createElement("button");
add.innerText = "Add Layer";
add.onclick = _ -> {
frames[currentFrame].layers.push(new Layer(width, height, "Layer " + frames[currentFrame].layers.length));
buildLayersUI(); render(); updatePreview();
};
layersDiv.appendChild(add);
}
// Input / tools
private function setupInput():Void {
canvas.onmousedown = (e:MouseEvent) -> {
var p = eventToPixel(e);
drawing = true;
lastX = p.x; lastY = p.y;
activeHistory = new HistoryEntry(currentLayer, currentFrame);
switch (tool) {
case "pen": applyPen(p.x, p.y);
case "eraser": applyEraser(p.x, p.y);
case "fill": applyFill(p.x, p.y); endStroke();
case "line": lineStart = { x: p.x, y: p.y };
case "rect": rectStart = { x: p.x, y: p.y };
}
render(); updatePreview();
};
canvas.onmousemove = (e:MouseEvent) -> {
if (!drawing) return;
var p = eventToPixel(e);
switch (tool) {
case "pen": drawLine(lastX, lastY, p.x, p.y);
case "eraser": drawLine(lastX, lastY, p.x, p.y, true);
case "line": render(); drawPreviewLine(lineStart.x, lineStart.y, p.x, p.y);
case "rect": render(); drawPreviewRect(rectStart.x, rectStart.y, p.x, p.y);
}
lastX = p.x; lastY = p.y;
updatePreview();
};
Browser.window.onmouseup = (_) -> {
if (!drawing) return;
if (tool == "line") {
var p = { x: lastX, y: lastY };
if (lineStart != null) { applyLine(lineStart.x, lineStart.y, p.x, p.y); lineStart = null; }
}
if (tool == "rect") {
var p2 = { x: lastX, y: lastY };
if (rectStart != null) { applyRect(rectStart.x, rectStart.y, p2.x, p2.y); rectStart = null; }
}
endStroke();
drawing = false;
render(); updatePreview();
};
}
private function eventToPixel(e:MouseEvent):{x:Int,y:Int} {
var rect = canvas.getBoundingClientRect();
var x = Std.int((e.clientX - rect.left) / scale);
var y = Std.int((e.clientY - rect.top) / scale);
x = Math.max(0, Math.min(width - 1, x));
y = Math.max(0, Math.min(height - 1, y));
return { x: x, y: y };
}
private function startStroke():Void { activeHistory = new HistoryEntry(currentLayer, currentFrame); }
private function endStroke():Void {
if (activeHistory != null && activeHistory.changes.length > 0) {
undoStack.push(activeHistory);
if (undoStack.length > 100) undoStack.shift();
redoStack = [];
}
activeHistory = null; lastX = -1; lastY = -1;
}
private function recordChange(idx:Int, oldC:UInt, newC:UInt):Void {
if (activeHistory == null) activeHistory = new HistoryEntry(currentLayer, currentFrame);
for (c in activeHistory.changes) if (c.idx == idx) return;
activeHistory.changes.push(new Change(idx, oldC, newC));
}
// Tools
private function applyPen(x:Int, y:Int):Void {
var L = frames[currentFrame].layers[currentLayer];
var idx = y * width + x;
var oldC = L.buffer.data[idx];
var newC = primaryColor;
if (oldC != newC) { L.buffer.data[idx] = newC; recordChange(idx, oldC, newC); }
}
private function applyEraser(x:Int, y:Int):Void {
var L = frames[currentFrame].layers[currentLayer];
var idx = y * width + x;
var oldC = L.buffer.data[idx];
var newC = 0x00000000;
if (oldC != newC) { L.buffer.data[idx] = newC; recordChange(idx, oldC, newC); }
}
private function applyFill(x:Int, y:Int):Void {
var L = frames[currentFrame].layers[currentLayer];
var target = L.buffer.get(x, y);
var fill = (tool == "eraser") ? 0x00000000 : primaryColor;
if (target == fill) return;
startStroke();
var q = [{ x: x, y: y }];
while (q.length > 0) {
var p = q.shift();
if (p.x < 0 || p.x >= width || p.y < 0 || p.y >= height) continue;
if (L.buffer.get(p.x, p.y) == target) {
var idx = p.y * width + p.x;
var oldC = L.buffer.data[idx];
L.buffer.data[idx] = fill;
recordChange(idx, oldC, fill);
q.push({ x: p.x + 1, y: p.y });
q.push({ x: p.x - 1, y: p.y });
q.push({ x: p.x, y: p.y + 1 });
q.push({ x: p.x, y: p.y - 1 });
}
}
endStroke();
}
private function drawLine(x0:Int, y0:Int, x1:Int, y1:Int, eraser:Bool = false):Void {
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
var sx = x0 < x1 ? 1 : -1;
var sy = y0 < y1 ? 1 : -1;
var err = dx - dy;
var x = x0; var y = y0;
while (true) {
if (eraser) applyEraser(x, y); else applyPen(x, y);
if (x == x1 && y == y1) break;
var e2 = 2 * err;
if (e2 > -dy) { err -= dy; x += sx; }
if (e2 < dx) { err += dx; y += sy; }
}
}
private function applyLine(x0:Int, y0:Int, x1:Int, y1:Int):Void { startStroke(); drawLine(x0,y0,x1,y1, tool=="eraser"); endStroke(); }
private function applyRect(x0:Int, y0:Int, x1:Int, y1:Int):Void {
startStroke();
var left = Math.min(x0, x1);
var right = Math.max(x0, x1);
var top = Math.min(y0, y1);
var bottom = Math.max(y0, y1);
for (x in left...right+1) { applyPen(x, top); applyPen(x, bottom); }
for (y in top...bottom+1) { applyPen(left, y); applyPen(right, y); }
endStroke();
}
private function drawPreviewLine(x0:Int, y0:Int, x1:Int, y1:Int):Void {
ctx.save();
ctx.strokeStyle = "#fff"; ctx.lineWidth = 1; ctx.setLineDash([4,2]);
ctx.beginPath(); ctx.moveTo(x0 * scale + 0.5, y0 * scale + 0.5); ctx.lineTo(x1 * scale + 0.5, y1 * scale + 0.5); ctx.stroke();
ctx.restore();
}
private function drawPreviewRect(x0:Int, y0:Int, x1:Int, y1:Int):Void {
var left = Math.min(x0, x1); var top = Math.min(y0, y1);
var w = Math.abs(x1 - x0) + 1; var h = Math.abs(y1 - y0) + 1;
ctx.save(); ctx.strokeStyle = "#fff"; ctx.setLineDash([4,2]); ctx.strokeRect(left * scale + 0.5, top * scale + 0.5, w * scale, h * scale); ctx.restore();
}
// Undo / Redo
public function undo():Void {
if (undoStack.length == 0) return;
var h = undoStack.pop();
var buf = frames[h.frameIdx].layers[h.layerIdx].buffer;
for (c in h.changes) buf.data[c.idx] = c.oldC;
redoStack.push(h);
render(); updatePreview();
}
public function redo():Void {
if (redoStack.length == 0) return;
var h = redoStack.pop();
var buf = frames[h.frameIdx].layers[h.layerIdx].buffer;
for (c in h.changes) buf.data[c.idx] = c.newC;
undoStack.push(h);
render(); updatePreview();
}
// Rendering
private function resizeCanvas():Void { canvas.width = width * scale; canvas.height = height * scale; }
public function render():Void {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.imageSmoothingEnabled = false;
for (ly in 0...frames[currentFrame].layers.length) {
var L = frames[currentFrame].layers[ly];
if (!L.visible) continue;
for (y in 0...height) for (x in 0...width) {
var c = L.buffer.get(x,y);
var a = (c >>> 24) & 0xFF;
var r = (c >> 16) & 0xFF;
var g = (c >> 8) & 0xFF;
var b = c & 0xFF;
if (a == 0) continue;
ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
ctx.fillRect(x * scale, y * scale, scale, scale);
}
}
if (showGrid) {
ctx.save();
ctx.strokeStyle = "rgba(255,255,255,0.06)"; ctx.lineWidth = 1;
for (i in 0...width+1) { ctx.beginPath(); ctx.moveTo(i * scale + 0.5, 0); ctx.lineTo(i * scale + 0.5, height * scale); ctx.stroke(); }
for (j in 0...height+1) { ctx.beginPath(); ctx.moveTo(0, j * scale + 0.5); ctx.lineTo(width * scale, j * scale + 0.5); ctx.stroke(); }
ctx.restore();
}
}
private function updatePreview():Void {
previewCtx.clearRect(0,0,previewCanvas.width, previewCanvas.height);
previewCtx.imageSmoothingEnabled = false;
for (ly in 0...frames[currentFrame].layers.length) {
var L = frames[currentFrame].layers[ly];
if (!L.visible) continue;
for (y in 0...height) for (x in 0...width) {
var c = L.buffer.get(x,y);
var a = (c >>> 24) & 0xFF;
var r = (c >> 16) & 0xFF;
var g = (c >> 8) & 0xFF;
var b = c & 0xFF;
if (a == 0) continue;
previewCtx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
previewCtx.fillRect(x, y, 1, 1);
}
}
}
// Export PNG
private function exportPNG():Void {
var off = cast Browser.document.createElement("canvas");
off.width = width; off.height = height;
var octx = off.getContext2d();
octx.imageSmoothingEnabled = false;
for (ly in 0...frames[currentFrame].layers.length) {
var L = frames[currentFrame].layers[ly];
if (!L.visible) continue;
for (y in 0...height) for (x in 0...width) {
var c = L.buffer.get(x,y);
var a = (c >>> 24) & 0xFF;
var r = (c >> 16) & 0xFF;
var g = (c >> 8) & 0xFF;
var b = c & 0xFF;
if (a == 0) continue;
octx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
octx.fillRect(x, y, 1, 1);
}
}
var url = off.toDataURL("image/png");
Browser.window.open(url, "_blank");
}
// Save project (download JSON)
private function saveProject():Void {
var obj = {
width: width, height: height,
frames: []
};
for (f in frames) {
var fr = { layers: [] };
for (L in f.layers) {
fr.layers.push({ name: L.name, visible: L.visible, opacity: L.opacity, data: L.buffer.cloneData() });
}
obj.frames.push(fr);
}
var json = haxe.Json.stringify(obj);
var blob = new js.html.Blob([json], { "type": "application/json" });
var url = Browser.window.URL.createObjectURL(blob);
var a = cast Browser.document.createElement("a");
a.href = url;
a.download = "pixel_project.json";
Browser.document.body.appendChild(a);
a.click();
Browser.document.body.removeChild(a);
Browser.window.URL.revokeObjectURL(url);
}
// Load project from File object
private function loadProjectFile(f:Dynamic):Void {
var reader = new FileReader();
reader.onload = e -> {
var txt = cast reader.result : String;
try {
var obj = haxe.Json.parse(txt);
// basic validation
if (obj.width != width || obj.height != height) {
// simple handling: ignore size mismatch for now
}
frames = [];
for (fr in obj.frames) {
var frame = new Frame(width, height);
frame.layers = [];
for (ly in fr.layers) {
var L = new Layer(width, height, ly.name);
L.visible = ly.visible;
L.opacity = ly.opacity;
// copy data
for (i in 0...Math.min(L.buffer.data.length, ly.data.length)) L.buffer.data[i] = ly.data[i];
frame.layers.push(L);
}
frames.push(frame);
}
currentFrame = 0; currentLayer = 0;
buildLayersUI(); render(); updatePreview();
} catch (err) {
Browser.window.alert("Failed to load project: " + err);
}
};
reader.readAsText(f);
}
// Shortcuts
private function setupShortcuts():Void {
Browser.window.onkeydown = (e) -> {
if (e.ctrlKey || e.metaKey) {
if (e.keyCode == 90) { undo(); return; } // Z
if (e.keyCode == 89) { redo(); return; } // Y
}
switch (e.key) {
case "b": tool = "pen";
case "e": tool = "eraser";
case "f": tool = "fill";
case "l": tool = "line";
case "r": tool = "rect";
case "s": e.preventDefault(); exportPNG();
}
};
}
// Utilities
private function colorToCss(c:UInt):String {
var a = (c >>> 24) & 0xFF;
var r = (c >> 16) & 0xFF;
var g = (c >> 8) & 0xFF;
var b = c & 0xFF;
if (a == 255) return "rgb(" + r + "," + g + "," + b + ")";
return "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
}
private function hexToUInt(hex:String):UInt {
var r = Std.parseInt("0x" + hex.substr(1,2));
var g = Std.parseInt("0x" + hex.substr(3,2));
var b = Std.parseInt("0x" + hex.substr(5,2));
return (0xFF << 24) | (r << 16) | (g << 8) | b;
}
}