#4992 Lunar Surface Operations Simulator

#4992 Lunar Surface Operations Simulator

  1. Simulation scene: Lunar habitat, power modules, solar array field, two lunar terrain vehicles, pressurized rover, and four astronauts in EVA space suits. Create a time covering 4 hours for astronaut work on the lunar surface.
  2. Create an HTML, JavaScript and CSS application to view the simulation based on the timeline
  3. Add an import mission timeline button
  4. Show the timeline file layout and format

#4992 Simulation scene: Lunar habitat, power modules, solar array field, two lunar terrain vehicles, pressurized rover, and four astronauts in EVA space suits. Create a time covering 4 hours for astronaut work on the lunar surface.

Lunar Surface EVA Simulation Timeline (4-Hour Operational Window)

Scene Assets:

  • Base Infrastructure: Lunar Habitat (Pressurized Airlock), Power Modules (PM-1, PM-2), Solar Array Field (SAF-East).

  • Mobility Assets: Pressurized Rover (PR-1), Two unpressurized Lunar Terrain Vehicles (LTV-1, LTV-2).

  • Crew: 4 Astronauts in AxEMU/EVA suits split into two buddy teams:

    • Team Alpha (EV-1 & EV-2): Power & Base Infrastructure Operations.

    • Team Beta (EV-3 & EV-4): Mobile Field Traverse & Geological Sampling.

Master EVA Timeline (T+00:00 to T+04:00)

Time WindowElapsedTeam Alpha (EV-1, EV-2)Team Beta (EV-3, EV-4)Active Assets & Telemetry Focus
00:00 – 00:3030 minAirlock depressurization, suit leak checks, egress to surface, and visual walkaround of Habitat hull.Airlock egress alongside Team Alpha; boot-up and pre-drive systems check on LTV-1, LTV-2, and PR-1.Habitat Airlock, Suit PLSS telemetry, PR-1 & LTV diagnostics.
00:30 – 01:1545 minDeploy power umbilical cable from Power Module PM-1 to Solar Array Field (SAF-East) junction box.Drive PR-1 (EV-3) and LTV-1 (EV-4) in tandem convoy 1.2 km south toward ridge sampling waypoint.PM-1, SAF-East, PR-1, LTV-1 (LTV-2 parked at Habitat on standby).
01:15 – 02:1560 minElectrostatic dust mitigation brushing on SAF-East panels; verify voltage bus handoff to PM-2.Execute geological core drilling and regolith sample caching at South Ridge; transfer cores to PR-1 rack.SAF-East, PM-2, PR-1 external sample carrier.
02:15 – 03:0045 minInspect radiator louvers on PM-1/PM-2; mount replacement telemetry transceiver on Habitat exterior mast.Return convoy traverse from South Ridge back to Base Camp; dock PR-1 to Habitat charging umbilical.Habitat, PM-1/PM-2, PR-1, LTV-1.
03:00 – 03:3030 minBoard LTV-2 for high-speed perimeter inspection loop around the Solar Array Field and comms relay.Unload sample canisters from PR-1; park LTV-1 and LTV-2 in designated charging bays; suit dust blow-off.LTV-1, LTV-2, PR-1, Base Charging Station.
03:30 – 04:0030 minReturn LTV-2 to charging bay; join Team Beta at airlock, execute final suit brushing, ingress, and repressurize.Assist Team Alpha with tool stowage; ingress Habitat airlock, seal outer hatch, and initiate repressurization.Habitat Airlock, all vehicles docked and charging.

Key Simulation Triggers & State Transitions

  • T+00:30 (Separation): Crew splits from a single cluster at the Habitat airlock into two independent spatial vectors—Team Alpha moving east toward the Solar Array Field, Team Beta moving south in vehicle formation.

  • T+01:15 (Peak Power & Distance): Team Beta reaches maximum range (1.2 km) while Team Alpha executes high-precision cable and solar panel maintenance. Comm relay handoff shifts from direct Habitat line-of-sight to PR-1 mast relay.

  • T+02:45 (Vehicle Re-docking): PR-1 connects to Power Module PM-2 for fast recharge; LTV-2 transitions from static standby to active perimeter patrol at T+03:00 so all three vehicles demonstrate active motion during the 4-hour simulation.

  • T+03:45 (Ingress Lock): All four astronauts return inside the Habitat airlock; PLSS battery and O2 reserves terminate at ~35–40% remaining capacity.


Create an HTML, JavaScript and CSS application to view the simulation based on the timeline

I will now generate a standalone interactive 2D lunar surface EVA simulation viewer covering the 4-hour operational window (T+00:00 to T+04:00), complete with NASA Mission Control telemetry, smooth kinematic interpolation, interactive canvas pan/zoom/follow controls, and timeline phase scrubbing.



Summary of the Simulation Viewer

  • Interactive 2D Lunar Surface Canvas: Renders the Lunar Habitat, Airlock vestibule, Exterior Comms Mast, Power Modules (PM-1 & PM-2), the 12-panel SAF-East Solar Array Field (which dynamically brightens as dust is brushed off), PR-1, LTV-1, LTV-2, all four astronauts (EV-1–EV-4), RF line-of-sight rings, and the South Ridge waypoint 1.2 km south.

  • Smooth 4-Hour Kinematic Interpolation (T+00:00 to T+04:00): Covers all six operational phases and four state triggers—including the T+00:30 team separation, animated umbilical deployment, T+01:15 South Ridge arrival and RF relay handoff to PR-1, T+02:45 PR-1 charging dock, T+03:00 LTV-2 perimeter inspection loop, and T+03:45 airlock ingress lock.

  • NASA Mission Control Telemetry & Controls: Includes playback speed controls (1x–120x), an interactive timeline scrubber with clickable phase segments and trigger jump buttons, live AxEMU PLSS oxygen/battery/heart-rate cards, vehicle/power telemetry, a scrolling mission event log, and click-to-inspect/follow camera controls.


Add an import mission timeline button

I will now update the Lunar Surface EVA Simulation application to include an Import Timeline button in the top Mission Control header bar, a complete JSON timeline import/export modal with live schema validation, and a fully data-driven simulation engine capable of dynamically rendering and scrubbing custom mission timelines.

Summary of Changes

  • Import Timeline Header Button & Modal UI: Added an Import Timeline button in the top Mission Control header bar that opens a modal dialog with drag-and-drop / file picker .json upload, a live JSON editor pre-populated with the active mission manifest, Load Sample / Reset Default, Export Current JSON, and Validate & Apply Timeline with detailed inline schema/chronology validation feedback.

  • Data-Driven Simulation & Timeline Chrome: Refactored the simulation engine to compile and execute directly from activeMission JSON manifests (missionTitle, durationMinutes, waypoints, phases, triggers, and entity/system keyframes), automatically rebuilding the timeline scrubber bounds, phase segments, trigger quick-jump buttons, and logging an [IMPORT] confirmation event upon applying a custom timeline.


Show the timeline file layout and format

The Import Timeline modal expects a self-contained JSON manifest defining the mission duration, 2D surface coordinates (in meters relative to the Habitat center at (0, 0)), timeline phases, state-transition triggers, and entity/system keyframes.

Top-Level JSON Structure

KeyTypeRequiredDescription
missionTitlestringYesHeader title displayed in Mission Control.
durationMinutesnumberYesTotal simulation window in minutes (e.g., 240 for 4 hours).
waypointsobjectNoNamed { "x": number, "y": number } surface markers rendered on the map (in meters).
phasesarrayYesContiguous operational intervals (startMin, endMin, id, title, alphaTask, betaTask).
triggersarrayNoDiscrete timeline markers & log events (min, id, label, summary, severity).
entitiesobjectYesKeyframed motion/state tracks for EV-1, EV-2, EV-3, EV-4, PR-1, LTV-1, and LTV-2.
systemsobjectNoKeyframed infrastructure states for umbilical, solarArray, and commRelay.

Complete Example Timeline JSON

{
  "missionTitle": "ARTEMIS BASE CAMP — EVA-04 SURFACE OPS",
  "durationMinutes": 240,
  "waypoints": {
    "habitatAirlock": { "x": 38, "y": 0 },
    "pm1": { "x": 115, "y": -55 },
    "pm2": { "x": 115, "y": 55 },
    "safEast": { "x": 235, "y": 0 },
    "chargingBay": { "x": -110, "y": 115 },
    "southRidge": { "x": -65, "y": 1200 }
  },
  "phases": [
    {
      "id": "P1",
      "startMin": 0,
      "endMin": 30,
      "title": "Airlock Egress & Vehicle Checkout",
      "alphaTask": "Depressurize airlock, egress, and inspect Habitat hull.",
      "betaTask": "Egress airlock; run boot-up diagnostics on PR-1, LTV-1, and LTV-2."
    },
    {
      "id": "P2",
      "startMin": 30,
      "endMin": 75,
      "title": "Umbilical Deployment & South Traverse",
      "alphaTask": "Deploy power umbilical from PM-1 to SAF-East junction box.",
      "betaTask": "Drive PR-1 and LTV-1 convoy 1.2 km south to South Ridge."
    },
    {
      "id": "P3",
      "startMin": 75,
      "endMin": 135,
      "title": "Solar Dust Mitigation & Core Drilling",
      "alphaTask": "Brush electrostatic dust on SAF-East; verify PM-2 bus handoff.",
      "betaTask": "Drill regolith core samples at South Ridge and load PR-1 rack."
    },
    {
      "id": "P4",
      "startMin": 135,
      "endMin": 180,
      "title": "Radiator Inspection & Return Convoy",
      "alphaTask": "Inspect PM-1/PM-2 radiator louvers; mount mast transceiver.",
      "betaTask": "Return convoy to Base Camp; dock PR-1 to charging umbilical."
    },
    {
      "id": "P5",
      "startMin": 180,
      "endMin": 210,
      "title": "LTV-2 Perimeter Loop & Sample Offload",
      "alphaTask": "Drive LTV-2 on high-speed perimeter loop around SAF-East.",
      "betaTask": "Offload core canisters from PR-1; park LTV-1 in charging bay."
    },
    {
      "id": "P6",
      "startMin": 210,
      "endMin": 240,
      "title": "Suit Dust Blow-Off & Airlock Ingress",
      "alphaTask": "Park LTV-2, perform final suit brushing, and ingress airlock.",
      "betaTask": "Stow tools, seal outer airlock hatch, and repressurize."
    }
  ],
  "triggers": [
    {
      "min": 30,
      "id": "T+00:30",
      "label": "Team Separation",
      "summary": "Alpha deploys East to SAF-East; Beta departs South in PR-1 + LTV-1.",
      "severity": "info"
    },
    {
      "min": 75,
      "id": "T+01:15",
      "label": "Peak Range & Relay Handoff",
      "summary": "Beta reaches South Ridge (1.2 km); comm relay shifts to PR-1 mast.",
      "severity": "nominal"
    },
    {
      "min": 165,
      "id": "T+02:45",
      "label": "PR-1 Charging Dock",
      "summary": "PR-1 docks to PM-2 umbilical; LTV-2 preps for perimeter loop.",
      "severity": "nominal"
    },
    {
      "min": 225,
      "id": "T+03:45",
      "label": "Airlock Ingress Lock",
      "summary": "All 4 crew inside airlock; PLSS O2/battery reserves at ~38%.",
      "severity": "info"
    }
  ],
  "entities": {
    "EV-1": {
      "role": "Commander (Alpha)",
      "team": "Alpha",
      "keyframes": [
        { "min": 0, "x": 18, "y": -4, "state": "AIRLOCK", "o2": 100, "bat": 100, "hr": 78 },
        { "min": 15, "x": 45, "y": -10, "state": "EGRESS", "o2": 96, "bat": 97, "hr": 92 },
        { "min": 30, "x": 65, "y": -25, "state": "WALKING", "o2": 91, "bat": 93, "hr": 104 },
        { "min": 75, "x": 205, "y": -12, "state": "WORKING", "o2": 78, "bat": 81, "hr": 116 },
        { "min": 135, "x": 230, "y": 14, "state": "WORKING", "o2": 62, "bat": 66, "hr": 112 },
        { "min": 180, "x": 110, "y": 42, "state": "INSPECTING", "o2": 50, "bat": 54, "hr": 98 },
        { "min": 195, "x": 295, "y": -65, "state": "RIDING LTV-2", "o2": 45, "bat": 50, "hr": 88 },
        { "min": 210, "x": -95, "y": 132, "state": "DOCKING", "o2": 41, "bat": 46, "hr": 94 },
        { "min": 225, "x": 22, "y": -4, "state": "AIRLOCK", "o2": 37, "bat": 41, "hr": 84 },
        { "min": 240, "x": 16, "y": -4, "state": "PRESSURIZED", "o2": 36, "bat": 40, "hr": 74 }
      ]
    },
    "PR-1": {
      "type": "Pressurized Rover",
      "keyframes": [
        { "min": 0, "x": -85, "y": 65, "heading": 90, "bat": 98, "speed": 0, "status": "STANDBY" },
        { "min": 30, "x": -85, "y": 65, "heading": 90, "bat": 97, "speed": 0, "status": "READY" },
        { "min": 75, "x": -65, "y": 1200, "heading": 90, "bat": 79, "speed": 1.6, "status": "TRAVERSE" },
        { "min": 135, "x": -65, "y": 1200, "heading": -90, "bat": 74, "speed": 0, "status": "SAMPLE OPS" },
        { "min": 165, "x": 92, "y": 78, "heading": 0, "bat": 58, "speed": 1.8, "status": "DOCKED" },
        { "min": 240, "x": 92, "y": 78, "heading": 0, "bat": 94, "speed": 0, "status": "CHARGING" }
      ]
    }
  },
  "systems": {
    "umbilical": [
      { "min": 0, "progress": 0.0, "active": false },
      { "min": 30, "progress": 0.0, "active": false },
      { "min": 75, "progress": 1.0, "active": true },
      { "min": 240, "progress": 1.0, "active": true }
    ],
    "solarArray": [
      { "min": 0, "cleanliness": 0.35, "outputKw": 14.2 },
      { "min": 75, "cleanliness": 0.35, "outputKw": 14.5 },
      { "min": 135, "cleanliness": 0.98, "outputKw": 28.4 },
      { "min": 240, "cleanliness": 0.96, "outputKw": 27.9 }
    ],
    "commRelay": [
      { "min": 0, "source": "HABITAT" },
      { "min": 75, "source": "PR-1" },
      { "min": 165, "source": "HABITAT" },
      { "min": 240, "source": "HABITAT" }
    ]
  }
}

