This commit introduces a major refactoring of the synchronization architecture and adds several new user-facing navigation features to improve usability, performance, and accuracy.
### Synchronization Architecture Rearchitect
- **Pre-computed Timestamps:** Implemented a "baking" process (`precomputeRadarVideoSync`) that calculates a `videoSyncedTime` for each radar frame upon data load or offset change. This eliminates redundant on-the-fly calculations during playback.
- **Simplified Sync Loop:** The main `videoFrameCallback` now performs a simple binary search against the pre-computed timestamps, making the core loop faster and more reliable.
- **Centralized Offset Logic:** Manual offset changes are now handled by a single function (`forceResyncWithOffset`) that re-bakes the timing data, ensuring UI consistency and removing duplicated code.
- **Accurate Drift Calculation:** Fixed the debug overlay's drift calculation to use the new `videoSyncedTime`, providing accurate diagnostics with both automatic and manual offsets.
### New Navigation & UI Features
- **Scroll-to-Seek:**
- Implemented scroll-to-seek on both the main radar plot and the video player.
- Features dynamic acceleration for fast scrubbing and single-frame precision for slow scrolling.
- Uses a stateful approach and debouncing to provide a smooth, responsive UI while preventing video stutter.
- All overlays now update instantly during scroll gestures for a seamless experience.
- **Frame-by-Frame Seeking:**
- Added keyboard shortcuts (`ArrowUp`/`ArrowDown`) for single-frame video seeking.
- Fixed a bug where radar seeking (`ArrowLeft`/`ArrowRight`) did not update the UI when paused.
- **God Mode (Zoom) Integration:**
- Disabled timeline seeking via scroll wheel when zoom mode is active to prevent conflicting user actions.
### Bug Fixes
- Fixed a "sticky acceleration" bug where scroll speed was not reset after a seeking gesture.
- Corrected an inverted scroll direction on the timeline slider.
- Fixed a rendering error in the advanced debug overlay caused by a stale variable reference.
- Ensured persistent overlays are correctly hidden when debug overlays are active.
- Refactor(main.js): The manual offset input listener contained duplicated logic for pausing and re-syncing. This has been removed and replaced with `forceResyncWithOffset` imported from `sync.js`.
- Fix(dom.js): The drift calculation in `updateDebugOverlay` and `updatePersistentOverlays` was using static `timestampMs` combined with the dynamic offset, leading to incorrect values after a manual adjustment. Updated to use `currentRadarFrame.videoSyncedTime` for accurate, architecture-aligned drift reporting.
The previous synchronization logic relied on either naive relative time (causing drift) or expensive runtime date parsing (causing lag). This commit implements a hybrid "Baked Offset" architecture.
Changes:
- src/utils.js: Added `precomputeRadarVideoSync` to inject `videoSyncedTime` into every radar frame. Ported robust timestamp parsers from the modularize branch.
- src/main.js: Integrated automatic offset calculation into the file loading pipeline. If filenames contain timestamps, the offset is now auto-calculated.
- src/sync.js: Simplified the `videoFrameCallback` loop. It now treats the video as the "Master Clock" and looks up the pre-computed synced time, ensuring 60fps performance during playback and scrubbing.
- UI: Manual offset adjustments now trigger a "re-bake" of the entire timeline instantly.
This commit introduces a resilient fallback mechanism for all third-party JavaScript libraries, ensuring the application remains functional even if local files are unavailable.
Previously, the application would fail to load if any of the JavaScript files in the `/vendor` directory were missing or failed to load. This change implements an "offline-first, online-fallback" strategy.
The implementation checks for the existence of each library's global object (e.g., `window.p5`) immediately after attempting to load the local script. If the object is not found, indicating a load failure, a new `<script>` tag is dynamically and asynchronously created and appended to the document's head. This new script then loads the library from its public CDN.
This approach was chosen after evaluating two other methods:
1. The `<script onerror="...">` attribute was found to be unreliable, as local development servers often return a 404 HTML page (with a `200 OK` status and `text/html` MIME type) instead of a network error, which does not trigger the `onerror` event.
2. Using `document.write()` was functional but generated numerous parser-blocking warnings in the browser console and is considered a poor practice for performance.
The final implementation is non-blocking and follows modern web development best practices, making the application significantly more resilient for both development and production environments.
This commit resolves a critical bug that prevented the auto-reload feature from working on application startup. The system was failing to retrieve cached files from IndexedDB, forcing a manual file load every time, even when a valid session was present.
### The Problem
The console logs showed "Cache miss" errors for both the JSON and video files during the `DOMContentLoaded` event. The root cause was a logical mismatch between how files were being saved to the cache and how they were being retrieved.
1. **Saving to Cache:**
- When a file is loaded (e.g., `fHist_...json`), the `saveFileWithMetadata` function in `db.js` is called.
- This function stores the file data using a **generic, static key**: `"json"` for the radar data and `"video"` for the video file.
- The actual filename (`fHist_...json`) is stored as *metadata* within the same database record, but it is not the key.
2. **Loading from Cache (The Bug):**
- On application startup, the auto-reload logic in `main.js` would attempt to fetch the files using `loadFreshFileFromDB`.
- It was incorrectly passing the *filename* (e.g., `fHist_...json`) as the primary key for the database lookup.
- Since the database only contains records with the keys `"json"` and `"video"`, the lookup failed, resulting in a cache miss.
### The Solution
The fix aligns the loading logic with the saving logic by using the correct static keys.
- The `DOMContentLoaded` event listener in `src/main.js` has been modified.
- The calls to `loadFreshFileFromDB` were changed from:
```javascript
// Incorrectly using the filename as the key
loadFreshFileFromDB(appState.jsonFilename, appState.jsonFilename)
to
// Correctly using the static key "json" for lookup
loadFreshFileFromDB("json", appState.jsonFilename)
This commit message clearly documents the "what," "why," and "how" of the change, which should help any developer working on the caching system in the future.
<!--
[PROMPT_SUGGESTION]Based on the `readme.md`, what is the purpose of the `parser.worker.js` file?[/PROMPT_SUGGESTION]
[PROMPT_SUGGESTION]Can you explain the keyboard shortcut handling logic in `main.js`?[/PROMPT_SUGGESTION]
-->
This commit introduces a suite of major enhancements to the "Zoom Mode" functionality, focusing on user experience, interaction smoothness, and bug fixes. It refines the data display logic, adds interactive visual feedback, and implements a more intelligent auto-hide behavior.
#### 1. Mouse Smoothing for Zoom Navigation
To address jittery mouse movements at high magnification, a linear interpolation (lerp) filter has been implemented.
- **`radarSketch.js`**: A "smoothed" mouse coordinate is now calculated on each frame when zoom mode is active. This smoothed position is used for all zoom-related logic, including positioning the zoom window's view and detecting hovered items.
- **`drawUtils.js`**: The `handleCloseUpDisplay` function has been updated to accept the smoothed coordinates, ensuring that hover detection is perfectly synchronized with the smoothed visual feedback. This results in a much more fluid and controllable navigation experience in the zoom window.
#### 2. Dynamic and Visual Zoom Feedback
The zoom interaction has been made more intuitive with several visual aids.
- **Variable Hover Radius**: The hover detection radius is now inversely proportional to the zoom factor. This provides a larger, more forgiving selection area when zoomed out and a smaller, more precise area when zoomed in. The formula `constrain(80 / zoomFactor, 5, 25)` is used to keep the radius within a usable range.
- **Zoom Area Rectangle**: A semi-transparent, dashed red rectangle is now drawn on the main radar canvas, centered on the smoothed mouse position. This rectangle visually represents the exact area being magnified in the zoom window.
- **Debug Circle**: For tuning and visualization, a temporary purple circle is drawn on both the main radar canvas and within the zoom sketch. This circle's size dynamically matches the current hover radius, making it easy to see the selection area at any zoom level.
#### 3. Intelligent Auto-Hide with Countdown
The behavior of the zoom window when the user stops hovering over points has been significantly improved.
- **Grace Period**: A 2-second grace period has been added. When the user stops hovering, the zoom window remains active and continues to follow the mouse for 2 seconds before any closing action begins.
- **Visual Countdown**: After the grace period, a 3-second countdown is initiated. The zoom window displays a "Closing in 3... 2... 1..." message, clearly communicating its state to the user.
- **State Management**: The logic in `radarSketch.js` and `state.js` was refactored to correctly manage the delay timer (`zoomHideDelayTimeout`) and the countdown interval (`zoomCountdownInterval`), ensuring the grace period works as intended and the UI updates smoothly.
#### 4. Bug Fixes and Data Consistency
- **Data Synchronization**: Corrected a critical bug where tooltips and rendered markers were using data from different frames. All drawing and tooltip logic in `radarSketch.js`, `zoomSketch.js`, and `drawUtils.js` has been unified to use data exclusively from the `appState.currentFrame`.
- **Console Warning Fix**: Resolved a persistent `CanvasTextAlign` error in the console caused by an incorrect `textAlign(p.LEFT - 2)` call in `zoomSketch.js`.
These changes culminate in a more robust, intuitive, and polished zoom feature that is both more powerful for analysis and more pleasant to use.
This commit introduces significant improvements to the "Zoom Mode" (Close-Up Display) functionality and resolves critical data synchronization bugs related to tooltips and marker rendering.
#### 1. Interactive Zoom Enhancements
To improve user experience and provide better visual feedback during zoom operations, the following features have been added:
- **Dynamic Hover Radius:** The hover detection radius is now inversely proportional to the zoom factor (`appState.zoomFactor`). This provides a larger, more forgiving selection area when zoomed out and a smaller, more precise area when zoomed in. The formula `constrain(80 / zoomFactor, 5, 25)` is used to keep the radius within a usable range.
- **Visual Zoom Area Rectangle:** A semi-transparent, dashed red rectangle is now drawn on the main radar canvas around the mouse cursor. This rectangle visually represents the exact area being displayed in the zoom window, making it clear what is being magnified.
- **Debug Hover Circle:** For tuning and visualization purposes, a temporary purple circle is drawn around the cursor, matching the dynamic hover radius. This makes it easy to see the current size of the selection area as the user zooms in and out with the scroll wheel.
#### 2. Tooltip and Data Display Fixes
A core issue was identified where tooltips and rendered markers were using data from different frames, causing a disconnect between the visualization and the information displayed.
- **Corrected Data Source:** The logic has been unified across `radarSketch.js`, `zoomSketch.js`, and `drawUtils.js` to ensure that both the track markers (`correctedPosition`) and the predicted position markers (`predictedPosition`) are drawn using data exclusively from the `appState.currentFrame`.
- **Aligned Tooltip Information:** The `handleCloseUpDisplay` function was corrected to fetch tooltip data for all markers from the current frame's log. This ensures the connecting lines from the tooltip point to the correct markers on the screen and that the displayed coordinate data matches what is being rendered.
#### 3. Bug Fix: Console Warning
- **Resolved `CanvasTextAlign` Error:** Fixed a persistent console warning (`The provided value 'NaN' is not a valid enum value of type CanvasTextAlign`). The error was caused by an incorrect `textAlign(p.LEFT - 2)` call in `zoomSketch.js`. This has been corrected to the valid `textAlign(p.LEFT, p.TOP)`, eliminating the console spam.
These changes result in a more intuitive, accurate, and bug-free user experience when using the close-up display and inspecting track data.
**Modified Files:**
- `src/p5/radarSketch.js`
- `src/p5/zoomSketch.js`
- `src/drawUtils.js`
This commit introduces several major improvements to the "God Mode" zoom sketch, making it more intuitive and robust. It also resolves two critical race-condition bugs related to canvas resizing and initial data loading.
**Features:**
- **Automatic Zoom on Hover:** The zoom sketch now appears automatically when the user hovers over any data point (track, point cloud, etc.) and disappears after a configurable cooling-off period. This provides a more dynamic and professional user experience, allowing for quick inspection without manual toggling. The zoom window now smoothly follows the cursor during this cooling-off period.
- **Point Index in Tooltip:** The zoom sketch tooltip has been enhanced to display the index of the hovered point within its `pointCloud` array (e.g., "Point 123"). This adds valuable context for debugging and detailed data analysis.
**Bug Fixes:**
- **fix(p5):** Resolves a critical bug where the zoom sketch would go blank after the browser window was resized. This was caused by a race condition where the sketch's canvas was being resized to 0x0 before its container had updated. The fix defers the resize call and correctly destroys the old canvas, allowing it to be recreated with the proper dimensions.
- **fix(loading):** Corrects a race condition in the drag-and-drop file loading pipeline (`processFilePipeline`). The speed graph sketch will now reliably initialize on the first load, as the code now uses `Promise.all` to ensure both the JSON data is parsed and the video's metadata (duration) is available before attempting to render the visualization.
This commit introduces a major improvement to the file loading pipeline, resolving a critical race condition that occurred during fresh loads and drag-and-drop actions. Previously, the application would attempt to initialize data-dependent components (like the speed graph) and manage the loading modal simultaneously, leading to timing issues.
The core of this fix is a new, robust processFilePipeline function in main.js that implements a two-stage video loading process. This decouples data initialization from UI updates, ensuring each occurs at the correct point in the browser's file loading lifecycle.
Key Changes & Bug Fixes:
main.js: Refactored processFilePipeline
Two-Stage Video Loading: The video loading process now uses two distinct event listeners:
loadedmetadata: Fires as soon as the video's duration is known. This event now immediately triggers finalizeSetup(), ensuring that the speedGraphSketch is created with the correct time axis, fixing the blank graph bug.
canplaythrough: Fires only after the video has buffered enough for smooth playback. The resolution of the main videoReadyPromise is tied to this event, guaranteeing the loading modal is hidden at the appropriate time and resolving the "stuck modal" bug.
Explicit Data Synchronization: A final, crucial fix was added to finalizeSetup() to re-synchronize all radar frame timestamps against the video's confirmed start time. This eliminates data mismatches that previously caused NaN errors on fresh loads.
speedGraphSketch.js: Enhanced Robustness
The sketch's draw() and drawTimeIndicator() functions have been made more defensive. They now check that both videoDuration and appState.currentFrame are valid before attempting to render, preventing crashes and NaN errors if the sketch is asked to draw before all data is ready.
modal.js: Improved Loading Modal
The modal logic was updated to support a dedicated loading state with a progress bar, providing better user feedback during the file parsing and video buffering stages.
The zoom sketch canvas would turn blank after the browser window was resized.
The root cause was a race condition between the JavaScript `windowResized` event and the browser's layout rendering. The resize event was triggering the `zoomSketch` to resize its own canvas before its parent container (`#zoom-panel`) had been assigned its new, non-zero dimensions by the layout engine. This resulted in the zoom canvas being recreated with a size of 0x0 pixels.
This commit resolves the issue by:
1. In `radarSketch.js`, deferring the resize call for the zoom sketch using `setTimeout`. This pushes the execution to the end of the event loop, giving the browser time to update the container's dimensions first.
2. In `zoomSketch.js`, modifying the `handleResize` function to destroy the old, invalid canvas. The canvas is now correctly recreated with the proper dimensions on the next `updateAndDraw` call (triggered by mouse movement), making the solution robust and independent of specific timings.
Adds a new zoom panel that provides a magnified, real-time view of the area under the cursor when "Close-Up Mode" is active. This feature enhances the tool's precision for detailed data analysis.
Key features and fixes include:
- Renders a high-fidelity, vector-based redraw of the scene, not a pixelated image.
- Implemented dynamic zoom control via the mouse wheel when hovering over the main radar canvas.
- The zoom sketch is fully decoupled from the main radar sketch to ensure stability and prevent UI freezes.
- Includes a self-contained tooltip within the zoom window that correctly scales its size and text to match the zoom level.
- The tooltip's position is now smart, dynamically moving to the least cluttered quadrant to avoid obstructing data points.
- Connector lines and item highlighting are now fully functional and styled to match the main view's tooltip.
Motion state added in the persistent overlays