#5047 DSL: Simulation Timeline Definition

#5047 DSL: Simulation Timeline Definition

#5047 I an developing a simulation application. Describe a DSL for generating timeline data for the simulation. Entities to consider are background image, static assets, assigning activities to assets based on time tag and duration, and waypoints (image and label) that can be referenced in the activities (from waypoint A to waypoint B).

A declarative, block-based DSL works best for simulation timelines because it separates spatial setup (background, waypoints, assets) from temporal behavior (activities). Below is a complete design for a human-readable DSL—let's call it SimLine—that compiles cleanly into JSON or an in-memory event graph for your simulation engine.

1. Core Design Principles

  • Declarative & Scoped: Top-level blocks define the world (scene, waypoints, assets), while the timeline block defines state changes over time.

  • Symbolic References: Activities reference waypoints and assets by ID rather than raw coordinates, making layouts easy to adjust without rewriting the timeline.

  • Flexible Time Syntax: Supports both relative offsets (+5s), absolute timestamps (00:15, 15s), and explicit durations (for 10s).

  • Deterministic Compilation: The parser validates all asset/waypoint references and checks for conflicting activities on the same asset before the simulation runs.

2. Entity Definitions & Syntax

Scene & Background

Defines the coordinate space, simulation bounds, and background image.

Code snippet
scene "WarehouseFloor" {
  background: "assets/maps/warehouse_v2.png"
  dimensions: 1920 x 1080
  scale: 1px = 0.1m        // Optional physical unit mapping
  duration: 2m             // Total simulation length
}

Waypoints

Named spatial anchors with coordinates, an optional icon/image, and a display label.

Code snippet
waypoints {
  dock_a {
    pos: (120, 450)
    label: "Loading Dock A"
    image: "assets/icons/dock.svg"
  }
  storage_01 {
    pos: (840, 210)
    label: "Aisle 1 Rack"
    image: "assets/icons/rack.svg"
  }
  charger {
    pos: (100, 100)
    label: "Charging Bay"
    image: "assets/icons/bolt.svg"
  }
}

Static & Active Assets

Entities placed in the simulation. Static props only need a position and image; active assets can be referenced in the timeline.

Code snippet
assets {
  // Static scenery asset (never assigned activities)
  static desk_main {
    image: "assets/sprites/desk.png"
    pos: (500, 500)
    layer: 1
  }

  // Dynamic asset (can be referenced in timeline)
  asset forklift_1 {
    image: "assets/sprites/forklift.png"
    start_at: dock_a       // Can reference a waypoint ID or raw (x, y)
    layer: 2
    tags: ["vehicle", "electric"]
  }
}

Timeline & Activities

Assigns actions to assets using a time tag (at) and duration (for), referencing waypoints for movement.

Code snippet
timeline {
  // Absolute time tag + duration
  at 0s for 12s {
    forklift_1: move from dock_a to storage_01 easing linear
  }

  // Parallel activities at the same timestamp
  at 12s for 5s {
    forklift_1: state "unloading"
    forklift_1: label "Dropping Pallet #4"
  }

  // Relative time tag (starts immediately after the previous block ends)
  after 0s for 15s {
    forklift_1: move from storage_01 to charger easing ease_in_out
  }
}

3. Built-in Activity Primitives

ActivitySyntaxBehavior
Movemove from <wpA> to <wpB> [easing <type>]Interpolates asset position from wpA to wpB over the block's duration.
Teleport / Placeplace at <wp>Instantly snaps asset to waypoint coordinates (duration 0s).
Wait / IdleidleHolds current position and state for the duration.
State / Spritestate "<name>" or image "<path>"Swaps visual state, animation clip, or sprite sheet.
Visibilityshow / hideToggles asset rendering (can fade over duration).

4. Compilation & Validation Rules

When your parser compiles this DSL into runtime timeline data (e.g., a sorted array of JSON keyframes), enforce four checks:

  1. Reference Resolution: Every from, to, and start_at ID must exist in waypoints. Every activity target must exist in assets (and cannot be marked static).

  2. Overlap Detection: Flag an error if the same asset is assigned two conflicting spatial activities (e.g., two move commands) whose [start_time, start_time + duration] intervals overlap.

  3. Continuity Warning: Emit a warning if an asset's move from B to C starts while the asset's last known position was A (unless an implicit teleport is intended).

  4. Time Normalization: Convert all at, after, m, and s tokens into canonical milliseconds (e.g., start_ms, end_ms) so the simulation loop only reads numeric timestamps.


A first sim is intended to be Lunar Surface Operations. What else would be useful in the DSL?

Lunar surface operations introduce hard physical constraints—power, lighting, communications, and payload handoffs—that a basic movement timeline won't capture. Extending the DSL with resources, environment layers, asset coupling, and mission time will let your simulation model realistic operational trade-offs.

1. Resource & Consumable Tracking

Lunar assets live and die by budgets: rover battery state-of-charge (SoC), EVA suit oxygen, thermal limits, and onboard data storage.

  • Asset Properties: Define initial states and capacities on each asset.

  • Activity Rates: Attach consumption or generation rates to timeline blocks so the engine can flag depletion or violations.

assets {
  asset ltv_rover {
    image: "assets/sprites/rover.png"
    start_at: lander_pad
    resources: {
      battery: 100% (min: 20%)
      data_buffer: 0GB (max: 64GB)
    }
  }
}

timeline {
  at MET 00:15:00 for 45m {
    ltv_rover: move from lander_pad to shackleton_rim
      drain battery 0.4%/m
      generate data_buffer 0.1GB/m
  }
}

2. Asset Coupling (Parenting & Payloads)

In lunar ops, assets constantly board, tow, deploy, and hand off other assets (e.g., astronauts boarding a rover, a rover deploying a seismometer, or sample tubes moving from an astronaut to a lander).

timeline {
  // Astronaut boards rover; position now inherits from ltv_rover
  at MET 00:10:00 {
    attach astronaut_1 to ltv_rover
  }

  // Rover deploys a static science package at its current waypoint
  at MET 01:05:00 for 10m {
    detach seismometer_a from ltv_rover at shackleton_rim
    seismometer_a: state "active_logging"
  }
}

3. Environment Zones & Comm Windows

A static background image isn't enough when lighting and line-of-sight dictate whether an activity is even legal.

  • Spatial Zones: Polygons or radii for Permanently Shadowed Regions (PSRs), solar-lit ridges, or Keep-Out Zones (KOZs) like lander blast zones or steep crater walls.

  • Temporal Windows: Direct-to-Earth (DTE) or relay satellite passes that gate high-bandwidth downlinks.

zones {
  psr_floor {
    polygon: [(300, 400), (520, 410), (480, 620)]
    type: shadow
    solar_multiplier: 0.0
    thermal_penalty: high
  }
  blast_zone {
    circle: (120, 450) radius 80px
    type: hazard
  }
}

windows {
  comm_relay_pass_1 {
    start: MET 00:30:00
    duration: 25m
    bandwidth: 50Mbps
  }
}

4. Multi-Point Paths & Terrain Modifiers

Straight lines between Waypoint A and Waypoint B rarely work on cratered terrain. Adding intermediate waypoints (via) or speed/slope profiles keeps paths realistic without cluttering the waypoints block with dozens of named stops.

at MET 01:20:00 for 30m {
  ltv_rover: move from shackleton_rim to base_camp
    via [(610, 320), (450, 290)]
    max_speed: 1.5m/s
}

5. Mission Elapsed Time (MET), Phases & Dependencies

Lunar simulations typically span hours or multi-day EVA cycles rather than seconds, and schedules shift when one task runs long.

  • MET & Phases: Support MET DD:HH:MM:SS timestamps and group blocks into phase containers (e.g., phase "EVA-1: Egress", phase "Lunar Night Hibernation") for timeline scrubbing and UI filtering.

  • Named Activities & Dependencies: Allow an activity to trigger relative to another activity's completion rather than a hardcoded timestamp.

phase "EVA-1: Sample Collection" {
  id: eva1_traverse
  at MET 00:15:00 for 45m {
    ltv_rover: move from lander_pad to crater_edge
  }

  // Starts 5 minutes after eva1_traverse finishes, even if its duration changes
  after eva1_traverse + 5m for 20m {
    astronaut_1: activity "core_sampling" at crater_edge
  }
}

Summary of Recommended Extensions

FeatureDSL ConstructEngine Benefit
Consumablesresources, drain, rechargeReal-time telemetry gauges and constraint violation alerts.
Couplingattach / detachAutomatic coordinate inheritance for crew, rovers, and payloads.
Environmentzones, windowsVisual map overlays plus validation for solar power and comm blackouts.
Pathingvia [...], max_speedObstacle avoidance around craters and boulders.
Mission TimeMET, phase, after <id>Resilient schedules that ripple cleanly when one task slips.



Write a complete, end-to-end sample SimLine DSL script for a 2-hour Lunar EVA mission using resources, zones, coupling, and MET phases.

Here is a complete, 2-hour (MET 00:00:00 to 02:00:00) SimLine DSL script for a Shackleton Crater Rim EVA. It incorporates spatial zones, comm windows, resource budgets, asset coupling, and phase-based scheduling.

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

// MISSION: Artemis-Style South Pole EVA-1 (Shackleton Rim Reconnaissance)

// DURATION: 2 Hours (120 Minutes)

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


scene "ShackletonRim_EVA1" {

  background: "assets/maps/shackleton_south_pole_dem.png"

  dimensions: 2048 x 2048

  scale: 1px = 0.5m

  duration: 2h

}


// ----------------------------------------------------------------------------

// 1. SPATIAL WAYPOINTS

// ----------------------------------------------------------------------------

waypoints {

  lander_pad {

    pos: (320, 1680)

    label: "HLS Lander Pad"

    image: "assets/icons/lander_pad.svg"

  }

  solar_ridge {

    pos: (740, 1220)

    label: "Connecting Ridge (High Sun)"

    image: "assets/icons/sun_waypoint.svg"

  }

  shackleton_rim {

    pos: (1420, 680)

    label: "Station 1: Shackleton Rim"

    image: "assets/icons/science_flag.svg"

  }

  psr_edge {

    pos: (1580, 560)

    label: "Station 2: PSR Shadow Boundary"

    image: "assets/icons/crater_sample.svg"

  }

}


// ----------------------------------------------------------------------------

// 2. ENVIRONMENT ZONES & COMM WINDOWS

// ----------------------------------------------------------------------------

zones {

  psr_crater_floor {

    polygon: [(1540, 480), (1950, 420), (1980, 820), (1610, 690)]

    type: shadow

    solar_multiplier: 0.0

    thermal_penalty: high

  }

  lander_blast_koz {

    circle: (320, 1680) radius 90px

    type: hazard

  }

  ridge_sunlight_corridor {

    polygon: [(580, 1380), (920, 1080), (1010, 1180), (670, 1480)]

    type: solar_rich

    solar_multiplier: 1.0

  }

}


windows {

  lunar_relay_pass_1 {

    start: MET 00:55:00

    duration: 25m

    bandwidth: 50Mbps

  }

}


// ----------------------------------------------------------------------------

// 3. STATIC & DYNAMIC ASSETS

// ----------------------------------------------------------------------------

assets {

  static hls_lander {

    image: "assets/sprites/hls_lander.png"

    pos: (320, 1680)

    layer: 1

  }


  asset ltv_rover {

    image: "assets/sprites/ltv_rover.png"

    start_at: lander_pad

    layer: 2

    tags: ["vehicle", "electric"]

    resources: {

      battery: 100% (min: 20%)

      data_buffer: 0GB (max: 64GB)

    }

  }


  asset astronaut_1 {

    image: "assets/sprites/eva_cdr.png"

    start_at: lander_pad

    layer: 3

    tags: ["crew", "commander"]

    resources: {

      suit_o2: 100% (min: 25%)

      suit_battery: 100% (min: 20%)

    }

  }


  asset astronaut_2 {

    image: "assets/sprites/eva_fe.png"

    start_at: lander_pad

    layer: 3

    tags: ["crew", "geologist"]

    resources: {

      suit_o2: 100% (min: 25%)

      suit_battery: 100% (min: 20%)

    }

  }


  asset seismometer_pkg {

    image: "assets/sprites/seismometer.png"

    start_at: lander_pad

    layer: 2

    tags: ["payload", "science"]

  }

}


// ----------------------------------------------------------------------------

// 4. MISSION TIMELINE (MET PHASES)

// ----------------------------------------------------------------------------

timeline {


  // --- PHASE 1: Egress & Rover Prep (00:00:00 - 00:15:00) ---

  phase "EVA-1: Egress & Rover Prep" {

    id: egress_checks

    at MET 00:00:00 for 10m {

      astronaut_1: state "suit_check"

      astronaut_2: state "suit_check"

      astronaut_1: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m

      astronaut_2: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m

      ltv_rover: state "pre_drive_boot"

    }


    id: board_rover

    after egress_checks + 0m for 5m {

      attach astronaut_1 to ltv_rover

      attach astronaut_2 to ltv_rover

      attach seismometer_pkg to ltv_rover

      ltv_rover: label "Crew Boarded - Ready to Roll"

    }

  }


  // --- PHASE 2: Outbound Traverse (00:15:00 - 00:45:00) ---

  phase "EVA-2: Outbound Traverse" {

    id: outbound_drive

    after board_rover + 0m for 30m {

      ltv_rover: move from lander_pad to shackleton_rim

        via [(520, 1480), (740, 1220), (1120, 910)]

        max_speed: 2.0m/s

        easing ease_in_out

        drain battery 0.8%/m

        generate data_buffer 0.3GB/m

      astronaut_1: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m

      astronaut_2: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m

    }

  }


  // --- PHASE 3: Science Deployment & PSR Sampling (00:45:00 - 01:20:00) ---

  phase "EVA-3: Rim Science & Sampling" {

    id: dismount_rim

    after outbound_drive + 0m for 5m {

      detach astronaut_1 from ltv_rover at shackleton_rim

      detach astronaut_2 from ltv_rover at shackleton_rim

      ltv_rover: state "standby_relay"

    }


    id: deploy_and_sample

    after dismount_rim + 0m for 15m {

      // Commander deploys seismometer at the rim

      detach seismometer_pkg from ltv_rover at shackleton_rim

      seismometer_pkg: state "active_logging"

      astronaut_1: state "deploying_payload"

      astronaut_1: drain suit_o2 0.45%/m, drain suit_battery 0.3%/m


      // Geologist traverses on foot to PSR shadow boundary for core sample

      astronaut_2: move from shackleton_rim to psr_edge

        max_speed: 0.6m/s

        drain suit_o2 0.6%/m, drain suit_battery 0.5%/m

      astronaut_2: label "Core Sampling at PSR Edge"

    }


    id: downlink_and_return

    after deploy_and_sample + 0m for 10m {

      // High-rate downlink occurs inside lunar_relay_pass_1 (00:55 - 01:20)

      ltv_rover: state "downlinking"

      ltv_rover: drain data_buffer 0.9GB/m, drain battery 0.4%/m


      // Geologist returns to rover with sealed sample tube

      astronaut_2: move from psr_edge to shackleton_rim

        max_speed: 0.6m/s

        drain suit_o2 0.5%/m, drain suit_battery 0.4%/m

      astronaut_1: state "stowing_tools"

      astronaut_1: drain suit_o2 0.35%/m, drain suit_battery 0.25%/m

    }


    id: reboard_rover

    after downlink_and_return + 0m for 5m {

      attach astronaut_1 to ltv_rover

      attach astronaut_2 to ltv_rover

      ltv_rover: label "Samples Stowed - Departing Rim"

    }

  }


  // --- PHASE 4: Return Traverse & Closeout (01:20:00 - 02:00:00) ---

  phase "EVA-4: Return & Closeout" {

    id: return_drive

    after reboard_rover + 0m for 30m {

      ltv_rover: move from shackleton_rim to lander_pad

        via [(1120, 910), (740, 1220), (520, 1480)]

        max_speed: 2.0m/s

        easing ease_in_out

        drain battery 0.75%/m

        generate data_buffer 0.2GB/m

      astronaut_1: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m

      astronaut_2: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m

    }


    id: eva_closeout

    after return_drive + 0m for 10m {

      detach astronaut_1 from ltv_rover at lander_pad

      detach astronaut_2 from ltv_rover at lander_pad

      ltv_rover: state "charging"

      ltv_rover: recharge battery 1.5%/m

      astronaut_1: state "airlock_ingress"

      astronaut_2: state "airlock_ingress"

      astronaut_1: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m

      astronaut_2: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m

    }

  }

}



Define the compiled JSON schema that supports resources, spatial zones, asset attachment, and MET timelines.

This JSON Schema (Draft 2020-12) defines the normalized, engine-ready output of the SimLine compiler. All symbolic references (after <id>, MET strings, waypoint names) are resolved into numeric millisecond timestamps (start_ms, end_ms) and explicit (x, y) coordinates so your playback engine can run without parsing logic.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://simline.local/schemas/lunar-timeline-v1.json",
  "title": "SimLine Compiled Simulation Timeline",
  "type": "object",
  "required": ["schema_version", "scene", "waypoints", "assets", "phases", "events"],
  "additionalProperties": false,
  "properties": {
    "schema_version": {
      "type": "string",
      "const": "1.0.0"
    },
    "scene": {
      "type": "object",
      "required": ["id", "background", "dimensions", "duration_ms"],
      "additionalProperties": false,
      "properties": {
        "id": { "type": "string" },
        "background": { "type": "string" },
        "dimensions": {
          "type": "object",
          "required": ["width", "height"],
          "properties": {
            "width": { "type": "integer", "minimum": 1 },
            "height": { "type": "integer", "minimum": 1 }
          }
        },
        "scale_m_per_px": { "type": "number", "exclusiveMinimum": 0 },
        "duration_ms": { "type": "integer", "minimum": 0 }
      }
    },
    "waypoints": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "required": ["pos", "label"],
        "additionalProperties": false,
        "properties": {
          "pos": { "$ref": "#/$defs/point2d" },
          "label": { "type": "string" },
          "image": { "type": "string" }
        }
      }
    },
    "zones": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["id", "type", "geometry"],
        "additionalProperties": false,
        "properties": {
          "id": { "type": "string" },
          "type": { "enum": ["shadow", "hazard", "solar_rich"] },
          "geometry": {
            "oneOf": [
              {
                "type": "object",
                "required": ["shape", "points"],
                "additionalProperties": false,
                "properties": {
                  "shape": { "const": "polygon" },
                  "points": {
                    "type": "array",
                    "minItems": 3,
                    "items": { "$ref": "#/$defs/point2d" }
                  }
                }
              },
              {
                "type": "object",
                "required": ["shape", "center", "radius_px"],
                "additionalProperties": false,
                "properties": {
                  "shape": { "const": "circle" },
                  "center": { "$ref": "#/$defs/point2d" },
                  "radius_px": { "type": "number", "exclusiveMinimum": 0 }
                }
              }
            ]
          },
          "modifiers": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "solar_multiplier": { "type": "number", "minimum": 0, "maximum": 1 },
              "thermal_penalty": { "enum": ["none", "low", "medium", "high"] }
            }
          }
        }
      }
    },
    "windows": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["id", "start_ms", "end_ms", "bandwidth_mbps"],
        "additionalProperties": false,
        "properties": {
          "id": { "type": "string" },
          "start_ms": { "type": "integer", "minimum": 0 },
          "end_ms": { "type": "integer", "minimum": 0 },
          "bandwidth_mbps": { "type": "number", "minimum": 0 }
        }
      }
    },
    "assets": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "required": ["is_static", "image", "start_pos", "layer"],
        "additionalProperties": false,
        "properties": {
          "is_static": { "type": "boolean" },
          "image": { "type": "string" },
          "start_pos": { "$ref": "#/$defs/point2d" },
          "start_waypoint_id": { "type": ["string", "null"] },
          "layer": { "type": "integer" },
          "tags": {
            "type": "array",
            "items": { "type": "string" }
          },
          "resources": {
            "type": "object",
            "additionalProperties": { "$ref": "#/$defs/resourceSpec" }
          }
        }
      }
    },
    "phases": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["id", "name", "start_ms", "end_ms"],
        "additionalProperties": false,
        "properties": {
          "id": { "type": "string" },
          "name": { "type": "string" },
          "start_ms": { "type": "integer", "minimum": 0 },
          "end_ms": { "type": "integer", "minimum": 0 }
        }
      }
    },
    "events": {
      "type": "array",
      "description": "Chronologically sorted by start_ms.",
      "items": {
        "oneOf": [
          { "$ref": "#/$defs/moveEvent" },
          { "$ref": "#/$defs/couplingEvent" },
          { "$ref": "#/$defs/stateEvent" },
          { "$ref": "#/$defs/labelEvent" },
          { "$ref": "#/$defs/resourceEvent" }
        ]
      }
    }
  },
  "$defs": {
    "point2d": {
      "type": "array",
      "prefixItems": [{ "type": "number" }, { "type": "number" }],
      "minItems": 2,
      "maxItems": 2
    },
    "resourceSpec": {
      "type": "object",
      "required": ["initial", "unit"],
      "additionalProperties": false,
      "properties": {
        "initial": { "type": "number" },
        "unit": { "type": "string" },
        "min": { "type": ["number", "null"] },
        "max": { "type": ["number", "null"] }
      }
    },
    "eventBase": {
      "type": "object",
      "required": ["id", "phase_id", "start_ms", "end_ms", "target_asset_id", "type"],
      "properties": {
        "id": { "type": "string" },
        "phase_id": { "type": "string" },
        "start_ms": { "type": "integer", "minimum": 0 },
        "end_ms": { "type": "integer", "minimum": 0 },
        "target_asset_id": { "type": "string" }
      }
    },
    "moveEvent": {
      "allOf": [
        { "$ref": "#/$defs/eventBase" },
        {
          "required": ["path"],
          "properties": {
            "type": { "const": "move" },
            "from_waypoint_id": { "type": ["string", "null"] },
            "to_waypoint_id": { "type": ["string", "null"] },
            "path": {
              "type": "array",
              "minItems": 2,
              "description": "Resolved polyline: [start_pos, ...via_points, end_pos]",
              "items": { "$ref": "#/$defs/point2d" }
            },
            "easing": { "enum": ["linear", "ease_in", "ease_out", "ease_in_out"], "default": "linear" },
            "max_speed_mps": { "type": "number", "exclusiveMinimum": 0 }
          }
        }
      ]
    },
    "couplingEvent": {
      "allOf": [
        { "$ref": "#/$defs/eventBase" },
        {
          "required": ["parent_asset_id"],
          "properties": {
            "type": { "enum": ["attach", "detach"] },
            "parent_asset_id": { "type": "string" },
            "detach_pos": { "$ref": "#/$defs/point2d" }
          }
        }
      ]
    },
    "stateEvent": {
      "allOf": [
        { "$ref": "#/$defs/eventBase" },
        {
          "required": ["state"],
          "properties": {
            "type": { "const": "state" },
            "state": { "type": "string" }
          }
        }
      ]
    },
    "labelEvent": {
      "allOf": [
        { "$ref": "#/$defs/eventBase" },
        {
          "required": ["text"],
          "properties": {
            "type": { "const": "label" },
            "text": { "type": "string" }
          }
        }
      ]
    },
    "resourceEvent": {
      "allOf": [
        { "$ref": "#/$defs/eventBase" },
        {
          "required": ["resource", "rate_per_min"],
          "properties": {
            "type": { "const": "resource_delta" },
            "resource": { "type": "string" },
            "rate_per_min": {
              "type": "number",
              "description": "Negative for drain, positive for recharge/generate."
            }
          }
        }
      ]
    }
  }
}

Key Design Decisions for the Playback Engine

  • Flattened, Sorted events Array: Instead of nesting events inside phases, phases are stored as lightweight time-range metadata (start_ms to end_ms) for UI scrubbing, while events is a single array sorted by start_ms. This lets the simulation loop binary-search or sweep active events at any timestamp t in O(log n) time.

  • Pre-Resolved path Polylines: The compiler expands move from A to B via [...] into a single path array of [x, y] pairs. The renderer only needs to interpolate along polyline segments without looking up waypoint IDs every frame.

  • Signed rate_per_min: drain, recharge, and generate all compile into a single resource_delta event type with a signed float (-0.8 for drain, +1.5 for recharge), simplifying telemetry integration during scrubbing.

  • O(1) Asset & Waypoint Maps: Storing assets and waypoints as dictionaries keyed by ID avoids linear scans when resolving target_asset_id or parent_asset_id during rendering.



Write the complete Pydantic v2 models in Python that implement and validate this SimLine compiled JSON schema.

Below is a complete, self-contained Pydantic v2 implementation (simline_schema.py) that mirrors the compiled JSON schema, enforces extra="forbid" (additionalProperties: false), and adds cross-field referential integrity checks (validating asset IDs, waypoint IDs, phase IDs, resource keys, and chronological ordering).

from __future__ import annotations

from typing import Annotated, Dict, List, Literal, Optional, Tuple, Union
from pydantic import BaseModel, ConfigDict, Field, model_validator

# ---------------------------------------------------------------------------
# Shared Primitives & Base Config
# ---------------------------------------------------------------------------

Point2D = Tuple[float, float]


class StrictModel(BaseModel):
    """Base model enforcing strict schema compliance (no unknown keys)."""
    model_config = ConfigDict(extra="forbid")


# ---------------------------------------------------------------------------
# 1. Scene & Waypoints
# ---------------------------------------------------------------------------

class Dimensions(StrictModel):
    width: int = Field(..., ge=1)
    height: int = Field(..., ge=1)


class Scene(StrictModel):
    id: str
    background: str
    dimensions: Dimensions
    scale_m_per_px: Optional[float] = Field(default=None, gt=0)
    duration_ms: int = Field(..., ge=0)


class Waypoint(StrictModel):
    pos: Point2D
    label: str
    image: Optional[str] = None


# ---------------------------------------------------------------------------
# 2. Spatial Zones & Communication Windows
# ---------------------------------------------------------------------------

class PolygonGeometry(StrictModel):
    shape: Literal["polygon"] = "polygon"
    points: List[Point2D] = Field(..., min_length=3)


class CircleGeometry(StrictModel):
    shape: Literal["circle"] = "circle"
    center: Point2D
    radius_px: float = Field(..., gt=0)


ZoneGeometry = Annotated[
    Union[PolygonGeometry, CircleGeometry],
    Field(discriminator="shape"),
]


class ZoneModifiers(StrictModel):
    solar_multiplier: Optional[float] = Field(default=None, ge=0.0, le=1.0)
    thermal_penalty: Optional[Literal["none", "low", "medium", "high"]] = None


class Zone(StrictModel):
    id: str
    type: Literal["shadow", "hazard", "solar_rich"]
    geometry: ZoneGeometry
    modifiers: Optional[ZoneModifiers] = None


class CommWindow(StrictModel):
    id: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)
    bandwidth_mbps: float = Field(..., ge=0.0)

    @model_validator(mode="after")
    def validate_time_bounds(self) -> CommWindow:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Window '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


# ---------------------------------------------------------------------------
# 3. Assets & Resources
# ---------------------------------------------------------------------------

class ResourceSpec(StrictModel):
    initial: float
    unit: str
    min: Optional[float] = None
    max: Optional[float] = None

    @model_validator(mode="after")
    def validate_bounds(self) -> ResourceSpec:
        if self.min is not None and self.max is not None and self.min > self.max:
            raise ValueError(f"Resource min ({self.min}) cannot exceed max ({self.max})")
        if self.min is not None and self.initial < self.min:
            raise ValueError(f"Initial value ({self.initial}) is below min ({self.min})")
        if self.max is not None and self.initial > self.max:
            raise ValueError(f"Initial value ({self.initial}) exceeds max ({self.max})")
        return self


class Asset(StrictModel):
    is_static: bool
    image: str
    start_pos: Point2D
    start_waypoint_id: Optional[str] = None
    layer: int
    tags: List[str] = Field(default_factory=list)
    resources: Dict[str, ResourceSpec] = Field(default_factory=dict)


# ---------------------------------------------------------------------------
# 4. Mission Phases & Timeline Events
# ---------------------------------------------------------------------------

class Phase(StrictModel):
    id: str
    name: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)

    @model_validator(mode="after")
    def validate_time_bounds(self) -> Phase:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Phase '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


class EventBase(StrictModel):
    id: str
    phase_id: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)
    target_asset_id: str

    @model_validator(mode="after")
    def validate_time_bounds(self) -> EventBase:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Event '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


class MoveEvent(EventBase):
    type: Literal["move"] = "move"
    from_waypoint_id: Optional[str] = None
    to_waypoint_id: Optional[str] = None
    path: List[Point2D] = Field(..., min_length=2)
    easing: Literal["linear", "ease_in", "ease_out", "ease_in_out"] = "linear"
    max_speed_mps: Optional[float] = Field(default=None, gt=0.0)


class CouplingEvent(EventBase):
    type: Literal["attach", "detach"]
    parent_asset_id: str
    detach_pos: Optional[Point2D] = None


class StateEvent(EventBase):
    type: Literal["state"] = "state"
    state: str


class LabelEvent(EventBase):
    type: Literal["label"] = "label"
    text: str


class ResourceEvent(EventBase):
    type: Literal["resource_delta"] = "resource_delta"
    resource: str
    rate_per_min: float = Field(
        ..., description="Negative for drain, positive for recharge/generate."
    )


TimelineEvent = Annotated[
    Union[MoveEvent, CouplingEvent, StateEvent, LabelEvent, ResourceEvent],
    Field(discriminator="type"),
]


# ---------------------------------------------------------------------------
# 5. Root Timeline Document & Cross-Reference Validation
# ---------------------------------------------------------------------------

class SimLineTimeline(StrictModel):
    schema_version: Literal["1.0.0"] = "1.0.0"
    scene: Scene
    waypoints: Dict[str, Waypoint]
    zones: List[Zone] = Field(default_factory=list)
    windows: List[CommWindow] = Field(default_factory=list)
    assets: Dict[str, Asset]
    phases: List[Phase]
    events: List[TimelineEvent]

    @model_validator(mode="after")
    def validate_referential_integrity(self) -> SimLineTimeline:
        phase_ids = {p.id for p in self.phases}

        # 1. Validate asset start waypoints
        for asset_id, asset in self.assets.items():
            if asset.start_waypoint_id and asset.start_waypoint_id not in self.waypoints:
                raise ValueError(
                    f"Asset '{asset_id}' references unknown start_waypoint_id "
                    f"'{asset.start_waypoint_id}'"
                )

        # 2. Validate events (references, static guards, chronological order)
        prev_start_ms = -1
        for ev in self.events:
            if ev.start_ms < prev_start_ms:
                raise ValueError(
                    f"Events must be sorted by start_ms: '{ev.id}' ({ev.start_ms}) "
                    f"appears after {prev_start_ms}"
                )
            prev_start_ms = ev.start_ms

            if ev.phase_id not in phase_ids:
                raise ValueError(f"Event '{ev.id}' references unknown phase_id '{ev.phase_id}'")

            if ev.target_asset_id not in self.assets:
                raise ValueError(
                    f"Event '{ev.id}' references unknown target_asset_id '{ev.target_asset_id}'"
                )

            target_asset = self.assets[ev.target_asset_id]
            if target_asset.is_static:
                raise ValueError(
                    f"Event '{ev.id}' cannot target static asset '{ev.target_asset_id}'"
                )

            if isinstance(ev, MoveEvent):
                for wp_id in (ev.from_waypoint_id, ev.to_waypoint_id):
                    if wp_id and wp_id not in self.waypoints:
                        raise ValueError(
                            f"MoveEvent '{ev.id}' references unknown waypoint '{wp_id}'"
                        )

            elif isinstance(ev, CouplingEvent):
                if ev.parent_asset_id not in self.assets:
                    raise ValueError(
                        f"CouplingEvent '{ev.id}' references unknown parent_asset_id "
                        f"'{ev.parent_asset_id}'"
                    )
                if ev.parent_asset_id == ev.target_asset_id:
                    raise ValueError(
                        f"CouplingEvent '{ev.id}' cannot attach/detach asset to itself"
                    )

            elif isinstance(ev, ResourceEvent):
                if ev.resource not in target_asset.resources:
                    raise ValueError(
                        f"ResourceEvent '{ev.id}' references undefined resource "
                        f"'{ev.resource}' on asset '{ev.target_asset_id}'"
                    )

        return self


# ---------------------------------------------------------------------------
# Quick Usage Example
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    import json

    # Export the exact JSON Schema from the Pydantic models
    print(json.dumps(SimLineTimeline.model_json_schema(), indent=2))

Usage in Your Pipeline

  • Validate compiled JSON: timeline = SimLineTimeline.model_validate_json(raw_json_str)

  • Serialize back to clean JSON: timeline.model_dump_json(indent=2)

  • Export Draft 2020-12 JSON Schema: SimLineTimeline.model_json_schema()


Write a Python compiler script that parses the SimLine Lunar EVA DSL into a validated SimLineTimeline Pydantic model and exports JSON.

Below is a zero-dependency (standard library + pydantic) Python compiler (simline_compiler.py) that parses the SimLine Lunar EVA DSL, resolves MET timestamps, after <id> dependencies, waypoint polylines, and signed resource deltas, validates the result against SimLineTimeline from simline_schema.py, and exports normalized JSON.

from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from simline_schema import (
    Asset,
    CircleGeometry,
    CommWindow,
    CouplingEvent,
    Dimensions,
    LabelEvent,
    MoveEvent,
    Phase,
    Point2D,
    PolygonGeometry,
    ResourceEvent,
    ResourceSpec,
    Scene,
    SimLineTimeline,
    StateEvent,
    TimelineEvent,
    Waypoint,
    Zone,
    ZoneModifiers,
)


# ---------------------------------------------------------------------------
# 1. Lexing & Time Utilities
# ---------------------------------------------------------------------------

def strip_comments(text: str) -> str:
    return re.sub(r"//.*", "", text)


def parse_duration_ms(token: str) -> int:
    """Converts '2h', '45m', '10s', '0m' into milliseconds."""
    token = token.strip()
    m = re.fullmatch(r"(\d+(?:\.\d+)?)(h|m|s|ms)", token)
    if not m:
        raise ValueError(f"Invalid duration token: '{token}'")
    val, unit = float(m.group(1)), m.group(2)
    mult = {"ms": 1, "s": 1_000, "m": 60_000, "h": 3_600_000}[unit]
    return int(round(val * mult))


def parse_met_ms(token: str) -> int:
    """Converts 'MET HH:MM:SS' or 'MET DD:HH:MM:SS' into milliseconds."""
    clean = token.replace("MET", "").strip()
    parts = [int(p) for p in clean.split(":")]
    if len(parts) == 3:
        h, m, s = parts
        d = 0
    elif len(parts) == 4:
        d, h, m, s = parts
    else:
        raise ValueError(f"Invalid MET timestamp: '{token}'")
    return ((d * 24 + h) * 3600 + m * 60 + s) * 1_000


def parse_point(text: str) -> Point2D:
    m = re.search(r"\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)", text)
    if not m:
        raise ValueError(f"Invalid 2D point: '{text}'")
    return (float(m.group(1)), float(m.group(2)))


def parse_point_list(text: str) -> List[Point2D]:
    return [
        (float(x), float(y))
        for x, y in re.findall(r"\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)", text)
    ]


def slugify(name: str) -> str:
    return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")


def extract_named_blocks(text: str) -> List[Tuple[str, str]]:
    """
    Extracts top-level '<header> { <body> }' blocks using brace depth counting.
    Returns a list of (header_str, body_str).
    """
    blocks: List[Tuple[str, str]] = []
    i, n = 0, len(text)
    while i < n:
        brace_idx = text.find("{", i)
        if brace_idx == -1:
            break
        header = text[i:brace_idx].strip()
        depth = 1
        j = brace_idx + 1
        while j < n and depth > 0:
            if text[j] == "{":
                depth += 1
            elif text[j] == "}":
                depth -= 1
            j += 1
        if depth != 0:
            raise SyntaxError(f"Unclosed brace in block: '{header[:40]}'")
        body = text[brace_idx + 1 : j - 1].strip()
        if header:
            blocks.append((header, body))
        i = j
    return blocks


# ---------------------------------------------------------------------------
# 2. Section Parsers
# ---------------------------------------------------------------------------

def parse_scene(header: str, body: str) -> Scene:
    m_id = re.search(r'"([^"]+)"', header)
    scene_id = m_id.group(1) if m_id else "UntitledScene"

    bg = re.search(r'background:\s*"([^"]+)"', body)
    dims = re.search(r"dimensions:\s*(\d+)\s*x\s*(\d+)", body)
    scale = re.search(r"scale:\s*1px\s*=\s*(\d+(?:\.\d+)?)m", body)
    dur = re.search(r"duration:\s*([^\s]+)", body)

    if not (bg and dims and dur):
        raise ValueError("Scene block missing required background, dimensions, or duration.")

    return Scene(
        id=scene_id,
        background=bg.group(1),
        dimensions=Dimensions(width=int(dims.group(1)), height=int(dims.group(2))),
        scale_m_per_px=float(scale.group(1)) if scale else None,
        duration_ms=parse_duration_ms(dur.group(1)),
    )


def parse_waypoints(body: str) -> Dict[str, Waypoint]:
    waypoints: Dict[str, Waypoint] = {}
    for wp_id, wp_body in extract_named_blocks(body):
        pos_m = re.search(r"pos:\s*(\([^)]+\))", wp_body)
        lbl_m = re.search(r'label:\s*"([^"]+)"', wp_body)
        img_m = re.search(r'image:\s*"([^"]+)"', wp_body)
        if not (pos_m and lbl_m):
            raise ValueError(f"Waypoint '{wp_id}' requires pos and label.")
        waypoints[wp_id] = Waypoint(
            pos=parse_point(pos_m.group(1)),
            label=lbl_m.group(1),
            image=img_m.group(1) if img_m else None,
        )
    return waypoints


