import base64

import json

import re

from pathlib import Path

import numpy as np

 

INPUT_TERRAIN_JSON = "chubu_hokuriku_hires_3d.json"

INPUT_ASSETS_JSON = "airspaces_and_f15j.json"

OUTPUT_HTML = "chubu_hokuriku_flight_3d.html"

 

MAX_GRID_DIM = 460

DEFAULT_Z_SCALE = 5.0


 

def parse_coord(val) -> float:

    if isinstance(val, (int, float)):

        return float(val)

    s = str(val).strip().upper()

    m = re.match(r"^(\d{2,3})(\d{2})(\d{2}(?:\.\d+)?)([NSEW])$", s)

    if m:

        res = float(m.group(1)) + float(m.group(2)) / 60.0 + float(m.group(3)) / 3600.0

        return -res if m.group(4) in ("S", "W") else res

    nums = re.findall(r"\d+(?:\.\d+)?", s)

    if len(nums) >= 3:

        res = float(nums[0]) + float(nums[1]) / 60.0 + float(nums[2]) / 3600.0

        return -res if ("S" in s or "W" in s) else res

    return float(nums[0])


 

def points_in_polygon(X, Y, poly_coords):

    inside = np.zeros(X.shape, dtype=bool)

    n = len(poly_coords)

    for i in range(n):

        j = (i - 1) % n

        xi, yi = poly_coords[i]

        xj, yj = poly_coords[j]

        cond1 = (yi > Y) != (yj > Y)

        denom = (yj - yi) if (yj != yi) else 1e-12

        x_intersect = (xj - xi) * (Y - yi) / denom + xi

        inside ^= (cond1 & (X < x_intersect))

    return inside


 

def triangulate_polygon(poly):

    pts = [list(p) for p in poly]

    if len(pts) > 2 and pts[0] == pts[-1]:

        pts.pop()

    n = len(pts)

    if n < 3:

        return [], []

    area = sum(pts[i][0] * pts[(i + 1) % n][1] - pts[(i + 1) % n][0] * pts[i][1] for i in range(n))

    if area < 0:

        pts.reverse()

 

    def cross(a, b, c):

        return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])

 

    def point_in_tri(p, a, b, c):

        return cross(a, b, p) >= -1e-12 and cross(b, c, p) >= -1e-12 and cross(c, a, p) >= -1e-12

 

    indices = list(range(n))

    triangles = []

    guard = 0

    while len(indices) > 3 and guard < n * n:

        guard += 1

        ear_found = False

        m = len(indices)

        for i in range(m):

            i0, i1, i2 = indices[(i - 1) % m], indices[i], indices[(i + 1) % m]

            a, b, c = pts[i0], pts[i1], pts[i2]

            if cross(a, b, c) > 1e-12:

                if not any(idx not in (i0, i1, i2) and point_in_tri(pts[idx], a, b, c) for idx in indices):

                    triangles.append((i0, i1, i2))

                    indices.pop(i)

                    ear_found = True

                    break

        if not ear_found:

            break

    if len(indices) == 3:

        triangles.append((indices[0], indices[1], indices[2]))

    return pts, triangles


 

def arr_to_b64(arr: np.ndarray) -> str:

    return base64.b64encode(arr.tobytes()).decode("ascii")


 

