-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
264 lines (224 loc) · 10.7 KB
/
index.js
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
let fs = require('fs'),
PNG = require('pngjs').PNG,
request = require('request');
const XMLHttpRequest = require('xhr2');
const config = require('./config.json');
const url = "https://place-api.zevent.fr/graphql";
let totalPrice = 0;
let placedPixels = []; // Array to store placed pixels
let data = {
'operationName': "setPixels",
"variables": {
"pixels": [
],
},
"query":"mutation setPixels($pixels: [PixelInput!]!) {\n setPixels(pixels: $pixels)\n}"
};
fs.createReadStream(config.imagePath)
.pipe(new PNG())
.on('parsed', function() {
let imgData = this.data;
let width = this.width;
let height = this.height;
parseColors(imgData, width, height);
});
let currentColorMapping = [];
function parseColors(imgData, width, height)
{
let xhrColor = new XMLHttpRequest();
xhrColor.open("POST", url);
xhrColor.setRequestHeader("Accept", "application/json");
xhrColor.setRequestHeader("Content-Type", "application/json");
xhrColor.send('{"operationName":"getAvailableColors","variables":{},"query":"query getAvailableColors {\\n getAvailableColors {\\n colorCode\\n name\\n __typename\\n }\\n}"}');
xhrColor.onreadystatechange = async function () {
if (xhrColor.readyState === 4) {
let colors = JSON.parse(xhrColor.responseText).data.getAvailableColors;
let colorsRGB = await colors.map((color) => {
return hexToRgb(color.colorCode);
});
if (config.currentImage === "map.png") {
console.log("Downloading ZPlace map image...");
//fetch map from internet
let xhrMap = new XMLHttpRequest();
xhrMap.open("POST", url);
xhrMap.setRequestHeader("Accept", "application/json");
xhrMap.setRequestHeader("Content-Type", "application/json");
xhrMap.send('{"operationName":"getLastBoardUrl","variables":{},"query":"query getLastBoardUrl {\\n lastBoardUrl\\n}"}');
xhrMap.onreadystatechange = async function () {
if (xhrMap.readyState === 4) {
let url = JSON.parse(xhrMap.responseText).data.lastBoardUrl;
console.log(url)
await request.head(url, async function (err, res) {
console.log('Map length', res.headers['content-length']);
await request(url, async function () {
console.log("Map downloaded");
const { colorMap, dimensions } = await loadMap();
currentColorMapping = colorMap;
console.log("Map loaded with " + colorMap.length + " pixels");
if (dimensions.width !== width || dimensions.height !== height) {
console.log("The map dimensions are not the same as the image dimensions");
process.exit(1);
}
await askingPixels(height, width, imgData, colorsRGB);
}).pipe(await fs.createWriteStream("map.png"));
});
}
}
} else if (config.currentImage !== "") {
currentColorMapping = await loadMap();
console.log("Map loaded with " + currentColorMapping.length + " pixels");
await askingPixels(height, width, imgData, colorsRGB);
}
}
};
}
async function askingPixels(height, width, imgData, colorsRGB) {
let processedPixels = 0;
let startTime = Date.now(); // Track when the process started
let totalNonTransparentPixels = 0;
// Count non-transparent pixels before processing
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let idx = (width * y + x) << 2;
if (imgData[idx + 3] !== 0) { // Pixel is not transparent
totalNonTransparentPixels++;
}
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let idx = (width * y + x) << 2;
if (imgData[idx + 3] !== 0) { // pixel is not transparent and not white
let xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
parsingPixelResponse(xhr, width, imgData, colorsRGB);
}
};
let pixelLevelData = {
"operationName": "getPixelLevel",
"variables": {"pixel": {"x": x, "y": y}},
"query": "query getPixelLevel($pixel: PixelUpgradeInput!) {\n getPixelLevel(pixel: $pixel) {\n x\n y\n level\n coloredBy\n upgradedBy\n __typename\n }\n}"
};
xhr.send(JSON.stringify(pixelLevelData));
// Update processed pixels count
processedPixels++;
let percentProcessed = ((processedPixels / totalNonTransparentPixels) * 100).toFixed(2);
let elapsedTime = Date.now() - startTime;
let avgTimePerPixel = elapsedTime / processedPixels;
let remainingPixels = totalNonTransparentPixels - processedPixels;
let eta = Math.round((avgTimePerPixel * remainingPixels) / 1000); // in seconds
console.log(`Processed: ${percentProcessed}% | ETA: ${formatTime(eta)}`);
// Wait based on config delay
let timeInterval = config.timeInterval;
if (timeInterval.activate && timeInterval.minimum > -1) { //Timeinterval is set
await new Promise(resolve =>
setTimeout(resolve, Math.floor(Math.random() * (config.timeInterval.maximum - config.timeInterval.minimum + 1)) + config.timeInterval.minimum)
);
}
}
}
}
}
function formatTime(seconds) {
let hrs = Math.floor(seconds / 3600);
let mins = Math.floor((seconds % 3600) / 60);
let secs = seconds % 60;
let formattedTime = "";
if (hrs > 0) {
formattedTime += `${hrs} hour${hrs !== 1 ? 's' : ''}, `;
}
if (mins > 0 || hrs > 0) {
formattedTime += `${mins} minute${mins !== 1 ? 's' : ''}, `;
}
formattedTime += `${secs} second${secs !== 1 ? 's' : ''}`;
return formattedTime;
}
function parsingPixelResponse(xhr, width, imgData, colorsRGB)
{
let response = JSON.parse(xhr.responseText);
let pixelObject = response.data.getPixelLevel;
let level = pixelObject.level;
let x = pixelObject.x;
let y = pixelObject.y;
let idx = (width * y + x) << 2;
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", url);
xmlHttpRequest.setRequestHeader("Authorization", "Bearer " + config.token);
xmlHttpRequest.setRequestHeader("Content-Type", "application/json");
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4) {
console.log("Response of placing for x " + x + " y " + y + " with level " + level + " : " + xmlHttpRequest.responseText);
}
}
let rgb = {r: imgData[idx], g: imgData[idx + 1], b: imgData[idx + 2]};
let closestColorIndex = getClosestColorIndex(idx, colorsRGB, rgb);
let currentColor = currentColorMapping[idx];
let oldColorIndex = getClosestColorIndex(idx, colorsRGB, currentColor);
if (closestColorIndex !== oldColorIndex) {
totalPrice += level;
console.log("Placing pixel at x" + x + " y" + y + " with level " + level + " and color " + closestColorIndex + ", old color "+oldColorIndex+", current price : " + totalPrice);
data["variables"]["pixels"] = [{
"x": x,
"y": y,
"color": closestColorIndex,
"currentLevel": level
}];
placedPixels.push({ x, y, color: closestColorIndex, level }); // Add placed pixel to the list
if (config.placing) xmlHttpRequest.send(JSON.stringify(data));
} else console.log("Pixel at x " + x + " y " + y + " is already placed with color " + closestColorIndex+", current price : " + totalPrice);
}
async function loadMap() {
return new Promise((resolve, reject) => {
let colorMap = [];
console.log("Parsing global image");
fs.createReadStream(config.currentImage)
.pipe(new PNG())
.on('parsed', function () {
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
if (x % 100 === 0 && y % 100 === 0 && y !== 0) console.log("Parsing global image : x" + x + " y" + y);
let idx = (this.width * y + x) << 2;
if (this.data[idx + 3] === 0) { // Check if pixel is transparent
colorMap[idx] = { r: 255, g: 255, b: 255 }; // Set default color to white
} else {
colorMap[idx] = { r: this.data[idx], g: this.data[idx + 1], b: this.data[idx + 2] };
}
}
}
console.log("Parsing global image done");
resolve({ colorMap: colorMap, dimensions: { width: this.width, height: this.height } });
})
.on('error', function (err) {
console.log(err);
reject(err);
});
});
}
function getClosestColorIndex(idx, colorsRGB, rgb) {
//find the closest color in the palette colorsRGB which contains {{r,g,b}}
let closestColor = colorsRGB.reduce((prev, curr) => {
return (getDistance(prev, rgb["r"], rgb["g"], rgb["b"]) < getDistance(curr, rgb["r"], rgb["g"], rgb["b"]) ? prev : curr)
});
//find closestColor index in colorsRGB which contains {{r,g,b}}
return colorsRGB.findIndex((color) => {
return color.r === closestColor.r && color.g === closestColor.g && color.b === closestColor.b;
});
}
function getDistance(color1, r, g, b) {
return Math.sqrt(Math.pow(color1.r - r, 2) + Math.pow(color1.g - g, 2) + Math.pow(color1.b - b, 2));
}
function hexToRgb(hex) {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
process.on('exit', () => {
console.log("List of placed pixels:", placedPixels);
});