版本比较
冬日绘板脚本
正文
增加 121 行删除 121 行
63 行未改动64656667686970717273747576777879808182838485862 行未改动89909192939495969798995 行未改动10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313425 行未改动16016116216316416516616716816917038 行未改动2092102112122132142152162172182192202214 行未改动2262272282292302312322332342352362372382392402412425 行未改动24824925025125225325425525625725825926026126226326419 行未改动2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193209 行未改动3303313323333343353363373383393403413423433443455 行未改动35135235335435535635735835937 行未改动39739839940040140240340440518 行未改动4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534 行未改动4584594604614624634644654664674684694704714724734744752 行未改动47847948048148248348448548648748848949049149249349449549649749849950050150250350450595 行未改动60160260360460560660760860961061161261361461517 行未改动63363463563663763863964064164264364464564664764864965065165265365465565642 行未改动69970070170270370470570670718 行未改动72672772872973073173273373411 行未改动74674774874975075175275375475575675775875976076176276376476576676776813 行未改动78278378478578678778878979016 行未改动8078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388392 行未改动84284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389417 行未改动9129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589594 行未改动96496596696796896997097197222 行未改动9959969979989991000100110021003100410051006100710082 行未改动10111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105820 行未改动107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311047 行未改动1112111311141115111611171118111911204 行未改动11251126112711281129113011311132113325 行未改动11591160116111621163116411651166116715 行未改动11831184118511861187118811891190119123 行未改动12151216121712181219122012211222122317 行未改动124112421243124412451246124712481249125012511252125312541255125612573 行未改动1261126212631264126512661267126812691270127112721273127412751276127719 行未改动12971298129913001301130213031304130516 行未改动13221323132413251326132713281329133082 行未改动14131414141514161417141814191420142114221423142414251426142714281429143014311432143314346 行未改动14411442144314441445144614471448144915 行未改动14651466146714681469147014711472147317 行未改动149114921493149414951496149714981499150015019 行未改动15111512151315141515151615171518151915201521152215231524152515261527152815296 行未改动153615371538153915401541154215431544154515461547154815491550155115521553155415555 行未改动63 行未改动this.repairWorker.on('message', (message) => {this.handleRepairMessage(message);});this.repairWorker.on('error', (error) => {console.error('修复工作线程错误:', error);});this.repairWorker.on('exit', (code) => {if (code !== 0) {console.log(`修复工作线程异常退出: ${code},5秒后重启`);setTimeout(() => this.init(), 5000);}});// 定时批量处理修复队列setInterval(() => this.processRepairBatch(), this.batchInterval);} catch (error) {console.error('修复管理器初始化失败:', error);setTimeout(() => this.init(), 5000);}2 行未改动// 添加需要修复的像素addRepairPixel(x, y, currentR, currentG, currentB) {const pixelKey = `${x},${y}`;const expected = this.controller.expectedPixels.get(pixelKey);if (!expected) return;// 检查颜色是否确实需要修复if (expected.r === currentR && expected.g === currentG && expected.b === currentB) {return;}5 行未改动g: expected.g,b: expected.b,timestamp: Date.now()});this.repairStats.totalQueued++;}// 批量处理修复任务processRepairBatch(batch) {if (!batch || !Array.isArray(batch) || batch.length === 0) return;console.log(`🔧 修复工作线程处理 ${batch.length} 个修复像素`);let processed = 0;for (const pixel of batch) {// 验证像素数据if (!pixel || typeof pixel.x !== 'number' || typeof pixel.y !== 'number') {continue;}const paintData = this.createPaintData(pixel);if (paintData) {this.appendData(paintData);processed++;// 限制单次处理数量,避免堆积if (processed >= this.batchControl.maxBatchSize) {break;}25 行未改动reportStats() {const now = Date.now();const elapsed = (now - this.repairStats.lastReportTime) / 1000;const rate = elapsed > 0 ? (this.repairStats.totalSent / elapsed).toFixed(1) : 0;console.log(`🛠️ 修复统计: 队列 ${this.pendingRepairs.size} | 累计发送 ${this.repairStats.totalSent} | 速率 ${rate}/秒`);this.repairStats.lastReportTime = now;this.repairStats.totalSent = 0;}38 行未改动if (now - this.globalRateLimit.lastResetTime >= 1000) {this.globalRateLimit.currentSecondPackets = 0;this.globalRateLimit.lastResetTime = now;}if (this.globalRateLimit.currentSecondPackets >= this.globalRateLimit.maxTotalPacketsPerSecond) {return false;}this.globalRateLimit.currentSecondPackets++;return true;}4 行未改动const totalSent = this.performanceStats.paintedPixels;const totalPixels = this.performanceStats.totalPixels;const progress = totalPixels > 0 ? (totalSent / totalPixels * 100).toFixed(2) : 0;const pixelsPerSecond = totalSent > 0 ? (totalSent / elapsed).toFixed(1) : 0;console.log(`🎯 全局进度: ${totalSent}/${totalPixels} (${progress}%) | ${pixelsPerSecond} 像素/秒 | 运行: ${Math.floor(elapsed)}秒`);// 如果进度长时间没有变化,可能是连接问题if (this.lastProgress === totalSent && elapsed > 30) {console.log(`⚠️ 进度停滞,检查连接状态`);}this.lastProgress = totalSent;}, 10000); // 每10秒报告一次}async loadImage() {5 行未改动console.log("正在极速加载图片...");const image = sharp(CONFIG.imagePath);const metadata = await image.metadata();const [scaledWidth, scaledHeight] = [Math.floor(metadata.width * CONFIG.scale),Math.floor(metadata.height * CONFIG.scale)];const resizedImage = image.resize(scaledWidth, scaledHeight).removeAlpha();const pixels = await resizedImage.raw().toBuffer();this.imageData = {width: scaledWidth,height: scaledHeight,channels: Math.min(metadata.channels, 3),19 行未改动const boardHeight = 600;// 如果目标坐标为负数或超出范围,自动调整到合适位置let startX = CONFIG.targetX;let startY = CONFIG.targetY;// 确保图片不会超出画板边界if (startX < 0) startX = 0;if (startY < 0) startY = 0;if (startX + width > boardWidth) startX = boardWidth - width;if (startY + height > boardHeight) startY = boardHeight - height;// 如果图片太大,从(0,0)开始绘制if (width > boardWidth || height > boardHeight) {startX = 0;startY = 0;console.warn(`图片尺寸 ${width}x${height} 超出画板范围 ${boardWidth}x${boardHeight},将从(0,0)开始绘制`);}console.log(`实际绘制起始坐标: (${startX}, ${startY}), 图片尺寸: ${width}x${height}`);for (let y = 0; y < height; y++) {for (let x = 0; x < width; x++) {const index = (y * width + x) * channels;const r = pixels[index];const g = pixels[index + 1];const b = pixels[index + 2];// 跳过白色像素// if (r === 255 && g === 255 && b === 255) continue;const targetX = startX + x;const targetY = startY + y;// 确保目标坐标在画板范围内if (targetX >= 0 && targetX < boardWidth && targetY >= 0 && targetY < boardHeight) {allPixels.push({ x: targetX, y: targetY, r, g, b });this.expectedPixels.set(`${targetX},${targetY}`, { x: targetX, y: targetY, r, g, b });9 行未改动// 将像素平均分配给工作线程distributePixelsToWorkers(allPixels) {const workerCount = CONFIG.maxThreads;const pixelsPerWorker = Math.ceil(allPixels.length / workerCount);console.log(`每个工作线程处理约 ${pixelsPerWorker} 个像素`);for (let i = 0; i < workerCount; i++) {const startIdx = i * pixelsPerWorker;const endIdx = Math.min(startIdx + pixelsPerWorker, allPixels.length);const workerPixels = allPixels.slice(startIdx, endIdx);const worker = this.workers.get(i);if (worker) {worker.postMessage({type: 'assignPixels',5 行未改动}async startWorkers() {const workerCount = CONFIG.maxThreads;for (let i = 0; i < workerCount; i++) {const worker = new Worker(new URL(import.meta.url), {workerData: {workerId: i,37 行未改动switch (message.type) {case 'ready':this.workerReadyCount++;console.log(`工作线程 ${workerId} 就绪`);if (this.workerReadyCount === this.workers.size) {const allPixels = this.prepareAllPixels();this.distributePixelsToWorkers(allPixels);this.startPerformanceMonitor();18 行未改动case 'needRepair':this.repairManager.addRepairQueue(message.x, message.y, message.r, message.g, message.b);break;case 'pixelOverwritten':this.repairManager.addRepairPixel(message.x, message.y, message.r, message.g, message.b);break;}}addToRepairQueue(x, y, currentR, currentG, currentB) {const pixelKey = `${x},${y}`;const expected = this.expectedPixels.get(pixelKey);if (expected && (expected.r !== currentR || expected.g !== currentG || expected.b !== currentB)) {const existingIndex = this.repairQueue.findIndex(p => p.x === x && p.y === y);if (existingIndex === -1) {this.repairQueue.push({x, y,r: expected.r,g: expected.g,b: expected.b,timestamp: Date.now()});// 如果修复队列较大,分配给工作线程处理if (this.repairQueue.length >= CONFIG.repairBatchSize) {this.distributeRepairTasks();}4 行未改动distributeRepairTasks() {if (this.repairQueue.length === 0) return;const repairBatch = this.repairQueue.splice(0, CONFIG.repairBatchSize);// 平均分配给所有工作线程const workerCount = this.workers.size;const repairPerWorker = Math.ceil(repairBatch.length / workerCount);for (let i = 0; i < workerCount; i++) {const startIdx = i * repairPerWorker;const endIdx = Math.min(startIdx + repairPerWorker, repairBatch.length);const workerRepair = repairBatch.slice(startIdx, endIdx);if (workerRepair.length > 0) {const worker = this.workers.get(i);if (worker) {worker.postMessage({2 行未改动});}}}console.log(`分配了 ${repairBatch.length} 个修复任务给工作线程`);}startPerformanceMonitor() {// setInterval(() => {// const now = Date.now();// const elapsed = (now - this.performanceStats.startTime) / 1000;// const pixelsPerSecond = this.performanceStats.paintedPixels / elapsed;// const progress = this.performanceStats.totalPixels > 0// ? (this.performanceStats.paintedPixels / this.performanceStats.totalPixels * 100).toFixed(2)// : 0;// console.log(`🚀 性能统计: ${this.performanceStats.paintedPixels}/${this.performanceStats.totalPixels} 像素 (${progress}%) | ${pixelsPerSecond.toFixed(1)} 像素/秒 | 修复: ${this.performanceStats.repairedPixels} | 修复队列: ${this.repairQueue.length}`);// }, 3000);}async main() {console.log("🚀 LGS Paintboard 极致性能多线程客户端启动");const imageLoaded = await this.loadImage();if (!imageLoaded) return;await this.startWorkers();95 行未改动return new Promise((resolve) => {try {console.log(`工作线程 ${this.workerId} 正在连接...`);this.ws = new WebSocket(this.config.wsUrl, {perMessageDeflate: false, // 禁用压缩避免协议问题maxPayload: 30000, // 增加最大载荷大小skipUTF8Validation: false // 确保UTF8验证});this.ws.binaryType = "arraybuffer";this.ws.onopen = () => {console.log(`工作线程 ${this.workerId} 连接成功`);17 行未改动this.ws.onclose = (event) => {this.isConnected = false;const reason = event.reason || "Unknown";const code = event.code || "Unknown";console.log(`工作线程 ${this.workerId} 连接关闭 (${code}: ${reason}),0.1秒后重连`);if (this.sendInterval) {clearInterval(this.sendInterval);this.sendInterval = null;}// 根据错误代码调整重连延迟let reconnectDelay = 1000;if (code === 1008) { // 策略限制reconnectDelay = 5000;} else if (code === 1011) { // 服务器错误reconnectDelay = 3000;}setTimeout(() => {this.connect().catch(console.error);}, reconnectDelay);};42 行未改动const colorR = dataView.getUint8(offset + 4);const colorG = dataView.getUint8(offset + 5);const colorB = dataView.getUint8(offset + 6);offset += 7;// 实时检测覆盖并通知修复管理器parentPort.postMessage({type: 'pixelOverwritten',x, y, r: colorR, g: colorG, b: colorB18 行未改动const code = dataView.getUint8(offset + 4);offset += 5;this.handlePaintResult(id, code);break;default:console.log(`工作线程 ${this.workerId} 未知消息类型: 0x${type.toString(16)}`);break;}11 行未改动if (callback) {this.pendingCallbacks.delete(id);callback(code);}if (code === 0xef) {// 绘画成功this.performanceStats.pixelsAccepted++;parentPort.postMessage({type: 'pixelAccepted',workerId: this.workerId});} else if (code === 0xee) {// 冷却中,不需要修复console.log(`⏸️ 工作线程 ${this.workerId} 像素冷却中`);} else {// 其他错误console.log(`❌ 工作线程 ${this.workerId} 绘画失败: 0x${code.toString(16)}`);parentPort.postMessage({type: 'pixelFailed',workerId: this.workerId,code: code});13 行未改动createPaintData(pixel) {const id = (this.paintId++) % 4294967296;const tokenBytes = new Uint8Array(16);const hexToken = this.config.token.replace(/-/g, '');for (let j = 0; j < 32; j += 2) {tokenBytes[j / 2] = parseInt(hexToken.substr(j, 2), 16);}16 行未改动// 预处理所有分配像素的数据包,支持拆分成多个批次preprocessAllPixels(pixels) {console.log(`工作线程 ${this.workerId} 预处理 ${pixels.length} 个像素数据包`);this.batchManager.batches = [];this.batchManager.currentBatchIndex = 0;// 增加批次大小,减少批次数量const batchSize = Math.min(30000, this.batchManager.maxPixelsPerBatch); // 增加到30000const batchCount = Math.ceil(pixels.length / batchSize);console.log(`工作线程 ${this.workerId} 将拆分为 ${batchCount} 个批次,每批 ${batchSize} 像素`);for (let i = 0; i < batchCount; i++) {const startIdx = i * batchSize;const endIdx = Math.min(startIdx + batchSize, pixels.length);const batchPixels = pixels.slice(startIdx, endIdx);const batchData = [];for (const pixel of batchPixels) {const paintData = this.createPaintData(pixel);batchData.push(paintData);}this.batchManager.batches.push(batchData);}console.log(`工作线程 ${this.workerId} 预处理完成,共 ${this.batchManager.batches.length} 个批次`);return this.batchManager.batches;}2 行未改动if (this.totalSize + data.length > 30000) {// 如果超过限制,先发送当前数据this.sendCurrentChunks();}this.chunks.push(data);this.totalSize += data.length;}// 检查是否被速率限制isRateLimited() {const now = Date.now();const timeSinceSecondStart = now - this.rateLimiter.currentSecondStart;// 如果已经过了1秒,重置计数器if (timeSinceSecondStart >= 1000) {this.rateLimiter.currentSecondStart = now;this.rateLimiter.packetsSentInCurrentSecond = 0;this.rateLimiter.isRateLimited = false;return false;}// 只在真正达到限制时才限制if (this.rateLimiter.packetsSentInCurrentSecond >= this.rateLimiter.maxPacketsPerSecond) {this.rateLimiter.isRateLimited = true;return true;}return false;}// 更新速率限制计数updateRateLimit() {const now = Date.now();// 性能监控this.performanceMonitor.packetsSinceLastLog++;this.performanceMonitor.totalPacketsSent++;// 每5秒输出一次实际发送速率if (now - this.performanceMonitor.lastLogTime > 5000) {const rate = (this.performanceMonitor.packetsSinceLastLog / 5).toFixed(1);console.log(`工作线程 ${this.workerId} 实际发送速率: ${rate} 包/秒, 累计: ${this.performanceMonitor.totalPacketsSent}`);this.performanceMonitor.lastLogTime = now;this.performanceMonitor.packetsSinceLastLog = 0;}const timeSinceSecondStart = now - this.rateLimiter.currentSecondStart;// 如果已经过了1秒,重置计数器if (timeSinceSecondStart >= 1000) {this.rateLimiter.currentSecondStart = now;this.rateLimiter.packetsSentInCurrentSecond = 1;17 行未改动}getMergedData() {if (this.chunks.length === 0) return null;const result = new Uint8Array(this.totalSize);let offset = 0;for (const chunk of this.chunks) {result.set(chunk, offset);offset += chunk.length;}this.chunks = [];this.totalSize = 0;return result;}// 发送当前累积的数据块sendCurrentChunks() {if (this.chunks.length === 0) return;// 严格控制数据包大小不超过30KB(留出安全余量)const MAX_PAYLOAD_SIZE = 30000;if (this.totalSize > MAX_PAYLOAD_SIZE) {// 如果数据太大,分批发送const batches = [];let currentBatch = [];let currentSize = 0;for (const chunk of this.chunks) {if (currentSize + chunk.length > MAX_PAYLOAD_SIZE && currentBatch.length > 0) {batches.push(currentBatch);currentBatch = [];currentSize = 0;}currentBatch.push(chunk);currentSize += chunk.length;}if (currentBatch.length > 0) {batches.push(currentBatch);}// 发送所有批次for (const batch of batches) {const data = this.mergeChunks(batch);if (data && data.length > 0) {4 行未改动console.error(`发送失败: ${error.message}`);}}}this.chunks = [];this.totalSize = 0;} else {// 正常发送22 行未改动startSending() {this.sendInterval = setInterval(() => {this.processQueuedPackets();// 检查数据大小,如果接近32KB就发送if (this.totalSize >= 30000) { // 在接近32KB时提前发送this.sendCurrentChunks();}// 常规发送逻辑if (this.isConnected && this.chunks.length > 0) {this.sendCurrentChunks();}2 行未改动// 持续发送预处理的像素数据,支持多批次依次发送startContinuousPainting(preprocessedBatches) {if (!preprocessedBatches || preprocessedBatches.length === 0) return;console.log(`🚀 工作线程 ${this.workerId} 启动: ${this.performanceStats.totalPixels}像素`);this.batchManager.isProcessing = true;const sendBatch = () => {if (!this.isConnected || !this.batchManager.isProcessing) return;const currentBatch = this.batchManager.batches[this.batchManager.currentBatchIndex];if (!currentBatch || currentBatch.length === 0) {this.switchToNextBatch();return;}let sentCount = 0;const maxToSend = Math.min(100, currentBatch.length); // 减少单次发送量for (let i = 0; i < maxToSend; i++) {if (this.isRateLimited()) {break;}const pixelData = currentBatch[i];const pixelKey = `${pixelData[1]},${pixelData[2]}`; // x,y 作为唯一标识// 避免重复发送同一像素if (!this.performanceStats.uniquePixelsSent.has(pixelKey)) {this.appendData(pixelData);this.performanceStats.uniquePixelsSent.add(pixelKey);this.performanceStats.pixelsSent++;sentCount++;}}currentBatch.splice(0, maxToSend); // 移除已处理的像素if (currentBatch.length === 0) {this.switchToNextBatch();}// 实时进度显示if (sentCount > 0) {const progress = (this.performanceStats.pixelsSent / this.performanceStats.totalPixels * 100).toFixed(1);console.log(`📦 工作线程 ${this.workerId}: ${this.performanceStats.pixelsSent}/${this.performanceStats.totalPixels} (${progress}%)`);20 行未改动this.performanceMonitor.lastLogTime = Date.now();this.performanceMonitor.packetsSinceLastLog = 0;}, 5000);}// 切换到下一个批次switchToNextBatch() {if (this.batchManager.batches.length === 0) return;const oldIndex = this.batchManager.currentBatchIndex;this.batchManager.currentBatchIndex = (this.batchManager.currentBatchIndex + 1) % this.batchManager.batches.length;this.performanceStats.batchesCompleted++;// 只有当所有批次都完成时才记录if (this.batchManager.currentBatchIndex === 0) {const elapsed = (Date.now() - this.performanceStats.startTime) / 1000;const pixelsPerSecond = (this.performanceStats.pixelsSent / elapsed).toFixed(1);const progress = (this.performanceStats.pixelsSent / this.performanceStats.totalPixels * 100).toFixed(1);console.log(`🔄 工作线程 ${this.workerId} 完成一轮: ${this.performanceStats.pixelsSent}/${this.performanceStats.totalPixels} (${progress}%) | ${pixelsPerSecond} 像素/秒`);// 如果已经发送完所有像素,停止发送if (this.performanceStats.pixelsSent >= this.performanceStats.totalPixels) {console.log(`✅ 工作线程 ${this.workerId} 完成所有像素发送`);this.batchManager.isProcessing = false;7 行未改动// 处理修复任务repairPixels(pixels) {console.log(`工作线程 ${this.workerId} 修复 ${pixels.length} 个像素`);for (const pixel of pixels) {const paintData = this.createPaintData(pixel);this.appendData(paintData);this.performance.pixelsRepaired++;4 行未改动// 主入口if (isMainThread) {const controller = new PaintBoardController();process.on('SIGINT', () => {console.log('正在关闭...');controller.shutdown();process.exit(0);25 行未改动batchesSent: 0,failedRepairs: 0,lastReportTime: Date.now()};// 修复线程的特殊设置this.batchControl = {maxBatchSize: 30000, // 更小的批次maxChunkSize: 30000, // 32KB限制15 行未改动async connectWebSocket() {return new Promise((resolve, reject) => {try {console.log('🔧 修复工作线程正在连接...');// 简化连接选项,避免兼容性问题this.ws = new WebSocket(this.config.wsUrl);this.ws.binaryType = "arraybuffer";23 行未改动this.ws.onclose = (event) => {clearTimeout(connectionTimeout);this.isConnected = false;console.log(`🔧 修复工作线程连接关闭 (${event.code}: ${event.reason || 'Unknown'})`);// 使用指数退避重连setTimeout(() => {this.connectWebSocket().catch(console.error);}, 5000);17 行未改动while (offset < buffer.byteLength) {// 确保有足够的数据读取类型if (offset >= buffer.byteLength) break;const type = dataView.getUint8(offset);offset += 1;switch (type) {case 0xfc: // Pingthis.sendPong();break;case 0xff: // 绘画结果if (offset + 5 <= buffer.byteLength) {const id = dataView.getUint32(offset, true);const code = dataView.getUint8(offset + 4);3 行未改动// 数据不完整,直接返回return;}break;case 0xfa: // 像素更新消息 - 修复线程可以忽略if (offset + 7 <= buffer.byteLength) {offset += 7; // 跳过像素数据} else {return;}break;default:// 对于未知类型,跳过但不报错break;}19 行未改动if (callback) {this.pendingCallbacks.delete(id);callback(code);}if (code === 0xef) {this.performance.totalRepaired++;} else if (code !== 0xee) {this.performance.failedRepairs++;16 行未改动try {const id = (this.paintId++) % 4294967296;const tokenBytes = new Uint8Array(16);const hexToken = this.config.token.replace(/-/g, '');// 严格验证 Tokenif (!hexToken || hexToken.length !== 32) {console.error('🔧 Token 格式错误');return null;82 行未改动}getMergedData() {if (this.chunks.length === 0) return null;try {const result = new Uint8Array(this.totalSize);let offset = 0;for (const chunk of this.chunks) {// 确保每个块都是 Uint8Arrayconst safeChunk = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);result.set(safeChunk, offset);offset += safeChunk.length;}console.log(`🔧 修复线程发送批次: ${this.chunks.length} 像素, ${this.totalSize} 字节`);this.chunks = [];this.totalSize = 0;return result;} catch (error) {6 行未改动// 发送当前累积的数据块sendCurrentChunks() {if (this.chunks.length === 0) return;const data = this.getMergedData();if (data && data.length > 0 && data.length <= this.batchControl.maxChunkSize) {try {this.ws.send(data);15 行未改动// 检查数据大小,如果接近32KB就发送if (this.totalSize >= 30000) { // 在接近32KB时提前发送this.sendCurrentChunks();}// 常规发送逻辑if (this.chunks.length > 0) {this.sendCurrentChunks();}17 行未改动if (!batch || batch.length === 0) return;// 限制修复批次大小const limitedBatch = batch;console.log(`🔧 修复工作线程处理 ${limitedBatch.length} 个修复像素`);let processed = 0;for (const pixel of limitedBatch) {const paintData = this.createPaintData(pixel);if (paintData) {9 行未改动}}const repairWorker = new RepairWorker();parentPort.on('message', (message) => {if (!message || !message.type) return;switch (message.type) {case 'repairBatch':if (message.pixels && Array.isArray(message.pixels)) {repairWorker.processRepairBatch(message.pixels);}break;case 'shutdown':console.log('🔧 修复工作线程收到关闭信号');if (repairWorker.ws) {repairWorker.ws.close();6 行未改动}});} else {const worker = new PaintBoardWorker();parentPort.on('message', (message) => {switch (message.type) {case 'assignPixels':const preprocessedData = worker.preprocessAllPixels(message.pixels);worker.startContinuousPainting(preprocessedData);break;case 'repairPixels':worker.repairPixels(message.pixels);break;case 'shutdown':if (worker.ws) worker.ws.close();if (worker.sendInterval) clearInterval(worker.sendInterval);process.exit(0);5 行未改动63 行未改动64656667686970717273747576777879808182838485862 行未改动89909192939495969798995 行未改动10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313425 行未改动16016116216316416516616716816917038 行未改动2092102112122132142152162172182192202214 行未改动2262272282292302312322332342352362372382392402412425 行未改动24824925025125225325425525625725825926026126226326419 行未改动2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193209 行未改动3303313323333343353363373383393403413423433443455 行未改动35135235335435535635735835937 行未改动39739839940040140240340440518 行未改动4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534 行未改动4584594604614624634644654664674684694704714724734744752 行未改动47847948048148248348448548648748848949049149249349449549649749849950050150250350450595 行未改动60160260360460560660760860961061161261361461517 行未改动63363463563663763863964064164264364464564664764864965065165265365465565642 行未改动69970070170270370470570670718 行未改动72672772872973073173273373411 行未改动74674774874975075175275375475575675775875976076176276376476576676776813 行未改动78278378478578678778878979016 行未改动8078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388392 行未改动84284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389417 行未改动9129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589594 行未改动96496596696796896997097197222 行未改动9959969979989991000100110021003100410051006100710082 行未改动10111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105820 行未改动107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311047 行未改动1112111311141115111611171118111911204 行未改动11251126112711281129113011311132113325 行未改动11591160116111621163116411651166116715 行未改动11831184118511861187118811891190119123 行未改动12151216121712181219122012211222122317 行未改动124112421243124412451246124712481249125012511252125312541255125612573 行未改动1261126212631264126512661267126812691270127112721273127412751276127719 行未改动12971298129913001301130213031304130516 行未改动13221323132413251326132713281329133082 行未改动14131414141514161417141814191420142114221423142414251426142714281429143014311432143314346 行未改动14411442144314441445144614471448144915 行未改动14651466146714681469147014711472147317 行未改动149114921493149414951496149714981499150015019 行未改动15111512151315141515151615171518151915201521152215231524152515261527152815296 行未改动153615371538153915401541154215431544154515461547154815491550155115521553155415555 行未改动63 行未改动this.repairWorker.on('message', (message) => {this.handleRepairMessage(message);});this.repairWorker.on('error', (error) => {console.error('修复工作线程错误:', error);});this.repairWorker.on('exit', (code) => {if (code !== 0) {console.log(`修复工作线程异常退出: ${code},5秒后重启`);setTimeout(() => this.init(), 5000);}});// 定时批量处理修复队列setInterval(() => this.processRepairBatch(), this.batchInterval);} catch (error) {console.error('修复管理器初始化失败:', error);setTimeout(() => this.init(), 5000);}2 行未改动// 添加需要修复的像素addRepairPixel(x, y, currentR, currentG, currentB) {const pixelKey = `${x},${y}`;const expected = this.controller.expectedPixels.get(pixelKey);if (!expected) return;// 检查颜色是否确实需要修复if (expected.r === currentR && expected.g === currentG && expected.b === currentB) {return;}5 行未改动g: expected.g,b: expected.b,timestamp: Date.now()});this.repairStats.totalQueued++;}// 批量处理修复任务processRepairBatch(batch) {if (!batch || !Array.isArray(batch) || batch.length === 0) return;console.log(`🔧 修复工作线程处理 ${batch.length} 个修复像素`);let processed = 0;for (const pixel of batch) {// 验证像素数据if (!pixel || typeof pixel.x !== 'number' || typeof pixel.y !== 'number') {continue;}const paintData = this.createPaintData(pixel);if (paintData) {this.appendData(paintData);processed++;// 限制单次处理数量,避免堆积if (processed >= this.batchControl.maxBatchSize) {break;}25 行未改动reportStats() {const now = Date.now();const elapsed = (now - this.repairStats.lastReportTime) / 1000;const rate = elapsed > 0 ? (this.repairStats.totalSent / elapsed).toFixed(1) : 0;console.log(`🛠️ 修复统计: 队列 ${this.pendingRepairs.size} | 累计发送 ${this.repairStats.totalSent} | 速率 ${rate}/秒`);this.repairStats.lastReportTime = now;this.repairStats.totalSent = 0;}38 行未改动if (now - this.globalRateLimit.lastResetTime >= 1000) {this.globalRateLimit.currentSecondPackets = 0;this.globalRateLimit.lastResetTime = now;}if (this.globalRateLimit.currentSecondPackets >= this.globalRateLimit.maxTotalPacketsPerSecond) {return false;}this.globalRateLimit.currentSecondPackets++;return true;}4 行未改动const totalSent = this.performanceStats.paintedPixels;const totalPixels = this.performanceStats.totalPixels;const progress = totalPixels > 0 ? (totalSent / totalPixels * 100).toFixed(2) : 0;const pixelsPerSecond = totalSent > 0 ? (totalSent / elapsed).toFixed(1) : 0;console.log(`🎯 全局进度: ${totalSent}/${totalPixels} (${progress}%) | ${pixelsPerSecond} 像素/秒 | 运行: ${Math.floor(elapsed)}秒`);// 如果进度长时间没有变化,可能是连接问题if (this.lastProgress === totalSent && elapsed > 30) {console.log(`⚠️ 进度停滞,检查连接状态`);}this.lastProgress = totalSent;}, 10000); // 每10秒报告一次}async loadImage() {5 行未改动console.log("正在极速加载图片...");const image = sharp(CONFIG.imagePath);const metadata = await image.metadata();const [scaledWidth, scaledHeight] = [Math.floor(metadata.width * CONFIG.scale),Math.floor(metadata.height * CONFIG.scale)];const resizedImage = image.resize(scaledWidth, scaledHeight).removeAlpha();const pixels = await resizedImage.raw().toBuffer();this.imageData = {width: scaledWidth,height: scaledHeight,channels: Math.min(metadata.channels, 3),19 行未改动const boardHeight = 600;// 如果目标坐标为负数或超出范围,自动调整到合适位置let startX = CONFIG.targetX;let startY = CONFIG.targetY;// 确保图片不会超出画板边界if (startX < 0) startX = 0;if (startY < 0) startY = 0;if (startX + width > boardWidth) startX = boardWidth - width;if (startY + height > boardHeight) startY = boardHeight - height;// 如果图片太大,从(0,0)开始绘制if (width > boardWidth || height > boardHeight) {startX = 0;startY = 0;console.warn(`图片尺寸 ${width}x${height} 超出画板范围 ${boardWidth}x${boardHeight},将从(0,0)开始绘制`);}console.log(`实际绘制起始坐标: (${startX}, ${startY}), 图片尺寸: ${width}x${height}`);for (let y = 0; y < height; y++) {for (let x = 0; x < width; x++) {const index = (y * width + x) * channels;const r = pixels[index];const g = pixels[index + 1];const b = pixels[index + 2];// 跳过白色像素// if (r === 255 && g === 255 && b === 255) continue;const targetX = startX + x;const targetY = startY + y;// 确保目标坐标在画板范围内if (targetX >= 0 && targetX < boardWidth && targetY >= 0 && targetY < boardHeight) {allPixels.push({ x: targetX, y: targetY, r, g, b });this.expectedPixels.set(`${targetX},${targetY}`, { x: targetX, y: targetY, r, g, b });9 行未改动// 将像素平均分配给工作线程distributePixelsToWorkers(allPixels) {const workerCount = CONFIG.maxThreads;const pixelsPerWorker = Math.ceil(allPixels.length / workerCount);console.log(`每个工作线程处理约 ${pixelsPerWorker} 个像素`);for (let i = 0; i < workerCount; i++) {const startIdx = i * pixelsPerWorker;const endIdx = Math.min(startIdx + pixelsPerWorker, allPixels.length);const workerPixels = allPixels.slice(startIdx, endIdx);const worker = this.workers.get(i);if (worker) {worker.postMessage({type: 'assignPixels',5 行未改动}async startWorkers() {const workerCount = CONFIG.maxThreads;for (let i = 0; i < workerCount; i++) {const worker = new Worker(new URL(import.meta.url), {workerData: {workerId: i,37 行未改动switch (message.type) {case 'ready':this.workerReadyCount++;console.log(`工作线程 ${workerId} 就绪`);if (this.workerReadyCount === this.workers.size) {const allPixels = this.prepareAllPixels();this.distributePixelsToWorkers(allPixels);this.startPerformanceMonitor();18 行未改动case 'needRepair':this.repairManager.addRepairQueue(message.x, message.y, message.r, message.g, message.b);break;case 'pixelOverwritten':this.repairManager.addRepairPixel(message.x, message.y, message.r, message.g, message.b);break;}}addToRepairQueue(x, y, currentR, currentG, currentB) {const pixelKey = `${x},${y}`;const expected = this.expectedPixels.get(pixelKey);if (expected && (expected.r !== currentR || expected.g !== currentG || expected.b !== currentB)) {const existingIndex = this.repairQueue.findIndex(p => p.x === x && p.y === y);if (existingIndex === -1) {this.repairQueue.push({x, y,r: expected.r,g: expected.g,b: expected.b,timestamp: Date.now()});// 如果修复队列较大,分配给工作线程处理if (this.repairQueue.length >= CONFIG.repairBatchSize) {this.distributeRepairTasks();}4 行未改动distributeRepairTasks() {if (this.repairQueue.length === 0) return;const repairBatch = this.repairQueue.splice(0, CONFIG.repairBatchSize);// 平均分配给所有工作线程const workerCount = this.workers.size;const repairPerWorker = Math.ceil(repairBatch.length / workerCount);for (let i = 0; i < workerCount; i++) {const startIdx = i * repairPerWorker;const endIdx = Math.min(startIdx + repairPerWorker, repairBatch.length);const workerRepair = repairBatch.slice(startIdx, endIdx);if (workerRepair.length > 0) {const worker = this.workers.get(i);if (worker) {worker.postMessage({2 行未改动});}}}console.log(`分配了 ${repairBatch.length} 个修复任务给工作线程`);}startPerformanceMonitor() {// setInterval(() => {// const now = Date.now();// const elapsed = (now - this.performanceStats.startTime) / 1000;// const pixelsPerSecond = this.performanceStats.paintedPixels / elapsed;// const progress = this.performanceStats.totalPixels > 0// ? (this.performanceStats.paintedPixels / this.performanceStats.totalPixels * 100).toFixed(2)// : 0;// console.log(`🚀 性能统计: ${this.performanceStats.paintedPixels}/${this.performanceStats.totalPixels} 像素 (${progress}%) | ${pixelsPerSecond.toFixed(1)} 像素/秒 | 修复: ${this.performanceStats.repairedPixels} | 修复队列: ${this.repairQueue.length}`);// }, 3000);}async main() {console.log("🚀 LGS Paintboard 极致性能多线程客户端启动");const imageLoaded = await this.loadImage();if (!imageLoaded) return;await this.startWorkers();95 行未改动return new Promise((resolve) => {try {console.log(`工作线程 ${this.workerId} 正在连接...`);this.ws = new WebSocket(this.config.wsUrl, {perMessageDeflate: false, // 禁用压缩避免协议问题maxPayload: 30000, // 增加最大载荷大小skipUTF8Validation: false // 确保UTF8验证});this.ws.binaryType = "arraybuffer";this.ws.onopen = () => {console.log(`工作线程 ${this.workerId} 连接成功`);17 行未改动this.ws.onclose = (event) => {this.isConnected = false;const reason = event.reason || "Unknown";const code = event.code || "Unknown";console.log(`工作线程 ${this.workerId} 连接关闭 (${code}: ${reason}),0.1秒后重连`);if (this.sendInterval) {clearInterval(this.sendInterval);this.sendInterval = null;}// 根据错误代码调整重连延迟let reconnectDelay = 1000;if (code === 1008) { // 策略限制reconnectDelay = 5000;} else if (code === 1011) { // 服务器错误reconnectDelay = 3000;}setTimeout(() => {this.connect().catch(console.error);}, reconnectDelay);};42 行未改动const colorR = dataView.getUint8(offset + 4);const colorG = dataView.getUint8(offset + 5);const colorB = dataView.getUint8(offset + 6);offset += 7;// 实时检测覆盖并通知修复管理器parentPort.postMessage({type: 'pixelOverwritten',x, y, r: colorR, g: colorG, b: colorB18 行未改动const code = dataView.getUint8(offset + 4);offset += 5;this.handlePaintResult(id, code);break;default:console.log(`工作线程 ${this.workerId} 未知消息类型: 0x${type.toString(16)}`);break;}11 行未改动if (callback) {this.pendingCallbacks.delete(id);callback(code);}if (code === 0xef) {// 绘画成功this.performanceStats.pixelsAccepted++;parentPort.postMessage({type: 'pixelAccepted',workerId: this.workerId});} else if (code === 0xee) {// 冷却中,不需要修复console.log(`⏸️ 工作线程 ${this.workerId} 像素冷却中`);} else {// 其他错误console.log(`❌ 工作线程 ${this.workerId} 绘画失败: 0x${code.toString(16)}`);parentPort.postMessage({type: 'pixelFailed',workerId: this.workerId,code: code});13 行未改动createPaintData(pixel) {const id = (this.paintId++) % 4294967296;const tokenBytes = new Uint8Array(16);const hexToken = this.config.token.replace(/-/g, '');for (let j = 0; j < 32; j += 2) {tokenBytes[j / 2] = parseInt(hexToken.substr(j, 2), 16);}16 行未改动// 预处理所有分配像素的数据包,支持拆分成多个批次preprocessAllPixels(pixels) {console.log(`工作线程 ${this.workerId} 预处理 ${pixels.length} 个像素数据包`);this.batchManager.batches = [];this.batchManager.currentBatchIndex = 0;// 增加批次大小,减少批次数量const batchSize = Math.min(30000, this.batchManager.maxPixelsPerBatch); // 增加到30000const batchCount = Math.ceil(pixels.length / batchSize);console.log(`工作线程 ${this.workerId} 将拆分为 ${batchCount} 个批次,每批 ${batchSize} 像素`);for (let i = 0; i < batchCount; i++) {const startIdx = i * batchSize;const endIdx = Math.min(startIdx + batchSize, pixels.length);const batchPixels = pixels.slice(startIdx, endIdx);const batchData = [];for (const pixel of batchPixels) {const paintData = this.createPaintData(pixel);batchData.push(paintData);}this.batchManager.batches.push(batchData);}console.log(`工作线程 ${this.workerId} 预处理完成,共 ${this.batchManager.batches.length} 个批次`);return this.batchManager.batches;}2 行未改动if (this.totalSize + data.length > 30000) {// 如果超过限制,先发送当前数据this.sendCurrentChunks();}this.chunks.push(data);this.totalSize += data.length;}// 检查是否被速率限制isRateLimited() {const now = Date.now();const timeSinceSecondStart = now - this.rateLimiter.currentSecondStart;// 如果已经过了1秒,重置计数器if (timeSinceSecondStart >= 1000) {this.rateLimiter.currentSecondStart = now;this.rateLimiter.packetsSentInCurrentSecond = 0;this.rateLimiter.isRateLimited = false;return false;}// 只在真正达到限制时才限制if (this.rateLimiter.packetsSentInCurrentSecond >= this.rateLimiter.maxPacketsPerSecond) {this.rateLimiter.isRateLimited = true;return true;}return false;}// 更新速率限制计数updateRateLimit() {const now = Date.now();// 性能监控this.performanceMonitor.packetsSinceLastLog++;this.performanceMonitor.totalPacketsSent++;// 每5秒输出一次实际发送速率if (now - this.performanceMonitor.lastLogTime > 5000) {const rate = (this.performanceMonitor.packetsSinceLastLog / 5).toFixed(1);console.log(`工作线程 ${this.workerId} 实际发送速率: ${rate} 包/秒, 累计: ${this.performanceMonitor.totalPacketsSent}`);this.performanceMonitor.lastLogTime = now;this.performanceMonitor.packetsSinceLastLog = 0;}const timeSinceSecondStart = now - this.rateLimiter.currentSecondStart;// 如果已经过了1秒,重置计数器if (timeSinceSecondStart >= 1000) {this.rateLimiter.currentSecondStart = now;this.rateLimiter.packetsSentInCurrentSecond = 1;17 行未改动}getMergedData() {if (this.chunks.length === 0) return null;const result = new Uint8Array(this.totalSize);let offset = 0;for (const chunk of this.chunks) {result.set(chunk, offset);offset += chunk.length;}this.chunks = [];this.totalSize = 0;return result;}// 发送当前累积的数据块sendCurrentChunks() {if (this.chunks.length === 0) return;// 严格控制数据包大小不超过30KB(留出安全余量)const MAX_PAYLOAD_SIZE = 30000;if (this.totalSize > MAX_PAYLOAD_SIZE) {// 如果数据太大,分批发送const batches = [];let currentBatch = [];let currentSize = 0;for (const chunk of this.chunks) {if (currentSize + chunk.length > MAX_PAYLOAD_SIZE && currentBatch.length > 0) {batches.push(currentBatch);currentBatch = [];currentSize = 0;}currentBatch.push(chunk);currentSize += chunk.length;}if (currentBatch.length > 0) {batches.push(currentBatch);}// 发送所有批次for (const batch of batches) {const data = this.mergeChunks(batch);if (data && data.length > 0) {4 行未改动console.error(`发送失败: ${error.message}`);}}}this.chunks = [];this.totalSize = 0;} else {// 正常发送22 行未改动startSending() {this.sendInterval = setInterval(() => {this.processQueuedPackets();// 检查数据大小,如果接近32KB就发送if (this.totalSize >= 30000) { // 在接近32KB时提前发送this.sendCurrentChunks();}// 常规发送逻辑if (this.isConnected && this.chunks.length > 0) {this.sendCurrentChunks();}2 行未改动// 持续发送预处理的像素数据,支持多批次依次发送startContinuousPainting(preprocessedBatches) {if (!preprocessedBatches || preprocessedBatches.length === 0) return;console.log(`🚀 工作线程 ${this.workerId} 启动: ${this.performanceStats.totalPixels}像素`);this.batchManager.isProcessing = true;const sendBatch = () => {if (!this.isConnected || !this.batchManager.isProcessing) return;const currentBatch = this.batchManager.batches[this.batchManager.currentBatchIndex];if (!currentBatch || currentBatch.length === 0) {this.switchToNextBatch();return;}let sentCount = 0;const maxToSend = Math.min(100, currentBatch.length); // 减少单次发送量for (let i = 0; i < maxToSend; i++) {if (this.isRateLimited()) {break;}const pixelData = currentBatch[i];const pixelKey = `${pixelData[1]},${pixelData[2]}`; // x,y 作为唯一标识// 避免重复发送同一像素if (!this.performanceStats.uniquePixelsSent.has(pixelKey)) {this.appendData(pixelData);this.performanceStats.uniquePixelsSent.add(pixelKey);this.performanceStats.pixelsSent++;sentCount++;}}currentBatch.splice(0, maxToSend); // 移除已处理的像素if (currentBatch.length === 0) {this.switchToNextBatch();}// 实时进度显示if (sentCount > 0) {const progress = (this.performanceStats.pixelsSent / this.performanceStats.totalPixels * 100).toFixed(1);console.log(`📦 工作线程 ${this.workerId}: ${this.performanceStats.pixelsSent}/${this.performanceStats.totalPixels} (${progress}%)`);20 行未改动this.performanceMonitor.lastLogTime = Date.now();this.performanceMonitor.packetsSinceLastLog = 0;}, 5000);}// 切换到下一个批次switchToNextBatch() {if (this.batchManager.batches.length === 0) return;const oldIndex = this.batchManager.currentBatchIndex;this.batchManager.currentBatchIndex = (this.batchManager.currentBatchIndex + 1) % this.batchManager.batches.length;this.performanceStats.batchesCompleted++;// 只有当所有批次都完成时才记录if (this.batchManager.currentBatchIndex === 0) {const elapsed = (Date.now() - this.performanceStats.startTime) / 1000;const pixelsPerSecond = (this.performanceStats.pixelsSent / elapsed).toFixed(1);const progress = (this.performanceStats.pixelsSent / this.performanceStats.totalPixels * 100).toFixed(1);console.log(`🔄 工作线程 ${this.workerId} 完成一轮: ${this.performanceStats.pixelsSent}/${this.performanceStats.totalPixels} (${progress}%) | ${pixelsPerSecond} 像素/秒`);// 如果已经发送完所有像素,停止发送if (this.performanceStats.pixelsSent >= this.performanceStats.totalPixels) {console.log(`✅ 工作线程 ${this.workerId} 完成所有像素发送`);this.batchManager.isProcessing = false;7 行未改动// 处理修复任务repairPixels(pixels) {console.log(`工作线程 ${this.workerId} 修复 ${pixels.length} 个像素`);for (const pixel of pixels) {const paintData = this.createPaintData(pixel);this.appendData(paintData);this.performance.pixelsRepaired++;4 行未改动// 主入口if (isMainThread) {const controller = new PaintBoardController();process.on('SIGINT', () => {console.log('正在关闭...');controller.shutdown();process.exit(0);25 行未改动batchesSent: 0,failedRepairs: 0,lastReportTime: Date.now()};// 修复线程的特殊设置this.batchControl = {maxBatchSize: 30000, // 更小的批次maxChunkSize: 30000, // 32KB限制15 行未改动async connectWebSocket() {return new Promise((resolve, reject) => {try {console.log('🔧 修复工作线程正在连接...');// 简化连接选项,避免兼容性问题this.ws = new WebSocket(this.config.wsUrl);this.ws.binaryType = "arraybuffer";23 行未改动this.ws.onclose = (event) => {clearTimeout(connectionTimeout);this.isConnected = false;console.log(`🔧 修复工作线程连接关闭 (${event.code}: ${event.reason || 'Unknown'})`);// 使用指数退避重连setTimeout(() => {this.connectWebSocket().catch(console.error);}, 5000);17 行未改动while (offset < buffer.byteLength) {// 确保有足够的数据读取类型if (offset >= buffer.byteLength) break;const type = dataView.getUint8(offset);offset += 1;switch (type) {case 0xfc: // Pingthis.sendPong();break;case 0xff: // 绘画结果if (offset + 5 <= buffer.byteLength) {const id = dataView.getUint32(offset, true);const code = dataView.getUint8(offset + 4);3 行未改动// 数据不完整,直接返回return;}break;case 0xfa: // 像素更新消息 - 修复线程可以忽略if (offset + 7 <= buffer.byteLength) {offset += 7; // 跳过像素数据} else {return;}break;default:// 对于未知类型,跳过但不报错break;}19 行未改动if (callback) {this.pendingCallbacks.delete(id);callback(code);}if (code === 0xef) {this.performance.totalRepaired++;} else if (code !== 0xee) {this.performance.failedRepairs++;16 行未改动try {const id = (this.paintId++) % 4294967296;const tokenBytes = new Uint8Array(16);const hexToken = this.config.token.replace(/-/g, '');// 严格验证 Tokenif (!hexToken || hexToken.length !== 32) {console.error('🔧 Token 格式错误');return null;82 行未改动}getMergedData() {if (this.chunks.length === 0) return null;try {const result = new Uint8Array(this.totalSize);let offset = 0;for (const chunk of this.chunks) {// 确保每个块都是 Uint8Arrayconst safeChunk = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);result.set(safeChunk, offset);offset += safeChunk.length;}console.log(`🔧 修复线程发送批次: ${this.chunks.length} 像素, ${this.totalSize} 字节`);this.chunks = [];this.totalSize = 0;return result;} catch (error) {6 行未改动// 发送当前累积的数据块sendCurrentChunks() {if (this.chunks.length === 0) return;const data = this.getMergedData();if (data && data.length > 0 && data.length <= this.batchControl.maxChunkSize) {try {this.ws.send(data);15 行未改动// 检查数据大小,如果接近32KB就发送if (this.totalSize >= 30000) { // 在接近32KB时提前发送this.sendCurrentChunks();}// 常规发送逻辑if (this.chunks.length > 0) {this.sendCurrentChunks();}17 行未改动if (!batch || batch.length === 0) return;// 限制修复批次大小const limitedBatch = batch;console.log(`🔧 修复工作线程处理 ${limitedBatch.length} 个修复像素`);let processed = 0;for (const pixel of limitedBatch) {const paintData = this.createPaintData(pixel);if (paintData) {9 行未改动}}const repairWorker = new RepairWorker();parentPort.on('message', (message) => {if (!message || !message.type) return;switch (message.type) {case 'repairBatch':if (message.pixels && Array.isArray(message.pixels)) {repairWorker.processRepairBatch(message.pixels);}break;case 'shutdown':console.log('🔧 修复工作线程收到关闭信号');if (repairWorker.ws) {repairWorker.ws.close();6 行未改动}});} else {const worker = new PaintBoardWorker();parentPort.on('message', (message) => {switch (message.type) {case 'assignPixels':const preprocessedData = worker.preprocessAllPixels(message.pixels);worker.startContinuousPainting(preprocessedData);break;case 'repairPixels':worker.repairPixels(message.pixels);break;case 'shutdown':if (worker.ws) worker.ws.close();if (worker.sendInterval) clearInterval(worker.sendInterval);process.exit(0);5 行未改动