Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,16 @@ def render_refresh_callback(self):
self.gamestate.render_arrays.rebuild_from_objects(self.gamestate.all_objects)

# Update the cached render arrays in sensor tracks
self._tracks.render_arrays = self.gamestate.render_arrays.get_render_data()
self._tracks.update()

# Regenerate display data with updated arrays
self._display_data.generate_render_arrays()
self._display_data.generate_render_arrays(self._radar_interval_active())
self._display_data.refresh_configuration()

@staticmethod
def _radar_interval_active() -> bool:
return config.app_config.get_float("radar", "update_interval") > 0.0

def handle_window_moved(self, window, xpos, ypos):
config.app_config.set("window", "location", (xpos, ypos))

Expand Down Expand Up @@ -333,7 +337,7 @@ def on_loop(self, delta_time):
float): #TODO implement in sensor_tracks
self.radar_sleep = 0
self._tracks.update()
self._display_data.generate_render_arrays()
self._display_data.generate_render_arrays(self._radar_interval_active())
self._ImguiUI.update()
self._ImguiUI.fps = self.clock.fps
self._ImguiUI.frame_time = self.gpu_frame_time_us
Expand Down
43 changes: 27 additions & 16 deletions src/display_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,26 @@ def __init__(self, scene: Scene, gamestate: GameState, tracks: SensorTracks):
# self.labels_renderer: RadarLabelsRenderer = RadarLabelsRenderer(self.scene)
self.labels_renderer: ImGuiRadarLabelsRenderer = ImGuiRadarLabelsRenderer(self.scene)

def generate_render_arrays(self):
def generate_render_arrays(self, freeze_label_data: bool = False):
"""
Generate the instance arrays for rendering. called
Generate the instance arrays for rendering. Called on each radar update.

Args:
freeze_label_data: Keep label data as of this update until the next one
(used when the radar update interval is longer than a frame).
"""
self._load_track_arrays()

# Update bullseye if enabled and position available
if config.app_config.get_bool("layers", "show_bullseye"):
bullseye_pos = self.gamestate.get_bullseye_pos()
if bullseye_pos != (0, 0): # Valid bullseye position
self.bullseye_renderer.set_bullseye(bullseye_pos[0], bullseye_pos[1])

# Snapshot track labels; they are laid out against the current view every frame
self.labels_renderer.take_snapshot(self.gamestate, freeze_label_data)

def _load_track_arrays(self):
render_arrays = self.sensor_tracks.render_arrays

if render_arrays:
Expand All @@ -46,15 +62,13 @@ def generate_render_arrays(self):
lock_lines = render_arrays.get('lock_lines')
self.lock_renderer.load_render_arrays(lock_lines)

# Update bullseye if enabled and position available
if config.app_config.get_bool("layers", "show_bullseye"):
bullseye_pos = self.gamestate.get_bullseye_pos()
if bullseye_pos != (0, 0): # Valid bullseye position
self.bullseye_renderer.set_bullseye(bullseye_pos[0], bullseye_pos[1])

# Clear and regenerate track labels
self.labels_renderer.clear()
self._generate_ac_labels()
def refresh_object_style(self, game_obj: GameObject):
"""
Apply a user edit to one object (e.g. color override) immediately, rather than
waiting for the next radar update. Labels already re-layout every frame.
"""
if self.sensor_tracks.refresh_object_style(game_obj):
self._load_track_arrays()

def set_hovered_obj(self, track: Optional[GameObject]):
"""
Expand All @@ -65,10 +79,6 @@ def set_hovered_obj(self, track: Optional[GameObject]):
"""
self.labels_renderer.set_hovered_obj(track)

def _generate_ac_labels(self):
"""Generate text labels for all visible tracks."""
self.labels_renderer.draw_all_ac_labels(self.gamestate)

def render(self):
"""
Render the display data.
Expand All @@ -89,7 +99,8 @@ def render(self):
# Render velocity vectors using the new vector renderer
self.vector_renderer.render()

# Render all track labels
# Render all track labels, re-projected against the current view every frame
self.labels_renderer.layout_labels()
self.labels_renderer.render()

def clear(self):
Expand Down
78 changes: 67 additions & 11 deletions src/draw/imgui_radar_labels_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
- Integration with the existing dockspace window
"""

import copy
import numpy as np
from typing import Dict, Optional, Tuple, Any
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass
import hashlib

Expand All @@ -24,6 +25,11 @@

import config

# GameObject attributes set by the user/UI rather than by radar data. These are copied from
# the live object onto frozen snapshot copies so edits (e.g. a callsign change) show at once.
_USER_DRIVEN_FIELDS = ("override_name", "override_color", "side_override_color", "bull_x", "bull_y",
"magnetic_variation")