Schema & Interpolation Rules

  • Coordinate System (x, y): Measured in meters on the lunar plane with the Lunar Habitat centered at (0, 0). Positive x is East (toward SAF-East at x: 235), and positive y is South (toward South Ridge at y: 1200).

  • Entities (entities): Must include keys for EV-1, EV-2, EV-3, EV-4, PR-1, LTV-1, and LTV-2. Each entity's keyframes array must be sorted in ascending order by min from 0 to durationMinutes.

    • Astronaut keyframes interpolate x, y, o2 (%), bat (%), and hr (bpm), and hold discrete state strings (e.g., "AIRLOCK", "WALKING", "WORKING", "RIDING LTV-2") until the next keyframe.

    • Vehicle keyframes interpolate x, y, heading (degrees), bat (%), and speed (m/s), and hold status strings (e.g., "STANDBY", "TRAVERSE", "CHARGING").

  • Phases (phases): Must be ordered chronologically (startMin < endMin) within [0, durationMinutes] to populate the color-coded timeline bar and active task banner.

  • Triggers (triggers): Optional milestone markers rendered as clickable jump pins on the timeline scrubber and automatically posted to the Mission Control event log when the simulation clock crosses min.

From <https://gemini.google.com/app/39a743a21517732f>  Google Gemini (4 Hydrogen)



<!DOCTYPE html>

<html lang="en" class="dark">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>ARTEMIS // LUNAR SURFACE EVA SIMULATION TELEMETRY (T+00:00 - T+04:00)</title>

  <!-- Tailwind CSS -->

  <script src="https://cdn.tailwindcss.com"></script>

  <!-- Google Fonts: Inter & JetBrains Mono -->

  <link rel="preconnect" href="https://fonts.googleapis.com">

  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">

  <script>

    tailwind.config = {

      darkMode: 'class',

      theme: {

        extend: {

          fontFamily: {

            sans: ['Inter', 'sans-serif'],

            mono: ['JetBrains Mono', 'monospace'],

          },

          colors: {

            mcc: {

              bg: '#06090f',

              panel: '#0c121e',

              card: '#111929',

              border: '#1e2c45',

              accent: '#38bdf8',

              amber: '#f59e0b',

              emerald: '#10b981',

              rose: '#f43f5e',

              purple: '#a855f7'

            }

          }

        }

      }

    };

  </script>

  <style>

    /* Custom scrollbar for NASA MCC aesthetic */

    ::-webkit-scrollbar {

      width: 6px;

      height: 6px;

    }

    ::-webkit-scrollbar-track {

      background: #06090f;

    }

    ::-webkit-scrollbar-thumb {

      background: #1e2c45;

      border-radius: 9999px;

    }

    ::-webkit-scrollbar-thumb:hover {

      background: #38bdf8;

    }


    /* Custom Range Scrubber Styling */

    input[type="range"].timeline-scrubber {

      -webkit-appearance: none;

      appearance: none;

      background: transparent;

      cursor: pointer;

    }

    input[type="range"].timeline-scrubber::-webkit-slider-runnable-track {

      height: 8px;

      border-radius: 9999px;

      background: #1e2c45;

    }

    input[type="range"].timeline-scrubber::-webkit-slider-thumb {

      -webkit-appearance: none;

      appearance: none;

      width: 18px;

      height: 18px;

      border-radius: 50%;

      background: #38bdf8;

      border: 2px solid #06090f;

      box-shadow: 0 0 10px rgba(56, 189, 248, 0.8);

      margin-top: -5px;

      transition: transform 0.1s ease;

    }

    input[type="range"].timeline-scrubber::-webkit-slider-thumb:hover {

      transform: scale(1.2);

    }


    /* Subtle scanline overlay on canvas */

    .canvas-scanline {

      background: linear-gradient(

        rgba(18, 16, 16, 0) 50%,

        rgba(0, 0, 0, 0.18) 50%

      );

      background-size: 100% 4px;

      pointer-events: none;

    }


    @keyframes pulse-ring {

      0% { transform: scale(0.95); opacity: 0.9; }

      50% { transform: scale(1.05); opacity: 0.4; }

      100% { transform: scale(0.95); opacity: 0.9; }

    }

    .status-dot-live {

      animation: pulse-ring 2s infinite ease-in-out;

    }

  </style>

</head>

