xxxxxxxxxx
361
var grid = 4;
var show = false;
var pixelCoords = new Set();
var animationIndex = 0;
var lastAnimationTime = 0;
var animationSpeed = 100;
var lastX = 0;
var lastY = 0;
var exportCount = {};
let refImg;
let imgLoaded = false;
let showRef = false;
let quantizedImg = null; // Initialize as null
let colorPicker, nameInput, clearButton, exportButton, refButton, fileInput, traceButton;
function setup() {
createCanvas(512, 256);
background(10);
colorPicker = createColorPicker("#FFFFFF");
colorPicker.position(0, height + 10);
colorPicker.size(colorPicker.width, 28);
nameInput = createInput('mySprite');
nameInput.position(colorPicker.x + colorPicker.width + 8, height + 10);
nameInput.size(150, 28);
clearButton = createButton("CLEAR");
clearButton.position(nameInput.x + nameInput.width + 8, height + 10);
clearButton.size(clearButton.width, 32);
clearButton.mousePressed(clean);
exportButton = createButton("EXPORT COORDS");
exportButton.position(clearButton.x + clearButton.width + 8, height + 10);
exportButton.size(116, 32);
exportButton.mousePressed(exportCoords);
refButton = createButton("REF PICTURE");
refButton.position(exportButton.x + exportButton.width + 8, height + 10);
refButton.size(100, 32);
refButton.mousePressed(() => showRef = !showRef);
traceButton = createButton("TRACE");
traceButton.position(refButton.x + refButton.width + 8, height + 10);
traceButton.size(80, 32);
traceButton.mousePressed(traceImage);
fileInput = createFileInput(handleFile);
fileInput.position(traceButton.x + traceButton.width + 8, height + 10);
let canvasElement = document.querySelector('canvas');
canvasElement.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
}
function draw() {
background(10);
if (showRef && imgLoaded) {
push();
tint(255, 127);
image(refImg, 0, 0, width, height);
pop();
}
for (let coordStr of pixelCoords) {
let coord = coordStr.split(',').map(Number);
noStroke();
fill(colorPicker.color());
square(coord[0] * grid, coord[1] * grid, grid);
}
if (pixelCoords.size > 0) {
let nowTime = millis();
if (nowTime - lastAnimationTime > animationSpeed) {
let coordArray = Array.from(pixelCoords);
let currentCoord = coordArray[animationIndex].split(',').map(Number);
noStroke();
fill(255, 0, 0);
square(currentCoord[0] * grid, currentCoord[1] * grid, grid);
animationIndex = (animationIndex + 1) % coordArray.length;
lastAnimationTime = nowTime;
} else {
let coordArray = Array.from(pixelCoords);
let currentCoord = coordArray[animationIndex].split(',').map(Number);
noStroke();
fill(255, 0, 0);
square(currentCoord[0] * grid, currentCoord[1] * grid, grid);
}
}
stroke(150);
line(width/2, 0, width/2, height);
line(0, height/2, width, height/2);
if (pixelCoords.size > 0) {
let nowTime = millis();
if (nowTime - lastAnimationTime > animationSpeed) {
if (showRef && imgLoaded) {
background(10);
push();
tint(255, 127);
image(refImg, 0, 0, width, height);
pop();
}
redrawAllPixels();
let coordArray = Array.from(pixelCoords);
let currentCoord = coordArray[animationIndex].split(',').map(Number);
noStroke();
fill(255, 0, 0);
square(currentCoord[0] * grid, currentCoord[1] * grid, grid);
animationIndex = (animationIndex + 1) % coordArray.length;
lastAnimationTime = nowTime;
}
}
if (mouseIsPressed) {
var currentX = snap(mouseX);
var currentY = snap(mouseY);
if (lastX === 0 && lastY === 0) {
lastX = currentX;
lastY = currentY;
}
var distance = dist(lastX, lastY, currentX, currentY);
var steps = Math.max(1, Math.ceil(distance / grid));
for (var i = 0; i <= steps; i++) {
var t = i / steps;
var x = lerp(lastX, currentX, t);
var y = lerp(lastY, currentY, t);
x = snap(x);
y = snap(y);
var gridX = Math.floor(x / grid);
var gridY = Math.floor(y / grid);
if (gridX >= 0 && gridX < 128 && gridY >= 0 && gridY < 64) {
if (mouseButton === RIGHT) {
pixelCoords.delete(`${gridX},${gridY}`);
} else if (mouseButton === LEFT) {
noStroke();
fill(colorPicker.color());
square(x, y, grid);
pixelCoords.add(`${gridX},${gridY}`);
}
}
}
lastX = currentX;
lastY = currentY;
} else {
lastX = 0;
lastY = 0;
}
}
function handleFile(file) {
imgLoaded = false;
quantizedImg = null; // Reset quantizedImg
if (file.type === 'image') {
refImg = createImg(file.data, 'Reference image', 'anonymous', imgCreated);
refImg.hide();
} else {
refImg = null;
}
}
function imgCreated() {
refImg.hide();
let g = createGraphics(refImg.elt.width, refImg.elt.height);
g.image(refImg, 0, 0);
refImg.remove();
refImg = g.get(0, 0, g.width, g.height);
if (refImg.width/refImg.height > width/height) {
refImg.resize(width, 0);
} else {
refImg.resize(0, height);
}
// Create quantized version for tracing
quantizedImg = createGraphics(128, 64);
quantizedImg.pixelDensity(1);
quantizedImg.background(255);
quantizedImg.image(refImg, 0, 0, 128, 64);
quantizedImg.loadPixels();
// Threshold the image
for (let i = 0; i < quantizedImg.pixels.length; i += 4) {
let avg = (quantizedImg.pixels[i] + quantizedImg.pixels[i + 1] + quantizedImg.pixels[i + 2]) / 3;
let binary = avg < 127 ? 0 : 255;
quantizedImg.pixels[i] = binary;
quantizedImg.pixels[i + 1] = binary;
quantizedImg.pixels[i + 2] = binary;
quantizedImg.pixels[i + 3] = 255;
}
quantizedImg.updatePixels();
imgLoaded = true;
showRef = true;
}
function getPixelColor(x, y) {
if (!quantizedImg || x < 0 || x >= 128 || y < 0 || y >= 64) return 255;
let index = 4 * (y * 128 + x);
return quantizedImg.pixels[index];
}
function findStartPixel() {
if (!quantizedImg) return null;
for (let x = 0; x < 128; x++) {
for (let y = 63; y >= 0; y--) {
if (getPixelColor(x, y) < 127) {
return { x, y };
}
}
}
return null;
}
function getMooreNeighbors(pixel) {
return [
{ x: pixel.x + 1, y: pixel.y }, // right
{ x: pixel.x + 1, y: pixel.y - 1 }, // top-right
{ x: pixel.x, y: pixel.y - 1 }, // top
{ x: pixel.x - 1, y: pixel.y - 1 }, // top-left
{ x: pixel.x - 1, y: pixel.y }, // left
{ x: pixel.x - 1, y: pixel.y + 1 }, // bottom-left
{ x: pixel.x, y: pixel.y + 1 }, // bottom
{ x: pixel.x + 1, y: pixel.y + 1 } // bottom-right
];
}
function traceContour(start) {
let contourPoints = [];
let visited = new Set();
let current = start;
let lastMove = { x: current.x, y: current.y + 1 };
do {
contourPoints.push(current);
let key = `${current.x},${current.y}`;
visited.add(key);
let neighbors = getMooreNeighbors(current);
let found = false;
let backtrackPoint = lastMove;
let startIdx = 0;
for (let i = 0; i < neighbors.length; i++) {
if (neighbors[i].x === backtrackPoint.x && neighbors[i].y === backtrackPoint.y) {
startIdx = (i + 1) % 8;
break;
}
}
for (let i = 0; i < 8; i++) {
let idx = (startIdx + i) % 8;
let neighbor = neighbors[idx];
if (getPixelColor(neighbor.x, neighbor.y) < 127) {
lastMove = current;
current = neighbor;
found = true;
break;
}
}
if (!found) {
current = backtrackPoint;
}
} while (!(current.x === start.x &&
current.y === start.y &&
contourPoints.length > 2));
return contourPoints;
}
function traceImage() {
if (!imgLoaded || !quantizedImg) {
console.log('No image loaded');
return;
}
clean();
let startPixel = findStartPixel();
if (startPixel) {
let contourPoints = traceContour(startPixel);
for (let point of contourPoints) {
pixelCoords.add(`${point.x},${point.y}`);
}
}
}
function snap(p) {
var cell = Math.round((p - grid / 2) / grid);
return cell * grid;
}
function redrawAllPixels() {
for (let coordStr of pixelCoords) {
let coord = coordStr.split(',').map(Number);
noStroke();
fill(colorPicker.color());
square(coord[0] * grid, coord[1] * grid, grid);
}
}
function clean() {
pixelCoords.clear();
animationIndex = 0;
lastAnimationTime = 0;
}
function exportCoords() {
let baseName = nameInput.value().trim() || 'mySprite';
if (!(baseName in exportCount)) {
exportCount[baseName] = 0;
}
exportCount[baseName]++;
let varName = baseName;
if (exportCount[baseName] > 1) {
varName = `${baseName}_${exportCount[baseName]}`;
}
let output = `const uint8_t ${varName}[][2] = {\n`;
let coordArray = Array.from(pixelCoords)
.map(coord => coord.split(',').map(Number))
coordArray.forEach((coord, index) => {
output += ` {${coord[0]}, ${coord[1]}}`;
if (index < coordArray.length - 1) output += ",";
output += "\n";
});
output += "};\n";
output += `const uint16_t ${varName}_length = ${coordArray.length};\n`;
let blob = new Blob([output], {type: 'text/plain'});
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = `${varName}.txt`;
a.click();
window.URL.revokeObjectURL(url);
}