|
|
@@ -105,6 +105,26 @@
|
|
|
|
|
|
let activeScene = "forest";
|
|
|
let rafId = null;
|
|
|
+ let uploadedPhoto = null;
|
|
|
+ let photoFit = null;
|
|
|
+ let erasing = false;
|
|
|
+ const selectionStrokes = [];
|
|
|
+ const photoFile = document.getElementById("photoFile");
|
|
|
+ const photoReset = document.getElementById("photoReset");
|
|
|
+ const photoStatus = document.getElementById("photoStatus");
|
|
|
+ const objectTempInput = document.getElementById("objectTemp");
|
|
|
+ const objectTempOut = document.getElementById("objectTempOut");
|
|
|
+ const selectionTools = document.getElementById("thermalSelectionTools");
|
|
|
+ const eraseSelection = document.getElementById("eraseSelection");
|
|
|
+ const clearSelection = document.getElementById("clearSelection");
|
|
|
+ const detectObjectsBtn = document.getElementById("detectObjects");
|
|
|
+ const detectStatus = document.getElementById("detectStatus");
|
|
|
+ const detectedObjectsEl = document.getElementById("detectedObjects");
|
|
|
+ let detectorModel = null;
|
|
|
+ let autoDetections = [];
|
|
|
+ const maskCanvas = document.createElement("canvas");
|
|
|
+ maskCanvas.width = NV_W; maskCanvas.height = NV_H;
|
|
|
+ const maskCtx = maskCanvas.getContext("2d");
|
|
|
|
|
|
/* ---------- Утилиты ---------- */
|
|
|
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
|
@@ -142,6 +162,7 @@
|
|
|
|
|
|
function drawNV() {
|
|
|
const scene = scenes[activeScene];
|
|
|
+ if (uploadedPhoto) { drawUploadedNV(); return; }
|
|
|
|
|
|
nvCtx.fillStyle = "#010806";
|
|
|
nvCtx.fillRect(0, 0, NV_W, NV_H);
|
|
|
@@ -260,6 +281,7 @@
|
|
|
|
|
|
function drawThermal() {
|
|
|
const scene = scenes[activeScene];
|
|
|
+ if (uploadedPhoto) { drawUploadedThermal(); return; }
|
|
|
const ambient = parseFloat(ambientInput.value);
|
|
|
const span = parseFloat(spanInput.value);
|
|
|
const paletteName = paletteInput.value;
|
|
|
@@ -319,7 +341,6 @@
|
|
|
function onControlsChange() {
|
|
|
updateOutputs();
|
|
|
scheduleRender();
|
|
|
- renderPhotoSimulations();
|
|
|
}
|
|
|
|
|
|
/* ---------- Подписки ---------- */
|
|
|
@@ -347,85 +368,93 @@
|
|
|
}
|
|
|
|
|
|
|
|
|
- /* ---------- Симуляция на загружаемой фотографии ---------- */
|
|
|
- const photoFile = document.getElementById("photoFile");
|
|
|
- const photoReset = document.getElementById("photoReset");
|
|
|
- const photoStatus = document.getElementById("photoStatus");
|
|
|
- const photoNvCanvas = document.getElementById("photoNvCanvas");
|
|
|
- const photoThermalCanvas = document.getElementById("photoThermalCanvas");
|
|
|
- const photoNvReadout = document.getElementById("photoNvReadout");
|
|
|
- const photoThermalReadout = document.getElementById("photoThermalReadout");
|
|
|
- const photoNvCtx = photoNvCanvas?.getContext("2d");
|
|
|
- const photoThermalCtx = photoThermalCanvas?.getContext("2d");
|
|
|
- let uploadedPhoto = null;
|
|
|
-
|
|
|
- function fitPhotoCanvas(ctx, canvas, image) {
|
|
|
- ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
|
- const scale = Math.min(canvas.width / image.width, canvas.height / image.height);
|
|
|
- const w = image.width * scale, h = image.height * scale;
|
|
|
- ctx.drawImage(image, (canvas.width-w)/2, (canvas.height-h)/2, w, h);
|
|
|
+ /* ---------- Фото заменяет встроенную сцену в тех же canvas ---------- */
|
|
|
+ function fitRect(image) {
|
|
|
+ const scale=Math.min(NV_W/image.width,NV_H/image.height);
|
|
|
+ const w=image.width*scale,h=image.height*scale;
|
|
|
+ return {x:(NV_W-w)/2,y:(NV_H-h)/2,w,h};
|
|
|
}
|
|
|
-
|
|
|
- function renderPhotoSimulations() {
|
|
|
- if (!uploadedPhoto || !photoNvCtx || !photoThermalCtx) return;
|
|
|
- fitPhotoCanvas(photoNvCtx, photoNvCanvas, uploadedPhoto);
|
|
|
- fitPhotoCanvas(photoThermalCtx, photoThermalCanvas, uploadedPhoto);
|
|
|
- const source = photoNvCtx.getImageData(0, 0, NV_W, NV_H);
|
|
|
- const thermalSource = photoThermalCtx.getImageData(0, 0, NV_W, NV_H);
|
|
|
- const nvGain = parseFloat(gainInput.value);
|
|
|
- const luxFactor = clamp(parseFloat(luxInput.value) / 0.05, 0.02, 1);
|
|
|
- const irFactor = irInput.checked ? 0.32 : 0;
|
|
|
- const photoNV = source.data;
|
|
|
- const photoThermal = thermalSource.data;
|
|
|
- for (let i=0; i<photoNV.length; i+=4) {
|
|
|
- const luminance = (0.2126*photoNV[i] + 0.7152*photoNV[i+1] + 0.0722*photoNV[i+2]) / 255;
|
|
|
- const amplified = clamp((luminance * (0.25 + nvGain*1.65) * (0.18 + luxFactor*0.9)) + irFactor*(0.25+luminance), 0, 1);
|
|
|
- const green = Math.round(255 * Math.pow(amplified, 0.72));
|
|
|
- photoNV[i] = Math.round(green*0.20); photoNV[i+1] = green; photoNV[i+2] = Math.round(green*0.42);
|
|
|
- const tl = (0.2126*thermalSource.data[i] + 0.7152*thermalSource.data[i+1] + 0.0722*thermalSource.data[i+2]) / 255;
|
|
|
- const t = clamp((tl - 0.03) / 0.94, 0, 1);
|
|
|
- const color = paletteRGB(paletteInput.value, t);
|
|
|
- photoThermal[i] = color[0]; photoThermal[i+1] = color[1]; photoThermal[i+2] = color[2];
|
|
|
+ function drawPhotoBase(ctx) {
|
|
|
+ ctx.fillStyle="#050505"; ctx.fillRect(0,0,NV_W,NV_H);
|
|
|
+ photoFit=fitRect(uploadedPhoto); ctx.drawImage(uploadedPhoto,photoFit.x,photoFit.y,photoFit.w,photoFit.h);
|
|
|
+ }
|
|
|
+ function drawUploadedNV() {
|
|
|
+ drawPhotoBase(nvCtx);
|
|
|
+ const im=nvCtx.getImageData(0,0,NV_W,NV_H), d=im.data;
|
|
|
+ const gain=parseFloat(gainInput.value), luxFactor=clamp(parseFloat(luxInput.value)/0.05,0.02,1), ir=irInput.checked?0.32:0;
|
|
|
+ for(let i=0;i<d.length;i+=4){
|
|
|
+ const lum=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2])/255;
|
|
|
+ const amp=clamp((lum*(0.25+gain*1.65)*(0.18+luxFactor*0.9))+ir*(0.25+lum),0,1);
|
|
|
+ const g=Math.round(255*Math.pow(amp,0.72)); d[i]=g*0.20; d[i+1]=g; d[i+2]=g*0.42;
|
|
|
}
|
|
|
- photoNvCtx.putImageData(source, 0, 0);
|
|
|
- photoThermalCtx.putImageData(thermalSource, 0, 0);
|
|
|
- photoNvReadout.textContent = `Усиление ${nvGain.toFixed(2)}× · ${irInput.checked ? "условная ИК-подсветка" : "без подсветки"}`;
|
|
|
- photoThermalReadout.textContent = `Псевдопалитра · ${paletteInput.value}`;
|
|
|
+ nvCtx.putImageData(im,0,0);
|
|
|
+ nvCtx.save();nvCtx.globalAlpha=.08;nvCtx.strokeStyle="#7dffb2";
|
|
|
+ for(let y=0;y<NV_H;y+=4){nvCtx.beginPath();nvCtx.moveTo(0,y);nvCtx.lineTo(NV_W,y);nvCtx.stroke();}nvCtx.restore();
|
|
|
+ nvReadout.textContent=`Фото · G=${gain.toFixed(2)}× · ИК=${irInput.checked?"вкл":"выкл"}`;
|
|
|
+ nvFoot.textContent="Учебная симуляция ЭОП: яркость исходного фото условно зависит от усиления, освещённости и ИК-подсветки. Спектральные данные фото отсутствуют.";
|
|
|
}
|
|
|
-
|
|
|
- function paletteRGB(name, t) {
|
|
|
- t = clamp(t, 0, 1);
|
|
|
- if (name === "whiteHot") return [Math.round(255*t),Math.round(255*t),Math.round(255*t)];
|
|
|
- if (name === "blackHot") return [Math.round(255*(1-t)),Math.round(255*(1-t)),Math.round(255*(1-t))];
|
|
|
- let stops;
|
|
|
- if (name === "ironbow") stops=[[0,0,0],[40,0,70],[140,30,20],[230,120,0],[255,210,40],[255,255,255]];
|
|
|
- else if (name === "rainbow") stops=[[0,0,70],[0,160,255],[0,220,120],[255,230,0],[255,80,0],[255,255,255]];
|
|
|
- else stops=[[20,0,30],[120,0,90],[220,40,20],[255,160,0],[255,255,180]];
|
|
|
- const n=stops.length-1, p=t*n, idx=Math.floor(p), f=p-idx, a=stops[idx], b=stops[Math.min(n,idx+1)];
|
|
|
- return [0,1,2].map(k=>Math.round(a[k]+(b[k]-a[k])*f));
|
|
|
+ function drawUploadedThermal() {
|
|
|
+ drawPhotoBase(thermalCtx);
|
|
|
+ const base=thermalCtx.getImageData(0,0,NV_W,NV_H), mask=maskCtx.getImageData(0,0,NV_W,NV_H);
|
|
|
+ const d=base.data, m=mask.data, ambient=+ambientInput.value, span=+spanInput.value, center=ambient+10, minT=center-span/2,maxT=center+span/2;
|
|
|
+ for(let i=0;i<d.length;i+=4){
|
|
|
+ const lum=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2])/255;
|
|
|
+ // Photo luminance is only a visual proxy for the unmarked background, not temperature.
|
|
|
+ let tApp=ambient+(lum-0.5)*span*0.65;
|
|
|
+ if(m[i+3]>0){ const encoded=m[i]; tApp=270+(encoded/255)*90; }
|
|
|
+ const t=clamp((tApp-minT)/(maxT-minT),0,1), c=paletteRGB(paletteInput.value,t);
|
|
|
+ d[i]=c[0];d[i+1]=c[1];d[i+2]=c[2];d[i+3]=255;
|
|
|
+ }
|
|
|
+ thermalCtx.putImageData(base,0,0);
|
|
|
+ thermalReadout.textContent=`Фото · палитра ${paletteInput.value} · ΔT=${span} K`;
|
|
|
+ thermalFoot.textContent="Фон псевдотепловой: яркость фото используется лишь как условная основа. Закрашенные области имеют заданную условную температуру.";
|
|
|
}
|
|
|
-
|
|
|
- if (photoFile) photoFile.addEventListener("change", () => {
|
|
|
- const file = photoFile.files?.[0];
|
|
|
- if (!file) return;
|
|
|
- if (!file.type.startsWith("image/")) { photoStatus.textContent = "Выберите файл изображения."; return; }
|
|
|
- const url = URL.createObjectURL(file);
|
|
|
- const image = new Image();
|
|
|
- image.onload = () => {
|
|
|
- uploadedPhoto = image;
|
|
|
- renderPhotoSimulations();
|
|
|
- photoStatus.textContent = `Загружено: ${file.name} (${image.width}×${image.height}). Обработка выполняется локально в браузере.`;
|
|
|
- URL.revokeObjectURL(url);
|
|
|
- };
|
|
|
- image.onerror = () => { photoStatus.textContent = "Не удалось открыть изображение."; URL.revokeObjectURL(url); };
|
|
|
- image.src = url;
|
|
|
+ function paletteRGB(name,t){
|
|
|
+ t=clamp(t,0,1); if(name==="whiteHot")return [255*t|0,255*t|0,255*t|0];if(name==="blackHot")return [255*(1-t)|0,255*(1-t)|0,255*(1-t)|0];
|
|
|
+ let stops=name==="ironbow"?[[0,0,0],[40,0,70],[140,30,20],[230,120,0],[255,210,40],[255,255,255]]:name==="rainbow"?[[0,0,70],[0,160,255],[0,220,120],[255,230,0],[255,80,0],[255,255,255]]:[[20,0,30],[120,0,90],[220,40,20],[255,160,0],[255,255,180]];
|
|
|
+ return lerpStops(stops,t);
|
|
|
+ }
|
|
|
+ function redrawMask() {
|
|
|
+ maskCtx.clearRect(0,0,NV_W,NV_H);
|
|
|
+ // Auto detections are rectangular educational masks with editable temperatures.
|
|
|
+ for (const det of autoDetections) {
|
|
|
+ const [x,y,w,h] = det.box;
|
|
|
+ const encoded = Math.round(clamp((det.temp-270)/90,0,1)*255);
|
|
|
+ maskCtx.fillStyle = `rgb(${encoded},0,0)`;
|
|
|
+ maskCtx.fillRect(x,y,w,h);
|
|
|
+ }
|
|
|
+ for(const stroke of selectionStrokes){maskCtx.globalCompositeOperation=stroke.erase?"destination-out":"source-over";maskCtx.strokeStyle=`rgb(${Math.round((stroke.temp-270)/90*255)},0,0)`;maskCtx.lineWidth=stroke.radius*2;maskCtx.lineCap="round";maskCtx.lineJoin="round";maskCtx.beginPath();stroke.points.forEach((pt,i)=>i?maskCtx.lineTo(pt.x,pt.y):maskCtx.moveTo(pt.x,pt.y));if(stroke.points.length===1)maskCtx.lineTo(stroke.points[0].x+.01,stroke.points[0].y+.01);maskCtx.stroke();}maskCtx.globalCompositeOperation="source-over";
|
|
|
+ }
|
|
|
+ function canvasPoint(canvas,e){const r=canvas.getBoundingClientRect();return {x:(e.clientX-r.left)*canvas.width/r.width,y:(e.clientY-r.top)*canvas.height/r.height};}
|
|
|
+ thermalCanvas.style.touchAction="none";
|
|
|
+ let drawing=false, currentStroke=null;
|
|
|
+ thermalCanvas.addEventListener("pointerdown",e=>{if(!uploadedPhoto)return;drawing=true;thermalCanvas.setPointerCapture(e.pointerId);currentStroke={temp:+objectTempInput.value,erase:erasing,radius:erasing?22:12,points:[canvasPoint(thermalCanvas,e)]};selectionStrokes.push(currentStroke);});
|
|
|
+ thermalCanvas.addEventListener("pointermove",e=>{if(!drawing||!currentStroke)return;currentStroke.points.push(canvasPoint(thermalCanvas,e));redrawMask();scheduleRender();});
|
|
|
+ thermalCanvas.addEventListener("pointerup",()=>{drawing=false;currentStroke=null;redrawMask();scheduleRender();});
|
|
|
+ thermalCanvas.addEventListener("pointercancel",()=>{drawing=false;currentStroke=null;});
|
|
|
+ if(objectTempInput)objectTempInput.addEventListener("input",()=>{objectTempOut.textContent=`${objectTempInput.value} K`;erasing=false;eraseSelection?.classList.remove("active");});
|
|
|
+ if(eraseSelection)eraseSelection.addEventListener("click",()=>{erasing=!erasing;eraseSelection.classList.toggle("active",erasing);});
|
|
|
+ if(clearSelection)clearSelection.addEventListener("click",()=>{selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";redrawMask();scheduleRender();});
|
|
|
+ // COCO-SSD object detection is optional and runs locally in the browser after model download.
|
|
|
+ const objectTempDefaults = {person:307, car:335, truck:340, bus:340, motorcycle:330, bicycle:300, dog:306, cat:306, bird:300, horse:305, sheep:300, cow:305, bear:308, elephant:305, laptop:315, tv:300, cell_phone:310, bottle:295, cup:305, chair:295, sofa:300, dining_table:295, keyboard:310, mouse:310};
|
|
|
+ if(detectObjectsBtn) detectObjectsBtn.addEventListener("click", async () => {
|
|
|
+ if(!uploadedPhoto){ if(detectStatus)detectStatus.textContent="Сначала загрузите фотографию."; return; }
|
|
|
+ if(!window.cocoSsd || !window.tf){ if(detectStatus)detectStatus.textContent="Модель распознавания недоступна. Проверьте интернет и перезагрузите страницу; ручная кисть работает."; return; }
|
|
|
+ detectObjectsBtn.disabled=true; if(detectStatus)detectStatus.textContent="Загрузка модели / распознавание…";
|
|
|
+ try {
|
|
|
+ if(!detectorModel){ await window.tf.ready(); detectorModel=await window.cocoSsd.load({base:"lite_mobilenet_v2"}); }
|
|
|
+ const predictions=await detectorModel.detect(uploadedPhoto);
|
|
|
+ autoDetections=predictions.filter(p=>p.score>=0.45).map(p=>({class:p.class,score:p.score,box:[fitRect(uploadedPhoto).x+p.bbox[0]*fitRect(uploadedPhoto).w/uploadedPhoto.width,fitRect(uploadedPhoto).y+p.bbox[1]*fitRect(uploadedPhoto).h/uploadedPhoto.height,p.bbox[2]*fitRect(uploadedPhoto).w/uploadedPhoto.width,p.bbox[3]*fitRect(uploadedPhoto).h/uploadedPhoto.height],temp:objectTempDefaults[p.class]||307}));
|
|
|
+ if(detectedObjectsEl){detectedObjectsEl.innerHTML="";autoDetections.forEach((det,i)=>{const row=document.createElement("div");row.className="detected-row";const label=document.createElement("label");label.className="detected-label";label.textContent=`${i+1}. ${det.class} (${Math.round(det.score*100)}%) · ${det.temp} K`;const slider=document.createElement("input");slider.type="range";slider.min="270";slider.max="360";slider.value=det.temp;slider.setAttribute("aria-label",`Температура объекта ${det.class}`);slider.addEventListener("input",()=>{det.temp=+slider.value;label.textContent=`${i+1}. ${det.class} (${Math.round(det.score*100)}%) · ${det.temp} K`;redrawMask();scheduleRender();});row.append(label,slider);detectedObjectsEl.append(row);});}
|
|
|
+ redrawMask();scheduleRender();if(detectStatus)detectStatus.textContent=autoDetections.length?`Найдено объектов: ${autoDetections.length}. Обнаружение приблизительное, редактируйте маски вручную.`:"Объекты не обнаружены с достаточной уверенностью. Попробуйте ручную кисть.";
|
|
|
+ } catch(err){ console.error(err); if(detectStatus)detectStatus.textContent="Не удалось выполнить распознавание. Можно использовать ручное выделение."; }
|
|
|
+ finally{detectObjectsBtn.disabled=false;}
|
|
|
});
|
|
|
- if (photoReset) photoReset.addEventListener("click", () => {
|
|
|
- uploadedPhoto = null; if (photoFile) photoFile.value = "";
|
|
|
- [photoNvCanvas, photoThermalCanvas].forEach(c => c && c.getContext("2d").clearRect(0,0,c.width,c.height));
|
|
|
- if (photoStatus) photoStatus.textContent = "Пока изображение не загружено.";
|
|
|
- if (photoNvReadout) photoNvReadout.textContent = "—"; if (photoThermalReadout) photoThermalReadout.textContent = "—";
|
|
|
+ if(photoFile)photoFile.addEventListener("change",()=>{
|
|
|
+ const file=photoFile.files?.[0];if(!file)return;if(!file.type.startsWith("image/")){photoStatus.textContent="Выберите файл изображения.";return;}
|
|
|
+ const url=URL.createObjectURL(file), image=new Image();image.onload=()=>{uploadedPhoto=image;selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";redrawMask();sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=true);if(sceneHint)sceneHint.textContent="Загруженная фотография заменяет встроенную сцену в обоих окнах.";if(photoReset)photoReset.hidden=false;if(selectionTools)selectionTools.hidden=false;photoStatus.textContent=`Загружено: ${file.name} · ${image.width}×${image.height}. Обработка локальная.`;scheduleRender();URL.revokeObjectURL(url);};image.onerror=()=>{photoStatus.textContent="Не удалось открыть изображение.";URL.revokeObjectURL(url);};image.src=url;
|
|
|
});
|
|
|
+ if(photoReset)photoReset.addEventListener("click",()=>{uploadedPhoto=null;photoFile.value="";selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";maskCtx.clearRect(0,0,NV_W,NV_H);sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=false);if(selectionTools)selectionTools.hidden=true;photoReset.hidden=true;photoStatus.textContent="Фото не загружено. Отображается встроенная сцена.";scheduleRender();});
|
|
|
|
|
|
/* ---------- Квиз ---------- */
|
|
|
const answers = {
|
|
|
@@ -482,7 +511,6 @@
|
|
|
/* ---------- Запуск ---------- */
|
|
|
updateOutputs();
|
|
|
render();
|
|
|
- renderPhotoSimulations();
|
|
|
|
|
|
// Плавный "живой" шум сенсоров
|
|
|
setInterval(render, 140);
|