# Per-anchor-location offset formula, as (offset_x_sign, text_width_coef, offset_y_sign, text_height_coef):
# dx = offset_x_sign * offset + text_width_coef * text_width
# dy = offset_y_sign * offset + text_height_coef * text_height
Expand Down Expand Up @@ -80,6 +86,10 @@ def __init__(self, scene: Scene):
# Cache for text labels - keyed by object_id + location
self._text_cache: Dict[str, CachedTextLabel] = {}

# Objects captured at the last radar update, per type:
# (object_type, live objects, objects used for label text, world positions)
self._snapshot: List[Tuple[Any, List[GameObject], List[GameObject], np.ndarray]] = []

# Track the currently hovered game object for special rendering
self._hovered_object: GameObject | None = None

Expand All @@ -94,8 +104,9 @@ def __init__(self, scene: Scene):
| imgui.WindowFlags_.no_focus_on_appearing.value | imgui.WindowFlags_.no_inputs.value)

def clear(self):
"""Clear the text cache to force regeneration of all labels."""
"""Clear the text cache and snapshot to force regeneration of all labels."""
self._text_cache.clear()
self._snapshot = []

def set_hovered_obj(self, obj: GameObject | None):
"""
Expand Down Expand Up @@ -238,23 +249,67 @@ def _is_on_screen(self, screen_x: float, screen_y: float) -> bool:
0 <= screen_y <= height
)

def draw_all_ac_labels(self, gamestate: GameState):
def draw_all_ac_labels(self, gamestate: GameState, freeze_objects: bool = False):
"""
Draw labels for every visible object type in the game state.
Snapshot the game state and lay out labels for every visible object type.

Args:
gamestate: Current game state containing all objects
freeze_objects: See take_snapshot
"""
self.take_snapshot(gamestate, freeze_objects)
self.layout_labels()

def take_snapshot(self, gamestate: GameState, freeze_objects: bool = False):
"""
Capture object positions (and optionally label data) at a radar update.

Labels are laid out from this snapshot every frame by layout_labels, so they
follow pan/zoom and user edits immediately while their position and data only
advance on radar updates.

Args:
gamestate: Current game state containing all objects
freeze_objects: Copy objects so label data (altitude, speed, ...) stays as it
was at this update. Unnecessary when snapshots are taken every frame.
"""
self._snapshot = []
for object_type, objects_by_id in gamestate.objects.items():
if not objects_by_id:
continue

live_objs = list(objects_by_id.values())
world_positions = np.array([(obj.U, obj.V) for obj in live_objs], dtype=np.float64)

# Only types with labels need frozen copies
labels = get_labels_for_class_type(object_type)
if freeze_objects and labels is not None and labels.labels:
label_objs = [copy.copy(obj) for obj in live_objs]
else:
label_objs = live_objs

self._snapshot.append((object_type, live_objs, label_objs, world_positions))

@staticmethod
def _sync_user_fields(frozen: GameObject, live: GameObject):
"""Carry user/UI-driven state from the live object onto a frozen snapshot copy."""
for field in _USER_DRIVEN_FIELDS:
setattr(frozen, field, getattr(live, field))

def layout_labels(self):
"""
Regenerate all label text and screen positions from the last snapshot using the
current camera, label configuration and hover state.
"""
self._text_cache.clear()

# Get offset for positioning labels relative to track icons
offset = config.app_config.get_int("radar", "contact_size")
label_padding = config.app_config.get_int("radar", "contact_label_padding")
total_offset = offset + label_padding
font_scale = config.app_config.get_float("radar", "contact_font_scale") / 100.0 # Convert to ImGui scale

for object_type, objects_by_id in gamestate.objects.items():
if not objects_by_id:
continue

for object_type, live_objs, label_objs, world_positions in self._snapshot:
# Respect the layer visibility toggle for this type, if it has one
layer_key = get_layer_key(object_type)
if layer_key is not None and not config.app_config.get_bool("layers", layer_key):
Expand All @@ -265,13 +320,14 @@ def draw_all_ac_labels(self, gamestate: GameState):
if labels is None or not labels.labels:
continue

objs = list(objects_by_id.values())
world_positions = np.array([(obj.U, obj.V) for obj in objs], dtype=np.float64)
frozen = label_objs is not live_objs
screen_positions = self.scene.world_to_screen_batch(world_positions).tolist()

for obj, (screen_x, screen_y) in zip(objs, screen_positions):
for live_obj, obj, (screen_x, screen_y) in zip(live_objs, label_objs, screen_positions):
if not self._is_on_screen(screen_x, screen_y):
continue
if frozen:
self._sync_user_fields(obj, live_obj)
self.draw_track_labels(obj, labels, total_offset, font_scale, screen_x, screen_y)

def draw_custom_text(self,
Expand Down
59 changes: 59 additions & 0 deletions src/sensor_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ def __init__(self, gamestate: GameState):
# self.tracks: dict[GameObjectType, dict[str, Track]] = {class_type: {} for class_type in GameObjectType}
self.cur_time: datetime.datetime | None = None
self.track_inactivity_timeout_sec = 10
self.render_arrays: dict | None = None
self._icon_index_maps: dict = {}
self._vector_index_map: dict[str, int] = {}
self._lock_index_map: dict[str, int] = {}

self.update_bullseye()

Expand Down Expand Up @@ -158,6 +162,7 @@ def update(self):
) # Only updates the current time when tracks are updated, this may be undeseirable

self.render_arrays = self.gamestate.render_arrays.get_render_data()
self._snapshot_index_maps()

# for classenum, object_class_dict in self.gamestate.objects.items():

Expand Down Expand Up @@ -195,6 +200,60 @@ def update(self):
# for id in to_delete:
# del self.tracks[classenum][id]

def _snapshot_index_maps(self):
"""Record which row each object occupies in the snapshotted render arrays."""
live = self.gamestate.render_arrays
self._icon_index_maps = {shape: dict(icon_data.id_to_index) for shape, icon_data in live.icon_data.items()}
self._vector_index_map = dict(live.velocity_vectors.id_to_index)
self._lock_index_map = dict(live.lock_lines.id_to_index)

def refresh_object_style(self, game_obj) -> bool:
"""
Apply a user-driven style change (e.g. color override) for one object to the
snapshotted render arrays immediately, without waiting for the next radar update.
Position and other track data are left as they were at the last radar update.