HTML_TEMPLATE = r"""<!DOCTYPE html>

<html lang="ja">

<head>

<meta charset="utf-8">

<title>WebGL 60FPS 3Dフライト・リプレイヤー (超大容量・全サンプリング対応)</title>

<style>

  * { box-sizing: border-box; }

  body { margin:0; padding:8px; background:#0d1117; color:#e6edf3; font-family:"Segoe UI","Yu Gothic UI",sans-serif; height:100vh; display:flex; flex-direction:column; overflow:hidden; user-select:none; }

  .toolbar { display:flex; flex-wrap:wrap; align-items:center; gap:6px; margin-bottom:6px; background:#161b22; border:1px solid #30363d; padding:6px 10px; border-radius:6px; font-size:12px; }

  button, select { background:#21262d; color:#e6edf3; border:1px solid #30363d; padding:5px 10px; border-radius:4px; cursor:pointer; font-size:12px; }

  button:hover { background:#30363d; }

  button.primary { background:#238636; border-color:#2ea043; font-weight:bold; }

  button.primary:hover { background:#2ea043; }

  button.chase { background:#8957e5; border-color:#a371f7; font-weight:bold; }

  button.chase:hover { background:#a371f7; }

  .sep { width:1px; height:20px; background:#30363d; margin:0 3px; }

  label { display:flex; align-items:center; gap:4px; cursor:pointer; }

  .main-area { position:relative; flex:1; min-height:0; border:1px solid #30363d; border-radius:6px; overflow:hidden; background:#0b1016; }

  canvas.gl-layer { position:absolute; inset:0; width:100%; height:100%; display:block; }

  #overlay { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; }

 

  .hud { position:absolute; top:10px; right:10px; width:260px; background:rgba(13,17,23,0.82); border:1px solid #30363d; border-radius:8px; padding:10px 12px; pointer-events:none; font-family:Consolas, monospace; }

  .hud-title { font-size:11px; color:#58a6ff; font-weight:bold; letter-spacing:1px; margin-bottom:6px; display:flex; justify-content:space-between; }

  .hud-grid { display:grid; grid-template-columns:1fr 1fr; gap:5px 8px; font-size:12px; }

  .hud-val { color:#7ee787; font-weight:bold; font-size:13px; }

  .hud-lbl { color:#8b949e; font-size:10px; display:block; }

  .attitude-wrap { display:flex; align-items:center; gap:10px; margin-top:8px; padding-top:8px; border-top:1px solid #30363d; }

  .adi-box { width:70px; height:70px; border-radius:50%; overflow:hidden; border:2px solid #8b949e; position:relative; flex-shrink:0; background:#1c2128; }

  .cam-hint { position:absolute; bottom:10px; left:10px; background:rgba(13,17,23,0.75); border:1px solid #30363d; border-radius:6px; padding:5px 10px; font-size:11px; color:#9fb1c6; pointer-events:none; }

 

  .player-bar { margin-top:6px; background:#161b22; border:1px solid #30363d; border-radius:6px; padding:8px 12px; display:flex; flex-direction:column; gap:6px; }

  .player-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:12px; }

  .seek-wrap { flex:1; display:flex; align-items:center; gap:8px; min-width:220px; }

  input[type=range] { cursor:pointer; }

  #seek-bar { flex:1; }

  #mini-chart { width:100%; height:42px; background:#0d1117; border-radius:4px; border:1px solid #21262d; cursor:pointer; }

  .csv-options { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:11px; color:#8b949e; border-top:1px solid #21262d; padding-top:5px; }

  input[type=file] { display:none; }

  .file-btn { background:#1f6feb; border:1px solid #58a6ff; color:#fff; padding:5px 12px; border-radius:4px; cursor:pointer; font-weight:bold; font-size:12px; }

  .file-btn:hover { background:#388bfd; }

</style>

</head>

<body>

 

  <div class="toolbar">

    <label class="file-btn">📂 CSV読込<input type="file" id="csv-input" accept=".csv,.txt"></label>

    <button onclick="loadDemoFlight()">▶ デモ飛行データ</button>

    <div class="sep"></div>

    <button class="chase" onclick="snapToAircraft()">🎯 機体にズーム追従</button>

    <label><input type="checkbox" id="chk-follow">自動追従</label>

    <button onclick="resetCamera()">🗺️ 全体俯瞰</button>

    <div class="sep"></div>

    <button onclick="zoomCamera(0.6)">+ 拡大</button>

    <button onclick="zoomCamera(1.6)">- 縮小</button>

    <div class="sep"></div>

    <span>高さ:</span>

    <select id="sel-z">

      <option value="1">1x(実寸)</option><option value="3">3x</option>

      <option value="5" selected>5x</option><option value="10">10x</option>

    </select>

    <span>機体:</span>

    <select id="sel-f15">

      <option value="1" selected>1x (実寸19.4m)</option>

      <option value="10">10x</option>

      <option value="50">50x</option>

      <option value="200">200x</option>

    </select>

    <div class="sep"></div>

    <label><input type="checkbox" id="chk-lake" checked>湖</label>

    <label><input type="checkbox" id="chk-base" checked>基地</label>

    <label><input type="checkbox" id="chk-airspace" checked>空域</label>

    <label><input type="checkbox" id="chk-trail" checked>全航跡</label>

    <label><input type="checkbox" id="chk-drop" checked>対地赤線</label>

  </div>

 

  <div class="main-area" id="canvas-wrap">

    <canvas id="glcanvas" class="gl-layer"></canvas>

    <canvas id="overlay"></canvas>

    <div class="cam-hint">左ドラッグ: 回転 / 右ドラッグ(or Shift+左): 移動 / ホイール: 超広域〜実寸ズーム</div>

 

    <div class="hud">

      <div class="hud-title"><span>F-15J TELEMETRY (60FPS WebGL)</span><span id="hud-status">STANDBY</span></div>

      <div class="hud-grid">

        <div><span class="hud-lbl">TIME</span><span class="hud-val" id="hud-time">00:00.0</span></div>

        <div><span class="hud-lbl">SPEED</span><span class="hud-val" id="hud-spd">---</span></div>

        <div><span class="hud-lbl">ALT (MSL)</span><span class="hud-val" id="hud-alt">---</span></div>

        <div><span class="hud-lbl">AGL (対地高度)</span><span class="hud-val" id="hud-agl">---</span></div>

        <div><span class="hud-lbl">VSI (昇降率)</span><span class="hud-val" id="hud-vsi">---</span></div>

        <div><span class="hud-lbl">LAT / LON</span><span class="hud-val" style="font-size:11px;" id="hud-pos">---</span></div>

      </div>

      <div class="attitude-wrap">

        <div class="adi-box">

          <svg viewBox="-50 -50 100 100" width="70" height="70">

            <g id="adi-horizon" transform="rotate(0) translate(0, 0)">

              <rect x="-100" y="-120" width="200" height="120" fill="#2374ab"/>

              <rect x="-100" y="0" width="200" height="120" fill="#6b4c2e"/>

              <line x1="-100" y1="0" x2="100" y2="0" stroke="#ffffff" stroke-width="2"/>

              <line x1="-20" y1="-15" x2="20" y2="-15" stroke="#fff" stroke-width="1"/>

              <line x1="-20" y1="15" x2="20" y2="15" stroke="#fff" stroke-width="1"/>

            </g>

            <path d="M -22,0 L -8,0 L 0,6 L 8,0 L 22,0" fill="none" stroke="#ffeb3b" stroke-width="2.5"/>

            <circle cx="0" cy="0" r="2" fill="#ffeb3b"/>

          </svg>

        </div>

        <div style="font-size:11px; line-height:1.5;">

          <div>HDG(Yaw): <span class="hud-val" id="hud-yaw">---</span></div>

          <div>PITCH: <span class="hud-val" id="hud-pitch">---</span></div>

          <div>ROLL: <span class="hud-val" id="hud-roll">---</span></div>

        </div>

      </div>

    </div>

  </div>

 

  <div class="player-bar">

    <canvas id="mini-chart"></canvas>

    <div class="player-row">

      <button id="btn-play" class="primary" onclick="togglePlay()" disabled>▶ 再生</button>

      <button onclick="stopFlight()" id="btn-stop" disabled>⏮ 先頭</button>

      <span>速度:</span>

      <select id="sel-play-spd">

        <option value="0.5">0.5x</option><option value="1" selected>1x</option>

        <option value="2">2x</option><option value="5">5x</option>

        <option value="10">10x</option><option value="30">30x</option>

        <option value="60">60x</option>

      </select>

      <div class="seek-wrap">

        <input id="seek-bar" type="range" min="0" max="1000" value="0" disabled oninput="onSeekPermille(this.value)">

        <span id="frame-info" style="min-width:190px; text-align:right;">CSV未読込</span>

      </div>

    </div>

    <div class="csv-options">

      <span>CSV設定:</span>

      <label>読込間引き: <select id="opt-thin" onchange="reparseIfLoaded()" title="100Hz等の巨大ログを省メモリ化する際の間引き">

        <option value="1" selected>1/1 (全点)</option><option value="2">1/2</option>

        <option value="5">1/5</option><option value="10">1/10</option><option value="20">1/20</option>

      </select></label>

      <label>高度: <select id="opt-alt-unit" onchange="reparseIfLoaded()"><option value="m">m</option><option value="ft">ft</option></select></label>

      <label>速度: <select id="opt-spd-unit" onchange="reparseIfLoaded()"><option value="kt">kt</option><option value="kmh">km/h</option><option value="ms">m/s</option></select></label>

      <label>角度: <select id="opt-ang-unit" onchange="reparseIfLoaded()"><option value="deg">度(deg)</option><option value="rad">rad</option></select></label>

      <label>XYZ順: <select id="opt-xyz-map" onchange="reparseIfLoaded()">

        <option value="RPY">X=Roll / Y=Pitch / Z=Yaw</option>

        <option value="PRY">X=Pitch / Y=Roll / Z=Yaw</option>

      </select></label>

      <label><input type="checkbox" id="opt-inv-roll" onchange="reparseIfLoaded()">Roll反転</label>

      <label><input type="checkbox" id="opt-inv-pitch" onchange="reparseIfLoaded()">Pitch反転</label>

    </div>

  </div>

 

<script>

const REF_LON = __REF_LON__, REF_LAT = __REF_LAT__;

const M_PER_LON = 111320.0 * Math.cos(REF_LAT * Math.PI / 180.0);

const M_PER_LAT = 110960.0;

const LON_MIN = __LON_MIN__, DLON = __DLON__, LAT_MAX = __LAT_MAX__, DLAT = __DLAT__;

const GRID_H = __GRID_H__, GRID_W = __GRID_W__;

 

function b64ToBuf(b64) {

  const bin = atob(b64);

  const len = bin.length;

  const bytes = new Uint8Array(len);

  for (let i = 0; i < len; i++) bytes[i] = bin.charCodeAt(i);

  return bytes.buffer;

}

 

function lonLatToMeters(lon, lat) {

  return [(lon - REF_LON) * M_PER_LON, (lat - REF_LAT) * M_PER_LAT];

}

 

const ELEV_GRID = new Float32Array(b64ToBuf("__ELEV_GRID_B64__"));

const CHUNKS_RAW = __CHUNKS_META__;

const LAKES_RAW = __LAKES_JSON__;

const AIRBASES = __AIRBASES_JSON__;

const AIRSPACES_RAW = __AIRSPACES_JSON__;

const F15_RAW = __F15_JSON__;

 

function getGroundElev(lon, lat) {

  const ix = Math.round((lon - LON_MIN) / DLON);

  const iy = Math.round((LAT_MAX - lat) / DLAT);

  if (ix < 0 || ix >= GRID_W || iy < 0 || iy >= GRID_H) return 0;

  const v = ELEV_GRID[iy * GRID_W + ix];

  return isNaN(v) ? 0 : v;

}

 

const glCanvas = document.getElementById("glcanvas");

const ovCanvas = document.getElementById("overlay");

const ovCtx = ovCanvas.getContext("2d");

const gl = glCanvas.getContext("webgl", { antialias: true, alpha: false });

if (!gl) alert("このブラウザはWebGLに対応していません。");

 

function compileShader(type, src) {

  const s = gl.createShader(type);

  gl.shaderSource(s, src);

  gl.compileShader(s);

  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));

  return s;

}

function createProgram(vs, fs) {

  const p = gl.createProgram();

  gl.attachShader(p, compileShader(gl.VERTEX_SHADER, vs));

  gl.attachShader(p, compileShader(gl.FRAGMENT_SHADER, fs));

  gl.linkProgram(p);

  if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));

  return p;

}

 

const terrainProg = createProgram(`

  attribute vec3 aPos;

  attribute vec2 aGrad;

  attribute vec3 aColor;

  uniform mat4 uVP;

  uniform float uZScale;

  varying vec3 vColor;

  varying float vDist;

  void main() {

    vec4 wp = vec4(aPos.x, aPos.y, aPos.z * uZScale, 1.0);

    gl_Position = uVP * wp;

    vDist = gl_Position.w;

    vec3 n = normalize(vec3(-aGrad.x * uZScale, -aGrad.y * uZScale, 1.0));

    vec3 lightDir = normalize(vec3(-0.65, 0.55, 0.72));

    float diff = max(dot(n, lightDir), 0.0);

    float shade = 0.36 + 0.76 * diff;

    vColor = aColor * shade;

  }

`, `

  precision mediump float;

  varying vec3 vColor;

  varying float vDist;

  void main() {

    float fog = clamp((vDist - 350000.0) / 850000.0, 0.0, 0.55);

    vec3 col = mix(vColor, vec3(0.05, 0.07, 0.10), fog);

    gl_FragColor = vec4(col, 1.0);

  }

`);

 

const meshProg = createProgram(`

  attribute vec3 aPos;

  attribute vec3 aNormal;

  attribute vec3 aColor;

  uniform mat4 uVP;

  uniform mat4 uModel;

  uniform float uZScale;

  uniform float uApplyZScale;

  uniform float uAmbient;

  varying vec3 vColor;

  void main() {

    vec4 wp = uModel * vec4(aPos, 1.0);

    if (uApplyZScale > 0.5) wp.z *= uZScale;

    gl_Position = uVP * wp;

    vec3 n = normalize(mat3(uModel) * aNormal);

    vec3 lightDir = normalize(vec3(-0.5, 0.5, 0.8));

    float diff = max(dot(n, lightDir), 0.0);

    vColor = aColor * (uAmbient + (1.0 - uAmbient) * diff);

  }

`, `

  precision mediump float;

  varying vec3 vColor;

  void main() {

    gl_FragColor = vec4(vColor, 1.0);

  }

`);

 

const terrainChunks = CHUNKS_RAW.map(c => {

  const pb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, pb); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(b64ToBuf(c.pos)), gl.STATIC_DRAW);

  const gb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, gb); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(b64ToBuf(c.grad)), gl.STATIC_DRAW);

  const cb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cb); gl.bufferData(gl.ARRAY_BUFFER, new Uint8Array(b64ToBuf(c.col)), gl.STATIC_DRAW);

  const ib = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib);

  const idxArr = new Uint16Array(b64ToBuf(c.idx));

  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idxArr, gl.STATIC_DRAW);

  return { pb, gb, cb, ib, count: idxArr.length };

});

 

const lakeMeshes = LAKES_RAW.map(lk => {

  const n = lk.tris.length;

  const pos = new Float32Array(n * 3), norm = new Float32Array(n * 3), col = new Float32Array(n * 3);

  for (let i = 0; i < n; i++) {

    const p = lk.pts[lk.tris[i]];

    const [mx, my] = lonLatToMeters(p[0], p[1]);

    pos[i*3] = mx; pos[i*3+1] = my; pos[i*3+2] = lk.elevation_m;

    norm[i*3+2] = 1.0;

    col[i*3] = 0.22; col[i*3+1] = 0.74; col[i*3+2] = 0.97;

  }

  const pb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, pb); gl.bufferData(gl.ARRAY_BUFFER, pos, gl.STATIC_DRAW);

  const nb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, nb); gl.bufferData(gl.ARRAY_BUFFER, norm, gl.STATIC_DRAW);

  const cb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cb); gl.bufferData(gl.ARRAY_BUFFER, col, gl.STATIC_DRAW);

  return { pb, nb, cb, count: n };

});

 

const f15Count = F15_RAW.pos.length / 3;

const f15PB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, f15PB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(F15_RAW.pos), gl.STATIC_DRAW);

const f15NB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, f15NB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(F15_RAW.norm), gl.STATIC_DRAW);

const f15CB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, f15CB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(F15_RAW.col), gl.STATIC_DRAW);

 

const airLines = [], airCols = [];

function hexToRgb(hex) {

  const v = parseInt(hex.slice(1), 16);

  return [((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255];

}

AIRSPACES_RAW.forEach(asp => {

  const rgb = hexToRgb(asp.color);

  const poly = asp.polygon.map(p => lonLatToMeters(p[0], p[1]));

  const z0 = asp.min_alt_m, z1 = asp.max_alt_m;

  const pushSeg = (ax, ay, az, bx, by, bz) => {

    airLines.push(ax, ay, az, bx, by, bz);

    airCols.push(...rgb, ...rgb);

  };

  for (let i = 0; i < poly.length - 1; i++) {

    const a = poly[i], b = poly[i+1];

    pushSeg(a[0], a[1], z0, b[0], b[1], z0);

    pushSeg(a[0], a[1], z1, b[0], b[1], z1);

    pushSeg(a[0], a[1], z0, a[0], a[1], z1);

  }

  const cLon = asp.polygon.slice(0, -1).reduce((s, p) => s + p[0], 0) / (asp.polygon.length - 1);

  const cLat = asp.polygon.slice(0, -1).reduce((s, p) => s + p[1], 0) / (asp.polygon.length - 1);

  const [cx, cy] = lonLatToMeters(cLon, cLat);

  asp.labelPos = [cx, cy, z1];

});

const airPB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, airPB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(airLines), gl.STATIC_DRAW);

const airCB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, airCB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(airCols), gl.STATIC_DRAW);

const airNB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, airNB); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(airLines.length).fill(1), gl.STATIC_DRAW);

const airCount = airLines.length / 3;

 

const trailPB = gl.createBuffer();

const trailFullColB = gl.createBuffer();

const trailNB = gl.createBuffer();

let trailCount = 0;

 

const dropPB = gl.createBuffer();

const dropCB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, dropCB);

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 0.32, 0.32, 1, 0.32, 0.32]), gl.STATIC_DRAW);

const dropNB = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, dropNB);

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0,1, 0,0,1]), gl.STATIC_DRAW);

 

function mulMat4(a, b) {

  const o = new Float32Array(16);

  for (let c = 0; c < 4; c++) {

    for (let r = 0; r < 4; r++) {

      o[c*4+r] = a[r]*b[c*4] + a[4+r]*b[c*4+1] + a[8+r]*b[c*4+2] + a[12+r]*b[c*4+3];

    }

  }

  return o;

}

function matPerspective(fovY, aspect, near, far) {

  const f = 1.0 / Math.tan(fovY / 2), nf = 1.0 / (near - far);

  return new Float32Array([f/aspect,0,0,0, 0,f,0,0, 0,0,(far+near)*nf,-1, 0,0,2*far*near*nf,0]);

}

function matLookAt(eye, ctr) {

  let fx = ctr[0]-eye[0], fy = ctr[1]-eye[1], fz = ctr[2]-eye[2];

  const fl = Math.hypot(fx, fy, fz) || 1;

  fx /= fl; fy /= fl; fz /= fl;

  let sx = fy, sy = -fx, sz = 0;

  const sl = Math.hypot(sx, sy, sz) || 1;

  sx /= sl; sy /= sl; sz /= sl;

  const ux = sy*fz - sz*fy, uy = sz*fx - sx*fz, uz = sx*fy - sy*fx;

  return new Float32Array([

    sx, ux, -fx, 0,  sy, uy, -fy, 0,  sz, uz, -fz, 0,

    -(sx*eye[0]+sy*eye[1]+sz*eye[2]),

    -(ux*eye[0]+uy*eye[1]+uz*eye[2]),

    (fx*eye[0]+fy*eye[1]+fz*eye[2]), 1

  ]);

}

function buildModelMat(tx, ty, tz, rollDeg, pitchDeg, yawDeg, scale) {

  const rr = rollDeg * Math.PI/180, pr = pitchDeg * Math.PI/180, yr = yawDeg * Math.PI/180;

  const cr = Math.cos(rr), sr = Math.sin(rr);

  const cp = Math.cos(pr), sp = Math.sin(pr);

  const cy = Math.cos(yr), sy = Math.sin(yr);

  const mR = [cr,0,-sr,0, 0,1,0,0, sr,0,cr,0, 0,0,0,1];

  const mP = [1,0,0,0, 0,cp,sp,0, 0,-sp,cp,0, 0,0,0,1];

  const mY = [cy,-sy,0,0, sy,cy,0,0, 0,0,1,0, 0,0,0,1];

  const mS = [scale,0,0,0, 0,scale,0,0, 0,0,scale,0, 0,0,0,1];

  const mT = [1,0,0,0, 0,1,0,0, 0,0,1,0, tx,ty,tz,1];

  return mulMat4(mT, mulMat4(mS, mulMat4(mY, mulMat4(mP, mR))));

}

 

const IDENTITY_MAT = new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]);

 

let camTarget = [0, 0, 5000];

let camYaw = 0.0;

let camPitch = 0.72;

let camDist = 420000.0;

 

function resetCamera() {

  document.getElementById("chk-follow").checked = false;

  camTarget = [0, 0, 5000]; camYaw = 0.0; camPitch = 0.72; camDist = 420000.0;

}

function zoomCamera(factor) {

  camDist = Math.max(25.0, Math.min(1400000.0, camDist * factor));

}

function snapToAircraft() {

  if (!fStore || fStore.len === 0) { alert("先にCSVまたはデモ飛行データを読み込んでください。"); return; }

  const f = sampleFlightAt(simTime);

  const zScale = parseFloat(document.getElementById("sel-z").value);

  camTarget = [f.mx, f.my, f.alt * zScale];

  camYaw = (f.yaw * Math.PI) / 180.0;

  camPitch = 0.28;

  camDist = 90.0;

  document.getElementById("chk-follow").checked = true;

}

 

let dragBtn = -1, lastMX = 0, lastMY = 0;

glCanvas.addEventListener("contextmenu", e => e.preventDefault());

glCanvas.addEventListener("mousedown", e => { dragBtn = e.button; lastMX = e.clientX; lastMY = e.clientY; });

window.addEventListener("mouseup", () => { dragBtn = -1; });

window.addEventListener("mousemove", e => {

  if (dragBtn === -1) return;

  const dx = e.clientX - lastMX, dy = e.clientY - lastMY;

  lastMX = e.clientX; lastMY = e.clientY;

  if (dragBtn === 0 && !e.shiftKey) {

    camYaw += dx * 0.006;

    camPitch = Math.max(0.03, Math.min(1.54, camPitch + dy * 0.006));

  } else {

    document.getElementById("chk-follow").checked = false;

    const spd = camDist * 0.0014;

    const rx = Math.cos(camYaw), ry = -Math.sin(camYaw);

    const fx = Math.sin(camYaw), fy = Math.cos(camYaw);

    camTarget[0] -= (dx * rx - dy * fx) * spd;

    camTarget[1] -= (dx * ry - dy * fy) * spd;

  }

});

glCanvas.addEventListener("wheel", e => {

  e.preventDefault();

  camDist = Math.max(25.0, Math.min(1400000.0, camDist * Math.pow(1.0015, e.deltaY)));

}, { passive: false });

 

// ==========================================

// 省メモリ TypedArray フライトストア (数百万行対応・GCゼロ)

// ==========================================

class FlightStore {

  constructor(initCap = 16384) {

    this.cap = initCap;

    this.len = 0;

    this.t     = new Float64Array(initCap);

    this.lon   = new Float64Array(initCap);

    this.lat   = new Float64Array(initCap);

    this.mx    = new Float32Array(initCap);

    this.my    = new Float32Array(initCap);

    this.alt   = new Float32Array(initCap);

    this.spd   = new Float32Array(initCap);

    this.roll  = new Float32Array(initCap);

    this.pitch = new Float32Array(initCap);

    this.yaw   = new Float32Array(initCap);

    this.vsi   = new Float32Array(initCap);

  }

  push(t, lon, lat, mx, my, alt, spd, roll, pitch, yaw) {

    if (this.len >= this.cap) {

      const nc = this.cap * 2;

      const g64 = a => { const n = new Float64Array(nc); n.set(a); return n; };

      const g32 = a => { const n = new Float32Array(nc); n.set(a); return n; };

      this.t = g64(this.t); this.lon = g64(this.lon); this.lat = g64(this.lat);

      this.mx = g32(this.mx); this.my = g32(this.my); this.alt = g32(this.alt);

      this.spd = g32(this.spd); this.roll = g32(this.roll); this.pitch = g32(this.pitch);

      this.yaw = g32(this.yaw); this.vsi = g32(this.vsi);

      this.cap = nc;

    }

    const k = this.len++;

    this.t[k] = t; this.lon[k] = lon; this.lat[k] = lat;

    this.mx[k] = mx; this.my[k] = my; this.alt[k] = alt;

    this.spd[k] = spd; this.roll[k] = roll; this.pitch[k] = pitch; this.yaw[k] = yaw;

  }

}

 

let currentSource = null;  // { type: "file", file } or { type: "text", text }

let loadJobId = 0;

let fStore = null;

let totalDuration = 0;

let simTime = 0;

let currentIdx = 0;

let isPlaying = false;

 

document.getElementById("csv-input").addEventListener("change", e => {

  const file = e.target.files[0];

  if (!file) return;

  currentSource = { type: "file", file };

  loadFromSource(currentSource);

});

 

function reparseIfLoaded() {

  if (currentSource) loadFromSource(currentSource);

}

 

function parseTimeVal(s) {

  const str = String(s).trim();

  if (/^\d{1,2}:\d{2}:\d{2}/.test(str)) {

    const p = str.split(":").map(Number);

    return p[0]*3600 + p[1]*60 + p[2];

  }

  return parseFloat(str);

}

 

function findCol(headers, candidates) {

  const low = headers.map(h => h.trim().toLowerCase());

  for (const c of candidates) { const i = low.findIndex(h => h === c); if (i !== -1) return i; }

  for (const c of candidates) { const i = low.findIndex(h => h.includes(c)); if (i !== -1) return i; }

  return -1;

}

 

function findFrameIndex(t) {

  if (!fStore || fStore.len === 0) return 0;

  let lo = 0, hi = fStore.len - 1;

  const ts = fStore.t;

  while (lo < hi) {

    const mid = (lo + hi + 1) >> 1;

    if (ts[mid] <= t) lo = mid;

    else hi = mid - 1;

  }

  return lo;

}

 

// 任意の時刻 t における連続補間フレームを取得 (0.1Hzでも100Hzでも60FPS滑らか)

function sampleFlightAt(t) {

  const idx = findFrameIndex(t);

  const nextIdx = Math.min(fStore.len - 1, idx + 1);

  const t0 = fStore.t[idx], t1 = fStore.t[nextIdx];

  const frac = (nextIdx > idx && t1 > t0) ? Math.max(0, Math.min(1, (t - t0) / (t1 - t0))) : 0;

  const lerpAng = (a, b) => a + ((((b - a + 540) % 360) - 180) * frac);

 

  return {

    idx,

    t,

    lon:   fStore.lon[idx]   + (fStore.lon[nextIdx]   - fStore.lon[idx])   * frac,

    lat:   fStore.lat[idx]   + (fStore.lat[nextIdx]   - fStore.lat[idx])   * frac,

    mx:    fStore.mx[idx]    + (fStore.mx[nextIdx]    - fStore.mx[idx])    * frac,

    my:    fStore.my[idx]    + (fStore.my[nextIdx]    - fStore.my[idx])    * frac,

    alt:   fStore.alt[idx]   + (fStore.alt[nextIdx]   - fStore.alt[idx])   * frac,

    spd:   fStore.spd[idx]   + (fStore.spd[nextIdx]   - fStore.spd[idx])   * frac,

    roll:  lerpAng(fStore.roll[idx], fStore.roll[nextIdx]),

    pitch: fStore.pitch[idx] + (fStore.pitch[nextIdx] - fStore.pitch[idx]) * frac,

    yaw:   lerpAng(fStore.yaw[idx],  fStore.yaw[nextIdx]),

    vsi:   fStore.vsi[idx]   + (fStore.vsi[nextIdx]   - fStore.vsi[idx])   * frac,

  };

}

 

async function loadFromSource(source) {

  const myJob = ++loadJobId;

  stopFlight();

  document.getElementById("btn-play").disabled = true;

  document.getElementById("btn-stop").disabled = true;

  document.getElementById("seek-bar").disabled = true;

  document.getElementById("hud-status").textContent = "LOADING 0%";

  document.getElementById("frame-info").textContent = "読込中...";

 

  const thinStep = Math.max(1, parseInt(document.getElementById("opt-thin").value, 10));

  const altScale = document.getElementById("opt-alt-unit").value === "ft" ? 0.3048 : 1.0;

  const spdUnit = document.getElementById("opt-spd-unit").value;

  const angScale = document.getElementById("opt-ang-unit").value === "rad" ? (180.0 / Math.PI) : 1.0;

  const invR = document.getElementById("opt-inv-roll").checked ? -1.0 : 1.0;

  const invP = document.getElementById("opt-inv-pitch").checked ? -1.0 : 1.0;

  const xyzMap = document.getElementById("opt-xyz-map").value;

 

  const estBytes = source.type === "file" ? source.file.size : source.text.length;

  const estRows = Math.min(2500000, Math.max(4096, Math.ceil(estBytes / (38 * thinStep)) + 1024));

  const store = new FlightStore(estRows);

 

  let colsMeta = null;

  let t0 = null;

  let rowCounter = 0;

 

  function processLines(lines) {

    for (let li = 0; li < lines.length; li++) {

      const line = lines[li].trim();

      if (!line) continue;

 

      if (!colsMeta) {

        const headers = line.split(",").map(h => h.trim());

        const cLat = findCol(headers, ["lat", "latitude", "緯度"]);

        const cLon = findCol(headers, ["lon", "lng", "long", "longitude", "経度"]);

        if (cLat === -1 || cLon === -1) {

          throw new Error("緯度(lat)・経度(lon)の列が見つかりません。\n検出ヘッダ: " + headers.join(", "));

        }

        let cRoll, cPitch;

        if (xyzMap === "RPY") {

          cRoll  = findCol(headers, ["roll", "bank", "phi", "ang_x", "angle_x", "rot_x", "x_deg", "x", "ロール"]);

          cPitch = findCol(headers, ["pitch", "theta", "ang_y", "angle_y", "rot_y", "y_deg", "y", "ピッチ"]);

        } else {

          cPitch = findCol(headers, ["pitch", "theta", "ang_x", "angle_x", "rot_x", "x_deg", "x", "ピッチ"]);

          cRoll  = findCol(headers, ["roll", "bank", "phi", "ang_y", "angle_y", "rot_y", "y_deg", "y", "ロール"]);

        }

        colsMeta = {

          cTime: findCol(headers, ["time", "t", "timestamp", "sec", "時間", "時刻"]),

          cLat, cLon,

          cAlt:  findCol(headers, ["alt_m", "alt_ft", "alt", "altitude", "高度"]),

          cSpd:  findCol(headers, ["speed_kt", "speed", "spd", "tas", "ias", "gs", "velocity", "vel", "速度"]),

          cRoll, cPitch,

          cYaw:  findCol(headers, ["yaw", "heading", "hdg", "psi", "ang_z", "angle_z", "rot_z", "z_deg", "z", "方位", "ヨー"]),

        };

        continue;

      }

 

      if ((rowCounter++ % thinStep) !== 0) continue;

 

      const cols = line.split(",");

      if (cols.length < 3) continue;

      const lat = parseFloat(cols[colsMeta.cLat]);

      const lon = parseFloat(cols[colsMeta.cLon]);

      if (isNaN(lat) || isNaN(lon)) continue;

 

      let t = colsMeta.cTime !== -1 ? parseTimeVal(cols[colsMeta.cTime]) : (rowCounter - 1) * 0.05;

      if (isNaN(t)) t = (rowCounter - 1) * 0.05;

      if (t0 === null) t0 = t;

 

      const altM = (colsMeta.cAlt !== -1 ? parseFloat(cols[colsMeta.cAlt]) : 3000) * altScale;

      let spdKt = 0;

      if (colsMeta.cSpd !== -1) {

        const rawS = parseFloat(cols[colsMeta.cSpd]) || 0;

        if (spdUnit === "kt") spdKt = rawS;

        else if (spdUnit === "kmh") spdKt = rawS / 1.852;

        else spdKt = rawS * 1.94384;

      }

 

      const roll  = (colsMeta.cRoll  !== -1 ? (parseFloat(cols[colsMeta.cRoll])  || 0) : 0) * angScale * invR;

      const pitch = (colsMeta.cPitch !== -1 ? (parseFloat(cols[colsMeta.cPitch]) || 0) : 0) * angScale * invP;

      const yaw   = (colsMeta.cYaw   !== -1 ? (parseFloat(cols[colsMeta.cYaw])   || 0) : 0) * angScale;

      const [mx, my] = lonLatToMeters(lon, lat);

 

      store.push(t - t0, lon, lat, mx, my, isNaN(altM) ? 3000 : altM, spdKt, roll, pitch, yaw);

    }

  }

 

  try {

    if (source.type === "text") {

      processLines(source.text.split(/\r?\n/));

    } else {

      const file = source.file;

      const CHUNK_BYTES = 4 * 1024 * 1024; // 4MB単位でストリーミング読込

      const decoder = new TextDecoder("utf-8");

      let offset = 0;

      let leftover = "";

 

      while (offset < file.size) {

        if (myJob !== loadJobId) return; // 別の読込が開始されたら中断

        const end = Math.min(file.size, offset + CHUNK_BYTES);

        const buf = await file.slice(offset, end).arrayBuffer();

        const isLast = (end >= file.size);

        const decoded = leftover + decoder.decode(buf, { stream: !isLast });

 

        if (!isLast) {

          const lastNl = decoded.lastIndexOf("\n");

          if (lastNl !== -1) {

            processLines(decoded.slice(0, lastNl).split(/\r?\n/));

            leftover = decoded.slice(lastNl + 1);

          } else {

            leftover = decoded;

          }

        } else {

          processLines(decoded.split(/\r?\n/));

          leftover = "";

        }

 

        offset = end;

        const pct = Math.min(99, Math.round((offset / file.size) * 100));

        document.getElementById("hud-status").textContent = `LOAD ${pct}%`;

        document.getElementById("frame-info").textContent = `読込中 ${pct}% (${store.len.toLocaleString()}点)`;

        await new Promise(r => setTimeout(r, 0)); // UIフリーズ防止

      }

    }

  } catch (err) {

    alert(err.message);

    document.getElementById("hud-status").textContent = "ERROR";

    return;

  }

 

  if (myJob !== loadJobId) return;

  if (store.len === 0) { alert("有効な行を読み込めませんでした"); return; }