| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694 |
- /* app.js — логика интерактивной модели
- * "Приборы ночного видения и тепловизоры"
- * Загружается из index.html: <script src="app.js" defer></script>
- * Все ID элементов совпадают с разметкой index.html.
- */
- "use strict";
- (() => {
- /* ---------- Константы и DOM ---------- */
- const NV_W = 720;
- const NV_H = 405;
- const nvCanvas = document.getElementById("nvCanvas");
- const thermalCanvas = document.getElementById("thermalCanvas");
- if (!nvCanvas || !thermalCanvas) return;
- const nvCtx = nvCanvas.getContext("2d");
- const thermalCtx = thermalCanvas.getContext("2d");
- const gainInput = document.getElementById("gain");
- const gainOut = document.getElementById("gainOut");
- const luxInput = document.getElementById("lux");
- const luxOut = document.getElementById("luxOut");
- const irInput = document.getElementById("ir");
- const paletteInput = document.getElementById("palette");
- const spanInput = document.getElementById("span");
- const spanOut = document.getElementById("spanOut");
- const ambientInput = document.getElementById("ambient");
- const ambientOut = document.getElementById("ambientOut");
- const nvReadout = document.getElementById("nvReadout");
- const thermalReadout = document.getElementById("thermalReadout");
- const nvFoot = document.getElementById("nvFoot");
- const thermalFoot = document.getElementById("thermalFoot");
- const sceneHint = document.getElementById("sceneHint");
- const sceneSwitch = document.getElementById("sceneSwitch");
- /* ---------- Данные сцен ---------- */
- /* Каждый элемент: {type, x, y, w, h, temp(K), em(ε), refl, bg?} */
- const scenes = {
- forest: {
- title: "Ночной лес",
- hint: "Ночной лес: слабая освещённость, тёплые биологические объекты и источник с высокой температурой.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.42, temp: 255, em: 0.95, refl: 0.01, bg: true },
- { type: "rect", x: 0.00, y: 0.42, w: 1.00, h: 0.58, temp: 284, em: 0.96, refl: 0.12 },
- { type: "rect", x: 0.10, y: 0.24, w: 0.055, h: 0.76, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.035, y: 0.10, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
- { type: "rect", x: 0.27, y: 0.30, w: 0.045, h: 0.70, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.21, y: 0.16, w: 0.17, h: 0.22, temp: 285, em: 0.94, refl: 0.08 },
- { type: "rect", x: 0.84, y: 0.22, w: 0.060, h: 0.78, temp: 279, em: 0.90, refl: 0.18 },
- { type: "ellipse", x: 0.77, y: 0.09, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
- { type: "ellipse", x: 0.66, y: 0.54, w: 0.065, h: 0.065, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.665, y: 0.595, w: 0.055, h: 0.24, temp: 309, em: 0.98, refl: 0.34 },
- { type: "ellipse", x: 0.75, y: 0.64, w: 0.10, h: 0.11, temp: 305, em: 0.97, refl: 0.30 },
- { type: "ellipse", x: 0.43, y: 0.70, w: 0.06, h: 0.08, temp: 900, em: 0.90, refl: 0.05 },
- { type: "ellipse", x: 0.48, y: 0.74, w: 0.04, h: 0.05, temp: 780, em: 0.88, refl: 0.05 }
- ]
- },
- city: {
- title: "Город ночью",
- hint: "Город ночью: холодное небо, нагретые здания и дороги, горячий двигатель автомобиля и человек.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.38, temp: 258, em: 0.95, refl: 0.01, bg: true },
- { type: "rect", x: 0.00, y: 0.38, w: 1.00, h: 0.62, temp: 290, em: 0.96, refl: 0.10 },
- { type: "rect", x: 0.04, y: 0.16, w: 0.20, h: 0.52, temp: 285, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.29, y: 0.08, w: 0.18, h: 0.62, temp: 286, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.52, y: 0.20, w: 0.15, h: 0.48, temp: 284, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.73, y: 0.12, w: 0.23, h: 0.56, temp: 287, em: 0.92, refl: 0.20 },
- { type: "rect", x: 0.075, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.155, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.075, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.155, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.31, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.39, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.31, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.39, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
- { type: "rect", x: 0.15, y: 0.78, w: 0.30, h: 0.09, temp: 300, em: 0.86, refl: 0.22 },
- { type: "rect", x: 0.19, y: 0.72, w: 0.18, h: 0.08, temp: 305, em: 0.88, refl: 0.24 },
- { type: "ellipse", x: 0.20, y: 0.70, w: 0.05, h: 0.04, temp: 360, em: 0.80, refl: 0.15 },
- { type: "ellipse", x: 0.79, y: 0.55, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.795, y: 0.59, w: 0.05, h: 0.24, temp: 309, em: 0.98, refl: 0.34 }
- ]
- },
- lab: {
- title: "Лаборатория",
- hint: "Лаборатория: ровный фон, горячая чашка, холодный лёд, электроника и человек.",
- elements: [
- { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.55, temp: 293, em: 0.94, refl: 0.35, bg: true },
- { type: "rect", x: 0.00, y: 0.55, w: 1.00, h: 0.45, temp: 295, em: 0.92, refl: 0.30 },
- { type: "rect", x: 0.08, y: 0.62, w: 0.84, h: 0.06, temp: 295, em: 0.90, refl: 0.30 },
- { type: "ellipse", x: 0.16, y: 0.51, w: 0.08, h: 0.10, temp: 350, em: 0.85, refl: 0.20 },
- { type: "rect", x: 0.17, y: 0.56, w: 0.06, h: 0.07, temp: 345, em: 0.84, refl: 0.20 },
- { type: "ellipse", x: 0.32, y: 0.57, w: 0.08, h: 0.05, temp: 273, em: 0.96, refl: 0.45 },
- { type: "rect", x: 0.55, y: 0.43, w: 0.18, h: 0.13, temp: 330, em: 0.86, refl: 0.18 },
- { type: "rect", x: 0.57, y: 0.45, w: 0.14, h: 0.09, temp: 335, em: 0.86, refl: 0.18 },
- { type: "ellipse", x: 0.78, y: 0.48, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
- { type: "rect", x: 0.79, y: 0.53, w: 0.05, h: 0.22, temp: 309, em: 0.98, refl: 0.34 },
- { type: "rect", x: 0.90, y: 0.60, w: 0.06, h: 0.08, temp: 320, em: 0.88, refl: 0.20 }
- ]
- }
- };
- let activeScene = "forest";
- let rafId = null;
- let uploadedPhoto = null;
- let photoFit = null;
- let personBox = null;
- let personModel = null;
- let personMask = null;
- let detectingPerson = false;
- const photoFile = document.getElementById("photoFile");
- const photoReset = document.getElementById("photoReset");
- const photoStatus = document.getElementById("photoStatus");
- const selectionTools = document.getElementById("thermalSelectionTools");
- const detectPersonBtn = document.getElementById("detectPerson");
- /* ---------- Утилиты ---------- */
- const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
- function drawShape(ctx, el, color) {
- const x = el.x * NV_W;
- const y = el.y * NV_H;
- const w = el.w * NV_W;
- const h = el.h * NV_H;
- ctx.fillStyle = color;
- if (el.type === "rect") {
- ctx.fillRect(x, y, w, h);
- } else if (el.type === "ellipse") {
- ctx.beginPath();
- ctx.ellipse(x + w / 2, y + h / 2, Math.max(0.1, w / 2), Math.max(0.1, h / 2), 0, 0, Math.PI * 2);
- ctx.fill();
- }
- }
- /* ---------- ЭОП ---------- */
- function nvBrightness(el) {
- const gain = parseFloat(gainInput.value);
- const lux = parseFloat(luxInput.value);
- const irOn = irInput.checked ? 1 : 0;
- // Фотонный поток: внешняя освещённость + опциональная ИК-подсветка.
- // Отражение объекта refl играет роль albedo по отношению к падающему потоку.
- const photonFactor = lux * 200 + irOn * 2.0;
- let v = 0.045 + photonFactor * el.refl * gain;
- v = Math.pow(clamp(v, 0, 1), 0.72); // гамма-коррекция свечения экрана ЭОП
- return Math.round(v * 255);
- }
- function drawNV() {
- const scene = scenes[activeScene];
- if (uploadedPhoto) { drawUploadedNV(); return; }
- nvCtx.fillStyle = "#010806";
- nvCtx.fillRect(0, 0, NV_W, NV_H);
- for (const el of scene.elements) {
- const g = nvBrightness(el);
- const r = Math.round(g * 0.22);
- const gg = Math.round(g);
- const b = Math.round(g * 0.42);
- drawShape(nvCtx, el, `rgb(${r},${gg},${b})`);
- }
- // Шум фотокатода / МКП (примерный визуальный эффект)
- nvCtx.save();
- nvCtx.globalCompositeOperation = "lighter";
- for (let i = 0; i < 2600; i++) {
- const x = Math.random() * NV_W;
- const y = Math.random() * NV_H;
- const a = Math.random() * 0.06;
- nvCtx.fillStyle = `rgba(120,255,180,${a})`;
- nvCtx.fillRect(x, y, 1, 1);
- }
- nvCtx.restore();
- // Строки развёртки (характерный вид ЭОП-изображения)
- nvCtx.save();
- nvCtx.globalAlpha = 0.08;
- nvCtx.strokeStyle = "#7dffb2";
- nvCtx.lineWidth = 1;
- for (let y = 0; y < NV_H; y += 4) {
- nvCtx.beginPath();
- nvCtx.moveTo(0, y + 0.5);
- nvCtx.lineTo(NV_W, y + 0.5);
- nvCtx.stroke();
- }
- nvCtx.restore();
- const gain = parseFloat(gainInput.value);
- const lux = parseFloat(luxInput.value);
- nvReadout.textContent =
- `E=${lux.toExponential(2)} лк · G=${gain.toFixed(2)}× · ИК=${irInput.checked ? "вкл" : "выкл"}`;
- nvFoot.textContent = irInput.checked
- ? "ИК-подсветка 850 нм добавляет фотоны ближнего ИК-диапазона; сильнее проявляются объекты с высоким отражением."
- : "Без ИК-подсветки яркость зависит от внешней освещённости и отражения объектов; в полной темноте сигнала нет.";
- }
- /* ---------- Тепловизор ---------- */
- function lerpStops(stops, t) {
- t = clamp(t, 0, 1);
- const n = stops.length - 1;
- const p = t * n;
- const i = Math.floor(p);
- const f = p - i;
- const a = stops[i];
- const b = stops[Math.min(n, i + 1)];
- return [
- Math.round(a[0] + (b[0] - a[0]) * f),
- Math.round(a[1] + (b[1] - a[1]) * f),
- Math.round(a[2] + (b[2] - a[2]) * f)
- ];
- }
- function paletteColor(name, t) {
- t = clamp(t, 0, 1);
- if (name === "whiteHot") {
- const v = Math.round(255 * t);
- return `rgb(${v},${v},${v})`;
- }
- if (name === "blackHot") {
- const v = Math.round(255 * (1 - t));
- return `rgb(${v},${v},${v})`;
- }
- 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 [r, g, b] = lerpStops(stops, t);
- return `rgb(${r},${g},${b})`;
- }
- // Наблюдаемая ("радиационная") температура серого тела:
- // T_app = [ ε·T_obj⁴ + (1−ε)·T_amb⁴ ]^(1/4)
- function apparentTemperature(el, ambient) {
- const eps = clamp(el.em, 0.01, 1);
- const t4 = eps * Math.pow(el.temp, 4) + (1 - eps) * Math.pow(ambient, 4);
- return Math.pow(t4, 0.25);
- }
- function drawThermal() {
- const scene = scenes[activeScene];
- if (uploadedPhoto) { drawUploadedThermal(); return; }
- const ambient = parseFloat(ambientInput.value);
- const span = parseFloat(spanInput.value);
- const paletteName = paletteInput.value;
- thermalCtx.fillStyle = "#000";
- thermalCtx.fillRect(0, 0, NV_W, NV_H);
- const center = ambient + 10;
- const minT = center - span / 2;
- const maxT = center + span / 2;
- for (const el of scene.elements) {
- const baseTemp = el.bg ? ambient : el.temp;
- const elCalc = el.bg ? { ...el, temp: baseTemp } : el;
- const tApp = apparentTemperature(elCalc, ambient);
- const t = (tApp - minT) / Math.max(0.001, maxT - minT);
- drawShape(thermalCtx, el, paletteColor(paletteName, t));
- }
- // Сенсорный шум микроболометра
- thermalCtx.save();
- for (let i = 0; i < 3600; i++) {
- const x = Math.random() * NV_W;
- const y = Math.random() * NV_H;
- const a = Math.random() * 0.045;
- thermalCtx.fillStyle = `rgba(255,255,255,${a})`;
- thermalCtx.fillRect(x, y, 1, 1);
- }
- thermalCtx.restore();
- thermalReadout.textContent = `T_фона=${ambient} K · ΔT=${span} K · ${paletteName}`;
- thermalFoot.textContent =
- `Окно отображения: ${Math.round(minT)}–${Math.round(maxT)} K. Цвет зависит от ε, температуры объекта и фона.`;
- }
- /* ---------- Рендер ---------- */
- function render() {
- drawNV();
- drawThermal();
- }
- function scheduleRender() {
- if (rafId !== null) cancelAnimationFrame(rafId);
- rafId = requestAnimationFrame(() => {
- rafId = null;
- render();
- });
- }
- function updateOutputs() {
- gainOut.textContent = `${parseFloat(gainInput.value).toFixed(2)}×`;
- luxOut.textContent = `${parseFloat(luxInput.value).toFixed(4)} лк`;
- spanOut.textContent = `${spanInput.value} K`;
- ambientOut.textContent = `${ambientInput.value} K`;
- }
- function onControlsChange() {
- updateOutputs();
- scheduleRender();
- }
- /* ---------- Подписки ---------- */
- gainInput.addEventListener("input", onControlsChange);
- luxInput.addEventListener("input", onControlsChange);
- irInput.addEventListener("change", onControlsChange);
- paletteInput.addEventListener("change", onControlsChange);
- spanInput.addEventListener("input", onControlsChange);
- ambientInput.addEventListener("input", onControlsChange);
- if (sceneSwitch) {
- sceneSwitch.addEventListener("click", (event) => {
- const btn = event.target.closest("button[data-scene]");
- if (!btn) return;
- activeScene = btn.dataset.scene;
- for (const b of sceneSwitch.querySelectorAll("button")) {
- b.classList.toggle("active", b === btn);
- }
- if (sceneHint) sceneHint.textContent = scenes[activeScene].hint;
- scheduleRender();
- });
- }
- /* ---------- Фото заменяет встроенную сцену в тех же 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 drawPhotoBase(ctx, monochrome=false, brightness=1) {
- 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);
- // Thermal-view base: subdued monochrome scene so the simulated heat layer
- // reads like a thermal display without hiding photographic texture.
- if(monochrome){
- const im=ctx.getImageData(0,0,NV_W,NV_H), d=im.data;
- for(let i=0;i<d.length;i+=4){
- const gray=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2]);
- const subdued=clamp((gray-18)*brightness,0,255);
- d[i]=d[i+1]=d[i+2]=subdued;
- }
- ctx.putImageData(im,0,0);
- }
- }
- 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;
- }
- 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 drawUploadedThermal() {
- // Keep the original photograph as a very subdued monochrome texture.
- // The segmented heat map should be the dominant, high-contrast layer.
- drawPhotoBase(thermalCtx, true, 0.24);
- const ambient = +ambientInput.value;
- const span = +spanInput.value;
- thermalReadout.textContent = `Фото · T_фона=${ambient} K · ΔT=${span} K · ${paletteInput.value}`;
- thermalFoot.textContent = `T_фона=${ambient} K: повышение температуры окружения уменьшает температурный контраст и сдвигает цвета человека к холодному краю шкалы. Карта условная, не измеряет температуру.`;
- if (personBox) drawPersonHeatOverlay();
- }
- 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);
- }
- // Draw the teaching heat map inside the filled outer-contour mask derived from BodyPix.
- // Internal segmentation holes are deliberately ignored; only the external silhouette matters.
- function drawPersonHeatOverlay() {
- if (!personBox || !photoFit || !personMask) return;
- const { data: maskData, width: maskW, height: maskH } = personMask;
- const [bx, by, bw, bh] = personBox;
- const overlay = document.createElement("canvas");
- overlay.width = NV_W;
- overlay.height = NV_H;
- const octx = overlay.getContext("2d");
- const img = octx.createImageData(NV_W, NV_H);
- const d = img.data;
- const span = +spanInput.value;
- const ambient = +ambientInput.value;
- // Fixed illustrative skin-surface temperatures (K), deliberately independent
- // of ambient temperature. This makes the background-temperature slider affect
- // the relative contrast exactly as a thermal display reference should.
- // ΔT controls the width of the display window: narrow range = stronger contrast.
- const displayCenter = ambient + 10;
- const displayMin = displayCenter - span / 2;
- const displaySpan = Math.max(1, span);
- for (let py = Math.max(0, Math.floor(by)); py < Math.min(NV_H, Math.ceil(by + bh)); py++) {
- for (let px = Math.max(0, Math.floor(bx)); px < Math.min(NV_W, Math.ceil(bx + bw)); px++) {
- const nx = (px - bx) / Math.max(1, bw);
- const ny = (py - by) / Math.max(1, bh);
- const mx = Math.min(maskW - 1, Math.max(0, Math.floor((px - photoFit.x) / photoFit.w * maskW)));
- const my = Math.min(maskH - 1, Math.max(0, Math.floor((py - photoFit.y) / photoFit.h * maskH)));
- if (px < photoFit.x || px >= photoFit.x + photoFit.w || py < photoFit.y || py >= photoFit.y + photoFit.h) continue;
- if (maskData[my * maskW + mx] === 0) continue;
- // Anatomical heat profile: cooler extremities, warmer torso, strongest
- // local maxima at the head and upper chest. This is not thermometry.
- const head = Math.exp(-((((nx - 0.50) / 0.17) ** 2) + (((ny - 0.105) / 0.10) ** 2)) * 2.0);
- const chest = Math.exp(-((((nx - 0.51) / 0.23) ** 2) + (((ny - 0.36) / 0.20) ** 2)) * 1.65);
- const core = Math.exp(-((((nx - 0.50) / 0.29) ** 2) + (((ny - 0.43) / 0.34) ** 2)) * 1.25);
- const shoulder = Math.exp(-((((nx - 0.50) / 0.34) ** 2) + (((ny - 0.24) / 0.13) ** 2)) * 1.3);
- const outer = clamp(
- 1 - Math.pow(Math.abs(nx - 0.5) * 2, 1.25) * 0.62 - Math.pow(Math.max(0, ny - 0.35), 1.15) * 0.25,
- 0,
- 1
- );
- // Approximate absolute apparent skin temperatures, Kelvin.
- // Head/chest are hottest; the outer silhouette remains cooler.
- const temp = 289 + 3 * outer + 5 * core + 11 * head + 10 * chest + 2 * shoulder;
- const t = clamp((temp - displayMin) / displaySpan, 0, 1);
- // Slight gamma compression keeps cooler extremities blue/green while
- // allowing the head and chest to reach vivid orange/red values.
- const colorT = Math.pow(t, 1.35);
- // Saturated blue -> cyan -> green -> yellow -> orange -> red scale.
- const bodyStops = [
- [0, 18, 105],
- [0, 75, 220],
- [0, 190, 220],
- [0, 220, 105],
- [210, 245, 0],
- [255, 145, 0],
- [255, 35, 0],
- [255, 225, 185]
- ];
- const c = lerpStops(bodyStops, colorT);
- const idx = (py * NV_W + px) * 4;
- d[idx] = c[0];
- d[idx + 1] = c[1];
- d[idx + 2] = c[2];
- // High opacity makes the temperature field readable; a little original
- // monochrome texture remains visible beneath the color.
- d[idx + 3] = Math.round(205 + 42 * colorT);
- }
- }
- octx.putImageData(img, 0, 0);
- thermalCtx.save();
- thermalCtx.globalAlpha = 0.90;
- thermalCtx.drawImage(overlay, 0, 0);
- thermalCtx.restore();
- }
- 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};}
- async function loadPersonDetector(){
- if(personModel)return personModel;
- if(!window.bodyPix){throw new Error("Модель сегментации не загрузилась. Проверьте интернет.");}
- personModel=await window.bodyPix.load({architecture:"MobileNetV1",outputStride:16,multiplier:0.75,quantBytes:2});
- return personModel;
- }
- // Build a render-only silhouette from the BodyPix result:
- // keep the largest foreground component and fill every background pocket
- // enclosed by its OUTER contour. The model output itself is never modified.
- function makeOuterContourMask(rawData, width, height) {
- const size = width * height;
- const foreground = new Uint8Array(size);
- for (let i = 0; i < size; i++) foreground[i] = rawData[i] > 0 ? 1 : 0;
- // 1) Find the largest 8-connected foreground component (the person).
- const visited = new Uint8Array(size);
- const queue = new Int32Array(size);
- let largestComponent = new Uint8Array(size);
- let largestSize = 0;
- const neighbours = [-1, 1, -width, width, -width - 1, -width + 1, width - 1, width + 1];
- for (let start = 0; start < size; start++) {
- if (!foreground[start] || visited[start]) continue;
- let head = 0, tail = 0;
- queue[tail++] = start;
- visited[start] = 1;
- while (head < tail) {
- const idx = queue[head++];
- const x = idx % width;
- const y = (idx / width) | 0;
- for (let n = 0; n < neighbours.length; n++) {
- const next = idx + neighbours[n];
- if (next < 0 || next >= size) continue;
- const nx = next % width;
- const ny = (next / width) | 0;
- if (Math.abs(nx - x) > 1 || Math.abs(ny - y) > 1) continue;
- if (foreground[next] && !visited[next]) {
- visited[next] = 1;
- queue[tail++] = next;
- }
- }
- }
- if (tail > largestSize) {
- largestSize = tail;
- largestComponent.fill(0);
- for (let i = 0; i < tail; i++) largestComponent[queue[i]] = 1;
- }
- }
- if (largestSize === 0) return { data: new Uint8Array(size), minX: 0, minY: 0, maxX: -1, maxY: -1 };
- // 2) Flood-fill the OUTSIDE background from the image borders.
- // Four-connected background plus eight-connected foreground prevents
- // diagonal pixel contacts from opening artificial holes in the silhouette.
- const outside = new Uint8Array(size);
- let head = 0, tail = 0;
- const pushOutside = (idx) => {
- if (idx >= 0 && idx < size && !largestComponent[idx] && !outside[idx]) {
- outside[idx] = 1;
- queue[tail++] = idx;
- }
- };
- for (let x = 0; x < width; x++) {
- pushOutside(x);
- if (height > 1) pushOutside((height - 1) * width + x);
- }
- for (let y = 1; y < height - 1; y++) {
- pushOutside(y * width);
- if (width > 1) pushOutside(y * width + width - 1);
- }
- while (head < tail) {
- const idx = queue[head++];
- const x = idx % width;
- const y = (idx / width) | 0;
- if (x > 0) pushOutside(idx - 1);
- if (x + 1 < width) pushOutside(idx + 1);
- if (y > 0) pushOutside(idx - width);
- if (y + 1 < height) pushOutside(idx + width);
- }
- // 3) Everything not connected to the outside is inside the person's
- // external contour. This fills internal BodyPix gaps and holes.
- const filled = new Uint8Array(size);
- let minX = width, minY = height, maxX = -1, maxY = -1;
- for (let y = 0; y < height; y++) {
- const row = y * width;
- for (let x = 0; x < width; x++) {
- const idx = row + x;
- if (largestComponent[idx] || !outside[idx]) {
- filled[idx] = 1;
- if (x < minX) minX = x;
- if (x > maxX) maxX = x;
- if (y < minY) minY = y;
- if (y > maxY) maxY = y;
- }
- }
- }
- return { data: filled, minX, minY, maxX, maxY };
- }
- async function detectSinglePerson(){
- if(!uploadedPhoto||detectingPerson)return; detectingPerson=true; detectPersonBtn.disabled=true;
- photoStatus.textContent="Загрузка модели сегментации и выделение внешнего контура…";
- try{
- const model=await loadPersonDetector();
- const seg=await model.segmentPerson(uploadedPhoto,{internalResolution:"medium",segmentationThreshold:0.7});
- const maskW=seg.width, maskH=seg.height;
- // Keep BodyPix segmentation untouched; create a separate filled mask only
- // for drawing, so interior holes/artifacts cannot interrupt the heat colors.
- const silhouette=makeOuterContourMask(seg.data,maskW,maskH);
- const {data:heatMask,minX,minY,maxX,maxY}=silhouette;
- if(maxX<0){personBox=null;personMask=null;photoStatus.textContent="Человек не выделен. Попробуйте фото с человеком крупнее и на контрастном фоне.";}
- else{
- const f=fitRect(uploadedPhoto);
- personBox=[f.x+minX/maskW*f.w,f.y+minY/maskH*f.h,(maxX-minX+1)/maskW*f.w,(maxY-minY+1)/maskH*f.h];
- personMask={data:heatMask,width:maskW,height:maskH};
- photoStatus.textContent="Внешний контур человека выделен. Внутренние пробелы сегментации заполнены, тепловая карта наносится сплошным слоем.";
- }
- }catch(err){photoStatus.textContent=err.message||"Ошибка сегментации.";personBox=null;personMask=null;}
- detectingPerson=false;detectPersonBtn.disabled=false;scheduleRender();
- }
- if(detectPersonBtn)detectPersonBtn.addEventListener("click",detectSinglePerson);
- 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;personBox=null;personMask=null;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;if(detectPersonBtn)detectPersonBtn.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;personBox=null;personMask=null;photoFile.value="";sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=false);if(selectionTools)selectionTools.hidden=true;if(detectPersonBtn)detectPersonBtn.hidden=true;photoReset.hidden=true;photoStatus.textContent="Фото не загружено. Отображается встроенная сцена.";scheduleRender();});
- /* ---------- Квиз ---------- */
- const answers = {
- q1: "b",
- q2: "a",
- q3: "b"
- };
- const checkBtn = document.getElementById("checkQuiz");
- const resetBtn = document.getElementById("resetQuiz");
- const quizResult = document.getElementById("quizResult");
- if (checkBtn) {
- checkBtn.addEventListener("click", () => {
- let correct = 0;
- let answered = 0;
- for (const key of Object.keys(answers)) {
- const selected = document.querySelector(`input[name="${key}"]:checked`);
- if (selected) {
- answered++;
- if (selected.value === answers[key]) correct++;
- }
- }
- if (!quizResult) return;
- if (answered < 3) {
- quizResult.innerHTML = `Ответьте на все вопросы. Сейчас выбрано <strong>${answered}</strong> из 3.`;
- return;
- }
- if (correct === 3) {
- quizResult.innerHTML = "Верно: <strong>3/3</strong>. Вы корректно различаете принципы ЭОП и тепловизора.";
- } else if (correct === 2) {
- quizResult.innerHTML = "Результат: <strong>2/3</strong>. Один принцип стоит повторить: различие отражённого и собственного ИК-излучения.";
- } else if (correct === 1) {
- quizResult.innerHTML = "Результат: <strong>1/3</strong>. Вернитесь к блоку «Научная основа модели» и сравните ЭОП с тепловизором.";
- } else {
- quizResult.innerHTML = "Результат: <strong>0/3</strong>. Начните с ключевой идеи: ЭОП усиливает свет, тепловизор регистрирует тепловое ИК-излучение.";
- }
- });
- }
- if (resetBtn) {
- resetBtn.addEventListener("click", () => {
- for (const radio of document.querySelectorAll('#quiz input[type="radio"]')) {
- radio.checked = false;
- }
- if (quizResult) quizResult.textContent = "Выберите ответы и нажмите «Проверить».";
- });
- }
- /* ---------- Запуск ---------- */
- updateOutputs();
- render();
- // Плавный "живой" шум сенсоров
- setInterval(render, 140);
- /* ---------- PWA: регистрация service worker (если файл рядом) ---------- */
- if ("serviceWorker" in navigator) {
- window.addEventListener("load", () => {
- navigator.serviceWorker
- .register("sw.js")
- .catch(() => { /* тихо игнорируем отсутствие sw.js */ });
- });
- }
- })();
|