def parse_zones(body: str) -> List[Zone]:
    zones: List[Zone] = []
    for zone_id, z_body in extract_named_blocks(body):
        type_m = re.search(r"type:\s*(\w+)", z_body)
        if not type_m:
            raise ValueError(f"Zone '{zone_id}' missing type.")

        poly_m = re.search(r"polygon:\s*\[([^\]]+)\]", z_body)
        circ_m = re.search(r"circle:\s*(\([^)]+\))\s*radius\s*(\d+(?:\.\d+)?)px", z_body)

        if poly_m:
            geom = PolygonGeometry(points=parse_point_list(poly_m.group(1)))
        elif circ_m:
            geom = CircleGeometry(
                center=parse_point(circ_m.group(1)),
                radius_px=float(circ_m.group(2)),
            )
        else:
            raise ValueError(f"Zone '{zone_id}' must define either polygon or circle.")

        solar_m = re.search(r"solar_multiplier:\s*(\d+(?:\.\d+)?)", z_body)
        therm_m = re.search(r"thermal_penalty:\s*(\w+)", z_body)
        mods = None
        if solar_m or therm_m:
            mods = ZoneModifiers(
                solar_multiplier=float(solar_m.group(1)) if solar_m else None,
                thermal_penalty=therm_m.group(1) if therm_m else None,
            )

        zones.append(Zone(id=zone_id, type=type_m.group(1), geometry=geom, modifiers=mods))
    return zones


def parse_windows(body: str) -> List[CommWindow]:
    windows: List[CommWindow] = []
    for win_id, w_body in extract_named_blocks(body):
        start_m = re.search(r"start:\s*(MET\s+[\d:]+)", w_body)
        dur_m = re.search(r"duration:\s*([^\s]+)", w_body)
        bw_m = re.search(r"bandwidth:\s*(\d+(?:\.\d+)?)Mbps", w_body)
        if not (start_m and dur_m and bw_m):
            raise ValueError(f"Window '{win_id}' missing start, duration, or bandwidth.")
        start_ms = parse_met_ms(start_m.group(1))
        end_ms = start_ms + parse_duration_ms(dur_m.group(1))
        windows.append(
            CommWindow(
                id=win_id,
                start_ms=start_ms,
                end_ms=end_ms,
                bandwidth_mbps=float(bw_m.group(1)),
            )
        )
    return windows


def parse_resources_block(res_body: str) -> Dict[str, ResourceSpec]:
    resources: Dict[str, ResourceSpec] = {}
    for line in res_body.splitlines():
        line = line.strip()
        if not line:
            continue
        # Example: battery: 100% (min: 20%)  or  data_buffer: 0GB (max: 64GB)
        m = re.match(
            r"(\w+):\s*(-?\d+(?:\.\d+)?)([A-Za-z%]+)(?:\s*\(([^)]+)\))?",
            line,
        )
        if not m:
            raise ValueError(f"Invalid resource spec: '{line}'")
        name, init_val, unit, bounds_str = m.group(1), float(m.group(2)), m.group(3), m.group(4)
        min_val = max_val = None
        if bounds_str:
            min_m = re.search(r"min:\s*(-?\d+(?:\.\d+)?)", bounds_str)
            max_m = re.search(r"max:\s*(-?\d+(?:\.\d+)?)", bounds_str)
            if min_m:
                min_val = float(min_m.group(1))
            if max_m:
                max_val = float(max_m.group(1))
        resources[name] = ResourceSpec(initial=init_val, unit=unit, min=min_val, max=max_val)
    return resources


def parse_assets(body: str, waypoints: Dict[str, Waypoint]) -> Dict[str, Asset]:
    assets: Dict[str, Asset] = {}
    for header, a_body in extract_named_blocks(body):
        m_hdr = re.match(r"(static|asset)\s+(\w+)", header)
        if not m_hdr:
            raise ValueError(f"Invalid asset header: '{header}'")
        is_static = m_hdr.group(1) == "static"
        asset_id = m_hdr.group(2)

        img_m = re.search(r'image:\s*"([^"]+)"', a_body)
        layer_m = re.search(r"layer:\s*(-?\d+)", a_body)
        if not (img_m and layer_m):
            raise ValueError(f"Asset '{asset_id}' requires image and layer.")

        start_wp_id: Optional[str] = None
        pos_m = re.search(r"pos:\s*(\([^)]+\))", a_body)
        start_at_m = re.search(r"start_at:\s*(\w+|\([^)]+\))", a_body)

        if pos_m:
            start_pos = parse_point(pos_m.group(1))
        elif start_at_m:
            val = start_at_m.group(1)
            if val.startswith("("):
                start_pos = parse_point(val)
            else:
                if val not in waypoints:
                    raise ValueError(f"Asset '{asset_id}' references unknown waypoint '{val}'")
                start_wp_id = val
                start_pos = waypoints[val].pos
        else:
            raise ValueError(f"Asset '{asset_id}' requires pos or start_at.")

        tags: List[str] = []
        tags_m = re.search(r"tags:\s*\[([^\]]*)\]", a_body)
        if tags_m:
            tags = re.findall(r'"([^"]+)"', tags_m.group(1))

        resources: Dict[str, ResourceSpec] = {}
        for sub_hdr, sub_body in extract_named_blocks(a_body):
            if sub_hdr.rstrip(":") == "resources":
                resources = parse_resources_block(sub_body)

        assets[asset_id] = Asset(
            is_static=is_static,
            image=img_m.group(1),
            start_pos=start_pos,
            start_waypoint_id=start_wp_id,
            layer=int(layer_m.group(1)),
            tags=tags,
            resources=resources,
        )
    return assets


# ---------------------------------------------------------------------------
# 3. Timeline & Activity Compiler
# ---------------------------------------------------------------------------

def parse_resource_deltas(
    text: str,
    block_id: str,
    phase_id: str,
    start_ms: int,
    end_ms: int,
    asset_id: str,
    counter: List[int],
) -> List[ResourceEvent]:
    events: List[ResourceEvent] = []
    pattern = re.compile(
        r"(drain|recharge|generate)\s+(\w+)\s+(\d+(?:\.\d+)?)[A-Za-z%]+/m"
    )
    for op, res_name, rate_str in pattern.findall(text):
        rate = float(rate_str)
        if op == "drain":
            rate = -rate
        counter[0] += 1
        events.append(
            ResourceEvent(
                id=f"{block_id}_ev{counter[0]}",
                phase_id=phase_id,
                start_ms=start_ms,
                end_ms=end_ms,
                target_asset_id=asset_id,
                resource=res_name,
                rate_per_min=rate,
            )
        )
    return events


def parse_timeline(
    body: str,
    waypoints: Dict[str, Waypoint],
) -> Tuple[List[Phase], List[TimelineEvent]]:
    phases: List[Phase] = []
    events: List[TimelineEvent] = []
    block_end_ms: Dict[str, int] = {}

    for phase_hdr, phase_body in extract_named_blocks(body):
        m_ph = re.match(r'phase\s+"([^"]+)"', phase_hdr)
        if not m_ph:
            raise ValueError(f"Invalid phase header: '{phase_hdr}'")
        phase_name = m_ph.group(1)
        phase_id = slugify(phase_name)
        phase_starts: List[int] = []
        phase_ends: List[int] = []

        for act_hdr, act_body in extract_named_blocks(phase_body):
            # Extract optional 'id: <block_id>'
            id_m = re.search(r"id:\s*(\w+)", act_hdr)
            block_id = id_m.group(1) if id_m else f"{phase_id}_blk_{len(block_end_ms) + 1}"

            # Resolve start_ms from 'at MET ...' or 'after <ref> + <offset>'
            at_m = re.search(r"at\s+(MET\s+[\d:]+)", act_hdr)
            after_m = re.search(r"after\s+(\w+)\s*\+\s*([^\s]+)", act_hdr)
            dur_m = re.search(r"for\s+([^\s]+)", act_hdr)

            if at_m:
                start_ms = parse_met_ms(at_m.group(1))
            elif after_m:
                ref_id, offset_tok = after_m.group(1), after_m.group(2)
                if ref_id not in block_end_ms:
                    raise ValueError(f"Block '{block_id}' references unknown prior block '{ref_id}'")
                start_ms = block_end_ms[ref_id] + parse_duration_ms(offset_tok)
            else:
                raise ValueError(f"Activity block '{block_id}' missing 'at' or 'after' timing.")

            duration_ms = parse_duration_ms(dur_m.group(1)) if dur_m else 0
            end_ms = start_ms + duration_ms

            block_end_ms[block_id] = end_ms
            phase_starts.append(start_ms)
            phase_ends.append(end_ms)

            # Group multi-line statements (indented continuations belong to previous command)
            raw_lines = [ln for ln in act_body.splitlines() if ln.strip()]
            statements: List[str] = []
            for ln in raw_lines:
                stripped = ln.strip()
                is_new_stmt = bool(
                    re.match(r"^(attach|detach)\s+", stripped)
                    or re.match(r"^\w+:\s+", stripped)
                )
                if is_new_stmt or not statements:
                    statements.append(stripped)
                else:
                    statements[-1] += " " + stripped

            ev_counter = [0]
            for stmt in statements:
                # 1. attach <child> to <parent>
                m_att = re.match(r"^attach\s+(\w+)\s+to\s+(\w+)$", stmt)
                if m_att:
                    ev_counter[0] += 1
                    events.append(
                        CouplingEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=m_att.group(1),
                            type="attach",
                            parent_asset_id=m_att.group(2),
                        )
                    )
                    continue

                # 2. detach <child> from <parent> at <wp>
                m_det = re.match(r"^detach\s+(\w+)\s+from\s+(\w+)\s+at\s+(\w+)$", stmt)
                if m_det:
                    child_id, parent_id, wp_id = m_det.group(1), m_det.group(2), m_det.group(3)
                    if wp_id not in waypoints:
                        raise ValueError(f"Detach references unknown waypoint '{wp_id}'")
                    ev_counter[0] += 1
                    events.append(
                        CouplingEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=child_id,
                            type="detach",
                            parent_asset_id=parent_id,
                            detach_pos=waypoints[wp_id].pos,
                        )
                    )
                    continue

                # 3. Asset-targeted statements: '<asset_id>: <command>'
                m_asset = re.match(r"^(\w+):\s+(.+)$", stmt)
                if not m_asset:
                    raise ValueError(f"Unrecognized timeline statement: '{stmt}'")
                asset_id, cmd = m_asset.group(1), m_asset.group(2)

                # 3a. state "..."
                m_state = re.match(r'^state\s+"([^"]+)"$', cmd)
                if m_state:
                    ev_counter[0] += 1
                    events.append(
                        StateEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            state=m_state.group(1),
                        )
                    )
                    continue

                # 3b. label "..."
                m_lbl = re.match(r'^label\s+"([^"]+)"$', cmd)
                if m_lbl:
                    ev_counter[0] += 1
                    events.append(
                        LabelEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            text=m_lbl.group(1),
                        )
                    )
                    continue

                # 3c. move from <wpA> to <wpB> [via [...]] [max_speed: ...] [easing ...] [resources...]
                m_move = re.match(r"^move\s+from\s+(\w+)\s+to\s+(\w+)(.*)$", cmd)
                if m_move:
                    wp_a, wp_b, rest = m_move.group(1), m_move.group(2), m_move.group(3)
                    if wp_a not in waypoints or wp_b not in waypoints:
                        raise ValueError(f"Move references unknown waypoint: '{wp_a}' or '{wp_b}'")

                    via_pts: List[Point2D] = []
                    via_m = re.search(r"via\s*\[([^\]]+)\]", rest)
                    if via_m:
                        via_pts = parse_point_list(via_m.group(1))

                    easing_m = re.search(r"easing\s+(linear|ease_in|ease_out|ease_in_out)", rest)
                    speed_m = re.search(r"max_speed:\s*(\d+(?:\.\d+)?)m/s", rest)

                    ev_counter[0] += 1
                    events.append(
                        MoveEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            from_waypoint_id=wp_a,
                            to_waypoint_id=wp_b,
                            path=[waypoints[wp_a].pos, *via_pts, waypoints[wp_b].pos],
                            easing=easing_m.group(1) if easing_m else "linear",
                            max_speed_mps=float(speed_m.group(1)) if speed_m else None,
                        )
                    )
                    # Also extract any inline drain/recharge/generate clauses attached to the move
                    events.extend(
                        parse_resource_deltas(
                            rest, block_id, phase_id, start_ms, end_ms, asset_id, ev_counter
                        )
                    )
                    continue

                # 3d. Standalone resource deltas (drain / recharge / generate)
                res_events = parse_resource_deltas(
                    cmd, block_id, phase_id, start_ms, end_ms, asset_id, ev_counter
                )
                if res_events:
                    events.extend(res_events)
                    continue

                raise ValueError(f"Unrecognized command for '{asset_id}': '{cmd}'")

        if phase_starts:
            phases.append(
                Phase(
                    id=phase_id,
                    name=phase_name,
                    start_ms=min(phase_starts),
                    end_ms=max(phase_ends),
                )
            )

    events.sort(key=lambda e: e.start_ms)
    return phases, events


# ---------------------------------------------------------------------------
# 4. Top-Level Compiler Entrypoint & CLI
# ---------------------------------------------------------------------------

