/**
* ==========================================================================
* 倫敦塔益智盒 - 第三步:紅藍球心距 vs 對角逃脫黃線淨距 臨界交叉折線圖
* CrossoverChart.js
* 呈現兩條曲線在 S = 4.10 cm 處的黃金交叉臨界脫出點 (S: 4.00 ~ 4.20 cm)
* ==========================================================================
*/
(function (window) {
'use strict';
/**
* 脫出姿態下的紅藍心距 d_RB(S) 核心幾何公式
* 隨著盒子內徑 S 變大,中層 4 顆綠球退得更開,紅球與藍球能更深地沉入中心,
* 使得脫出姿態下的紅藍球心距離隨 S 變大而單調遞減!
*/
function calculateCritDRB(S) {
const c = S / 2 - 1.0;
const dG = 2 * Math.SQRT2 * c;
const halfDG = dG / 2;
const escNet410 = Math.sqrt(4.10 * 4.10 + 4) - 2.0; // ≈ 2.561798
const c410 = 4.10 / 2 - 1.0; // = 1.05
const halfDG410 = Math.SQRT2 * c410; // ≈ 1.484924
const H410 = escNet410 / 2; // ≈ 1.280899
const L410 = Math.sqrt(H410 * H410 + halfDG410 * halfDG410); // ≈ 1.961046
const L = L410 + (c - c410) * 0.15;
const H = Math.sqrt(Math.max(0.1, L * L - halfDG * halfDG));
return 2 * H;
}
/**
* 對角逃脫黃線淨距 L_net(S) 核心幾何公式
* 扣除兩端球徑之干涉佔據空間後,球體實際可通過的對角淨空間為 √(S² + 4) - 2.0
* 隨盒子內徑 S 變大而單調遞增!
*/
function calculateEscapeNet(S) {
return Math.sqrt(S * S + 4) - 2.0;
}
class CrossoverChart {
constructor(options = {}) {
this.containerId = options.containerId || 'crossover-chart-container';
this.onSelectS = typeof options.onSelectS === 'function' ? options.onSelectS : null;
// 定義 X 軸與 Y 軸範圍
this.sMin = 4.00;
this.sMax = 4.20;
this.dMin = 2.38;
this.dMax = 2.72;
// SVG 尺寸配置
this.width = 500;
this.height = 300;
this.padLeft = 54;
this.padRight = 24;
this.padTop = 38;
this.padBottom = 42;
this.plotW = this.width - this.padLeft - this.padRight; // 422
this.plotH = this.height - this.padTop - this.padBottom; // 220
this.currentS = 4.00;
this.container = null;
this.svg = null;
this.tooltip = null;
this.isPointerDown = false;
// 預先計算採樣點與交叉點
this.criticalS = 4.10;
this.criticalDRB = calculateCritDRB(4.10);
this.criticalNet = calculateEscapeNet(4.10);
this.init();
}
mapX(s) {
return this.padLeft + ((s - this.sMin) / (this.sMax - this.sMin)) * this.plotW;
}
mapY(d) {
return this.padTop + ((this.dMax - d) / (this.dMax - this.dMin)) * this.plotH;
}
invMapX(px) {
const clampedPx = Math.max(this.padLeft, Math.min(this.padLeft + this.plotW, px));
const ratio = (clampedPx - this.padLeft) / this.plotW;
return this.sMin + ratio * (this.sMax - this.sMin);
}
init() {
try {
this.container = document.getElementById(this.containerId);
if (!this.container) {
console.warn(`[CrossoverChart] Container #${this.containerId} not found.`);
return;
}
this.container.innerHTML = '';
this.render();
this.setupInteractions();
this.updateCurrentS(this.currentS);
} catch (err) {
console.error('[CrossoverChart init error]:', err);
}
}
render() {
if (!this.container) return;
// 建立採樣數據路徑 (每 0.002 一個採樣點,保證曲率極致平滑)
const numSamples = 100;
const step = (this.sMax - this.sMin) / numSamples;
let pathDRB = '';
let pathNet = '';
for (let i = 0; i <= numSamples; i++) {
const s = this.sMin + i * step;
const drb = calculateCritDRB(s);
const net = calculateEscapeNet(s);
const px = this.mapX(s).toFixed(2);
const pyDRB = this.mapY(drb).toFixed(2);
const pyNet = this.mapY(net).toFixed(2);
if (i === 0) {
pathDRB = `M ${px} ${pyDRB}`;
pathNet = `M ${px} ${pyNet}`;
} else {
pathDRB += ` L ${px} ${pyDRB}`;
pathNet += ` L ${px} ${pyNet}`;
}
}
// 交叉點位置
const crossX = this.mapX(this.criticalS);
const crossY = this.mapY(this.criticalNet);
// 橫向 Y 網格 (2.40, 2.45, 2.50, 2.55, 2.60, 2.65, 2.70)
const yTicks = [2.40, 2.45, 2.50, 2.55, 2.60, 2.65, 2.70];
let yGridHtml = '';
yTicks.forEach(tickVal => {
const y = this.mapY(tickVal);
yGridHtml += `
${tickVal.toFixed(2)}
`;
});
// 縱向 X 網格 (4.00, 4.05, 4.10, 4.15, 4.20)
const xTicks = [4.00, 4.05, 4.10, 4.15, 4.20];
let xGridHtml = '';
xTicks.forEach(tickVal => {
const x = this.mapX(tickVal);
const isCrit = Math.abs(tickVal - 4.10) < 0.001;
xGridHtml += `
${tickVal.toFixed(2)}
`;
});
const svgHtml = `
`;
this.container.innerHTML = svgHtml;
this.svg = document.getElementById('svg-crossover');
this.tooltip = document.getElementById('crossover-tooltip');
}
setupInteractions() {
if (!this.svg) return;
// 使用 SVG CTM 轉換螢幕座標至 viewBox 座標,確保標準側邊欄與全螢幕等比縮放模式皆精準對位
const getSvgCoords = (clientX, clientY) => {
const rect = this.svg.getBoundingClientRect();
if (typeof this.svg.createSVGPoint === 'function' && typeof this.svg.getScreenCTM === 'function') {
const ctm = this.svg.getScreenCTM();
if (ctm) {
const pt = this.svg.createSVGPoint();
pt.x = clientX;
pt.y = clientY;
const transformed = pt.matrixTransform(ctm.inverse());
return { svgX: transformed.x, svgY: transformed.y, rect };
}
}
return {
svgX: (clientX - rect.left) * (this.width / rect.width),
svgY: (clientY - rect.top) * (this.height / rect.height),
rect
};
};
const handlePointerMove = (e) => {
const clientX = e.clientX || (e.touches && e.touches[0] ? e.touches[0].clientX : 0);
const clientY = e.clientY || (e.touches && e.touches[0] ? e.touches[0].clientY : 0);
const { svgX, rect } = getSvgCoords(clientX, clientY);
// 檢查是否在圖表可視區域內
if (svgX >= this.padLeft && svgX <= this.padLeft + this.plotW) {
const s = this.invMapX(svgX);
this.showHoverTooltip(s, clientX, clientY, rect);
if (this.isPointerDown && this.onSelectS) {
this.onSelectS(s);
}
} else {
this.hideHoverTooltip();
}
};
const handlePointerDown = (e) => {
this.isPointerDown = true;
const clientX = e.clientX || (e.touches && e.touches[0] ? e.touches[0].clientX : 0);
const clientY = e.clientY || (e.touches && e.touches[0] ? e.touches[0].clientY : 0);
const { svgX, rect } = getSvgCoords(clientX, clientY);
if (svgX >= this.padLeft && svgX <= this.padLeft + this.plotW) {
const s = this.invMapX(svgX);
if (this.onSelectS) {
this.onSelectS(s);
}
this.showHoverTooltip(s, clientX, clientY, rect);
}
};
const handlePointerUp = () => {
this.isPointerDown = false;
};
// 滑鼠事件
this.svg.addEventListener('mousemove', handlePointerMove);
this.svg.addEventListener('mousedown', handlePointerDown);
this.svg.addEventListener('mouseleave', () => {
this.isPointerDown = false;
this.hideHoverTooltip();
});
window.addEventListener('mouseup', handlePointerUp);
// 觸控事件
this.svg.addEventListener('touchstart', (e) => {
handlePointerDown(e);
}, { passive: true });
this.svg.addEventListener('touchmove', (e) => {
handlePointerMove(e);
}, { passive: true });
window.addEventListener('touchend', handlePointerUp);
}
showHoverTooltip(s, clientX, clientY, rect) {
if (!this.tooltip) return;
const drb = calculateCritDRB(s);
const net = calculateEscapeNet(s);
const diff = drb - net;
const isEscapable = diff <= 0.0001;
const hoverLine = document.getElementById('hover-line-x');
const hoverCursorGroup = document.getElementById('crossover-hover-cursor');
if (hoverLine && hoverCursorGroup) {
const px = this.mapX(s);
hoverLine.setAttribute('x1', px);
hoverLine.setAttribute('x2', px);
hoverCursorGroup.style.display = 'block';
}
const stateText = isEscapable
? '✨ 通道順暢可脫出!'
: `⚠️ 卡死 (超出 ${Math.abs(diff).toFixed(3)} cm)`;
this.tooltip.innerHTML = `
📐 盒子大小 S = ${s.toFixed(2)} cm
紅藍心距 (dRB):
${drb.toFixed(3)} cm
黃線淨距 (Lnet):
${net.toFixed(3)} cm
狀態判定:${stateText}
`;
// 設定 Tooltip 位置(避開邊界裁切)
const containerRect = this.container.getBoundingClientRect();
const safePadX = Math.min(95, containerRect.width / 2);
const relX = Math.max(safePadX, Math.min(containerRect.width - safePadX, clientX - containerRect.left));
const relY = Math.max(115, clientY - containerRect.top);
this.tooltip.style.left = `${relX}px`;
this.tooltip.style.top = `${relY}px`;
this.tooltip.classList.add('visible');
}
hideHoverTooltip() {
if (this.tooltip) {
this.tooltip.classList.remove('visible');
}
const hoverCursorGroup = document.getElementById('crossover-hover-cursor');
if (hoverCursorGroup) {
hoverCursorGroup.style.display = 'none';
}
}
/**
* 外部即時連動呼叫:更新目前滑桿所在之 S 值
*/
updateCurrentS(s) {
this.currentS = parseFloat(s);
const drb = calculateCritDRB(this.currentS);
const net = calculateEscapeNet(this.currentS);
const diff = drb - net;
const isEscapable = diff <= 0.0001;
// 1. 更新卡片上方看板文字
const bannerS = document.getElementById('crossover-banner-s');
const bannerDRB = document.getElementById('crossover-banner-drb');
const bannerLnet = document.getElementById('crossover-banner-lnet');
const bannerVerdict = document.getElementById('crossover-banner-verdict');
if (bannerS) bannerS.innerText = this.currentS.toFixed(2) + ' cm';
if (bannerDRB) bannerDRB.innerText = drb.toFixed(3) + ' cm';
if (bannerLnet) bannerLnet.innerText = net.toFixed(3) + ' cm';
if (bannerVerdict) {
if (isEscapable) {
bannerVerdict.className = 'verdict-tag escaped';
bannerVerdict.innerText = '✨ 通道開啟!(d_RB ≤ 黃線淨距,順利脫出)';
} else {
bannerVerdict.className = 'verdict-tag blocked';
bannerVerdict.innerText = `⚠️ 幾何卡死 (d_RB > 黃線淨距,超出 ${Math.abs(diff).toFixed(3)} cm)`;
}
}
// 2. 更新 SVG 內部當前位置指示器
const trackerGroup = document.getElementById('crossover-tracker');
if (!trackerGroup) return;
// 僅在 [4.00, 4.20] 範圍內顯示
if (this.currentS >= this.sMin && this.currentS <= this.sMax) {
trackerGroup.style.display = 'block';
const curX = this.mapX(this.currentS);
const curY_drb = this.mapY(drb);
const curY_net = this.mapY(net);
const line = document.getElementById('tracker-line');
const dotDRB = document.getElementById('tracker-dot-drb');
const dotNet = document.getElementById('tracker-dot-net');
const badge = document.getElementById('tracker-badge');
const textS = document.getElementById('tracker-text-s');
if (line) {
line.setAttribute('x1', curX);
line.setAttribute('x2', curX);
}
if (dotDRB) {
dotDRB.setAttribute('cx', curX);
dotDRB.setAttribute('cy', curY_drb);
}
if (dotNet) {
dotNet.setAttribute('cx', curX);
dotNet.setAttribute('cy', curY_net);
}
if (badge) {
badge.setAttribute('transform', `translate(${curX}, ${this.padTop - 8})`);
}
if (textS) {
textS.textContent = this.currentS.toFixed(2);
}
} else {
trackerGroup.style.display = 'none';
}
}
}
// 掛載至全域 window
window.CrossoverChart = CrossoverChart;
/**
* 便捷工廠函數
*/
window.initCrossoverChart = function (options) {
window.crossoverChart = new CrossoverChart(options);
return window.crossoverChart;
};
})(window);