<body class="bg-mcc-bg text-slate-200 font-sans antialiased selection:bg-sky-500 selection:text-white overflow-x-hidden lg:overflow-hidden flex flex-col min-h-screen lg:h-screen">


  <!-- TOP MISSION CONTROL HEADER -->

  <header class="bg-mcc-panel border-b border-mcc-border px-4 py-2.5 flex flex-wrap items-center justify-between gap-3 shrink-0 z-20">

    <div class="flex items-center gap-3">

      <div class="w-9 h-9 rounded-lg bg-sky-500/10 border border-sky-500/40 flex items-center justify-center text-sky-400 font-mono font-bold text-sm shadow-inner">

        EVA

      </div>

      <div>

        <div class="flex items-center gap-2">

          <h1 class="text-sm sm:text-base font-bold tracking-wider uppercase text-white">

            Lunar Surface Operations // Shackleton Rim Base

          </h1>

          <span class="hidden sm:inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-mono font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">

            <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 status-dot-live"></span>

            SIM NOMINAL

          </span>

        </div>

        <p class="text-[11px] font-mono text-slate-400">

          4-HR SURFACE EVA TIMELINE • CREW: TEAM ALPHA (EV-1/2) & TEAM BETA (EV-3/4) • ASSETS: HAB, PM-1/2, SAF-EAST, PR-1, LTV-1/2

        </p>

      </div>

    </div>


    <!-- MET Clock & Active Phase Pill -->

    <div class="flex items-center gap-3 sm:gap-5">

      <div class="hidden md:block text-right">

        <div class="text-[10px] font-mono uppercase tracking-widest text-slate-400">Current Operational Phase</div>

        <div id="headerPhaseLabel" class="text-xs font-mono font-semibold text-amber-400">

          PHASE 1: EGRESS & SYSTEM CHECKS

        </div>

      </div>

      <div class="bg-mcc-bg border border-mcc-border rounded-lg px-3.5 py-1.5 text-right shadow-inner">

        <div class="text-[10px] font-mono uppercase tracking-widest text-slate-400">Mission Elapsed Time</div>

        <div id="metClockDisplay" class="text-lg sm:text-xl font-mono font-bold text-sky-400 tracking-wider">

          T+00:00:00

        </div>

      </div>

    </div>

  </header>


  <!-- MAIN WORKSPACE GRID -->

  <main class="flex-1 flex flex-col lg:flex-row overflow-hidden min-h-0">


    <!-- LEFT SIDEBAR: CREW & PLSS TELEMETRY -->

    <aside class="w-full lg:w-80 xl:w-88 bg-mcc-panel border-b lg:border-b-0 lg:border-r border-mcc-border flex flex-col shrink-0 lg:overflow-y-auto">

      <div class="px-3.5 py-2.5 border-b border-mcc-border flex items-center justify-between bg-mcc-card/50">

        <span class="text-xs font-mono font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">

          <svg class="w-3.5 h-3.5 text-sky-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>

          Crew & AxEMU PLSS Telemetry

        </span>

        <span class="text-[10px] font-mono text-slate-400">4 ACTIVE</span>

      </div>


      <!-- Team Alpha Header -->

      <div class="px-3.5 pt-2.5 pb-1 flex items-center justify-between">

        <span class="text-[10px] font-mono font-semibold uppercase tracking-widest text-sky-400">Team Alpha • Infrastructure</span>

        <span class="text-[10px] font-mono text-slate-500">SAF-East / Base</span>

      </div>

      <div id="teamAlphaCards" class="px-3 space-y-2.5 pb-2">

        <!-- Populated dynamically via JS -->

      </div>


      <!-- Team Beta Header -->

      <div class="px-3.5 pt-2 pb-1 flex items-center justify-between border-t border-mcc-border/60">

        <span class="text-[10px] font-mono font-semibold uppercase tracking-widest text-amber-400">Team Beta • Field Traverse</span>

        <span class="text-[10px] font-mono text-slate-500">South Ridge (1.2km)</span>

      </div>

      <div id="teamBetaCards" class="px-3 space-y-2.5 pb-3">

        <!-- Populated dynamically via JS -->

      </div>

    </aside>


    <!-- CENTER VIEWPORT: INTERACTIVE 2D LUNAR SURFACE CANVAS -->

    <section class="flex-1 flex flex-col relative bg-mcc-bg min-h-[420px] lg:min-h-0 overflow-hidden">

      <!-- Canvas Container -->

      <div id="canvasContainer" class="relative flex-1 w-full h-full overflow-hidden cursor-grab active:cursor-grabbing select-none">

        <canvas id="lunarCanvas" class="block w-full h-full"></canvas>

        <div class="canvas-scanline absolute inset-0"></div>


        <!-- Top-Left Canvas HUD: Camera & Layer Toggles -->

        <div class="absolute top-3 left-3 flex flex-wrap items-center gap-1.5 z-10">

          <button id="btnResetCam" class="px-2.5 py-1.5 rounded-lg bg-mcc-panel/90 hover:bg-mcc-card border border-mcc-border text-[11px] font-mono text-slate-200 shadow-lg backdrop-blur-sm transition flex items-center gap-1.5" title="Reset Overview Camera">

            <svg class="w-3.5 h-3.5 text-sky-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"/></svg>

            Overview

          </button>

          <button id="btnZoomBase" class="px-2.5 py-1.5 rounded-lg bg-mcc-panel/90 hover:bg-mcc-card border border-mcc-border text-[11px] font-mono text-slate-200 shadow-lg backdrop-blur-sm transition">

            Base Camp

          </button>

          <button id="btnZoomRidge" class="px-2.5 py-1.5 rounded-lg bg-mcc-panel/90 hover:bg-mcc-card border border-mcc-border text-[11px] font-mono text-slate-200 shadow-lg backdrop-blur-sm transition">

            South Ridge

          </button>

          <button id="btnToggleTracks" class="px-2.5 py-1.5 rounded-lg bg-sky-500/20 border border-sky-500/50 text-[11px] font-mono text-sky-300 shadow-lg backdrop-blur-sm transition">

            Tracks: ON

          </button>

          <button id="btnToggleComms" class="px-2.5 py-1.5 rounded-lg bg-sky-500/20 border border-sky-500/50 text-[11px] font-mono text-sky-300 shadow-lg backdrop-blur-sm transition">

            RF Rings: ON

          </button>

        </div>


        <!-- Top-Right Canvas HUD: Selected / Followed Entity Inspector -->

        <div id="entityInspector" class="absolute top-3 right-3 w-64 rounded-xl bg-mcc-panel/95 border border-mcc-border p-3 shadow-2xl backdrop-blur-md z-10 transition-all">

          <div class="flex items-center justify-between border-b border-mcc-border pb-1.5 mb-2">

            <div class="flex items-center gap-1.5">

              <span id="inspDot" class="w-2 h-2 rounded-full bg-sky-400"></span>

              <span id="inspName" class="text-xs font-mono font-bold text-white">LUNAR HABITAT</span>

            </div>

            <div class="flex items-center gap-1">

              <button id="btnFollowToggle" class="px-2 py-0.5 rounded text-[10px] font-mono bg-mcc-card hover:bg-sky-500/20 text-slate-300 border border-mcc-border transition">

                FOLLOW: OFF

              </button>

            </div>

          </div>

          <div id="inspDetails" class="space-y-1 text-[11px] font-mono text-slate-300">

            <!-- Populated dynamically -->

          </div>

          <div class="mt-2 pt-1.5 border-t border-mcc-border/60 text-[10px] font-mono text-slate-500 flex justify-between">

            <span>Click any asset to inspect</span>

            <span id="zoomLevelLabel">1.0x</span>

          </div>

        </div>


        <!-- Bottom-Left Canvas HUD: Map Legend & Scale Bar -->

        <div class="absolute bottom-3 left-3 flex flex-wrap items-center gap-3 bg-mcc-panel/90 border border-mcc-border rounded-lg px-3 py-1.5 text-[10px] font-mono text-slate-300 backdrop-blur-sm pointer-events-none">

          <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-sky-400 inline-block"></span> Team Alpha (EV-1/2)</div>

          <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-amber-400 inline-block"></span> Team Beta (EV-3/4)</div>

          <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-emerald-400 inline-block"></span> PR-1 / LTV-1/2</div>

          <div class="flex items-center gap-1.5 border-l border-mcc-border pl-3">

            <span id="scaleBarLabel">200m</span>

            <div id="scaleBarVisual" class="h-1.5 border-x border-b border-slate-400 w-12"></div>

          </div>

        </div>


        <!-- Bottom-Right Zoom Controls -->

        <div class="absolute bottom-3 right-3 flex flex-col gap-1 z-10">

          <button id="btnZoomIn" class="w-8 h-8 rounded-lg bg-mcc-panel/90 hover:bg-mcc-card border border-mcc-border text-slate-200 font-mono font-bold flex items-center justify-center shadow-lg">+</button>

          <button id="btnZoomOut" class="w-8 h-8 rounded-lg bg-mcc-panel/90 hover:bg-mcc-card border border-mcc-border text-slate-200 font-mono font-bold flex items-center justify-center shadow-lg">−</button>

        </div>

      </div>

    </section>


    <!-- RIGHT SIDEBAR: VEHICLES, POWER & MISSION LOG -->

    <aside class="w-full lg:w-88 xl:w-96 bg-mcc-panel border-t lg:border-t-0 lg:border-l border-mcc-border flex flex-col shrink-0 lg:overflow-y-auto">

      

      <!-- Mobility Assets Section -->

      <div class="px-3.5 py-2.5 border-b border-mcc-border flex items-center justify-between bg-mcc-card/50">

        <span class="text-xs font-mono font-bold uppercase tracking-wider text-slate-300 flex items-center gap-2">

          <svg class="w-3.5 h-3.5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>

          Mobility & Surface Power Grid

        </span>

      </div>


      <!-- Vehicles Grid -->

      <div id="vehicleCards" class="p-3 space-y-2 border-b border-mcc-border">

        <!-- Populated dynamically via JS -->

      </div>


      <!-- Base Power & Comms Telemetry -->

      <div class="p-3 border-b border-mcc-border space-y-2">

        <div class="flex items-center justify-between">

          <span class="text-[10px] font-mono font-semibold uppercase tracking-widest text-slate-400">Base Power & RF Telemetry</span>

          <span id="commRelayBadge" class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-sky-500/15 text-sky-400 border border-sky-500/30">

            HABITAT DIRECT LOS

          </span>

        </div>

        <div id="powerGridCard" class="bg-mcc-card rounded-xl p-2.5 border border-mcc-border space-y-2 text-xs font-mono">

          <!-- Populated dynamically via JS -->

        </div>

      </div>


      <!-- Event & State Transition Log -->

      <div class="flex-1 flex flex-col min-h-[180px]">

        <div class="px-3.5 py-2 border-b border-mcc-border flex items-center justify-between bg-mcc-card/40">

          <span class="text-[11px] font-mono font-bold uppercase tracking-wider text-slate-300">

            Mission Event & Trigger Log

          </span>

          <span class="text-[10px] font-mono text-slate-500">AUTO-SYNC</span>

        </div>

        <div id="missionEventLog" class="flex-1 p-3 space-y-2 overflow-y-auto font-mono text-[11px]">

          <!-- Populated dynamically via JS -->

        </div>

      </div>

    </aside>


  </main>


  <!-- BOTTOM PLAYBACK & TIMELINE SCRUBBER BAR -->

  <footer class="bg-mcc-panel border-t border-mcc-border px-4 py-3 shrink-0 z-20">

    <div class="max-w-[1920px] mx-auto flex flex-col gap-2.5">

      

      <!-- Top Row: Playback Buttons, Speed Selector, and Phase Trigger Quick-Jumps -->

      <div class="flex flex-wrap items-center justify-between gap-3">

        <!-- Playback Transport -->

        <div class="flex items-center gap-2">

          <button id="btnPlayPause" class="px-3.5 py-1.5 rounded-lg bg-sky-500 hover:bg-sky-400 text-slate-950 font-mono font-bold text-xs flex items-center gap-1.5 shadow-md shadow-sky-500/20 transition">

            <svg id="iconPlay" class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20"><path d="M6.3 2.841A1.5 1.5 0 004 4.11V15.89a1.5 1.5 0 002.3 1.269l9.344-5.89a1.5 1.5 0 000-2.538L6.3 2.84z"/></svg>

            <svg id="iconPause" class="w-3.5 h-3.5 hidden" fill="currentColor" viewBox="0 0 20 20"><path d="M5.75 3a.75.75 0 00-.75.75v12.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75V3.75A.75.75 0 007.25 3h-1.5zM12.75 3a.75.75 0 00-.75.75v12.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75V3.75a.75.75 0 00-.75-.75h-1.5z"/></svg>

            <span id="playPauseLabel">PLAY</span>

          </button>


          <button id="btnReset" class="px-2.5 py-1.5 rounded-lg bg-mcc-card hover:bg-slate-800 border border-mcc-border text-slate-300 font-mono text-xs transition" title="Reset to T+00:00">

            RESET

          </button>


          <!-- Speed Selector -->

          <div class="flex items-center bg-mcc-bg border border-mcc-border rounded-lg p-0.5 ml-1">

            <span class="text-[10px] font-mono text-slate-500 px-2">RATE:</span>

            <button data-speed="1" class="speed-btn px-2 py-1 rounded-md text-[11px] font-mono text-slate-400 hover:text-white transition">1x</button>

            <button data-speed="10" class="speed-btn px-2 py-1 rounded-md text-[11px] font-mono text-slate-400 hover:text-white transition">10x</button>

            <button data-speed="30" class="speed-btn px-2 py-1 rounded-md text-[11px] font-mono bg-sky-500/20 text-sky-400 font-bold transition">30x</button>

            <button data-speed="60" class="speed-btn px-2 py-1 rounded-md text-[11px] font-mono text-slate-400 hover:text-white transition">60x</button>

            <button data-speed="120" class="speed-btn px-2 py-1 rounded-md text-[11px] font-mono text-slate-400 hover:text-white transition">120x</button>

          </div>

        </div>


        <!-- Key State Trigger Quick-Jump Badges -->

        <div class="flex flex-wrap items-center gap-1.5">

          <span class="text-[10px] font-mono text-slate-400 uppercase mr-1 hidden sm:inline">Triggers:</span>

          <button data-jump="30" class="trigger-jump px-2 py-1 rounded-md bg-mcc-card hover:bg-sky-500/20 border border-mcc-border hover:border-sky-500/40 text-[10px] font-mono text-slate-300 transition">

            T+00:30 Separation

          </button>

          <button data-jump="75" class="trigger-jump px-2 py-1 rounded-md bg-mcc-card hover:bg-amber-500/20 border border-mcc-border hover:border-amber-500/40 text-[10px] font-mono text-slate-300 transition">

            T+01:15 Peak Dist / Relay

          </button>

          <button data-jump="165" class="trigger-jump px-2 py-1 rounded-md bg-mcc-card hover:bg-emerald-500/20 border border-mcc-border hover:border-emerald-500/40 text-[10px] font-mono text-slate-300 transition">

            T+02:45 PR-1 Dock

          </button>

          <button data-jump="225" class="trigger-jump px-2 py-1 rounded-md bg-mcc-card hover:bg-purple-500/20 border border-mcc-border hover:border-purple-500/40 text-[10px] font-mono text-slate-300 transition">

            T+03:45 Ingress Lock

          </button>

        </div>

      </div>


      <!-- Bottom Row: Interactive Scrubber Slider & Phase Segments -->

      <div class="relative pt-1">

        <!-- Phase Segment Bar Visual -->

        <div class="grid grid-cols-48 h-2 rounded-full overflow-hidden mb-1.5 bg-mcc-bg border border-mcc-border/80 text-[9px] font-mono" style="grid-template-columns: 30fr 45fr 60fr 45fr 30fr 30fr;">

          <div data-jump="0" class="phase-seg cursor-pointer bg-sky-500/30 hover:bg-sky-500/50 border-r border-mcc-bg transition" title="00:00-00:30: Airlock Egress & Pre-Drive Checks"></div>

          <div data-jump="30" class="phase-seg cursor-pointer bg-indigo-500/30 hover:bg-indigo-500/50 border-r border-mcc-bg transition" title="00:30-01:15: Umbilical Deploy & Convoy South"></div>

          <div data-jump="75" class="phase-seg cursor-pointer bg-amber-500/30 hover:bg-amber-500/50 border-r border-mcc-bg transition" title="01:15-02:15: SAF-East Cleaning & Core Drilling"></div>

          <div data-jump="135" class="phase-seg cursor-pointer bg-emerald-500/30 hover:bg-emerald-500/50 border-r border-mcc-bg transition" title="02:15-03:00: Radiator/Mast Ops & Return Convoy"></div>

          <div data-jump="180" class="phase-seg cursor-pointer bg-cyan-500/30 hover:bg-cyan-500/50 border-r border-mcc-bg transition" title="03:00-03:30: LTV-2 Perimeter Loop & Sample Unload"></div>

          <div data-jump="210" class="phase-seg cursor-pointer bg-purple-500/30 hover:bg-purple-500/50 transition" title="03:30-04:00: Final Dust Blow-off & Airlock Ingress"></div>

        </div>


        <!-- Scrubber Input -->

        <input id="timelineSlider" type="range" min="0" max="240" step="0.05" value="0" class="timeline-scrubber w-full block" />


        <!-- Tick Labels -->

        <div class="flex justify-between text-[10px] font-mono text-slate-400 mt-1 select-none">

          <span class="cursor-pointer hover:text-sky-400" data-jump="0">00:00 (Egress)</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="30">00:30</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="75">01:15 (Ridge)</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="135">02:15 (Return)</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="180">03:00 (LTV-2 Loop)</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="210">03:30</span>

          <span class="cursor-pointer hover:text-sky-400" data-jump="240">04:00 (Seal)</span>

        </div>

      </div>


    </div>

  </footer>


  <script>

    /**

     * LUNAR SURFACE EVA SIMULATION ENGINE (T+00:00 to T+04:00)

     * Coordinate System:

     *   Origin (0, 0) = Lunar Habitat Center (meters)

     *   +X = East, -X = West

     *   +Y = South, -Y = North (Canvas standard Y-down maps cleanly to North-up!)

     *   South Ridge Sampling Waypoint = (0, 1200) -> 1.2 km South of Habitat

     */


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

    // 1. STATIC SCENE INFRASTRUCTURE & LUNAR TERRAIN DATA

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

    const INFRASTRUCTURE = {

      habitat: {

        id: 'habitat',

        name: 'LUNAR HABITAT',

        type: 'Pressurized Module',

        x: 0,

        y: 0,

        radius: 26,

        airlock: { x: 0, y: 28 },

        mast: { x: -16, y: -16 },

        color: '#e2e8f0'

      },

      pm1: {

        id: 'pm1',

        name: 'POWER MODULE PM-1',

        type: 'Fission/Battery Bus A',

        x: 95,

        y: -20,

        w: 28,

        h: 18,

        color: '#38bdf8'

      },

      pm2: {

        id: 'pm2',

        name: 'POWER MODULE PM-2',

        type: 'Secondary Bus & Fast Charger',

        x: 95,

        y: 32,

        w: 28,

        h: 18,

        color: '#10b981'

      },

      safEast: {

        id: 'safEast',

        name: 'SOLAR ARRAY FIELD (SAF-EAST)',

        type: '3x4 Vertical/Tracking Array',

        x: 210,

        y: -35,

        rows: 3,

        cols: 4,

        panelW: 22,

        panelH: 14,

        gapX: 30,

        gapY: 26,

        junctionBox: { x: 162, y: -12 }

      },

      southRidge: {

        id: 'southRidge',

        name: 'SOUTH RIDGE WAYPOINT',

        type: 'Geological Core Site Alpha',

        x: 0,

        y: 1200,

        radius: 45

      },

      bays: {

        pr1: { x: -45, y: 55 },

        ltv1: { x: -15, y: 65 },

        ltv2: { x: 25, y: 65 }

      }

    };


    // Deterministic procedural craters & ridge contours for visual spatial reference

    const CRATERS = [

      { x: -180, y: -120, r: 55, depth: 0.35 },

      { x: 340, y: 110, r: 75, depth: 0.4 },

      { x: -240, y: 260, r: 90, depth: 0.3 },

      { x: 160, y: 420, r: 110, depth: 0.45 },

      { x: -140, y: 650, r: 85, depth: 0.35 },

      { x: 220, y: 840, r: 130, depth: 0.4 },

      { x: -290, y: 980, r: 95, depth: 0.3 },

      { x: 145, y: 1130, r: 60, depth: 0.45 },

      { x: -95, y: 1290, r: 70, depth: 0.35 },

      { x: 40, y: 145, r: 22, depth: 0.25 },

      { x: -65, y: 310, r: 30, depth: 0.3 },

      { x: 95, y: 680, r: 38, depth: 0.28 }

    ];


    // Timeline Phases Definition

    const PHASES = [

      {

        id: 1,

        start: 0,

        end: 30,

        shortName: 'PHASE 1: EGRESS & CHECKS',

        title: 'Airlock Egress & Pre-Drive Systems Check',

        alphaTask: 'Airlock egress; visual walkaround of Habitat hull',

        betaTask: 'Airlock egress; pre-drive systems check on PR-1, LTV-1, LTV-2'

      },

      {

        id: 2,

        start: 30,

        end: 75,

        shortName: 'PHASE 2: DEPLOY & CONVOY SOUTH',

        title: 'Umbilical Deployment & 1.2 km South Convoy',

        alphaTask: 'Deploying power umbilical cable from PM-1 to SAF-East',

        betaTask: 'Tandem convoy drive (PR-1 + LTV-1) 1.2 km south to Ridge'

      },

      {

        id: 3,

        start: 75,

        end: 135,

        shortName: 'PHASE 3: DUST MITIGATION & CORING',

        title: 'SAF-East Dust Mitigation & Ridge Core Drilling',

        alphaTask: 'Electrostatic dust brushing on SAF-East; PM-2 voltage handoff',

        betaTask: 'Geological core drilling & sample caching into PR-1 rack'

      },

      {

        id: 4,

        start: 135,

        end: 180,

        shortName: 'PHASE 4: RADIATORS & RETURN CONVOY',

        title: 'Radiator/Mast Upgrade & Return Convoy to Base',

        alphaTask: 'Inspect PM-1/2 radiators; mount Habitat mast transceiver',

        betaTask: 'Return convoy north to Base; dock PR-1 to PM-2 charger'

      },

      {

        id: 5,

        start: 180,

        end: 210,

        shortName: 'PHASE 5: LTV-2 LOOP & UNLOAD',

        title: 'LTV-2 Perimeter Inspection & Sample Unload',

        alphaTask: 'High-speed perimeter inspection loop around SAF-East on LTV-2',

        betaTask: 'Unload geological cores from PR-1; park LTV-1 in charging bay'

      },

      {

        id: 6,

        start: 210,

        end: 240,

        shortName: 'PHASE 6: DUST BLOW-OFF & INGRESS',

        title: 'Final Suit Dust Blow-off & Airlock Repressurization',

        alphaTask: 'Park LTV-2 in bay; suit dust blow-off & Habitat airlock ingress',

        betaTask: 'Tool stowage; suit dust blow-off & Habitat airlock ingress'

      }

    ];


    // Mission Trigger Events for Log

    const MISSION_TRIGGERS = [

      { min: 0, type: 'INFO', tag: 'T+00:00', text: 'Airlock depressurized to 0.0 psi. Outer hatch open; EVA clock started.' },

      { min: 10, type: 'INFO', tag: 'T+00:10', text: 'All 4 crew on lunar regolith. Team Alpha starting hull walkaround; Team Beta booting PR-1 & LTVs.' },

      { min: 30, type: 'TRIGGER', tag: 'T+00:30 [SEPARATION]', text: 'Crew splits into two vectors: Team Alpha East to PM-1/SAF-East; Team Beta South convoy (PR-1 + LTV-1).' },

      { min: 52, type: 'INFO', tag: 'T+00:52', text: 'PM-1 to SAF-East high-voltage umbilical connected and locked at Junction Box J-1.' },

      { min: 75, type: 'TRIGGER', tag: 'T+01:15 [PEAK DIST & RELAY]', text: 'Team Beta arrives at South Ridge (1.2 km). RF Comm Relay switches to PR-1 Mast Relay.' },

      { min: 105, type: 'INFO', tag: 'T+01:45', text: 'SAF-East dust brushing 50% complete; array output rising. Team Beta caching Core Sample #2.' },

      { min: 135, type: 'INFO', tag: 'T+02:15', text: 'SAF-East cleaning 100% (48.4 kW nominal). Team Beta departs South Ridge northbound.' },

      { min: 165, type: 'TRIGGER', tag: 'T+02:45 [PR-1 DOCKING]', text: 'PR-1 docked to PM-2 fast-charging umbilical. RF Comm Relay returned to Habitat Mast.' },

      { min: 180, type: 'INFO', tag: 'T+03:00', text: 'Team Alpha boards standby LTV-2 for SAF-East perimeter inspection loop. Team Beta unloading cores.' },

      { min: 210, type: 'INFO', tag: 'T+03:30', text: 'LTV-2 returned to charging bay. All 3 vehicles docked. Crew converging at Airlock.' },

      { min: 225, type: 'TRIGGER', tag: 'T+03:45 [INGRESS LOCK]', text: 'All 4 astronauts inside Habitat Airlock. Outer hatch sealed; repressurization initiated.' },

      { min: 240, type: 'SUCCESS', tag: 'T+04:00 [EVA COMPLETE]', text: 'Airlock at 8.2 psi. 4-hour surface EVA concluded nominally. PLSS reserves ~38%.' }

    ];


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

    // 2. MATH & INTERPOLATION HELPERS

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

    const clamp = (v, min, max) => Math.max(min, Math.min(max, v));

    const lerp = (a, b, t) => a + (b - a) * t;

    const smoothstep = (t) => {

      const x = clamp(t, 0, 1);

      return x * x * (3 - 2 * x);

    };

    const dist2D = (a, b) => Math.hypot(b.x - a.x, b.y - a.y);


    // Piecewise linear / smooth waypoint path evaluator

    function evalPath(tMin, keyframes, smooth = true) {

      if (tMin <= keyframes[0].t) {

        return { x: keyframes[0].x, y: keyframes[0].y, heading: keyframes[0].heading ?? 0, speed: 0 };

      }

      const last = keyframes[keyframes.length - 1];

      if (tMin >= last.t) {

        return { x: last.x, y: last.y, heading: last.heading ?? 0, speed: 0 };

      }

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

        const k0 = keyframes[i];

        const k1 = keyframes[i + 1];

        if (tMin >= k0.t && tMin <= k1.t) {

          const dt = k1.t - k0.t;

          const rawU = dt > 0 ? (tMin - k0.t) / dt : 0;

          const u = smooth ? smoothstep(rawU) : rawU;

          const x = lerp(k0.x, k1.x, u);

          const y = lerp(k0.y, k1.y, u);

          const dx = k1.x - k0.x;

          const dy = k1.y - k0.y;

          const segDist = Math.hypot(dx, dy);

          const heading = segDist > 0.5 ? Math.atan2(dy, dx) : (k1.heading ?? k0.heading ?? 0);

          // Speed in km/h (meters / minutes * 0.06)

          const speed = dt > 0 && segDist > 0.5 ? (segDist / dt) * 0.06 : 0;

          return { x, y, heading, speed };

        }

      }

      return { x: last.x, y: last.y, heading: 0, speed: 0 };

    }


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

    // 3. KINEMATIC TRAJECTORIES FOR ALL 4 ASTRONAUTS & 3 VEHICLES

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

    // Keyframes carefully choreographed to match every phase of the 240-minute timeline

    const TRAJECTORIES = {

      // Pressurized Rover (PR-1)

      pr1: [

        { t: 0, x: -45, y: 55, heading: Math.PI / 2 },

        { t: 30, x: -45, y: 55, heading: Math.PI / 2 },

        { t: 36, x: -35, y: 120, heading: Math.PI / 2 },

        { t: 55, x: -22, y: 620, heading: Math.PI / 2 },

        { t: 75, x: -18, y: 1185, heading: Math.PI / 2 }, // Arrives South Ridge (1.2 km)

        { t: 135, x: -18, y: 1185, heading: Math.PI / 2 }, // Parked during coring

        { t: 155, x: -20, y: 640, heading: -Math.PI / 2 },

        { t: 162, x: 45, y: 95, heading: -Math.PI / 4 },

        { t: 165, x: 75, y: 48, heading: 0 }, // Docked at PM-2 fast charger at T+02:45

        { t: 240, x: 75, y: 48, heading: 0 }

      ],


      // Lunar Terrain Vehicle 1 (LTV-1)

      ltv1: [

        { t: 0, x: -15, y: 65, heading: Math.PI / 2 },

        { t: 30, x: -15, y: 65, heading: Math.PI / 2 },

        { t: 36, x: -8, y: 135, heading: Math.PI / 2 },

        { t: 55, x: 12, y: 635, heading: Math.PI / 2 },

        { t: 75, x: 18, y: 1192, heading: Math.PI / 2 }, // Arrives South Ridge

        { t: 135, x: 18, y: 1192, heading: Math.PI / 2 },

        { t: 155, x: 14, y: 650, heading: -Math.PI / 2 },

        { t: 175, x: -15, y: 95, heading: -Math.PI / 2 },

        { t: 185, x: -15, y: 65, heading: Math.PI / 2 }, // Parked back in charging bay

        { t: 240, x: -15, y: 65, heading: Math.PI / 2 }

      ],


      // Lunar Terrain Vehicle 2 (LTV-2 - Standby until 03:00, then SAF-East perimeter loop)

      ltv2: [

        { t: 0, x: 25, y: 65, heading: Math.PI / 2 },

        { t: 180, x: 25, y: 65, heading: Math.PI / 2 }, // Standby at Base until T+03:00

        { t: 185, x: 85, y: 72, heading: 0 },

        { t: 191, x: 345, y: 65, heading: 0 }, // South-East corner of SAF-East

        { t: 197, x: 350, y: -75, heading: -Math.PI / 2 }, // North-East corner of SAF-East

        { t: 203, x: 140, y: -82, heading: Math.PI }, // North-West corner of SAF-East

        { t: 207, x: 55, y: 15, heading: Math.PI * 0.75 },

        { t: 210, x: 25, y: 65, heading: Math.PI / 2 }, // Returned to charging bay at T+03:30

        { t: 240, x: 25, y: 65, heading: Math.PI / 2 }

      ],


      // EV-1 (Team Alpha Lead)

      ev1: [

        { t: 0, x: 0, y: 12 }, // Inside airlock

        { t: 8, x: -6, y: 34 }, // Egress onto surface

        { t: 16, x: -34, y: 0 }, // Hull walkaround West

        { t: 24, x: 0, y: -34 }, // Hull walkaround North

        { t: 30, x: 28, y: -12 }, // Separation trigger

        { t: 38, x: 92, y: -12 }, // Arrive PM-1

        { t: 52, x: 160, y: -12 }, // Deploy umbilical to SAF-East junction box

        { t: 75, x: 195, y: -35 }, // Start dust mitigation brushing Row 1

        { t: 95, x: 295, y: -35 }, // Brushing Row 1 East

        { t: 115, x: 295, y: -9 }, // Brushing Row 2

        { t: 130, x: 195, y: 17 }, // Brushing Row 3

        { t: 135, x: 115, y: 28 }, // Verify voltage bus handoff to PM-2

        { t: 152, x: 95, y: 22 }, // Inspect PM-2 radiator louvers

        { t: 168, x: -14, y: -22 }, // Mount replacement transceiver on Habitat mast

        { t: 180, x: 22, y: 63 }, // Board LTV-2 (left seat)

        // Rides LTV-2 perimeter loop (180 - 210)

        { t: 185, x: 82, y: 70 },

        { t: 191, x: 342, y: 63 },

        { t: 197, x: 347, y: -77 },

        { t: 203, x: 137, y: -84 },

        { t: 207, x: 52, y: 13 },

        { t: 210, x: 22, y: 63 }, // Dismount LTV-2

        { t: 220, x: -4, y: 34 }, // Dust blow-off at airlock apron

        { t: 226, x: -2, y: 10 }, // Ingress lock

        { t: 240, x: -2, y: 10 }

      ],


      // EV-2 (Team Alpha Support)

      ev2: [

        { t: 0, x: 2, y: 12 },

        { t: 9, x: 6, y: 34 },

        { t: 17, x: 34, y: 4 }, // Hull walkaround East

        { t: 25, x: 12, y: -32 },

        { t: 30, x: 34, y: -6 }, // Separation trigger

        { t: 39, x: 102, y: -8 }, // PM-1 umbilical spool assist

        { t: 54, x: 164, y: -6 }, // Lock umbilical at SAF-East

        { t: 75, x: 205, y: 17 }, // Start dust mitigation brushing Row 3

        { t: 95, x: 300, y: 17 },

        { t: 115, x: 245, y: -9 },

        { t: 135, x: 112, y: 36 }, // PM-2 bus verification

        { t: 152, x: 95, y: -10 }, // Inspect PM-1 radiator louvers

        { t: 168, x: -22, y: -14 }, // Assist Habitat mast transceiver mount

        { t: 180, x: 28, y: 67 }, // Board LTV-2 (right seat)

        // Rides LTV-2 perimeter loop (180 - 210)

        { t: 185, x: 88, y: 74 },

        { t: 191, x: 348, y: 67 },

        { t: 197, x: 353, y: -73 },

        { t: 203, x: 143, y: -80 },

        { t: 207, x: 58, y: 17 },

        { t: 210, x: 28, y: 67 }, // Dismount LTV-2

        { t: 221, x: 4, y: 34 }, // Dust blow-off

        { t: 227, x: 2, y: 10 }, // Ingress lock

        { t: 240, x: 2, y: 10 }

      ],


      // EV-3 (Team Beta Lead - PR-1 Driver & Core Drill Operator)

      ev3: [

        { t: 0, x: -2, y: 14 },

        { t: 10, x: -10, y: 38 }, // Egress

        { t: 22, x: -40, y: 55 }, // Pre-drive inspection PR-1

        { t: 30, x: -45, y: 55 }, // Board PR-1 cabin

        { t: 36, x: -35, y: 120 },

        { t: 55, x: -22, y: 620 },

        { t: 75, x: -18, y: 1185 }, // Arrive South Ridge

        { t: 82, x: -6, y: 1202 }, // Dismount & setup core drill

        { t: 105, x: 4, y: 1212 }, // Core drilling & sample extraction

        { t: 125, x: -14, y: 1190 }, // Load sample canisters onto PR-1 rack

        { t: 135, x: -18, y: 1185 }, // Board PR-1 for return convoy

        { t: 155, x: -20, y: 640 },

        { t: 162, x: 45, y: 95 },

        { t: 165, x: 75, y: 48 }, // Dock PR-1 at PM-2 charger

        { t: 172, x: 64, y: 44 }, // Connect charging umbilical

        { t: 185, x: 62, y: 54 }, // Unload sample canisters from PR-1 rack

        { t: 202, x: 8, y: 34 }, // Transfer canisters to Habitat airlock

        { t: 216, x: -2, y: 32 }, // Dust blow-off

        { t: 224, x: -2, y: 14 }, // Ingress lock

        { t: 240, x: -2, y: 14 }

      ],


      // EV-4 (Team Beta Support - LTV-1 Driver & Sample Caching)

      ev4: [

        { t: 0, x: 2, y: 14 },

        { t: 11, x: 10, y: 38 }, // Egress

        { t: 22, x: 8, y: 65 }, // Pre-drive inspection LTV-1 & LTV-2

        { t: 30, x: -15, y: 65 }, // Board LTV-1

        { t: 36, x: -8, y: 135 },

        { t: 55, x: 12, y: 635 },

        { t: 75, x: 18, y: 1192 }, // Arrive South Ridge

        { t: 82, x: 12, y: 1205 }, // Dismount & deploy sample cache

        { t: 108, x: -2, y: 1215 }, // Regolith trenching & core sealing

        { t: 128, x: 14, y: 1196 }, // Stow tools on LTV-1

        { t: 135, x: 18, y: 1192 }, // Board LTV-1 for return

        { t: 155, x: 14, y: 650 },

        { t: 175, x: -15, y: 95 },

        { t: 185, x: -15, y: 65 }, // Park LTV-1 in charging bay

        { t: 196, x: 24, y: 52 }, // Assist EV-3 with sample transfer & tool stowage

        { t: 216, x: 4, y: 32 }, // Dust blow-off

        { t: 225, x: 2, y: 14 }, // Ingress lock

        { t: 240, x: 2, y: 14 }

      ]

    };


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

    // 4. SIMULATION STATE & TELEMETRY COMPUTATION

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

    const state = {

      simMinutes: 0,          // 0.0 to 240.0

      isPlaying: true,

      playbackSpeed: 30,      // 1x, 10x, 30x, 60x, 120x

      selectedEntityId: 'habitat',

      followSelected: false,

      showTracks: true,

      showComms: true,

      // Camera state (world meters -> screen pixels)

      cam: {

        x: 60,

        y: 520,

        zoom: 0.45,

        isDragging: false,

        dragStartX: 0,

        dragStartY: 0,

        camStartX: 0,

        camStartY: 0

      },

      lastFrameTime: performance.now(),

      lastUiUpdate: 0,

      lastLogMin: -1

    };


    // Compute instantaneous simulation snapshot at minute `t` (0..240)

    function computeTelemetrySnapshot(t) {

      const currentPhase = PHASES.find(p => t >= p.start && t <= p.end) || PHASES[PHASES.length - 1];


      // Evaluate positions

      const pr1 = evalPath(t, TRAJECTORIES.pr1);

      const ltv1 = evalPath(t, TRAJECTORIES.ltv1);

      const ltv2 = evalPath(t, TRAJECTORIES.ltv2);

      const ev1 = evalPath(t, TRAJECTORIES.ev1);

      const ev2 = evalPath(t, TRAJECTORIES.ev2);

      const ev3 = evalPath(t, TRAJECTORIES.ev3);

      const ev4 = evalPath(t, TRAJECTORIES.ev4);


      // Dynamic Subsystem States

      // 1) Umbilical cable deployment progress (00:38 to 00:52)

      const umbilicalProgress = clamp((t - 38) / (52 - 38), 0, 1);


      // 2) SAF-East dust mitigation cleaning progress (01:15 to 02:15 -> 75 to 135)

      const safCleanProgress = clamp((t - 75) / (135 - 75), 0, 1);

      const safPowerKw = lerp(31.2, 48.6, safCleanProgress);


      // 3) PR-1 docked to PM-2 charging umbilical (from T+02:45 = 165 onward)

      const pr1Docked = t >= 165;


      // 4) Comm Relay state (01:15 to 02:45 -> 75 to 165 uses PR-1 Mast Relay)

      const relayMode = (t >= 75 && t < 165) ? 'PR-1 MAST RELAY' : 'HABITAT DIRECT LOS';


      // 5) Habitat Airlock pressurization state

      const airlockState = t < 8 ? 'DEPRESSURIZING' : (t >= 225 ? 'REPRESSURIZING' : 'VACUUM / OPEN');


      // 6) Vehicle Telemetry

      // PR-1 battery drains on drive south (30-75) and north (135-165), charges after 165

      let pr1Batt = 98;

      if (t < 30) pr1Batt = 98;

      else if (t < 75) pr1Batt = lerp(98, 76, (t - 30) / 45);

      else if (t < 135) pr1Batt = lerp(76, 72, (t - 75) / 60); // Drilling power draw

      else if (t < 165) pr1Batt = lerp(72, 54, (t - 135) / 30);

      else pr1Batt = lerp(54, 89, (t - 165) / 75);


      // LTV-1 battery drains on south/north traverse, charges after 185

      let ltv1Batt = 96;

      if (t < 30) ltv1Batt = 96;

      else if (t < 75) ltv1Batt = lerp(96, 68, (t - 30) / 45);

      else if (t < 135) ltv1Batt = lerp(68, 66, (t - 75) / 60);

      else if (t < 185) ltv1Batt = lerp(66, 42, (t - 135) / 50);

      else ltv1Batt = lerp(42, 74, (t - 185) / 55);


      // LTV-2 battery stays at 100% until 180, drains during 180-210 loop, charges after 210

      let ltv2Batt = 100;

      if (t < 180) ltv2Batt = 100;

      else if (t < 210) ltv2Batt = lerp(100, 79, (t - 180) / 30);

      else ltv2Batt = lerp(79, 92, (t - 210) / 30);


      // 7) Astronaut PLSS Telemetry (O2 depletes smoothly from 100% down to ~37-39%)

      const calcCrewStats = (id, name, role, team, pos, baseO2Drain, hrOffset, isDriving) => {

        const insideHab = t < 6 || t >= 226;

        const o2 = clamp(100 - (t / 240) * baseO2Drain, 35, 100);

        const batt = clamp(100 - (t / 240) * (baseO2Drain - 4.5), 38, 100);

        const distHab = Math.round(dist2D(pos, INFRASTRUCTURE.habitat));

        // Subtle realistic metabolic oscillation

        const activityBoost = isDriving ? 8 : (t >= 75 && t <= 135 ? 24 : 14);

        const hr = insideHab

          ? Math.round(74 + Math.sin(t * 0.5 + hrOffset) * 3)

          : Math.round(88 + activityBoost + Math.sin(t * 0.8 + hrOffset) * 6);


        return {

          id,

          name,

          role,

          team,

          pos,

          insideHab,

          o2: o2.toFixed(1),

          batt: batt.toFixed(1),

          hr,

          distHab,

          task: team === 'Alpha' ? currentPhase.alphaTask : currentPhase.betaTask

        };

      };


      const crew = [

        calcCrewStats('ev1', 'EV-1 (CDR)', 'Team Alpha Lead', 'Alpha', ev1, 61.5, 0.0, t >= 180 && t <= 210),

        calcCrewStats('ev2', 'EV-2 (FE-1)', 'Power & Comms Spec', 'Alpha', ev2, 60.2, 1.3, t >= 180 && t <= 210),

        calcCrewStats('ev3', 'EV-3 (PLT)', 'Team Beta Lead', 'Beta', ev3, 62.8, 2.5, (t >= 30 && t <= 75) || (t >= 135 && t <= 165)),

        calcCrewStats('ev4', 'EV-4 (MS-1)', 'Geology & Sampling', 'Beta', ev4, 61.9, 3.7, (t >= 30 && t <= 75) || (t >= 135 && t <= 165))

      ];


      const vehicles = [

        {

          id: 'pr1',

          name: 'PR-1 (Pressurized Rover)',

          pos: pr1,

          batt: pr1Batt.toFixed(0),

          status: pr1Docked ? 'DOCKED / CHARGING' : (pr1.speed > 0.2 ? 'CONVOY TRANSIT' : (t >= 75 && t <= 135 ? 'RIDGE RELAY / RACK' : 'STANDBY')),

          accent: 'emerald'

        },

        {

          id: 'ltv1',

          name: 'LTV-1 (Unpressurized)',

          pos: ltv1,

          batt: ltv1Batt.toFixed(0),

          status: t >= 185 ? 'BAY CHARGING' : (ltv1.speed > 0.2 ? 'CONVOY TRANSIT' : (t >= 75 && t <= 135 ? 'RIDGE PARKED' : 'PRE-DRIVE')),

          accent: 'sky'

        },

        {

          id: 'ltv2',

          name: 'LTV-2 (Unpressurized)',

          pos: ltv2,

          batt: ltv2Batt.toFixed(0),

          status: (t >= 180 && t <= 210) ? 'PERIMETER LOOP' : (t > 210 ? 'BAY CHARGING' : 'BASE STANDBY'),

          accent: 'amber'

        }

      ];


      return {

        t,

        currentPhase,

        crew,

        vehicles,

        umbilicalProgress,

        safCleanProgress,

        safPowerKw: safPowerKw.toFixed(1),

        pr1Docked,

        relayMode,

        airlockState

      };

    }


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

    // 5. HTML5 CANVAS RENDERING ENGINE

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

    const canvas = document.getElementById('lunarCanvas');

    const ctx = canvas.getContext('2d');

    const container = document.getElementById('canvasContainer');


    function resizeCanvas() {

      const rect = container.getBoundingClientRect();

      const dpr = window.devicePixelRatio || 1;

      canvas.width = rect.width * dpr;

      canvas.height = rect.height * dpr;

      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    }

    window.addEventListener('resize', resizeCanvas);

    resizeCanvas();


    // Coordinate conversions

    function worldToScreen(wx, wy) {

      const rect = container.getBoundingClientRect();

      return {

        x: (wx - state.cam.x) * state.cam.zoom + rect.width / 2,

        y: (wy - state.cam.y) * state.cam.zoom + rect.height / 2

      };

    }


    function screenToWorld(sx, sy) {

      const rect = container.getBoundingClientRect();

      return {

        x: (sx - rect.width / 2) / state.cam.zoom + state.cam.x,

        y: (sy - rect.height / 2) / state.cam.zoom + state.cam.y

      };

    }


    // Helper to draw trajectory polylines

    function drawTrajectoryPath(keyframes, strokeStyle, dash = [4, 4]) {

      ctx.save();

      ctx.beginPath();

      ctx.strokeStyle = strokeStyle;

      ctx.lineWidth = 1.5;

      ctx.setLineDash(dash);

      keyframes.forEach((kf, idx) => {

        if (idx === 0) ctx.moveTo(kf.x, kf.y);

        else ctx.lineTo(kf.x, kf.y);

      });

      ctx.stroke();

      ctx.restore();

    }


    // Main Render Loop

    function renderScene(snap) {

      const rect = container.getBoundingClientRect();

      const width = rect.width;

      const height = rect.height;


      // Update camera follow if active

      if (state.followSelected) {

        const target = getEntityWorldPos(state.selectedEntityId, snap);

        if (target) {

          state.cam.x = lerp(state.cam.x, target.x, 0.12);

          state.cam.y = lerp(state.cam.y, target.y, 0.12);

        }

      }


      // 1. Clear Regolith Background

      ctx.fillStyle = '#090d14';

      ctx.fillRect(0, 0, width, height);


      ctx.save();

      // Apply World Camera Transform

      ctx.translate(width / 2, height / 2);

      ctx.scale(state.cam.zoom, state.cam.zoom);

      ctx.translate(-state.cam.x, -state.cam.y);


      // 2. Adaptive Coordinate Grid (100m major, 25m minor when zoomed in)

      const topLeft = screenToWorld(0, 0);

      const botRight = screenToWorld(width, height);

      const gridStep = state.cam.zoom > 1.2 ? 25 : 100;

      const startX = Math.floor(topLeft.x / gridStep) * gridStep;

      const endX = Math.ceil(botRight.x / gridStep) * gridStep;

      const startY = Math.floor(topLeft.y / gridStep) * gridStep;

      const endY = Math.ceil(botRight.y / gridStep) * gridStep;


      ctx.lineWidth = 1 / state.cam.zoom;

      for (let gx = startX; gx <= endX; gx += gridStep) {

        ctx.strokeStyle = gx % 100 === 0 ? 'rgba(56, 189, 248, 0.09)' : 'rgba(148, 163, 184, 0.04)';

        ctx.beginPath();

        ctx.moveTo(gx, startY);

        ctx.lineTo(gx, endY);

        ctx.stroke();

      }

      for (let gy = startY; gy <= endY; gy += gridStep) {

        ctx.strokeStyle = gy % 100 === 0 ? 'rgba(56, 189, 248, 0.09)' : 'rgba(148, 163, 184, 0.04)';

        ctx.beginPath();

        ctx.moveTo(startX, gy);

        ctx.lineTo(endX, gy);

        ctx.stroke();

      }


      // 3. Lunar Terrain Features: Craters & South Ridge Contour

      CRATERS.forEach(c => {

        const grad = ctx.createRadialGradient(c.x - c.r * 0.2, c.y - c.r * 0.2, c.r * 0.1, c.x, c.y, c.r);

        grad.addColorStop(0, `rgba(4, 6, 10, ${c.depth + 0.2})`);

        grad.addColorStop(0.82, `rgba(18, 25, 38, ${c.depth})`);

        grad.addColorStop(0.95, 'rgba(148, 163, 184, 0.12)');

        grad.addColorStop(1, 'rgba(9, 13, 20, 0)');

        ctx.fillStyle = grad;

        ctx.beginPath();

        ctx.arc(c.x, c.y, c.r, 0, Math.PI * 2);

        ctx.fill();

      });


      // South Ridge Geological Escarpment (1.2 km South)

      const sr = INFRASTRUCTURE.southRidge;

      ctx.save();

      ctx.strokeStyle = 'rgba(245, 158, 11, 0.28)';

      ctx.lineWidth = 2;

      ctx.setLineDash([8, 6]);

      ctx.beginPath();

      ctx.arc(sr.x, sr.y, sr.radius, 0, Math.PI * 2);

      ctx.stroke();


      // Escarpment ridge line

      ctx.setLineDash([]);

      ctx.strokeStyle = 'rgba(148, 163, 184, 0.25)';

      ctx.lineWidth = 3;

      ctx.beginPath();

      ctx.moveTo(-180, 1235);

      ctx.quadraticCurveTo(-50, 1265, 20, 1255);

      ctx.quadraticCurveTo(110, 1245, 210, 1275);

      ctx.stroke();


      ctx.fillStyle = 'rgba(245, 158, 11, 0.85)';

      ctx.font = '600 12px "JetBrains Mono", monospace';

      ctx.textAlign = 'center';

      ctx.fillText('SOUTH RIDGE WAYPOINT (1.2 KM)', sr.x, sr.y + sr.radius + 18);

      ctx.restore();


      // 4. RF Communications Line-of-Sight Rings & Active Relay Beam

      if (state.showComms) {

        const hab = INFRASTRUCTURE.habitat;

        const pr1Pos = snap.vehicles[0].pos;

        const isRelayActive = snap.relayMode === 'PR-1 MAST RELAY';


        // Habitat Direct LOS Ring (850m radius)

        ctx.save();

        ctx.strokeStyle = isRelayActive ? 'rgba(56, 189, 248, 0.12)' : 'rgba(56, 189, 248, 0.28)';

        ctx.lineWidth = 1.5;

        ctx.setLineDash([10, 8]);

        ctx.beginPath();

        ctx.arc(hab.mast.x, hab.mast.y, 850, 0, Math.PI * 2);

        ctx.stroke();


        // PR-1 Mast Relay Ring (450m local range around PR-1)

        ctx.strokeStyle = isRelayActive ? 'rgba(16, 185, 129, 0.38)' : 'rgba(16, 185, 129, 0.12)';

        ctx.beginPath();

        ctx.arc(pr1Pos.x, pr1Pos.y, 450, 0, Math.PI * 2);

        ctx.stroke();


        // Active RF Link Line between Habitat Mast and PR-1 when beyond direct LOS

        if (isRelayActive) {

          ctx.setLineDash([6, 6]);

          ctx.strokeStyle = 'rgba(16, 185, 129, 0.55)';

          ctx.lineWidth = 2;

          ctx.beginPath();

          ctx.moveTo(hab.mast.x, hab.mast.y);

          ctx.lineTo(pr1Pos.x, pr1Pos.y);

          ctx.stroke();

        }

        ctx.restore();

      }


      // 5. Planned & Traversed Vehicle/Crew Tracks

      if (state.showTracks) {

        drawTrajectoryPath(TRAJECTORIES.pr1, 'rgba(16, 185, 129, 0.22)', [6, 6]);

        drawTrajectoryPath(TRAJECTORIES.ltv1, 'rgba(56, 189, 248, 0.18)', [4, 6]);

        drawTrajectoryPath(TRAJECTORIES.ltv2, 'rgba(245, 158, 11, 0.22)', [4, 4]);

      }


      // 6. Power Umbilical Cables & SAF-East Solar Array Field

      const pm1 = INFRASTRUCTURE.pm1;

      const pm2 = INFRASTRUCTURE.pm2;

      const saf = INFRASTRUCTURE.safEast;


      // Permanent Bus Link PM-1 <-> PM-2

      ctx.strokeStyle = '#334155';

      ctx.lineWidth = 3;

      ctx.beginPath();

      ctx.moveTo(pm1.x, pm1.y);

      ctx.lineTo(pm2.x, pm2.y);

      ctx.stroke();


      // Animated Power Umbilical from PM-1 to SAF-East Junction Box (deployed 00:38 - 00:52)

      if (snap.umbilicalProgress > 0) {

        const endX = lerp(pm1.x + 14, saf.junctionBox.x, snap.umbilicalProgress);

        const endY = lerp(pm1.y + 4, saf.junctionBox.y, snap.umbilicalProgress);

        ctx.save();

        ctx.strokeStyle = snap.umbilicalProgress >= 1 ? '#38bdf8' : '#f59e0b';

        ctx.lineWidth = 3;

        ctx.beginPath();

        ctx.moveTo(pm1.x + 14, pm1.y + 4);

        ctx.lineTo(endX, endY);

        ctx.stroke();


        // Junction box node

        ctx.fillStyle = snap.umbilicalProgress >= 1 ? '#10b981' : '#f59e0b';

        ctx.fillRect(saf.junctionBox.x - 4, saf.junctionBox.y - 4, 8, 8);

        ctx.restore();

      }


      // Render Individual Solar Panels in SAF-East (12 panels, brightening as dust is brushed!)

      const totalPanels = saf.rows * saf.cols;

      let panelIdx = 0;

      for (let r = 0; r < saf.rows; r++) {

        for (let c = 0; c < saf.cols; c++) {

          const px = saf.x + c * saf.gapX;

          const py = saf.y + r * saf.gapY;

          const panelThreshold = panelIdx / totalPanels;

          const isClean = snap.safCleanProgress > panelThreshold;


          // Panel frame

          ctx.fillStyle = isClean ? '#0284c7' : '#334155';

          ctx.strokeStyle = isClean ? '#38bdf8' : '#64748b';

          ctx.lineWidth = 1.5;

          ctx.fillRect(px - saf.panelW / 2, py - saf.panelH / 2, saf.panelW, saf.panelH);

          ctx.strokeRect(px - saf.panelW / 2, py - saf.panelH / 2, saf.panelW, saf.panelH);


          // Photovoltaic cell grid lines

          ctx.strokeStyle = isClean ? 'rgba(186, 230, 253, 0.45)' : 'rgba(148, 163, 184, 0.2)';

          ctx.lineWidth = 0.8;

          ctx.beginPath();

          ctx.moveTo(px, py - saf.panelH / 2);

          ctx.lineTo(px, py + saf.panelH / 2);

          ctx.moveTo(px - saf.panelW / 2, py);

          ctx.lineTo(px + saf.panelW / 2, py);

          ctx.stroke();


          panelIdx++;

        }

      }

      ctx.fillStyle = '#94a3b8';

      ctx.font = '600 10px "JetBrains Mono", monospace';

      ctx.textAlign = 'center';

      ctx.fillText(`SAF-EAST (${Math.round(snap.safCleanProgress * 100)}% CLEAN)`, saf.x + 45, saf.y - 18);


      // 7. Power Modules PM-1 & PM-2

      [pm1, pm2].forEach(pm => {

        ctx.save();

        ctx.fillStyle = '#1e293b';

        ctx.strokeStyle = pm.color;

        ctx.lineWidth = 2;

        ctx.fillRect(pm.x - pm.w / 2, pm.y - pm.h / 2, pm.w, pm.h);

        ctx.strokeRect(pm.x - pm.w / 2, pm.y - pm.h / 2, pm.w, pm.h);


        // Radiator fins

        ctx.fillStyle = pm.color;

        ctx.fillRect(pm.x - pm.w / 2 + 3, pm.y - pm.h / 2 - 4, pm.w - 6, 3);

        ctx.fillRect(pm.x - pm.w / 2 + 3, pm.y + pm.h / 2 + 1, pm.w - 6, 3);


        ctx.fillStyle = '#e2e8f0';

        ctx.font = '600 9px "JetBrains Mono", monospace';

        ctx.textAlign = 'center';

        ctx.fillText(pm.id.toUpperCase(), pm.x, pm.y + 3);

        ctx.restore();

      });


      // PR-1 Charging Umbilical from PM-2 when docked (T+02:45+)

      if (snap.pr1Docked) {

        const pr1Pos = snap.vehicles[0].pos;

        ctx.save();

        ctx.strokeStyle = '#10b981';

        ctx.lineWidth = 2.5;

        ctx.beginPath();

        ctx.moveTo(pm2.x - 10, pm2.y + 9);

        ctx.lineTo(pr1Pos.x + 12, pr1Pos.y);

        ctx.stroke();

        ctx.restore();

      }


      // 8. Vehicle Parking / Charging Bays at Base Camp

      Object.entries(INFRASTRUCTURE.bays).forEach(([key, bay]) => {

        ctx.save();

        ctx.strokeStyle = 'rgba(148, 163, 184, 0.3)';

        ctx.lineWidth = 1;

        ctx.setLineDash([3, 3]);

        ctx.strokeRect(bay.x - 14, bay.y - 18, 28, 36);

        ctx.restore();

      });


      // 9. Lunar Habitat & Pressurized Airlock Bay

      const hab = INFRASTRUCTURE.habitat;

      ctx.save();

      // Main Habitat Pressure Hull

      ctx.fillStyle = '#1e293b';

      ctx.strokeStyle = '#e2e8f0';

      ctx.lineWidth = 2.5;

      ctx.beginPath();

      ctx.arc(hab.x, hab.y, hab.radius, 0, Math.PI * 2);

      ctx.fill();

      ctx.stroke();


      // Inner structural ribs

      ctx.strokeStyle = 'rgba(148, 163, 184, 0.25)';

      ctx.lineWidth = 1;

      ctx.beginPath();

      ctx.arc(hab.x, hab.y, hab.radius * 0.65, 0, Math.PI * 2);

      ctx.stroke();


      // Pressurized Airlock Vestibule (South side)

      ctx.fillStyle = snap.airlockState === 'VACUUM / OPEN' ? '#0f172a' : '#065f46';

      ctx.strokeStyle = snap.airlockState === 'VACUUM / OPEN' ? '#f59e0b' : '#10b981';

      ctx.lineWidth = 2;

      ctx.fillRect(-10, hab.radius - 4, 20, 14);

      ctx.strokeRect(-10, hab.radius - 4, 20, 14);


      // Exterior Comms Mast (North-West side)

      ctx.fillStyle = snap.t >= 168 ? '#10b981' : '#38bdf8';

      ctx.beginPath();

      ctx.arc(hab.mast.x, hab.mast.y, 4.5, 0, Math.PI * 2);

      ctx.fill();


      // Habitat Label

      ctx.fillStyle = '#f8fafc';

      ctx.font = '700 10px "JetBrains Mono", monospace';

      ctx.textAlign = 'center';

      ctx.fillText('HABITAT', hab.x, hab.y + 3);

      ctx.restore();


      // 10. Render Vehicles (PR-1, LTV-1, LTV-2)

      snap.vehicles.forEach(v => {

        ctx.save();

        ctx.translate(v.pos.x, v.pos.y);

        ctx.rotate(v.pos.heading);


        const isPR = v.id === 'pr1';

        const len = isPR ? 24 : 16;

        const wid = isPR ? 14 : 11;


        // Selection halo

        if (state.selectedEntityId === v.id) {

          ctx.strokeStyle = '#38bdf8';

          ctx.lineWidth = 2;

          ctx.beginPath();

          ctx.arc(0, 0, len * 0.9, 0, Math.PI * 2);

          ctx.stroke();

        }


        // Wheels

        ctx.fillStyle = '#0f172a';

        ctx.fillRect(-len * 0.38, -wid / 2 - 2.5, 5, 2.5);

        ctx.fillRect(len * 0.22, -wid / 2 - 2.5, 5, 2.5);

        ctx.fillRect(-len * 0.38, wid / 2, 5, 2.5);

        ctx.fillRect(len * 0.22, wid / 2, 5, 2.5);


        // Chassis

        ctx.fillStyle = isPR ? '#10b981' : (v.id === 'ltv1' ? '#38bdf8' : '#f59e0b');

        ctx.strokeStyle = '#0f172a';

        ctx.lineWidth = 1.5;

        ctx.beginPath();

        ctx.roundRect(-len / 2, -wid / 2, len, wid, 3);

        ctx.fill();

        ctx.stroke();


        // Forward windshield / direction indicator

        ctx.fillStyle = '#0f172a';

        ctx.fillRect(len / 2 - 5, -wid / 2 + 2, 3, wid - 4);


        ctx.restore();


        // Vehicle callsign tag

        ctx.fillStyle = '#e2e8f0';

        ctx.font = '600 9px "JetBrains Mono", monospace';

        ctx.textAlign = 'center';

        ctx.fillText(v.id.toUpperCase(), v.pos.x, v.pos.y - (v.id === 'pr1' ? 14 : 11));

      });


      // 11. Render Astronauts (EV-1, EV-2, EV-3, EV-4)

      snap.crew.forEach(c => {

        if (c.insideHab) return; // Inside pressurized habitat airlock


        const color = c.team === 'Alpha' ? '#38bdf8' : '#f59e0b';

        ctx.save();

        ctx.translate(c.pos.x, c.pos.y);


        // Selection ring

        if (state.selectedEntityId === c.id) {

          ctx.strokeStyle = '#ffffff';

          ctx.lineWidth = 1.5;

          ctx.beginPath();

          ctx.arc(0, 0, 10, 0, Math.PI * 2);

          ctx.stroke();

        }


        // PLSS Backpack

        ctx.fillStyle = '#cbd5e1';

        ctx.fillRect(-4.5, -3.5, 3, 7);


        // EVA Suit Helmet & Torso

        ctx.fillStyle = color;

        ctx.strokeStyle = '#090d14';

        ctx.lineWidth = 1.5;

        ctx.beginPath();

        ctx.arc(0, 0, 5, 0, Math.PI * 2);

        ctx.fill();

        ctx.stroke();


        // Gold Visor

        ctx.fillStyle = '#fef08a';

        ctx.beginPath();

        ctx.arc(1.8, 0, 2.2, -Math.PI / 2, Math.PI / 2);

        ctx.fill();


        // Astronaut Callsign

        ctx.fillStyle = color;

        ctx.font = '700 9px "JetBrains Mono", monospace';

        ctx.textAlign = 'left';

        ctx.fillText(c.id.toUpperCase(), 7, 3);


        ctx.restore();

      });


      // Selection ring for Static Infrastructure

      if (['habitat', 'pm1', 'pm2', 'safEast', 'southRidge'].includes(state.selectedEntityId)) {

        const pos = getEntityWorldPos(state.selectedEntityId, snap);

        if (pos) {

          ctx.save();

          ctx.strokeStyle = '#38bdf8';

          ctx.lineWidth = 2;

          ctx.setLineDash([4, 4]);

          ctx.beginPath();

          ctx.arc(pos.x, pos.y, 38, 0, Math.PI * 2);

          ctx.stroke();

          ctx.restore();

        }

      }


      ctx.restore();


      // Update Scale Bar HUD

      updateScaleBarHud();

    }


    function getEntityWorldPos(id, snap) {

      if (id === 'habitat') return { x: 0, y: 0 };

      if (id === 'pm1') return { x: INFRASTRUCTURE.pm1.x, y: INFRASTRUCTURE.pm1.y };

      if (id === 'pm2') return { x: INFRASTRUCTURE.pm2.x, y: INFRASTRUCTURE.pm2.y };

      if (id === 'safEast') return { x: INFRASTRUCTURE.safEast.x + 45, y: INFRASTRUCTURE.safEast.y + 26 };

      if (id === 'southRidge') return { x: INFRASTRUCTURE.southRidge.x, y: INFRASTRUCTURE.southRidge.y };

      const v = snap.vehicles.find(item => item.id === id);

      if (v) return v.pos;

      const c = snap.crew.find(item => item.id === id);

      if (c) return c.pos;

      return null;

    }


    function updateScaleBarHud() {

      // Target ~60px visual bar

      const targetPx = 60;

      const rawMeters = targetPx / state.cam.zoom;

      const niceSteps = [10, 25, 50, 100, 200, 500, 1000];

      const chosenMeters = niceSteps.reduce((prev, curr) =>

        Math.abs(curr - rawMeters) < Math.abs(prev - rawMeters) ? curr : prev

      );

      const barPx = Math.round(chosenMeters * state.cam.zoom);

      document.getElementById('scaleBarVisual').style.width = `${barPx}px`;

      document.getElementById('scaleBarLabel').textContent = chosenMeters >= 1000 ? `${chosenMeters / 1000}km` : `${chosenMeters}m`;

      document.getElementById('zoomLevelLabel').textContent = `${state.cam.zoom.toFixed(2)}x`;

    }


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

    // 6. DOM TELEMETRY PANELS & MISSION LOG UPDATES

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

    function formatMetClock(minutesFloat) {

      const totalSec = Math.floor(minutesFloat * 60);

      const hrs = Math.floor(totalSec / 3600);

      const mins = Math.floor((totalSec % 3600) / 60);

      const secs = totalSec % 60;

      const pad = n => String(n).padStart(2, '0');

      return `T+${pad(hrs)}:${pad(mins)}:${pad(secs)}`;

    }


    function renderTelemetryPanels(snap) {

      // 1. Header Clock & Phase

      document.getElementById('metClockDisplay').textContent = formatMetClock(snap.t);

      document.getElementById('headerPhaseLabel').textContent = snap.currentPhase.shortName;

      document.getElementById('timelineSlider').value = snap.t;


      // 2. Crew Cards (Team Alpha & Team Beta)

      const renderCrewCard = (c) => {

        const isSelected = state.selectedEntityId === c.id;

        const borderClass = isSelected ? 'border-sky-400 bg-sky-950/20' : 'border-mcc-border bg-mcc-card hover:border-slate-600';

        const teamColor = c.team === 'Alpha' ? 'text-sky-400' : 'text-amber-400';

        const o2Color = parseFloat(c.o2) < 45 ? 'bg-amber-400' : 'bg-emerald-400';


        return `

          <div onclick="selectEntity('${c.id}')" class="cursor-pointer rounded-xl p-2.5 border ${borderClass} transition-all">

            <div class="flex items-center justify-between mb-1">

              <div class="flex items-center gap-1.5">

                <span class="font-mono font-bold text-xs ${teamColor}">${c.name}</span>

                <span class="text-[10px] font-mono text-slate-400">• ${c.insideHab ? 'AIRLOCK' : c.distHab + 'm'}</span>

              </div>

              <span class="text-[10px] font-mono text-rose-400 font-semibold">♥ ${c.hr} BPM</span>

            </div>

            <div class="text-[10px] text-slate-300 truncate mb-2" title="${c.task}">${c.task}</div>

            <div class="grid grid-cols-2 gap-2 text-[10px] font-mono">

              <div>

                <div class="flex justify-between text-slate-400 mb-0.5">

                  <span>PLSS O2</span>

                  <span class="text-slate-200 font-semibold">${c.o2}%</span>

                </div>

                <div class="w-full h-1.5 bg-mcc-bg rounded-full overflow-hidden">

                  <div class="h-full ${o2Color} transition-all duration-150" style="width: ${c.o2}%"></div>

                </div>

              </div>

              <div>

                <div class="flex justify-between text-slate-400 mb-0.5">

                  <span>SUIT BATT</span>

                  <span class="text-slate-200 font-semibold">${c.batt}%</span>

                </div>

                <div class="w-full h-1.5 bg-mcc-bg rounded-full overflow-hidden">

                  <div class="h-full bg-sky-400 transition-all duration-150" style="width: ${c.batt}%"></div>

                </div>

              </div>

            </div>

          </div>

        `;

      };


      document.getElementById('teamAlphaCards').innerHTML = snap.crew

        .filter(c => c.team === 'Alpha')

        .map(renderCrewCard)

        .join('');


      document.getElementById('teamBetaCards').innerHTML = snap.crew

        .filter(c => c.team === 'Beta')

        .map(renderCrewCard)

        .join('');


      // 3. Vehicle Cards

      document.getElementById('vehicleCards').innerHTML = snap.vehicles.map(v => {

        const isSelected = state.selectedEntityId === v.id;

        const borderClass = isSelected ? 'border-sky-400 bg-sky-950/20' : 'border-mcc-border bg-mcc-card hover:border-slate-600';

        const badgeColor = v.status.includes('CHARGING') || v.status.includes('DOCKED')

          ? 'text-emerald-400 bg-emerald-500/10 border-emerald-500/30'

          : (v.pos.speed > 0.2 ? 'text-sky-400 bg-sky-500/10 border-sky-500/30' : 'text-slate-300 bg-slate-800 border-slate-700');


        return `

          <div onclick="selectEntity('${v.id}')" class="cursor-pointer rounded-xl p-2.5 border ${borderClass} transition-all">

            <div class="flex items-center justify-between mb-1">

              <span class="font-mono font-bold text-xs text-white">${v.name}</span>

              <span class="px-1.5 py-0.5 rounded text-[9px] font-mono font-semibold border ${badgeColor}">${v.status}</span>

            </div>

            <div class="flex items-center justify-between text-[10px] font-mono text-slate-400">

              <span>BATT: <strong class="text-slate-200">${v.batt}%</strong></span>

              <span>SPD: <strong class="text-slate-200">${v.pos.speed.toFixed(1)} km/h</strong></span>

              <span>POS: <strong class="text-slate-200">${Math.round(v.pos.x)},${Math.round(v.pos.y)}m</strong></span>

            </div>

          </div>

        `;

      }).join('');


      // 4. Power & Comms Telemetry

      const relayBadge = document.getElementById('commRelayBadge');

      relayBadge.textContent = snap.relayMode;

      relayBadge.className = snap.relayMode === 'PR-1 MAST RELAY'

        ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-500/15 text-emerald-400 border border-emerald-500/30'

        : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-sky-500/15 text-sky-400 border border-sky-500/30';


      document.getElementById('powerGridCard').innerHTML = `

        <div class="flex justify-between items-center">

          <span class="text-slate-400">SAF-East Output:</span>

          <span class="text-emerald-400 font-bold">${snap.safPowerKw} kW <span class="text-[10px] text-slate-400">(${Math.round(snap.safCleanProgress * 100)}% clean)</span></span>

        </div>

        <div class="flex justify-between items-center">

          <span class="text-slate-400">PM-1 / SAF Umbilical:</span>

          <span class="${snap.umbilicalProgress >= 1 ? 'text-sky-400' : 'text-amber-400'} font-semibold">

            ${snap.umbilicalProgress >= 1 ? 'LOCKED / ACTIVE' : (snap.umbilicalProgress > 0 ? 'DEPLOYING ' + Math.round(snap.umbilicalProgress * 100) + '%' : 'STOWED')}

          </span>

        </div>

        <div class="flex justify-between items-center">

          <span class="text-slate-400">PM-2 Fast Charger:</span>

          <span class="${snap.pr1Docked ? 'text-emerald-400' : 'text-slate-300'} font-semibold">

            ${snap.pr1Docked ? 'PR-1 DOCKED (42 kW)' : 'BUS NOMINAL (STANDBY)'}

          </span>

        </div>

        <div class="flex justify-between items-center">

          <span class="text-slate-400">Habitat Airlock:</span>

          <span class="${snap.airlockState === 'VACUUM / OPEN' ? 'text-amber-400' : 'text-emerald-400'} font-semibold">${snap.airlockState}</span>

        </div>

      `;


      // 5. Entity Inspector HUD

      updateEntityInspector(snap);


      // 6. Event & State Transition Log

      updateEventLog(snap.t);

    }


    function updateEntityInspector(snap) {

      const id = state.selectedEntityId;

      const nameEl = document.getElementById('inspName');

      const detailsEl = document.getElementById('inspDetails');

      const dotEl = document.getElementById('inspDot');


      const crewMember = snap.crew.find(c => c.id === id);

      const vehicle = snap.vehicles.find(v => v.id === id);


      if (crewMember) {

        dotEl.className = `w-2 h-2 rounded-full ${crewMember.team === 'Alpha' ? 'bg-sky-400' : 'bg-amber-400'}`;

        nameEl.textContent = crewMember.name;

        detailsEl.innerHTML = `

          <div>Role: <span class="text-white">${crewMember.role}</span></div>

          <div>Range to Hab: <span class="text-white">${crewMember.distHab} m</span></div>

          <div>PLSS O2 / Batt: <span class="text-emerald-400">${crewMember.o2}%</span> / <span class="text-sky-400">${crewMember.batt}%</span></div>

          <div class="text-slate-400 pt-0.5 leading-tight">${crewMember.task}</div>

        `;

      } else if (vehicle) {

        dotEl.className = 'w-2 h-2 rounded-full bg-emerald-400';

        nameEl.textContent = vehicle.name.toUpperCase();

        detailsEl.innerHTML = `

          <div>State: <span class="text-emerald-400">${vehicle.status}</span></div>

          <div>Battery SOC: <span class="text-white">${vehicle.batt}%</span></div>

          <div>Ground Speed: <span class="text-white">${vehicle.pos.speed.toFixed(1)} km/h</span></div>

          <div>Coords: <span class="text-white">${Math.round(vehicle.pos.x)}m E, ${Math.round(vehicle.pos.y)}m S</span></div>

        `;

      } else if (id === 'safEast') {

        dotEl.className = 'w-2 h-2 rounded-full bg-sky-400';

        nameEl.textContent = 'SOLAR ARRAY FIELD (SAF-EAST)';

        detailsEl.innerHTML = `

          <div>Array Output: <span class="text-emerald-400">${snap.safPowerKw} kW</span></div>

          <div>Dust Mitigation: <span class="text-white">${Math.round(snap.safCleanProgress * 100)}% Brushed</span></div>

          <div>Umbilical Link: <span class="text-white">${snap.umbilicalProgress >= 1 ? 'Connected to PM-1' : 'Pending'}</span></div>

        `;

      } else if (id === 'southRidge') {

        dotEl.className = 'w-2 h-2 rounded-full bg-amber-400';

        nameEl.textContent = 'SOUTH RIDGE WAYPOINT';

        detailsEl.innerHTML = `

          <div>Distance: <span class="text-white">1,200 m South of Habitat</span></div>

          <div>Objective: <span class="text-white">Regolith Core Drilling</span></div>

          <div>RF Link: <span class="text-emerald-400">${snap.relayMode}</span></div>

        `;

      } else {

        dotEl.className = 'w-2 h-2 rounded-full bg-slate-200';

        nameEl.textContent = 'LUNAR HABITAT & AIRLOCK';

        detailsEl.innerHTML = `

          <div>Airlock State: <span class="text-amber-400">${snap.airlockState}</span></div>

          <div>Comm Relay: <span class="text-sky-400">${snap.relayMode}</span></div>

          <div>Mast Transceiver: <span class="text-white">${snap.t >= 168 ? 'Upgraded Gen-2' : 'Nominal Gen-1'}</span></div>

        `;

      }

    }


    function updateEventLog(t) {

      const currentFloor = Math.floor(t);

      if (currentFloor === state.lastLogMin) return;

      state.lastLogMin = currentFloor;


      const visibleEvents = MISSION_TRIGGERS.filter(ev => ev.min <= t).reverse();

      const logContainer = document.getElementById('missionEventLog');

      logContainer.innerHTML = visibleEvents.map(ev => {

        const badgeStyle = ev.type === 'TRIGGER'

          ? 'text-amber-400 bg-amber-500/10 border-amber-500/30'

          : (ev.type === 'SUCCESS'

            ? 'text-emerald-400 bg-emerald-500/10 border-emerald-500/30'

            : 'text-sky-400 bg-sky-500/10 border-sky-500/30');


        return `

          <div class="p-2 rounded-lg bg-mcc-card/80 border border-mcc-border/80">

            <div class="flex items-center justify-between mb-1">

              <span class="px-1.5 py-0.5 rounded text-[9px] font-bold border ${badgeStyle}">${ev.tag}</span>

            </div>

            <p class="text-slate-300 leading-snug">${ev.text}</p>

          </div>

        `;

      }).join('');

    }


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

    // 7. USER INTERACTIONS (PAN, ZOOM, ENTITY PICKING, TIMELINE CONTROLS)

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

    window.selectEntity = function(id) {

      state.selectedEntityId = id;

      const snap = computeTelemetrySnapshot(state.simMinutes);

      renderTelemetryPanels(snap);

    };


    // Canvas Mouse & Touch Panning + Entity Click Inspection

    let pointerDownPos = { x: 0, y: 0 };


    canvas.addEventListener('mousedown', (e) => {

      state.cam.isDragging = true;

      state.cam.dragStartX = e.clientX;

      state.cam.dragStartY = e.clientY;

      state.cam.camStartX = state.cam.x;

      state.cam.camStartY = state.cam.y;

      pointerDownPos = { x: e.clientX, y: e.clientY };

    });


    window.addEventListener('mousemove', (e) => {

      if (!state.cam.isDragging) return;

      const dx = (e.clientX - state.cam.dragStartX) / state.cam.zoom;

      const dy = (e.clientY - state.cam.dragStartY) / state.cam.zoom;

      state.cam.x = state.cam.camStartX - dx;

      state.cam.y = state.cam.camStartY - dy;

      if (Math.hypot(e.clientX - pointerDownPos.x, e.clientY - pointerDownPos.y) > 4) {

        state.followSelected = false;

        updateFollowBtn();

      }

    });


    window.addEventListener('mouseup', (e) => {

      if (state.cam.isDragging) {

        const moved = Math.hypot(e.clientX - pointerDownPos.x, e.clientY - pointerDownPos.y);

        if (moved < 5) {

          handleCanvasClick(e.clientX, e.clientY);

        }

      }

      state.cam.isDragging = false;

    });


    // Wheel Zoom centered on cursor

    canvas.addEventListener('wheel', (e) => {

      e.preventDefault();

      const rect = canvas.getBoundingClientRect();

      const sx = e.clientX - rect.left;

      const sy = e.clientY - rect.top;

      const beforeWorld = screenToWorld(sx, sy);


      const zoomFactor = e.deltaY < 0 ? 1.15 : 0.87;

      state.cam.zoom = clamp(state.cam.zoom * zoomFactor, 0.25, 4.5);


      const afterWorld = screenToWorld(sx, sy);

      state.cam.x += beforeWorld.x - afterWorld.x;

      state.cam.y += beforeWorld.y - afterWorld.y;

    }, { passive: false });


    // Touch Support for Mobile/Tablet Pan & Tap

    canvas.addEventListener('touchstart', (e) => {

      if (e.touches.length === 1) {

        const touch = e.touches[0];

        state.cam.isDragging = true;

        state.cam.dragStartX = touch.clientX;

        state.cam.dragStartY = touch.clientY;

        state.cam.camStartX = state.cam.x;

        state.cam.camStartY = state.cam.y;

        pointerDownPos = { x: touch.clientX, y: touch.clientY };

      }

    }, { passive: true });


    canvas.addEventListener('touchmove', (e) => {

      if (!state.cam.isDragging || e.touches.length !== 1) return;

      const touch = e.touches[0];

      const dx = (touch.clientX - state.cam.dragStartX) / state.cam.zoom;

      const dy = (touch.clientY - state.cam.dragStartY) / state.cam.zoom;

      state.cam.x = state.cam.camStartX - dx;

      state.cam.y = state.cam.camStartY - dy;

    }, { passive: true });


    canvas.addEventListener('touchend', (e) => {

      if (state.cam.isDragging && e.changedTouches.length === 1) {

        const touch = e.changedTouches[0];

        if (Math.hypot(touch.clientX - pointerDownPos.x, touch.clientY - pointerDownPos.y) < 8) {

          handleCanvasClick(touch.clientX, touch.clientY);

        }

      }

      state.cam.isDragging = false;

    });


    function handleCanvasClick(clientX, clientY) {

      const rect = canvas.getBoundingClientRect();

      const worldPt = screenToWorld(clientX - rect.left, clientY - rect.top);

      const snap = computeTelemetrySnapshot(state.simMinutes);


      const candidates = [

        ...snap.crew.filter(c => !c.insideHab).map(c => ({ id: c.id, x: c.pos.x, y: c.pos.y, r: 16 })),

        ...snap.vehicles.map(v => ({ id: v.id, x: v.pos.x, y: v.pos.y, r: 22 })),

        { id: 'habitat', x: 0, y: 0, r: 35 },

        { id: 'pm1', x: INFRASTRUCTURE.pm1.x, y: INFRASTRUCTURE.pm1.y, r: 24 },

        { id: 'pm2', x: INFRASTRUCTURE.pm2.x, y: INFRASTRUCTURE.pm2.y, r: 24 },

        { id: 'safEast', x: INFRASTRUCTURE.safEast.x + 45, y: INFRASTRUCTURE.safEast.y + 26, r: 65 },

        { id: 'southRidge', x: INFRASTRUCTURE.southRidge.x, y: INFRASTRUCTURE.southRidge.y, r: 55 }

      ];


      const hitRadius = Math.max(20, 26 / state.cam.zoom);

      let closest = null;

      let minD = Infinity;


      candidates.forEach(cand => {

        const d = dist2D(worldPt, cand);

        if (d <= Math.max(cand.r, hitRadius) && d < minD) {

          minD = d;

          closest = cand;

        }

      });


      if (closest) {

        selectEntity(closest.id);

      }

    }


    // Camera Presets & Toggles

    document.getElementById('btnResetCam').addEventListener('click', () => {

      state.followSelected = false;

      updateFollowBtn();

      state.cam.x = 60;

      state.cam.y = 540;

      state.cam.zoom = 0.45;

    });


    document.getElementById('btnZoomBase').addEventListener('click', () => {

      state.followSelected = false;

      updateFollowBtn();

      state.cam.x = 110;

      state.cam.y = 10;

      state.cam.zoom = 1.65;

    });


    document.getElementById('btnZoomRidge').addEventListener('click', () => {

      state.followSelected = false;

      updateFollowBtn();

      state.cam.x = 0;

      state.cam.y = 1200;

      state.cam.zoom = 1.8;

    });


    document.getElementById('btnZoomIn').addEventListener('click', () => {

      state.cam.zoom = clamp(state.cam.zoom * 1.3, 0.25, 4.5);

    });


    document.getElementById('btnZoomOut').addEventListener('click', () => {

      state.cam.zoom = clamp(state.cam.zoom * 0.77, 0.25, 4.5);

    });


    document.getElementById('btnToggleTracks').addEventListener('click', (e) => {

      state.showTracks = !state.showTracks;

      e.target.textContent = `Tracks: ${state.showTracks ? 'ON' : 'OFF'}`;

      e.target.className = state.showTracks

        ? 'px-2.5 py-1.5 rounded-lg bg-sky-500/20 border border-sky-500/50 text-[11px] font-mono text-sky-300 shadow-lg backdrop-blur-sm transition'

        : 'px-2.5 py-1.5 rounded-lg bg-mcc-panel/90 border border-mcc-border text-[11px] font-mono text-slate-400 shadow-lg backdrop-blur-sm transition';

    });


    document.getElementById('btnToggleComms').addEventListener('click', (e) => {

      state.showComms = !state.showComms;

      e.target.textContent = `RF Rings: ${state.showComms ? 'ON' : 'OFF'}`;

      e.target.className = state.showComms

        ? 'px-2.5 py-1.5 rounded-lg bg-sky-500/20 border border-sky-500/50 text-[11px] font-mono text-sky-300 shadow-lg backdrop-blur-sm transition'

        : 'px-2.5 py-1.5 rounded-lg bg-mcc-panel/90 border border-mcc-border text-[11px] font-mono text-slate-400 shadow-lg backdrop-blur-sm transition';

    });


    function updateFollowBtn() {

      const btn = document.getElementById('btnFollowToggle');

      btn.textContent = `FOLLOW: ${state.followSelected ? 'ON' : 'OFF'}`;

      btn.className = state.followSelected

        ? 'px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/25 text-sky-300 border border-sky-400 transition'

        : 'px-2 py-0.5 rounded text-[10px] font-mono bg-mcc-card hover:bg-sky-500/20 text-slate-300 border border-mcc-border transition';

    }


    document.getElementById('btnFollowToggle').addEventListener('click', () => {

      state.followSelected = !state.followSelected;

      updateFollowBtn();

    });


    // Playback Transport Controls

    function updatePlayPauseUI() {

      document.getElementById('playPauseLabel').textContent = state.isPlaying ? 'PAUSE' : 'PLAY';

      document.getElementById('iconPlay').classList.toggle('hidden', state.isPlaying);

      document.getElementById('iconPause').classList.toggle('hidden', !state.isPlaying);

    }


    document.getElementById('btnPlayPause').addEventListener('click', () => {

      if (state.simMinutes >= 240 && !state.isPlaying) {

        state.simMinutes = 0;

        state.lastLogMin = -1;

      }

      state.isPlaying = !state.isPlaying;

      updatePlayPauseUI();

    });


    document.getElementById('btnReset').addEventListener('click', () => {

      state.simMinutes = 0;

      state.lastLogMin = -1;

      state.isPlaying = false;

      updatePlayPauseUI();

      const snap = computeTelemetrySnapshot(0);

      renderTelemetryPanels(snap);

    });


    // Playback Speed Selector

    document.querySelectorAll('.speed-btn').forEach(btn => {

      btn.addEventListener('click', () => {

        state.playbackSpeed = Number(btn.dataset.speed);

        document.querySelectorAll('.speed-btn').forEach(b => {

          b.className = 'speed-btn px-2 py-1 rounded-md text-[11px] font-mono text-slate-400 hover:text-white transition';

        });

        btn.className = 'speed-btn px-2 py-1 rounded-md text-[11px] font-mono bg-sky-500/20 text-sky-400 font-bold transition';

      });

    });


    // Timeline Scrubber & Phase/Trigger Quick Jumps

    const slider = document.getElementById('timelineSlider');

    slider.addEventListener('input', (e) => {

      state.simMinutes = parseFloat(e.target.value);

      state.lastLogMin = -1;

      const snap = computeTelemetrySnapshot(state.simMinutes);

      renderTelemetryPanels(snap);

    });


    document.querySelectorAll('[data-jump]').forEach(el => {

      el.addEventListener('click', () => {

        state.simMinutes = parseFloat(el.dataset.jump);

        state.lastLogMin = -1;

        const snap = computeTelemetrySnapshot(state.simMinutes);

        renderTelemetryPanels(snap);

      });

    });


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

    // 8. MAIN ANIMATION LOOP

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

    function animate(now) {

      const dtSec = Math.min((now - state.lastFrameTime) / 1000, 0.1);

      state.lastFrameTime = now;


      if (state.isPlaying) {

        // 1x speed = 1 sim minute per 60 real seconds

        state.simMinutes += (dtSec / 60) * state.playbackSpeed;

        if (state.simMinutes >= 240) {

          state.simMinutes = 240;

          state.isPlaying = false;

          updatePlayPauseUI();

        }

      }


      const snap = computeTelemetrySnapshot(state.simMinutes);

      renderScene(snap);


      // Throttle DOM telemetry panel updates to ~12 Hz for crisp performance

      if (now - state.lastUiUpdate > 80) {

        renderTelemetryPanels(snap);

        state.lastUiUpdate = now;

      }


      requestAnimationFrame(animate);

    }


    window.onload = function () {

      resizeCanvas();

      updatePlayPauseUI();

      const initialSnap = computeTelemetrySnapshot(0);

      renderTelemetryPanels(initialSnap);

      state.lastFrameTime = performance.now();

      requestAnimationFrame(animate);

    };

  </script>

</body>

</html>


From <https://gemini.google.com/app/39a743a21517732f>  Google Gemini (4 Hydrogen)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#4188 Hybrid/GraphRAG