Returns:
True if any snapshotted array was modified.
"""
if not self.render_arrays:
return False

live = self.gamestate.render_arrays
live.update_object(game_obj)
object_id = game_obj.object_id
changed = False

icons = self.render_arrays.get('icons', {})
for shape, snap_index_map in self._icon_index_maps.items():
snap_idx = snap_index_map.get(object_id)
live_idx = live.icon_data[shape].id_to_index.get(object_id)
snap_array = icons.get(shape)
if snap_idx is None or live_idx is None or snap_array is None:
continue
snap_array[snap_idx]['color'] = live.icon_data[shape].data[live_idx]['color']
changed = True

vectors = self.render_arrays.get('velocity_vectors')
snap_idx = self._vector_index_map.get(object_id)
live_idx = live.velocity_vectors.id_to_index.get(object_id)
if vectors is not None and snap_idx is not None and live_idx is not None:
vectors[snap_idx]['color'] = live.velocity_vectors.data[live_idx]['color']
changed = True

lock_lines = self.render_arrays.get('lock_lines')
if lock_lines is not None:
prefix = f"{object_id}:"
for lock_pair, snap_idx in self._lock_index_map.items():
if not lock_pair.startswith(prefix):
continue
live_idx = live.lock_lines.id_to_index.get(lock_pair)
if live_idx is not None:
lock_lines[snap_idx]['color'] = live.lock_lines.data[live_idx]['color']
changed = True

return changed

def clear(self):
"""
Clear all tracks.
Expand Down
4 changes: 4 additions & 0 deletions src/ui/imgui_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ def contact_color_window(self):
if changed:
self.current_contact_color = list(new_color)
obj.override_color = tuple(new_color) # type: ignore
self.display_data.refresh_object_style(obj)

imgui.separator()

Expand All @@ -663,6 +664,7 @@ def contact_color_window(self):
imgui.ColorEditFlags_.no_border.value, imgui.ImVec2(30, 30)):
self.current_contact_color = list(coalition_color)
obj.override_color = tuple(coalition_color) # type: ignore
self.display_data.refresh_object_style(obj)

# Tooltip with color name
if imgui.is_item_hovered():
Expand All @@ -684,6 +686,7 @@ def contact_color_window(self):
imgui.ImVec2(30, 30)):
self.current_contact_color = list(custom_color)
obj.override_color = tuple(custom_color) # type: ignore
self.display_data.refresh_object_style(obj)

imgui.separator()

Expand All @@ -699,6 +702,7 @@ def contact_color_window(self):
if imgui.button("Reset", imgui.ImVec2(80, 0)):
# Reset to original color (remove override)
obj.override_color = None
self.display_data.refresh_object_style(obj)
self.contact_color_window_open = False

imgui.same_line()
Expand Down