app.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. /* app.js — логика интерактивной модели
  2. * "Приборы ночного видения и тепловизоры"
  3. * Загружается из index.html: <script src="app.js" defer></script>
  4. * Все ID элементов совпадают с разметкой index.html.
  5. */
  6. "use strict";
  7. (() => {
  8. /* ---------- Константы и DOM ---------- */
  9. const NV_W = 720;
  10. const NV_H = 405;
  11. const nvCanvas = document.getElementById("nvCanvas");
  12. const thermalCanvas = document.getElementById("thermalCanvas");
  13. if (!nvCanvas || !thermalCanvas) return;
  14. const nvCtx = nvCanvas.getContext("2d");
  15. const thermalCtx = thermalCanvas.getContext("2d");
  16. const gainInput = document.getElementById("gain");
  17. const gainOut = document.getElementById("gainOut");
  18. const luxInput = document.getElementById("lux");
  19. const luxOut = document.getElementById("luxOut");
  20. const irInput = document.getElementById("ir");
  21. const paletteInput = document.getElementById("palette");
  22. const spanInput = document.getElementById("span");
  23. const spanOut = document.getElementById("spanOut");
  24. const ambientInput = document.getElementById("ambient");
  25. const ambientOut = document.getElementById("ambientOut");
  26. const nvReadout = document.getElementById("nvReadout");
  27. const thermalReadout = document.getElementById("thermalReadout");
  28. const nvFoot = document.getElementById("nvFoot");
  29. const thermalFoot = document.getElementById("thermalFoot");
  30. const sceneHint = document.getElementById("sceneHint");
  31. const sceneSwitch = document.getElementById("sceneSwitch");
  32. /* ---------- Данные сцен ---------- */
  33. /* Каждый элемент: {type, x, y, w, h, temp(K), em(ε), refl, bg?} */
  34. const scenes = {
  35. forest: {
  36. title: "Ночной лес",
  37. hint: "Ночной лес: слабая освещённость, тёплые биологические объекты и источник с высокой температурой.",
  38. elements: [
  39. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.42, temp: 255, em: 0.95, refl: 0.01, bg: true },
  40. { type: "rect", x: 0.00, y: 0.42, w: 1.00, h: 0.58, temp: 284, em: 0.96, refl: 0.12 },
  41. { type: "rect", x: 0.10, y: 0.24, w: 0.055, h: 0.76, temp: 279, em: 0.90, refl: 0.18 },
  42. { type: "ellipse", x: 0.035, y: 0.10, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
  43. { type: "rect", x: 0.27, y: 0.30, w: 0.045, h: 0.70, temp: 279, em: 0.90, refl: 0.18 },
  44. { type: "ellipse", x: 0.21, y: 0.16, w: 0.17, h: 0.22, temp: 285, em: 0.94, refl: 0.08 },
  45. { type: "rect", x: 0.84, y: 0.22, w: 0.060, h: 0.78, temp: 279, em: 0.90, refl: 0.18 },
  46. { type: "ellipse", x: 0.77, y: 0.09, w: 0.20, h: 0.24, temp: 285, em: 0.94, refl: 0.08 },
  47. { type: "ellipse", x: 0.66, y: 0.54, w: 0.065, h: 0.065, temp: 310, em: 0.98, refl: 0.35 },
  48. { type: "rect", x: 0.665, y: 0.595, w: 0.055, h: 0.24, temp: 309, em: 0.98, refl: 0.34 },
  49. { type: "ellipse", x: 0.75, y: 0.64, w: 0.10, h: 0.11, temp: 305, em: 0.97, refl: 0.30 },
  50. { type: "ellipse", x: 0.43, y: 0.70, w: 0.06, h: 0.08, temp: 900, em: 0.90, refl: 0.05 },
  51. { type: "ellipse", x: 0.48, y: 0.74, w: 0.04, h: 0.05, temp: 780, em: 0.88, refl: 0.05 }
  52. ]
  53. },
  54. city: {
  55. title: "Город ночью",
  56. hint: "Город ночью: холодное небо, нагретые здания и дороги, горячий двигатель автомобиля и человек.",
  57. elements: [
  58. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.38, temp: 258, em: 0.95, refl: 0.01, bg: true },
  59. { type: "rect", x: 0.00, y: 0.38, w: 1.00, h: 0.62, temp: 290, em: 0.96, refl: 0.10 },
  60. { type: "rect", x: 0.04, y: 0.16, w: 0.20, h: 0.52, temp: 285, em: 0.92, refl: 0.20 },
  61. { type: "rect", x: 0.29, y: 0.08, w: 0.18, h: 0.62, temp: 286, em: 0.92, refl: 0.20 },
  62. { type: "rect", x: 0.52, y: 0.20, w: 0.15, h: 0.48, temp: 284, em: 0.92, refl: 0.20 },
  63. { type: "rect", x: 0.73, y: 0.12, w: 0.23, h: 0.56, temp: 287, em: 0.92, refl: 0.20 },
  64. { type: "rect", x: 0.075, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  65. { type: "rect", x: 0.155, y: 0.25, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  66. { type: "rect", x: 0.075, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  67. { type: "rect", x: 0.155, y: 0.39, w: 0.045, h: 0.06, temp: 295, em: 0.90, refl: 0.25 },
  68. { type: "rect", x: 0.31, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  69. { type: "rect", x: 0.39, y: 0.23, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  70. { type: "rect", x: 0.31, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  71. { type: "rect", x: 0.39, y: 0.41, w: 0.045, h: 0.06, temp: 296, em: 0.90, refl: 0.25 },
  72. { type: "rect", x: 0.15, y: 0.78, w: 0.30, h: 0.09, temp: 300, em: 0.86, refl: 0.22 },
  73. { type: "rect", x: 0.19, y: 0.72, w: 0.18, h: 0.08, temp: 305, em: 0.88, refl: 0.24 },
  74. { type: "ellipse", x: 0.20, y: 0.70, w: 0.05, h: 0.04, temp: 360, em: 0.80, refl: 0.15 },
  75. { type: "ellipse", x: 0.79, y: 0.55, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
  76. { type: "rect", x: 0.795, y: 0.59, w: 0.05, h: 0.24, temp: 309, em: 0.98, refl: 0.34 }
  77. ]
  78. },
  79. lab: {
  80. title: "Лаборатория",
  81. hint: "Лаборатория: ровный фон, горячая чашка, холодный лёд, электроника и человек.",
  82. elements: [
  83. { type: "rect", x: 0.00, y: 0.00, w: 1.00, h: 0.55, temp: 293, em: 0.94, refl: 0.35, bg: true },
  84. { type: "rect", x: 0.00, y: 0.55, w: 1.00, h: 0.45, temp: 295, em: 0.92, refl: 0.30 },
  85. { type: "rect", x: 0.08, y: 0.62, w: 0.84, h: 0.06, temp: 295, em: 0.90, refl: 0.30 },
  86. { type: "ellipse", x: 0.16, y: 0.51, w: 0.08, h: 0.10, temp: 350, em: 0.85, refl: 0.20 },
  87. { type: "rect", x: 0.17, y: 0.56, w: 0.06, h: 0.07, temp: 345, em: 0.84, refl: 0.20 },
  88. { type: "ellipse", x: 0.32, y: 0.57, w: 0.08, h: 0.05, temp: 273, em: 0.96, refl: 0.45 },
  89. { type: "rect", x: 0.55, y: 0.43, w: 0.18, h: 0.13, temp: 330, em: 0.86, refl: 0.18 },
  90. { type: "rect", x: 0.57, y: 0.45, w: 0.14, h: 0.09, temp: 335, em: 0.86, refl: 0.18 },
  91. { type: "ellipse", x: 0.78, y: 0.48, w: 0.06, h: 0.06, temp: 310, em: 0.98, refl: 0.35 },
  92. { type: "rect", x: 0.79, y: 0.53, w: 0.05, h: 0.22, temp: 309, em: 0.98, refl: 0.34 },
  93. { type: "rect", x: 0.90, y: 0.60, w: 0.06, h: 0.08, temp: 320, em: 0.88, refl: 0.20 }
  94. ]
  95. }
  96. };
  97. let activeScene = "forest";
  98. let rafId = null;
  99. let uploadedPhoto = null;
  100. let photoFit = null;
  101. let personBox = null;
  102. let personModel = null;
  103. let personMask = null;
  104. let detectingPerson = false;
  105. const photoFile = document.getElementById("photoFile");
  106. const photoReset = document.getElementById("photoReset");
  107. const photoStatus = document.getElementById("photoStatus");
  108. const selectionTools = document.getElementById("thermalSelectionTools");
  109. const detectPersonBtn = document.getElementById("detectPerson");
  110. /* ---------- Утилиты ---------- */
  111. const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  112. function drawShape(ctx, el, color) {
  113. const x = el.x * NV_W;
  114. const y = el.y * NV_H;
  115. const w = el.w * NV_W;
  116. const h = el.h * NV_H;
  117. ctx.fillStyle = color;
  118. if (el.type === "rect") {
  119. ctx.fillRect(x, y, w, h);
  120. } else if (el.type === "ellipse") {
  121. ctx.beginPath();
  122. 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);
  123. ctx.fill();
  124. }
  125. }
  126. /* ---------- ЭОП ---------- */
  127. function nvBrightness(el) {
  128. const gain = parseFloat(gainInput.value);
  129. const lux = parseFloat(luxInput.value);
  130. const irOn = irInput.checked ? 1 : 0;
  131. // Фотонный поток: внешняя освещённость + опциональная ИК-подсветка.
  132. // Отражение объекта refl играет роль albedo по отношению к падающему потоку.
  133. const photonFactor = lux * 200 + irOn * 2.0;
  134. let v = 0.045 + photonFactor * el.refl * gain;
  135. v = Math.pow(clamp(v, 0, 1), 0.72); // гамма-коррекция свечения экрана ЭОП
  136. return Math.round(v * 255);
  137. }
  138. function drawNV() {
  139. const scene = scenes[activeScene];
  140. if (uploadedPhoto) { drawUploadedNV(); return; }
  141. nvCtx.fillStyle = "#010806";
  142. nvCtx.fillRect(0, 0, NV_W, NV_H);
  143. for (const el of scene.elements) {
  144. const g = nvBrightness(el);
  145. const r = Math.round(g * 0.22);
  146. const gg = Math.round(g);
  147. const b = Math.round(g * 0.42);
  148. drawShape(nvCtx, el, `rgb(${r},${gg},${b})`);
  149. }
  150. // Шум фотокатода / МКП (примерный визуальный эффект)
  151. nvCtx.save();
  152. nvCtx.globalCompositeOperation = "lighter";
  153. for (let i = 0; i < 2600; i++) {
  154. const x = Math.random() * NV_W;
  155. const y = Math.random() * NV_H;
  156. const a = Math.random() * 0.06;
  157. nvCtx.fillStyle = `rgba(120,255,180,${a})`;
  158. nvCtx.fillRect(x, y, 1, 1);
  159. }
  160. nvCtx.restore();
  161. // Строки развёртки (характерный вид ЭОП-изображения)
  162. nvCtx.save();
  163. nvCtx.globalAlpha = 0.08;
  164. nvCtx.strokeStyle = "#7dffb2";
  165. nvCtx.lineWidth = 1;
  166. for (let y = 0; y < NV_H; y += 4) {
  167. nvCtx.beginPath();
  168. nvCtx.moveTo(0, y + 0.5);
  169. nvCtx.lineTo(NV_W, y + 0.5);
  170. nvCtx.stroke();
  171. }
  172. nvCtx.restore();
  173. const gain = parseFloat(gainInput.value);
  174. const lux = parseFloat(luxInput.value);
  175. nvReadout.textContent =
  176. `E=${lux.toExponential(2)} лк · G=${gain.toFixed(2)}× · ИК=${irInput.checked ? "вкл" : "выкл"}`;
  177. nvFoot.textContent = irInput.checked
  178. ? "ИК-подсветка 850 нм добавляет фотоны ближнего ИК-диапазона; сильнее проявляются объекты с высоким отражением."
  179. : "Без ИК-подсветки яркость зависит от внешней освещённости и отражения объектов; в полной темноте сигнала нет.";
  180. }
  181. /* ---------- Тепловизор ---------- */
  182. function lerpStops(stops, t) {
  183. t = clamp(t, 0, 1);
  184. const n = stops.length - 1;
  185. const p = t * n;
  186. const i = Math.floor(p);
  187. const f = p - i;
  188. const a = stops[i];
  189. const b = stops[Math.min(n, i + 1)];
  190. return [
  191. Math.round(a[0] + (b[0] - a[0]) * f),
  192. Math.round(a[1] + (b[1] - a[1]) * f),
  193. Math.round(a[2] + (b[2] - a[2]) * f)
  194. ];
  195. }
  196. function paletteColor(name, t) {
  197. t = clamp(t, 0, 1);
  198. if (name === "whiteHot") {
  199. const v = Math.round(255 * t);
  200. return `rgb(${v},${v},${v})`;
  201. }
  202. if (name === "blackHot") {
  203. const v = Math.round(255 * (1 - t));
  204. return `rgb(${v},${v},${v})`;
  205. }
  206. let stops;
  207. if (name === "ironbow") {
  208. stops = [
  209. [0, 0, 0],
  210. [40, 0, 70],
  211. [140, 30, 20],
  212. [230, 120, 0],
  213. [255, 210, 40],
  214. [255, 255, 255]
  215. ];
  216. } else if (name === "rainbow") {
  217. stops = [
  218. [0, 0, 70],
  219. [0, 160, 255],
  220. [0, 220, 120],
  221. [255, 230, 0],
  222. [255, 80, 0],
  223. [255, 255, 255]
  224. ];
  225. } else {
  226. stops = [
  227. [20, 0, 30],
  228. [120, 0, 90],
  229. [220, 40, 20],
  230. [255, 160, 0],
  231. [255, 255, 180]
  232. ];
  233. }
  234. const [r, g, b] = lerpStops(stops, t);
  235. return `rgb(${r},${g},${b})`;
  236. }
  237. // Наблюдаемая ("радиационная") температура серого тела:
  238. // T_app = [ ε·T_obj⁴ + (1−ε)·T_amb⁴ ]^(1/4)
  239. function apparentTemperature(el, ambient) {
  240. const eps = clamp(el.em, 0.01, 1);
  241. const t4 = eps * Math.pow(el.temp, 4) + (1 - eps) * Math.pow(ambient, 4);
  242. return Math.pow(t4, 0.25);
  243. }
  244. function drawThermal() {
  245. const scene = scenes[activeScene];
  246. if (uploadedPhoto) { drawUploadedThermal(); return; }
  247. const ambient = parseFloat(ambientInput.value);
  248. const span = parseFloat(spanInput.value);
  249. const paletteName = paletteInput.value;
  250. thermalCtx.fillStyle = "#000";
  251. thermalCtx.fillRect(0, 0, NV_W, NV_H);
  252. const center = ambient + 10;
  253. const minT = center - span / 2;
  254. const maxT = center + span / 2;
  255. for (const el of scene.elements) {
  256. const baseTemp = el.bg ? ambient : el.temp;
  257. const elCalc = el.bg ? { ...el, temp: baseTemp } : el;
  258. const tApp = apparentTemperature(elCalc, ambient);
  259. const t = (tApp - minT) / Math.max(0.001, maxT - minT);
  260. drawShape(thermalCtx, el, paletteColor(paletteName, t));
  261. }
  262. // Сенсорный шум микроболометра
  263. thermalCtx.save();
  264. for (let i = 0; i < 3600; i++) {
  265. const x = Math.random() * NV_W;
  266. const y = Math.random() * NV_H;
  267. const a = Math.random() * 0.045;
  268. thermalCtx.fillStyle = `rgba(255,255,255,${a})`;
  269. thermalCtx.fillRect(x, y, 1, 1);
  270. }
  271. thermalCtx.restore();
  272. thermalReadout.textContent = `T_фона=${ambient} K · ΔT=${span} K · ${paletteName}`;
  273. thermalFoot.textContent =
  274. `Окно отображения: ${Math.round(minT)}–${Math.round(maxT)} K. Цвет зависит от ε, температуры объекта и фона.`;
  275. }
  276. /* ---------- Рендер ---------- */
  277. function render() {
  278. drawNV();
  279. drawThermal();
  280. }
  281. function scheduleRender() {
  282. if (rafId !== null) cancelAnimationFrame(rafId);
  283. rafId = requestAnimationFrame(() => {
  284. rafId = null;
  285. render();
  286. });
  287. }
  288. function updateOutputs() {
  289. gainOut.textContent = `${parseFloat(gainInput.value).toFixed(2)}×`;
  290. luxOut.textContent = `${parseFloat(luxInput.value).toFixed(4)} лк`;
  291. spanOut.textContent = `${spanInput.value} K`;
  292. ambientOut.textContent = `${ambientInput.value} K`;
  293. }
  294. function onControlsChange() {
  295. updateOutputs();
  296. scheduleRender();
  297. }
  298. /* ---------- Подписки ---------- */
  299. gainInput.addEventListener("input", onControlsChange);
  300. luxInput.addEventListener("input", onControlsChange);
  301. irInput.addEventListener("change", onControlsChange);
  302. paletteInput.addEventListener("change", onControlsChange);
  303. spanInput.addEventListener("input", onControlsChange);
  304. ambientInput.addEventListener("input", onControlsChange);
  305. if (sceneSwitch) {
  306. sceneSwitch.addEventListener("click", (event) => {
  307. const btn = event.target.closest("button[data-scene]");
  308. if (!btn) return;
  309. activeScene = btn.dataset.scene;
  310. for (const b of sceneSwitch.querySelectorAll("button")) {
  311. b.classList.toggle("active", b === btn);
  312. }
  313. if (sceneHint) sceneHint.textContent = scenes[activeScene].hint;
  314. scheduleRender();
  315. });
  316. }
  317. /* ---------- Фото заменяет встроенную сцену в тех же canvas ---------- */
  318. function fitRect(image) {
  319. const scale=Math.min(NV_W/image.width,NV_H/image.height);
  320. const w=image.width*scale,h=image.height*scale;
  321. return {x:(NV_W-w)/2,y:(NV_H-h)/2,w,h};
  322. }
  323. function drawPhotoBase(ctx, monochrome=false, brightness=1) {
  324. ctx.fillStyle="#050505"; ctx.fillRect(0,0,NV_W,NV_H);
  325. photoFit=fitRect(uploadedPhoto); ctx.drawImage(uploadedPhoto,photoFit.x,photoFit.y,photoFit.w,photoFit.h);
  326. // Thermal-view base: subdued monochrome scene so the simulated heat layer
  327. // reads like a thermal display without hiding photographic texture.
  328. if(monochrome){
  329. const im=ctx.getImageData(0,0,NV_W,NV_H), d=im.data;
  330. for(let i=0;i<d.length;i+=4){
  331. const gray=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2]);
  332. const subdued=clamp((gray-18)*brightness,0,255);
  333. d[i]=d[i+1]=d[i+2]=subdued;
  334. }
  335. ctx.putImageData(im,0,0);
  336. }
  337. }
  338. function drawUploadedNV() {
  339. drawPhotoBase(nvCtx);
  340. const im=nvCtx.getImageData(0,0,NV_W,NV_H), d=im.data;
  341. const gain=parseFloat(gainInput.value), luxFactor=clamp(parseFloat(luxInput.value)/0.05,0.02,1), ir=irInput.checked?0.32:0;
  342. for(let i=0;i<d.length;i+=4){
  343. const lum=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2])/255;
  344. const amp=clamp((lum*(0.25+gain*1.65)*(0.18+luxFactor*0.9))+ir*(0.25+lum),0,1);
  345. 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;
  346. }
  347. nvCtx.putImageData(im,0,0);
  348. nvCtx.save();nvCtx.globalAlpha=.08;nvCtx.strokeStyle="#7dffb2";
  349. for(let y=0;y<NV_H;y+=4){nvCtx.beginPath();nvCtx.moveTo(0,y);nvCtx.lineTo(NV_W,y);nvCtx.stroke();}nvCtx.restore();
  350. nvReadout.textContent=`Фото · G=${gain.toFixed(2)}× · ИК=${irInput.checked?"вкл":"выкл"}`;
  351. nvFoot.textContent="Учебная симуляция ЭОП: яркость исходного фото условно зависит от усиления, освещённости и ИК-подсветки. Спектральные данные фото отсутствуют.";
  352. }
  353. function drawUploadedThermal() {
  354. // Keep the original photograph as a very subdued monochrome texture.
  355. // The segmented heat map should be the dominant, high-contrast layer.
  356. drawPhotoBase(thermalCtx, true, 0.24);
  357. const ambient = +ambientInput.value;
  358. const span = +spanInput.value;
  359. thermalReadout.textContent = `Фото · T_фона=${ambient} K · ΔT=${span} K · ${paletteInput.value}`;
  360. thermalFoot.textContent = `T_фона=${ambient} K: повышение температуры окружения уменьшает температурный контраст и сдвигает цвета человека к холодному краю шкалы. Карта условная, не измеряет температуру.`;
  361. if (personBox) drawPersonHeatOverlay();
  362. }
  363. function paletteRGB(name,t){
  364. 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];
  365. 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]];
  366. return lerpStops(stops,t);
  367. }
  368. // Draw the teaching heat map inside the filled outer-contour mask derived from BodyPix.
  369. // Internal segmentation holes are deliberately ignored; only the external silhouette matters.
  370. function drawPersonHeatOverlay() {
  371. if (!personBox || !photoFit || !personMask) return;
  372. const { data: maskData, width: maskW, height: maskH } = personMask;
  373. const [bx, by, bw, bh] = personBox;
  374. const overlay = document.createElement("canvas");
  375. overlay.width = NV_W;
  376. overlay.height = NV_H;
  377. const octx = overlay.getContext("2d");
  378. const img = octx.createImageData(NV_W, NV_H);
  379. const d = img.data;
  380. const span = +spanInput.value;
  381. const ambient = +ambientInput.value;
  382. // Fixed illustrative skin-surface temperatures (K), deliberately independent
  383. // of ambient temperature. This makes the background-temperature slider affect
  384. // the relative contrast exactly as a thermal display reference should.
  385. // ΔT controls the width of the display window: narrow range = stronger contrast.
  386. const displayCenter = ambient + 10;
  387. const displayMin = displayCenter - span / 2;
  388. const displaySpan = Math.max(1, span);
  389. for (let py = Math.max(0, Math.floor(by)); py < Math.min(NV_H, Math.ceil(by + bh)); py++) {
  390. for (let px = Math.max(0, Math.floor(bx)); px < Math.min(NV_W, Math.ceil(bx + bw)); px++) {
  391. const nx = (px - bx) / Math.max(1, bw);
  392. const ny = (py - by) / Math.max(1, bh);
  393. const mx = Math.min(maskW - 1, Math.max(0, Math.floor((px - photoFit.x) / photoFit.w * maskW)));
  394. const my = Math.min(maskH - 1, Math.max(0, Math.floor((py - photoFit.y) / photoFit.h * maskH)));
  395. if (px < photoFit.x || px >= photoFit.x + photoFit.w || py < photoFit.y || py >= photoFit.y + photoFit.h) continue;
  396. if (maskData[my * maskW + mx] === 0) continue;
  397. // Anatomical heat profile: cooler extremities, warmer torso, strongest
  398. // local maxima at the head and upper chest. This is not thermometry.
  399. const head = Math.exp(-((((nx - 0.50) / 0.17) ** 2) + (((ny - 0.105) / 0.10) ** 2)) * 2.0);
  400. const chest = Math.exp(-((((nx - 0.51) / 0.23) ** 2) + (((ny - 0.36) / 0.20) ** 2)) * 1.65);
  401. const core = Math.exp(-((((nx - 0.50) / 0.29) ** 2) + (((ny - 0.43) / 0.34) ** 2)) * 1.25);
  402. const shoulder = Math.exp(-((((nx - 0.50) / 0.34) ** 2) + (((ny - 0.24) / 0.13) ** 2)) * 1.3);
  403. const outer = clamp(
  404. 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,
  405. 0,
  406. 1
  407. );
  408. // Approximate absolute apparent skin temperatures, Kelvin.
  409. // Head/chest are hottest; the outer silhouette remains cooler.
  410. const temp = 289 + 3 * outer + 5 * core + 11 * head + 10 * chest + 2 * shoulder;
  411. const t = clamp((temp - displayMin) / displaySpan, 0, 1);
  412. // Slight gamma compression keeps cooler extremities blue/green while
  413. // allowing the head and chest to reach vivid orange/red values.
  414. const colorT = Math.pow(t, 1.35);
  415. // Saturated blue -> cyan -> green -> yellow -> orange -> red scale.
  416. const bodyStops = [
  417. [0, 18, 105],
  418. [0, 75, 220],
  419. [0, 190, 220],
  420. [0, 220, 105],
  421. [210, 245, 0],
  422. [255, 145, 0],
  423. [255, 35, 0],
  424. [255, 225, 185]
  425. ];
  426. const c = lerpStops(bodyStops, colorT);
  427. const idx = (py * NV_W + px) * 4;
  428. d[idx] = c[0];
  429. d[idx + 1] = c[1];
  430. d[idx + 2] = c[2];
  431. // High opacity makes the temperature field readable; a little original
  432. // monochrome texture remains visible beneath the color.
  433. d[idx + 3] = Math.round(205 + 42 * colorT);
  434. }
  435. }
  436. octx.putImageData(img, 0, 0);
  437. thermalCtx.save();
  438. thermalCtx.globalAlpha = 0.90;
  439. thermalCtx.drawImage(overlay, 0, 0);
  440. thermalCtx.restore();
  441. }
  442. 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};}
  443. async function loadPersonDetector(){
  444. if(personModel)return personModel;
  445. if(!window.bodyPix){throw new Error("Модель сегментации не загрузилась. Проверьте интернет.");}
  446. personModel=await window.bodyPix.load({architecture:"MobileNetV1",outputStride:16,multiplier:0.75,quantBytes:2});
  447. return personModel;
  448. }
  449. // Build a render-only silhouette from the BodyPix result:
  450. // keep the largest foreground component and fill every background pocket
  451. // enclosed by its OUTER contour. The model output itself is never modified.
  452. function makeOuterContourMask(rawData, width, height) {
  453. const size = width * height;
  454. const foreground = new Uint8Array(size);
  455. for (let i = 0; i < size; i++) foreground[i] = rawData[i] > 0 ? 1 : 0;
  456. // 1) Find the largest 8-connected foreground component (the person).
  457. const visited = new Uint8Array(size);
  458. const queue = new Int32Array(size);
  459. let largestComponent = new Uint8Array(size);
  460. let largestSize = 0;
  461. const neighbours = [-1, 1, -width, width, -width - 1, -width + 1, width - 1, width + 1];
  462. for (let start = 0; start < size; start++) {
  463. if (!foreground[start] || visited[start]) continue;
  464. let head = 0, tail = 0;
  465. queue[tail++] = start;
  466. visited[start] = 1;
  467. while (head < tail) {
  468. const idx = queue[head++];
  469. const x = idx % width;
  470. const y = (idx / width) | 0;
  471. for (let n = 0; n < neighbours.length; n++) {
  472. const next = idx + neighbours[n];
  473. if (next < 0 || next >= size) continue;
  474. const nx = next % width;
  475. const ny = (next / width) | 0;
  476. if (Math.abs(nx - x) > 1 || Math.abs(ny - y) > 1) continue;
  477. if (foreground[next] && !visited[next]) {
  478. visited[next] = 1;
  479. queue[tail++] = next;
  480. }
  481. }
  482. }
  483. if (tail > largestSize) {
  484. largestSize = tail;
  485. largestComponent.fill(0);
  486. for (let i = 0; i < tail; i++) largestComponent[queue[i]] = 1;
  487. }
  488. }
  489. if (largestSize === 0) return { data: new Uint8Array(size), minX: 0, minY: 0, maxX: -1, maxY: -1 };
  490. // 2) Flood-fill the OUTSIDE background from the image borders.
  491. // Four-connected background plus eight-connected foreground prevents
  492. // diagonal pixel contacts from opening artificial holes in the silhouette.
  493. const outside = new Uint8Array(size);
  494. let head = 0, tail = 0;
  495. const pushOutside = (idx) => {
  496. if (idx >= 0 && idx < size && !largestComponent[idx] && !outside[idx]) {
  497. outside[idx] = 1;
  498. queue[tail++] = idx;
  499. }
  500. };
  501. for (let x = 0; x < width; x++) {
  502. pushOutside(x);
  503. if (height > 1) pushOutside((height - 1) * width + x);
  504. }
  505. for (let y = 1; y < height - 1; y++) {
  506. pushOutside(y * width);
  507. if (width > 1) pushOutside(y * width + width - 1);
  508. }
  509. while (head < tail) {
  510. const idx = queue[head++];
  511. const x = idx % width;
  512. const y = (idx / width) | 0;
  513. if (x > 0) pushOutside(idx - 1);
  514. if (x + 1 < width) pushOutside(idx + 1);
  515. if (y > 0) pushOutside(idx - width);
  516. if (y + 1 < height) pushOutside(idx + width);
  517. }
  518. // 3) Everything not connected to the outside is inside the person's
  519. // external contour. This fills internal BodyPix gaps and holes.
  520. const filled = new Uint8Array(size);
  521. let minX = width, minY = height, maxX = -1, maxY = -1;
  522. for (let y = 0; y < height; y++) {
  523. const row = y * width;
  524. for (let x = 0; x < width; x++) {
  525. const idx = row + x;
  526. if (largestComponent[idx] || !outside[idx]) {
  527. filled[idx] = 1;
  528. if (x < minX) minX = x;
  529. if (x > maxX) maxX = x;
  530. if (y < minY) minY = y;
  531. if (y > maxY) maxY = y;
  532. }
  533. }
  534. }
  535. return { data: filled, minX, minY, maxX, maxY };
  536. }
  537. async function detectSinglePerson(){
  538. if(!uploadedPhoto||detectingPerson)return; detectingPerson=true; detectPersonBtn.disabled=true;
  539. photoStatus.textContent="Загрузка модели сегментации и выделение внешнего контура…";
  540. try{
  541. const model=await loadPersonDetector();
  542. const seg=await model.segmentPerson(uploadedPhoto,{internalResolution:"medium",segmentationThreshold:0.7});
  543. const maskW=seg.width, maskH=seg.height;
  544. // Keep BodyPix segmentation untouched; create a separate filled mask only
  545. // for drawing, so interior holes/artifacts cannot interrupt the heat colors.
  546. const silhouette=makeOuterContourMask(seg.data,maskW,maskH);
  547. const {data:heatMask,minX,minY,maxX,maxY}=silhouette;
  548. if(maxX<0){personBox=null;personMask=null;photoStatus.textContent="Человек не выделен. Попробуйте фото с человеком крупнее и на контрастном фоне.";}
  549. else{
  550. const f=fitRect(uploadedPhoto);
  551. 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];
  552. personMask={data:heatMask,width:maskW,height:maskH};
  553. photoStatus.textContent="Внешний контур человека выделен. Внутренние пробелы сегментации заполнены, тепловая карта наносится сплошным слоем.";
  554. }
  555. }catch(err){photoStatus.textContent=err.message||"Ошибка сегментации.";personBox=null;personMask=null;}
  556. detectingPerson=false;detectPersonBtn.disabled=false;scheduleRender();
  557. }
  558. if(detectPersonBtn)detectPersonBtn.addEventListener("click",detectSinglePerson);
  559. if(photoFile)photoFile.addEventListener("change",()=>{
  560. const file=photoFile.files?.[0];if(!file)return;if(!file.type.startsWith("image/")){photoStatus.textContent="Выберите файл изображения.";return;}
  561. 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;
  562. });
  563. 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();});
  564. /* ---------- Квиз ---------- */
  565. const answers = {
  566. q1: "b",
  567. q2: "a",
  568. q3: "b"
  569. };
  570. const checkBtn = document.getElementById("checkQuiz");
  571. const resetBtn = document.getElementById("resetQuiz");
  572. const quizResult = document.getElementById("quizResult");
  573. if (checkBtn) {
  574. checkBtn.addEventListener("click", () => {
  575. let correct = 0;
  576. let answered = 0;
  577. for (const key of Object.keys(answers)) {
  578. const selected = document.querySelector(`input[name="${key}"]:checked`);
  579. if (selected) {
  580. answered++;
  581. if (selected.value === answers[key]) correct++;
  582. }
  583. }
  584. if (!quizResult) return;
  585. if (answered < 3) {
  586. quizResult.innerHTML = `Ответьте на все вопросы. Сейчас выбрано <strong>${answered}</strong> из 3.`;
  587. return;
  588. }
  589. if (correct === 3) {
  590. quizResult.innerHTML = "Верно: <strong>3/3</strong>. Вы корректно различаете принципы ЭОП и тепловизора.";
  591. } else if (correct === 2) {
  592. quizResult.innerHTML = "Результат: <strong>2/3</strong>. Один принцип стоит повторить: различие отражённого и собственного ИК-излучения.";
  593. } else if (correct === 1) {
  594. quizResult.innerHTML = "Результат: <strong>1/3</strong>. Вернитесь к блоку «Научная основа модели» и сравните ЭОП с тепловизором.";
  595. } else {
  596. quizResult.innerHTML = "Результат: <strong>0/3</strong>. Начните с ключевой идеи: ЭОП усиливает свет, тепловизор регистрирует тепловое ИК-излучение.";
  597. }
  598. });
  599. }
  600. if (resetBtn) {
  601. resetBtn.addEventListener("click", () => {
  602. for (const radio of document.querySelectorAll('#quiz input[type="radio"]')) {
  603. radio.checked = false;
  604. }
  605. if (quizResult) quizResult.textContent = "Выберите ответы и нажмите «Проверить».";
  606. });
  607. }
  608. /* ---------- Запуск ---------- */
  609. updateOutputs();
  610. render();
  611. // Плавный "живой" шум сенсоров
  612. setInterval(render, 140);
  613. /* ---------- PWA: регистрация service worker (если файл рядом) ---------- */
  614. if ("serviceWorker" in navigator) {
  615. window.addEventListener("load", () => {
  616. navigator.serviceWorker
  617. .register("sw.js")
  618. .catch(() => { /* тихо игнорируем отсутствие sw.js */ });
  619. });
  620. }
  621. })();