// VSI & Yaw自動補完

  const autoYaw = (colsMeta.cYaw === -1);

  for (let i = 0; i < store.len; i++) {

    const p = Math.max(0, i - 1), n = Math.min(store.len - 1, i + 1);

    const dt = Math.max(0.01, store.t[n] - store.t[p]);

    store.vsi[i] = (store.alt[n] - store.alt[p]) / dt;

    if (autoYaw && i < store.len - 1) {

      store.yaw[i] = (Math.atan2(store.mx[n] - store.mx[p], store.my[n] - store.my[p]) * 180 / Math.PI + 360) % 360;

    }

  }

  if (autoYaw && store.len > 1) store.yaw[store.len - 1] = store.yaw[store.len - 2];

 

  // GPU航跡は最大12,000点へ均等サンプリングして軽量維持

  const MAX_TRAIL_PTS = 12000;

  const tStep = Math.max(1, Math.floor(store.len / MAX_TRAIL_PTS));

  const tIdx = [];

  for (let i = 0; i < store.len; i += tStep) tIdx.push(i);

  if (tIdx[tIdx.length - 1] !== store.len - 1) tIdx.push(store.len - 1);

 

  trailCount = tIdx.length;

  const trailPos = new Float32Array(trailCount * 3);

  const trailColAll = new Float32Array(trailCount * 3);

  const trailNorm = new Float32Array(trailCount * 3);

  for (let k = 0; k < trailCount; k++) {

    const idx = tIdx[k];

    trailPos[k*3] = store.mx[idx]; trailPos[k*3+1] = store.my[idx]; trailPos[k*3+2] = store.alt[idx];

    trailColAll[k*3] = 0.0; trailColAll[k*3+1] = 0.96; trailColAll[k*3+2] = 1.0;

    trailNorm[k*3+2] = 1.0;

  }

 

  gl.bindBuffer(gl.ARRAY_BUFFER, trailPB); gl.bufferData(gl.ARRAY_BUFFER, trailPos, gl.STATIC_DRAW);

  gl.bindBuffer(gl.ARRAY_BUFFER, trailFullColB); gl.bufferData(gl.ARRAY_BUFFER, trailColAll, gl.STATIC_DRAW);

  gl.bindBuffer(gl.ARRAY_BUFFER, trailNB); gl.bufferData(gl.ARRAY_BUFFER, trailNorm, gl.STATIC_DRAW);

 

  fStore = store;

  totalDuration = Math.max(0.1, store.t[store.len - 1]);

  simTime = 0;

  currentIdx = 0;

 

  const sb = document.getElementById("seek-bar");

  sb.value = 0; sb.disabled = false;

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

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

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

  drawMiniChartBg();

  updateHUD(sampleFlightAt(0));

}

 

function fmtTime(sec) {

  const m = Math.floor(sec / 60);

  const s = (sec % 60).toFixed(1).padStart(4, "0");

  return `${String(m).padStart(2, "0")}:${s}`;

}

 

function updateHUD(f) {

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

  const gndAlt = getGroundElev(f.lon, f.lat);

  const agl = Math.max(0, f.alt - gndAlt);

 

  document.getElementById("hud-time").textContent = fmtTime(f.t);

  document.getElementById("hud-spd").textContent = `${f.spd.toFixed(0)} kt (${(f.spd * 1.852).toFixed(0)} km/h)`;

  document.getElementById("hud-alt").textContent = `${f.alt.toFixed(0)} m (${(f.alt / 0.3048).toFixed(0)} ft)`;

  document.getElementById("hud-agl").textContent = `${agl.toFixed(0)} m`;

  document.getElementById("hud-vsi").textContent = `${f.vsi >= 0 ? "+" : ""}${f.vsi.toFixed(1)} m/s`;

  document.getElementById("hud-pos").textContent = `${f.lat.toFixed(3)}°N ${f.lon.toFixed(3)}°E`;

  document.getElementById("hud-yaw").textContent = `${(((f.yaw % 360) + 360) % 360).toFixed(0)}°`;

  document.getElementById("hud-pitch").textContent = `${f.pitch >= 0 ? "+" : ""}${f.pitch.toFixed(1)}°`;

  document.getElementById("hud-roll").textContent = `${f.roll >= 0 ? "+" : ""}${f.roll.toFixed(1)}°`;

 

  const pitchPx = Math.max(-35, Math.min(35, f.pitch * 1.2));

  document.getElementById("adi-horizon").setAttribute("transform", `rotate(${-f.roll}) translate(0, ${pitchPx})`);

 

  const ratio = Math.max(0, Math.min(1, f.t / totalDuration));

  document.getElementById("seek-bar").value = Math.round(ratio * 1000);

  document.getElementById("frame-info").textContent = `${fmtTime(f.t)} / ${fmtTime(totalDuration)} (${fStore.len.toLocaleString()}点)`;

  drawMiniChartCursor(ratio);

}

 

