-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
942 lines (810 loc) · 23.3 KB
/
Copy pathmain.js
File metadata and controls
942 lines (810 loc) · 23.3 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^e(rror)?$" }]*/
import express from 'express';
import fs from 'fs';
import fetch from 'node-fetch';
import WebSocket from 'ws';
import nunjucks from 'nunjucks';
import path from 'path';
import { fileURLToPath } from 'url';
import multer from 'multer';
import sharp from 'sharp';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3000;
const WEBPORT = 3001;
const DRAWPORT = 3002;
const WS_URL = 'wss://paintboard.luogu.me/api/paintboard/ws';
const BASE_URL = 'https://paintboard.luogu.me/api';
// const WS_URL = 'ws://localhost:32767/api/paintboard/ws';
// const BASE_URL = 'http://localhost:32767/api';
const TOKEN_FILE = './tokens.txt';
const UPLOAD_DIR = './uploads/';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, UPLOAD_DIR); // 上传目录
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
});
const upload = multer({ storage });
// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR);
}
if (!fs.existsSync(TOKEN_FILE)) {
fs.writeFileSync(TOKEN_FILE, "");
}
// 上传图片并提取像素信息的 API
app.post('/api/upload-image', upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).send('没有选择任何文件。');
}
const filePath = path.join(UPLOAD_DIR, req.file.filename);
try {
// 使用 sharp 处理上传的图片
const image = sharp(filePath);
const metadata = await image.metadata(); // 获取图片元数据(包括尺寸等)
const { width, height, channels } = metadata;
const pixels = await image.raw().toBuffer(); // 获取像素数据
const pixelData = [];
for (let i = 0; i < pixels.length; i += channels) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
if (channels === 4) {
const a = pixels[i + 3];
pixelData.push({ r, g, b, a });
} else {
pixelData.push({ r, g, b });
}
}
res.json({ width, height, pixelData });
} catch (error) {
res.status(500).send('图片处理失败。');
}
});
nunjucks.configure(path.join(__dirname, 'views'), {
autoescape: true,
express: app,
noCache: true
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.get('/', (req, res) => {
res.render('index.njk');
});
app.get('/heatmap', (req, res) => {
res.render('heatmap.njk');
});
import { createCanvas } from 'canvas';
let heatmap = [];
const heatmap_millseconds = 600 * 1000
setInterval(() => {
while (heatmap.length && heatmap[0][0] < Date.now() - heatmap_millseconds) {
heatmap.shift();
}
}, 10000);
function generateHeatmap() {
const hsv2rgb = (h, s, v) => {
var r, g, b, i, f, p, q, t;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
};
const map = new Map();
let maximum = 0;
const convertRatio = 20;
heatmap.forEach((item) => {
const key = [Math.floor(item[1] / convertRatio), Math.floor(item[2] / convertRatio)].toString();
if (map.has(key)) {
map.set(key, map.get(key) + 1);
} else {
map.set(key, 1);
}
maximum = Math.max(maximum, map.get(key));
});
const logMax = Math.log10(maximum + 1);
let list = [];
for (let x = 0; x < Math.floor(1000 / convertRatio); x++) {
for (let y = 0; y < Math.floor(600 / convertRatio); y++) {
if (map.has([x, y].toString())) {
const rawValue = map.get([x, y].toString());
const normalizedValue = Math.log10(rawValue + 1) / logMax; // 对数归一化
const pseudo = hsv2rgb(0.7 - normalizedValue * 0.7, 1, 0.65 + normalizedValue * 0.35);
list.push([x, y, pseudo.r, pseudo.g, pseudo.b, 255]);
} else {
list.push([x, y, 0, 0, 0, 255]);
}
}
}
return list;
}
app.get('/heatmap.png', (req, res) => {
const convertRatio = 20;
const blockSize = 10;
const canvas = createCanvas(Math.floor(1000 / convertRatio * blockSize), Math.floor(600 / convertRatio * blockSize));
const ctx = canvas.getContext('2d');
const canvasData = ctx.getImageData(0, 0, Math.floor(1000 / convertRatio * blockSize), Math.floor(600 / convertRatio * blockSize));
const drawReal = (x, y, r, g, b, a) => {
const index = Math.floor(x + y * 1000 / convertRatio * blockSize) * 4;
canvasData.data[index + 0] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
};
const drawPixel = (x, y, r, g, b, a) => {
const rx = x * blockSize, ry = y * blockSize;
for (let i = 0; i < blockSize; i++) {
for (let j = 0; j < blockSize; j++) {
drawReal(rx + i, ry + j, r, g, b, a);
}
}
};
const data = generateHeatmap();
for (let point of data) drawPixel(point[0], point[1], point[2], point[3], point[4], point[5]);
ctx.putImageData(canvasData, 0, 0);
const imageBuffer = canvas.toBuffer('image/png');
res.setHeader('Content-Type', 'image/png').send(imageBuffer);
});
app.get('/heatlist', (req, res) => res.status(200).send(generateHeatmap()));
app.post('/queryheat', (req, res) => {
const { time, lx, ly, rx, ry } = req.body;
let cnt = 0;
heatmap.forEach((item) => {
let x = item[1], y = item[2], tim = item[0];
if (x < lx || x > rx) return;
if (y < ly || y > ry) return;
if (tim < Date.now() - time * 1000) return;
cnt++;
});
res.status(200).send(cnt.toString());
});
import { WebSocketServer } from 'ws';
import http from 'http';
const server = http.createServer();
const wss = new WebSocketServer({ server });
let logClients = [];
wss.on('connection', (client) => {
logClients.push(client);
client.on('close', () => {
logClients = logClients.filter(c => c !== client);
});
});
function getTime(type) {
const date = new Date();
if (type === 0) {
return date.getTime();
}
else if (type === 1) {
return date.toLocaleTimeString('en-US', { hour12: false });
}
}
// 广播日志
function broadcastLog(message) {
logClients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
console.log(message);
}
let ws;
let paintCb = new Map();
let processAttack;
let status = false;
let needRestart = false;
let lstPath, lstStartX, lstStartY;
let paintId = 0;
let paintCnt = 0;
let attackCnt = 0;
let recieveCnt = 0;
let coloredCnt = 0;
let queueTotal = 0, queuePos = 0;
setInterval(() => {
let paintRate = paintCnt / 1.0;
let attackRate = attackCnt / 1.0;
let recieveRate = recieveCnt / 1.0;
let coloredRate = coloredCnt / 1.0;
const buffer = ws.bufferedAmount;
attackCnt = 0;
paintCnt = 0;
recieveCnt = 0;
coloredCnt = 0;
reportMsg(JSON.stringify({ type: 'data_view', paintRate, attackRate, recieveRate, coloredRate, buffer, queueTotal, queuePos }));
}, 1000);
setInterval(() => {
reportMsg(JSON.stringify({ type: 'heatlist', data: generateHeatmap() }));
}, 2000);
let board = [];
async function initBoard() {
const st = getTime(0);
await fetch(`${BASE_URL}/paintboard/getboard`)
.then(response => {
if (!response.ok) {
broadcastLog(`获取绘版信息失败: ${response.status}`);
return new ArrayBuffer();
}
broadcastLog(`绘版信息已返回。`);
return response.arrayBuffer();
})
.then(arrayBuffer => {
const byteArray = new Uint8Array(arrayBuffer);
for (let y = 0; y < 600; y++) {
for (let x = 0; x < 1000; x++) {
const idx = (y * 1000 + x) * 3;
let r = byteArray[idx], g = byteArray[idx + 1], b = byteArray[idx + 2];
const pixel = { r, g, b };
board[y][x] = pixel;
}
}
}).catch(error => broadcastLog(`获取绘版信息失败: ${error}`));
const ed = getTime(0);
broadcastLog(`初始化耗时: ${ed - st} ms`);
}
for (let y = 0; y < 600; y++) {
board[y] = [];
for (let x = 0; x < 1000; x++) {
board[y][x] = { r: 255, g: 255, b: 255 };
}
}
async function init() {
broadcastLog(`正在初始化绘版。`);
await initBoard();
broadcastLog(`绘版加载完成。`);
}
app.get('/init', (req, res) => { init(); res.status(200).end(); });
function connect() {
broadcastLog("正在连接 WebSocket。");
ws = new WebSocket(WS_URL);
ws.binaryType = "arraybuffer";
ws.onopen = async () => {
const message = 'WebSocket 连接已打开。';
broadcastLog(message);
await init();
if (!status && needRestart) {
try {
SdrawTask(lstPath, lstStartX, lstStartY);
broadcastLog("正在自动重启画图任务。");
} catch (e) {
broadcastLog("自动重启画图任务失败。");
}
needRestart = false;
}
status = true;
};
ws.onmessage = async (event) => {
const buffer = event.data;
const dataView = new DataView(buffer);
let offset = 0;
while (offset < buffer.byteLength) {
const type = dataView.getUint8(offset);
offset += 1;
switch (type) {
case 0xfa: {
const x = dataView.getUint16(offset, true);
const y = dataView.getUint16(offset + 2, true);
const colorR = dataView.getUint8(offset + 4);
const colorG = dataView.getUint8(offset + 5);
const colorB = dataView.getUint8(offset + 6);
board[y][x] = { r: colorR, g: colorG, b: colorB };
offset += 7;
if (processAttack) await processAttack(x, y, colorR, colorG, colorB);
heatmap.push([Date.now(), x, y]);
break;
}
case 0xfc: {
ws.send(new Uint8Array([0xfb]));
break;
}
case 0xff: {
recieveCnt++;
const id = dataView.getUint32(offset, true);
const code = dataView.getUint8(offset + 4);
offset += 5;
const cb = paintCb.get(id);
if (cb) {
cb(code);
paintCb.delete(id);
}
break;
}
default:
const message = `未知的消息类型: ${type}`;
broadcastLog(message);
}
}
};
ws.onerror = (err) => {
const message = `WebSocket 出错: ${err.message}。`;
stopDrawing = true;
isDrawing = false;
broadcastLog(message);
};
ws.onclose = (err) => {
const reason = err.reason ? err.reason : "Unknown";
const message = `WebSocket 已经关闭 (${err.code}: ${reason}),尝试重连。`;
if (isDrawing) needRestart = true;
stopDrawing = true;
isDrawing = false;
broadcastLog(message);
status = false;
processAttack = null;
setTimeout(connect, 0);
};
}
connect();
let chunks = []; // 存储数据片段
let totalSize = 0;
function appendData(paintData) {
chunks.push(paintData);
totalSize += paintData.length;
}
function getMergedData() {
let result = new Uint8Array(totalSize);
let offset = 0;
for (let chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
totalSize = 0;
chunks = [];
return result;
}
setInterval(() => {
if (chunks.length > 0 && ws.readyState === WebSocket.OPEN) {
ws.send(getMergedData());
}
}, 1000 / 50.0);
function uintToUint8Array(uint, bytes) {
const array = new Uint8Array(bytes);
for (let i = 0; i < bytes; i++) {
array[i] = uint & 0xff;
uint = uint >> 8;
}
return array;
}
async function paint(uid, token, r, g, b, nowX, nowY) {
// const id = (paintId++) % 4294967296;
const id = (paintId++) % 1048576;
paintCnt++;
const tokenBytes = new Uint8Array(16);
token.replace(/-/g, '').match(/.{2}/g).map((byte, i) =>
tokenBytes[i] = parseInt(byte, 16));
const paintData = new Uint8Array([
0xfe,
...uintToUint8Array(nowX, 2),
...uintToUint8Array(nowY, 2),
r, g, b,
...uintToUint8Array(uid, 3),
...tokenBytes,
...uintToUint8Array(id, 4)
]);
appendData(paintData);
paintCb.set(id, (code) => {
switch (code) {
case 0xef: // success
coloredCnt++;
break;
case 0xed: // invalid token
broadcastLog(`失效的 Token: ${token}#${uid}。`);
break;
case 0xee:
broadcastLog(`Token ${token}#${uid} 冷却中。`);
break;
}
});
}
const reportServer = http.createServer();
const report = new WebSocketServer({ server: reportServer });
let reportClients = [];
report.on('connection', (client) => {
reportClients.push(client)
client.on('close', () => {
reportClients = reportClients.filter(c => c !== client);
});
});
function reportMsg(msg) {
reportClients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(msg);
}
});
}
app.use(express.json());
// 获取 token
app.post('/api/paintboard/token', async (req, res) => {
const { uid, paste } = req.body;
if (!uid || !paste) {
const errorMessage = '无效的 UID 或剪贴板。';
return res.status(400).send(errorMessage);
}
try {
const body = JSON.stringify({ uid: parseInt(uid), access_key: paste });
const response = await fetch(`${BASE_URL}/auth/gettoken`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
if (!response.ok || response.status != 200) {
return res.status(response.status).send('内部服务器错误。');
}
const data = await response.json();
let token = data.data.token;
try {
const tokenData = JSON.stringify([token, uid]);
fs.appendFileSync(TOKEN_FILE, tokenData + '\n');
} catch (error) {
res.status(500).send('内部服务器错误。');
}
res.json(data);
} catch (error) {
res.status(500).send('内部服务器错误。');
}
});
// 读取 tokens 文件
let fTokens = [];
let idx = 0;
let info = { fmax: 0, sim: 5, mod: 30000, strategy: { cd: 'explosive', order: 'random', priority: 'none', counterattack: 'none' } };
async function getNextToken() {
if (info.strategy.cd === 'amortized') await delay(Math.ceil(info.mod / info.fmax));
let res = fTokens[idx];
idx += 1;
if (idx >= info.fmax) {
idx = 0;
if (info.strategy.cd === 'explosive') await delay(info.mod);
}
return res;
}
app.get('/api/getinfo', (req, res) => {
res.status(200).send(info);
});
function createNormalApi(name) {
app.post('/api/' + name, (req, res) => {
const { val } = req.body;
info[name] = val;
res.status(200).end();
});
}
createNormalApi('fmax');
createNormalApi('sim');
createNormalApi('mod');
function createStrategyApi(name) {
app.post('/api/strategy/' + name, (req, res) => {
const { val } = req.body;
info.strategy[name] = val;
res.status(200).end();
});
}
createStrategyApi('cd');
createStrategyApi('order');
createStrategyApi('priority');
createStrategyApi('counterattack');
app.get('/api/tokens', (req, res) => {
try {
const fileContent = fs.readFileSync(TOKEN_FILE, 'utf-8');
const lines = fileContent
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
const tokens = lines.map((line) => {
try {
const tokenPair = JSON.parse(line);
if (Array.isArray(tokenPair) && tokenPair.length === 2) {
return { token: tokenPair[0], uid: parseInt(tokenPair[1]) };
}
return null;
} catch (e) {
return null;
}
}).filter(item => item !== null);
fTokens = tokens;
if (info.fmax == 0) info.fmax = tokens.length;
res.json(tokens);
} catch (error) {
res.status(500).send('内部服务器错误。');
}
});
app.get('/api/images', (req, res) => {
try {
const files = fs.readdirSync(UPLOAD_DIR).filter(file => !fs.statSync(path.join(UPLOAD_DIR, file)).isDirectory());
res.json(files);
} catch (error) {
res.status(500).send('图像列表获取失败。');
}
});
let isDrawing = false; // 控制是否继续绘画
let stopDrawing = false; // 控制是否停止任务
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Heap-based PriorityQueue implementation with deduplication support
class PriorityQueue {
constructor(compareFn = null) {
this.heap = [];
this.keySet = new Set(); // For deduplication based on x,y coordinates
this.compareFn = compareFn; // Custom comparator for priority
}
_makeKey(x, y) {
return `${x},${y}`;
}
_parent(i) {
return Math.floor((i - 1) / 2);
}
_leftChild(i) {
return 2 * i + 1;
}
_rightChild(i) {
return 2 * i + 2;
}
_swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
_compare(a, b) {
if (this.compareFn) {
return this.compareFn(a, b) > 0; // Use custom comparator (higher priority first)
}
// Default: no priority, maintain insertion order (FIFO-like behavior)
return false;
}
_heapifyUp(index) {
while (index > 0) {
const parent = this._parent(index);
if (this._compare(this.heap[index], this.heap[parent])) {
this._swap(index, parent);
index = parent;
} else {
break;
}
}
}
_heapifyDown(index) {
while (true) {
let largest = index;
const left = this._leftChild(index);
const right = this._rightChild(index);
if (left < this.heap.length && this._compare(this.heap[left], this.heap[largest])) {
largest = left;
}
if (right < this.heap.length && this._compare(this.heap[right], this.heap[largest])) {
largest = right;
}
if (largest !== index) {
this._swap(index, largest);
index = largest;
} else {
break;
}
}
}
push(item) {
const key = this._makeKey(item.x, item.y);
if (this.keySet.has(key)) {
return false; // Already exists, skip
}
this.heap.push(item);
this.keySet.add(key);
this._heapifyUp(this.heap.length - 1);
return true;
}
pop() {
if (this.heap.length === 0) {
return null;
}
if (this.heap.length === 1) {
const item = this.heap.pop();
this.keySet.delete(this._makeKey(item.x, item.y));
return item;
}
const top = this.heap[0];
this.heap[0] = this.heap.pop();
this.keySet.delete(this._makeKey(top.x, top.y));
this._heapifyDown(0);
return top;
}
peek() {
return this.heap.length > 0 ? this.heap[0] : null;
}
get length() {
return this.heap.length;
}
clear() {
this.heap = [];
this.keySet.clear();
}
isEmpty() {
return this.heap.length === 0;
}
setComparator(compareFn) {
this.compareFn = compareFn;
// Rebuild heap with new comparator
const items = [...this.heap];
this.heap = [];
for (const item of items) {
this.heap.push(item);
}
// Heapify from bottom up
for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--) {
this._heapifyDown(i);
}
}
}
let pointQueue = new PriorityQueue();
async function SdrawTask(imagePath, startX, startY) {
// 绘画任务的主函数
info.imagePath = imagePath.split('\\')[1];
info.startX = startX;
info.startY = startY;
isDrawing = true;
stopDrawing = false;
pointQueue = new PriorityQueue();
const image = sharp(imagePath);
const { width, height, channels } = await image.metadata();
const pixels = await image.raw().toBuffer();
const xL = startX, xR = startX + width - 1;
const yL = startY, yR = startY + height - 1;
const totalPixels = width * height; // Total pixels in the image
broadcastLog(`图像位置: [(${xL}, ${yL}), (${xR}, ${yR})]`);
broadcastLog(`总像素数: ${totalPixels}`);
const getPixelAt = (x, y) => {
const index = (y * width + x) * channels; // 每个像素占 channels 个字节(RGB/RGBA)
if (channels === 4) {
return { r: pixels[index], g: pixels[index + 1], b: pixels[index + 2], a: pixels[index + 3] };
} else {
return { r: pixels[index], g: pixels[index + 1], b: pixels[index + 2] };
}
};
function calculateColorDistance(color1, color2) {
// 计算三维距离
if (("a" in color1 && color1.a === 0) || ("a" in color2 && color2.a === 0)) {
return 0;
}
const r1 = color1.r, g1 = color1.g, b1 = color1.b;
const r2 = color2.r, g2 = color2.g, b2 = color2.b;
const distance = Math.sqrt(Math.pow(r1 - r2, 2) + Math.pow(g1 - g2, 2) + Math.pow(b1 - b2, 2));
return distance;
}
function isSame(realPixel, correctPixel) {
return calculateColorDistance(realPixel, correctPixel) <= info.sim;
}
async function loadBoard() {
// 加载绘版上的错误像素
for (let y = 0; y < 600; y++) {
for (let x = 0; x < 1000; x++) {
if (x < xL || x > xR) continue;
if (y < yL || y > yR) continue;
const pixel = board[y][x];
const realPixel = getPixelAt(x - xL, y - yL);
if (isSame(pixel, realPixel)) continue;
pointQueue.push({ x: x - xL, y: y - yL, rx: y, ry: x });
}
}
}
// Set up priority comparator based on strategy
function updatePriorityComparator() {
if (info.strategy.priority === 'alpha' && channels === 4) {
pointQueue.setComparator((a, b) => getPixelAt(b.x, b.y).a - getPixelAt(a.x, a.y).a);
} else {
pointQueue.setComparator(null); // No priority, FIFO-like
}
}
processAttack = async (x, y, r, g, b) => {
if (x < xL || x > xR) return;
if (y < yL || y > yR) return;
let realX = x - startX, realY = y - startY;
const realPixel = { r, g, b };
const correctPixel = getPixelAt(realX, realY);
if (isSame(realPixel, correctPixel)) {
return;
}
attackCnt++;
// Add to queue with deduplication
pointQueue.push({ x: realX, y: realY, rx: y, ry: x });
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function processStop() {
queuePos = 0;
queueTotal = 0;
isDrawing = false; // 停止任务
info.imagePath = null;
info.startX = null;
info.startY = null;
broadcastLog('绘画任务已停止。');
}
const drawTask = async () => {
if (stopDrawing) {
processStop();
return;
}
// Initial load
await loadBoard();
updatePriorityComparator();
broadcastLog(`队列初始化完成,目前队列长度: ${pointQueue.length}。`);
// Continuous drawing loop
while (!stopDrawing) {
// Update progress: totalPixels - remaining queue size
queueTotal = totalPixels;
queuePos = totalPixels - pointQueue.length;
if (pointQueue.isEmpty()) {
// No pixels to paint, wait a bit
broadcastLog(`队列为空,等待中...`);
await delay(3000);
continue;
}
// Pop the highest priority item from the heap
const pos = pointQueue.pop();
if (!pos) continue;
const pixel = getPixelAt(pos.x, pos.y);
// Check if still needs painting
if (!isSame(board[pos.rx][pos.ry], pixel)) {
const tk = await getNextToken();
paint(tk.uid, tk.token, pixel.r, pixel.g, pixel.b, pos.x + startX, pos.y + startY);
}
}
processStop();
};
drawTask();
}
// 启动绘画任务 API
app.post('/api/start-draw', async (req, res) => {
const { imageName, startX, startY } = req.body;
if (ws.readyState !== WebSocket.OPEN || !status) {
return res.status(400).send('WebSocket 未连接');
}
if (isDrawing) {
return res.status(400).send('存在正在执行的绘画任务。');
}
if (fTokens.length == 0) {
return res.status(400).send('请先加载 Token。');
}
const imagePath = path.join(UPLOAD_DIR, imageName);
if (!fs.existsSync(imagePath)) {
return res.status(404).send('找不到对应图像。');
}
lstPath = imagePath, lstStartX = startX, lstStartY = startY;
try {
await SdrawTask(imagePath, startX, startY);
res.json({ message: '绘画任务已启动。' });
} catch (e) {
return res.status(500).send('内部服务器错误。');
}
});
// 停止绘画任务 API
app.post('/api/stop-draw', (req, res) => {
if (!isDrawing) {
return res.status(400).send('没有正在执行的绘画任务。');
}
processAttack = null;
stopDrawing = true;
pointQueue.clear();
res.json({ message: '正在停止绘画任务。' });
});
server.listen(PORT, () => {
console.log(`日志 WS 地址: ws://localhost:${PORT}`);
});
app.listen(WEBPORT, () => {
console.log(`Web 地址: http://localhost:${WEBPORT}`);
});
reportServer.listen(DRAWPORT, () => {
console.log(`信息 WS 地址: ws://localhost:${DRAWPORT}`);
});