版本比较
冬日绘板脚本
正文
增加 121 行删除 121 行
63 行未改动64656667686869707172727374757677787980818282838485862 行未改动899091929393949595969798995 行未改动10510610710810910911011111211311411511611711811811912012112212312412512512612712812913013013113213313425 行未改动16016116216316416416516616616716816917038 行未改动2092102112122132132142152162172172182192202214 行未改动2262272282292302302312322322332342352362372382382392402412425 行未改动24824925025125225225325425525625725725825926026026126226326419 行未改动2842852862872882882892902912922932942942952962972982993003013013023033033043053063073083093103103113123133133143153163163173183193209 行未改动3303313323333343343353363363373383393403413413423433443455 行未改动35135235335435535535635735835937 行未改动39739839940040140140240340440518 行未改动4244254264274284284294304314324334344354364374384384394404414424434444454454464474484494494504514524534 行未改动4584594604614624624634644654664664674684694704714714724734744752 行未改动47847948048148248248348448548648748848949049149149249349449449549649749849950050150150250350450595 行未改动60160260360460560560660760860961061161161261361461517 行未改动63363463563663763763863963964064164264364464464564664764864965065165265265365465565642 行未改动69970070170270370370470570670718 行未改动72672772872973073073173273373411 行未改动74674774874975075075175275375475475575675775875976076176276376476476576676776813 行未改动78278378478578678678778878979016 行未改动8078088098108118118128138148148158168178178188198198208218218228238248258268268278288298308318328328338348358358368378388392 行未改动84284384484584684684784884985085185285385485585585685785885986086186286386386486586686786886986987087187287387487587687687787887988088088188288388488588688788888888989089089189289389417 行未改动9129139149159169169179189199209219229239239249259269279289299309319329329339349359359369379389399409419419429439449459469479489499509519519529539549559559569579589594 行未改动96496596696796896896997097197222 行未改动99599699799899999910001001100210031004100410051006100710082 行未改动101110121013101410151015101610171017101810191019102010211022102210231024102510261027102810281029103010311031103210331034103510361036103710381039103910401041104210431044104510461047104810481049105010511052105310541054105510561057105820 行未改动107910801081108210831083108410851086108710871088108910901090109110921092109310941095109610971098109810991100110011011102110311047 行未改动11121113111411151116111611171118111911204 行未改动112511261127112811291129113011311132113325 行未改动115911601161116211631163116411651166116715 行未改动118311841185118611871187118811891190119123 行未改动121512161217121812191219122012211222122317 行未改动12411242124312441245124512461247124812491250125112521253125312541255125612573 行未改动126112621263126412651265126612671268126912701271127212731273127412751276127719 行未改动129712981299130013011301130213031304130516 行未改动132213231324132513261326132713281329133082 行未改动141314141415141614171417141814191420142114211422142314241425142614271428142814291430143014311432143314346 行未改动144114421443144414451445144614471448144915 行未改动146514661467146814691469147014711472147317 行未改动14911492149314941495149514961497149714981499150015019 行未改动15111512151315141515151515161517151815181519152015211522152315241525152515261527152815296 行未改动153615371538153915401540154115421543154415451546154715471548154915501551155115521553155415555 行未改动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, 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 // 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({ 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({ 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); // 增加到30000
const 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: // Ping this.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, '');
// 严格验证 Token if (!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) { // 确保每个块都是 Uint8Array const 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 行未改动