let miniBgImg = null;

function drawMiniChartBg() {

  const cvs = document.getElementById("mini-chart");

  const w = cvs.clientWidth, h = cvs.clientHeight;

  cvs.width = w; cvs.height = h;

  const ctx = cvs.getContext("2d");

  ctx.clearRect(0, 0, w, h);

  if (!fStore || fStore.len < 2) return;

 

  let maxAlt = 1000, maxSpd = 200;

  for (let i = 0; i < fStore.len; i++) {

    if (fStore.alt[i] > maxAlt) maxAlt = fStore.alt[i];

    if (fStore.spd[i] > maxSpd) maxSpd = fStore.spd[i];

  }

 

  const step = Math.max(1, Math.floor(fStore.len / 2000));

  ctx.strokeStyle = "#38bdf8"; ctx.lineWidth = 1.5; ctx.beginPath();

  for (let i = 0; i < fStore.len; i += step) {

    const x = (fStore.t[i] / totalDuration) * w;

    const y = h - (fStore.alt[i] / maxAlt) * (h - 6) - 3;

    i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);

  }

  ctx.stroke();

 

  ctx.strokeStyle = "#ffa726"; ctx.lineWidth = 1.2; ctx.beginPath();

  for (let i = 0; i < fStore.len; i += step) {

    const x = (fStore.t[i] / totalDuration) * w;

    const y = h - (fStore.spd[i] / maxSpd) * (h - 6) - 3;

    i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);

  }

  ctx.stroke();

  miniBgImg = ctx.getImageData(0, 0, w, h);

}

 

function drawMiniChartCursor(ratio) {

  if (!miniBgImg || !fStore || fStore.len < 2) return;

  const cvs = document.getElementById("mini-chart");

  const ctx = cvs.getContext("2d");

  ctx.putImageData(miniBgImg, 0, 0);

  const cx = ratio * cvs.width;

  ctx.strokeStyle = "#ff5252"; ctx.lineWidth = 2;

  ctx.beginPath(); ctx.moveTo(cx, 0); ctx.lineTo(cx, cvs.height); ctx.stroke();

}

 

document.getElementById("mini-chart").addEventListener("click", e => {

  if (!fStore || fStore.len < 2) return;

  const rect = e.target.getBoundingClientRect();

  const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));

  simTime = ratio * totalDuration;

  updateHUD(sampleFlightAt(simTime));

});

 

function togglePlay() {

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

  isPlaying = !isPlaying;

  document.getElementById("btn-play").textContent = isPlaying ? "⏸ 一時停止" : "▶ 再生";

  document.getElementById("hud-status").textContent = isPlaying ? "PLAYING" : "PAUSED";

  if (isPlaying && simTime >= totalDuration) simTime = 0;

}

 

function stopFlight() {

  isPlaying = false;

  document.getElementById("btn-play").textContent = "▶ 再生";

  document.getElementById("hud-status").textContent = (fStore && fStore.len) ? "READY" : "STANDBY";

  if (fStore && fStore.len > 0) { simTime = 0; currentIdx = 0; updateHUD(sampleFlightAt(0)); }

}

 