def compile_simline(source_text: str) -> SimLineTimeline:
    clean_text = strip_comments(source_text)
    top_blocks = extract_named_blocks(clean_text)

    scene: Optional[Scene] = None
    waypoints: Dict[str, Waypoint] = {}
    zones: List[Zone] = []
    windows: List[CommWindow] = []
    assets: Dict[str, Asset] = {}
    timeline_body: Optional[str] = None

    for header, body in top_blocks:
        if header.startswith("scene"):
            scene = parse_scene(header, body)
        elif header == "waypoints":
            waypoints = parse_waypoints(body)
        elif header == "zones":
            zones = parse_zones(body)
        elif header == "windows":
            windows = parse_windows(body)
        elif header == "assets":
            assets = parse_assets(body, waypoints)
        elif header == "timeline":
            timeline_body = body

    if scene is None:
        raise ValueError("Missing required 'scene' block.")
    if timeline_body is None:
        raise ValueError("Missing required 'timeline' block.")

    phases, events = parse_timeline(timeline_body, waypoints)

    # Triggers full Pydantic v2 schema + referential integrity validation
    return SimLineTimeline(
        scene=scene,
        waypoints=waypoints,
        zones=zones,
        windows=windows,
        assets=assets,
        phases=phases,
        events=events,
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Compile SimLine DSL to validated timeline JSON.")
    parser.add_argument("input", type=Path, help="Path to .simline DSL file")
    parser.add_argument("-o", "--output", type=Path, help="Output JSON path (defaults to stdout)")
    args = parser.parse_args()

    source = args.input.read_text(encoding="utf-8")
    timeline = compile_simline(source)
    json_out = timeline.model_dump_json(indent=2)

    if args.output:
        args.output.write_text(json_out, encoding="utf-8")
        print(f"Compiled {len(timeline.events)} events across {len(timeline.phases)} phases -> {args.output}")
    else:
        print(json_out)


if __name__ == "__main__":
    main()

Running the Compiler

Save the Lunar EVA script as shackleton_eva1.simline in the same directory as simline_schema.py and simline_compiler.py, then run:

python simline_compiler.py shackleton_eva1.simline -o shackleton_eva1.json

If any waypoint ID, asset ID, resource name, static asset mutation, or after <id> dependency is invalid, Pydantic v2 or the compiler will halt with a descriptive error before writing the JSON file.


Build a single-file HTML/CSS/JS playback viewer which loads a JSON file and plays it back, with simulation controls and statistics panels

Below is a complete, zero-dependency, single-file HTML/CSS/JS playback viewer (simline_viewer.html). Save it locally and open it in any browser.

It uses a requestAnimationFrame loop driven by DOMHighResTimeStamp with delta-time clamping (<= 250ms) so switching browser tabs never causes simulation jumps. It supports loading any JSON file exported by simline_compiler.py and includes a Load Sample EVA button with the compiled Shackleton Rim mission pre-embedded for immediate testing.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SimLine — Lunar Surface Operations Playback Viewer</title>
<style>
  :root {
    --bg: #0b0f17;
    --panel: #131a26;
    --panel-border: #233044;
    --text: #e2e8f0;
    --muted: #8b9bb4;
    --accent: #38bdf8;
    --ok: #22c55e;
    --warn: #f59e0b;
    --danger: #ef4444;
    --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    --font-sans: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: var(--font-sans);
    height: 100vh;
    display: grid;
    grid-template-rows: 52px 1fr 112px;
    overflow: hidden;
  }

  /* Header */
  header {
    background: var(--panel);
    border-bottom: 1px solid var(--panel-border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    gap: 12px;
  }
  .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: 0.4px; }
  .brand span.tag {
    font-size: 11px; font-family: var(--font-mono);
    background: #1e293b; color: var(--accent);
    padding: 2px 7px; border-radius: 4px; border: 1px solid #334155;
  }
  .header-actions { display: flex; align-items: center; gap: 8px; }
  button, .file-btn {
    background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 6px;
    padding: 6px 12px; font-size: 13px; cursor: pointer;
    transition: background 0.15s, border-color 0.15s;
  }
  button:hover, .file-btn:hover { background: #273549; border-color: var(--accent); }
  button.primary { background: #0284c7; border-color: #38bdf8; color: #fff; font-weight: 600; }
  button.primary:hover { background: #0369a1; }
  input[type="file"] { display: none; }

  /* Main Workspace */
  main {
    display: grid;
    grid-template-columns: 1fr 360px;
    overflow: hidden;
  }
  .viewport {
    position: relative;
    background: #070a0f;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }
  canvas {
    display: block;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 0 0 1px var(--panel-border);
  }
  .overlay-hud {
    position: absolute;
    top: 12px; left: 12px;
    background: rgba(11, 15, 23, 0.85);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 8px 12px;
    font-family: var(--font-mono);
    font-size: 12px;
    pointer-events: none;
  }
  .overlay-hud .met { font-size: 18px; font-weight: 700; color: var(--accent); }
  .overlay-hud .phase-lbl { color: var(--muted); margin-top: 2px; }

  /* Sidebar Statistics Panels */
  aside {
    background: var(--panel);
    border-left: 1px solid var(--panel-border);
    overflow-y: auto;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  .card {
    background: #0e141f;
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 10px 12px;
  }
  .card h3 {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    color: var(--muted);
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
  }
  .stat-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  .stat-box {
    background: #131c2b;
    border: 1px solid #1e293b;
    border-radius: 6px;
    padding: 6px 8px;
  }
  .stat-box .lbl { font-size: 10px; color: var(--muted); text-transform: uppercase; }
  .stat-box .val { font-size: 15px; font-family: var(--font-mono); font-weight: 700; margin-top: 2px; }

  /* Resource Bars */
  .asset-group { margin-bottom: 10px; }
  .asset-group:last-child { margin-bottom: 0; }
  .asset-hdr {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 12px; font-weight: 600; margin-bottom: 4px;
  }
  .badge {
    font-size: 10px; font-family: var(--font-mono);
    padding: 1px 6px; border-radius: 4px;
    background: #1e293b; color: var(--accent);
  }
  .badge.ok { background: rgba(34,197,94,0.15); color: var(--ok); }
  .badge.warn { background: rgba(245,158,11,0.15); color: var(--warn); }
  .badge.danger { background: rgba(239,68,68,0.2); color: var(--danger); }

  .res-row { margin-bottom: 5px; }
  .res-meta {
    display: flex; justify-content: space-between;
    font-size: 11px; font-family: var(--font-mono); color: var(--muted);
    margin-bottom: 2px;
  }
  .bar-track {
    height: 6px; background: #1e293b; border-radius: 3px; overflow: hidden;
  }
  .bar-fill { height: 100%; background: var(--accent); transition: width 0.08s linear; }
  .bar-fill.ok { background: var(--ok); }
  .bar-fill.warn { background: var(--warn); }
  .bar-fill.danger { background: var(--danger); }

  /* Event & Alert Lists */
  .list-item {
    font-size: 11px; font-family: var(--font-mono);
    padding: 5px 7px; border-radius: 4px;
    background: #131c2b; margin-bottom: 4px;
    border-left: 3px solid var(--accent);
  }
  .list-item.alert { border-left-color: var(--warn); color: #fde68a; }
  .list-item.danger { border-left-color: var(--danger); color: #fecaca; }

  /* Footer Playback Controls */
  footer {
    background: var(--panel);
    border-top: 1px solid var(--panel-border);
    padding: 10px 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 8px;
  }
  .scrubber-row { display: flex; align-items: center; gap: 12px; }
  .scrubber-row input[type="range"] { flex: 1; accent-color: var(--accent); cursor: pointer; }
  .time-readout { font-family: var(--font-mono); font-size: 12px; color: var(--muted); min-width: 135px; text-align: right; }

  .controls-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
  }
  .btn-group { display: flex; align-items: center; gap: 6px; }
  .phase-pills { display: flex; gap: 6px; overflow-x: auto; max-width: 55%; }
  .phase-pill {
    font-size: 11px; padding: 4px 8px; white-space: nowrap;
    background: #131c2b; border: 1px solid #233044; color: var(--muted);
  }
  .phase-pill.active { border-color: var(--accent); color: var(--text); background: #1e293b; }
  select {
    background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 6px;
    padding: 5px 8px; font-size: 12px; font-family: var(--font-mono);
  }
</style>
</head>
<body>

<header>
  <div class="brand">
    <span>SimLine Playback Viewer</span>
    <span class="tag" id="sceneTag">NO FILE LOADED</span>
  </div>
  <div class="header-actions">
    <label class="file-btn">
      Load Compiled JSON
      <input type="file" id="fileInput" accept=".json" />
    </label>
    <button class="primary" id="btnLoadSample">Load Sample Lunar EVA</button>
  </div>
</header>

<main>
  <section class="viewport">
    <canvas id="simCanvas" width="900" height="900"></canvas>
    <div class="overlay-hud">
      <div class="met" id="hudMet">MET 00:00:00</div>
      <div class="phase-lbl" id="hudPhase">Load a timeline JSON to begin</div>
    </div>
  </section>

  <aside>
    <div class="card">
      <h3>Mission Telemetry <span id="commBadge" class="badge">COMM: --</span></h3>
      <div class="stat-grid">
        <div class="stat-box">
          <div class="lbl">Active Events</div>
          <div class="val" id="statActiveEvents">0</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Total Distance</div>
          <div class="val" id="statTotalDist">0 m</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Comm Bandwidth</div>
          <div class="val" id="statBandwidth">0 Mbps</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Progress</div>
          <div class="val" id="statProgress">0.0%</div>
        </div>
      </div>
    </div>

    <div class="card">
      <h3>Asset Resources &amp; States</h3>
      <div id="resourcePanel"><div class="res-meta">No assets loaded.</div></div>
    </div>

    <div class="card">
      <h3>Zone &amp; Constraint Alerts</h3>
      <div id="alertPanel"><div class="res-meta">Nominal — no active alerts.</div></div>
    </div>

    <div class="card">
      <h3>Active Timeline Events</h3>
      <div id="eventPanel"><div class="res-meta">No active events.</div></div>
    </div>
  </aside>
</main>

<footer>
  <div class="scrubber-row">
    <input type="range" id="scrubber" min="0" max="1000" value="0" step="100" />
    <div class="time-readout" id="timeReadout">00:00:00 / 00:00:00</div>
  </div>
  <div class="controls-row">
    <div class="btn-group">
      <button id="btnReset" title="Reset to MET 00:00:00">&#x23EE; Reset</button>
      <button id="btnStepBack" title="Step back 1 min">-1m</button>
      <button id="btnPlayPause" class="primary">&#x25B6; Play</button>
      <button id="btnStepFwd" title="Step forward 1 min">+1m</button>
      <select id="speedSelect" title="Simulation Speed">
        <option value="1">1x (Real-time)</option>
        <option value="10">10x</option>
        <option value="60">60x (1m/s)</option>
        <option value="120" selected>120x (2m/s)</option>
        <option value="300">300x (5m/s)</option>
      </select>
    </div>
    <div class="phase-pills" id="phasePills"></div>
  </div>
</footer>

<script>
(() => {
  // -------------------------------------------------------------------------
  // State & DOM References
  // -------------------------------------------------------------------------
  const canvas = document.getElementById("simCanvas");
  const ctx = canvas.getContext("2d");

  const el = {
    sceneTag: document.getElementById("sceneTag"),
    fileInput: document.getElementById("fileInput"),
    btnLoadSample: document.getElementById("btnLoadSample"),
    hudMet: document.getElementById("hudMet"),
    hudPhase: document.getElementById("hudPhase"),
    commBadge: document.getElementById("commBadge"),
    statActiveEvents: document.getElementById("statActiveEvents"),
    statTotalDist: document.getElementById("statTotalDist"),
    statBandwidth: document.getElementById("statBandwidth"),
    statProgress: document.getElementById("statProgress"),
    resourcePanel: document.getElementById("resourcePanel"),
    alertPanel: document.getElementById("alertPanel"),
    eventPanel: document.getElementById("eventPanel"),
    scrubber: document.getElementById("scrubber"),
    timeReadout: document.getElementById("timeReadout"),
    btnReset: document.getElementById("btnReset"),
    btnStepBack: document.getElementById("btnStepBack"),
    btnPlayPause: document.getElementById("btnPlayPause"),
    btnStepFwd: document.getElementById("btnStepFwd"),
    speedSelect: document.getElementById("speedSelect"),
    phasePills: document.getElementById("phasePills"),
  };

  let simData = null;
  let bgImage = null;
  let isPlaying = false;
  let currentMs = 0;
  let speedMultiplier = 120;
  let lastFrameTime = null;

  // -------------------------------------------------------------------------
  // Formatting & Math Helpers
  // -------------------------------------------------------------------------
  function formatMET(ms) {
    const totalSec = Math.max(0, Math.floor(ms / 1000));
    const h = String(Math.floor(totalSec / 3600)).padStart(2, "0");
    const m = String(Math.floor((totalSec % 3600) / 60)).padStart(2, "0");
    const s = String(totalSec % 60).padStart(2, "0");
    return `${h}:${m}:${s}`;
  }

  function applyEasing(t, type) {
    if (type === "ease_in") return t * t;
    if (type === "ease_out") return t * (2 - t);
    if (type === "ease_in_out") return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    return t;
  }

  function polylineLength(pts) {
    let len = 0;
    for (let i = 1; i < pts.length; i++) {
      len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    }
    return len;
  }

  function samplePolyline(pts, fraction) {
    if (pts.length === 0) return [0, 0];
    if (fraction <= 0) return pts[0];
    if (fraction >= 1) return pts[pts.length - 1];
    const total = polylineLength(pts);
    let target = total * fraction;
    for (let i = 1; i < pts.length; i++) {
      const seg = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
      if (target <= seg && seg > 0) {
        const u = target / seg;
        return [
          pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * u,
          pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * u,
        ];
      }
      target -= seg;
    }
    return pts[pts.length - 1];
  }

  function pointInPolygon(pt, vs) {
    const [x, y] = pt;
    let inside = false;
    for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
      const [xi, yi] = vs[i], [xj, yj] = vs[j];
      const intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }
    return inside;
  }

  function pointInZone(pt, zone) {
    if (zone.geometry.shape === "circle") {
      const [cx, cy] = zone.geometry.center;
      return Math.hypot(pt[0] - cx, pt[1] - cy) <= zone.geometry.radius_px;
    }
    return pointInPolygon(pt, zone.geometry.points);
  }

  // -------------------------------------------------------------------------
  // Deterministic State Evaluator at Timestamp `t`
  // -------------------------------------------------------------------------
  function evaluateState(data, t) {
    const assetState = {};
    let totalDistPx = 0;

    // 1. Initialize assets
    for (const [id, spec] of Object.entries(data.assets)) {
      const resources = {};
      for (const [rKey, rSpec] of Object.entries(spec.resources || {})) {
        resources[rKey] = { ...rSpec, value: rSpec.initial };
      }
      assetState[id] = {
        id,
        ...spec,
        pos: [...spec.start_pos],
        parent: null,
        state: spec.is_static ? "static" : "idle",
        label: "",
        resources,
      };
    }

    const activeEvents = [];
    const activeMovePaths = [];

    // 2. Sweep chronologically sorted events up to timestamp t
    for (const ev of data.events) {
      if (ev.start_ms > t) break;
      const a = assetState[ev.target_asset_id];
      if (!a) continue;

      const isActive = t >= ev.start_ms && t <= ev.end_ms;
      if (isActive) activeEvents.push(ev);

      if (ev.type === "move") {
        const dur = Math.max(1, ev.end_ms - ev.start_ms);
        const frac = Math.min(1, Math.max(0, (t - ev.start_ms) / dur));
        const eased = applyEasing(frac, ev.easing);
        a.pos = samplePolyline(ev.path, eased);
        totalDistPx += polylineLength(ev.path) * eased;
        if (isActive) activeMovePaths.push(ev.path);
      } else if (ev.type === "attach") {
        a.parent = ev.parent_asset_id;
      } else if (ev.type === "detach") {
        a.parent = null;
        if (ev.detach_pos) a.pos = [...ev.detach_pos];
      } else if (ev.type === "state") {
        a.state = ev.state;
      } else if (ev.type === "label") {
        if (isActive) a.label = ev.text;
      } else if (ev.type === "resource_delta") {
        const elapsedMs = Math.min(t, ev.end_ms) - ev.start_ms;
        if (elapsedMs > 0 && a.resources[ev.resource]) {
          a.resources[ev.resource].value += ev.rate_per_min * (elapsedMs / 60000);
        }
      }
    }

    // 3. Resolve parent-child coordinate inheritance
    for (const a of Object.values(assetState)) {
      if (a.parent && assetState[a.parent]) {
        a.pos = [...assetState[a.parent].pos];
      }
    }

    // 4. Evaluate active comm windows, phase, and zone alerts
    const activePhase = data.phases.find(p => t >= p.start_ms && t <= p.end_ms) || null;
    const activeWindow = (data.windows || []).find(w => t >= w.start_ms && t <= w.end_ms) || null;

    const alerts = [];
    for (const a of Object.values(assetState)) {
      if (a.is_static) continue;
      for (const z of data.zones || []) {
        if (pointInZone(a.pos, z)) {
          if (z.type === "hazard") {
            alerts.push({ level: "danger", text: `${a.id} inside HAZARD zone (${z.id})` });
          } else if (z.type === "shadow") {
            alerts.push({ level: "alert", text: `${a.id} in PSR shadow (${z.id})` });
          }
        }
      }
      for (const [rKey, r] of Object.entries(a.resources)) {
        if (r.min != null && r.value < r.min) {
          alerts.push({ level: "danger", text: `${a.id} ${rKey} BELOW MIN (${r.value.toFixed(1)}${r.unit})` });
        }
        if (r.max != null && r.value > r.max) {
          alerts.push({ level: "danger", text: `${a.id} ${rKey} EXCEEDS MAX (${r.value.toFixed(1)}${r.unit})` });
        }
      }
    }

    const scale = data.scene.scale_m_per_px || 1;
    return {
      assetState,
      activeEvents,
      activeMovePaths,
      activePhase,
      activeWindow,
      alerts,
      totalDistM: totalDistPx * scale,
    };
  }

  // -------------------------------------------------------------------------
  // 2D Canvas Renderer
  // -------------------------------------------------------------------------
  function render(state) {
    if (!simData) return;
    const { width, height } = simData.scene.dimensions;
    const scaleX = canvas.width / width;
    const scaleY = canvas.height / height;
    const s = Math.min(scaleX, scaleY);

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.scale(s, s);

    // 1. Background image or procedural lunar grid
    if (bgImage && bgImage.complete && bgImage.naturalWidth > 0) {
      ctx.drawImage(bgImage, 0, 0, width, height);
    } else {
      ctx.fillStyle = "#0d1117";
      ctx.fillRect(0, 0, width, height);
      ctx.strokeStyle = "rgba(148, 163, 184, 0.08)";
      ctx.lineWidth = 2;
      const step = Math.round(width / 16);
      for (let x = 0; x <= width; x += step) {
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke();
      }
      for (let y = 0; y <= height; y += step) {
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke();
      }
    }

    // 2. Spatial Zones
    for (const z of simData.zones || []) {
      ctx.save();
      if (z.type === "shadow") {
        ctx.fillStyle = "rgba(30, 58, 138, 0.35)";
        ctx.strokeStyle = "#60a5fa";
      } else if (z.type === "hazard") {
        ctx.fillStyle = "rgba(239, 68, 68, 0.18)";
        ctx.strokeStyle = "#ef4444";
      } else {
        ctx.fillStyle = "rgba(250, 204, 21, 0.15)";
        ctx.strokeStyle = "#facc15";
      }
      ctx.lineWidth = 3;
      ctx.setLineDash([12, 8]);
      ctx.beginPath();
      if (z.geometry.shape === "circle") {
        const [cx, cy] = z.geometry.center;
        ctx.arc(cx, cy, z.geometry.radius_px, 0, Math.PI * 2);
      } else {
        z.geometry.points.forEach((p, idx) => idx === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
        ctx.closePath();
      }
      ctx.fill();
      ctx.stroke();
      ctx.restore();
    }

    // 3. All Planned Move Paths (faint) & Active Paths (bright)
    for (const ev of simData.events) {
      if (ev.type !== "move") continue;
      ctx.save();
      ctx.strokeStyle = "rgba(148, 163, 184, 0.25)";
      ctx.lineWidth = 4;
      ctx.setLineDash([10, 10]);
      ctx.beginPath();
      ev.path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      ctx.stroke();
      ctx.restore();
    }
    for (const path of state.activeMovePaths) {
      ctx.save();
      ctx.strokeStyle = "#38bdf8";
      ctx.lineWidth = 6;
      ctx.beginPath();
      path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      ctx.stroke();
      ctx.restore();
    }

    // 4. Waypoints
    for (const [id, wp] of Object.entries(simData.waypoints)) {
      const [x, y] = wp.pos;
      ctx.save();
      ctx.fillStyle = "#f8fafc";
      ctx.strokeStyle = "#38bdf8";
      ctx.lineWidth = 4;
      ctx.beginPath();
      ctx.arc(x, y, 12, 0, Math.PI * 2);
      ctx.fill();
      ctx.stroke();

      ctx.font = "bold 26px system-ui, sans-serif";
      ctx.fillStyle = "#e2e8f0";
      ctx.fillText(wp.label, x + 20, y + 8);
      ctx.restore();
    }

    // 5. Assets (sorted by layer)
    const sortedAssets = Object.values(state.assetState).sort((a, b) => a.layer - b.layer);
    for (const a of sortedAssets) {
      if (a.parent) continue; // Rendered as docked badge on parent
      const [x, y] = a.pos;
      const color = a.is_static ? "#94a3b8" : a.tags.includes("vehicle") ? "#38bdf8" : a.tags.includes("crew") ? "#22c55e" : "#f59e0b";

      ctx.save();
      ctx.fillStyle = color;
      ctx.strokeStyle = "#0b0f17";
      ctx.lineWidth = 4;
      ctx.beginPath();
      if (a.tags.includes("vehicle") || a.is_static) {
        ctx.roundRect(x - 22, y - 22, 44, 44, 8);
      } else {
        ctx.arc(x, y, 18, 0, Math.PI * 2);
      }
      ctx.fill();
      ctx.stroke();

      // Label & State
      ctx.font = "bold 24px ui-monospace, monospace";
      ctx.fillStyle = "#ffffff";
      ctx.fillText(a.id, x - 26, y - 30);

      if (a.label) {
        ctx.font = "22px system-ui, sans-serif";
        ctx.fillStyle = "#fde047";
        ctx.fillText(a.label, x + 28, y - 4);
      }

      // Docked children indicator
      const children = sortedAssets.filter(c => c.parent === a.id);
      if (children.length > 0) {
        ctx.font = "bold 20px ui-monospace, monospace";
        ctx.fillStyle = "#38bdf8";
        ctx.fillText(`+${children.length} aboard`, x + 28, y + 22);
      }
      ctx.restore();
    }

    ctx.restore();
  }

  // -------------------------------------------------------------------------
  // HUD & Statistics Panel Updater
  // -------------------------------------------------------------------------
  function updateUI(state) {
    if (!simData) return;
    const dur = simData.scene.duration_ms || 1;
    el.hudMet.textContent = `MET ${formatMET(currentMs)}`;
    el.hudPhase.textContent = state.activePhase ? state.activePhase.name : "Between Phases";
    el.timeReadout.textContent = `${formatMET(currentMs)} / ${formatMET(dur)}`;
    el.scrubber.value = Math.round(currentMs);

    // Telemetry stats
    el.statActiveEvents.textContent = state.activeEvents.length;
    el.statTotalDist.textContent = `${Math.round(state.totalDistM).toLocaleString()} m`;
    el.statProgress.textContent = `${((currentMs / dur) * 100).toFixed(1)}%`;

    if (state.activeWindow) {
      el.commBadge.textContent = `COMM: ${state.activeWindow.id}`;
      el.commBadge.className = "badge ok";
      el.statBandwidth.textContent = `${state.activeWindow.bandwidth_mbps} Mbps`;
    } else {
      el.commBadge.textContent = "COMM: BLACKOUT";
      el.commBadge.className = "badge warn";
      el.statBandwidth.textContent = "0 Mbps";
    }

    // Phase pills highlight
    Array.from(el.phasePills.children).forEach(btn => {
      btn.classList.toggle("active", state.activePhase && btn.dataset.phaseId === state.activePhase.id);
    });

    // Resources panel
    el.resourcePanel.innerHTML = Object.values(state.assetState)
      .filter(a => !a.is_static)
      .map(a => {
        const resHtml = Object.entries(a.resources).map(([k, r]) => {
          const maxVal = r.max ?? 100;
          const pct = Math.min(100, Math.max(0, (r.value / maxVal) * 100));
          let cls = "ok";
          if ((r.min != null && r.value < r.min) || (r.max != null && r.value > r.max)) cls = "danger";
          else if (r.min != null && r.value < r.min + 15) cls = "warn";
          return `
            <div class="res-row">
              <div class="res-meta"><span>${k}</span><span>${r.value.toFixed(1)}${r.unit}</span></div>
              <div class="bar-track"><div class="bar-fill ${cls}" style="width:${pct}%"></div></div>
            </div>`;
        }).join("");
        const statusText = a.parent ? `aboard ${a.parent}` : a.state;
        return `
          <div class="asset-group">
            <div class="asset-hdr"><span>${a.id}</span><span class="badge">${statusText}</span></div>
            ${resHtml || '<div class="res-meta">No consumables</div>'}
          </div>`;
      }).join("");

    // Alerts panel
    el.alertPanel.innerHTML = state.alerts.length
      ? state.alerts.map(al => `<div class="list-item ${al.level}">${al.text}</div>`).join("")
      : '<div class="res-meta">Nominal — no active alerts.</div>';

    // Active events panel
    el.eventPanel.innerHTML = state.activeEvents.length
      ? state.activeEvents.map(ev => `<div class="list-item">[${ev.type}] ${ev.target_asset_id} (${ev.id})</div>`).join("")
      : '<div class="res-meta">No active events at this timestamp.</div>';
  }

  // -------------------------------------------------------------------------
  // Main Playback Loop
  // -------------------------------------------------------------------------
  function tick(now) {
    if (isPlaying && simData) {
      if (lastFrameTime !== null) {
        const dtMs = Math.min(250, now - lastFrameTime); // Clamp delta to prevent tab-switch jumps
        currentMs += dtMs * speedMultiplier;
        if (currentMs >= simData.scene.duration_ms) {
          currentMs = simData.scene.duration_ms;
          setPlaying(false);
        }
      }
      lastFrameTime = now;
      const state = evaluateState(simData, currentMs);
      render(state);
      updateUI(state);
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);

  function setPlaying(play) {
    isPlaying = play;
    lastFrameTime = null;
    el.btnPlayPause.innerHTML = isPlaying ? "&#x23F8; Pause" : "&#x25B6; Play";
  }

  function loadTimeline(jsonObj) {
    simData = jsonObj;
    currentMs = 0;
    setPlaying(false);
    el.sceneTag.textContent = simData.scene.id;
    el.scrubber.max = simData.scene.duration_ms;

    // Attempt to load background image if path resolves locally
    bgImage = new Image();
    bgImage.src = simData.scene.background;

    // Build phase jump buttons
    el.phasePills.innerHTML = "";
    for (const p of simData.phases) {
      const btn = document.createElement("button");
      btn.className = "phase-pill";
      btn.textContent = p.name;
      btn.dataset.phaseId = p.id;
      btn.onclick = () => {
        currentMs = p.start_ms;
        const st = evaluateState(simData, currentMs);
        render(st); updateUI(st);
      };
      el.phasePills.appendChild(btn);
    }

    const st = evaluateState(simData, currentMs);
    render(st);
    updateUI(st);
  }

  // -------------------------------------------------------------------------
  // Event Listeners
  // -------------------------------------------------------------------------
  el.fileInput.addEventListener("change", (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try { loadTimeline(JSON.parse(ev.target.result)); }
      catch (err) { alert("Invalid JSON file: " + err.message); }
    };
    reader.readAsText(file);
  });

  el.btnPlayPause.onclick = () => {
    if (!simData) return;
    if (currentMs >= simData.scene.duration_ms) currentMs = 0;
    setPlaying(!isPlaying);
  };
  el.btnReset.onclick = () => {
    if (!simData) return;
    setPlaying(false); currentMs = 0;
    const st = evaluateState(simData, currentMs); render(st); updateUI(st);
  };
  el.btnStepBack.onclick = () => {
    if (!simData) return;
    currentMs = Math.max(0, currentMs - 60000);
    const st = evaluateState(simData, currentMs); render(st); updateUI(st);
  };
  el.btnStepFwd.onclick = () => {
    if (!simData) return;
    currentMs = Math.min(simData.scene.duration_ms, currentMs + 60000);
    const st = evaluateState(simData, currentMs); render(st); updateUI(st);
  };
  el.speedSelect.onchange = (e) => { speedMultiplier = Number(e.target.value); };
  el.scrubber.oninput = (e) => {
    if (!simData) return;
    currentMs = Number(e.target.value);
    const st = evaluateState(simData, currentMs); render(st); updateUI(st);
  };

  // -------------------------------------------------------------------------
  // Embedded Sample Lunar EVA Timeline (Compiled Shackleton Rim EVA-1)
  // -------------------------------------------------------------------------
  const SAMPLE_TIMELINE = {
    schema_version: "1.0.0",
    scene: { id: "ShackletonRim_EVA1", background: "", dimensions: { width: 2048, height: 2048 }, scale_m_per_px: 0.5, duration_ms: 7200000 },
    waypoints: {
      lander_pad: { pos: [320, 1680], label: "HLS Lander Pad" },
      solar_ridge: { pos: [740, 1220], label: "Connecting Ridge" },
      shackleton_rim: { pos: [1420, 680], label: "Station 1: Shackleton Rim" },
      psr_edge: { pos: [1580, 560], label: "Station 2: PSR Edge" }
    },
    zones: [
      { id: "psr_crater_floor", type: "shadow", geometry: { shape: "polygon", points: [[1540,480],[1950,420],[1980,820],[1610,690]] } },
      { id: "lander_blast_koz", type: "hazard", geometry: { shape: "circle", center: [320,1680], radius_px: 90 } },
      { id: "ridge_sunlight_corridor", type: "solar_rich", geometry: { shape: "polygon", points: [[580,1380],[920,1080],[1010,1180],[670,1480]] } }
    ],
    windows: [{ id: "lunar_relay_pass_1", start_ms: 3300000, end_ms: 4800000, bandwidth_mbps: 50 }],
    assets: {
      hls_lander: { is_static: true, image: "", start_pos: [320,1680], layer: 1, tags: ["lander"], resources: {} },
      ltv_rover: { is_static: false, image: "", start_pos: [320,1680], layer: 2, tags: ["vehicle"], resources: { battery: { initial: 100, unit: "%", min: 20, max: 100 }, data_buffer: { initial: 0, unit: "GB", min: 0, max: 64 } } },
      astronaut_1: { is_static: false, image: "", start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      astronaut_2: { is_static: false, image: "", start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      seismometer_pkg: { is_static: false, image: "", start_pos: [320,1680], layer: 2, tags: ["payload"], resources: {} }
    },
    phases: [
      { id: "eva_1", name: "EVA-1: Egress & Prep", start_ms: 0, end_ms: 900000 },
      { id: "eva_2", name: "EVA-2: Outbound Traverse", start_ms: 900000, end_ms: 2700000 },
      { id: "eva_3", name: "EVA-3: Rim Science", start_ms: 2700000, end_ms: 4800000 },
      { id: "eva_4", name: "EVA-4: Return & Closeout", start_ms: 4800000, end_ms: 7200000 }
    ],
    events: [
      { id: "e1", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e2", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e3", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e4", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e5", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "seismometer_pkg", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e6", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "move", path: [[320,1680],[520,1480],[740,1220],[1120,910],[1420,680]], easing: "ease_in_out" },
      { id: "e7", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.8 },
      { id: "e8", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: 0.3 },
      { id: "e9", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e10", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e11", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e12", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e13", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "seismometer_pkg", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e14", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "move", path: [[1420,680],[1580,560]], easing: "linear" },
      { id: "e15", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "label", text: "Core Sampling at PSR Edge" },
      { id: "e16", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.6 },
      { id: "e17", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "state", state: "downlinking" },
      { id: "e18", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: -0.9 },
      { id: "e19", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "astronaut_2", type: "move", path: [[1580,560],[1420,680]], easing: "linear" },
      { id: "e20", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e21", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e22", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "move", path: [[1420,680],[1120,910],[740,1220],[520,1480],[320,1680]], easing: "ease_in_out" },
      { id: "e23", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.75 },
      { id: "e24", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e25", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e26", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: 1.5 }
    ]
  };

  el.btnLoadSample.onclick = () => loadTimeline(SAMPLE_TIMELINE);
  loadTimeline(SAMPLE_TIMELINE);
})();
</script>
</body>
</html>


Add mouse-wheel zoom, click-and-drag pan, and custom sprite image rendering to simline_viewer.html.

This updated simline_viewer.html adds three capabilities to the playback engine:

  • Cursor-Centered Mouse-Wheel Zoom: Scroll up/down over the canvas to zoom (0.4x–8.0x) pinned to the cursor position, with a live zoom readout and a Reset View button.

  • Click-and-Drag Panning: Drag anywhere on the canvas to pan across the lunar map (works while paused or playing).

  • Custom Sprite Rendering + Local Asset Loader: Automatically renders asset.image and waypoint.image sprites when available (with embedded SVG sprites in the sample mission) and includes a Load Sprites / Map multi-file picker that matches local PNG/SVG files by filename to bypass browser local-path restrictions.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SimLine — Lunar Surface Operations Playback Viewer</title>
<style>
  :root {
    --bg: #0b0f17;
    --panel: #131a26;
    --panel-border: #233044;
    --text: #e2e8f0;
    --muted: #8b9bb4;
    --accent: #38bdf8;
    --ok: #22c55e;
    --warn: #f59e0b;
    --danger: #ef4444;
    --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    --font-sans: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: var(--font-sans);
    height: 100vh;
    display: grid;
    grid-template-rows: 52px 1fr 112px;
    overflow: hidden;
  }

  /* Header */
  header {
    background: var(--panel);
    border-bottom: 1px solid var(--panel-border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    gap: 12px;
  }
  .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: 0.4px; }
  .brand span.tag {
    font-size: 11px; font-family: var(--font-mono);
    background: #1e293b; color: var(--accent);
    padding: 2px 7px; border-radius: 4px; border: 1px solid #334155;
  }
  .header-actions { display: flex; align-items: center; gap: 8px; }
  button, .file-btn {
    background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 6px;
    padding: 6px 12px; font-size: 13px; cursor: pointer;
    transition: background 0.15s, border-color 0.15s;
  }
  button:hover, .file-btn:hover { background: #273549; border-color: var(--accent); }
  button.primary { background: #0284c7; border-color: #38bdf8; color: #fff; font-weight: 600; }
  button.primary:hover { background: #0369a1; }
  input[type="file"] { display: none; }

  /* Main Workspace */
  main {
    display: grid;
    grid-template-columns: 1fr 360px;
    overflow: hidden;
  }
  .viewport {
    position: relative;
    background: #070a0f;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    user-select: none;
  }
  canvas {
    display: block;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 0 0 1px var(--panel-border);
    cursor: grab;
  }
  canvas.dragging { cursor: grabbing; }
  .overlay-hud {
    position: absolute;
    top: 12px; left: 12px;
    background: rgba(11, 15, 23, 0.85);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 8px 12px;
    font-family: var(--font-mono);
    font-size: 12px;
    pointer-events: none;
  }
  .overlay-hud .met { font-size: 18px; font-weight: 700; color: var(--accent); }
  .overlay-hud .phase-lbl { color: var(--muted); margin-top: 2px; }

  .camera-hud {
    position: absolute;
    bottom: 12px; left: 12px;
    background: rgba(11, 15, 23, 0.88);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 6px 10px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-family: var(--font-mono);
    font-size: 11px;
    color: var(--muted);
  }
  .camera-hud button {
    padding: 3px 8px;
    font-size: 11px;
  }

  /* Sidebar Statistics Panels */
  aside {
    background: var(--panel);
    border-left: 1px solid var(--panel-border);
    overflow-y: auto;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  .card {
    background: #0e141f;
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 10px 12px;
  }
  .card h3 {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    color: var(--muted);
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
  }
  .stat-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  .stat-box {
    background: #131c2b;
    border: 1px solid #1e293b;
    border-radius: 6px;
    padding: 6px 8px;
  }
  .stat-box .lbl { font-size: 10px; color: var(--muted); text-transform: uppercase; }
  .stat-box .val { font-size: 15px; font-family: var(--font-mono); font-weight: 700; margin-top: 2px; }

  /* Resource Bars */
  .asset-group { margin-bottom: 10px; }
  .asset-group:last-child { margin-bottom: 0; }
  .asset-hdr {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 12px; font-weight: 600; margin-bottom: 4px;
  }
  .badge {
    font-size: 10px; font-family: var(--font-mono);
    padding: 1px 6px; border-radius: 4px;
    background: #1e293b; color: var(--accent);
  }
  .badge.ok { background: rgba(34,197,94,0.15); color: var(--ok); }
  .badge.warn { background: rgba(245,158,11,0.15); color: var(--warn); }
  .badge.danger { background: rgba(239,68,68,0.2); color: var(--danger); }

  .res-row { margin-bottom: 5px; }
  .res-meta {
    display: flex; justify-content: space-between;
    font-size: 11px; font-family: var(--font-mono); color: var(--muted);
    margin-bottom: 2px;
  }
  .bar-track {
    height: 6px; background: #1e293b; border-radius: 3px; overflow: hidden;
  }
  .bar-fill { height: 100%; background: var(--accent); transition: width 0.08s linear; }
  .bar-fill.ok { background: var(--ok); }
  .bar-fill.warn { background: var(--warn); }
  .bar-fill.danger { background: var(--danger); }

  /* Event & Alert Lists */
  .list-item {
    font-size: 11px; font-family: var(--font-mono);
    padding: 5px 7px; border-radius: 4px;
    background: #131c2b; margin-bottom: 4px;
    border-left: 3px solid var(--accent);
  }
  .list-item.alert { border-left-color: var(--warn); color: #fde68a; }
  .list-item.danger { border-left-color: var(--danger); color: #fecaca; }

  /* Footer Playback Controls */
  footer {
    background: var(--panel);
    border-top: 1px solid var(--panel-border);
    padding: 10px 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 8px;
  }
  .scrubber-row { display: flex; align-items: center; gap: 12px; }
  .scrubber-row input[type="range"] { flex: 1; accent-color: var(--accent); cursor: pointer; }
  .time-readout { font-family: var(--font-mono); font-size: 12px; color: var(--muted); min-width: 135px; text-align: right; }

  .controls-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
  }
  .btn-group { display: flex; align-items: center; gap: 6px; }
  .phase-pills { display: flex; gap: 6px; overflow-x: auto; max-width: 55%; }
  .phase-pill {
    font-size: 11px; padding: 4px 8px; white-space: nowrap;
    background: #131c2b; border: 1px solid #233044; color: var(--muted);
  }
  .phase-pill.active { border-color: var(--accent); color: var(--text); background: #1e293b; }
  select {
    background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 6px;
    padding: 5px 8px; font-size: 12px; font-family: var(--font-mono);
  }
</style>
</head>
<body>

<header>
  <div class="brand">
    <span>SimLine Playback Viewer</span>
    <span class="tag" id="sceneTag">NO FILE LOADED</span>
  </div>
  <div class="header-actions">
    <label class="file-btn" title="Select local PNG/SVG files matching asset or background filenames">
      Load Sprites / Map
      <input type="file" id="spriteInput" accept="image/*" multiple />
    </label>
    <label class="file-btn">
      Load Compiled JSON
      <input type="file" id="fileInput" accept=".json" />
    </label>
    <button class="primary" id="btnLoadSample">Load Sample Lunar EVA</button>
  </div>
</header>

<main>
  <section class="viewport">
    <canvas id="simCanvas" width="900" height="900"></canvas>
    <div class="overlay-hud">
      <div class="met" id="hudMet">MET 00:00:00</div>
      <div class="phase-lbl" id="hudPhase">Load a timeline JSON to begin</div>
    </div>
    <div class="camera-hud">
      <span>Scroll: Zoom &bull; Drag: Pan</span>
      <span id="zoomReadout" style="color: var(--accent); font-weight: 700;">100%</span>
      <button id="btnResetView">Reset View</button>
    </div>
  </section>

  <aside>
    <div class="card">
      <h3>Mission Telemetry <span id="commBadge" class="badge">COMM: --</span></h3>
      <div class="stat-grid">
        <div class="stat-box">
          <div class="lbl">Active Events</div>
          <div class="val" id="statActiveEvents">0</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Total Distance</div>
          <div class="val" id="statTotalDist">0 m</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Comm Bandwidth</div>
          <div class="val" id="statBandwidth">0 Mbps</div>
        </div>
        <div class="stat-box">
          <div class="lbl">Progress</div>
          <div class="val" id="statProgress">0.0%</div>
        </div>
      </div>
    </div>

    <div class="card">
      <h3>Asset Resources &amp; States</h3>
      <div id="resourcePanel"><div class="res-meta">No assets loaded.</div></div>
    </div>

    <div class="card">
      <h3>Zone &amp; Constraint Alerts</h3>
      <div id="alertPanel"><div class="res-meta">Nominal — no active alerts.</div></div>
    </div>

    <div class="card">
      <h3>Active Timeline Events</h3>
      <div id="eventPanel"><div class="res-meta">No active events.</div></div>
    </div>
  </aside>
</main>

<footer>
  <div class="scrubber-row">
    <input type="range" id="scrubber" min="0" max="1000" value="0" step="100" />
    <div class="time-readout" id="timeReadout">00:00:00 / 00:00:00</div>
  </div>
  <div class="controls-row">
    <div class="btn-group">
      <button id="btnReset" title="Reset to MET 00:00:00">&#x23EE; Reset</button>
      <button id="btnStepBack" title="Step back 1 min">-1m</button>
      <button id="btnPlayPause" class="primary">&#x25B6; Play</button>
      <button id="btnStepFwd" title="Step forward 1 min">+1m</button>
      <select id="speedSelect" title="Simulation Speed">
        <option value="1">1x (Real-time)</option>
        <option value="10">10x</option>
        <option value="60">60x (1m/s)</option>
        <option value="120" selected>120x (2m/s)</option>
        <option value="300">300x (5m/s)</option>
      </select>
    </div>
    <div class="phase-pills" id="phasePills"></div>
  </div>
</footer>

<script>
(() => {
  // -------------------------------------------------------------------------
  // State & DOM References
  // -------------------------------------------------------------------------
  const canvas = document.getElementById("simCanvas");
  const ctx = canvas.getContext("2d");

  const el = {
    sceneTag: document.getElementById("sceneTag"),
    fileInput: document.getElementById("fileInput"),
    spriteInput: document.getElementById("spriteInput"),
    btnLoadSample: document.getElementById("btnLoadSample"),
    hudMet: document.getElementById("hudMet"),
    hudPhase: document.getElementById("hudPhase"),
    zoomReadout: document.getElementById("zoomReadout"),
    btnResetView: document.getElementById("btnResetView"),
    commBadge: document.getElementById("commBadge"),
    statActiveEvents: document.getElementById("statActiveEvents"),
    statTotalDist: document.getElementById("statTotalDist"),
    statBandwidth: document.getElementById("statBandwidth"),
    statProgress: document.getElementById("statProgress"),
    resourcePanel: document.getElementById("resourcePanel"),
    alertPanel: document.getElementById("alertPanel"),
    eventPanel: document.getElementById("eventPanel"),
    scrubber: document.getElementById("scrubber"),
    timeReadout: document.getElementById("timeReadout"),
    btnReset: document.getElementById("btnReset"),
    btnStepBack: document.getElementById("btnStepBack"),
    btnPlayPause: document.getElementById("btnPlayPause"),
    btnStepFwd: document.getElementById("btnStepFwd"),
    speedSelect: document.getElementById("speedSelect"),
    phasePills: document.getElementById("phasePills"),
  };

  let simData = null;
  let bgImage = null;
  const spriteCache = new Map(); // key: path, filename, or asset_id -> HTMLImageElement

  let isPlaying = false;
  let currentMs = 0;
  let speedMultiplier = 120;
  let lastFrameTime = null;

  // Camera state for pan & zoom
  const camera = {
    zoom: 1.0,
    minZoom: 0.4,
    maxZoom: 8.0,
    panX: 0,
    panY: 0,
    isDragging: false,
    dragStartX: 0,
    dragStartY: 0,
  };

  function getBaseScale() {
    if (!simData) return 1;
    const { width, height } = simData.scene.dimensions;
    return Math.min(canvas.width / width, canvas.height / height);
  }

  function resetCamera() {
    camera.zoom = 1.0;
    camera.panX = 0;
    camera.panY = 0;
    el.zoomReadout.textContent = "100%";
    redrawCurrent();
  }

  function redrawCurrent() {
    if (!simData) return;
    const st = evaluateState(simData, currentMs);
    render(st);
    updateUI(st);
  }

  // -------------------------------------------------------------------------
  // Sprite & Image Cache Helpers
  // -------------------------------------------------------------------------
  function basename(path) {
    if (!path) return "";
    return path.split(/[\\/]/).pop().toLowerCase();
  }

  function cacheImageSrc(key, src) {
    if (!src) return;
    const img = new Image();
    img.onload = () => redrawCurrent();
    img.src = src;
    spriteCache.set(key, img);
    const base = basename(src);
    if (base && !src.startsWith("data:")) {
      spriteCache.set(base, img);
    }
  }

  function getLoadedSprite(entityId, imagePath) {
    const candidates = [entityId, imagePath, basename(imagePath)];
    for (const key of candidates) {
      if (!key) continue;
      const img = spriteCache.get(key);
      if (img && img.complete && img.naturalWidth > 0) return img;
    }
    return null;
  }

  function preloadTimelineSprites(data) {
    bgImage = null;
    if (data.scene.background) {
      const existing = spriteCache.get(basename(data.scene.background));
      if (existing) {
        bgImage = existing;
      } else {
        bgImage = new Image();
        bgImage.onload = () => redrawCurrent();
        bgImage.src = data.scene.background;
      }
    }
    for (const [id, asset] of Object.entries(data.assets || {})) {
      if (asset.image) cacheImageSrc(id, asset.image);
    }
    for (const [id, wp] of Object.entries(data.waypoints || {})) {
      if (wp.image) cacheImageSrc(`wp:${id}`, wp.image);
    }
  }

  // -------------------------------------------------------------------------
  // Formatting & Math Helpers
  // -------------------------------------------------------------------------
  function formatMET(ms) {
    const totalSec = Math.max(0, Math.floor(ms / 1000));
    const h = String(Math.floor(totalSec / 3600)).padStart(2, "0");
    const m = String(Math.floor((totalSec % 3600) / 60)).padStart(2, "0");
    const s = String(totalSec % 60).padStart(2, "0");
    return `${h}:${m}:${s}`;
  }

  function applyEasing(t, type) {
    if (type === "ease_in") return t * t;
    if (type === "ease_out") return t * (2 - t);
    if (type === "ease_in_out") return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    return t;
  }

  function polylineLength(pts) {
    let len = 0;
    for (let i = 1; i < pts.length; i++) {
      len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    }
    return len;
  }

  function samplePolyline(pts, fraction) {
    if (pts.length === 0) return [0, 0];
    if (fraction <= 0) return pts[0];
    if (fraction >= 1) return pts[pts.length - 1];
    const total = polylineLength(pts);
    let target = total * fraction;
    for (let i = 1; i < pts.length; i++) {
      const seg = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
      if (target <= seg && seg > 0) {
        const u = target / seg;
        return [
          pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * u,
          pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * u,
        ];
      }
      target -= seg;
    }
    return pts[pts.length - 1];
  }

  function pointInPolygon(pt, vs) {
    const [x, y] = pt;
    let inside = false;
    for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
      const [xi, yi] = vs[i], [xj, yj] = vs[j];
      const intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }
    return inside;
  }

  function pointInZone(pt, zone) {
    if (zone.geometry.shape === "circle") {
      const [cx, cy] = zone.geometry.center;
      return Math.hypot(pt[0] - cx, pt[1] - cy) <= zone.geometry.radius_px;
    }
    return pointInPolygon(pt, zone.geometry.points);
  }

  // -------------------------------------------------------------------------
  // Deterministic State Evaluator at Timestamp `t`
  // -------------------------------------------------------------------------
  function evaluateState(data, t) {
    const assetState = {};
    let totalDistPx = 0;

    for (const [id, spec] of Object.entries(data.assets)) {
      const resources = {};
      for (const [rKey, rSpec] of Object.entries(spec.resources || {})) {
        resources[rKey] = { ...rSpec, value: rSpec.initial };
      }
      assetState[id] = {
        id,
        ...spec,
        pos: [...spec.start_pos],
        parent: null,
        state: spec.is_static ? "static" : "idle",
        label: "",
        resources,
      };
    }

    const activeEvents = [];
    const activeMovePaths = [];

    for (const ev of data.events) {
      if (ev.start_ms > t) break;
      const a = assetState[ev.target_asset_id];
      if (!a) continue;

      const isActive = t >= ev.start_ms && t <= ev.end_ms;
      if (isActive) activeEvents.push(ev);

      if (ev.type === "move") {
        const dur = Math.max(1, ev.end_ms - ev.start_ms);
        const frac = Math.min(1, Math.max(0, (t - ev.start_ms) / dur));
        const eased = applyEasing(frac, ev.easing);
        a.pos = samplePolyline(ev.path, eased);
        totalDistPx += polylineLength(ev.path) * eased;
        if (isActive) activeMovePaths.push(ev.path);
      } else if (ev.type === "attach") {
        a.parent = ev.parent_asset_id;
      } else if (ev.type === "detach") {
        a.parent = null;
        if (ev.detach_pos) a.pos = [...ev.detach_pos];
      } else if (ev.type === "state") {
        a.state = ev.state;
      } else if (ev.type === "label") {
        if (isActive) a.label = ev.text;
      } else if (ev.type === "resource_delta") {
        const elapsedMs = Math.min(t, ev.end_ms) - ev.start_ms;
        if (elapsedMs > 0 && a.resources[ev.resource]) {
          a.resources[ev.resource].value += ev.rate_per_min * (elapsedMs / 60000);
        }
      }
    }

    for (const a of Object.values(assetState)) {
      if (a.parent && assetState[a.parent]) {
        a.pos = [...assetState[a.parent].pos];
      }
    }

    const activePhase = data.phases.find(p => t >= p.start_ms && t <= p.end_ms) || null;
    const activeWindow = (data.windows || []).find(w => t >= w.start_ms && t <= w.end_ms) || null;

    const alerts = [];
    for (const a of Object.values(assetState)) {
      if (a.is_static) continue;
      for (const z of data.zones || []) {
        if (pointInZone(a.pos, z)) {
          if (z.type === "hazard") {
            alerts.push({ level: "danger", text: `${a.id} inside HAZARD zone (${z.id})` });
          } else if (z.type === "shadow") {
            alerts.push({ level: "alert", text: `${a.id} in PSR shadow (${z.id})` });
          }
        }
      }
      for (const [rKey, r] of Object.entries(a.resources)) {
        if (r.min != null && r.value < r.min) {
          alerts.push({ level: "danger", text: `${a.id} ${rKey} BELOW MIN (${r.value.toFixed(1)}${r.unit})` });
        }
        if (r.max != null && r.value > r.max) {
          alerts.push({ level: "danger", text: `${a.id} ${rKey} EXCEEDS MAX (${r.value.toFixed(1)}${r.unit})` });
        }
      }
    }

    const scale = data.scene.scale_m_per_px || 1;
    return {
      assetState,
      activeEvents,
      activeMovePaths,
      activePhase,
      activeWindow,
      alerts,
      totalDistM: totalDistPx * scale,
    };
  }

  // -------------------------------------------------------------------------
  // 2D Canvas Renderer (with Camera Transform & Custom Sprites)
  // -------------------------------------------------------------------------
  function render(state) {
    if (!simData) return;
    const { width, height } = simData.scene.dimensions;
    const totalScale = getBaseScale() * camera.zoom;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(camera.panX, camera.panY);
    ctx.scale(totalScale, totalScale);

    // 1. Background image or procedural lunar grid
    if (bgImage && bgImage.complete && bgImage.naturalWidth > 0) {
      ctx.drawImage(bgImage, 0, 0, width, height);
    } else {
      ctx.fillStyle = "#0d1117";
      ctx.fillRect(0, 0, width, height);
      ctx.strokeStyle = "rgba(148, 163, 184, 0.08)";
      ctx.lineWidth = 2;
      const step = Math.round(width / 16);
      for (let x = 0; x <= width; x += step) {
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke();
      }
      for (let y = 0; y <= height; y += step) {
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke();
      }
    }

    // 2. Spatial Zones
    for (const z of simData.zones || []) {
      ctx.save();
      if (z.type === "shadow") {
        ctx.fillStyle = "rgba(30, 58, 138, 0.35)";
        ctx.strokeStyle = "#60a5fa";
      } else if (z.type === "hazard") {
        ctx.fillStyle = "rgba(239, 68, 68, 0.18)";
        ctx.strokeStyle = "#ef4444";
      } else {
        ctx.fillStyle = "rgba(250, 204, 21, 0.15)";
        ctx.strokeStyle = "#facc15";
      }
      ctx.lineWidth = 3;
      ctx.setLineDash([12, 8]);
      ctx.beginPath();
      if (z.geometry.shape === "circle") {
        const [cx, cy] = z.geometry.center;
        ctx.arc(cx, cy, z.geometry.radius_px, 0, Math.PI * 2);
      } else {
        z.geometry.points.forEach((p, idx) => idx === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
        ctx.closePath();
      }
      ctx.fill();
      ctx.stroke();
      ctx.restore();
    }

    // 3. Planned & Active Move Paths
    for (const ev of simData.events) {
      if (ev.type !== "move") continue;
      ctx.save();
      ctx.strokeStyle = "rgba(148, 163, 184, 0.25)";
      ctx.lineWidth = 4;
      ctx.setLineDash([10, 10]);
      ctx.beginPath();
      ev.path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      ctx.stroke();
      ctx.restore();
    }
    for (const path of state.activeMovePaths) {
      ctx.save();
      ctx.strokeStyle = "#38bdf8";
      ctx.lineWidth = 6;
      ctx.beginPath();
      path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      ctx.stroke();
      ctx.restore();
    }

    // 4. Waypoints (custom icon or vector marker)
    for (const [id, wp] of Object.entries(simData.waypoints)) {
      const [x, y] = wp.pos;
      const wpImg = getLoadedSprite(`wp:${id}`, wp.image);
      ctx.save();
      if (wpImg) {
        ctx.drawImage(wpImg, x - 20, y - 20, 40, 40);
      } else {
        ctx.fillStyle = "#f8fafc";
        ctx.strokeStyle = "#38bdf8";
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.arc(x, y, 12, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
      }
      ctx.font = "bold 26px system-ui, sans-serif";
      ctx.fillStyle = "#e2e8f0";
      ctx.fillText(wp.label, x + 24, y + 8);
      ctx.restore();
    }

    // 5. Assets (custom sprite image or vector fallback)
    const sortedAssets = Object.values(state.assetState).sort((a, b) => a.layer - b.layer);
    for (const a of sortedAssets) {
      if (a.parent) continue;
      const [x, y] = a.pos;
      const sprite = getLoadedSprite(a.id, a.image);
      const isLarge = a.tags.includes("vehicle") || a.is_static;
      const size = isLarge ? 64 : 46;

      ctx.save();
      if (sprite) {
        ctx.drawImage(sprite, x - size / 2, y - size / 2, size, size);
      } else {
        const color = a.is_static ? "#94a3b8" : a.tags.includes("vehicle") ? "#38bdf8" : a.tags.includes("crew") ? "#22c55e" : "#f59e0b";
        ctx.fillStyle = color;
        ctx.strokeStyle = "#0b0f17";
        ctx.lineWidth = 4;
        ctx.beginPath();
        if (isLarge) {
          ctx.roundRect(x - 22, y - 22, 44, 44, 8);
        } else {
          ctx.arc(x, y, 18, 0, Math.PI * 2);
        }
        ctx.fill();
        ctx.stroke();
      }

      // Label & State
      ctx.font = "bold 24px ui-monospace, monospace";
      ctx.fillStyle = "#ffffff";
      ctx.fillText(a.id, x - 28, y - size / 2 - 8);

      if (a.label) {
        ctx.font = "22px system-ui, sans-serif";
        ctx.fillStyle = "#fde047";
        ctx.fillText(a.label, x + size / 2 + 8, y - 4);
      }

      const children = sortedAssets.filter(c => c.parent === a.id);
      if (children.length > 0) {
        ctx.font = "bold 20px ui-monospace, monospace";
        ctx.fillStyle = "#38bdf8";
        ctx.fillText(`+${children.length} aboard`, x + size / 2 + 8, y + 22);
      }
      ctx.restore();
    }

    ctx.restore();
  }

  // -------------------------------------------------------------------------
  // HUD & Statistics Panel Updater
  // -------------------------------------------------------------------------
  function updateUI(state) {
    if (!simData) return;
    const dur = simData.scene.duration_ms || 1;
    el.hudMet.textContent = `MET ${formatMET(currentMs)}`;
    el.hudPhase.textContent = state.activePhase ? state.activePhase.name : "Between Phases";
    el.timeReadout.textContent = `${formatMET(currentMs)} / ${formatMET(dur)}`;
    el.scrubber.value = Math.round(currentMs);

    el.statActiveEvents.textContent = state.activeEvents.length;
    el.statTotalDist.textContent = `${Math.round(state.totalDistM).toLocaleString()} m`;
    el.statProgress.textContent = `${((currentMs / dur) * 100).toFixed(1)}%`;

    if (state.activeWindow) {
      el.commBadge.textContent = `COMM: ${state.activeWindow.id}`;
      el.commBadge.className = "badge ok";
      el.statBandwidth.textContent = `${state.activeWindow.bandwidth_mbps} Mbps`;
    } else {
      el.commBadge.textContent = "COMM: BLACKOUT";
      el.commBadge.className = "badge warn";
      el.statBandwidth.textContent = "0 Mbps";
    }

    Array.from(el.phasePills.children).forEach(btn => {
      btn.classList.toggle("active", state.activePhase && btn.dataset.phaseId === state.activePhase.id);
    });

    el.resourcePanel.innerHTML = Object.values(state.assetState)
      .filter(a => !a.is_static)
      .map(a => {
        const resHtml = Object.entries(a.resources).map(([k, r]) => {
          const maxVal = r.max ?? 100;
          const pct = Math.min(100, Math.max(0, (r.value / maxVal) * 100));
          let cls = "ok";
          if ((r.min != null && r.value < r.min) || (r.max != null && r.value > r.max)) cls = "danger";
          else if (r.min != null && r.value < r.min + 15) cls = "warn";
          return `
            <div class="res-row">
              <div class="res-meta"><span>${k}</span><span>${r.value.toFixed(1)}${r.unit}</span></div>
              <div class="bar-track"><div class="bar-fill ${cls}" style="width:${pct}%"></div></div>
            </div>`;
        }).join("");
        const statusText = a.parent ? `aboard ${a.parent}` : a.state;
        return `
          <div class="asset-group">
            <div class="asset-hdr"><span>${a.id}</span><span class="badge">${statusText}</span></div>
            ${resHtml || '<div class="res-meta">No consumables</div>'}
          </div>`;
      }).join("");

    el.alertPanel.innerHTML = state.alerts.length
      ? state.alerts.map(al => `<div class="list-item ${al.level}">${al.text}</div>`).join("")
      : '<div class="res-meta">Nominal — no active alerts.</div>';

    el.eventPanel.innerHTML = state.activeEvents.length
      ? state.activeEvents.map(ev => `<div class="list-item">[${ev.type}] ${ev.target_asset_id} (${ev.id})</div>`).join("")
      : '<div class="res-meta">No active events at this timestamp.</div>';
  }

  // -------------------------------------------------------------------------
  // Main Playback Loop
  // -------------------------------------------------------------------------
  function tick(now) {
    if (isPlaying && simData) {
      if (lastFrameTime !== null) {
        const dtMs = Math.min(250, now - lastFrameTime);
        currentMs += dtMs * speedMultiplier;
        if (currentMs >= simData.scene.duration_ms) {
          currentMs = simData.scene.duration_ms;
          setPlaying(false);
        }
      }
      lastFrameTime = now;
      redrawCurrent();
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);

  function setPlaying(play) {
    isPlaying = play;
    lastFrameTime = null;
    el.btnPlayPause.innerHTML = isPlaying ? "&#x23F8; Pause" : "&#x25B6; Play";
  }

  function loadTimeline(jsonObj) {
    simData = jsonObj;
    currentMs = 0;
    setPlaying(false);
    el.sceneTag.textContent = simData.scene.id;
    el.scrubber.max = simData.scene.duration_ms;

    preloadTimelineSprites(simData);

    el.phasePills.innerHTML = "";
    for (const p of simData.phases) {
      const btn = document.createElement("button");
      btn.className = "phase-pill";
      btn.textContent = p.name;
      btn.dataset.phaseId = p.id;
      btn.onclick = () => {
        currentMs = p.start_ms;
        redrawCurrent();
      };
      el.phasePills.appendChild(btn);
    }
    resetCamera();
  }

  // -------------------------------------------------------------------------
  // Canvas Zoom & Pan Listeners
  // -------------------------------------------------------------------------
  function getCanvasCoords(e) {
    const rect = canvas.getBoundingClientRect();
    return {
      x: (e.clientX - rect.left) * (canvas.width / rect.width),
      y: (e.clientY - rect.top) * (canvas.height / rect.height),
    };
  }

  canvas.addEventListener("wheel", (e) => {
    if (!simData) return;
    e.preventDefault();
    const { x: mx, y: my } = getCanvasCoords(e);
    const oldScale = getBaseScale() * camera.zoom;
    const worldX = (mx - camera.panX) / oldScale;
    const worldY = (my - camera.panY) / oldScale;

    const zoomFactor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
    camera.zoom = Math.min(camera.maxZoom, Math.max(camera.minZoom, camera.zoom * zoomFactor));

    const newScale = getBaseScale() * camera.zoom;
    camera.panX = mx - worldX * newScale;
    camera.panY = my - worldY * newScale;

    el.zoomReadout.textContent = `${Math.round(camera.zoom * 100)}%`;
    redrawCurrent();
  }, { passive: false });

  canvas.addEventListener("mousedown", (e) => {
    if (!simData || e.button !== 0) return;
    const { x, y } = getCanvasCoords(e);
    camera.isDragging = true;
    camera.dragStartX = x - camera.panX;
    camera.dragStartY = y - camera.panY;
    canvas.classList.add("dragging");
  });

  window.addEventListener("mousemove", (e) => {
    if (!camera.isDragging) return;
    const { x, y } = getCanvasCoords(e);
    camera.panX = x - camera.dragStartX;
    camera.panY = y - camera.dragStartY;
    redrawCurrent();
  });

  window.addEventListener("mouseup", () => {
    if (!camera.isDragging) return;
    camera.isDragging = false;
    canvas.classList.remove("dragging");
  });

  el.btnResetView.onclick = resetCamera;

  // -------------------------------------------------------------------------
  // File & Control Listeners
  // -------------------------------------------------------------------------
  el.fileInput.addEventListener("change", (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try { loadTimeline(JSON.parse(ev.target.result)); }
      catch (err) { alert("Invalid JSON file: " + err.message); }
    };
    reader.readAsText(file);
  });

  el.spriteInput.addEventListener("change", (e) => {
    for (const file of e.target.files) {
      const url = URL.createObjectURL(file);
      const fname = file.name.toLowerCase();
      const stem = fname.replace(/\.[^.]+$/, "");
      cacheImageSrc(fname, url);
      cacheImageSrc(stem, url);
      if (simData && simData.scene.background && basename(simData.scene.background) === fname) {
        bgImage = spriteCache.get(fname);
      }
    }
    redrawCurrent();
  });

  el.btnPlayPause.onclick = () => {
    if (!simData) return;
    if (currentMs >= simData.scene.duration_ms) currentMs = 0;
    setPlaying(!isPlaying);
  };
  el.btnReset.onclick = () => {
    if (!simData) return;
    setPlaying(false); currentMs = 0; redrawCurrent();
  };
  el.btnStepBack.onclick = () => {
    if (!simData) return;
    currentMs = Math.max(0, currentMs - 60000); redrawCurrent();
  };
  el.btnStepFwd.onclick = () => {
    if (!simData) return;
    currentMs = Math.min(simData.scene.duration_ms, currentMs + 60000); redrawCurrent();
  };
  el.speedSelect.onchange = (e) => { speedMultiplier = Number(e.target.value); };
  el.scrubber.oninput = (e) => {
    if (!simData) return;
    currentMs = Number(e.target.value); redrawCurrent();
  };

  // -------------------------------------------------------------------------
  // Embedded Sample SVG Sprites & Lunar EVA Timeline
  // -------------------------------------------------------------------------
  const svgUri = (svg) => "data:image/svg+xml;utf8," + encodeURIComponent(svg.trim());

  const SPRITE_LANDER = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><polygon points="32,6 50,24 44,44 20,44 14,24" fill="#cbd5e1" stroke="#0f172a" stroke-width="3"/><line x1="20" y1="44" x2="10" y2="58" stroke="#94a3b8" stroke-width="4"/><line x1="44" y1="44" x2="54" y2="58" stroke="#94a3b8" stroke-width="4"/><circle cx="32" cy="24" r="6" fill="#38bdf8"/></svg>`);
  const SPRITE_ROVER = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="14" y="16" width="36" height="32" rx="6" fill="#0284c7" stroke="#e2e8f0" stroke-width="3"/><rect x="6" y="12" width="8" height="14" rx="2" fill="#475569"/><rect x="50" y="12" width="8" height="14" rx="2" fill="#475569"/><rect x="6" y="38" width="8" height="14" rx="2" fill="#475569"/><rect x="50" y="38" width="8" height="14" rx="2" fill="#475569"/><rect x="22" y="22" width="20" height="12" rx="2" fill="#38bdf8"/></svg>`);
  const SPRITE_CREW = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><circle cx="32" cy="32" r="22" fill="#f8fafc" stroke="#22c55e" stroke-width="4"/><ellipse cx="32" cy="28" rx="12" ry="9" fill="#f59e0b" stroke="#0f172a" stroke-width="2"/></svg>`);
  const SPRITE_SEISMO = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><polygon points="32,10 54,50 10,50" fill="#f59e0b" stroke="#0f172a" stroke-width="3"/><circle cx="32" cy="36" r="6" fill="#0f172a"/></svg>`);

  const SAMPLE_TIMELINE = {
    schema_version: "1.0.0",
    scene: { id: "ShackletonRim_EVA1", background: "", dimensions: { width: 2048, height: 2048 }, scale_m_per_px: 0.5, duration_ms: 7200000 },
    waypoints: {
      lander_pad: { pos: [320, 1680], label: "HLS Lander Pad" },
      solar_ridge: { pos: [740, 1220], label: "Connecting Ridge" },
      shackleton_rim: { pos: [1420, 680], label: "Station 1: Shackleton Rim" },
      psr_edge: { pos: [1580, 560], label: "Station 2: PSR Edge" }
    },
    zones: [
      { id: "psr_crater_floor", type: "shadow", geometry: { shape: "polygon", points: [[1540,480],[1950,420],[1980,820],[1610,690]] } },
      { id: "lander_blast_koz", type: "hazard", geometry: { shape: "circle", center: [320,1680], radius_px: 90 } },
      { id: "ridge_sunlight_corridor", type: "solar_rich", geometry: { shape: "polygon", points: [[580,1380],[920,1080],[1010,1180],[670,1480]] } }
    ],
    windows: [{ id: "lunar_relay_pass_1", start_ms: 3300000, end_ms: 4800000, bandwidth_mbps: 50 }],
    assets: {
      hls_lander: { is_static: true, image: SPRITE_LANDER, start_pos: [320,1680], layer: 1, tags: ["lander"], resources: {} },
      ltv_rover: { is_static: false, image: SPRITE_ROVER, start_pos: [320,1680], layer: 2, tags: ["vehicle"], resources: { battery: { initial: 100, unit: "%", min: 20, max: 100 }, data_buffer: { initial: 0, unit: "GB", min: 0, max: 64 } } },
      astronaut_1: { is_static: false, image: SPRITE_CREW, start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      astronaut_2: { is_static: false, image: SPRITE_CREW, start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      seismometer_pkg: { is_static: false, image: SPRITE_SEISMO, start_pos: [320,1680], layer: 2, tags: ["payload"], resources: {} }
    },
    phases: [
      { id: "eva_1", name: "EVA-1: Egress & Prep", start_ms: 0, end_ms: 900000 },
      { id: "eva_2", name: "EVA-2: Outbound Traverse", start_ms: 900000, end_ms: 2700000 },
      { id: "eva_3", name: "EVA-3: Rim Science", start_ms: 2700000, end_ms: 4800000 },
      { id: "eva_4", name: "EVA-4: Return & Closeout", start_ms: 4800000, end_ms: 7200000 }
    ],
    events: [
      { id: "e1", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e2", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e3", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e4", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e5", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "seismometer_pkg", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e6", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "move", path: [[320,1680],[520,1480],[740,1220],[1120,910],[1420,680]], easing: "ease_in_out" },
      { id: "e7", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.8 },
      { id: "e8", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: 0.3 },
      { id: "e9", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e10", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e11", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e12", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e13", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "seismometer_pkg", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e14", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "move", path: [[1420,680],[1580,560]], easing: "linear" },
      { id: "e15", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "label", text: "Core Sampling at PSR Edge" },
      { id: "e16", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.6 },
      { id: "e17", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "state", state: "downlinking" },
      { id: "e18", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: -0.9 },
      { id: "e19", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "astronaut_2", type: "move", path: [[1580,560],[1420,680]], easing: "linear" },
      { id: "e20", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e21", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e22", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "move", path: [[1420,680],[1120,910],[740,1220],[520,1480],[320,1680]], easing: "ease_in_out" },
      { id: "e23", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.75 },
      { id: "e24", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e25", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e26", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: 1.5 }
    ]
  };

  el.btnLoadSample.onclick = () => loadTimeline(SAMPLE_TIMELINE);
  loadTimeline(SAMPLE_TIMELINE);
})();
</script>
</body>
</html>


Update simline_viewer.html so moving vehicle sprites automatically rotate to align with their current polyline segment heading.

Update these three sections inside the <script> block of simline_viewer.html to compute segment headings along polylines and rotate vehicle sprites while keeping their text labels upright.

1. Replace samplePolyline with samplePolylineWithHeading

This returns both the interpolated [x, y] position and the segment angle in radians via Math.atan2(dy, dx).

JavaScript
  function samplePolylineWithHeading(pts, fraction) {
    if (pts.length === 0) return { pos: [0, 0], heading: 0 };
    if (pts.length === 1) return { pos: pts[0], heading: 0 };

    if (fraction <= 0) {
      const dx = pts[1][0] - pts[0][0];
      const dy = pts[1][1] - pts[0][1];
      return { pos: pts[0], heading: Math.atan2(dy, dx) };
    }
    if (fraction >= 1) {
      const n = pts.length;
      const dx = pts[n - 1][0] - pts[n - 2][0];
      const dy = pts[n - 1][1] - pts[n - 2][1];
      return { pos: pts[n - 1], heading: Math.atan2(dy, dx) };
    }

    const total = polylineLength(pts);
    let target = total * fraction;
    for (let i = 1; i < pts.length; i++) {
      const dx = pts[i][0] - pts[i - 1][0];
      const dy = pts[i][1] - pts[i - 1][1];
      const seg = Math.hypot(dx, dy);
      if (target <= seg && seg > 0) {
        const u = target / seg;
        return {
          pos: [pts[i - 1][0] + dx * u, pts[i - 1][1] + dy * u],
          heading: Math.atan2(dy, dx),
        };
      }
      target -= seg;
    }

    const n = pts.length;
    return {
      pos: pts[n - 1],
      heading: Math.atan2(pts[n - 1][1] - pts[n - 2][1], pts[n - 1][0] - pts[n - 2][0]),
    };
  }

2. Track heading in evaluateState

Add heading: null when initializing each asset, and store the heading during move events so the vehicle holds its last orientation when parked.

      // Inside assetState[id] initialization:
      assetState[id] = {
        id,
        ...spec,
        pos: [...spec.start_pos],
        heading: null,          // <-- ADD THIS
        parent: null,
        state: spec.is_static ? "static" : "idle",
        label: "",
        resources,
      };
//----
      // Inside the event sweep loop, replace the `if (ev.type === "move")` block:
      if (ev.type === "move") {
        const dur = Math.max(1, ev.end_ms - ev.start_ms);
        const frac = Math.min(1, Math.max(0, (t - ev.start_ms) / dur));
        const eased = applyEasing(frac, ev.easing);
        const sample = samplePolylineWithHeading(ev.path, eased);
        a.pos = sample.pos;
        a.heading = sample.heading;
        totalDistPx += polylineLength(ev.path) * eased;
        if (isActive) activeMovePaths.push(ev.path);
      }

3. Apply Rotation to Vehicle Sprites in render

Isolate the rotation inside a nested ctx.save() / ctx.restore() around the sprite draw call so labels and crew badges stay horizontal. Because SPRITE_ROVER is drawn facing up (-Y), adding Math.PI / 2 aligns its nose with the travel vector.

    // Replace section "// 5. Assets" inside render(state):
    const SPRITE_HEADING_OFFSET = Math.PI / 2; // Use 0 if custom sprites face right (+X)
    const sortedAssets = Object.values(state.assetState).sort((a, b) => a.layer - b.layer);

    for (const a of sortedAssets) {
      if (a.parent) continue;
      const [x, y] = a.pos;
      const sprite = getLoadedSprite(a.id, a.image);
      const isVehicle = a.tags.includes("vehicle");
      const isLarge = isVehicle || a.is_static;
      const size = isLarge ? 64 : 46;

      // Draw sprite or vector marker (rotated for vehicles with a heading)
      ctx.save();
      ctx.translate(x, y);
      if (isVehicle && a.heading !== null) {
        ctx.rotate(a.heading + SPRITE_HEADING_OFFSET);
      }

      if (sprite) {
        ctx.drawImage(sprite, -size / 2, -size / 2, size, size);
      } else {
        const color = a.is_static ? "#94a3b8" : isVehicle ? "#38bdf8" : a.tags.includes("crew") ? "#22c55e" : "#f59e0b";
        ctx.fillStyle = color;
        ctx.strokeStyle = "#0b0f17";
        ctx.lineWidth = 4;
        ctx.beginPath();
        if (isLarge) {
          ctx.roundRect(-22, -22, 44, 44, 8);
        } else {
          ctx.arc(0, 0, 18, 0, Math.PI * 2);
        }
        ctx.fill();
        ctx.stroke();

        // Forward direction indicator on fallback vector vehicle
        if (isVehicle) {
          ctx.fillStyle = "#ffffff";
          ctx.beginPath();
          ctx.moveTo(0, -18);
          ctx.lineTo(8, -6);
          ctx.lineTo(-8, -6);
          ctx.closePath();
          ctx.fill();
        }
      }
      ctx.restore();

      // Draw upright labels & docked crew count
      ctx.save();
      ctx.font = "bold 24px ui-monospace, monospace";
      ctx.fillStyle = "#ffffff";
      ctx.fillText(a.id, x - 28, y - size / 2 - 8);

      if (a.label) {
        ctx.font = "22px system-ui, sans-serif";
        ctx.fillStyle = "#fde047";
        ctx.fillText(a.label, x + size / 2 + 8, y - 4);
      }

      const children = sortedAssets.filter(c => c.parent === a.id);
      if (children.length > 0) {
        ctx.font = "bold 20px ui-monospace, monospace";
        ctx.fillStyle = "#38bdf8";
        ctx.fillText(`+${children.length} aboard`, x + size / 2 + 8, y + 22);
      }
      ctx.restore();
    }


Add an interactive Authoring Mode to simline_viewer.html so I can click on the canvas to place waypoints, draw traverse paths, and export a .simline DSL file.

Add these four drop-in sections to simline_viewer.html to enable an interactive Authoring Mode with click-to-place waypoints, snap-to-waypoint traverse path drawing (with automatic speed-based duration calculation), and one-click .simline DSL export.

1. Add Authoring Toolbar CSS (inside <style>)

  .author-toolbar {
    position: absolute;
    top: 12px; right: 12px;
    background: rgba(11, 15, 23, 0.92);
    border: 1px solid var(--accent);
    border-radius: 8px;
    padding: 8px 10px;
    display: none;
    flex-direction: column;
    gap: 8px;
    font-size: 12px;
    min-width: 240px;
  }
  .author-toolbar.visible { display: flex; }
  .author-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
  .author-toolbar button.active-tool {
    background: #0284c7; border-color: #38bdf8; color: #fff; font-weight: 600;
  }
  .author-hint {
    font-family: var(--font-mono); font-size: 11px; color: var(--warn);
  }
  .author-toolbar input[type="number"] {
    width: 64px; background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 5px; padding: 4px 6px;
    font-family: var(--font-mono); font-size: 12px;
  }

2. Add Toggle Button & Toolbar HTML

In <header>, add the Authoring Mode toggle inside .header-actions:

    <button id="btnToggleAuthor">Authoring Mode: OFF</button>

Inside <section class="viewport">, right after .camera-hud, add the floating authoring toolbar:

    <div class="author-toolbar" id="authorToolbar">
      <div class="author-row">
        <button id="toolPan" class="active-tool">Pan</button>
        <button id="toolWaypoint">+ Waypoint</button>
        <button id="toolPath">+ Path</button>
      </div>
      <div class="author-row">
        <select id="authorAsset"></select>
        <label style="color:var(--muted);font-size:11px;">Speed:</label>
        <input type="number" id="authorSpeed" value="2.0" step="0.2" min="0.1" />
        <span style="color:var(--muted);font-size:11px;">m/s</span>
      </div>
      <div class="author-hint" id="authorHint">Select a tool to edit the map.</div>
      <div class="author-row">
        <button id="btnCancelPath">Cancel Path</button>
        <button id="btnExportDsl" class="primary">Export .simline</button>
      </div>
    </div>

3. Add Authoring State, Canvas Handlers & Draft Overlay (inside <script>)

Add the new DOM references to el:

    btnToggleAuthor: document.getElementById("btnToggleAuthor"),
    authorToolbar: document.getElementById("authorToolbar"),
    toolPan: document.getElementById("toolPan"),
    toolWaypoint: document.getElementById("toolWaypoint"),
    toolPath: document.getElementById("toolPath"),
    authorAsset: document.getElementById("authorAsset"),
    authorSpeed: document.getElementById("authorSpeed"),
    authorHint: document.getElementById("authorHint"),
    btnCancelPath: document.getElementById("btnCancelPath"),
    btnExportDsl: document.getElementById("btnExportDsl"),

Add the authoring state and coordinate helpers right below camera:

  const authoring = {
    enabled: false,
    tool: "pan", // "pan" | "waypoint" | "path"
    draftPath: null, // { fromWpId, via: [[x,y], ...] }
  };

  function screenToWorld(canvasX, canvasY) {
    const totalScale = getBaseScale() * camera.zoom;
    return [
      Math.round((canvasX - camera.panX) / totalScale),
      Math.round((canvasY - camera.panY) / totalScale),
    ];
  }

  function findNearestWaypoint(worldPt, maxDistWorld = 45) {
    if (!simData) return null;
    let bestId = null, bestDist = maxDistWorld;
    for (const [id, wp] of Object.entries(simData.waypoints)) {
      const d = Math.hypot(wp.pos[0] - worldPt[0], wp.pos[1] - worldPt[1]);
      if (d < bestDist) { bestDist = d; bestId = id; }
    }
    return bestId;
  }

  function setAuthorTool(tool) {
    authoring.tool = tool;
    authoring.draftPath = null;
    el.toolPan.classList.toggle("active-tool", tool === "pan");
    el.toolWaypoint.classList.toggle("active-tool", tool === "waypoint");
    el.toolPath.classList.toggle("active-tool", tool === "path");
    canvas.style.cursor = tool === "pan" ? "grab" : "crosshair";
    el.authorHint.textContent =
      tool === "waypoint" ? "Click map to place a new waypoint." :
      tool === "path" ? "Click start waypoint, optional via points, then end waypoint." :
      "Drag to pan, scroll to zoom.";
    redrawCurrent();
  }

Populate the asset dropdown inside loadTimeline(jsonObj):

    el.authorAsset.innerHTML = Object.entries(simData.assets)
      .filter(([, a]) => !a.is_static)
      .map(([id]) => `<option value="${id}">${id}</option>`)
      .join("");

Update the canvas.addEventListener("mousedown", ...) listener so left-clicks in waypoint or path mode edit the map instead of panning:

  canvas.addEventListener("mousedown", (e) => {
    if (!simData || e.button !== 0) return;
    const { x, y } = getCanvasCoords(e);

    if (authoring.enabled && authoring.tool === "waypoint") {
      const worldPt = screenToWorld(x, y);
      const nextNum = Object.keys(simData.waypoints).length + 1;
      const wpId = `wp_${nextNum}`;
      const label = prompt("Waypoint label:", `Station ${nextNum}`);
      if (label !== null) {
        simData.waypoints[wpId] = { pos: worldPt, label: label.trim() || wpId };
        el.authorHint.textContent = `Added ${wpId} at (${worldPt[0]}, ${worldPt[1]})`;
        redrawCurrent();
      }
      return;
    }

    if (authoring.enabled && authoring.tool === "path") {
      const worldPt = screenToWorld(x, y);
      const hitWp = findNearestWaypoint(worldPt);

      if (!authoring.draftPath) {
        if (!hitWp) {
          el.authorHint.textContent = "Click an existing waypoint to start the path.";
          return;
        }
        authoring.draftPath = { fromWpId: hitWp, via: [] };
        el.authorHint.textContent = `From ${hitWp} — click via points or end waypoint.`;
      } else if (hitWp && hitWp !== authoring.draftPath.fromWpId) {
        // Finalize traverse path and append MoveEvent
        const fromId = authoring.draftPath.fromWpId;
        const path = [
          simData.waypoints[fromId].pos,
          ...authoring.draftPath.via,
          simData.waypoints[hitWp].pos,
        ];
        const distM = polylineLength(path) * (simData.scene.scale_m_per_px || 1);
        const speed = Math.max(0.1, Number(el.authorSpeed.value) || 2.0);
        const durMs = Math.max(60000, Math.ceil((distM / speed) / 60) * 60000);

        const startMs = Math.round(currentMs);
        const endMs = startMs + durMs;
        const phaseId = simData.phases[0]?.id || "authored_phase";

        simData.events.push({
          id: `auth_move_${simData.events.length + 1}`,
          phase_id: phaseId,
          start_ms: startMs,
          end_ms: endMs,
          target_asset_id: el.authorAsset.value,
          type: "move",
          from_waypoint_id: fromId,
          to_waypoint_id: hitWp,
          path,
          easing: "ease_in_out",
          max_speed_mps: speed,
        });
        simData.events.sort((a, b) => a.start_ms - b.start_ms);
        if (endMs > simData.scene.duration_ms) {
          simData.scene.duration_ms = endMs;
          el.scrubber.max = endMs;
        }

        authoring.draftPath = null;
        el.authorHint.textContent = `Added traverse ${fromId} -> ${hitWp} (${Math.round(distM)}m, ${durMs / 60000}m)`;
      } else {
        authoring.draftPath.via.push(worldPt);
        el.authorHint.textContent = `Added via point #${authoring.draftPath.via.length}. Click end waypoint to finish.`;
      }
      redrawCurrent();
      return;
    }

    // Default Pan behavior
    camera.isDragging = true;
    camera.dragStartX = x - camera.panX;
    camera.dragStartY = y - camera.panY;
    canvas.classList.add("dragging");
  });

Inside render(state), right before the final ctx.restore(), draw the active draft path:

    // 6. Authoring Draft Path Overlay
    if (authoring.enabled && authoring.draftPath) {
      const startPos = simData.waypoints[authoring.draftPath.fromWpId].pos;
      const pts = [startPos, ...authoring.draftPath.via];
      ctx.save();
      ctx.strokeStyle = "#f59e0b";
      ctx.lineWidth = 5;
      ctx.setLineDash([12, 8]);
      ctx.beginPath();
      pts.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      ctx.stroke();
      ctx.fillStyle = "#f59e0b";
      for (const p of authoring.draftPath.via) {
        ctx.beginPath(); ctx.arc(p[0], p[1], 10, 0, Math.PI * 2); ctx.fill();
      }
      ctx.restore();
    }

4. Add the .simline DSL Exporter & Toolbar Listeners

Add this serializer and button wiring at the bottom of the <script> block:

  function exportSimLineDSL(data) {
    const lines = [];
    const durMin = Math.ceil(data.scene.duration_ms / 60000);

    lines.push(`scene "${data.scene.id}" {`);
    lines.push(`  background: "${data.scene.background || ""}"`);
    lines.push(`  dimensions: ${data.scene.dimensions.width} x ${data.scene.dimensions.height}`);
    if (data.scene.scale_m_per_px) lines.push(`  scale: 1px = ${data.scene.scale_m_per_px}m`);
    lines.push(`  duration: ${durMin}m`);
    lines.push(`}\n`);

    lines.push(`waypoints {`);
    for (const [id, wp] of Object.entries(data.waypoints)) {
      lines.push(`  ${id} {`);
      lines.push(`    pos: (${Math.round(wp.pos[0])}, ${Math.round(wp.pos[1])})`);
      lines.push(`    label: "${wp.label}"`);
      if (wp.image && !wp.image.startsWith("data:")) lines.push(`    image: "${wp.image}"`);
      lines.push(`  }`);
    }
    lines.push(`}\n`);

    if (data.zones?.length) {
      lines.push(`zones {`);
      for (const z of data.zones) {
        lines.push(`  ${z.id} {`);
        if (z.geometry.shape === "circle") {
          const [cx, cy] = z.geometry.center;
          lines.push(`    circle: (${cx}, ${cy}) radius ${z.geometry.radius_px}px`);
        } else {
          const pts = z.geometry.points.map(p => `(${p[0]}, ${p[1]})`).join(", ");
          lines.push(`    polygon: [${pts}]`);
        }
        lines.push(`    type: ${z.type}`);
        lines.push(`  }`);
      }
      lines.push(`}\n`);
    }

    lines.push(`assets {`);
    for (const [id, a] of Object.entries(data.assets)) {
      const kw = a.is_static ? "static" : "asset";
      lines.push(`  ${kw} ${id} {`);
      lines.push(`    image: "${a.image && !a.image.startsWith("data:") ? a.image : ""}"`);
      lines.push(a.is_static ? `    pos: (${a.start_pos[0]}, ${a.start_pos[1]})` : `    start_at: (${a.start_pos[0]}, ${a.start_pos[1]})`);
      lines.push(`    layer: ${a.layer}`);
      if (a.tags?.length) lines.push(`    tags: [${a.tags.map(t => `"${t}"`).join(", ")}]`);
      const resEntries = Object.entries(a.resources || {});
      if (resEntries.length) {
        lines.push(`    resources: {`);
        for (const [rk, rv] of resEntries) {
          const bounds = [rv.min != null ? `min: ${rv.min}${rv.unit}` : "", rv.max != null ? `max: ${rv.max}${rv.unit}` : ""].filter(Boolean).join(", ");
          lines.push(`      ${rk}: ${rv.initial}${rv.unit}${bounds ? ` (${bounds})` : ""}`);
        }
        lines.push(`    }`);
      }
      lines.push(`  }`);
    }
    lines.push(`}\n`);

    lines.push(`timeline {`);
    lines.push(`  phase "Authored Mission Timeline" {`);
    for (const ev of data.events) {
      const durM = Math.max(0, Math.round((ev.end_ms - ev.start_ms) / 60000));
      lines.push(`    id: ${ev.id}`);
      lines.push(`    at MET ${formatMET(ev.start_ms)} for ${durM}m {`);
      if (ev.type === "move") {
        const fromId = ev.from_waypoint_id || "lander_pad";
        const toId = ev.to_waypoint_id || "lander_pad";
        const viaPts = ev.path.slice(1, -1).map(p => `(${Math.round(p[0])}, ${Math.round(p[1])})`).join(", ");
        lines.push(`      ${ev.target_asset_id}: move from ${fromId} to ${toId}`);
        if (viaPts) lines.push(`        via [${viaPts}]`);
        if (ev.max_speed_mps) lines.push(`        max_speed: ${ev.max_speed_mps}m/s`);
        if (ev.easing) lines.push(`        easing ${ev.easing}`);
      } else if (ev.type === "attach") {
        lines.push(`      attach ${ev.target_asset_id} to ${ev.parent_asset_id}`);
      } else if (ev.type === "detach") {
        lines.push(`      detach ${ev.target_asset_id} from ${ev.parent_asset_id} at lander_pad`);
      } else if (ev.type === "state") {
        lines.push(`      ${ev.target_asset_id}: state "${ev.state}"`);
      } else if (ev.type === "label") {
        lines.push(`      ${ev.target_asset_id}: label "${ev.text}"`);
      } else if (ev.type === "resource_delta") {
        const op = ev.rate_per_min < 0 ? "drain" : "recharge";
        const unit = data.assets[ev.target_asset_id]?.resources?.[ev.resource]?.unit || "%";
        lines.push(`      ${ev.target_asset_id}: ${op} ${ev.resource} ${Math.abs(ev.rate_per_min)}${unit}/m`);
      }
      lines.push(`    }`);
    }
    lines.push(`  }`);
    lines.push(`}`);
    return lines.join("\n");
  }

  el.btnToggleAuthor.onclick = () => {
    authoring.enabled = !authoring.enabled;
    el.btnToggleAuthor.textContent = `Authoring Mode: ${authoring.enabled ? "ON" : "OFF"}`;
    el.btnToggleAuthor.classList.toggle("primary", authoring.enabled);
    el.authorToolbar.classList.toggle("visible", authoring.enabled);
    if (!authoring.enabled) setAuthorTool("pan");
  };
  el.toolPan.onclick = () => setAuthorTool("pan");
  el.toolWaypoint.onclick = () => setAuthorTool("waypoint");
  el.toolPath.onclick = () => setAuthorTool("path");
  el.btnCancelPath.onclick = () => {
    authoring.draftPath = null;
    el.authorHint.textContent = "Draft path cleared.";
    redrawCurrent();
  };
  el.btnExportDsl.onclick = () => {
    if (!simData) return;
    const dslText = exportSimLineDSL(simData);
    const blob = new Blob([dslText], { type: "text/plain;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `${simData.scene.id}.simline`;
    a.click();
    URL.revokeObjectURL(a.href);
  };


Extend Authoring Mode in simline_viewer.html with a Draw Zone tool to click-to-place polygon shadow or hazard zones and include them in the .simline export.

Add these four updates to simline_viewer.html to enable click-to-draw polygon zones (shadow, hazard, and solar_rich), live draft rendering, and full zone modifier export in .simline files.

1. Add the Draw Zone Button & Zone Type Selector (inside #authorToolbar)

Update #authorToolbar so it includes the + Zone tool, a zone-type dropdown, and a Finish Zone button:

    <div class="author-toolbar" id="authorToolbar">
      <div class="author-row">
        <button id="toolPan" class="active-tool">Pan</button>
        <button id="toolWaypoint">+ Waypoint</button>
        <button id="toolPath">+ Path</button>
        <button id="toolZone">+ Zone</button>
      </div>
      <div class="author-row">
        <select id="authorAsset"></select>
        <label style="color:var(--muted);font-size:11px;">Speed:</label>
        <input type="number" id="authorSpeed" value="2.0" step="0.2" min="0.1" />
        <span style="color:var(--muted);font-size:11px;">m/s</span>
      </div>
      <div class="author-row">
        <label style="color:var(--muted);font-size:11px;">Zone Type:</label>
        <select id="authorZoneType">
          <option value="shadow">PSR Shadow</option>
          <option value="hazard">Hazard (KOZ)</option>
          <option value="solar_rich">Solar Rich</option>
        </select>
        <button id="btnFinishZone">Finish Zone</button>
      </div>
      <div class="author-hint" id="authorHint">Select a tool to edit the map.</div>
      <div class="author-row">
        <button id="btnCancelDraft">Cancel Draft</button>
        <button id="btnExportDsl" class="primary">Export .simline</button>
      </div>
    </div>

2. Extend Authoring State & Tool Switcher (inside <script>)

Add the new DOM references to el:

    toolZone: document.getElementById("toolZone"),
    authorZoneType: document.getElementById("authorZoneType"),
    btnFinishZone: document.getElementById("btnFinishZone"),
    btnCancelDraft: document.getElementById("btnCancelDraft"),

Update the authoring object and setAuthorTool:

  const authoring = {
    enabled: false,
    tool: "pan", // "pan" | "waypoint" | "path" | "zone"
    draftPath: null,
    draftZone: [], // Array of [x, y] polygon vertices
  };

  function setAuthorTool(tool) {
    authoring.tool = tool;
    authoring.draftPath = null;
    authoring.draftZone = [];
    el.toolPan.classList.toggle("active-tool", tool === "pan");
    el.toolWaypoint.classList.toggle("active-tool", tool === "waypoint");
    el.toolPath.classList.toggle("active-tool", tool === "path");
    el.toolZone.classList.toggle("active-tool", tool === "zone");
    canvas.style.cursor = tool === "pan" ? "grab" : "crosshair";
    el.authorHint.textContent =
      tool === "waypoint" ? "Click map to place a new waypoint." :
      tool === "path" ? "Click start waypoint, optional via points, then end waypoint." :
      tool === "zone" ? "Click 3+ vertices. Click first vertex or 'Finish Zone' to close." :
      "Drag to pan, scroll to zoom.";
    redrawCurrent();
  }

  function commitDraftZone() {
    if (!simData || authoring.draftZone.length < 3) {
      el.authorHint.textContent = "A polygon zone requires at least 3 vertices.";
      return;
    }
    const zType = el.authorZoneType.value;
    const nextNum = (simData.zones?.length || 0) + 1;
    const rawId = prompt("Zone ID (no spaces):", `${zType}_zone_${nextNum}`);
    if (rawId === null) return;

    const zoneId = rawId.trim().replace(/\s+/g, "_") || `${zType}_zone_${nextNum}`;
    const modifiers =
      zType === "shadow" ? { solar_multiplier: 0.0, thermal_penalty: "high" } :
      zType === "solar_rich" ? { solar_multiplier: 1.0 } :
      undefined;

    simData.zones = simData.zones || [];
    simData.zones.push({
      id: zoneId,
      type: zType,
      geometry: { shape: "polygon", points: authoring.draftZone.map(p => [...p]) },
      ...(modifiers ? { modifiers } : {}),
    });

    authoring.draftZone = [];
    el.authorHint.textContent = `Added ${zType} zone '${zoneId}'.`;
    redrawCurrent();
  }

3. Handle Zone Clicks & Render the Draft Polygon

Inside canvas.addEventListener("mousedown", ...), add this block right after the authoring.tool === "path" block:

    if (authoring.enabled && authoring.tool === "zone") {
      const worldPt = screenToWorld(x, y);
      // Close polygon if user clicks near the first vertex with 3+ points placed
      if (authoring.draftZone.length >= 3) {
        const [fx, fy] = authoring.draftZone[0];
        if (Math.hypot(worldPt[0] - fx, worldPt[1] - fy) <= 35) {
          commitDraftZone();
          return;
        }
      }
      authoring.draftZone.push(worldPt);
      el.authorHint.textContent = `Zone vertex #${authoring.draftZone.length} placed. ${
        authoring.draftZone.length >= 3 ? "Click first vertex or 'Finish Zone' to close." : "Add more vertices."
      }`;
      redrawCurrent();
      return;
    }

Inside render(state), right after the Authoring Draft Path Overlay block, draw the active polygon draft:

    // 7. Authoring Draft Zone Overlay
    if (authoring.enabled && authoring.draftZone.length > 0) {
      const zType = el.authorZoneType.value;
      const stroke = zType === "hazard" ? "#ef4444" : zType === "shadow" ? "#60a5fa" : "#facc15";
      const fill = zType === "hazard" ? "rgba(239,68,68,0.22)" : zType === "shadow" ? "rgba(30,58,138,0.35)" : "rgba(250,204,21,0.18)";

      ctx.save();
      ctx.strokeStyle = stroke;
      ctx.fillStyle = fill;
      ctx.lineWidth = 4;
      ctx.setLineDash([10, 6]);
      ctx.beginPath();
      authoring.draftZone.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      if (authoring.draftZone.length >= 3) {
        ctx.closePath();
        ctx.fill();
      }
      ctx.stroke();

      // Vertex markers (highlight vertex 0 when ready to close)
      authoring.draftZone.forEach((p, i) => {
        ctx.beginPath();
        ctx.fillStyle = i === 0 && authoring.draftZone.length >= 3 ? "#ffffff" : stroke;
        ctx.arc(p[0], p[1], i === 0 && authoring.draftZone.length >= 3 ? 14 : 9, 0, Math.PI * 2);
        ctx.fill();
      });
      ctx.restore();
    }

4. Wire Toolbar Buttons & Export Zone Modifiers in .simline

Update the zones loop inside exportSimLineDSL(data) so solar_multiplier and thermal_penalty are written out cleanly:

    if (data.zones?.length) {
      lines.push(`zones {`);
      for (const z of data.zones) {
        lines.push(`  ${z.id} {`);
        if (z.geometry.shape === "circle") {
          const [cx, cy] = z.geometry.center;
          lines.push(`    circle: (${Math.round(cx)}, ${Math.round(cy)}) radius ${z.geometry.radius_px}px`);
        } else {
          const pts = z.geometry.points.map(p => `(${Math.round(p[0])}, ${Math.round(p[1])})`).join(", ");
          lines.push(`    polygon: [${pts}]`);
        }
        lines.push(`    type: ${z.type}`);
        if (z.modifiers?.solar_multiplier != null) {
          lines.push(`    solar_multiplier: ${z.modifiers.solar_multiplier}`);
        }
        if (z.modifiers?.thermal_penalty) {
          lines.push(`    thermal_penalty: ${z.modifiers.thermal_penalty}`);
        }
        lines.push(`  }`);
      }
      lines.push(`}\n`);
    }

Finally, wire up the new toolbar buttons at the bottom of <script>:

  el.toolZone.onclick = () => setAuthorTool("zone");
  el.btnFinishZone.onclick = commitDraftZone;
  el.btnCancelDraft.onclick = () => {
    authoring.draftPath = null;
    authoring.draftZone = [];
    el.authorHint.textContent = "Active draft cleared.";
    redrawCurrent();
  };


Add an Export JSON button and an Undo/Redo stack for authored waypoints, traverse paths, and polygon zones in simline_viewer.html.

Add these four drop-in updates to simline_viewer.html to add Undo/Redo (with Ctrl/Cmd+Z and Ctrl/Cmd+Y shortcuts) and Export JSON to Authoring Mode.

1. Add Undo, Redo & Export JSON Buttons (inside #authorToolbar)

Update the bottom row of #authorToolbar and add a history row:

      <div class="author-row">
        <button id="btnUndo" disabled title="Undo (Ctrl+Z)">&#x21A9; Undo</button>
        <button id="btnRedo" disabled title="Redo (Ctrl+Y)">&#x21AA; Redo</button>
        <button id="btnCancelDraft">Cancel Draft</button>
      </div>
      <div class="author-row">
        <button id="btnExportDsl" class="primary">Export .simline</button>
        <button id="btnExportJson">Export .json</button>
      </div>

2. Add the History Stack & Snapshot Helpers (inside <script>)

Add the new DOM references to el:

    btnUndo: document.getElementById("btnUndo"),
    btnRedo: document.getElementById("btnRedo"),
    btnExportJson: document.getElementById("btnExportJson"),

Add the snapshot-based Undo/Redo manager right below authoring:

  const history = {
    undo: [],
    redo: [],
    maxDepth: 50,
  };

  function captureSnapshot() {
    return structuredClone({
      waypoints: simData.waypoints,
      zones: simData.zones || [],
      events: simData.events,
      duration_ms: simData.scene.duration_ms,
    });
  }

  function applySnapshot(snap) {
    simData.waypoints = structuredClone(snap.waypoints);
    simData.zones = structuredClone(snap.zones);
    simData.events = structuredClone(snap.events);
    simData.scene.duration_ms = snap.duration_ms;
    el.scrubber.max = snap.duration_ms;
    if (currentMs > snap.duration_ms) currentMs = snap.duration_ms;
    authoring.draftPath = null;
    authoring.draftZone = [];
    updateHistoryButtons();
    redrawCurrent();
  }

  function pushUndoSnapshot() {
    if (!simData) return;
    history.undo.push(captureSnapshot());
    if (history.undo.length > history.maxDepth) history.undo.shift();
    history.redo = [];
    updateHistoryButtons();
  }

  function updateHistoryButtons() {
    el.btnUndo.disabled = history.undo.length === 0;
    el.btnRedo.disabled = history.redo.length === 0;
  }

  function undoAuthoring() {
    if (!simData || history.undo.length === 0) return;
    history.redo.push(captureSnapshot());
    applySnapshot(history.undo.pop());
    el.authorHint.textContent = "Undid last authoring action.";
  }

  function redoAuthoring() {
    if (!simData || history.redo.length === 0) return;
    history.undo.push(captureSnapshot());
    applySnapshot(history.redo.pop());
    el.authorHint.textContent = "Redid authoring action.";
  }

3. Record Snapshots Before Each Authoring Mutation

Insert pushUndoSnapshot(); immediately before mutating simData in these three places:

  1. Waypoint placement (inside canvas mousedown, right before simData.waypoints[wpId] = ...):

      if (label !== null) {
        pushUndoSnapshot();
        simData.waypoints[wpId] = { pos: worldPt, label: label.trim() || wpId };
    
  2. Traverse path finalization (inside canvas mousedown, right before simData.events.push(...)):

        pushUndoSnapshot();
        simData.events.push({
    
  3. Polygon zone commit (inside commitDraftZone(), right before simData.zones = simData.zones || [];):

    pushUndoSnapshot();
    simData.zones = simData.zones || [];
    

Also clear the history stack inside loadTimeline(jsonObj) so a newly loaded file starts clean:

    history.undo = [];
    history.redo = [];
    updateHistoryButtons();

4. Wire Export JSON, Undo/Redo Buttons & Keyboard Shortcuts

Add these listeners at the bottom of <script>:

  el.btnUndo.onclick = undoAuthoring;
  el.btnRedo.onclick = redoAuthoring;

  el.btnExportJson.onclick = () => {
    if (!simData) return;
    const jsonText = JSON.stringify(simData, null, 2);
    const blob = new Blob([jsonText], { type: "application/json;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `${simData.scene.id}.json`;
    a.click();
    URL.revokeObjectURL(a.href);
  };

  window.addEventListener("keydown", (e) => {
    if (!authoring.enabled) return;
    if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;

    const mod = e.ctrlKey || e.metaKey;
    if (mod && e.key.toLowerCase() === "z" && !e.shiftKey) {
      e.preventDefault();
      undoAuthoring();
    } else if (mod && (e.key.toLowerCase() === "y" || (e.key.toLowerCase() === "z" && e.shiftKey))) {
      e.preventDefault();
      redoAuthoring();
    }
  });


Add Mount and Dismount buttons with child/parent dropdowns to Authoring Mode in simline_viewer.html, wired into the Undo/Redo stack and .simline exporter.

Add these four drop-in updates to simline_viewer.html to schedule attach (Mount) and detach (Dismount) events at the current MET, wired into the Undo/Redo stack and .simline exporter.

1. Add Child/Parent Dropdowns & Buttons (inside #authorToolbar)

Add this .author-row right below the Zone Type row in #authorToolbar:

      <div class="author-row">
        <select id="authorChild" title="Child asset (crew or payload)"></select>
        <span style="color:var(--muted);font-size:11px;">&rarr;</span>
        <select id="authorParent" title="Parent asset (vehicle)"></select>
      </div>
      <div class="author-row">
        <button id="btnMount">Mount</button>
        <button id="btnDismount">Dismount</button>
      </div>

2. Populate Dropdowns & Add DOM References (inside <script>)

Add the four new elements to el:

    authorChild: document.getElementById("authorChild"),
    authorParent: document.getElementById("authorParent"),
    btnMount: document.getElementById("btnMount"),
    btnDismount: document.getElementById("btnDismount"),

Inside loadTimeline(jsonObj), right after populating el.authorAsset, populate el.authorChild and el.authorParent:

    const dynamicAssets = Object.entries(simData.assets).filter(([, a]) => !a.is_static);
    const assetOptions = dynamicAssets.map(([id]) => `<option value="${id}">${id}</option>`).join("");
    el.authorChild.innerHTML = assetOptions;
    el.authorParent.innerHTML = assetOptions;

    // Default to first crew/payload as child and first vehicle as parent
    const defaultChild = dynamicAssets.find(([, a]) => !a.tags?.includes("vehicle"))?.[0];
    const defaultParent = dynamicAssets.find(([, a]) => a.tags?.includes("vehicle"))?.[0];
    if (defaultChild) el.authorChild.value = defaultChild;
    if (defaultParent) el.authorParent.value = defaultParent;

3. Wire Mount & Dismount into the Undo/Redo Stack

Add this helper and button wiring at the bottom of <script>:

  function addCouplingEvent(type) {
    if (!simData) return;
    const childId = el.authorChild.value;
    const parentId = el.authorParent.value;

    if (!childId || !parentId || childId === parentId) {
      el.authorHint.textContent = "Select two different assets for child and parent.";
      return;
    }

    const startMs = Math.round(currentMs);
    const state = evaluateState(simData, startMs);
    const parentPos = state.assetState[parentId]?.pos || simData.assets[parentId].start_pos;
    const phaseId = state.activePhase?.id || simData.phases[0]?.id || "authored_phase";

    pushUndoSnapshot();

    const ev = {
      id: `auth_${type}_${simData.events.length + 1}`,
      phase_id: phaseId,
      start_ms: startMs,
      end_ms: startMs,
      target_asset_id: childId,
      type,
      parent_asset_id: parentId,
    };

    if (type === "detach") {
      ev.detach_pos = [Math.round(parentPos[0]), Math.round(parentPos[1])];
    }

    simData.events.push(ev);
    simData.events.sort((a, b) => a.start_ms - b.start_ms);

    const verb = type === "attach" ? "Mounted" : "Dismounted";
    const prep = type === "attach" ? "onto" : "from";
    el.authorHint.textContent = `${verb} ${childId} ${prep} ${parentId} at MET ${formatMET(startMs)}.`;
    redrawCurrent();
  }

  el.btnMount.onclick = () => addCouplingEvent("attach");
  el.btnDismount.onclick = () => addCouplingEvent("detach");

4. Resolve Detach Waypoints in exportSimLineDSL

Replace the else if (ev.type === "detach") branch inside exportSimLineDSL(data) so exported detach statements match the nearest waypoint to detach_pos instead of hardcoding lander_pad:

      } else if (ev.type === "detach") {
        let wpId = Object.keys(data.waypoints)[0] || "lander_pad";
        if (ev.detach_pos) {
          let bestDist = Infinity;
          for (const [id, wp] of Object.entries(data.waypoints)) {
            const d = Math.hypot(wp.pos[0] - ev.detach_pos[0], wp.pos[1] - ev.detach_pos[1]);
            if (d < bestDist) {
              bestDist = d;
              wpId = id;
            }
          }
        }
        lines.push(`      detach ${ev.target_asset_id} from ${ev.parent_asset_id} at ${wpId}`);


Add an Event Inspector panel to Authoring Mode in simline_viewer.html so I can view, jump to, or delete individual authored events with Undo support.

Add these three drop-in updates to simline_viewer.html to embed a scrollable Event Inspector inside Authoring Mode with one-click MET jump, event deletion wired into the Undo/Redo stack, and an All / Authored filter.

1. Add Event Inspector CSS (inside <style>)

  .insp-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-top: 1px solid var(--panel-border);
    padding-top: 6px;
  }
  .event-inspector {
    max-height: 180px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding-right: 2px;
  }
  .insp-row {
    display: grid;
    grid-template-columns: 1fr auto auto;
    align-items: center;
    gap: 6px;
    background: #131c2b;
    border: 1px solid #1e293b;
    border-left: 3px solid var(--accent);
    border-radius: 4px;
    padding: 4px 6px;
    font-family: var(--font-mono);
    font-size: 11px;
  }
  .insp-row.active {
    border-color: var(--accent);
    background: #1a273c;
  }
  .insp-info {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
  }
  .insp-info .t { color: var(--accent); margin-right: 4px; }
  .insp-row button {
    padding: 2px 6px;
    font-size: 10px;
  }
  .insp-row button.del-btn:hover {
    background: rgba(239, 68, 68, 0.25);
    border-color: var(--danger);
    color: #fecaca;
  }

2. Add the Inspector Container (inside #authorToolbar)

Place this block right above the Undo/Redo .author-row inside #authorToolbar:

      <div class="insp-header">
        <span>Event Inspector (<span id="inspCount">0</span>)</span>
        <select id="inspFilter" style="padding:2px 4px;font-size:10px;">
          <option value="all">All Events</option>
          <option value="authored">Authored Only</option>
        </select>
      </div>
      <div class="event-inspector" id="eventInspector">
        <div class="res-meta">No events.</div>
      </div>

3. Wire Rendering, Jump & Undo-Safe Delete (inside <script>)

Add the new DOM references to el:

    inspCount: document.getElementById("inspCount"),
    inspFilter: document.getElementById("inspFilter"),
    eventInspector: document.getElementById("eventInspector"),

Add renderEventInspector() right below addCouplingEvent:

  function renderEventInspector() {
    if (!simData || !authoring.enabled) return;

    const filter = el.inspFilter.value;
    const list = simData.events.filter(ev =>
      filter === "authored" ? ev.id.startsWith("auth_") : true
    );

    el.inspCount.textContent = list.length;

    if (list.length === 0) {
      el.eventInspector.innerHTML = '<div class="res-meta">No matching events.</div>';
      return;
    }

    el.eventInspector.innerHTML = "";
    for (const ev of list) {
      const isActive = currentMs >= ev.start_ms && currentMs <= ev.end_ms;
      const row = document.createElement("div");
      row.className = `insp-row${isActive ? " active" : ""}`;

      const info = document.createElement("div");
      info.className = "insp-info";
      info.title = `${ev.id} (${formatMET(ev.start_ms)} - ${formatMET(ev.end_ms)})`;
      info.innerHTML = `<span class="t">${formatMET(ev.start_ms)}</span>[${ev.type}] ${ev.target_asset_id}`;
      info.onclick = () => {
        setPlaying(false);
        currentMs = ev.start_ms;
        redrawCurrent();
      };

      const btnJump = document.createElement("button");
      btnJump.textContent = "Go";
      btnJump.title = `Jump to MET ${formatMET(ev.start_ms)}`;
      btnJump.onclick = info.onclick;

      const btnDel = document.createElement("button");
      btnDel.className = "del-btn";
      btnDel.textContent = "×";
      btnDel.title = `Delete ${ev.id}`;
      btnDel.onclick = () => {
        pushUndoSnapshot();
        simData.events = simData.events.filter(item => item.id !== ev.id);
        el.authorHint.textContent = `Deleted event '${ev.id}' (Ctrl+Z to undo).`;
        redrawCurrent();
      };

      row.append(info, btnJump, btnDel);
      el.eventInspector.appendChild(row);
    }
  }

  el.inspFilter.onchange = renderEventInspector;

Finally, call renderEventInspector() in two places so the list stays synced with scrubbing, authoring, and Undo/Redo:

  1. Inside redrawCurrent():

    function redrawCurrent() {
      if (!simData) return;
      const st = evaluateState(simData, currentMs);
      render(st);
      updateUI(st);
      if (authoring.enabled) renderEventInspector();
    }
    
  2. Inside el.btnToggleAuthor.onclick, right after el.authorToolbar.classList.toggle("visible", authoring.enabled);:

    if (authoring.enabled) renderEventInspector();


Add a live HTML5 Canvas sparkline chart to the sidebar of simline_viewer.html that plots rover battery and crew O2 curves over the full mission timeline with a moving MET playhead.

Add these three drop-in sections to simline_viewer.html to embed a live HTML5 Canvas telemetry sparkline in the sidebar. It plots rover battery and crew suit_o2 curves across the full mission duration, renders their minimum safety thresholds, tracks currentMs with a moving MET playhead, and supports click-to-scrub directly on the chart.

1. Add Sparkline CSS (inside <style>)

  .spark-canvas {
    width: 100%;
    height: 120px;
    display: block;
    background: #0b0f17;
    border: 1px solid #1e293b;
    border-radius: 6px;
    cursor: pointer;
  }
  .spark-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 6px;
    font-family: var(--font-mono);
    font-size: 10px;
    color: var(--muted);
  }
  .spark-legend-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }
  .spark-swatch {
    width: 10px;
    height: 3px;
    border-radius: 2px;
  }

2. Add the Sparkline Card (inside <aside>)

Place this card right below the Mission Telemetry card inside <aside>:

    <div class="card">
      <h3>Consumables Profile <span class="badge">0–100%</span></h3>
      <canvas id="sparkCanvas" class="spark-canvas" width="330" height="120"></canvas>
      <div class="spark-legend" id="sparkLegend"></div>
    </div>

3. Add Curve Sampling, Canvas Rendering & Click-to-Scrub (inside <script>)

Add the new DOM references to el:

    sparkCanvas: document.getElementById("sparkCanvas"),
    sparkLegend: document.getElementById("sparkLegend"),

Add the telemetry sampler and renderer right below updateUI(state):

  const sparkCtx = el.sparkCanvas.getContext("2d");
  const SPARK_COLORS = ["#38bdf8", "#22c55e", "#f59e0b", "#a855f7", "#f43f5e"];
  let telemetrySeries = []; // [{ label, color, min, points: [{ t, v }] }]

  function buildTelemetrySeries(data) {
    telemetrySeries = [];
    if (!data || !data.scene.duration_ms) return;

    // Auto-discover rover battery and crew O2 resources
    const tracked = [];
    for (const [assetId, asset] of Object.entries(data.assets || {})) {
      if (asset.is_static || !asset.resources) continue;
      for (const [resKey, resSpec] of Object.entries(asset.resources)) {
        if (resKey === "battery" || resKey === "suit_o2") {
          tracked.push({
            assetId,
            resKey,
            label: `${assetId}.${resKey}`,
            min: resSpec.min ?? null,
            max: resSpec.max ?? 100,
            color: SPARK_COLORS[tracked.length % SPARK_COLORS.length],
            points: [],
          });
        }
      }
    }

    if (tracked.length === 0) return;

    const dur = data.scene.duration_ms;
    const steps = 120;
    for (let i = 0; i <= steps; i++) {
      const t = (dur * i) / steps;
      const st = evaluateState(data, t);
      for (const s of tracked) {
        const r = st.assetState[s.assetId]?.resources?.[s.resKey];
        if (r) s.points.push({ t, v: r.value });
      }
    }

    telemetrySeries = tracked;
    el.sparkLegend.innerHTML = telemetrySeries
      .map(
        s => `<div class="spark-legend-item">
                <span class="spark-swatch" style="background:${s.color}"></span>
                <span>${s.label}</span>
              </div>`
      )
      .join("");
  }

  function renderSparkline() {
    const c = el.sparkCanvas;
    const w = c.width;
    const h = c.height;
    const pad = { top: 10, right: 8, bottom: 16, left: 26 };
    const plotW = w - pad.left - pad.right;
    const plotH = h - pad.top - pad.bottom;

    sparkCtx.clearRect(0, 0, w, h);
    if (!simData || telemetrySeries.length === 0) return;

    const dur = simData.scene.duration_ms || 1;
    const xOf = (t) => pad.left + (t / dur) * plotW;
    const yOf = (pct) => pad.top + plotH - (Math.max(0, Math.min(100, pct)) / 100) * plotH;

    // 1. Horizontal gridlines & Y-axis labels (0%, 25%, 50%, 75%, 100%)
    sparkCtx.font = "9px ui-monospace, monospace";
    sparkCtx.fillStyle = "#64748b";
    sparkCtx.strokeStyle = "rgba(148, 163, 184, 0.12)";
    sparkCtx.lineWidth = 1;
    for (const pct of [0, 25, 50, 75, 100]) {
      const y = yOf(pct);
      sparkCtx.beginPath();
      sparkCtx.moveTo(pad.left, y);
      sparkCtx.lineTo(w - pad.right, y);
      sparkCtx.stroke();
      sparkCtx.fillText(`${pct}`, 4, y + 3);
    }

    // 2. Minimum safety threshold lines (dashed red)
    const drawnMins = new Set();
    for (const s of telemetrySeries) {
      if (s.min != null && !drawnMins.has(s.min)) {
        drawnMins.add(s.min);
        const y = yOf(s.min);
        sparkCtx.save();
        sparkCtx.strokeStyle = "rgba(239, 68, 68, 0.45)";
        sparkCtx.setLineDash([4, 3]);
        sparkCtx.beginPath();
        sparkCtx.moveTo(pad.left, y);
        sparkCtx.lineTo(w - pad.right, y);
        sparkCtx.stroke();
        sparkCtx.restore();
      }
    }

    // 3. Plot each resource curve
    for (const s of telemetrySeries) {
      sparkCtx.save();
      sparkCtx.strokeStyle = s.color;
      sparkCtx.lineWidth = 1.8;
      sparkCtx.beginPath();
      s.points.forEach((pt, idx) => {
        const x = xOf(pt.t);
        const y = yOf(pt.v);
        if (idx === 0) sparkCtx.moveTo(x, y);
        else sparkCtx.lineTo(x, y);
      });
      sparkCtx.stroke();
      sparkCtx.restore();
    }

    // 4. Moving MET playhead & live value dots
    const px = xOf(currentMs);
    sparkCtx.save();
    sparkCtx.strokeStyle = "#f8fafc";
    sparkCtx.lineWidth = 1.2;
    sparkCtx.beginPath();
    sparkCtx.moveTo(px, pad.top);
    sparkCtx.lineTo(px, h - pad.bottom);
    sparkCtx.stroke();

    const curState = evaluateState(simData, currentMs);
    for (const s of telemetrySeries) {
      const r = curState.assetState[s.assetId]?.resources?.[s.resKey];
      if (!r) continue;
      sparkCtx.fillStyle = s.color;
      sparkCtx.beginPath();
      sparkCtx.arc(px, yOf(r.value), 3.2, 0, Math.PI * 2);
      sparkCtx.fill();
    }
    sparkCtx.restore();
  }

  // Click anywhere on the sparkline to scrub to that MET
  el.sparkCanvas.addEventListener("mousedown", (e) => {
    if (!simData) return;
    const rect = el.sparkCanvas.getBoundingClientRect();
    const padLeft = 26, padRight = 8;
    const clickX = ((e.clientX - rect.left) / rect.width) * el.sparkCanvas.width;
    const frac = Math.min(1, Math.max(0, (clickX - padLeft) / (el.sparkCanvas.width - padLeft - padRight)));
    currentMs = frac * simData.scene.duration_ms;
    redrawCurrent();
  });

Finally, hook the chart into your existing lifecycle functions:

  1. Inside loadTimeline(jsonObj) (right before resetCamera();):

    buildTelemetrySeries(simData);
    
  2. Inside applySnapshot(snap) (right before redrawCurrent();):

    buildTelemetrySeries(simData);
    
  3. Inside redrawCurrent() (right after updateUI(st);):

    renderSparkline();


Write a Python post-compilation validator module that simulates a SimLineTimeline to check battery/O2 depletion, comm window alignment, speed limits, and keep-out zone collisions.

Below is a standalone Python post-compilation validator module (simline_validator.py) that simulates a compiled SimLineTimeline at configurable time steps and checks resource bounds, comm window alignment, traverse speed limits, and keep-out zone (KOZ) collisions.

from __future__ import annotations

import argparse
import math
import sys
from pathlib import Path
from typing import Dict, List, Literal, Optional, Tuple

from pydantic import BaseModel

from simline_schema import (
    CircleGeometry,
    CouplingEvent,
    MoveEvent,
    Point2D,
    PolygonGeometry,
    ResourceEvent,
    SimLineTimeline,
    StateEvent,
    Zone,
)


# ---------------------------------------------------------------------------
# 1. Validation Report Models
# ---------------------------------------------------------------------------

class ValidationFinding(BaseModel):
    severity: Literal["ERROR", "WARNING"]
    category: Literal["RESOURCE", "COMM", "SPEED", "ZONE"]
    met_ms: int
    asset_id: str
    message: str


class ValidationReport(BaseModel):
    scene_id: str
    passed: bool
    errors: List[ValidationFinding]
    warnings: List[ValidationFinding]

    def summary(self) -> str:
        status = "PASSED" if self.passed else "FAILED"
        lines = [
            f"SimLine Validation [{self.scene_id}]: {status} "
            f"({len(self.errors)} errors, {len(self.warnings)} warnings)"
        ]
        for f in self.errors + self.warnings:
            lines.append(
                f"  [{f.severity}] [{f.category}] MET {format_met(f.met_ms)} "
                f"({f.asset_id}): {f.message}"
            )
        return "\n".join(lines)


# ---------------------------------------------------------------------------
# 2. Geometry & Time Helpers
# ---------------------------------------------------------------------------

def format_met(ms: int) -> str:
    sec = max(0, ms // 1000)
    return f"{sec // 3600:02d}:{(sec % 3600) // 60:02d}:{sec % 60:02d}"


def polyline_length_px(pts: List[Point2D]) -> float:
    return sum(
        math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1])
        for i in range(1, len(pts))
    )


def sample_polyline(pts: List[Point2D], fraction: float) -> Point2D:
    if fraction <= 0.0:
        return pts[0]
    if fraction >= 1.0:
        return pts[-1]
    target = polyline_length_px(pts) * fraction
    for i in range(1, len(pts)):
        dx = pts[i][0] - pts[i - 1][0]
        dy = pts[i][1] - pts[i - 1][1]
        seg = math.hypot(dx, dy)
        if target <= seg and seg > 0:
            u = target / seg
            return (pts[i - 1][0] + dx * u, pts[i - 1][1] + dy * u)
        target -= seg
    return pts[-1]


def point_in_polygon(pt: Point2D, poly: List[Point2D]) -> bool:
    x, y = pt
    inside = False
    j = len(poly) - 1
    for i in range(len(poly)):
        xi, yi = poly[i]
        xj, yj = poly[j]
        if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi):
            inside = not inside
        j = i
    return inside


def point_in_zone(pt: Point2D, zone: Zone) -> bool:
    if isinstance(zone.geometry, CircleGeometry):
        cx, cy = zone.geometry.center
        return math.hypot(pt[0] - cx, pt[1] - cy) <= zone.geometry.radius_px
    if isinstance(zone.geometry, PolygonGeometry):
        return point_in_polygon(pt, zone.geometry.points)
    return False


# ---------------------------------------------------------------------------
# 3. Physics & Operational Constraint Validator
# ---------------------------------------------------------------------------

def validate_timeline(
    timeline: SimLineTimeline,
    step_ms: int = 10_000,
) -> ValidationReport:
    errors: List[ValidationFinding] = []
    warnings: List[ValidationFinding] = []
    scale = timeline.scene.scale_m_per_px or 1.0

    # --- Check A: Traverse Speed Limits ---
    for ev in timeline.events:
        if isinstance(ev, MoveEvent) and ev.max_speed_mps is not None:
            dur_s = (ev.end_ms - ev.start_ms) / 1000.0
            dist_m = polyline_length_px(ev.path) * scale
            if dur_s <= 0:
                errors.append(
                    ValidationFinding(
                        severity="ERROR",
                        category="SPEED",
                        met_ms=ev.start_ms,
                        asset_id=ev.target_asset_id,
                        message=f"Move '{ev.id}' has zero duration for {dist_m:.1f}m path.",
                    )
                )
            else:
                avg_speed = dist_m / dur_s
                if avg_speed > ev.max_speed_mps:
                    errors.append(
                        ValidationFinding(
                            severity="ERROR",
                            category="SPEED",
                            met_ms=ev.start_ms,
                            asset_id=ev.target_asset_id,
                            message=(
                                f"Move '{ev.id}' requires {avg_speed:.2f} m/s "
                                f"(exceeds max_speed {ev.max_speed_mps:.2f} m/s)."
                            ),
                        )
                    )

    # --- Check B: Comm Window Alignment for Downlinks ---
    def is_in_comm_window(start_ms: int, end_ms: int) -> bool:
        return any(
            w.start_ms <= start_ms and end_ms <= w.end_ms
            for w in timeline.windows
        )

    for ev in timeline.events:
        is_downlink = (
            (isinstance(ev, StateEvent) and ev.state.lower() == "downlinking")
            or (
                isinstance(ev, ResourceEvent)
                and ev.resource == "data_buffer"
                and ev.rate_per_min < 0
            )
        )
        if is_downlink and not is_in_comm_window(ev.start_ms, ev.end_ms):
            errors.append(
                ValidationFinding(
                    severity="ERROR",
                    category="COMM",
                    met_ms=ev.start_ms,
                    asset_id=ev.target_asset_id,
                    message=(
                        f"Downlink event '{ev.id}' ({format_met(ev.start_ms)}-"
                        f"{format_met(ev.end_ms)}) falls outside all comm windows."
                    ),
                )
            )

    # --- Check C & D: Time-Stepped Resource & Spatial Zone Simulation ---
    reported_flags: set[Tuple[str, str, str]] = set()
    dur_ms = timeline.scene.duration_ms
    t = 0

    while t <= dur_ms:
        positions: Dict[str, Point2D] = {
            aid: a.start_pos for aid, a in timeline.assets.items()
        }
        parents: Dict[str, Optional[str]] = {aid: None for aid in timeline.assets}
        resources: Dict[str, Dict[str, float]] = {
            aid: {rk: rv.initial for rk, rv in a.resources.items()}
            for aid, a in timeline.assets.items()
        }

        for ev in timeline.events:
            if ev.start_ms > t:
                break
            aid = ev.target_asset_id
            if isinstance(ev, MoveEvent):
                span = max(1, ev.end_ms - ev.start_ms)
                frac = min(1.0, max(0.0, (t - ev.start_ms) / span))
                positions[aid] = sample_polyline(ev.path, frac)
            elif isinstance(ev, CouplingEvent):
                if ev.type == "attach":
                    parents[aid] = ev.parent_asset_id
                else:
                    parents[aid] = None
                    if ev.detach_pos:
                        positions[aid] = ev.detach_pos
            elif isinstance(ev, ResourceEvent):
                elapsed_ms = min(t, ev.end_ms) - ev.start_ms
                if elapsed_ms > 0:
                    resources[aid][ev.resource] += ev.rate_per_min * (elapsed_ms / 60_000.0)

        # Resolve parent-child coordinate inheritance
        for aid, parent_id in parents.items():
            if parent_id and parent_id in positions:
                positions[aid] = positions[parent_id]

        # Evaluate resource limits and zone intersections
        for aid, asset in timeline.assets.items():
            if asset.is_static:
                continue

            # 1. Resource min/max bounds
            for r_key, r_spec in asset.resources.items():
                val = resources[aid][r_key]
                if r_spec.min is not None and val < r_spec.min:
                    flag = ("RES_MIN", aid, r_key)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="RESOURCE",
                                met_ms=t,
                                asset_id=aid,
                                message=(
                                    f"'{r_key}' dropped to {val:.1f}{r_spec.unit} "
                                    f"(below minimum {r_spec.min}{r_spec.unit})."
                                ),
                            )
                        )
                if r_spec.max is not None and val > r_spec.max:
                    flag = ("RES_MAX", aid, r_key)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="RESOURCE",
                                met_ms=t,
                                asset_id=aid,
                                message=(
                                    f"'{r_key}' reached {val:.1f}{r_spec.unit} "
                                    f"(exceeds maximum {r_spec.max}{r_spec.unit})."
                                ),
                            )
                        )

            # 2. Spatial Keep-Out Zones (hazard) & PSR Shadow warnings
            pos = positions[aid]
            for zone in timeline.zones:
                if not point_in_zone(pos, zone):
                    continue
                if zone.type == "hazard":
                    # Ignore assets parked at their starting waypoint inside a lander pad KOZ
                    if pos == asset.start_pos and t == 0:
                        continue
                    flag = ("ZONE_HAZARD", aid, zone.id)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="ZONE",
                                met_ms=t,
                                asset_id=aid,
                                message=f"Entered HAZARD keep-out zone '{zone.id}'.",
                            )
                        )
                elif zone.type == "shadow":
                    flag = ("ZONE_SHADOW", aid, zone.id)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        warnings.append(
                            ValidationFinding(
                                severity="WARNING",
                                category="ZONE",
                                met_ms=t,
                                asset_id=aid,
                                message=f"Entered PSR shadow zone '{zone.id}' (thermal/solar penalty).",
                            )
                        )

        t += step_ms

    return ValidationReport(
        scene_id=timeline.scene.id,
        passed=len(errors) == 0,
        errors=errors,
        warnings=warnings,
    )


# ---------------------------------------------------------------------------
# 4. CLI Entrypoint
# ---------------------------------------------------------------------------

def main() -> None:
    parser = argparse.ArgumentParser(description="Validate a compiled SimLine timeline JSON.")
    parser.add_argument("input", type=Path, help="Path to compiled timeline .json file")
    parser.add_argument("--step-ms", type=int, default=10_000, help="Simulation step size in ms")
    parser.add_argument("--json-report", type=Path, help="Optional path to write JSON report")
    args = parser.parse_args()

    timeline = SimLineTimeline.model_validate_json(args.input.read_text(encoding="utf-8"))
    report = validate_timeline(timeline, step_ms=args.step_ms)

    print(report.summary())
    if args.json_report:
        args.json_report.write_text(report.model_dump_json(indent=2), encoding="utf-8")

    sys.exit(0 if report.passed else 1)


if __name__ == "__main__":
    main()

Usage

Run it directly on any compiled JSON file from simline_compiler.py or exported from simline_viewer.html:

python simline_validator.py shackleton_eva1.json --step-ms 5000 --json-report audit_report.json

It exits with code 0 when all hard constraints pass and 1 if any resource depletion, speed violation, comm blackout downlink, or hazard KOZ breach is detected.


Integrate validate_timeline from simline_validator.py into simline_compiler.py with a --strict CLI flag that blocks JSON export on validation errors.

Update simline_compiler.py with these two drop-in changes to run validate_timeline automatically during compilation, print the audit summary to stderr (keeping stdout clean for piped JSON), and block JSON export when --strict is enabled and errors are found.

1. Import validate_timeline (top of simline_compiler.py)

Add this import right below your simline_schema imports:

from simline_validator import validate_timeline

2. Replace main() with Validation & --strict Support

def main() -> None:
    parser = argparse.ArgumentParser(
        description="Compile SimLine DSL to validated timeline JSON."
    )
    parser.add_argument("input", type=Path, help="Path to .simline DSL file")
    parser.add_argument(
        "-o", "--output", type=Path, help="Output JSON path (defaults to stdout)"
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Block JSON export and exit with code 1 if physics/constraint validation fails.",
    )
    parser.add_argument(
        "--skip-validate",
        action="store_true",
        help="Skip post-compilation physics and constraint validation.",
    )
    parser.add_argument(
        "--step-ms",
        type=int,
        default=10_000,
        help="Validation simulation step size in milliseconds (default: 10000).",
    )
    parser.add_argument(
        "--report",
        type=Path,
        help="Optional path to write the JSON validation report.",
    )
    args = parser.parse_args()

    source = args.input.read_text(encoding="utf-8")
    timeline = compile_simline(source)

    if not args.skip_validate:
        report = validate_timeline(timeline, step_ms=args.step_ms)
        print(report.summary(), file=sys.stderr)

        if args.report:
            args.report.write_text(report.model_dump_json(indent=2), encoding="utf-8")

        if args.strict and not report.passed:
            print(
                "Strict mode enabled: JSON export blocked due to validation errors.",
                file=sys.stderr,
            )
            sys.exit(1)

    json_out = timeline.model_dump_json(indent=2)

    if args.output:
        args.output.write_text(json_out, encoding="utf-8")
        print(
            f"Compiled {len(timeline.events)} events across {len(timeline.phases)} phases -> {args.output}",
            file=sys.stderr,
        )
    else:
        print(json_out)

CLI Usage Examples

# Standard compile: prints validation summary to stderr, still exports JSON
python simline_compiler.py shackleton_eva1.simline -o shackleton_eva1.json

# Strict CI/CD compile: blocks JSON export and exits with code 1 on any ERROR
python simline_compiler.py shackleton_eva1.simline -o shackleton_eva1.json --strict --step-ms 5000 --report audit.json


Bring it altogether with complete file listings

Place all five files in the same directory. You only need Python 3.10+ with pydantic>=2.0 (pip install pydantic) and any modern web browser.

Project Layout & Quick Start

simline/
├── shackleton_eva1.simline   # 1. Sample 2-hour Lunar EVA mission script
├── simline_schema.py         # 2. Pydantic v2 schema & referential integrity
├── simline_validator.py      # 3. Physics, resource, comm, & KOZ validator
├── simline_compiler.py       # 4. DSL-to-JSON compiler with --strict audit
└── simline_viewer.html       # 5. Standalone 2D playback & authoring studio
# Compile and audit the mission script (blocks export on errors in --strict mode)
python simline_compiler.py shackleton_eva1.simline -o shackleton_eva1.json --strict

# Open simline_viewer.html in your browser and load shackleton_eva1.json (or use the built-in sample)

1. shackleton_eva1.simline

// ============================================================================
// MISSION: Artemis-Style South Pole EVA-1 (Shackleton Rim Reconnaissance)
// DURATION: 2 Hours (120 Minutes)
// ============================================================================

scene "ShackletonRim_EVA1" {
  background: "assets/maps/shackleton_south_pole_dem.png"
  dimensions: 2048 x 2048
  scale: 1px = 0.5m
  duration: 2h
}

waypoints {
  lander_pad {
    pos: (320, 1680)
    label: "HLS Lander Pad"
    image: "assets/icons/lander_pad.svg"
  }
  solar_ridge {
    pos: (740, 1220)
    label: "Connecting Ridge (High Sun)"
    image: "assets/icons/sun_waypoint.svg"
  }
  shackleton_rim {
    pos: (1420, 680)
    label: "Station 1: Shackleton Rim"
    image: "assets/icons/science_flag.svg"
  }
  psr_edge {
    pos: (1580, 560)
    label: "Station 2: PSR Shadow Boundary"
    image: "assets/icons/crater_sample.svg"
  }
}

zones {
  psr_crater_floor {
    polygon: [(1540, 480), (1950, 420), (1980, 820), (1610, 690)]
    type: shadow
    solar_multiplier: 0.0
    thermal_penalty: high
  }
  lander_blast_koz {
    circle: (320, 1680) radius 90px
    type: hazard
  }
  ridge_sunlight_corridor {
    polygon: [(580, 1380), (920, 1080), (1010, 1180), (670, 1480)]
    type: solar_rich
    solar_multiplier: 1.0
  }
}

windows {
  lunar_relay_pass_1 {
    start: MET 00:55:00
    duration: 25m
    bandwidth: 50Mbps
  }
}

assets {
  static hls_lander {
    image: "assets/sprites/hls_lander.png"
    pos: (320, 1680)
    layer: 1
  }

  asset ltv_rover {
    image: "assets/sprites/ltv_rover.png"
    start_at: lander_pad
    layer: 2
    tags: ["vehicle", "electric"]
    resources: {
      battery: 100% (min: 20%)
      data_buffer: 0GB (max: 64GB)
    }
  }

  asset astronaut_1 {
    image: "assets/sprites/eva_cdr.png"
    start_at: lander_pad
    layer: 3
    tags: ["crew", "commander"]
    resources: {
      suit_o2: 100% (min: 25%)
      suit_battery: 100% (min: 20%)
    }
  }

  asset astronaut_2 {
    image: "assets/sprites/eva_fe.png"
    start_at: lander_pad
    layer: 3
    tags: ["crew", "geologist"]
    resources: {
      suit_o2: 100% (min: 25%)
      suit_battery: 100% (min: 20%)
    }
  }

  asset seismometer_pkg {
    image: "assets/sprites/seismometer.png"
    start_at: lander_pad
    layer: 2
    tags: ["payload", "science"]
  }
}

timeline {
  phase "EVA-1: Egress & Rover Prep" {
    id: egress_checks
    at MET 00:00:00 for 10m {
      astronaut_1: state "suit_check"
      astronaut_2: state "suit_check"
      astronaut_1: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m
      astronaut_2: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m
      ltv_rover: state "pre_drive_boot"
    }

    id: board_rover
    after egress_checks + 0m for 5m {
      attach astronaut_1 to ltv_rover
      attach astronaut_2 to ltv_rover
      attach seismometer_pkg to ltv_rover
      ltv_rover: label "Crew Boarded - Ready to Roll"
    }
  }

  phase "EVA-2: Outbound Traverse" {
    id: outbound_drive
    after board_rover + 0m for 30m {
      ltv_rover: move from lander_pad to shackleton_rim
        via [(520, 1480), (740, 1220), (1120, 910)]
        max_speed: 2.0m/s
        easing ease_in_out
        drain battery 0.8%/m
        generate data_buffer 0.3GB/m
      astronaut_1: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m
      astronaut_2: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m
    }
  }

  phase "EVA-3: Rim Science & Sampling" {
    id: dismount_rim
    after outbound_drive + 0m for 5m {
      detach astronaut_1 from ltv_rover at shackleton_rim
      detach astronaut_2 from ltv_rover at shackleton_rim
      ltv_rover: state "standby_relay"
    }

    id: deploy_and_sample
    after dismount_rim + 0m for 15m {
      detach seismometer_pkg from ltv_rover at shackleton_rim
      seismometer_pkg: state "active_logging"
      astronaut_1: state "deploying_payload"
      astronaut_1: drain suit_o2 0.45%/m, drain suit_battery 0.3%/m

      astronaut_2: move from shackleton_rim to psr_edge
        max_speed: 0.6m/s
        drain suit_o2 0.6%/m, drain suit_battery 0.5%/m
      astronaut_2: label "Core Sampling at PSR Edge"
    }

    id: downlink_and_return
    after deploy_and_sample + 0m for 10m {
      ltv_rover: state "downlinking"
      ltv_rover: drain data_buffer 0.9GB/m, drain battery 0.4%/m

      astronaut_2: move from psr_edge to shackleton_rim
        max_speed: 0.6m/s
        drain suit_o2 0.5%/m, drain suit_battery 0.4%/m
      astronaut_1: state "stowing_tools"
      astronaut_1: drain suit_o2 0.35%/m, drain suit_battery 0.25%/m
    }

    id: reboard_rover
    after downlink_and_return + 0m for 5m {
      attach astronaut_1 to ltv_rover
      attach astronaut_2 to ltv_rover
      ltv_rover: label "Samples Stowed - Departing Rim"
    }
  }

  phase "EVA-4: Return & Closeout" {
    id: return_drive
    after reboard_rover + 0m for 30m {
      ltv_rover: move from shackleton_rim to lander_pad
        via [(1120, 910), (740, 1220), (520, 1480)]
        max_speed: 2.0m/s
        easing ease_in_out
        drain battery 0.75%/m
        generate data_buffer 0.2GB/m
      astronaut_1: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m
      astronaut_2: drain suit_o2 0.3%/m, drain suit_battery 0.2%/m
    }

    id: eva_closeout
    after return_drive + 0m for 10m {
      detach astronaut_1 from ltv_rover at lander_pad
      detach astronaut_2 from ltv_rover at lander_pad
      ltv_rover: state "charging"
      ltv_rover: recharge battery 1.5%/m
      astronaut_1: state "airlock_ingress"
      astronaut_2: state "airlock_ingress"
      astronaut_1: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m
      astronaut_2: drain suit_o2 0.25%/m, drain suit_battery 0.2%/m
    }
  }
}

2. simline_schema.py

from __future__ import annotations

from typing import Annotated, Dict, List, Literal, Optional, Tuple, Union
from pydantic import BaseModel, ConfigDict, Field, model_validator

Point2D = Tuple[float, float]


class StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid")


class Dimensions(StrictModel):
    width: int = Field(..., ge=1)
    height: int = Field(..., ge=1)


class Scene(StrictModel):
    id: str
    background: str
    dimensions: Dimensions
    scale_m_per_px: Optional[float] = Field(default=None, gt=0)
    duration_ms: int = Field(..., ge=0)


class Waypoint(StrictModel):
    pos: Point2D
    label: str
    image: Optional[str] = None


class PolygonGeometry(StrictModel):
    shape: Literal["polygon"] = "polygon"
    points: List[Point2D] = Field(..., min_length=3)


class CircleGeometry(StrictModel):
    shape: Literal["circle"] = "circle"
    center: Point2D
    radius_px: float = Field(..., gt=0)


ZoneGeometry = Annotated[
    Union[PolygonGeometry, CircleGeometry],
    Field(discriminator="shape"),
]


class ZoneModifiers(StrictModel):
    solar_multiplier: Optional[float] = Field(default=None, ge=0.0, le=1.0)
    thermal_penalty: Optional[Literal["none", "low", "medium", "high"]] = None


class Zone(StrictModel):
    id: str
    type: Literal["shadow", "hazard", "solar_rich"]
    geometry: ZoneGeometry
    modifiers: Optional[ZoneModifiers] = None


class CommWindow(StrictModel):
    id: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)
    bandwidth_mbps: float = Field(..., ge=0.0)

    @model_validator(mode="after")
    def validate_time_bounds(self) -> CommWindow:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Window '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


class ResourceSpec(StrictModel):
    initial: float
    unit: str
    min: Optional[float] = None
    max: Optional[float] = None

    @model_validator(mode="after")
    def validate_bounds(self) -> ResourceSpec:
        if self.min is not None and self.max is not None and self.min > self.max:
            raise ValueError(f"Resource min ({self.min}) cannot exceed max ({self.max})")
        if self.min is not None and self.initial < self.min:
            raise ValueError(f"Initial value ({self.initial}) is below min ({self.min})")
        if self.max is not None and self.initial > self.max:
            raise ValueError(f"Initial value ({self.initial}) exceeds max ({self.max})")
        return self


class Asset(StrictModel):
    is_static: bool
    image: str
    start_pos: Point2D
    start_waypoint_id: Optional[str] = None
    layer: int
    tags: List[str] = Field(default_factory=list)
    resources: Dict[str, ResourceSpec] = Field(default_factory=dict)


class Phase(StrictModel):
    id: str
    name: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)

    @model_validator(mode="after")
    def validate_time_bounds(self) -> Phase:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Phase '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


class EventBase(StrictModel):
    id: str
    phase_id: str
    start_ms: int = Field(..., ge=0)
    end_ms: int = Field(..., ge=0)
    target_asset_id: str

    @model_validator(mode="after")
    def validate_time_bounds(self) -> EventBase:
        if self.end_ms < self.start_ms:
            raise ValueError(
                f"Event '{self.id}': end_ms ({self.end_ms}) < start_ms ({self.start_ms})"
            )
        return self


class MoveEvent(EventBase):
    type: Literal["move"] = "move"
    from_waypoint_id: Optional[str] = None
    to_waypoint_id: Optional[str] = None
    path: List[Point2D] = Field(..., min_length=2)
    easing: Literal["linear", "ease_in", "ease_out", "ease_in_out"] = "linear"
    max_speed_mps: Optional[float] = Field(default=None, gt=0.0)


class CouplingEvent(EventBase):
    type: Literal["attach", "detach"]
    parent_asset_id: str
    detach_pos: Optional[Point2D] = None


class StateEvent(EventBase):
    type: Literal["state"] = "state"
    state: str


class LabelEvent(EventBase):
    type: Literal["label"] = "label"
    text: str


class ResourceEvent(EventBase):
    type: Literal["resource_delta"] = "resource_delta"
    resource: str
    rate_per_min: float = Field(
        ..., description="Negative for drain, positive for recharge/generate."
    )


TimelineEvent = Annotated[
    Union[MoveEvent, CouplingEvent, StateEvent, LabelEvent, ResourceEvent],
    Field(discriminator="type"),
]


class SimLineTimeline(StrictModel):
    schema_version: Literal["1.0.0"] = "1.0.0"
    scene: Scene
    waypoints: Dict[str, Waypoint]
    zones: List[Zone] = Field(default_factory=list)
    windows: List[CommWindow] = Field(default_factory=list)
    assets: Dict[str, Asset]
    phases: List[Phase]
    events: List[TimelineEvent]

    @model_validator(mode="after")
    def validate_referential_integrity(self) -> SimLineTimeline:
        phase_ids = {p.id for p in self.phases}

        for asset_id, asset in self.assets.items():
            if asset.start_waypoint_id and asset.start_waypoint_id not in self.waypoints:
                raise ValueError(
                    f"Asset '{asset_id}' references unknown start_waypoint_id "
                    f"'{asset.start_waypoint_id}'"
                )

        prev_start_ms = -1
        for ev in self.events:
            if ev.start_ms < prev_start_ms:
                raise ValueError(
                    f"Events must be sorted by start_ms: '{ev.id}' ({ev.start_ms}) "
                    f"appears after {prev_start_ms}"
                )
            prev_start_ms = ev.start_ms

            if ev.phase_id not in phase_ids:
                raise ValueError(f"Event '{ev.id}' references unknown phase_id '{ev.phase_id}'")

            if ev.target_asset_id not in self.assets:
                raise ValueError(
                    f"Event '{ev.id}' references unknown target_asset_id '{ev.target_asset_id}'"
                )

            target_asset = self.assets[ev.target_asset_id]
            if target_asset.is_static:
                raise ValueError(
                    f"Event '{ev.id}' cannot target static asset '{ev.target_asset_id}'"
                )

            if isinstance(ev, MoveEvent):
                for wp_id in (ev.from_waypoint_id, ev.to_waypoint_id):
                    if wp_id and wp_id not in self.waypoints:
                        raise ValueError(
                            f"MoveEvent '{ev.id}' references unknown waypoint '{wp_id}'"
                        )

            elif isinstance(ev, CouplingEvent):
                if ev.parent_asset_id not in self.assets:
                    raise ValueError(
                        f"CouplingEvent '{ev.id}' references unknown parent_asset_id "
                        f"'{ev.parent_asset_id}'"
                    )
                if ev.parent_asset_id == ev.target_asset_id:
                    raise ValueError(
                        f"CouplingEvent '{ev.id}' cannot attach/detach asset to itself"
                    )

            elif isinstance(ev, ResourceEvent):
                if ev.resource not in target_asset.resources:
                    raise ValueError(
                        f"ResourceEvent '{ev.id}' references undefined resource "
                        f"'{ev.resource}' on asset '{ev.target_asset_id}'"
                    )

        return self

3. simline_validator.py

from __future__ import annotations

import argparse
import math
import sys
from pathlib import Path
from typing import Dict, List, Literal, Optional, Tuple

from pydantic import BaseModel

from simline_schema import (
    CircleGeometry,
    CouplingEvent,
    MoveEvent,
    Point2D,
    PolygonGeometry,
    ResourceEvent,
    SimLineTimeline,
    StateEvent,
    Zone,
)


class ValidationFinding(BaseModel):
    severity: Literal["ERROR", "WARNING"]
    category: Literal["RESOURCE", "COMM", "SPEED", "ZONE"]
    met_ms: int
    asset_id: str
    message: str


class ValidationReport(BaseModel):
    scene_id: str
    passed: bool
    errors: List[ValidationFinding]
    warnings: List[ValidationFinding]

    def summary(self) -> str:
        status = "PASSED" if self.passed else "FAILED"
        lines = [
            f"SimLine Validation [{self.scene_id}]: {status} "
            f"({len(self.errors)} errors, {len(self.warnings)} warnings)"
        ]
        for f in self.errors + self.warnings:
            lines.append(
                f"  [{f.severity}] [{f.category}] MET {format_met(f.met_ms)} "
                f"({f.asset_id}): {f.message}"
            )
        return "\n".join(lines)


def format_met(ms: int) -> str:
    sec = max(0, ms // 1000)
    return f"{sec // 3600:02d}:{(sec % 3600) // 60:02d}:{sec % 60:02d}"


def polyline_length_px(pts: List[Point2D]) -> float:
    return sum(
        math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1])
        for i in range(1, len(pts))
    )


def sample_polyline(pts: List[Point2D], fraction: float) -> Point2D:
    if fraction <= 0.0:
        return pts[0]
    if fraction >= 1.0:
        return pts[-1]
    target = polyline_length_px(pts) * fraction
    for i in range(1, len(pts)):
        dx = pts[i][0] - pts[i - 1][0]
        dy = pts[i][1] - pts[i - 1][1]
        seg = math.hypot(dx, dy)
        if target <= seg and seg > 0:
            u = target / seg
            return (pts[i - 1][0] + dx * u, pts[i - 1][1] + dy * u)
        target -= seg
    return pts[-1]


def point_in_polygon(pt: Point2D, poly: List[Point2D]) -> bool:
    x, y = pt
    inside = False
    j = len(poly) - 1
    for i in range(len(poly)):
        xi, yi = poly[i]
        xj, yj = poly[j]
        if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi):
            inside = not inside
        j = i
    return inside


def point_in_zone(pt: Point2D, zone: Zone) -> bool:
    if isinstance(zone.geometry, CircleGeometry):
        cx, cy = zone.geometry.center
        return math.hypot(pt[0] - cx, pt[1] - cy) <= zone.geometry.radius_px
    if isinstance(zone.geometry, PolygonGeometry):
        return point_in_polygon(pt, zone.geometry.points)
    return False


def validate_timeline(
    timeline: SimLineTimeline,
    step_ms: int = 10_000,
) -> ValidationReport:
    errors: List[ValidationFinding] = []
    warnings: List[ValidationFinding] = []
    scale = timeline.scene.scale_m_per_px or 1.0

    for ev in timeline.events:
        if isinstance(ev, MoveEvent) and ev.max_speed_mps is not None:
            dur_s = (ev.end_ms - ev.start_ms) / 1000.0
            dist_m = polyline_length_px(ev.path) * scale
            if dur_s <= 0:
                errors.append(
                    ValidationFinding(
                        severity="ERROR",
                        category="SPEED",
                        met_ms=ev.start_ms,
                        asset_id=ev.target_asset_id,
                        message=f"Move '{ev.id}' has zero duration for {dist_m:.1f}m path.",
                    )
                )
            else:
                avg_speed = dist_m / dur_s
                if avg_speed > ev.max_speed_mps:
                    errors.append(
                        ValidationFinding(
                            severity="ERROR",
                            category="SPEED",
                            met_ms=ev.start_ms,
                            asset_id=ev.target_asset_id,
                            message=(
                                f"Move '{ev.id}' requires {avg_speed:.2f} m/s "
                                f"(exceeds max_speed {ev.max_speed_mps:.2f} m/s)."
                            ),
                        )
                    )

    def is_in_comm_window(start_ms: int, end_ms: int) -> bool:
        return any(
            w.start_ms <= start_ms and end_ms <= w.end_ms
            for w in timeline.windows
        )

    for ev in timeline.events:
        is_downlink = (
            (isinstance(ev, StateEvent) and ev.state.lower() == "downlinking")
            or (
                isinstance(ev, ResourceEvent)
                and ev.resource == "data_buffer"
                and ev.rate_per_min < 0
            )
        )
        if is_downlink and not is_in_comm_window(ev.start_ms, ev.end_ms):
            errors.append(
                ValidationFinding(
                    severity="ERROR",
                    category="COMM",
                    met_ms=ev.start_ms,
                    asset_id=ev.target_asset_id,
                    message=(
                        f"Downlink event '{ev.id}' ({format_met(ev.start_ms)}-"
                        f"{format_met(ev.end_ms)}) falls outside all comm windows."
                    ),
                )
            )

    reported_flags: set[Tuple[str, str, str]] = set()
    dur_ms = timeline.scene.duration_ms
    t = 0

    while t <= dur_ms:
        positions: Dict[str, Point2D] = {
            aid: a.start_pos for aid, a in timeline.assets.items()
        }
        parents: Dict[str, Optional[str]] = {aid: None for aid in timeline.assets}
        resources: Dict[str, Dict[str, float]] = {
            aid: {rk: rv.initial for rk, rv in a.resources.items()}
            for aid, a in timeline.assets.items()
        }

        for ev in timeline.events:
            if ev.start_ms > t:
                break
            aid = ev.target_asset_id
            if isinstance(ev, MoveEvent):
                span = max(1, ev.end_ms - ev.start_ms)
                frac = min(1.0, max(0.0, (t - ev.start_ms) / span))
                positions[aid] = sample_polyline(ev.path, frac)
            elif isinstance(ev, CouplingEvent):
                if ev.type == "attach":
                    parents[aid] = ev.parent_asset_id
                else:
                    parents[aid] = None
                    if ev.detach_pos:
                        positions[aid] = ev.detach_pos
            elif isinstance(ev, ResourceEvent):
                elapsed_ms = min(t, ev.end_ms) - ev.start_ms
                if elapsed_ms > 0:
                    resources[aid][ev.resource] += ev.rate_per_min * (elapsed_ms / 60_000.0)

        for aid, parent_id in parents.items():
            if parent_id and parent_id in positions:
                positions[aid] = positions[parent_id]

        for aid, asset in timeline.assets.items():
            if asset.is_static:
                continue

            for r_key, r_spec in asset.resources.items():
                val = resources[aid][r_key]
                if r_spec.min is not None and val < r_spec.min:
                    flag = ("RES_MIN", aid, r_key)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="RESOURCE",
                                met_ms=t,
                                asset_id=aid,
                                message=(
                                    f"'{r_key}' dropped to {val:.1f}{r_spec.unit} "
                                    f"(below minimum {r_spec.min}{r_spec.unit})."
                                ),
                            )
                        )
                if r_spec.max is not None and val > r_spec.max:
                    flag = ("RES_MAX", aid, r_key)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="RESOURCE",
                                met_ms=t,
                                asset_id=aid,
                                message=(
                                    f"'{r_key}' reached {val:.1f}{r_spec.unit} "
                                    f"(exceeds maximum {r_spec.max}{r_spec.unit})."
                                ),
                            )
                        )

            pos = positions[aid]
            for zone in timeline.zones:
                if not point_in_zone(pos, zone):
                    continue
                if zone.type == "hazard":
                    if pos == asset.start_pos and t == 0:
                        continue
                    flag = ("ZONE_HAZARD", aid, zone.id)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        errors.append(
                            ValidationFinding(
                                severity="ERROR",
                                category="ZONE",
                                met_ms=t,
                                asset_id=aid,
                                message=f"Entered HAZARD keep-out zone '{zone.id}'.",
                            )
                        )
                elif zone.type == "shadow":
                    flag = ("ZONE_SHADOW", aid, zone.id)
                    if flag not in reported_flags:
                        reported_flags.add(flag)
                        warnings.append(
                            ValidationFinding(
                                severity="WARNING",
                                category="ZONE",
                                met_ms=t,
                                asset_id=aid,
                                message=f"Entered PSR shadow zone '{zone.id}' (thermal/solar penalty).",
                            )
                        )

        t += step_ms

    return ValidationReport(
        scene_id=timeline.scene.id,
        passed=len(errors) == 0,
        errors=errors,
        warnings=warnings,
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Validate a compiled SimLine timeline JSON.")
    parser.add_argument("input", type=Path, help="Path to compiled timeline .json file")
    parser.add_argument("--step-ms", type=int, default=10_000, help="Simulation step size in ms")
    parser.add_argument("--json-report", type=Path, help="Optional path to write JSON report")
    args = parser.parse_args()

    timeline = SimLineTimeline.model_validate_json(args.input.read_text(encoding="utf-8"))
    report = validate_timeline(timeline, step_ms=args.step_ms)

    print(report.summary())
    if args.json_report:
        args.json_report.write_text(report.model_dump_json(indent=2), encoding="utf-8")

    sys.exit(0 if report.passed else 1)


if __name__ == "__main__":
    main()

4. simline_compiler.py

from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from simline_schema import (
    Asset,
    CircleGeometry,
    CommWindow,
    CouplingEvent,
    Dimensions,
    LabelEvent,
    MoveEvent,
    Phase,
    Point2D,
    PolygonGeometry,
    ResourceEvent,
    ResourceSpec,
    Scene,
    SimLineTimeline,
    StateEvent,
    TimelineEvent,
    Waypoint,
    Zone,
    ZoneModifiers,
)
from simline_validator import validate_timeline


def strip_comments(text: str) -> str:
    return re.sub(r"//.*", "", text)


def parse_duration_ms(token: str) -> int:
    token = token.strip()
    m = re.fullmatch(r"(\d+(?:\.\d+)?)(h|m|s|ms)", token)
    if not m:
        raise ValueError(f"Invalid duration token: '{token}'")
    val, unit = float(m.group(1)), m.group(2)
    mult = {"ms": 1, "s": 1_000, "m": 60_000, "h": 3_600_000}[unit]
    return int(round(val * mult))


def parse_met_ms(token: str) -> int:
    clean = token.replace("MET", "").strip()
    parts = [int(p) for p in clean.split(":")]
    if len(parts) == 3:
        h, m, s = parts
        d = 0
    elif len(parts) == 4:
        d, h, m, s = parts
    else:
        raise ValueError(f"Invalid MET timestamp: '{token}'")
    return ((d * 24 + h) * 3600 + m * 60 + s) * 1_000


def parse_point(text: str) -> Point2D:
    m = re.search(r"\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)", text)
    if not m:
        raise ValueError(f"Invalid 2D point: '{text}'")
    return (float(m.group(1)), float(m.group(2)))


def parse_point_list(text: str) -> List[Point2D]:
    return [
        (float(x), float(y))
        for x, y in re.findall(r"\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)", text)
    ]


def slugify(name: str) -> str:
    return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")


def extract_named_blocks(text: str) -> List[Tuple[str, str]]:
    blocks: List[Tuple[str, str]] = []
    i, n = 0, len(text)
    while i < n:
        brace_idx = text.find("{", i)
        if brace_idx == -1:
            break
        header = text[i:brace_idx].strip()
        depth = 1
        j = brace_idx + 1
        while j < n and depth > 0:
            if text[j] == "{":
                depth += 1
            elif text[j] == "}":
                depth -= 1
            j += 1
        if depth != 0:
            raise SyntaxError(f"Unclosed brace in block: '{header[:40]}'")
        body = text[brace_idx + 1 : j - 1].strip()
        if header:
            blocks.append((header, body))
        i = j
    return blocks


def parse_scene(header: str, body: str) -> Scene:
    m_id = re.search(r'"([^"]+)"', header)
    scene_id = m_id.group(1) if m_id else "UntitledScene"

    bg = re.search(r'background:\s*"([^"]*)"', body)
    dims = re.search(r"dimensions:\s*(\d+)\s*x\s*(\d+)", body)
    scale = re.search(r"scale:\s*1px\s*=\s*(\d+(?:\.\d+)?)m", body)
    dur = re.search(r"duration:\s*([^\s]+)", body)

    if not (bg and dims and dur):
        raise ValueError("Scene block missing required background, dimensions, or duration.")

    return Scene(
        id=scene_id,
        background=bg.group(1),
        dimensions=Dimensions(width=int(dims.group(1)), height=int(dims.group(2))),
        scale_m_per_px=float(scale.group(1)) if scale else None,
        duration_ms=parse_duration_ms(dur.group(1)),
    )


def parse_waypoints(body: str) -> Dict[str, Waypoint]:
    waypoints: Dict[str, Waypoint] = {}
    for wp_id, wp_body in extract_named_blocks(body):
        pos_m = re.search(r"pos:\s*(\([^)]+\))", wp_body)
        lbl_m = re.search(r'label:\s*"([^"]+)"', wp_body)
        img_m = re.search(r'image:\s*"([^"]+)"', wp_body)
        if not (pos_m and lbl_m):
            raise ValueError(f"Waypoint '{wp_id}' requires pos and label.")
        waypoints[wp_id] = Waypoint(
            pos=parse_point(pos_m.group(1)),
            label=lbl_m.group(1),
            image=img_m.group(1) if img_m else None,
        )
    return waypoints


def parse_zones(body: str) -> List[Zone]:
    zones: List[Zone] = []
    for zone_id, z_body in extract_named_blocks(body):
        type_m = re.search(r"type:\s*(\w+)", z_body)
        if not type_m:
            raise ValueError(f"Zone '{zone_id}' missing type.")

        poly_m = re.search(r"polygon:\s*\[([^\]]+)\]", z_body)
        circ_m = re.search(r"circle:\s*(\([^)]+\))\s*radius\s*(\d+(?:\.\d+)?)px", z_body)

        if poly_m:
            geom = PolygonGeometry(points=parse_point_list(poly_m.group(1)))
        elif circ_m:
            geom = CircleGeometry(
                center=parse_point(circ_m.group(1)),
                radius_px=float(circ_m.group(2)),
            )
        else:
            raise ValueError(f"Zone '{zone_id}' must define either polygon or circle.")

        solar_m = re.search(r"solar_multiplier:\s*(\d+(?:\.\d+)?)", z_body)
        therm_m = re.search(r"thermal_penalty:\s*(\w+)", z_body)
        mods = None
        if solar_m or therm_m:
            mods = ZoneModifiers(
                solar_multiplier=float(solar_m.group(1)) if solar_m else None,
                thermal_penalty=therm_m.group(1) if therm_m else None,
            )

        zones.append(Zone(id=zone_id, type=type_m.group(1), geometry=geom, modifiers=mods))
    return zones


def parse_windows(body: str) -> List[CommWindow]:
    windows: List[CommWindow] = []
    for win_id, w_body in extract_named_blocks(body):
        start_m = re.search(r"start:\s*(MET\s+[\d:]+)", w_body)
        dur_m = re.search(r"duration:\s*([^\s]+)", w_body)
        bw_m = re.search(r"bandwidth:\s*(\d+(?:\.\d+)?)Mbps", w_body)
        if not (start_m and dur_m and bw_m):
            raise ValueError(f"Window '{win_id}' missing start, duration, or bandwidth.")
        start_ms = parse_met_ms(start_m.group(1))
        end_ms = start_ms + parse_duration_ms(dur_m.group(1))
        windows.append(
            CommWindow(
                id=win_id,
                start_ms=start_ms,
                end_ms=end_ms,
                bandwidth_mbps=float(bw_m.group(1)),
            )
        )
    return windows


def parse_resources_block(res_body: str) -> Dict[str, ResourceSpec]:
    resources: Dict[str, ResourceSpec] = {}
    for line in res_body.splitlines():
        line = line.strip()
        if not line:
            continue
        m = re.match(
            r"(\w+):\s*(-?\d+(?:\.\d+)?)([A-Za-z%]+)(?:\s*\(([^)]+)\))?",
            line,
        )
        if not m:
            raise ValueError(f"Invalid resource spec: '{line}'")
        name, init_val, unit, bounds_str = m.group(1), float(m.group(2)), m.group(3), m.group(4)
        min_val = max_val = None
        if bounds_str:
            min_m = re.search(r"min:\s*(-?\d+(?:\.\d+)?)", bounds_str)
            max_m = re.search(r"max:\s*(-?\d+(?:\.\d+)?)", bounds_str)
            if min_m:
                min_val = float(min_m.group(1))
            if max_m:
                max_val = float(max_m.group(1))
        resources[name] = ResourceSpec(initial=init_val, unit=unit, min=min_val, max=max_val)
    return resources


def parse_assets(body: str, waypoints: Dict[str, Waypoint]) -> Dict[str, Asset]:
    assets: Dict[str, Asset] = {}
    for header, a_body in extract_named_blocks(body):
        m_hdr = re.match(r"(static|asset)\s+(\w+)", header)
        if not m_hdr:
            raise ValueError(f"Invalid asset header: '{header}'")
        is_static = m_hdr.group(1) == "static"
        asset_id = m_hdr.group(2)

        img_m = re.search(r'image:\s*"([^"]*)"', a_body)
        layer_m = re.search(r"layer:\s*(-?\d+)", a_body)
        if not (img_m and layer_m):
            raise ValueError(f"Asset '{asset_id}' requires image and layer.")

        start_wp_id: Optional[str] = None
        pos_m = re.search(r"pos:\s*(\([^)]+\))", a_body)
        start_at_m = re.search(r"start_at:\s*(\w+|\([^)]+\))", a_body)

        if pos_m:
            start_pos = parse_point(pos_m.group(1))
        elif start_at_m:
            val = start_at_m.group(1)
            if val.startswith("("):
                start_pos = parse_point(val)
            else:
                if val not in waypoints:
                    raise ValueError(f"Asset '{asset_id}' references unknown waypoint '{val}'")
                start_wp_id = val
                start_pos = waypoints[val].pos
        else:
            raise ValueError(f"Asset '{asset_id}' requires pos or start_at.")

        tags: List[str] = []
        tags_m = re.search(r"tags:\s*\[([^\]]*)\]", a_body)
        if tags_m:
            tags = re.findall(r'"([^"]+)"', tags_m.group(1))

        resources: Dict[str, ResourceSpec] = {}
        for sub_hdr, sub_body in extract_named_blocks(a_body):
            if sub_hdr.rstrip(":") == "resources":
                resources = parse_resources_block(sub_body)

        assets[asset_id] = Asset(
            is_static=is_static,
            image=img_m.group(1),
            start_pos=start_pos,
            start_waypoint_id=start_wp_id,
            layer=int(layer_m.group(1)),
            tags=tags,
            resources=resources,
        )
    return assets


def parse_resource_deltas(
    text: str,
    block_id: str,
    phase_id: str,
    start_ms: int,
    end_ms: int,
    asset_id: str,
    counter: List[int],
) -> List[ResourceEvent]:
    events: List[ResourceEvent] = []
    pattern = re.compile(
        r"(drain|recharge|generate)\s+(\w+)\s+(\d+(?:\.\d+)?)[A-Za-z%]+/m"
    )
    for op, res_name, rate_str in pattern.findall(text):
        rate = float(rate_str)
        if op == "drain":
            rate = -rate
        counter[0] += 1
        events.append(
            ResourceEvent(
                id=f"{block_id}_ev{counter[0]}",
                phase_id=phase_id,
                start_ms=start_ms,
                end_ms=end_ms,
                target_asset_id=asset_id,
                resource=res_name,
                rate_per_min=rate,
            )
        )
    return events


def parse_timeline(
    body: str,
    waypoints: Dict[str, Waypoint],
) -> Tuple[List[Phase], List[TimelineEvent]]:
    phases: List[Phase] = []
    events: List[TimelineEvent] = []
    block_end_ms: Dict[str, int] = {}

    for phase_hdr, phase_body in extract_named_blocks(body):
        m_ph = re.match(r'phase\s+"([^"]+)"', phase_hdr)
        if not m_ph:
            raise ValueError(f"Invalid phase header: '{phase_hdr}'")
        phase_name = m_ph.group(1)
        phase_id = slugify(phase_name)
        phase_starts: List[int] = []
        phase_ends: List[int] = []

        for act_hdr, act_body in extract_named_blocks(phase_body):
            id_m = re.search(r"id:\s*(\w+)", act_hdr)
            block_id = id_m.group(1) if id_m else f"{phase_id}_blk_{len(block_end_ms) + 1}"

            at_m = re.search(r"at\s+(MET\s+[\d:]+)", act_hdr)
            after_m = re.search(r"after\s+(\w+)\s*\+\s*([^\s]+)", act_hdr)
            dur_m = re.search(r"for\s+([^\s]+)", act_hdr)

            if at_m:
                start_ms = parse_met_ms(at_m.group(1))
            elif after_m:
                ref_id, offset_tok = after_m.group(1), after_m.group(2)
                if ref_id not in block_end_ms:
                    raise ValueError(f"Block '{block_id}' references unknown prior block '{ref_id}'")
                start_ms = block_end_ms[ref_id] + parse_duration_ms(offset_tok)
            else:
                raise ValueError(f"Activity block '{block_id}' missing 'at' or 'after' timing.")

            duration_ms = parse_duration_ms(dur_m.group(1)) if dur_m else 0
            end_ms = start_ms + duration_ms

            block_end_ms[block_id] = end_ms
            phase_starts.append(start_ms)
            phase_ends.append(end_ms)

            raw_lines = [ln for ln in act_body.splitlines() if ln.strip()]
            statements: List[str] = []
            for ln in raw_lines:
                stripped = ln.strip()
                is_new_stmt = bool(
                    re.match(r"^(attach|detach)\s+", stripped)
                    or re.match(r"^\w+:\s+", stripped)
                )
                if is_new_stmt or not statements:
                    statements.append(stripped)
                else:
                    statements[-1] += " " + stripped

            ev_counter = [0]
            for stmt in statements:
                m_att = re.match(r"^attach\s+(\w+)\s+to\s+(\w+)$", stmt)
                if m_att:
                    ev_counter[0] += 1
                    events.append(
                        CouplingEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=m_att.group(1),
                            type="attach",
                            parent_asset_id=m_att.group(2),
                        )
                    )
                    continue

                m_det = re.match(r"^detach\s+(\w+)\s+from\s+(\w+)\s+at\s+(\w+)$", stmt)
                if m_det:
                    child_id, parent_id, wp_id = m_det.group(1), m_det.group(2), m_det.group(3)
                    if wp_id not in waypoints:
                        raise ValueError(f"Detach references unknown waypoint '{wp_id}'")
                    ev_counter[0] += 1
                    events.append(
                        CouplingEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=child_id,
                            type="detach",
                            parent_asset_id=parent_id,
                            detach_pos=waypoints[wp_id].pos,
                        )
                    )
                    continue

                m_asset = re.match(r"^(\w+):\s+(.+)$", stmt)
                if not m_asset:
                    raise ValueError(f"Unrecognized timeline statement: '{stmt}'")
                asset_id, cmd = m_asset.group(1), m_asset.group(2)

                m_state = re.match(r'^state\s+"([^"]+)"$', cmd)
                if m_state:
                    ev_counter[0] += 1
                    events.append(
                        StateEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            state=m_state.group(1),
                        )
                    )
                    continue

                m_lbl = re.match(r'^label\s+"([^"]+)"$', cmd)
                if m_lbl:
                    ev_counter[0] += 1
                    events.append(
                        LabelEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            text=m_lbl.group(1),
                        )
                    )
                    continue

                m_move = re.match(r"^move\s+from\s+(\w+)\s+to\s+(\w+)(.*)$", cmd)
                if m_move:
                    wp_a, wp_b, rest = m_move.group(1), m_move.group(2), m_move.group(3)
                    if wp_a not in waypoints or wp_b not in waypoints:
                        raise ValueError(f"Move references unknown waypoint: '{wp_a}' or '{wp_b}'")

                    via_pts: List[Point2D] = []
                    via_m = re.search(r"via\s*\[([^\]]+)\]", rest)
                    if via_m:
                        via_pts = parse_point_list(via_m.group(1))

                    easing_m = re.search(r"easing\s+(linear|ease_in|ease_out|ease_in_out)", rest)
                    speed_m = re.search(r"max_speed:\s*(\d+(?:\.\d+)?)m/s", rest)

                    ev_counter[0] += 1
                    events.append(
                        MoveEvent(
                            id=f"{block_id}_ev{ev_counter[0]}",
                            phase_id=phase_id,
                            start_ms=start_ms,
                            end_ms=end_ms,
                            target_asset_id=asset_id,
                            from_waypoint_id=wp_a,
                            to_waypoint_id=wp_b,
                            path=[waypoints[wp_a].pos, *via_pts, waypoints[wp_b].pos],
                            easing=easing_m.group(1) if easing_m else "linear",
                            max_speed_mps=float(speed_m.group(1)) if speed_m else None,
                        )
                    )
                    events.extend(
                        parse_resource_deltas(
                            rest, block_id, phase_id, start_ms, end_ms, asset_id, ev_counter
                        )
                    )
                    continue

                res_events = parse_resource_deltas(
                    cmd, block_id, phase_id, start_ms, end_ms, asset_id, ev_counter
                )
                if res_events:
                    events.extend(res_events)
                    continue

                raise ValueError(f"Unrecognized command for '{asset_id}': '{cmd}'")

        if phase_starts:
            phases.append(
                Phase(
                    id=phase_id,
                    name=phase_name,
                    start_ms=min(phase_starts),
                    end_ms=max(phase_ends),
                )
            )

    events.sort(key=lambda e: e.start_ms)
    return phases, events


def compile_simline(source_text: str) -> SimLineTimeline:
    clean_text = strip_comments(source_text)
    top_blocks = extract_named_blocks(clean_text)

    scene: Optional[Scene] = None
    waypoints: Dict[str, Waypoint] = {}
    zones: List[Zone] = []
    windows: List[CommWindow] = []
    assets: Dict[str, Asset] = {}
    timeline_body: Optional[str] = None

    for header, body in top_blocks:
        if header.startswith("scene"):
            scene = parse_scene(header, body)
        elif header == "waypoints":
            waypoints = parse_waypoints(body)
        elif header == "zones":
            zones = parse_zones(body)
        elif header == "windows":
            windows = parse_windows(body)
        elif header == "assets":
            assets = parse_assets(body, waypoints)
        elif header == "timeline":
            timeline_body = body

    if scene is None:
        raise ValueError("Missing required 'scene' block.")
    if timeline_body is None:
        raise ValueError("Missing required 'timeline' block.")

    phases, events = parse_timeline(timeline_body, waypoints)

    return SimLineTimeline(
        scene=scene,
        waypoints=waypoints,
        zones=zones,
        windows=windows,
        assets=assets,
        phases=phases,
        events=events,
    )


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Compile SimLine DSL to validated timeline JSON."
    )
    parser.add_argument("input", type=Path, help="Path to .simline DSL file")
    parser.add_argument(
        "-o", "--output", type=Path, help="Output JSON path (defaults to stdout)"
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Block JSON export and exit with code 1 if physics/constraint validation fails.",
    )
    parser.add_argument(
        "--skip-validate",
        action="store_true",
        help="Skip post-compilation physics and constraint validation.",
    )
    parser.add_argument(
        "--step-ms",
        type=int,
        default=10_000,
        help="Validation simulation step size in milliseconds (default: 10000).",
    )
    parser.add_argument(
        "--report",
        type=Path,
        help="Optional path to write the JSON validation report.",
    )
    args = parser.parse_args()

    source = args.input.read_text(encoding="utf-8")
    timeline = compile_simline(source)

    if not args.skip_validate:
        report = validate_timeline(timeline, step_ms=args.step_ms)
        print(report.summary(), file=sys.stderr)

        if args.report:
            args.report.write_text(report.model_dump_json(indent=2), encoding="utf-8")

        if args.strict and not report.passed:
            print(
                "Strict mode enabled: JSON export blocked due to validation errors.",
                file=sys.stderr,
            )
            sys.exit(1)

    json_out = timeline.model_dump_json(indent=2)

    if args.output:
        args.output.write_text(json_out, encoding="utf-8")
        print(
            f"Compiled {len(timeline.events)} events across {len(timeline.phases)} phases -> {args.output}",
            file=sys.stderr,
        )
    else:
        print(json_out)


if __name__ == "__main__":
    main()

5. simline_viewer.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SimLine — Lunar Surface Operations Playback &amp; Authoring Studio</title>
<style>
  :root {
    --bg: #0b0f17;
    --panel: #131a26;
    --panel-border: #233044;
    --text: #e2e8f0;
    --muted: #8b9bb4;
    --accent: #38bdf8;
    --ok: #22c55e;
    --warn: #f59e0b;
    --danger: #ef4444;
    --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    --font-sans: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: var(--font-sans);
    height: 100vh;
    display: grid;
    grid-template-rows: 52px 1fr 112px;
    overflow: hidden;
  }

  /* Header */
  header {
    background: var(--panel);
    border-bottom: 1px solid var(--panel-border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    gap: 12px;
  }
  .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: 0.4px; }
  .brand span.tag {
    font-size: 11px; font-family: var(--font-mono);
    background: #1e293b; color: var(--accent);
    padding: 2px 7px; border-radius: 4px; border: 1px solid #334155;
  }
  .header-actions { display: flex; align-items: center; gap: 8px; }
  button, .file-btn {
    background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 6px;
    padding: 6px 12px; font-size: 13px; cursor: pointer;
    transition: background 0.15s, border-color 0.15s;
  }
  button:hover, .file-btn:hover { background: #273549; border-color: var(--accent); }
  button:disabled { opacity: 0.45; cursor: not-allowed; }
  button.primary { background: #0284c7; border-color: #38bdf8; color: #fff; font-weight: 600; }
  button.primary:hover { background: #0369a1; }
  input[type="file"] { display: none; }

  /* Main Workspace */
  main {
    display: grid;
    grid-template-columns: 1fr 360px;
    overflow: hidden;
  }
  .viewport {
    position: relative;
    background: #070a0f;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    user-select: none;
  }
  canvas#simCanvas {
    display: block;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 0 0 1px var(--panel-border);
    cursor: grab;
  }
  canvas#simCanvas.dragging { cursor: grabbing; }

  .overlay-hud {
    position: absolute;
    top: 12px; left: 12px;
    background: rgba(11, 15, 23, 0.85);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 8px 12px;
    font-family: var(--font-mono);
    font-size: 12px;
    pointer-events: none;
  }
  .overlay-hud .met { font-size: 18px; font-weight: 700; color: var(--accent); }
  .overlay-hud .phase-lbl { color: var(--muted); margin-top: 2px; }

  .camera-hud {
    position: absolute;
    bottom: 12px; left: 12px;
    background: rgba(11, 15, 23, 0.88);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 6px 10px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-family: var(--font-mono);
    font-size: 11px;
    color: var(--muted);
  }
  .camera-hud button { padding: 3px 8px; font-size: 11px; }

  /* Authoring Toolbar */
  .author-toolbar {
    position: absolute;
    top: 12px; right: 12px;
    background: rgba(11, 15, 23, 0.94);
    border: 1px solid var(--accent);
    border-radius: 8px;
    padding: 8px 10px;
    display: none;
    flex-direction: column;
    gap: 7px;
    font-size: 12px;
    width: 280px;
    max-height: calc(100% - 24px);
    overflow-y: auto;
  }
  .author-toolbar.visible { display: flex; }
  .author-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
  .author-toolbar button { padding: 4px 8px; font-size: 11px; }
  .author-toolbar button.active-tool {
    background: #0284c7; border-color: #38bdf8; color: #fff; font-weight: 600;
  }
  .author-hint { font-family: var(--font-mono); font-size: 11px; color: var(--warn); }
  .author-toolbar input[type="number"] {
    width: 60px; background: #1e293b; color: var(--text);
    border: 1px solid #334155; border-radius: 5px; padding: 3px 6px;
    font-family: var(--font-mono); font-size: 11px;
  }

  /* Event Inspector */
  .insp-header {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 11px; color: var(--muted); text-transform: uppercase;
    letter-spacing: 0.5px; border-top: 1px solid var(--panel-border); padding-top: 6px;
  }
  .event-inspector {
    max-height: 160px; overflow-y: auto;
    display: flex; flex-direction: column; gap: 4px; padding-right: 2px;
  }
  .insp-row {
    display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 5px;
    background: #131c2b; border: 1px solid #1e293b; border-left: 3px solid var(--accent);
    border-radius: 4px; padding: 4px 6px; font-family: var(--font-mono); font-size: 11px;
  }
  .insp-row.active { border-color: var(--accent); background: #1a273c; }
  .insp-info { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
  .insp-info .t { color: var(--accent); margin-right: 4px; }
  .insp-row button { padding: 2px 6px; font-size: 10px; }
  .insp-row button.del-btn:hover {
    background: rgba(239, 68, 68, 0.25); border-color: var(--danger); color: #fecaca;
  }

  /* Sidebar Statistics Panels */
  aside {
    background: var(--panel);
    border-left: 1px solid var(--panel-border);
    overflow-y: auto;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  .card {
    background: #0e141f;
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 10px 12px;
  }
  .card h3 {
    font-size: 11px; text-transform: uppercase; letter-spacing: 0.8px;
    color: var(--muted); margin-bottom: 8px;
    display: flex; justify-content: space-between; align-items: center;
  }
  .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
  .stat-box {
    background: #131c2b; border: 1px solid #1e293b; border-radius: 6px; padding: 6px 8px;
  }
  .stat-box .lbl { font-size: 10px; color: var(--muted); text-transform: uppercase; }
  .stat-box .val { font-size: 15px; font-family: var(--font-mono); font-weight: 700; margin-top: 2px; }

  /* Sparkline */
  .spark-canvas {
    width: 100%; height: 120px; display: block;
    background: #0b0f17; border: 1px solid #1e293b; border-radius: 6px; cursor: pointer;
  }
  .spark-legend {
    display: flex; flex-wrap: wrap; gap: 10px; margin-top: 6px;
    font-family: var(--font-mono); font-size: 10px; color: var(--muted);
  }
  .spark-legend-item { display: flex; align-items: center; gap: 5px; }
  .spark-swatch { width: 10px; height: 3px; border-radius: 2px; }

  /* Resource Bars */
  .asset-group { margin-bottom: 10px; }
  .asset-group:last-child { margin-bottom: 0; }
  .asset-hdr {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 12px; font-weight: 600; margin-bottom: 4px;
  }
  .badge {
    font-size: 10px; font-family: var(--font-mono);
    padding: 1px 6px; border-radius: 4px;
    background: #1e293b; color: var(--accent);
  }
  .badge.ok { background: rgba(34,197,94,0.15); color: var(--ok); }
  .badge.warn { background: rgba(245,158,11,0.15); color: var(--warn); }
  .badge.danger { background: rgba(239,68,68,0.2); color: var(--danger); }

  .res-row { margin-bottom: 5px; }
  .res-meta {
    display: flex; justify-content: space-between;
    font-size: 11px; font-family: var(--font-mono); color: var(--muted); margin-bottom: 2px;
  }
  .bar-track { height: 6px; background: #1e293b; border-radius: 3px; overflow: hidden; }
  .bar-fill { height: 100%; background: var(--accent); transition: width 0.08s linear; }
  .bar-fill.ok { background: var(--ok); }
  .bar-fill.warn { background: var(--warn); }
  .bar-fill.danger { background: var(--danger); }

  .list-item {
    font-size: 11px; font-family: var(--font-mono);
    padding: 5px 7px; border-radius: 4px;
    background: #131c2b; margin-bottom: 4px; border-left: 3px solid var(--accent);
  }
  .list-item.alert { border-left-color: var(--warn); color: #fde68a; }
  .list-item.danger { border-left-color: var(--danger); color: #fecaca; }

  /* Footer Playback Controls */
  footer {
    background: var(--panel); border-top: 1px solid var(--panel-border);
    padding: 10px 16px; display: flex; flex-direction: column; justify-content: space-between; gap: 8px;
  }
  .scrubber-row { display: flex; align-items: center; gap: 12px; }
  .scrubber-row input[type="range"] { flex: 1; accent-color: var(--accent); cursor: pointer; }
  .time-readout { font-family: var(--font-mono); font-size: 12px; color: var(--muted); min-width: 135px; text-align: right; }
  .controls-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
  .btn-group { display: flex; align-items: center; gap: 6px; }
  .phase-pills { display: flex; gap: 6px; overflow-x: auto; max-width: 55%; }
  .phase-pill {
    font-size: 11px; padding: 4px 8px; white-space: nowrap;
    background: #131c2b; border: 1px solid #233044; color: var(--muted);
  }
  .phase-pill.active { border-color: var(--accent); color: var(--text); background: #1e293b; }
  select {
    background: #1e293b; color: var(--text); border: 1px solid #334155;
    border-radius: 6px; padding: 4px 7px; font-size: 11px; font-family: var(--font-mono);
  }
</style>
</head>
<body>

<header>
  <div class="brand">
    <span>SimLine Studio</span>
    <span class="tag" id="sceneTag">NO FILE LOADED</span>
  </div>
  <div class="header-actions">
    <button id="btnToggleAuthor">Authoring Mode: OFF</button>
    <label class="file-btn" title="Select local PNG/SVG files matching asset or background filenames">
      Load Sprites / Map
      <input type="file" id="spriteInput" accept="image/*" multiple />
    </label>
    <label class="file-btn">
      Load Compiled JSON
      <input type="file" id="fileInput" accept=".json" />
    </label>
    <button class="primary" id="btnLoadSample">Load Sample EVA</button>
  </div>
</header>

<main>
  <section class="viewport">
    <canvas id="simCanvas" width="900" height="900"></canvas>
    <div class="overlay-hud">
      <div class="met" id="hudMet">MET 00:00:00</div>
      <div class="phase-lbl" id="hudPhase">Load a timeline JSON to begin</div>
    </div>
    <div class="camera-hud">
      <span>Scroll: Zoom &bull; Drag: Pan</span>
      <span id="zoomReadout" style="color: var(--accent); font-weight: 700;">100%</span>
      <button id="btnResetView">Reset View</button>
    </div>

    <div class="author-toolbar" id="authorToolbar">
      <div class="author-row">
        <button id="toolPan" class="active-tool">Pan</button>
        <button id="toolWaypoint">+ Waypoint</button>
        <button id="toolPath">+ Path</button>
        <button id="toolZone">+ Zone</button>
      </div>
      <div class="author-row">
        <select id="authorAsset" title="Asset to traverse"></select>
        <label style="color:var(--muted);font-size:11px;">Speed:</label>
        <input type="number" id="authorSpeed" value="2.0" step="0.2" min="0.1" />
        <span style="color:var(--muted);font-size:11px;">m/s</span>
      </div>
      <div class="author-row">
        <label style="color:var(--muted);font-size:11px;">Zone:</label>
        <select id="authorZoneType">
          <option value="shadow">PSR Shadow</option>
          <option value="hazard">Hazard (KOZ)</option>
          <option value="solar_rich">Solar Rich</option>
        </select>
        <button id="btnFinishZone">Finish Zone</button>
      </div>
      <div class="author-row">
        <select id="authorChild" title="Child asset (crew/payload)"></select>
        <span style="color:var(--muted);font-size:11px;">&rarr;</span>
        <select id="authorParent" title="Parent asset (vehicle)"></select>
      </div>
      <div class="author-row">
        <button id="btnMount">Mount</button>
        <button id="btnDismount">Dismount</button>
      </div>
      <div class="author-hint" id="authorHint">Select a tool to edit the map.</div>

      <div class="insp-header">
        <span>Event Inspector (<span id="inspCount">0</span>)</span>
        <select id="inspFilter" style="padding:2px 4px;font-size:10px;">
          <option value="all">All Events</option>
          <option value="authored">Authored Only</option>
        </select>
      </div>
      <div class="event-inspector" id="eventInspector">
        <div class="res-meta">No events.</div>
      </div>

      <div class="author-row">
        <button id="btnUndo" disabled title="Undo (Ctrl+Z)">&#x21A9; Undo</button>
        <button id="btnRedo" disabled title="Redo (Ctrl+Y)">&#x21AA; Redo</button>
        <button id="btnCancelDraft">Cancel Draft</button>
      </div>
      <div class="author-row">
        <button id="btnExportDsl" class="primary">Export .simline</button>
        <button id="btnExportJson">Export .json</button>
      </div>
    </div>
  </section>

  <aside>
    <div class="card">
      <h3>Mission Telemetry <span id="commBadge" class="badge">COMM: --</span></h3>
      <div class="stat-grid">
        <div class="stat-box"><div class="lbl">Active Events</div><div class="val" id="statActiveEvents">0</div></div>
        <div class="stat-box"><div class="lbl">Total Distance</div><div class="val" id="statTotalDist">0 m</div></div>
        <div class="stat-box"><div class="lbl">Comm Bandwidth</div><div class="val" id="statBandwidth">0 Mbps</div></div>
        <div class="stat-box"><div class="lbl">Progress</div><div class="val" id="statProgress">0.0%</div></div>
      </div>
    </div>

    <div class="card">
      <h3>Consumables Profile <span class="badge">0–100%</span></h3>
      <canvas id="sparkCanvas" class="spark-canvas" width="330" height="120"></canvas>
      <div class="spark-legend" id="sparkLegend"></div>
    </div>

    <div class="card">
      <h3>Asset Resources &amp; States</h3>
      <div id="resourcePanel"><div class="res-meta">No assets loaded.</div></div>
    </div>

    <div class="card">
      <h3>Zone &amp; Constraint Alerts</h3>
      <div id="alertPanel"><div class="res-meta">Nominal — no active alerts.</div></div>
    </div>

    <div class="card">
      <h3>Active Timeline Events</h3>
      <div id="eventPanel"><div class="res-meta">No active events.</div></div>
    </div>
  </aside>
</main>

<footer>
  <div class="scrubber-row">
    <input type="range" id="scrubber" min="0" max="1000" value="0" step="100" />
    <div class="time-readout" id="timeReadout">00:00:00 / 00:00:00</div>
  </div>
  <div class="controls-row">
    <div class="btn-group">
      <button id="btnReset" title="Reset to MET 00:00:00">&#x23EE; Reset</button>
      <button id="btnStepBack" title="Step back 1 min">-1m</button>
      <button id="btnPlayPause" class="primary">&#x25B6; Play</button>
      <button id="btnStepFwd" title="Step forward 1 min">+1m</button>
      <select id="speedSelect" title="Simulation Speed">
        <option value="1">1x (Real-time)</option>
        <option value="10">10x</option>
        <option value="60">60x (1m/s)</option>
        <option value="120" selected>120x (2m/s)</option>
        <option value="300">300x (5m/s)</option>
      </select>
    </div>
    <div class="phase-pills" id="phasePills"></div>
  </div>
</footer>

<script>
(() => {
  const canvas = document.getElementById("simCanvas");
  const ctx = canvas.getContext("2d");

  const el = {
    sceneTag: document.getElementById("sceneTag"),
    fileInput: document.getElementById("fileInput"),
    spriteInput: document.getElementById("spriteInput"),
    btnLoadSample: document.getElementById("btnLoadSample"),
    btnToggleAuthor: document.getElementById("btnToggleAuthor"),
    authorToolbar: document.getElementById("authorToolbar"),
    toolPan: document.getElementById("toolPan"),
    toolWaypoint: document.getElementById("toolWaypoint"),
    toolPath: document.getElementById("toolPath"),
    toolZone: document.getElementById("toolZone"),
    authorAsset: document.getElementById("authorAsset"),
    authorSpeed: document.getElementById("authorSpeed"),
    authorZoneType: document.getElementById("authorZoneType"),
    btnFinishZone: document.getElementById("btnFinishZone"),
    authorChild: document.getElementById("authorChild"),
    authorParent: document.getElementById("authorParent"),
    btnMount: document.getElementById("btnMount"),
    btnDismount: document.getElementById("btnDismount"),
    authorHint: document.getElementById("authorHint"),
    inspCount: document.getElementById("inspCount"),
    inspFilter: document.getElementById("inspFilter"),
    eventInspector: document.getElementById("eventInspector"),
    btnUndo: document.getElementById("btnUndo"),
    btnRedo: document.getElementById("btnRedo"),
    btnCancelDraft: document.getElementById("btnCancelDraft"),
    btnExportDsl: document.getElementById("btnExportDsl"),
    btnExportJson: document.getElementById("btnExportJson"),
    hudMet: document.getElementById("hudMet"),
    hudPhase: document.getElementById("hudPhase"),
    zoomReadout: document.getElementById("zoomReadout"),
    btnResetView: document.getElementById("btnResetView"),
    commBadge: document.getElementById("commBadge"),
    statActiveEvents: document.getElementById("statActiveEvents"),
    statTotalDist: document.getElementById("statTotalDist"),
    statBandwidth: document.getElementById("statBandwidth"),
    statProgress: document.getElementById("statProgress"),
    sparkCanvas: document.getElementById("sparkCanvas"),
    sparkLegend: document.getElementById("sparkLegend"),
    resourcePanel: document.getElementById("resourcePanel"),
    alertPanel: document.getElementById("alertPanel"),
    eventPanel: document.getElementById("eventPanel"),
    scrubber: document.getElementById("scrubber"),
    timeReadout: document.getElementById("timeReadout"),
    btnReset: document.getElementById("btnReset"),
    btnStepBack: document.getElementById("btnStepBack"),
    btnPlayPause: document.getElementById("btnPlayPause"),
    btnStepFwd: document.getElementById("btnStepFwd"),
    speedSelect: document.getElementById("speedSelect"),
    phasePills: document.getElementById("phasePills"),
  };

  let simData = null;
  let bgImage = null;
  const spriteCache = new Map();
  let isPlaying = false;
  let currentMs = 0;
  let speedMultiplier = 120;
  let lastFrameTime = null;

  const camera = { zoom: 1.0, minZoom: 0.4, maxZoom: 8.0, panX: 0, panY: 0, isDragging: false, dragStartX: 0, dragStartY: 0 };
  const authoring = { enabled: false, tool: "pan", draftPath: null, draftZone: [] };
  const history = { undo: [], redo: [], maxDepth: 50 };

  const sparkCtx = el.sparkCanvas.getContext("2d");
  const SPARK_COLORS = ["#38bdf8", "#22c55e", "#f59e0b", "#a855f7", "#f43f5e"];
  let telemetrySeries = [];

  // --- Camera & Coordinate Helpers ---
  function getBaseScale() {
    if (!simData) return 1;
    return Math.min(canvas.width / simData.scene.dimensions.width, canvas.height / simData.scene.dimensions.height);
  }
  function screenToWorld(cx, cy) {
    const s = getBaseScale() * camera.zoom;
    return [Math.round((cx - camera.panX) / s), Math.round((cy - camera.panY) / s)];
  }
  function getCanvasCoords(e) {
    const r = canvas.getBoundingClientRect();
    return { x: (e.clientX - r.left) * (canvas.width / r.width), y: (e.clientY - r.top) * (canvas.height / r.height) };
  }
  function resetCamera() {
    camera.zoom = 1.0; camera.panX = 0; camera.panY = 0;
    el.zoomReadout.textContent = "100%";
    redrawCurrent();
  }
  function findNearestWaypoint(worldPt, maxDist = 45) {
    if (!simData) return null;
    let bestId = null, bestDist = maxDist;
    for (const [id, wp] of Object.entries(simData.waypoints)) {
      const d = Math.hypot(wp.pos[0] - worldPt[0], wp.pos[1] - worldPt[1]);
      if (d < bestDist) { bestDist = d; bestId = id; }
    }
    return bestId;
  }

  // --- Undo / Redo History ---
  function captureSnapshot() {
    return structuredClone({
      waypoints: simData.waypoints,
      zones: simData.zones || [],
      events: simData.events,
      duration_ms: simData.scene.duration_ms,
    });
  }
  function updateHistoryButtons() {
    el.btnUndo.disabled = history.undo.length === 0;
    el.btnRedo.disabled = history.redo.length === 0;
  }
  function pushUndoSnapshot() {
    if (!simData) return;
    history.undo.push(captureSnapshot());
    if (history.undo.length > history.maxDepth) history.undo.shift();
    history.redo = [];
    updateHistoryButtons();
  }
  function applySnapshot(snap) {
    simData.waypoints = structuredClone(snap.waypoints);
    simData.zones = structuredClone(snap.zones);
    simData.events = structuredClone(snap.events);
    simData.scene.duration_ms = snap.duration_ms;
    el.scrubber.max = snap.duration_ms;
    if (currentMs > snap.duration_ms) currentMs = snap.duration_ms;
    authoring.draftPath = null;
    authoring.draftZone = [];
    updateHistoryButtons();
    buildTelemetrySeries(simData);
    redrawCurrent();
  }
  function undoAuthoring() {
    if (!simData || !history.undo.length) return;
    history.redo.push(captureSnapshot());
    applySnapshot(history.undo.pop());
    el.authorHint.textContent = "Undid last authoring action.";
  }
  function redoAuthoring() {
    if (!simData || !history.redo.length) return;
    history.undo.push(captureSnapshot());
    applySnapshot(history.redo.pop());
    el.authorHint.textContent = "Redid authoring action.";
  }

  // --- Sprite Cache ---
  function basename(p) { return p ? p.split(/[\\/]/).pop().toLowerCase() : ""; }
  function cacheImageSrc(key, src) {
    if (!src) return;
    const img = new Image();
    img.onload = () => redrawCurrent();
    img.src = src;
    spriteCache.set(key, img);
    const b = basename(src);
    if (b && !src.startsWith("data:")) spriteCache.set(b, img);
  }
  function getLoadedSprite(entityId, imagePath) {
    for (const k of [entityId, imagePath, basename(imagePath)]) {
      if (!k) continue;
      const img = spriteCache.get(k);
      if (img && img.complete && img.naturalWidth > 0) return img;
    }
    return null;
  }
  function preloadTimelineSprites(data) {
    bgImage = null;
    if (data.scene.background) {
      const existing = spriteCache.get(basename(data.scene.background));
      if (existing) bgImage = existing;
      else { bgImage = new Image(); bgImage.onload = () => redrawCurrent(); bgImage.src = data.scene.background; }
    }
    for (const [id, a] of Object.entries(data.assets || {})) if (a.image) cacheImageSrc(id, a.image);
    for (const [id, wp] of Object.entries(data.waypoints || {})) if (wp.image) cacheImageSrc(`wp:${id}`, wp.image);
  }

  // --- Math & Geometry ---
  function formatMET(ms) {
    const s = Math.max(0, Math.floor(ms / 1000));
    return `${String(Math.floor(s / 3600)).padStart(2, "0")}:${String(Math.floor((s % 3600) / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
  }
  function applyEasing(t, type) {
    if (type === "ease_in") return t * t;
    if (type === "ease_out") return t * (2 - t);
    if (type === "ease_in_out") return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    return t;
  }
  function polylineLength(pts) {
    let len = 0;
    for (let i = 1; i < pts.length; i++) len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    return len;
  }
  function samplePolylineWithHeading(pts, fraction) {
    if (pts.length === 0) return { pos: [0, 0], heading: 0 };
    if (pts.length === 1) return { pos: pts[0], heading: 0 };
    if (fraction <= 0) return { pos: pts[0], heading: Math.atan2(pts[1][1] - pts[0][1], pts[1][0] - pts[0][0]) };
    if (fraction >= 1) {
      const n = pts.length;
      return { pos: pts[n - 1], heading: Math.atan2(pts[n - 1][1] - pts[n - 2][1], pts[n - 1][0] - pts[n - 2][0]) };
    }
    let target = polylineLength(pts) * fraction;
    for (let i = 1; i < pts.length; i++) {
      const dx = pts[i][0] - pts[i - 1][0], dy = pts[i][1] - pts[i - 1][1];
      const seg = Math.hypot(dx, dy);
      if (target <= seg && seg > 0) {
        const u = target / seg;
        return { pos: [pts[i - 1][0] + dx * u, pts[i - 1][1] + dy * u], heading: Math.atan2(dy, dx) };
      }
      target -= seg;
    }
    const n = pts.length;
    return { pos: pts[n - 1], heading: Math.atan2(pts[n - 1][1] - pts[n - 2][1], pts[n - 1][0] - pts[n - 2][0]) };
  }
  function pointInPolygon(pt, vs) {
    const [x, y] = pt;
    let inside = false;
    for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
      const [xi, yi] = vs[i], [xj, yj] = vs[j];
      if (((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)) inside = !inside;
    }
    return inside;
  }
  function pointInZone(pt, z) {
    if (z.geometry.shape === "circle") return Math.hypot(pt[0] - z.geometry.center[0], pt[1] - z.geometry.center[1]) <= z.geometry.radius_px;
    return pointInPolygon(pt, z.geometry.points);
  }

  // --- Deterministic State Evaluator ---
  function evaluateState(data, t) {
    const assetState = {};
    let totalDistPx = 0;

    for (const [id, spec] of Object.entries(data.assets)) {
      const resources = {};
      for (const [rk, rv] of Object.entries(spec.resources || {})) resources[rk] = { ...rv, value: rv.initial };
      assetState[id] = { id, ...spec, pos: [...spec.start_pos], heading: null, parent: null, state: spec.is_static ? "static" : "idle", label: "", resources };
    }

    const activeEvents = [];
    const activeMovePaths = [];

    for (const ev of data.events) {
      if (ev.start_ms > t) break;
      const a = assetState[ev.target_asset_id];
      if (!a) continue;
      const isActive = t >= ev.start_ms && t <= ev.end_ms;
      if (isActive) activeEvents.push(ev);

      if (ev.type === "move") {
        const dur = Math.max(1, ev.end_ms - ev.start_ms);
        const eased = applyEasing(Math.min(1, Math.max(0, (t - ev.start_ms) / dur)), ev.easing);
        const sample = samplePolylineWithHeading(ev.path, eased);
        a.pos = sample.pos;
        a.heading = sample.heading;
        totalDistPx += polylineLength(ev.path) * eased;
        if (isActive) activeMovePaths.push(ev.path);
      } else if (ev.type === "attach") {
        a.parent = ev.parent_asset_id;
      } else if (ev.type === "detach") {
        a.parent = null;
        if (ev.detach_pos) a.pos = [...ev.detach_pos];
      } else if (ev.type === "state") {
        a.state = ev.state;
      } else if (ev.type === "label") {
        if (isActive) a.label = ev.text;
      } else if (ev.type === "resource_delta") {
        const elapsedMs = Math.min(t, ev.end_ms) - ev.start_ms;
        if (elapsedMs > 0 && a.resources[ev.resource]) a.resources[ev.resource].value += ev.rate_per_min * (elapsedMs / 60000);
      }
    }

    for (const a of Object.values(assetState)) if (a.parent && assetState[a.parent]) a.pos = [...assetState[a.parent].pos];

    const activePhase = data.phases.find(p => t >= p.start_ms && t <= p.end_ms) || null;
    const activeWindow = (data.windows || []).find(w => t >= w.start_ms && t <= w.end_ms) || null;

    const alerts = [];
    for (const a of Object.values(assetState)) {
      if (a.is_static) continue;
      for (const z of data.zones || []) {
        if (pointInZone(a.pos, z)) {
          if (z.type === "hazard") alerts.push({ level: "danger", text: `${a.id} inside HAZARD zone (${z.id})` });
          else if (z.type === "shadow") alerts.push({ level: "alert", text: `${a.id} in PSR shadow (${z.id})` });
        }
      }
      for (const [rk, r] of Object.entries(a.resources)) {
        if (r.min != null && r.value < r.min) alerts.push({ level: "danger", text: `${a.id} ${rk} BELOW MIN (${r.value.toFixed(1)}${r.unit})` });
        if (r.max != null && r.value > r.max) alerts.push({ level: "danger", text: `${a.id} ${rk} EXCEEDS MAX (${r.value.toFixed(1)}${r.unit})` });
      }
    }

    return { assetState, activeEvents, activeMovePaths, activePhase, activeWindow, alerts, totalDistM: totalDistPx * (data.scene.scale_m_per_px || 1) };
  }

  // --- 2D Canvas Renderer ---
  function render(state) {
    if (!simData) return;
    const { width, height } = simData.scene.dimensions;
    const totalScale = getBaseScale() * camera.zoom;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(camera.panX, camera.panY);
    ctx.scale(totalScale, totalScale);

    // 1. Background
    if (bgImage && bgImage.complete && bgImage.naturalWidth > 0) {
      ctx.drawImage(bgImage, 0, 0, width, height);
    } else {
      ctx.fillStyle = "#0d1117";
      ctx.fillRect(0, 0, width, height);
      ctx.strokeStyle = "rgba(148, 163, 184, 0.08)";
      ctx.lineWidth = 2;
      const step = Math.round(width / 16);
      for (let x = 0; x <= width; x += step) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke(); }
      for (let y = 0; y <= height; y += step) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke(); }
    }

    // 2. Zones
    for (const z of simData.zones || []) {
      ctx.save();
      if (z.type === "shadow") { ctx.fillStyle = "rgba(30, 58, 138, 0.35)"; ctx.strokeStyle = "#60a5fa"; }
      else if (z.type === "hazard") { ctx.fillStyle = "rgba(239, 68, 68, 0.18)"; ctx.strokeStyle = "#ef4444"; }
      else { ctx.fillStyle = "rgba(250, 204, 21, 0.15)"; ctx.strokeStyle = "#facc15"; }
      ctx.lineWidth = 3; ctx.setLineDash([12, 8]);
      ctx.beginPath();
      if (z.geometry.shape === "circle") ctx.arc(z.geometry.center[0], z.geometry.center[1], z.geometry.radius_px, 0, Math.PI * 2);
      else { z.geometry.points.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])); ctx.closePath(); }
      ctx.fill(); ctx.stroke(); ctx.restore();
    }

    // 3. Move Paths
    for (const ev of simData.events) {
      if (ev.type !== "move") continue;
      ctx.save(); ctx.strokeStyle = "rgba(148, 163, 184, 0.25)"; ctx.lineWidth = 4; ctx.setLineDash([10, 10]);
      ctx.beginPath(); ev.path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])); ctx.stroke(); ctx.restore();
    }
    for (const path of state.activeMovePaths) {
      ctx.save(); ctx.strokeStyle = "#38bdf8"; ctx.lineWidth = 6;
      ctx.beginPath(); path.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])); ctx.stroke(); ctx.restore();
    }

    // 4. Waypoints
    for (const [id, wp] of Object.entries(simData.waypoints)) {
      const [x, y] = wp.pos;
      const wpImg = getLoadedSprite(`wp:${id}`, wp.image);
      ctx.save();
      if (wpImg) ctx.drawImage(wpImg, x - 20, y - 20, 40, 40);
      else {
        ctx.fillStyle = "#f8fafc"; ctx.strokeStyle = "#38bdf8"; ctx.lineWidth = 4;
        ctx.beginPath(); ctx.arc(x, y, 12, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
      }
      ctx.font = "bold 26px system-ui, sans-serif"; ctx.fillStyle = "#e2e8f0";
      ctx.fillText(wp.label, x + 24, y + 8);
      ctx.restore();
    }

    // 5. Assets (rotated for vehicles)
    const SPRITE_HEADING_OFFSET = Math.PI / 2;
    const sortedAssets = Object.values(state.assetState).sort((a, b) => a.layer - b.layer);
    for (const a of sortedAssets) {
      if (a.parent) continue;
      const [x, y] = a.pos;
      const sprite = getLoadedSprite(a.id, a.image);
      const isVehicle = a.tags.includes("vehicle");
      const isLarge = isVehicle || a.is_static;
      const size = isLarge ? 64 : 46;

      ctx.save();
      ctx.translate(x, y);
      if (isVehicle && a.heading !== null) ctx.rotate(a.heading + SPRITE_HEADING_OFFSET);
      if (sprite) {
        ctx.drawImage(sprite, -size / 2, -size / 2, size, size);
      } else {
        const color = a.is_static ? "#94a3b8" : isVehicle ? "#38bdf8" : a.tags.includes("crew") ? "#22c55e" : "#f59e0b";
        ctx.fillStyle = color; ctx.strokeStyle = "#0b0f17"; ctx.lineWidth = 4;
        ctx.beginPath();
        if (isLarge) ctx.roundRect(-22, -22, 44, 44, 8);
        else ctx.arc(0, 0, 18, 0, Math.PI * 2);
        ctx.fill(); ctx.stroke();
        if (isVehicle) {
          ctx.fillStyle = "#ffffff"; ctx.beginPath();
          ctx.moveTo(0, -18); ctx.lineTo(8, -6); ctx.lineTo(-8, -6); ctx.closePath(); ctx.fill();
        }
      }
      ctx.restore();

      ctx.save();
      ctx.font = "bold 24px ui-monospace, monospace"; ctx.fillStyle = "#ffffff";
      ctx.fillText(a.id, x - 28, y - size / 2 - 8);
      if (a.label) { ctx.font = "22px system-ui, sans-serif"; ctx.fillStyle = "#fde047"; ctx.fillText(a.label, x + size / 2 + 8, y - 4); }
      const children = sortedAssets.filter(c => c.parent === a.id);
      if (children.length > 0) {
        ctx.font = "bold 20px ui-monospace, monospace"; ctx.fillStyle = "#38bdf8";
        ctx.fillText(`+${children.length} aboard`, x + size / 2 + 8, y + 22);
      }
      ctx.restore();
    }

    // 6. Authoring Draft Path Overlay
    if (authoring.enabled && authoring.draftPath) {
      const pts = [simData.waypoints[authoring.draftPath.fromWpId].pos, ...authoring.draftPath.via];
      ctx.save(); ctx.strokeStyle = "#f59e0b"; ctx.lineWidth = 5; ctx.setLineDash([12, 8]);
      ctx.beginPath(); pts.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])); ctx.stroke();
      ctx.fillStyle = "#f59e0b";
      for (const p of authoring.draftPath.via) { ctx.beginPath(); ctx.arc(p[0], p[1], 10, 0, Math.PI * 2); ctx.fill(); }
      ctx.restore();
    }

    // 7. Authoring Draft Zone Overlay
    if (authoring.enabled && authoring.draftZone.length > 0) {
      const zType = el.authorZoneType.value;
      const stroke = zType === "hazard" ? "#ef4444" : zType === "shadow" ? "#60a5fa" : "#facc15";
      const fill = zType === "hazard" ? "rgba(239,68,68,0.22)" : zType === "shadow" ? "rgba(30,58,138,0.35)" : "rgba(250,204,21,0.18)";
      ctx.save(); ctx.strokeStyle = stroke; ctx.fillStyle = fill; ctx.lineWidth = 4; ctx.setLineDash([10, 6]);
      ctx.beginPath();
      authoring.draftZone.forEach((p, i) => i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]));
      if (authoring.draftZone.length >= 3) { ctx.closePath(); ctx.fill(); }
      ctx.stroke();
      authoring.draftZone.forEach((p, i) => {
        ctx.beginPath();
        ctx.fillStyle = i === 0 && authoring.draftZone.length >= 3 ? "#ffffff" : stroke;
        ctx.arc(p[0], p[1], i === 0 && authoring.draftZone.length >= 3 ? 14 : 9, 0, Math.PI * 2);
        ctx.fill();
      });
      ctx.restore();
    }

    ctx.restore();
  }

  // --- Sparkline Chart ---
  function buildTelemetrySeries(data) {
    telemetrySeries = [];
    if (!data || !data.scene.duration_ms) return;
    const tracked = [];
    for (const [assetId, asset] of Object.entries(data.assets || {})) {
      if (asset.is_static || !asset.resources) continue;
      for (const [resKey, resSpec] of Object.entries(asset.resources)) {
        if (resKey === "battery" || resKey === "suit_o2") {
          tracked.push({ assetId, resKey, label: `${assetId}.${resKey}`, min: resSpec.min ?? null, color: SPARK_COLORS[tracked.length % SPARK_COLORS.length], points: [] });
        }
      }
    }
    if (!tracked.length) return;
    const dur = data.scene.duration_ms, steps = 120;
    for (let i = 0; i <= steps; i++) {
      const t = (dur * i) / steps;
      const st = evaluateState(data, t);
      for (const s of tracked) {
        const r = st.assetState[s.assetId]?.resources?.[s.resKey];
        if (r) s.points.push({ t, v: r.value });
      }
    }
    telemetrySeries = tracked;
    el.sparkLegend.innerHTML = telemetrySeries
      .map(s => `<div class="spark-legend-item"><span class="spark-swatch" style="background:${s.color}"></span><span>${s.label}</span></div>`)
      .join("");
  }

  function renderSparkline() {
    const c = el.sparkCanvas, w = c.width, h = c.height;
    const pad = { top: 10, right: 8, bottom: 16, left: 26 };
    const plotW = w - pad.left - pad.right, plotH = h - pad.top - pad.bottom;
    sparkCtx.clearRect(0, 0, w, h);
    if (!simData || !telemetrySeries.length) return;

    const dur = simData.scene.duration_ms || 1;
    const xOf = (t) => pad.left + (t / dur) * plotW;
    const yOf = (pct) => pad.top + plotH - (Math.max(0, Math.min(100, pct)) / 100) * plotH;

    sparkCtx.font = "9px ui-monospace, monospace";
    sparkCtx.fillStyle = "#64748b";
    sparkCtx.strokeStyle = "rgba(148, 163, 184, 0.12)";
    sparkCtx.lineWidth = 1;
    for (const pct of [0, 25, 50, 75, 100]) {
      const y = yOf(pct);
      sparkCtx.beginPath(); sparkCtx.moveTo(pad.left, y); sparkCtx.lineTo(w - pad.right, y); sparkCtx.stroke();
      sparkCtx.fillText(`${pct}`, 4, y + 3);
    }

    const drawnMins = new Set();
    for (const s of telemetrySeries) {
      if (s.min != null && !drawnMins.has(s.min)) {
        drawnMins.add(s.min);
        const y = yOf(s.min);
        sparkCtx.save(); sparkCtx.strokeStyle = "rgba(239, 68, 68, 0.45)"; sparkCtx.setLineDash([4, 3]);
        sparkCtx.beginPath(); sparkCtx.moveTo(pad.left, y); sparkCtx.lineTo(w - pad.right, y); sparkCtx.stroke(); sparkCtx.restore();
      }
    }

    for (const s of telemetrySeries) {
      sparkCtx.save(); sparkCtx.strokeStyle = s.color; sparkCtx.lineWidth = 1.8;
      sparkCtx.beginPath();
      s.points.forEach((pt, idx) => idx === 0 ? sparkCtx.moveTo(xOf(pt.t), yOf(pt.v)) : sparkCtx.lineTo(xOf(pt.t), yOf(pt.v)));
      sparkCtx.stroke(); sparkCtx.restore();
    }

    const px = xOf(currentMs);
    sparkCtx.save(); sparkCtx.strokeStyle = "#f8fafc"; sparkCtx.lineWidth = 1.2;
    sparkCtx.beginPath(); sparkCtx.moveTo(px, pad.top); sparkCtx.lineTo(px, h - pad.bottom); sparkCtx.stroke();
    const curState = evaluateState(simData, currentMs);
    for (const s of telemetrySeries) {
      const r = curState.assetState[s.assetId]?.resources?.[s.resKey];
      if (!r) continue;
      sparkCtx.fillStyle = s.color; sparkCtx.beginPath(); sparkCtx.arc(px, yOf(r.value), 3.2, 0, Math.PI * 2); sparkCtx.fill();
    }
    sparkCtx.restore();
  }

  // --- HUD & Inspector Updaters ---
  function updateUI(state) {
    if (!simData) return;
    const dur = simData.scene.duration_ms || 1;
    el.hudMet.textContent = `MET ${formatMET(currentMs)}`;
    el.hudPhase.textContent = state.activePhase ? state.activePhase.name : "Between Phases";
    el.timeReadout.textContent = `${formatMET(currentMs)} / ${formatMET(dur)}`;
    el.scrubber.value = Math.round(currentMs);
    el.statActiveEvents.textContent = state.activeEvents.length;
    el.statTotalDist.textContent = `${Math.round(state.totalDistM).toLocaleString()} m`;
    el.statProgress.textContent = `${((currentMs / dur) * 100).toFixed(1)}%`;

    if (state.activeWindow) {
      el.commBadge.textContent = `COMM: ${state.activeWindow.id}`; el.commBadge.className = "badge ok";
      el.statBandwidth.textContent = `${state.activeWindow.bandwidth_mbps} Mbps`;
    } else {
      el.commBadge.textContent = "COMM: BLACKOUT"; el.commBadge.className = "badge warn";
      el.statBandwidth.textContent = "0 Mbps";
    }

    Array.from(el.phasePills.children).forEach(btn => btn.classList.toggle("active", state.activePhase && btn.dataset.phaseId === state.activePhase.id));

    el.resourcePanel.innerHTML = Object.values(state.assetState).filter(a => !a.is_static).map(a => {
      const resHtml = Object.entries(a.resources).map(([k, r]) => {
        const pct = Math.min(100, Math.max(0, (r.value / (r.max ?? 100)) * 100));
        let cls = "ok";
        if ((r.min != null && r.value < r.min) || (r.max != null && r.value > r.max)) cls = "danger";
        else if (r.min != null && r.value < r.min + 15) cls = "warn";
        return `<div class="res-row"><div class="res-meta"><span>${k}</span><span>${r.value.toFixed(1)}${r.unit}</span></div><div class="bar-track"><div class="bar-fill ${cls}" style="width:${pct}%"></div></div></div>`;
      }).join("");
      return `<div class="asset-group"><div class="asset-hdr"><span>${a.id}</span><span class="badge">${a.parent ? `aboard ${a.parent}` : a.state}</span></div>${resHtml || '<div class="res-meta">No consumables</div>'}</div>`;
    }).join("");

    el.alertPanel.innerHTML = state.alerts.length ? state.alerts.map(al => `<div class="list-item ${al.level}">${al.text}</div>`).join("") : '<div class="res-meta">Nominal — no active alerts.</div>';
    el.eventPanel.innerHTML = state.activeEvents.length ? state.activeEvents.map(ev => `<div class="list-item">[${ev.type}] ${ev.target_asset_id} (${ev.id})</div>`).join("") : '<div class="res-meta">No active events at this timestamp.</div>';
  }

  function renderEventInspector() {
    if (!simData || !authoring.enabled) return;
    const filter = el.inspFilter.value;
    const list = simData.events.filter(ev => filter === "authored" ? ev.id.startsWith("auth_") : true);
    el.inspCount.textContent = list.length;
    if (!list.length) { el.eventInspector.innerHTML = '<div class="res-meta">No matching events.</div>'; return; }

    el.eventInspector.innerHTML = "";
    for (const ev of list) {
      const row = document.createElement("div");
      row.className = `insp-row${currentMs >= ev.start_ms && currentMs <= ev.end_ms ? " active" : ""}`;
      const info = document.createElement("div");
      info.className = "insp-info";
      info.title = `${ev.id} (${formatMET(ev.start_ms)} - ${formatMET(ev.end_ms)})`;
      info.innerHTML = `<span class="t">${formatMET(ev.start_ms)}</span>[${ev.type}] ${ev.target_asset_id}`;
      info.onclick = () => { setPlaying(false); currentMs = ev.start_ms; redrawCurrent(); };

      const btnJump = document.createElement("button");
      btnJump.textContent = "Go"; btnJump.onclick = info.onclick;

      const btnDel = document.createElement("button");
      btnDel.className = "del-btn"; btnDel.textContent = "×"; btnDel.title = `Delete ${ev.id}`;
      btnDel.onclick = () => {
        pushUndoSnapshot();
        simData.events = simData.events.filter(item => item.id !== ev.id);
        el.authorHint.textContent = `Deleted event '${ev.id}' (Ctrl+Z to undo).`;
        buildTelemetrySeries(simData);
        redrawCurrent();
      };
      row.append(info, btnJump, btnDel);
      el.eventInspector.appendChild(row);
    }
  }

  function redrawCurrent() {
    if (!simData) return;
    const st = evaluateState(simData, currentMs);
    render(st);
    updateUI(st);
    renderSparkline();
    if (authoring.enabled) renderEventInspector();
  }

  // --- Authoring Actions ---
  function setAuthorTool(tool) {
    authoring.tool = tool; authoring.draftPath = null; authoring.draftZone = [];
    el.toolPan.classList.toggle("active-tool", tool === "pan");
    el.toolWaypoint.classList.toggle("active-tool", tool === "waypoint");
    el.toolPath.classList.toggle("active-tool", tool === "path");
    el.toolZone.classList.toggle("active-tool", tool === "zone");
    canvas.style.cursor = tool === "pan" ? "grab" : "crosshair";
    el.authorHint.textContent =
      tool === "waypoint" ? "Click map to place a new waypoint." :
      tool === "path" ? "Click start waypoint, optional via points, then end waypoint." :
      tool === "zone" ? "Click 3+ vertices. Click first vertex or 'Finish Zone' to close." :
      "Drag to pan, scroll to zoom.";
    redrawCurrent();
  }

  function commitDraftZone() {
    if (!simData || authoring.draftZone.length < 3) { el.authorHint.textContent = "A polygon zone requires at least 3 vertices."; return; }
    const zType = el.authorZoneType.value;
    const nextNum = (simData.zones?.length || 0) + 1;
    const rawId = prompt("Zone ID (no spaces):", `${zType}_zone_${nextNum}`);
    if (rawId === null) return;
    const zoneId = rawId.trim().replace(/\s+/g, "_") || `${zType}_zone_${nextNum}`;
    const modifiers = zType === "shadow" ? { solar_multiplier: 0.0, thermal_penalty: "high" } : zType === "solar_rich" ? { solar_multiplier: 1.0 } : undefined;
    pushUndoSnapshot();
    simData.zones = simData.zones || [];
    simData.zones.push({ id: zoneId, type: zType, geometry: { shape: "polygon", points: authoring.draftZone.map(p => [...p]) }, ...(modifiers ? { modifiers } : {}) });
    authoring.draftZone = [];
    el.authorHint.textContent = `Added ${zType} zone '${zoneId}'.`;
    redrawCurrent();
  }

  function addCouplingEvent(type) {
    if (!simData) return;
    const childId = el.authorChild.value, parentId = el.authorParent.value;
    if (!childId || !parentId || childId === parentId) { el.authorHint.textContent = "Select two different assets for child and parent."; return; }
    const startMs = Math.round(currentMs);
    const state = evaluateState(simData, startMs);
    const parentPos = state.assetState[parentId]?.pos || simData.assets[parentId].start_pos;
    const phaseId = state.activePhase?.id || simData.phases[0]?.id || "authored_phase";
    pushUndoSnapshot();
    const ev = { id: `auth_${type}_${simData.events.length + 1}`, phase_id: phaseId, start_ms: startMs, end_ms: startMs, target_asset_id: childId, type, parent_asset_id: parentId };
    if (type === "detach") ev.detach_pos = [Math.round(parentPos[0]), Math.round(parentPos[1])];
    simData.events.push(ev);
    simData.events.sort((a, b) => a.start_ms - b.start_ms);
    el.authorHint.textContent = `${type === "attach" ? "Mounted" : "Dismounted"} ${childId} ${type === "attach" ? "onto" : "from"} ${parentId} at MET ${formatMET(startMs)}.`;
    redrawCurrent();
  }

  function exportSimLineDSL(data) {
    const lines = [];
    lines.push(`scene "${data.scene.id}" {`);
    lines.push(`  background: "${data.scene.background || ""}"`);
    lines.push(`  dimensions: ${data.scene.dimensions.width} x ${data.scene.dimensions.height}`);
    if (data.scene.scale_m_per_px) lines.push(`  scale: 1px = ${data.scene.scale_m_per_px}m`);
    lines.push(`  duration: ${Math.ceil(data.scene.duration_ms / 60000)}m\n}\n`);

    lines.push(`waypoints {`);
    for (const [id, wp] of Object.entries(data.waypoints)) {
      lines.push(`  ${id} {\n    pos: (${Math.round(wp.pos[0])}, ${Math.round(wp.pos[1])})\n    label: "${wp.label}"`);
      if (wp.image && !wp.image.startsWith("data:")) lines.push(`    image: "${wp.image}"`);
      lines.push(`  }`);
    }
    lines.push(`}\n`);

    if (data.zones?.length) {
      lines.push(`zones {`);
      for (const z of data.zones) {
        lines.push(`  ${z.id} {`);
        if (z.geometry.shape === "circle") lines.push(`    circle: (${Math.round(z.geometry.center[0])}, ${Math.round(z.geometry.center[1])}) radius ${z.geometry.radius_px}px`);
        else lines.push(`    polygon: [${z.geometry.points.map(p => `(${Math.round(p[0])}, ${Math.round(p[1])})`).join(", ")}]`);
        lines.push(`    type: ${z.type}`);
        if (z.modifiers?.solar_multiplier != null) lines.push(`    solar_multiplier: ${z.modifiers.solar_multiplier}`);
        if (z.modifiers?.thermal_penalty) lines.push(`    thermal_penalty: ${z.modifiers.thermal_penalty}`);
        lines.push(`  }`);
      }
      lines.push(`}\n`);
    }

    lines.push(`assets {`);
    for (const [id, a] of Object.entries(data.assets)) {
      lines.push(`  ${a.is_static ? "static" : "asset"} ${id} {`);
      lines.push(`    image: "${a.image && !a.image.startsWith("data:") ? a.image : ""}"`);
      lines.push(a.is_static ? `    pos: (${a.start_pos[0]}, ${a.start_pos[1]})` : `    start_at: (${a.start_pos[0]}, ${a.start_pos[1]})`);
      lines.push(`    layer: ${a.layer}`);
      if (a.tags?.length) lines.push(`    tags: [${a.tags.map(t => `"${t}"`).join(", ")}]`);
      const resEntries = Object.entries(a.resources || {});
      if (resEntries.length) {
        lines.push(`    resources: {`);
        for (const [rk, rv] of resEntries) {
          const bounds = [rv.min != null ? `min: ${rv.min}${rv.unit}` : "", rv.max != null ? `max: ${rv.max}${rv.unit}` : ""].filter(Boolean).join(", ");
          lines.push(`      ${rk}: ${rv.initial}${rv.unit}${bounds ? ` (${bounds})` : ""}`);
        }
        lines.push(`    }`);
      }
      lines.push(`  }`);
    }
    lines.push(`}\n`);

    lines.push(`timeline {\n  phase "Authored Mission Timeline" {`);
    for (const ev of data.events) {
      const durM = Math.max(0, Math.round((ev.end_ms - ev.start_ms) / 60000));
      lines.push(`    id: ${ev.id}\n    at MET ${formatMET(ev.start_ms)} for ${durM}m {`);
      if (ev.type === "move") {
        const viaPts = ev.path.slice(1, -1).map(p => `(${Math.round(p[0])}, ${Math.round(p[1])})`).join(", ");
        lines.push(`      ${ev.target_asset_id}: move from ${ev.from_waypoint_id || "lander_pad"} to ${ev.to_waypoint_id || "lander_pad"}`);
        if (viaPts) lines.push(`        via [${viaPts}]`);
        if (ev.max_speed_mps) lines.push(`        max_speed: ${ev.max_speed_mps}m/s`);
        if (ev.easing) lines.push(`        easing ${ev.easing}`);
      } else if (ev.type === "attach") {
        lines.push(`      attach ${ev.target_asset_id} to ${ev.parent_asset_id}`);
      } else if (ev.type === "detach") {
        let wpId = Object.keys(data.waypoints)[0] || "lander_pad";
        if (ev.detach_pos) {
          let bestDist = Infinity;
          for (const [id, wp] of Object.entries(data.waypoints)) {
            const d = Math.hypot(wp.pos[0] - ev.detach_pos[0], wp.pos[1] - ev.detach_pos[1]);
            if (d < bestDist) { bestDist = d; wpId = id; }
          }
        }
        lines.push(`      detach ${ev.target_asset_id} from ${ev.parent_asset_id} at ${wpId}`);
      } else if (ev.type === "state") {
        lines.push(`      ${ev.target_asset_id}: state "${ev.state}"`);
      } else if (ev.type === "label") {
        lines.push(`      ${ev.target_asset_id}: label "${ev.text}"`);
      } else if (ev.type === "resource_delta") {
        const unit = data.assets[ev.target_asset_id]?.resources?.[ev.resource]?.unit || "%";
        lines.push(`      ${ev.target_asset_id}: ${ev.rate_per_min < 0 ? "drain" : "recharge"} ${ev.resource} ${Math.abs(ev.rate_per_min)}${unit}/m`);
      }
      lines.push(`    }`);
    }
    lines.push(`  }\n}`);
    return lines.join("\n");
  }

  // --- Playback Loop & Loader ---
  function tick(now) {
    if (isPlaying && simData) {
      if (lastFrameTime !== null) {
        currentMs += Math.min(250, now - lastFrameTime) * speedMultiplier;
        if (currentMs >= simData.scene.duration_ms) { currentMs = simData.scene.duration_ms; setPlaying(false); }
      }
      lastFrameTime = now;
      redrawCurrent();
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);

  function setPlaying(play) {
    isPlaying = play; lastFrameTime = null;
    el.btnPlayPause.innerHTML = isPlaying ? "&#x23F8; Pause" : "&#x25B6; Play";
  }

  function loadTimeline(jsonObj) {
    simData = jsonObj; currentMs = 0; setPlaying(false);
    el.sceneTag.textContent = simData.scene.id;
    el.scrubber.max = simData.scene.duration_ms;
    history.undo = []; history.redo = []; updateHistoryButtons();
    preloadTimelineSprites(simData);

    const dynamicAssets = Object.entries(simData.assets).filter(([, a]) => !a.is_static);
    const assetOptions = dynamicAssets.map(([id]) => `<option value="${id}">${id}</option>`).join("");
    el.authorAsset.innerHTML = assetOptions;
    el.authorChild.innerHTML = assetOptions;
    el.authorParent.innerHTML = assetOptions;
    const defChild = dynamicAssets.find(([, a]) => !a.tags?.includes("vehicle"))?.[0];
    const defParent = dynamicAssets.find(([, a]) => a.tags?.includes("vehicle"))?.[0];
    if (defChild) el.authorChild.value = defChild;
    if (defParent) el.authorParent.value = defParent;

    el.phasePills.innerHTML = "";
    for (const p of simData.phases) {
      const btn = document.createElement("button");
      btn.className = "phase-pill"; btn.textContent = p.name; btn.dataset.phaseId = p.id;
      btn.onclick = () => { currentMs = p.start_ms; redrawCurrent(); };
      el.phasePills.appendChild(btn);
    }
    buildTelemetrySeries(simData);
    resetCamera();
  }

  // --- Event Listeners ---
  canvas.addEventListener("wheel", (e) => {
    if (!simData) return;
    e.preventDefault();
    const { x: mx, y: my } = getCanvasCoords(e);
    const oldScale = getBaseScale() * camera.zoom;
    const wx = (mx - camera.panX) / oldScale, wy = (my - camera.panY) / oldScale;
    camera.zoom = Math.min(camera.maxZoom, Math.max(camera.minZoom, camera.zoom * (e.deltaY < 0 ? 1.15 : 1 / 1.15)));
    const newScale = getBaseScale() * camera.zoom;
    camera.panX = mx - wx * newScale; camera.panY = my - wy * newScale;
    el.zoomReadout.textContent = `${Math.round(camera.zoom * 100)}%`;
    redrawCurrent();
  }, { passive: false });

  canvas.addEventListener("mousedown", (e) => {
    if (!simData || e.button !== 0) return;
    const { x, y } = getCanvasCoords(e);

    if (authoring.enabled && authoring.tool === "waypoint") {
      const worldPt = screenToWorld(x, y);
      const nextNum = Object.keys(simData.waypoints).length + 1;
      const wpId = `wp_${nextNum}`;
      const label = prompt("Waypoint label:", `Station ${nextNum}`);
      if (label !== null) {
        pushUndoSnapshot();
        simData.waypoints[wpId] = { pos: worldPt, label: label.trim() || wpId };
        el.authorHint.textContent = `Added ${wpId} at (${worldPt[0]}, ${worldPt[1]})`;
        redrawCurrent();
      }
      return;
    }

    if (authoring.enabled && authoring.tool === "path") {
      const worldPt = screenToWorld(x, y);
      const hitWp = findNearestWaypoint(worldPt);
      if (!authoring.draftPath) {
        if (!hitWp) { el.authorHint.textContent = "Click an existing waypoint to start the path."; return; }
        authoring.draftPath = { fromWpId: hitWp, via: [] };
        el.authorHint.textContent = `From ${hitWp} — click via points or end waypoint.`;
      } else if (hitWp && hitWp !== authoring.draftPath.fromWpId) {
        const fromId = authoring.draftPath.fromWpId;
        const path = [simData.waypoints[fromId].pos, ...authoring.draftPath.via, simData.waypoints[hitWp].pos];
        const distM = polylineLength(path) * (simData.scene.scale_m_per_px || 1);
        const speed = Math.max(0.1, Number(el.authorSpeed.value) || 2.0);
        const durMs = Math.max(60000, Math.ceil((distM / speed) / 60) * 60000);
        const startMs = Math.round(currentMs), endMs = startMs + durMs;
        pushUndoSnapshot();
        simData.events.push({
          id: `auth_move_${simData.events.length + 1}`, phase_id: simData.phases[0]?.id || "authored_phase",
          start_ms: startMs, end_ms: endMs, target_asset_id: el.authorAsset.value,
          type: "move", from_waypoint_id: fromId, to_waypoint_id: hitWp, path, easing: "ease_in_out", max_speed_mps: speed,
        });
        simData.events.sort((a, b) => a.start_ms - b.start_ms);
        if (endMs > simData.scene.duration_ms) { simData.scene.duration_ms = endMs; el.scrubber.max = endMs; }
        authoring.draftPath = null;
        el.authorHint.textContent = `Added traverse ${fromId} -> ${hitWp} (${Math.round(distM)}m, ${durMs / 60000}m)`;
      } else {
        authoring.draftPath.via.push(worldPt);
        el.authorHint.textContent = `Added via point #${authoring.draftPath.via.length}. Click end waypoint to finish.`;
      }
      redrawCurrent();
      return;
    }

    if (authoring.enabled && authoring.tool === "zone") {
      const worldPt = screenToWorld(x, y);
      if (authoring.draftZone.length >= 3 && Math.hypot(worldPt[0] - authoring.draftZone[0][0], worldPt[1] - authoring.draftZone[0][1]) <= 35) {
        commitDraftZone(); return;
      }
      authoring.draftZone.push(worldPt);
      el.authorHint.textContent = `Zone vertex #${authoring.draftZone.length} placed.`;
      redrawCurrent();
      return;
    }

    camera.isDragging = true; camera.dragStartX = x - camera.panX; camera.dragStartY = y - camera.panY;
    canvas.classList.add("dragging");
  });

  window.addEventListener("mousemove", (e) => {
    if (!camera.isDragging) return;
    const { x, y } = getCanvasCoords(e);
    camera.panX = x - camera.dragStartX; camera.panY = y - camera.dragStartY;
    redrawCurrent();
  });
  window.addEventListener("mouseup", () => { if (camera.isDragging) { camera.isDragging = false; canvas.classList.remove("dragging"); } });

  el.sparkCanvas.addEventListener("mousedown", (e) => {
    if (!simData) return;
    const rect = el.sparkCanvas.getBoundingClientRect();
    const clickX = ((e.clientX - rect.left) / rect.width) * el.sparkCanvas.width;
    const frac = Math.min(1, Math.max(0, (clickX - 26) / (el.sparkCanvas.width - 34)));
    currentMs = frac * simData.scene.duration_ms;
    redrawCurrent();
  });

  el.fileInput.addEventListener("change", (e) => {
    const file = e.target.files[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => { try { loadTimeline(JSON.parse(ev.target.result)); } catch (err) { alert("Invalid JSON: " + err.message); } };
    reader.readAsText(file);
  });
  el.spriteInput.addEventListener("change", (e) => {
    for (const file of e.target.files) {
      const url = URL.createObjectURL(file), fname = file.name.toLowerCase();
      cacheImageSrc(fname, url); cacheImageSrc(fname.replace(/\.[^.]+$/, ""), url);
      if (simData && simData.scene.background && basename(simData.scene.background) === fname) bgImage = spriteCache.get(fname);
    }
    redrawCurrent();
  });

  el.btnToggleAuthor.onclick = () => {
    authoring.enabled = !authoring.enabled;
    el.btnToggleAuthor.textContent = `Authoring Mode: ${authoring.enabled ? "ON" : "OFF"}`;
    el.btnToggleAuthor.classList.toggle("primary", authoring.enabled);
    el.authorToolbar.classList.toggle("visible", authoring.enabled);
    if (authoring.enabled) renderEventInspector(); else setAuthorTool("pan");
  };
  el.toolPan.onclick = () => setAuthorTool("pan");
  el.toolWaypoint.onclick = () => setAuthorTool("waypoint");
  el.toolPath.onclick = () => setAuthorTool("path");
  el.toolZone.onclick = () => setAuthorTool("zone");
  el.btnFinishZone.onclick = commitDraftZone;
  el.btnMount.onclick = () => addCouplingEvent("attach");
  el.btnDismount.onclick = () => addCouplingEvent("detach");
  el.inspFilter.onchange = renderEventInspector;
  el.btnUndo.onclick = undoAuthoring;
  el.btnRedo.onclick = redoAuthoring;
  el.btnCancelDraft.onclick = () => { authoring.draftPath = null; authoring.draftZone = []; el.authorHint.textContent = "Active draft cleared."; redrawCurrent(); };
  el.btnResetView.onclick = resetCamera;

  el.btnExportDsl.onclick = () => {
    if (!simData) return;
    const blob = new Blob([exportSimLineDSL(simData)], { type: "text/plain;charset=utf-8" });
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `${simData.scene.id}.simline`; a.click(); URL.revokeObjectURL(a.href);
  };
  el.btnExportJson.onclick = () => {
    if (!simData) return;
    const blob = new Blob([JSON.stringify(simData, null, 2)], { type: "application/json;charset=utf-8" });
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `${simData.scene.id}.json`; a.click(); URL.revokeObjectURL(a.href);
  };

  window.addEventListener("keydown", (e) => {
    if (!authoring.enabled || e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
    const mod = e.ctrlKey || e.metaKey;
    if (mod && e.key.toLowerCase() === "z" && !e.shiftKey) { e.preventDefault(); undoAuthoring(); }
    else if (mod && (e.key.toLowerCase() === "y" || (e.key.toLowerCase() === "z" && e.shiftKey))) { e.preventDefault(); redoAuthoring(); }
  });

  el.btnPlayPause.onclick = () => { if (!simData) return; if (currentMs >= simData.scene.duration_ms) currentMs = 0; setPlaying(!isPlaying); };
  el.btnReset.onclick = () => { if (!simData) return; setPlaying(false); currentMs = 0; redrawCurrent(); };
  el.btnStepBack.onclick = () => { if (!simData) return; currentMs = Math.max(0, currentMs - 60000); redrawCurrent(); };
  el.btnStepFwd.onclick = () => { if (!simData) return; currentMs = Math.min(simData.scene.duration_ms, currentMs + 60000); redrawCurrent(); };
  el.speedSelect.onchange = (e) => { speedMultiplier = Number(e.target.value); };
  el.scrubber.oninput = (e) => { if (!simData) return; currentMs = Number(e.target.value); redrawCurrent(); };

  // --- Embedded Sample Sprites & Lunar EVA Timeline ---
  const svgUri = (svg) => "data:image/svg+xml;utf8," + encodeURIComponent(svg.trim());
  const SPRITE_LANDER = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><polygon points="32,6 50,24 44,44 20,44 14,24" fill="#cbd5e1" stroke="#0f172a" stroke-width="3"/><line x1="20" y1="44" x2="10" y2="58" stroke="#94a3b8" stroke-width="4"/><line x1="44" y1="44" x2="54" y2="58" stroke="#94a3b8" stroke-width="4"/><circle cx="32" cy="24" r="6" fill="#38bdf8"/></svg>`);
  const SPRITE_ROVER = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="14" y="16" width="36" height="32" rx="6" fill="#0284c7" stroke="#e2e8f0" stroke-width="3"/><rect x="6" y="12" width="8" height="14" rx="2" fill="#475569"/><rect x="50" y="12" width="8" height="14" rx="2" fill="#475569"/><rect x="6" y="38" width="8" height="14" rx="2" fill="#475569"/><rect x="50" y="38" width="8" height="14" rx="2" fill="#475569"/><rect x="22" y="22" width="20" height="12" rx="2" fill="#38bdf8"/></svg>`);
  const SPRITE_CREW = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><circle cx="32" cy="32" r="22" fill="#f8fafc" stroke="#22c55e" stroke-width="4"/><ellipse cx="32" cy="28" rx="12" ry="9" fill="#f59e0b" stroke="#0f172a" stroke-width="2"/></svg>`);
  const SPRITE_SEISMO = svgUri(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><polygon points="32,10 54,50 10,50" fill="#f59e0b" stroke="#0f172a" stroke-width="3"/><circle cx="32" cy="36" r="6" fill="#0f172a"/></svg>`);

  const SAMPLE_TIMELINE = {
    schema_version: "1.0.0",
    scene: { id: "ShackletonRim_EVA1", background: "", dimensions: { width: 2048, height: 2048 }, scale_m_per_px: 0.5, duration_ms: 7200000 },
    waypoints: {
      lander_pad: { pos: [320, 1680], label: "HLS Lander Pad" },
      solar_ridge: { pos: [740, 1220], label: "Connecting Ridge" },
      shackleton_rim: { pos: [1420, 680], label: "Station 1: Shackleton Rim" },
      psr_edge: { pos: [1580, 560], label: "Station 2: PSR Edge" }
    },
    zones: [
      { id: "psr_crater_floor", type: "shadow", geometry: { shape: "polygon", points: [[1540,480],[1950,420],[1980,820],[1610,690]] }, modifiers: { solar_multiplier: 0.0, thermal_penalty: "high" } },
      { id: "lander_blast_koz", type: "hazard", geometry: { shape: "circle", center: [320,1680], radius_px: 90 } },
      { id: "ridge_sunlight_corridor", type: "solar_rich", geometry: { shape: "polygon", points: [[580,1380],[920,1080],[1010,1180],[670,1480]] }, modifiers: { solar_multiplier: 1.0 } }
    ],
    windows: [{ id: "lunar_relay_pass_1", start_ms: 3300000, end_ms: 4800000, bandwidth_mbps: 50 }],
    assets: {
      hls_lander: { is_static: true, image: SPRITE_LANDER, start_pos: [320,1680], layer: 1, tags: ["lander"], resources: {} },
      ltv_rover: { is_static: false, image: SPRITE_ROVER, start_pos: [320,1680], layer: 2, tags: ["vehicle"], resources: { battery: { initial: 100, unit: "%", min: 20, max: 100 }, data_buffer: { initial: 0, unit: "GB", min: 0, max: 64 } } },
      astronaut_1: { is_static: false, image: SPRITE_CREW, start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      astronaut_2: { is_static: false, image: SPRITE_CREW, start_pos: [320,1680], layer: 3, tags: ["crew"], resources: { suit_o2: { initial: 100, unit: "%", min: 25, max: 100 }, suit_battery: { initial: 100, unit: "%", min: 20, max: 100 } } },
      seismometer_pkg: { is_static: false, image: SPRITE_SEISMO, start_pos: [320,1680], layer: 2, tags: ["payload"], resources: {} }
    },
    phases: [
      { id: "eva_1", name: "EVA-1: Egress & Prep", start_ms: 0, end_ms: 900000 },
      { id: "eva_2", name: "EVA-2: Outbound Traverse", start_ms: 900000, end_ms: 2700000 },
      { id: "eva_3", name: "EVA-3: Rim Science", start_ms: 2700000, end_ms: 4800000 },
      { id: "eva_4", name: "EVA-4: Return & Closeout", start_ms: 4800000, end_ms: 7200000 }
    ],
    events: [
      { id: "e1", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e2", phase_id: "eva_1", start_ms: 0, end_ms: 600000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.25 },
      { id: "e3", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e4", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e5", phase_id: "eva_1", start_ms: 600000, end_ms: 900000, target_asset_id: "seismometer_pkg", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e6", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "move", from_waypoint_id: "lander_pad", to_waypoint_id: "shackleton_rim", path: [[320,1680],[520,1480],[740,1220],[1120,910],[1420,680]], easing: "ease_in_out", max_speed_mps: 2.0 },
      { id: "e7", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.8 },
      { id: "e8", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: 0.3 },
      { id: "e9", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_1", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e10", phase_id: "eva_2", start_ms: 900000, end_ms: 2700000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.3 },
      { id: "e11", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e12", phase_id: "eva_3", start_ms: 2700000, end_ms: 3000000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e13", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "seismometer_pkg", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [1420,680] },
      { id: "e14", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "move", from_waypoint_id: "shackleton_rim", to_waypoint_id: "psr_edge", path: [[1420,680],[1580,560]], easing: "linear", max_speed_mps: 0.6 },
      { id: "e15", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "label", text: "Core Sampling at PSR Edge" },
      { id: "e16", phase_id: "eva_3", start_ms: 3000000, end_ms: 3900000, target_asset_id: "astronaut_2", type: "resource_delta", resource: "suit_o2", rate_per_min: -0.6 },
      { id: "e17", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "state", state: "downlinking" },
      { id: "e18", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "data_buffer", rate_per_min: -0.9 },
      { id: "e19", phase_id: "eva_3", start_ms: 3900000, end_ms: 4500000, target_asset_id: "astronaut_2", type: "move", from_waypoint_id: "psr_edge", to_waypoint_id: "shackleton_rim", path: [[1580,560],[1420,680]], easing: "linear", max_speed_mps: 0.6 },
      { id: "e20", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_1", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e21", phase_id: "eva_3", start_ms: 4500000, end_ms: 4800000, target_asset_id: "astronaut_2", type: "attach", parent_asset_id: "ltv_rover" },
      { id: "e22", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "move", from_waypoint_id: "shackleton_rim", to_waypoint_id: "lander_pad", path: [[1420,680],[1120,910],[740,1220],[520,1480],[320,1680]], easing: "ease_in_out", max_speed_mps: 2.0 },
      { id: "e23", phase_id: "eva_4", start_ms: 4800000, end_ms: 6600000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: -0.75 },
      { id: "e24", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_1", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e25", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "astronaut_2", type: "detach", parent_asset_id: "ltv_rover", detach_pos: [320,1680] },
      { id: "e26", phase_id: "eva_4", start_ms: 6600000, end_ms: 7200000, target_asset_id: "ltv_rover", type: "resource_delta", resource: "battery", rate_per_min: 1.5 }
    ]
  };

  el.btnLoadSample.onclick = () => loadTimeline(SAMPLE_TIMELINE);
  loadTimeline(SAMPLE_TIMELINE);
})();
</script>
</body>
</html>


Suggest icon sizes for the lunar sim timeline

For a 2048 × 2048 lunar map rendered on a 900 × 900 canvas (base scale ≈ 0.44x) with zoom up to 800%, size your icons across two contexts: Map Sprites (world-space) and Timeline/HUD Controls (screen-space).

1. Map Canvas Sprites (World-Space)

Use SVG whenever possible so sprites stay crisp at 800% zoom. If using raster PNGs, author them at 2x–4x their base render size to prevent pixelation when zoomed in.

Entity CategorySource File (PNG / SVG)World-Space Render SizeOn-Screen Size (at 100% Zoom)
Static Landmarks (hls_lander, habitats)256 × 256 px (or SVG)72–96 px~32–42 px
Vehicles (ltv_rover)128 × 128 px (or SVG)56–64 px~25–28 px
Crew (astronaut_1, astronaut_2)128 × 128 px (or SVG)40–48 px~18–21 px
Deployable Payloads (seismometer_pkg)128 × 128 px (or SVG)36–40 px~16–18 px
Waypoints (lander_pad, shackleton_rim)64 × 64 px (or SVG)32–40 px~14–18 px
  • Visual Hierarchy: Keep a ~1.5:1 size ratio between vehicles and crew, and a ~1.2:1 ratio between crew and waypoints, so overlapping icons at stations remain distinguishable.

  • Padding: Leave 10–15% transparent padding inside each sprite canvas so rotated vehicles (ctx.rotate) never clip at the corners.

2. Timeline & HUD UI Icons (Screen-Space)

If you add icons to the playback bar, Event Inspector, or sidebar telemetry cards, stick to standard UI pixel grids:

UI LocationRecommended SizeNotes
Timeline Scrubber / Phase Markers14 × 14 px or 16 × 16 pxKeeps dense event clusters readable without overlapping.
Event Inspector Rows (move, attach, detach)14 × 14 pxAligns cleanly with 11px monospace text.
Sidebar Asset Headers & Legend20 × 20 px or 24 × 24 pxMatches the height of asset badges and resource bars.
Authoring Toolbar Buttons16 × 16 pxStandard icon-button proportion with 4–6px padding.

3. Tip for Zooming (simline_viewer.html)

At 800% zoom, a 64px world-space rover becomes ~225px wide on screen and can obscure nearby waypoints. If you want icons to stay readable at both 40% and 800% zoom, scale them sub-linearly with the camera zoom inside render():

JavaScript
// Scales smoothly without getting huge at 800% or tiny at 40%
const zoomCompensation = 1 / Math.pow(camera.zoom, 0.55);
const drawSize = baseSize * zoomCompensation;


Can these icons be generated by Nano Banana?

Yes—Nano Banana 2 (Gemini 3 Flash Image) can generate the icons for your lunar simulation, and you can also refine any result with Nano Banana Pro by clicking the three-dot menu on a generated image and selecting Redo with Pro.

Here is how it fits into your simline_viewer.html workflow and a few practical tips to get game-ready sprites:

What Works Well with Nano Banana

  • Consistent Icon Sets (Style Transfer): Because Nano Banana 2 supports multi-image composition and style transfer, you can generate one anchor sprite first (for example, the ltv_rover) and use it as a reference image to generate the hls_lander, astronaut_1, seismometer_pkg, and waypoint markers in the exact same top-down visual style.

  • Sprite Sheets or Individual Icons: You can either generate individual square icons or a clean grid/sheet of all lunar assets in a single pass, then slice and resize them to 128 × 128 px or 256 × 256 px PNGs for sharp rendering even when zoomed in.

  • Lunar Terrain Map: It can also generate a top-down 2048 × 2048 Shackleton Crater Rim background map to load alongside your sprites via the Load Sprites / Map button.

Things to Keep in Mind

  1. Raster PNGs vs. Vector SVGs: Nano Banana outputs raster images rather than native .svg code. That works seamlessly with simline_viewer.html's ctx.drawImage() pipeline—just downscale the generated images to 128 × 128 or 256 × 256 PNGs so they stay crisp up to 800% zoom. (If you want tiny, infinitely scalable inline SVGs for UI buttons, hand-coded SVG is still better.)

  2. Background Removal: Generated images won't natively have an alpha channel. Prompt for a flat, solid high-contrast background (such as pure black #000000 or pure white #FFFFFF with no drop shadows), then strip the background with a quick Python Pillow script before loading the PNGs into the viewer.

  3. Top-Down Heading Alignment: For vehicles like ltv_rover, explicitly specify "strictly top-down orthographic view, facing straight up (north), centered with generous padding" so the rover aligns cleanly with the SPRITE_HEADING_OFFSET = Math.PI / 2 rotation logic already built into simline_viewer.html.

If you'd like, I can generate the first lunar asset icon (like the top-down ltv_rover or hls_lander) right now, or write a small Python script to batch-remove backgrounds and resize a generated sprite sheet into individual PNGs.


Shackleton Crater Rim background map

Here is your top-down Shackleton Crater Rim background map, featuring the sunlit connecting ridge and the permanently shadowed crater floor in the upper-right corner ready to load into simline_viewer.html:



top-down HLS Lander Pad



Top-down Station 1: Shackleton Rim



Top-down Station 2: PSR Shadow Boundary



Top-down LTV Rover



Top-down HLS Lander



Top-down astronaut on EVA


From <https://gemini.google.com/app/26be29b0585d5221>  Google Gemini (4 Neon)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#761 New Ways to Access Online Content, particularly Virtual Reality Content