#5051 Excel Workbook Simulator
#5051 Excel Workbook Simulator
Continued from
https://learningfromchatgpt.blogspot.com/2026/12/5047-dsl-simulation-timeline-definition.html
#5051 Describe how the simulator can be implemented in an Excel Workbook, with timeline(s) defined on separate worksheets
Implementing the SimLine simulator in an Excel workbook (.xlsm) maps cleanly onto a data-engine-view architecture: structured Excel Tables (ListObjects) replace the DSL blocks, each mission scenario lives on its own timeline worksheet, formulas compute deterministic state at any Mission Elapsed Time (MET), and a dashboard sheet renders the 2D map, telemetry gauges, and playback controls.
1. Workbook Architecture (Worksheet Layout)
Separate static world definitions from scenario timelines so you can swap or compare multiple mission plans (e.g., nominal vs. contingency EVA) without duplicating map data.
| Worksheet Name | Role | Contents / Excel Tables |
| Dashboard | View & Controls | 2D Lunar Map, Play/Pause/Step buttons, Speed selector, Active Timeline dropdown, MET scrubber, Resource Gauges, Sparkline chart, Alert banner. |
| Scene_World | World Setup | Scene dimensions (2048 × 2048), scale (0.5 m/px), background image path, tbl_Waypoints, tbl_Zones, tbl_CommWindows. |
| Assets | Entity Registry | tbl_Assets (ID, Static flag, Sprite filename, Start Waypoint, Layer, Tags) and tbl_Resources (Asset ID, Resource Name, Initial, Min, Max, Unit). |
| TL_EVA1_Nominal | Timeline #1 | tbl_TL_EVA1_Nominal — full event schedule for the baseline 2-hour Shackleton Rim mission. |
| TL_EVA1_Abort | Timeline #2 | tbl_TL_EVA1_Abort — alternate scenario (e.g., early rover battery fault and direct return) using the exact same column schema. |
| Sim_Engine | Hidden State Calc | Pulls the active timeline sheet, evaluates asset (X, Y), heading, parent coupling, resource levels, zone checks, and 120-point sparkline series at the current MET. |
2. Defining Timelines on Separate Worksheets
Every timeline worksheet (TL_*) uses an identical Excel Table schema so the engine can switch scenarios dynamically from a single dropdown cell on Dashboard (e.g., Dashboard!B2 = "TL_EVA1_Nominal").
Timeline Table Columns
| Column | Example Value | Purpose |
| Event_ID | outbound_drive | Unique block/event key for dependency references. |
| Phase | EVA-2: Outbound | Used for phase jump buttons and timeline filtering. |
| Trigger_Mode | AFTER or AT | Determines whether Start_MET_Min is absolute or chained. |
| Ref_Event_ID | board_rover | Prior Event_ID when Trigger_Mode = "AFTER". |
| Offset_Min | 0 | Delay after Ref_Event_ID completes. |
| Duration_Min | 30 | Event length in minutes. |
| Start_MET_Min | (Formula) | Resolves AT or XLOOKUP(Ref_Event_ID, ...) + Offset_Min. |
| End_MET_Min | (Formula) | =[@Start_MET_Min] + [@Duration_Min] |
| Target_Asset | ltv_rover | Data-validated dropdown bound to tbl_Assets[Asset_ID]. |
| Event_Type | move / attach / detach / state / resource_delta | Data-validated primitive type. |
From_WP / To_WP | lander_pad → shackleton_rim | Waypoint dropdowns bound to tbl_Waypoints[WP_ID]. |
| Via_Points | 520,1480; 740,1220; 1120,910 | Optional semicolon-delimited intermediate (x, y) coordinates. |
| Param_1 | battery / ltv_rover / downlinking | Resource name, parent asset ID, or state string. |
| Param_2 | -0.8 / 2.0 | Signed rate_per_min or max_speed_mps. |
| Validation_Flag | (Formula) | Instant row-level check (OK, SPEED_ERR, COMM_ERR, STATIC_ERR). |
Chaining after <id> with Native Formulas
In Start_MET_Min, use XLOOKUP so editing any upstream duration automatically ripples the entire mission schedule:
=IF([@Trigger_Mode]="AT", [@Offset_Min], XLOOKUP([@Ref_Event_ID], [Event_ID], [End_MET_Min], 0) + [@Offset_Min])
Multi-Timeline Switching
Formula-only approach: On
Sim_Engine, copy the active timeline into a staging range via a single VBAWorksheet_Changehandler when theDashboardscenario dropdown changes (avoiding volatileINDIRECTrecalculation overhead on large tables).Scenario Comparison tab (optional): Because each timeline lives on its own sheet, a summary tab can display side-by-side KPIs (Final Rover Battery %, Min Crew O2 %, Total Distance, Constraint Errors) across all
TL_*tabs simultaneously.
3. State Evaluation & Physics Engine (Sim_Engine)
A single master clock cell—Sim_Engine!B2 (Current_MET_Min, ranging from 0 to 120)—drives the entire workbook.
Resource Integration (100% Formula-Driven):
For each asset and resource, calculate the exact level at
Current_MET_MinusingSUMPRODUCTover the active timeline'sresource_deltarows:=Initial_Val + SUMPRODUCT( (Active_Type="resource_delta") * (Active_Asset=Asset_ID) * (Active_Param1=Res_Name) * (Active_Param2) * MAX(0, MIN(Current_MET_Min, Active_End) - Active_Start) )Note: Wrap the
MAX(0, ...)clamp withIF(Current_MET_Min > Active_Start, MIN(Current_MET_Min, Active_End) - Active_Start, 0)so it evaluates cleanly as an array formula.Position, Polyline Interpolation & Coupling:
Straight-line moves: Pure Excel formulas (
XLOOKUPfor the latestmoveevent withStart_MET <= t, then linear/eased interpolation betweenFrom_WPandTo_WP).Multi-segment
viapolylines, heading angle, and point-in-polygon KOZ checks: Implement as clean VBA User-Defined Functions (UDFs)—SimSamplePolylineX(pathStr, frac),SimSamplePolylineY(pathStr, frac),SimHeadingDeg(pathStr, frac), andSimPointInPoly(x, y, polyStr).Parent-Child Coupling (
attach/detach): Find the most recentattachordetachrow for each asset whereStart_MET <= t. If the latest event isattach, the asset's(X, Y)formula simply references its parent asset's(X, Y)cells.
Sparkline Data Table:
Place a 121-row table (
t = 0, 1, 2, ... 120 min) onSim_Engineusing the same resource integration formula. Bind a standard Excel Line Chart onDashboardto this table, plus a vertical 2-point XY series atx = Current_MET_Minto render the moving MET playhead.
4. 2D Map Rendering & Playback Controls (Dashboard)
Excel supports two distinct rendering strategies depending on whether you prioritize zero-macro simplicity or rotated sprite graphics:
Approach A: XY Scatter Chart Map (Best for Scrubbing & Native Charts)
Insert a square XY Scatter Chart locked to
X: [0, 2048]andY: [0, 2048](with Y-axis set to Values in reverse order so(0, 0)sits at the top-left, matching canvas coordinates).Set the Plot Area Fill to your
Shackleton Crater RimPNG image.Plot each visual layer as a chart series:
Zones: Closed XY polygon series with dashed borders.
Traverse Paths: Connected XY scatter lines (faint grey for planned, bright cyan for active).
Waypoints & Assets: Single-point XY series where each marker's Fill is set to your custom PNG icon (
HLS Lander,Station 1,Astronaut,LTV Rover).
Limitation: Excel chart markers cannot rotate dynamically per frame; the rover icon stays upright.
Approach B: VBA Shapes on a Locked Map (Best for Rotated Sprites)
Place the
Shackleton Crater Rimimage as a locked backgroundShapeonDashboard(e.g.,600 × 600 pt).Insert your transparent PNG sprites (
ltv_rover,astronaut_1,hls_lander, etc.) as namedShapeobjects above it.A lightweight VBA
UpdateMapSprites()subroutine reads(X, Y, Heading, Parent)fromSim_Engineand updates each sprite:shp.Left = mapLeft + (worldX / 2048#) * mapWidth - (shp.Width / 2#) shp.Top = mapTop + (worldY / 2048#) * mapHeight - (shp.Height / 2#) shp.Rotation = headingDeg ' Aligns LTV Rover nose to travel direction shp.Visible = IIf(parentId = "", msoTrue, msoFalse)
Playback Controls
Manual Scrubbing: Link a Form Control Scroll Bar (min
0, max1200for 0.1-min resolution) directly toSim_Engine!B2. Dragging the bar updates the map, resource bars, alerts, and sparkline playhead in real time.Play / Pause / Speed Loop: Use a VBA
Do While isPlayingloop withTimerdelta-clamping andDoEvents(allowing the Pause button to interrupt cleanly), steppingCurrent_MET_Minbydt * speedMultiplierand callingCalculate+UpdateMapSprites.
5. Constraint Validation & SimLine Round-Trip Export
Live Constraint Highlighting: Apply Conditional Formatting on
Dashboardtelemetry cards (red fill ifBattery < 20%orSuit_O2 < 25%, amber ifComm = BLACKOUTduring a downlink, red alert banner ifSimPointInPolyreturnsTRUEfor a hazard KOZ).JSON /
.simlineBridge: Add an Export Active Timeline to JSON button backed by a short VBA macro that serializesScene_World,Assets, and the currently selectedTL_*sheet into the exactSimLineTimelineJSON schema—letting you author and run quick trade studies in Excel, then drop the exported.jsonstraight intosimline_viewer.htmlorsimline_validator.py.
Would you like me to generate a working .xlsx template workbook with the Scene_World, Assets, TL_EVA1_Nominal, TL_EVA1_Abort, Sim_Engine, and Dashboard sheets pre-wired with formulas and the XY Scatter map?
Yes
Your XLSX file is ready
What's Inside SimLine_Lunar_EVA_Simulator.xlsx
| Worksheet | Purpose | Key Features |
| Dashboard | Mission Control View | Scenario dropdown (C4), editable Current MET (min) scrubber (C5), live KPI cards (Phase, Comm Link, Active Events, Progress, Audit), Live Asset Telemetry table with conditional formatting, Nominal vs. Abort comparison table, 2D Operations XY Scatter Map, and Consumables Profile Line Chart. |
| Scene_World | World Setup | 2048 × 2048 coordinate bounds, 0.5 m/px scale, 4 named waypoints, 3 environment zones (PSR shadow, lander KOZ, solar corridor), and the lunar_relay_pass_1 comm window (MET 55–80 min, 50 Mbps). |
| Assets | Entity & Resource Registry | Static/dynamic asset table with INDEX/MATCH starting coordinates plus initial/min/max consumable specs for ltv_rover, astronaut_1, and astronaut_2. |
| TL_EVA1_Nominal | Baseline 2-Hour EVA | 31 events with chained AFTER formulas, data-validated dropdowns, and row-level Validation_Flag checks (static mutation, comm blackout downlinks, and speed limits). |
| TL_EVA1_Abort | Contingency Scenario | 18-event abort timeline triggered by a -2.8%/min rover battery fault on the Connecting Ridge, forcing a direct return to the HLS pad. |
| Sim_Engine | Formula Engine | Non-volatile scenario staging table, live position/coupling/resource evaluator at Current MET, map zone polygon coordinates, and a 61-point (0–120 min) telemetry curve table driving the dashboard chart. |
Quick Tips for Using It in Excel
Scrub the Mission: Change cell Dashboard!C5 (default
60min) to any value between0and120to watch the rover, crew, seismometer, resource levels, and comm window status update on the map and tables.Compare Scenarios: Switch Dashboard!C4 between
TL_EVA1_NominalandTL_EVA1_Abortto immediately swap timelines and re-plot the consumables chart.Add Your Lunar Background Image: Right-click the plot area of the 2D Operations Map chart on
Dashboard→ Format Plot Area → Fill → Picture or texture fill → select the Shackleton Crater Rim map image generated earlier.Add a Visual Scrubber Bar (Optional): Go to Developer → Insert → Scroll Bar (Form Control), draw it next to
C5, right-click → Format Control, set Minimum0, Maximum120, and Cell link to$C$5.
Would you like the companion VBA macro module to add a Play/Pause animation loop and an Export Active Timeline to SimLine JSON button?
Yes
Save SimLine_Lunar_EVA_Simulator.xlsx as an Excel Macro-Enabled Workbook (.xlsm), press Alt + F11 → Insert → Module, and paste the complete VBA module below. It is pre-wired to the exact sheets and cell ranges in your workbook and exports schema-valid JSON compatible with both simline_viewer.html and simline_validator.py.
Complete VBA Module (modSimLineStudio)
Option Explicit
' =============================================================================
' SimLine Studio — Playback Controller & SimLineTimeline JSON Exporter
' Wired to: Dashboard, Scene_World, Assets, TL_EVA1_Nominal, TL_EVA1_Abort
' =============================================================================
Private gIsPlaying As Boolean
Private gSpeedSimMinPerSec As Double ' Simulation minutes advanced per real second
' -----------------------------------------------------------------------------
' 1. PLAYBACK CONTROLS (Assign these macros to Dashboard Form Control Buttons)
' -----------------------------------------------------------------------------
Public Sub Sim_TogglePlayPause()
If gIsPlaying Then
gIsPlaying = False
Application.StatusBar = "SimLine: Paused"
Exit Sub
End If
If gSpeedSimMinPerSec <= 0 Then gSpeedSimMinPerSec = 2# ' Default: 120x (2 min/sec)
Dim wsDash As Worksheet
Dim wsWorld As Worksheet
Dim maxMet As Double
Dim curMet As Double
Dim lastTick As Double
Dim nowTick As Double
Dim dt As Double
Set wsDash = ThisWorkbook.Worksheets("Dashboard")
Set wsWorld = ThisWorkbook.Worksheets("Scene_World")
maxMet = Val(wsWorld.Range("B11").Value)
If maxMet <= 0 Then maxMet = 120#
' Restart from 0 if already at end of mission
If Val(wsDash.Range("C5").Value) >= maxMet Then
wsDash.Range("C5").Value = 0
End If
gIsPlaying = True
lastTick = Timer
Application.StatusBar = "SimLine: Playing (" & gSpeedSimMinPerSec & " sim-min/sec) — Click Play/Pause again to stop"
Do While gIsPlaying
nowTick = Timer
dt = nowTick - lastTick
If dt < 0 Then dt = dt + 86400# ' Handle midnight Timer rollover
' Throttle updates to ~15 FPS so Excel charts redraw smoothly
If dt >= 0.065 Then
lastTick = nowTick
curMet = Val(wsDash.Range("C5").Value) + (dt * gSpeedSimMinPerSec)
If curMet >= maxMet Then
wsDash.Range("C5").Value = maxMet
wsDash.Calculate
gIsPlaying = False
Application.StatusBar = "SimLine: Mission Complete (MET " & maxMet & " min)"
Exit Do
Else
wsDash.Range("C5").Value = Round(curMet, 2)
Application.Calculate
End If
End If
DoEvents
Loop
End Sub
Public Sub Sim_Reset()
gIsPlaying = False
ThisWorkbook.Worksheets("Dashboard").Range("C5").Value = 0
Application.Calculate
Application.StatusBar = "SimLine: Reset to MET 00:00:00"
End Sub
Public Sub Sim_StepForward()
Dim wsDash As Worksheet
Dim maxMet As Double
gIsPlaying = False
Set wsDash = ThisWorkbook.Worksheets("Dashboard")
maxMet = Val(ThisWorkbook.Worksheets("Scene_World").Range("B11").Value)
wsDash.Range("C5").Value = Application.WorksheetFunction.Min(maxMet, Val(wsDash.Range("C5").Value) + 2#)
Application.Calculate
End Sub
Public Sub Sim_StepBack()
Dim wsDash As Worksheet
gIsPlaying = False
Set wsDash = ThisWorkbook.Worksheets("Dashboard")
wsDash.Range("C5").Value = Application.WorksheetFunction.Max(0, Val(wsDash.Range("C5").Value) - 2#)
Application.Calculate
End Sub
Public Sub Sim_CycleSpeed()
Select Case gSpeedSimMinPerSec
Case 1#: gSpeedSimMinPerSec = 2# ' 120x
Case 2#: gSpeedSimMinPerSec = 5# ' 300x
Case 5#: gSpeedSimMinPerSec = 0.5 ' 30x
Case Else: gSpeedSimMinPerSec = 1# ' 60x
End Select
Application.StatusBar = "SimLine Speed: " & gSpeedSimMinPerSec & " sim-min/sec"
MsgBox "Playback speed set to " & gSpeedSimMinPerSec & " sim-min/sec (" & (gSpeedSimMinPerSec * 60) & "x).", vbInformation, "SimLine Studio"
End Sub
' -----------------------------------------------------------------------------
' 2. EXPORT ACTIVE TIMELINE TO SIMLINE JSON (Schema v1.0.0)
' -----------------------------------------------------------------------------
Public Sub ExportActiveTimelineToJSON()
Dim wsDash As Worksheet, wsWorld As Worksheet, wsAssets As Worksheet, wsTL As Worksheet
Dim scenName As String, sceneId As String
Dim savePath As Variant
Dim json As String
Dim fNum As Integer
gIsPlaying = False
Set wsDash = ThisWorkbook.Worksheets("Dashboard")
Set wsWorld = ThisWorkbook.Worksheets("Scene_World")
Set wsAssets = ThisWorkbook.Worksheets("Assets")
scenName = Trim$(CStr(wsDash.Range("C4").Value))
On Error Resume Next
Set wsTL = ThisWorkbook.Worksheets(scenName)
On Error GoTo 0
If wsTL Is Nothing Then
MsgBox "Timeline worksheet '" & scenName & "' not found.", vbCritical, "Export Failed"
Exit Sub
End If
sceneId = Trim$(CStr(wsWorld.Range("B6").Value))
savePath = Application.GetSaveAsFilename( _
InitialFileName:=sceneId & "_" & scenName & ".json", _
FileFilter:="SimLine JSON Files (*.json), *.json", _
Title:="Export Active Timeline to SimLine JSON")
If savePath = False Then Exit Sub
json = BuildSimLineJSON(wsWorld, wsAssets, wsTL)
fNum = FreeFile
Open CStr(savePath) For Output As #fNum
Print #fNum, json
Close #fNum
MsgBox "Exported '" & scenName & "' to:" & vbCrLf & CStr(savePath), vbInformation, "SimLine Export Complete"
End Sub
Private Function BuildSimLineJSON(wsWorld As Worksheet, wsAssets As Worksheet, wsTL As Worksheet) As String
Dim sb As String
Dim r As Long, i As Long, j As Long
Dim firstItem As Boolean
' --- Header & Scene ---
sb = "{" & vbCrLf
sb = sb & " ""schema_version"": ""1.0.0""," & vbCrLf
sb = sb & " ""scene"": {" & vbCrLf
sb = sb & " ""id"": """ & JsonEsc(wsWorld.Range("B6").Value) & """," & vbCrLf
sb = sb & " ""background"": """ & JsonEsc(wsWorld.Range("B7").Value) & """," & vbCrLf
sb = sb & " ""dimensions"": { ""width"": " & CLng(wsWorld.Range("B8").Value) & ", ""height"": " & CLng(wsWorld.Range("B9").Value) & " }," & vbCrLf
sb = sb & " ""scale_m_per_px"": " & NumStr(wsWorld.Range("B10").Value) & "," & vbCrLf
sb = sb & " ""duration_ms"": " & CLng(Val(wsWorld.Range("B11").Value) * 60000#) & vbCrLf
sb = sb & " }," & vbCrLf
' --- Waypoints (Scene_World rows 15..18+) ---
sb = sb & " ""waypoints"": {" & vbCrLf
firstItem = True
r = 15
Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
If Not firstItem Then sb = sb & "," & vbCrLf
firstItem = False
sb = sb & " """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """: { "
sb = sb & """pos"": [" & NumStr(wsWorld.Cells(r, 2).Value) & ", " & NumStr(wsWorld.Cells(r, 3).Value) & "], "
sb = sb & """label"": """ & JsonEsc(wsWorld.Cells(r, 4).Value) & """"
If Trim$(CStr(wsWorld.Cells(r, 5).Value)) <> "" Then
sb = sb & ", ""image"": """ & JsonEsc(wsWorld.Cells(r, 5).Value) & """"
End If
sb = sb & " }"
r = r + 1
Loop
sb = sb & vbCrLf & " }," & vbCrLf
' --- Zones (Scene_World rows 22..24+) ---
sb = sb & " ""zones"": [" & vbCrLf
firstItem = True
r = 22
Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
If Not firstItem Then sb = sb & "," & vbCrLf
firstItem = False
sb = sb & " { ""id"": """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """, "
sb = sb & """type"": """ & JsonEsc(wsWorld.Cells(r, 2).Value) & """, "
If LCase$(Trim$(CStr(wsWorld.Cells(r, 3).Value))) = "circle" Then
sb = sb & """geometry"": { ""shape"": ""circle"", ""center"": [" & ParseCoordPair(wsWorld.Cells(r, 7).Value) & "], ""radius_px"": " & NumStr(wsWorld.Cells(r, 6).Value) & " }"
Else
sb = sb & """geometry"": { ""shape"": ""polygon"", ""points"": [" & ParseCoordList(wsWorld.Cells(r, 7).Value) & "] }"
End If
If Trim$(CStr(wsWorld.Cells(r, 4).Value)) <> "" Or Trim$(CStr(wsWorld.Cells(r, 5).Value)) <> "" Then
sb = sb & ", ""modifiers"": { ""solar_multiplier"": " & NumStr(wsWorld.Cells(r, 4).Value) & ", ""thermal_penalty"": """ & JsonEsc(wsWorld.Cells(r, 5).Value) & """ }"
End If
sb = sb & " }"
r = r + 1
Loop
sb = sb & vbCrLf & " ]," & vbCrLf
' --- Comm Windows (Scene_World rows 28+) ---
sb = sb & " ""windows"": [" & vbCrLf
firstItem = True
r = 28
Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
If Not firstItem Then sb = sb & "," & vbCrLf
firstItem = False
sb = sb & " { ""id"": """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """, "
sb = sb & """start_ms"": " & CLng(Val(wsWorld.Cells(r, 2).Value) * 60000#) & ", "
sb = sb & """end_ms"": " & CLng(Val(wsWorld.Cells(r, 4).Value) * 60000#) & ", "
sb = sb & """bandwidth_mbps"": " & NumStr(wsWorld.Cells(r, 5).Value) & " }"
r = r + 1
Loop
sb = sb & vbCrLf & " ]," & vbCrLf
' --- Assets & Resources (Assets rows 6..10, Resources rows 15..20+) ---
sb = sb & " ""assets"": {" & vbCrLf
firstItem = True
r = 6
Do While Trim$(CStr(wsAssets.Cells(r, 1).Value)) <> ""
Dim aId As String, isStat As String, resJson As String, rr As Long, firstRes As Boolean
aId = Trim$(CStr(wsAssets.Cells(r, 1).Value))
isStat = IIf(UCase$(Trim$(CStr(wsAssets.Cells(r, 2).Value))) = "TRUE", "true", "false")
If Not firstItem Then sb = sb & "," & vbCrLf
firstItem = False
resJson = "{"
firstRes = True
rr = 15
Do While Trim$(CStr(wsAssets.Cells(rr, 1).Value)) <> ""
If Trim$(CStr(wsAssets.Cells(rr, 2).Value)) = aId Then
If Not firstRes Then resJson = resJson & ", "
firstRes = False
resJson = resJson & """" & JsonEsc(wsAssets.Cells(rr, 3).Value) & """: { "
resJson = resJson & """initial"": " & NumStr(wsAssets.Cells(rr, 4).Value) & ", "
resJson = resJson & """unit"": """ & JsonEsc(wsAssets.Cells(rr, 7).Value) & """, "
resJson = resJson & """min"": " & NumStr(wsAssets.Cells(rr, 5).Value) & ", "
resJson = resJson & """max"": " & NumStr(wsAssets.Cells(rr, 6).Value) & " }"
End If
rr = rr + 1
Loop
resJson = resJson & "}"
sb = sb & " """ & JsonEsc(aId) & """: { "
sb = sb & """is_static"": " & isStat & ", "
sb = sb & """image"": """ & JsonEsc(wsAssets.Cells(r, 8).Value) & """, "
sb = sb & """start_pos"": [" & NumStr(wsAssets.Cells(r, 5).Value) & ", " & NumStr(wsAssets.Cells(r, 6).Value) & "], "
sb = sb & """start_waypoint_id"": """ & JsonEsc(wsAssets.Cells(r, 4).Value) & """, "
sb = sb & """layer"": " & CLng(wsAssets.Cells(r, 7).Value) & ", "
sb = sb & """tags"": [""" & JsonEsc(wsAssets.Cells(r, 3).Value) & """], "
sb = sb & """resources"": " & resJson & " }"
r = r + 1
Loop
sb = sb & vbCrLf & " }," & vbCrLf
' --- Collect & Sort Timeline Rows by Start_MET_Min (Required by SimLine schema) ---
Dim evRows() As Long
Dim evCount As Long
evCount = 0
For r = 5 To 39
If Trim$(CStr(wsTL.Cells(r, 1).Value)) <> "" Then
evCount = evCount + 1
ReDim Preserve evRows(1 To evCount)
evRows(evCount) = r
End If
Next r
' Insertion sort by Start_MET_Min (col H = 8)
For i = 2 To evCount
Dim keyRow As Long, keyStart As Double
keyRow = evRows(i)
keyStart = Val(wsTL.Cells(keyRow, 8).Value)
j = i - 1
Do While j >= 1
If Val(wsTL.Cells(evRows(j), 8).Value) > keyStart Then
evRows(j + 1) = evRows(j)
j = j - 1
Else
Exit Do
End If
Loop
evRows(j + 1) = keyRow
Next i
' --- Phases (Aggregated from Events) ---
Dim phNames() As String, phStart() As Long, phEnd() As Long
Dim phCount As Long, pIdx As Long, foundPh As Long
phCount = 0
For i = 1 To evCount
r = evRows(i)
Dim pName As String, sMs As Long, eMs As Long
pName = Trim$(CStr(wsTL.Cells(r, 3).Value))
sMs = CLng(Val(wsTL.Cells(r, 8).Value) * 60000#)
eMs = CLng(Val(wsTL.Cells(r, 9).Value) * 60000#)
foundPh = 0
For pIdx = 1 To phCount
If phNames(pIdx) = pName Then foundPh = pIdx: Exit For
Next pIdx
If foundPh = 0 Then
phCount = phCount + 1
ReDim Preserve phNames(1 To phCount)
ReDim Preserve phStart(1 To phCount)
ReDim Preserve phEnd(1 To phCount)
phNames(phCount) = pName
phStart(phCount) = sMs
phEnd(phCount) = eMs
Else
If sMs < phStart(foundPh) Then phStart(foundPh) = sMs
If eMs > phEnd(foundPh) Then phEnd(foundPh) = eMs
End If
Next i
sb = sb & " ""phases"": [" & vbCrLf
For pIdx = 1 To phCount
If pIdx > 1 Then sb = sb & "," & vbCrLf
sb = sb & " { ""id"": """ & Slugify(phNames(pIdx)) & """, ""name"": """ & JsonEsc(phNames(pIdx)) & """, ""start_ms"": " & phStart(pIdx) & ", ""end_ms"": " & phEnd(pIdx) & " }"
Next pIdx
sb = sb & vbCrLf & " ]," & vbCrLf
' --- Events ---
sb = sb & " ""events"": [" & vbCrLf
For i = 1 To evCount
r = evRows(i)
Dim evType As String, fromWp As String, toWp As String, p1 As String, p2 As String
evType = LCase$(Trim$(CStr(wsTL.Cells(r, 11).Value)))
fromWp = Trim$(CStr(wsTL.Cells(r, 12).Value))
toWp = Trim$(CStr(wsTL.Cells(r, 13).Value))
p1 = Trim$(CStr(wsTL.Cells(r, 14).Value))
p2 = Trim$(CStr(wsTL.Cells(r, 15).Value))
If i > 1 Then sb = sb & "," & vbCrLf
sb = sb & " { ""id"": """ & JsonEsc(wsTL.Cells(r, 1).Value) & """, "
sb = sb & """phase_id"": """ & Slugify(CStr(wsTL.Cells(r, 3).Value)) & """, "
sb = sb & """start_ms"": " & CLng(Val(wsTL.Cells(r, 8).Value) * 60000#) & ", "
sb = sb & """end_ms"": " & CLng(Val(wsTL.Cells(r, 9).Value) * 60000#) & ", "
sb = sb & """target_asset_id"": """ & JsonEsc(wsTL.Cells(r, 10).Value) & """, "
sb = sb & """type"": """ & evType & """"
Select Case evType
Case "move"
sb = sb & ", ""from_waypoint_id"": """ & JsonEsc(fromWp) & """, ""to_waypoint_id"": """ & JsonEsc(toWp) & """"
sb = sb & ", ""path"": [[" & LookupWpPos(wsWorld, fromWp) & "], [" & LookupWpPos(wsWorld, toWp) & "]]"
sb = sb & ", ""easing"": """ & IIf(p1 <> "", JsonEsc(p1), "linear") & """"
If Val(p2) > 0 Then sb = sb & ", ""max_speed_mps"": " & NumStr(p2)
Case "attach"
sb = sb & ", ""parent_asset_id"": """ & JsonEsc(p1) & """"
Case "detach"
sb = sb & ", ""parent_asset_id"": """ & JsonEsc(p1) & """"
If toWp <> "" Then sb = sb & ", ""detach_pos"": [" & LookupWpPos(wsWorld, toWp) & "]"
Case "state"
sb = sb & ", ""state"": """ & JsonEsc(p1) & """"
Case "label"
sb = sb & ", ""text"": """ & JsonEsc(p1) & """"
Case "resource_delta"
sb = sb & ", ""resource"": """ & JsonEsc(p1) & """, ""rate_per_min"": " & NumStr(p2)
End Select
sb = sb & " }"
Next i
sb = sb & vbCrLf & " ]" & vbCrLf & "}"
BuildSimLineJSON = sb
End Function
' -----------------------------------------------------------------------------
' 3. HELPER FUNCTIONS
' -----------------------------------------------------------------------------
Private Function LookupWpPos(wsWorld As Worksheet, wpId As String) As String
Dim r As Long
r = 15
Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
If Trim$(CStr(wsWorld.Cells(r, 1).Value)) = wpId Then
LookupWpPos = NumStr(wsWorld.Cells(r, 2).Value) & ", " & NumStr(wsWorld.Cells(r, 3).Value)
Exit Function
End If
r = r + 1
Loop
LookupWpPos = "0, 0"
End Function
Private Function ParseCoordPair(ByVal s As String) As String
Dim parts() As String
parts = Split(Trim$(s), ",")
If UBound(parts) >= 1 Then
ParseCoordPair = NumStr(parts(0)) & ", " & NumStr(parts(1))
Else
ParseCoordPair = "0, 0"
End If
End Function
Private Function ParseCoordList(ByVal s As String) As String
Dim pairs() As String, out As String, k As Long
pairs = Split(s, ";")
For k = LBound(pairs) To UBound(pairs)
If Trim$(pairs(k)) <> "" Then
If out <> "" Then out = out & ", "
out = out & "[" & ParseCoordPair(pairs(k)) & "]"
End If
Next k
ParseCoordList = out
End Function
Private Function JsonEsc(ByVal v As Variant) As String
Dim s As String
s = CStr(v)
s = Replace(s, "\", "\\")
s = Replace(s, """", "\""")
s = Replace(s, vbCrLf, " ")
s = Replace(s, vbLf, " ")
JsonEsc = s
End Function
Private Function NumStr(ByVal v As Variant) As String
NumStr = Replace(Trim$(Str$(Val(v))), ",", ".")
End Function
Private Function Slugify(ByVal s As String) As String
Dim i As Long, ch As String, res As String
s = LCase$(Trim$(s))
For i = 1 To Len(s)
ch = Mid$(s, i, 1)
If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Then
res = res & ch
ElseIf Right$(res, 1) <> "_" And Len(res) > 0 Then
res = res & "_"
End If
Next i
If Right$(res, 1) = "_" Then res = Left$(res, Len(res) - 1)
Slugify = res
End Function
Wiring the Buttons on Dashboard
Go to Developer → Insert → Button (Form Control) and draw 5 small buttons along row 6 (or next to
C4:D5) onDashboard.Assign each button to its matching macro:
Play / Pause →
Sim_TogglePlayPauseReset →
Sim_Reset-2m →
Sim_StepBack+2m →
Sim_StepForwardSpeed →
Sim_CycleSpeedExport JSON →
ExportActiveTimelineToJSON
Click Export JSON to write a
SimLineTimelinev1.0.0 file you can drop directly intosimline_viewer.html(via Load Compiled JSON) or audit withpython simline_validator.py <exported>.json.
Provide a tutorial for adding a timeline
Adding a new mission scenario (for example, TL_EVA1_Extended) to SimLine_Lunar_EVA_Simulator.xlsx takes five steps. Because the VBA exporter reads the active sheet name directly from Dashboard!C4, no VBA code changes are required.
Step 1: Duplicate an Existing Timeline Sheet
Right-click the
TL_EVA1_Nominaltab at the bottom of Excel and select Move or Copy...Check Create a copy, place it next to
TL_EVA1_Abort, and click OK.Rename the new tab to your scenario name (e.g.,
TL_EVA1_Extended). Keep the name free of spaces so formulas stay clean.Update the banner title in
A1:A2to describe your new scenario.
Step 2: Author Your Mission Events (Rows 5–39)
Edit the event rows in A5:P39. Do not overwrite the formulas in columns H (Start_MET_Min), I (End_MET_Min), or Q (Validation_Flag).
Clearing unused rows: If your new timeline has fewer than 31 events, clear columns
A:Pon the extra rows (leaving them blank).Chaining events: Set
Trigger_Mode(Col D) toATfor absolute timestamps (entered inOffset_Min, Col F), orAFTERto chain off any priorBlock_ID(entered inRef_Block_ID, Col E).Adding new assets or waypoints: If your scenario needs a new location or asset, add it to
Scene_World(below row 18) orAssets(below row 10) first, then expand theINDEX/MATCHranges if you go beyond the existing rows.Verify inline: Check Column Q (
Validation_Flag)—every active row should turn green (OK). Any redERR:flag indicates a speed limit, static asset, or comm blackout violation.
Step 3: Add the New Sheet to the Dashboard Dropdown
Go to the
Dashboardsheet and select cellC4(Active Timeline).On the ribbon, go to Data → Data Validation.
In the Source box, append your new sheet's exact tab name:
TL_EVA1_Nominal,TL_EVA1_Abort,TL_EVA1_ExtendedClick OK.
Step 4: Wire the New Sheet into Sim_Engine
Go to the
Sim_Enginesheet and select cellA5.Replace the existing
IFformula with a nestedIF(works in all Excel versions) orIFS(Excel 2019+/365) that includes your new sheet:=IF(Dashboard!$C$4="TL_EVA1_Nominal", TL_EVA1_Nominal!A5, IF(Dashboard!$C$4="TL_EVA1_Abort", TL_EVA1_Abort!A5, TL_EVA1_Extended!A5))Copy cell
A5across columnsA5:Q5, then fill down throughA39:Q39.Tip: Do not touch columns
R:V—those automatically compute active status, elapsed overlap, and interpolated(X, Y)coordinates fromA5:Q39.
Step 5: Add the Scenario to the Comparison Table (Optional)
If you want your new timeline to appear in the side-by-side Scenario Comparison table:
On
Sim_Engine, copy rowO44:T44down toO45:T45.In
O45, typeTL_EVA1_Extended.Select
P45:T45, pressCtrl + H(Find & Replace), replaceTL_EVA1_AbortwithTL_EVA1_Extended, and click Replace All.On
Dashboard, insert a row below row 18 (or use row 19) and copyA18:G18down so it referencesSim_Engine!O45:T45.
Step 6: Test & Export
Switch
Dashboard!C4toTL_EVA1_Extended.Scrub
Dashboard!C5(or click Play / Pause) to verify the 2D Operations Map, Live Asset Telemetry, and Consumables Profile chart update to your new mission.Click Export JSON to generate a
SimLineTimelinev1.0.0.jsonfile forsimline_viewer.htmlorsimline_validator.py.
From <https://gemini.google.com/app/26be29b0585d5221> Google Gemini (4 Neon)

Comments
Post a Comment