function onSeekPermille(val) {

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

  simTime = (parseFloat(val) / 1000.0) * totalDuration;

  updateHUD(sampleFlightAt(simTime));

}

 

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

  if (e.code === "Space" && document.activeElement.tagName !== "INPUT" && document.activeElement.tagName !== "SELECT") {

    e.preventDefault(); togglePlay();

  }

});

 

function loadDemoFlight() {

  const rows = ["time,lat,lon,alt_m,speed_kt,roll,pitch,yaw"];

  const N = 600, dt = 0.2;

  let lat = 36.3946, lon = 136.4065, alt = 20;

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

    const t = i * dt;

    let hdg = 315, pitch = 0, roll = 0, spd = 160;

    if (i < 80) {

      pitch = 16; spd = 180 + i * 3.5; alt += 16; hdg = 315;

    } else if (i < 300) {

      const k = (i - 80) / 220.0;

      hdg = 315 + k * 210; roll = 48 * Math.sin(k * Math.PI);

      pitch = 10 * Math.cos(k * Math.PI * 2); spd = 460; alt += 14;

    } else if (i < 440) {

      const k = (i - 300) / 140.0;

      hdg = 165; roll = k * 360; pitch = 14 * Math.sin(k * Math.PI * 2); spd = 500;

    } else {

      hdg = 165 - (i - 440) * 0.4; roll = -25; pitch = -5; spd = 430; alt = Math.max(2000, alt - 8);

    }

    const rad = hdg * Math.PI / 180;

    const distM = (spd * 0.5144) * dt;

    lat += (distM * Math.cos(rad)) / 110960;

    lon += (distM * Math.sin(rad)) / (111320 * Math.cos(lat * Math.PI / 180));

    rows.push(`${t.toFixed(2)},${lat.toFixed(6)},${lon.toFixed(6)},${alt.toFixed(1)},${spd.toFixed(1)},${roll.toFixed(1)},${pitch.toFixed(1)},${(hdg % 360).toFixed(1)}`);

  }

  document.getElementById("opt-alt-unit").value = "m";

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

  document.getElementById("opt-ang-unit").value = "deg";

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

  currentSource = { type: "text", text: rows.join("\n") };

  loadFromSource(currentSource);

}

 

let prevFrameTime = performance.now();

let lastHudTime = 0;

 

function projectToScreen(vp, wx, wy, wz, w, h) {

  const cx = vp[0]*wx + vp[4]*wy + vp[8]*wz + vp[12];

  const cy = vp[1]*wx + vp[5]*wy + vp[9]*wz + vp[13];

  const cw = vp[3]*wx + vp[7]*wy + vp[11]*wz + vp[15];

  if (cw <= 0.0) return null;

  return [(cx / cw * 0.5 + 0.5) * w, (-cy / cw * 0.5 + 0.5) * h];

}

 

function drawMeshObj(vp, model, zScale, applyZ, ambient, pb, nb, cb, count, mode) {

  gl.uniformMatrix4fv(gl.getUniformLocation(meshProg, "uVP"), false, vp);

  gl.uniformMatrix4fv(gl.getUniformLocation(meshProg, "uModel"), false, model);

  gl.uniform1f(gl.getUniformLocation(meshProg, "uZScale"), zScale);

  gl.uniform1f(gl.getUniformLocation(meshProg, "uApplyZScale"), applyZ);

  gl.uniform1f(gl.getUniformLocation(meshProg, "uAmbient"), ambient);

 

  const aPos = gl.getAttribLocation(meshProg, "aPos");

  const aNorm = gl.getAttribLocation(meshProg, "aNormal");

  const aCol = gl.getAttribLocation(meshProg, "aColor");

  gl.bindBuffer(gl.ARRAY_BUFFER, pb); gl.enableVertexAttribArray(aPos); gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, nb); gl.enableVertexAttribArray(aNorm); gl.vertexAttribPointer(aNorm, 3, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, cb); gl.enableVertexAttribArray(aCol); gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);

  gl.drawArrays(mode, 0, count);

}

 

function renderLoop(now) {

  const dtReal = Math.min(0.1, (now - prevFrameTime) / 1000.0);

  prevFrameTime = now;

 

  if (isPlaying && fStore && fStore.len > 0) {

    const playSpd = parseFloat(document.getElementById("sel-play-spd").value);

    simTime += dtReal * playSpd;

    if (simTime >= totalDuration) {

      simTime = totalDuration;

      isPlaying = false;

      document.getElementById("btn-play").textContent = "▶ 再生";

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

      updateHUD(sampleFlightAt(simTime));

    }

  }

 

  const wrap = document.getElementById("canvas-wrap");

  const cw = wrap.clientWidth, ch = wrap.clientHeight;

  if (glCanvas.width !== cw || glCanvas.height !== ch) {

    glCanvas.width = cw; glCanvas.height = ch;

    ovCanvas.width = cw; ovCanvas.height = ch;

  }

  gl.viewport(0, 0, cw, ch);

  gl.enable(gl.DEPTH_TEST);

  gl.clearColor(0.05, 0.07, 0.10, 1.0);

  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

 

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

  const f15Scale = parseFloat(document.getElementById("sel-f15").value);

 

  let acFrame = null;

  if (fStore && fStore.len > 0) {

    acFrame = sampleFlightAt(simTime);

    currentIdx = acFrame.idx;

    if (isPlaying && (now - lastHudTime >= 66)) {

      lastHudTime = now;

      updateHUD(acFrame);

    }

    if (document.getElementById("chk-follow").checked) {

      camTarget[0] = acFrame.mx;

      camTarget[1] = acFrame.my;

      camTarget[2] = acFrame.alt * zScale;

    }

  }

 

  const cosP = Math.cos(camPitch), sinP = Math.sin(camPitch);

  const eye = [

    camTarget[0] - camDist * cosP * Math.sin(camYaw),

    camTarget[1] - camDist * cosP * Math.cos(camYaw),

    camTarget[2] + camDist * sinP

  ];

  const zNear = Math.max(2.0, camDist * 0.02);

  const zFar = Math.max(400000.0, camDist * 30.0 + 700000.0);

  const vp = mulMat4(matPerspective(45 * Math.PI / 180, cw / Math.max(1, ch), zNear, zFar), matLookAt(eye, camTarget));

 

  gl.useProgram(terrainProg);

  gl.uniformMatrix4fv(gl.getUniformLocation(terrainProg, "uVP"), false, vp);

  gl.uniform1f(gl.getUniformLocation(terrainProg, "uZScale"), zScale);

  const tPos = gl.getAttribLocation(terrainProg, "aPos");

  const tGrad = gl.getAttribLocation(terrainProg, "aGrad");

  const tCol = gl.getAttribLocation(terrainProg, "aColor");

  for (const c of terrainChunks) {

    gl.bindBuffer(gl.ARRAY_BUFFER, c.pb); gl.enableVertexAttribArray(tPos); gl.vertexAttribPointer(tPos, 3, gl.FLOAT, false, 0, 0);

    gl.bindBuffer(gl.ARRAY_BUFFER, c.gb); gl.enableVertexAttribArray(tGrad); gl.vertexAttribPointer(tGrad, 2, gl.FLOAT, false, 0, 0);

    gl.bindBuffer(gl.ARRAY_BUFFER, c.cb); gl.enableVertexAttribArray(tCol); gl.vertexAttribPointer(tCol, 3, gl.UNSIGNED_BYTE, true, 0, 0);

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, c.ib);

    gl.drawElements(gl.TRIANGLES, c.count, gl.UNSIGNED_SHORT, 0);

  }

 

  gl.useProgram(meshProg);

  if (document.getElementById("chk-lake").checked) {

    for (const lk of lakeMeshes) drawMeshObj(vp, IDENTITY_MAT, zScale, 1.0, 0.90, lk.pb, lk.nb, lk.cb, lk.count, gl.TRIANGLES);

  }

  if (document.getElementById("chk-airspace").checked) {

    drawMeshObj(vp, IDENTITY_MAT, zScale, 1.0, 1.0, airPB, airNB, airCB, airCount, gl.LINES);

  }

  if (acFrame) {

    if (document.getElementById("chk-trail").checked && trailCount > 1) {

      drawMeshObj(vp, IDENTITY_MAT, zScale, 1.0, 1.0, trailPB, trailNB, trailFullColB, trailCount, gl.LINE_STRIP);

    }

    if (document.getElementById("chk-drop").checked) {

      const gnd = getGroundElev(acFrame.lon, acFrame.lat);

      gl.bindBuffer(gl.ARRAY_BUFFER, dropPB);

      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([acFrame.mx, acFrame.my, acFrame.alt, acFrame.mx, acFrame.my, gnd]), gl.DYNAMIC_DRAW);

      drawMeshObj(vp, IDENTITY_MAT, zScale, 1.0, 1.0, dropPB, dropNB, dropCB, 2, gl.LINES);

    }

    const acModel = buildModelMat(acFrame.mx, acFrame.my, acFrame.alt * zScale, acFrame.roll, acFrame.pitch, acFrame.yaw, f15Scale);

    drawMeshObj(vp, acModel, zScale, 0.0, 0.65, f15PB, f15NB, f15CB, f15Count, gl.TRIANGLES);

  }

 

  ovCtx.clearRect(0, 0, cw, ch);

  ovCtx.font = "12px sans-serif";

  if (document.getElementById("chk-base").checked) {

    for (const b of AIRBASES) {

      const sp = projectToScreen(vp, b.mx, b.my, (b.elev + 80) * zScale, cw, ch);

      if (!sp) continue;

      ovCtx.beginPath(); ovCtx.arc(sp[0], sp[1], 5, 0, Math.PI*2);

      ovCtx.fillStyle = "#ff1744"; ovCtx.fill();

      ovCtx.lineWidth = 1.5; ovCtx.strokeStyle = "#ffffff"; ovCtx.stroke();

      ovCtx.fillStyle = "#ffffff"; ovCtx.fillText(b.name, sp[0] + 8, sp[1] + 4);

    }

  }

  if (document.getElementById("chk-airspace").checked) {

    for (const asp of AIRSPACES_RAW) {

      const sp = projectToScreen(vp, asp.labelPos[0], asp.labelPos[1], asp.labelPos[2] * zScale, cw, ch);

      if (!sp) continue;

      ovCtx.fillStyle = asp.color;

      ovCtx.fillText(asp.name, sp[0], sp[1]);

    }

  }

  if (acFrame) {

    const sp = projectToScreen(vp, acFrame.mx, acFrame.my, acFrame.alt * zScale, cw, ch);

    if (sp) {

      ovCtx.strokeStyle = "#00ff88"; ovCtx.lineWidth = 1.5;

      ovCtx.strokeRect(sp[0] - 10, sp[1] - 10, 20, 20);

      ovCtx.fillStyle = "#00ff88";

      ovCtx.fillText("F-15J", sp[0] + 14, sp[1] - 6);

    }

  }

 

  requestAnimationFrame(renderLoop);

}

 

requestAnimationFrame(renderLoop);

</script>

</body>

</html>

"""


 

def main():

    print("地形・アセットを読み込み中...")

    with open(INPUT_TERRAIN_JSON, "r", encoding="utf-8") as f:

        tdata = json.load(f)

    with open(INPUT_ASSETS_JSON, "r", encoding="utf-8") as f:

        adata = json.load(f)

 

    lons_full = np.array(tdata["lons"], dtype=np.float64)

    lats_full = np.array(tdata["lats"], dtype=np.float64)

    Z_full = np.array(

        [[np.nan if v is None else v for v in r] for r in tdata["elevations_m"]],

        dtype=np.float32

    )

 

    stride = max(1, int(np.ceil(max(Z_full.shape) / MAX_GRID_DIM)))

    lons = lons_full[::stride]

    lats = lats_full[::stride]

    Z = Z_full[::stride, ::stride].copy()

    H, W = Z.shape

    print(f"WebGLメッシュ構築中: {Z_full.shape} -> {Z.shape} (1/{stride})")

 

    X_s, Y_s = np.meshgrid(lons, lats)

    for lk in tdata.get("lake_polygons", []):

        arr = np.array(lk["polygon"])

        bx0, by0, bx1, by1 = arr[:, 0].min(), arr[:, 1].min(), arr[:, 0].max(), arr[:, 1].max()

        ix = np.where((lons >= bx0) & (lons <= bx1))[0]

        iy = np.where((lats >= by0) & (lats <= by1))[0]

        if len(ix) > 0 and len(iy) > 0:

            sub_X = X_s[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            sub_Y = Y_s[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            l_mask = points_in_polygon(sub_X, sub_Y, lk["polygon"])

            sub_Z = Z[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            Z[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1] = np.where(

                l_mask & (~np.isnan(sub_Z)), np.minimum(sub_Z, lk["elevation_m"] - 40.0), sub_Z

            )

 

    ref_lon = float((lons.min() + lons.max()) / 2.0)

    ref_lat = float((lats.min() + lats.max()) / 2.0)

    m_per_lon = 111320.0 * np.cos(np.radians(ref_lat))

    m_per_lat = 110960.0

 

    X_m = (X_s - ref_lon) * m_per_lon

    Y_m = (Y_s - ref_lat) * m_per_lat

    Z0 = np.nan_to_num(Z, nan=0.0)

 

    dy_m = abs(lats[1] - lats[0]) * m_per_lat

    dx_m = abs(lons[1] - lons[0]) * m_per_lon

    gy, gx = np.gradient(Z0, dy_m, dx_m)

    gy = -gy

    slope = np.hypot(gx, gy)

    rock_factor = np.clip((slope - 0.20) / 0.55, 0.0, 1.0)

 

    h_norm = np.clip(Z0 / 3776.0, 0.0, 1.0)

    stops = [0.00, 0.05, 0.22, 0.45, 0.70, 0.88, 1.00]

    cols = np.array([

        [33, 77, 36], [51, 102, 44], [70, 110, 53], [107, 101, 66],

        [120, 98, 77], [148, 144, 138], [248, 250, 252]

    ], dtype=np.float32)

    rgb = np.zeros((H, W, 3), dtype=np.float32)

    for c in range(3):

        rgb[:, :, c] = np.interp(h_norm, stops, cols[:, c])

    rock_col = np.array([122, 114, 105], dtype=np.float32)

    rgb = rgb * (1.0 - rock_factor[:, :, None] * 0.7) + rock_col * (rock_factor[:, :, None] * 0.7)

    rgb_u8 = np.clip(rgb, 0, 255).astype(np.uint8)

 

    valid_mask = ~np.isnan(Z)

    chunk_rows = max(20, 55000 // W)

    chunks_meta = []

    for r0 in range(0, H - 1, chunk_rows):

        r1 = min(H - 1, r0 + chunk_rows)

        sub_valid = valid_mask[r0:r1+1, :]

        cell_ok = sub_valid[:-1, :-1] & sub_valid[1:, :-1] & sub_valid[:-1, 1:] & sub_valid[1:, 1:]

        if not np.any(cell_ok):

            continue

 

        pos = np.stack([X_m[r0:r1+1, :], Y_m[r0:r1+1, :], Z0[r0:r1+1, :]], axis=-1).astype(np.float32)

        grad = np.stack([gx[r0:r1+1, :], gy[r0:r1+1, :]], axis=-1).astype(np.float32)

        col = rgb_u8[r0:r1+1, :, :]

 

        rr, cc = np.where(cell_ok)

        i0 = rr * W + cc

        i1 = (rr + 1) * W + cc

        i2 = rr * W + (cc + 1)

        i3 = (rr + 1) * W + (cc + 1)

        tris = np.concatenate([

            np.stack([i0, i1, i2], axis=-1),

            np.stack([i2, i1, i3], axis=-1)

        ], axis=0).astype(np.uint16)

 

        chunks_meta.append({

            "pos": arr_to_b64(pos),

            "grad": arr_to_b64(grad),

            "col": arr_to_b64(col),

            "idx": arr_to_b64(tris)

        })

 

    lakes_json = []

    for lk in tdata.get("lake_polygons", []):

        pts, tris = triangulate_polygon(lk["polygon"])

        if tris:

            lakes_json.append({

                "name": lk["name"],

                "elevation_m": float(lk["elevation_m"]),

                "pts": pts,

                "tris": [v for t in tris for v in t]

            })

 

    airbases_json = []

    for b in adata.get("airbases", []):

        blon, blat = parse_coord(b["lon"]), parse_coord(b["lat"])

        ix = int(np.argmin(np.abs(lons - blon)))

        iy = int(np.argmin(np.abs(lats - blat)))

        elev = float(Z[iy, ix]) if not np.isnan(Z[iy, ix]) else 0.0

        airbases_json.append({

            "name": b["name"],

            "mx": float((blon - ref_lon) * m_per_lon),

            "my": float((blat - ref_lat) * m_per_lat),

            "elev": elev

        })

 

    airspaces_json = []

    for asp in adata.get("airspaces", []):

        airspaces_json.append({

            "name": asp["name"],

            "color": asp["color"],

            "min_alt_m": float(asp["min_alt_m"]),

            "max_alt_m": float(asp["max_alt_m"]),

            "polygon": [[parse_coord(p[0]), parse_coord(p[1])] for p in asp["polygon"]]

        })

 

    mesh = adata["f15j_mesh"]

    verts = np.array(mesh["vertices"], dtype=np.float32)

    f15_pos, f15_norm, f15_col = [], [], []

    for face, hex_col in zip(mesh["faces"], mesh["face_colors"]):

        v0, v1, v2 = verts[face[0]], verts[face[1]], verts[face[2]]

        n = np.cross(v1 - v0, v2 - v0)

        nl = np.linalg.norm(n)

        n = n / nl if nl > 1e-6 else np.array([0.0, 0.0, 1.0], dtype=np.float32)

        hx = hex_col.lstrip("#")

        rgb_f = [int(hx[0:2], 16) / 255.0, int(hx[2:4], 16) / 255.0, int(hx[4:6], 16) / 255.0]

        for v in (v0, v1, v2):

            f15_pos.extend(v.tolist())

            f15_norm.extend(n.tolist())

            f15_col.extend(rgb_f)

 

    f15_json = {"pos": f15_pos, "norm": f15_norm, "col": f15_col}

 

    html = HTML_TEMPLATE

    replacements = {

        "__REF_LON__": str(ref_lon),

        "__REF_LAT__": str(ref_lat),

        "__LON_MIN__": str(float(lons.min())),

        "__DLON__": str(float(lons[1] - lons[0])),

        "__LAT_MAX__": str(float(lats[0])),

        "__DLAT__": str(abs(float(lats[1] - lats[0]))),

        "__GRID_H__": str(H),

        "__GRID_W__": str(W),

        "__ELEV_GRID_B64__": arr_to_b64(Z.astype(np.float32)),

        "__CHUNKS_META__": json.dumps(chunks_meta),

        "__LAKES_JSON__": json.dumps(lakes_json, ensure_ascii=False),

        "__AIRBASES_JSON__": json.dumps(airbases_json, ensure_ascii=False),

        "__AIRSPACES_JSON__": json.dumps(airspaces_json, ensure_ascii=False),

        "__F15_JSON__": json.dumps(f15_json),

    }

    for k, v in replacements.items():

        html = html.replace(k, v)

 

    Path(OUTPUT_HTML).write_text(html, encoding="utf-8")

    size_mb = Path(OUTPUT_HTML).stat().st_size / (1024 * 1024)

    print(f"完了! -> {OUTPUT_HTML} ({size_mb:.2f} MB)")


 

if __name__ == "__main__":

    main()