Merge pull request #11 from bleackstorm/feat/steamframe-gaming-vr-mode

Feat/steamframe gaming vr mode
This commit is contained in:
bleackstorm authored and GitHub committed 2026-11-25 21:48:16 +01:00
commit 8028680f07
21 files changed
+1983 -3783

No files matched your search

Generated
+55 -1759
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -2,14 +2,13 @@
name = "steamframe-fpv"
version = "0.3.0"
edition = "2021"
description = "Application graphique et VR native Steam Frame (OpenXR + Vulkan + egui) pour Eachine Sphere Link (USB RNDIS) et Head-Tracking RadioMaster Nomad (ELRS Wi-Fi)"
description = "Application graphique et VR native Steam Frame (OpenXR + Vulkan + GPUI) pour Eachine Sphere Link (USB RNDIS) et Head-Tracking RadioMaster Nomad (ELRS Wi-Fi)"
[dependencies]
anyhow = "1.0"
ash = "0.38"
chrono = "0.4"
clap = { version = "4.5", features = ["derive"] }
eframe = { version = "0.29", default-features = true }
glam = "0.29"
gpui = "0.2.2"
gstreamer = "0.23"
+7 -4
View File
@@ -33,12 +33,15 @@ Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rus
## Interfaces Graphiques & Mode CLI
1. **GPUI (`--gui-engine gpui`, par défaut)** (`src/gui_gpui.rs`) : Interface GPU-accélérée organisée en 4 onglets :
1. **GPUI (Interface unique GPU-accélérée)** (`src/gui_gpui.rs`) : Interface GPU-accélérée organisée en 4 onglets :
- **`📹 Cockpit`** : Retour vidéo plein écran + bandeau HUD flottant activable/désactivable.
- **`⚙️ Réglages`** : Configuration VRX/UVC, presets réseau Nomad, édition IP/Port, **Mock Manuel Pan/Tilt/Roll** (envoi unitaire ou continu 50 Hz), projection VR et DVR.
- **`⚙️ Réglages`** : Configuration VRX/UVC, presets réseau Nomad, édition IP/Port, **Mock Manuel Pan/Tilt/Roll** (envoi unitaire ou continu 50 Hz), projection VR & optique temps réel, vitesses CRSF et DVR.
- **`📊 Télémétrie`** : Jauges CRSF Pan/Tilt/Roll et métriques de vol/lien radio.
- **`📜 Logs`** : Console filtrable (`Tous`, `Warn / Erreurs`, `Erreurs seules`) synchronisée sans verrou avec `steamframe_fpv.log`.
2. **egui (`--gui-engine egui`)** (`src/gui.rs`) : Interface de contrôle classique complète (sliders optiques temps réel, simulation manuelle, sélecteurs UVC/RNDIS, journal diagnostic).
2. **Menu Minimaliste VR dans le casque (OpenXR / Mode Gaming `--vr-only`)** :
- Lancez `./launch_vr.sh` (ou ajoutez `steamframe-fpv-vr.desktop` en jeu non-Steam en Mode Gaming) pour démarrer directement en immersion OpenXR sans fenêtre 2D.
- Ouverture via `Options`/`L3` (G29), `View`/`Select` (Steam Controller) ou `Menu`/`Y` (contrôleurs VR OpenXR natifs).
- Menu principal compact (`Source`, `Tare HT`, `Projection`, `Distance`, `OSD`, `DVR`, `Avancé >`, `Quitter l'App` avec double confirmation) + sous-menu Avancé (`Suivi tête`, `k1`, `FOV`, `Plafond 3e vitesse`, `Vibrations SC`, `Canal Radxa 5.8 GHz`).
3. **Mode Ligne de Commande (`--no-gui`)** : Exécution sans fenêtre graphique pour bancs de test ou usage embarqué.
---
@@ -95,7 +98,7 @@ Le script [launch.sh](launch.sh) prépare `libxkbcommon-x11.so` si besoin, compi
| Option | Défaut | Description |
| --- | --- | --- |
| `--gui-engine` | `gpui` | Moteur IHM : `gpui` ou `egui` |
| `--vr-only` | `false` | Mode VR natif direct sans fenêtre 2D GPUI (Mode Gaming SteamOS) |
| `--no-gui` | `false` | Lance uniquement le moteur sans IHM |
| `--headless` | `false` | Désactive OpenXR (mode Bureau / test) |
| `--usb-video-mode` | `rndis` | Acquisition vidéo : `rndis` ou `uvc` |
Executable
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# SteamFrame FPV — Lanceur VR Natif (Mode Gaming SteamOS / OpenXR Direct sans fenêtre 2D)
set -e
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd "$DIR"
# Bibliothèques locales éventuelles
if [ -d "$HOME/.local/lib" ]; then
export LD_LIBRARY_PATH="$HOME/.local/lib:${LD_LIBRARY_PATH:-}"
fi
# Compiler en Release si le binaire n'est pas encore présent
if [ ! -f "$DIR/target/release/steamframe-fpv" ]; then
echo "Compilation initiale de SteamFrame FPV en mode Release..."
cargo build --release
fi
exec "$DIR/target/release/steamframe-fpv" --vr-only "$@"
+5 -1
View File
@@ -1,4 +1,8 @@
# Règle Udev pour le récepteur Eachine Sphere Link (Radxa Zero 3W / Rockchip RV1106 / RNDIS)
# Déclenche l'attribution de l'IP 192.168.1.10/24 dès que le câble USB-C est branché sur le Steam Frame ou PC
ACTION=="add", SUBSYSTEM=="net", KERNEL=="usb*|enx*", ATTRS{idVendor}=="1d6b|2207|0525", RUN+="/usr/bin/ip addr add 192.168.1.10/24 dev %k", RUN+="/usr/bin/ip link set dev %k up"
# Accès HIDRAW non-root (uaccess) pour le Steam Controller (Ibex 28de:1302..1305) en Mode Gaming SteamOS
# Permet la lecture directe des rapports 0x42 et les retours haptiques 0x80 sans sudo ni conflit Lizard Mode
KERNEL=="hidraw*", ATTRS{idVendor}=="28de", ATTRS{idProduct}=="1302|1303|1304|1305", MODE="0660", TAG+="uaccess"
SUBSYSTEM=="hidraw", ATTRS{idVendor}=="28de", ATTRS{idProduct}=="1302|1303|1304|1305", MODE="0660", TAG+="uaccess"
+12 -4
View File
@@ -25,12 +25,20 @@ if [ "$ARCH" = "aarch64" ]; then
export RUSTFLAGS="-C target-cpu=native -C opt-level=3"
cargo build --release
echo "[3/3] Installation locale du lanceur .desktop..."
echo "[3/3] Installation locale des lanceurs .desktop (Bureau GPUI + Mode VR Gaming)..."
mkdir -p ~/.local/share/applications
cp steamframe-fpv.desktop ~/.local/share/applications/
sed -i "s|/home/deck/projects/steamframe_fpv|$DIR|g" ~/.local/share/applications/steamframe-fpv.desktop
chmod +x "$DIR/launch.sh" "$DIR/launch_vr.sh"
for desktop_file in steamframe-fpv.desktop steamframe-fpv-vr.desktop; do
cp "$desktop_file" ~/.local/share/applications/
sed -i -E \
-e "s|^Exec=.*/(launch(_vr)?\.sh)|Exec=$DIR/\1|g" \
-e "s|^Path=.*|Path=$DIR|g" \
-e "s|^Icon=.*/assets/|Icon=$DIR/assets/|g" \
"$HOME/.local/share/applications/$desktop_file"
done
echo "=== SUCCÈS : Binaire compilé dans $DIR/target/release/steamframe-fpv ==="
echo " Mode Gaming : ajoutez 'SteamFrame FPV (Mode VR)' (launch_vr.sh) en jeu non-Steam."
else
echo "[!] Exécution sur hôte ${ARCH} (Ubuntu / PC de développement)."
echo "[2/3] Compilation Release hôte standard..."
@@ -39,7 +47,7 @@ else
echo "[3/3] Création de l'archive de déploiement pour le Steam Frame..."
mkdir -p dist
tar --exclude="target" --exclude=".git" -czf dist/steamframe-fpv-deploy.tar.gz \
Cargo.toml Cargo.lock src scripts assets README.md launch.sh steamframe-fpv.desktop
Cargo.toml Cargo.lock src scripts assets README.md launch.sh launch_vr.sh steamframe-fpv.desktop steamframe-fpv-vr.desktop
echo "=== SUCCÈS : Archive de déploiement créée dans $DIR/dist/steamframe-fpv-deploy.tar.gz ==="
echo "Pour déployer sur le casque, lancez : ./scripts/deploy_to_steamframe.sh [ip_steamframe]"
+1 -1
View File
@@ -23,7 +23,7 @@ echo "[2/5] Préparation du paquet de déploiement..."
echo "[3/5] Transfert des fichiers du projet sur le Steam Frame..."
ssh "${TARGET_HOST}" "mkdir -p ~/projects/steamframe_fpv"
scp dist/steamframe-fpv-deploy.tar.gz "${TARGET_HOST}:~/projects/steamframe_fpv/"
ssh "${TARGET_HOST}" "cd ~/projects/steamframe_fpv && tar -xzf steamframe-fpv-deploy.tar.gz && chmod +x scripts/*.sh launch.sh"
ssh "${TARGET_HOST}" "cd ~/projects/steamframe_fpv && tar -xzf steamframe-fpv-deploy.tar.gz && chmod +x scripts/*.sh launch.sh launch_vr.sh"
echo "[4/5] Installation de la règle udev USB RNDIS (auto-attribution 192.168.1.10/24)..."
scp scripts/99-radxa-vrx-rndis.rules "${TARGET_HOST}:/tmp/"
+11 -3
View File
@@ -17,16 +17,21 @@ echo -e "${BLUE}======================================================${NC}"
# 1. Vérification du service Monado
echo -n "Vérification du service Monado... "
STARTED_MONADO=0
if pgrep monado-service >/dev/null 2>&1; then
echo -e "${GREEN}[OK - Monado est actif]${NC}"
else
echo -e "${YELLOW}[Démarrage de Monado en arrière-plan...]${NC}"
./scripts/start_monado_simulated.sh >/dev/null 2>&1 &
tail -f /dev/null | ./scripts/start_monado_simulated.sh >/tmp/monado_test.log 2>&1 &
MONADO_WRAPPER_PID=$!
STARTED_MONADO=1
trap 'if [ "$STARTED_MONADO" -eq 1 ]; then pkill -f monado-service 2>/dev/null || true; kill "$MONADO_WRAPPER_PID" 2>/dev/null || true; fi' EXIT
sleep 2
if pgrep monado-service >/dev/null 2>&1; then
echo -e "${GREEN}[OK - Monado démarré]${NC}"
else
echo -e "${RED}[ERREUR] Impossible de contacter Monado.${NC}"
tail -n 20 /tmp/monado_test.log || true
exit 1
fi
fi
@@ -82,10 +87,13 @@ run_mode_test "dome" "Dôme 140° (Equirect2 avec dé-distorsion)" "--lens-k1 -0
run_mode_test "cylinder" "Cylindre Incurvé 140° (Cylinder layer)" ""
run_mode_test "flat" "Quad Plat Virtuel (Quad layer)" ""
# 4. Test d'initialisation de l'interface graphique GPUI avec OpenXR
# 4. Test du Mode VR Natif (--vr-only, Mode Gaming SteamOS)
run_mode_test "dome" "Mode VR Natif Gaming (--vr-only)" "--vr-only"
# 5. Test d'initialisation de l'interface graphique GPUI avec OpenXR
echo -e "\n${BLUE}--- Étape 2 : Test d'intégration IHM moderne (GPUI + OpenXR) ---${NC}"
gpui_log="/tmp/openxr_test_gpui.log"
timeout 3 ./target/release/steamframe-fpv --gui-engine gpui > "$gpui_log" 2>&1 || true
timeout 3 ./target/release/steamframe-fpv > "$gpui_log" 2>&1 || true
if grep -q "Changement d'état session : FOCUSED" "$gpui_log"; then
echo -e "${GREEN}✔ L'interface GPUI se synchronise et alimente parfaitement la session OpenXR FOCUSED.${NC}"
+4 -4
View File
@@ -140,10 +140,6 @@ pub struct AppConfig {
#[arg(long, default_value_t = false)]
pub head_tracking_enabled: bool,
/// Moteur d'interface graphique : "gpui" (GPU-accéléré moderne Tailwind) ou "egui" (classique)
#[arg(long, default_value = "gpui")]
pub gui_engine: String,
/// Adresse IP du pont unifié G29/Radxa (192.168.1.1) ou du Backpack Wi-Fi Nomad (10.0.0.1)
#[arg(long, default_value = "192.168.1.1")]
pub nomad_ip: String,
@@ -188,6 +184,10 @@ pub struct AppConfig {
#[arg(long, default_value_t = false)]
pub no_gui: bool,
/// Mode VR natif direct sans fenêtre 2D GPUI (idéal pour le Mode Gaming SteamOS sur Steam Frame)
#[arg(long, default_value_t = false)]
pub vr_only: bool,
/// Chemin du fichier journal d'erreurs et de diagnostic
#[arg(long, default_value = "steamframe_fpv.log")]
pub log_file: String,
+74 -2
View File
@@ -1492,6 +1492,35 @@ impl SteamControllerWorker {
let mut last_haptics_tick = Instant::now() - Duration::from_millis(HAPTICS_INTERVAL_MS);
let mut rumble_is_zero = true;
// Garde RAII garantissant l'envoi d'une trame neutre désarmée même en cas de panic! du worker.
struct DisarmOnDrop<'a> {
socket: &'a UdpSocket,
target: SocketAddr,
active_source: &'a AtomicU8,
}
impl Drop for DisarmOnDrop<'_> {
fn drop(&mut self) {
if ControlSource::from_u8(self.active_source.load(Ordering::Acquire))
== ControlSource::SteamController
{
let safe_frame = encode_rc_frame(
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
false,
0,
);
let _ = self.socket.send_to(safe_frame.as_bytes(), self.target);
}
}
}
let _disarm_guard = DisarmOnDrop {
socket: &socket,
target,
active_source: &active_source,
};
// Synchronisation initiale de la source souhaitée et des vitesses auprès de la RP2350
let init_cmd = encode_src_command(last_source);
let _ = socket.send_to(init_cmd.as_bytes(), target);
@@ -1596,6 +1625,26 @@ impl SteamControllerWorker {
gamepad = None;
haptics.reset();
rumble_is_zero = true;
// Sécurité critique (< 5 ms) : envoyer immédiatement 3 trames désarmées avant même
// l'expiration du watchdog 400 ms sur la RP2350.
if desired_source == ControlSource::SteamController {
let safe_frame = encode_rc_frame(
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
CRSF_CHANNEL_MID,
false,
0,
);
for i in 0..3 {
let _ = socket.send_to(safe_frame.as_bytes(), target);
if i < 2 {
thread::sleep(Duration::from_millis(2));
}
}
}
let mut st = state.lock();
st.connected = false;
st.armed = false;
@@ -1864,12 +1913,35 @@ impl SteamControllerWorker {
}
}
}
// Actions Cockpit (identiques au mapping G29)
// Actions Cockpit & Menu Rapide VR (identiques au mapping G29)
BTN_SELECT => {
let open = control.toggle_vr_menu();
st.set_toast(if open { "MENU VR ON" } else { "MENU VR OFF" });
}
BTN_SOUTH if control.is_vr_menu_open() => {
control.vr_menu_activate();
}
BTN_EAST if control.is_vr_menu_open() => {
control.close_vr_menu();
st.set_toast("MENU VR OFF");
}
BTN_DPAD_UP if control.is_vr_menu_open() => {
control.vr_menu_move(-1);
}
BTN_DPAD_DOWN if control.is_vr_menu_open() => {
control.vr_menu_move(1);
}
BTN_DPAD_LEFT if control.is_vr_menu_open() => {
control.vr_menu_adjust(-1);
}
BTN_DPAD_RIGHT if control.is_vr_menu_open() => {
control.vr_menu_adjust(1);
}
BTN_SOUTH | BTN_THUMBR | BTN_MODE => {
control.request_recenter();
st.set_toast("TARE HT OK");
}
BTN_EAST | BTN_SELECT => {
BTN_EAST => {
let now_rec = control.toggle_dvr();
st.set_toast(if now_rec { "DVR REC" } else { "DVR STOP" });
}
+17 -4
View File
@@ -101,13 +101,26 @@ impl DomeWarpLut {
return;
}
// SAFETY: `align_to` / `align_to_mut` découpent proprement les tranches d'octets en préfixe, tranche alignée `u32` et suffixe.
let (src_head, src_u32, src_tail) = unsafe { input_rgba[..expected_bytes].align_to::<u32>() };
let (dst_head, dst_u32, dst_tail) = unsafe { output_rgba[..expected_bytes].align_to_mut::<u32>() };
if src_head.is_empty() && src_tail.is_empty() && dst_head.is_empty() && dst_tail.is_empty() {
// Chemin ultra-rapide 32-bit (1 instruction CPU de copie par pixel RGBA)
for (dst, &src_idx) in dst_u32.iter_mut().zip(self.src_pixel_offsets.iter()) {
*dst = src_u32[src_idx as usize];
if src_head.is_empty()
&& src_tail.is_empty()
&& dst_head.is_empty()
&& dst_tail.is_empty()
&& src_u32.len() >= total_pixels
&& dst_u32.len() >= total_pixels
{
// Chemin ultra-rapide 32-bit sans bounds-check par pixel :
// `DomeWarpLut::new` garantit que tout offset de `src_pixel_offsets` est < `width * height == total_pixels <= src_u32.len()`.
for (dst, &src_idx) in dst_u32[..total_pixels]
.iter_mut()
.zip(self.src_pixel_offsets.iter())
{
debug_assert!((src_idx as usize) < src_u32.len());
// SAFETY: `src_idx < total_pixels <= src_u32.len()` est invariant par construction de `DomeWarpLut::new`.
*dst = unsafe { *src_u32.get_unchecked(src_idx as usize) };
}
} else {
// Repli sécurisé si les tampons ne sont pas alignés sur 32-bit
+9 -4
View File
@@ -9,7 +9,8 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;
/// Format de conteneur d'enregistrement DVR
/// Plafond mémoire de la file `appsrc` DVR (32 Mo) pour empêcher tout OOM si le stockage ralentit.
const DVR_MAX_QUEUE_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DvrContainer {
Mkv,
@@ -104,7 +105,7 @@ impl DvrRecorder {
let muxer = container.muxer_element();
let pipeline_str = format!(
"appsrc name=dvr_src is-live=true format=time do-timestamp=true caps={caps} ! \
"appsrc name=dvr_src is-live=true format=time do-timestamp=true max-bytes={DVR_MAX_QUEUE_BYTES} caps={caps} ! \
{parser} config-interval=-1 ! \
{muxer} ! \
filesink name=dvr_sink sync=false"
@@ -135,7 +136,7 @@ impl DvrRecorder {
let muxer = container.muxer_element();
let pipeline_str = format!(
"appsrc name=dvr_src is-live=true format=time do-timestamp=true \
"appsrc name=dvr_src is-live=true format=time do-timestamp=true max-bytes={DVR_MAX_QUEUE_BYTES} \
caps=video/x-raw,format=RGBA,width={width},height={height},framerate=60/1 ! \
videoconvert ! \
x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60 ! \
@@ -236,11 +237,15 @@ impl DvrRecorder {
self.is_recording.load(Ordering::Relaxed)
}
/// Pousse un buffer GStreamer existant (zéro-copie de pointeur GstBuffer)
/// Pousse un buffer GStreamer existant (zéro-copie de pointeur GstBuffer, avec garde-fou anti-OOM)
pub fn push_buffer(&self, buffer: gst::Buffer) {
if !self.is_recording.load(Ordering::Relaxed) {
return;
}
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
// File saturée (stockage lent) : abandonner la trame plutôt que saturer la RAM en vol.
return;
}
self.bytes_written
.fetch_add(buffer.size() as u64, Ordering::Relaxed);
self.frames_recorded.fetch_add(1, Ordering::Relaxed);
+854 -180
View File
File diff suppressed because it is too large. Load diff
+95 -1
View File
@@ -399,7 +399,56 @@ impl G29BridgeReceiver {
log::info!("[G29 Bridge] Bouton volant reçu : {:?}", btn);
let menu_open = control.map(|c| c.is_vr_menu_open()).unwrap_or(false);
let toast = match btn {
G29ButtonEvent::Options | G29ButtonEvent::L3 => {
if let Some(ctrl) = control {
let open = ctrl.toggle_vr_menu();
Some(if open {
"MENU VR ON".to_string()
} else {
"MENU VR OFF".to_string()
})
} else {
Some("MENU VR".to_string())
}
}
G29ButtonEvent::Cross if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_activate();
}
None
}
G29ButtonEvent::Circle if menu_open => {
if let Some(ctrl) = control {
ctrl.close_vr_menu();
}
Some("MENU VR OFF".to_string())
}
G29ButtonEvent::DpadUp if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(-1);
}
None
}
G29ButtonEvent::DpadDown if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(1);
}
None
}
G29ButtonEvent::DpadLeft if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(-1);
}
None
}
G29ButtonEvent::DpadRight if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(1);
}
None
}
G29ButtonEvent::Cross | G29ButtonEvent::Ps | G29ButtonEvent::R3 => {
if let Some(ctrl) = control {
ctrl.request_recenter();
@@ -462,7 +511,6 @@ impl G29BridgeReceiver {
}
Some("PAN +1".to_string())
}
G29ButtonEvent::Options | G29ButtonEvent::L3 => None,
};
{
@@ -595,4 +643,50 @@ mod tests {
&[]
));
}
#[test]
fn test_vr_menu_g29_navigation() {
let engine = crate::engine::FpvEngineController::new(true, true);
let ctrl = engine.control_handle();
let state = Arc::new(Mutex::new(G29State::default()));
assert!(!ctrl.is_vr_menu_open());
G29BridgeReceiver::process_line("$G29_EVT,BTN=OPTIONS", &state, Some(&ctrl), None);
assert!(ctrl.is_vr_menu_open());
// Descendre 2 fois (0 -> 2 : PROJECTION VR) puis flèche droite (DOME 140 -> CYL 140)
for _ in 0..2 {
G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None);
}
G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_RIGHT", &state, Some(&ctrl), None);
let data = ctrl.vr_menu_render_data().unwrap();
assert_eq!(data.page, crate::telemetry_osd::VrMenuPage::Main);
assert_eq!(data.selected_idx, 2);
assert_eq!(data.projection_label, "CYL 140");
// Entrer dans le sous-menu Avancé (index 6) puis revenir au menu principal avec Circle
for _ in 0..4 {
G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None);
}
G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None);
assert_eq!(
ctrl.vr_menu_render_data().unwrap().page,
crate::telemetry_osd::VrMenuPage::Advanced
);
G29BridgeReceiver::process_line("$G29_EVT,BTN=CIRCLE", &state, Some(&ctrl), None);
assert!(ctrl.is_vr_menu_open());
assert_eq!(
ctrl.vr_menu_render_data().unwrap().page,
crate::telemetry_osd::VrMenuPage::Main
);
// Double confirmation sur Quitter l'App (index 7)
G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None);
G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None);
assert!(!ctrl.is_exit_requested());
assert!(ctrl.vr_menu_render_data().unwrap().quit_confirm_pending);
G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None);
assert!(ctrl.is_exit_requested());
assert!(!ctrl.is_vr_menu_open());
}
}
-1717
View File
File diff suppressed because it is too large. Load diff
+193 -28
View File
@@ -175,6 +175,8 @@ impl SteamFrameGpuiApp {
/// Synchronise l'état IHM avec le moteur FPV en minimisant au maximum la contention des verrous
fn sync_from_engine(&mut self, window: &mut Window) -> bool {
let mut changed = false;
self.controls
.set_preview_active(self.active_tab == ActiveTab::Cockpit);
// 1. Snapshot rapide avec maintien minimal du verrou monitor
let (preview_frame_seq, new_frame_data) = {
@@ -273,11 +275,20 @@ impl SteamFrameGpuiApp {
(mon.preview_frame_seq, frame_data)
}; // Verrou `engine_monitor` immédiatement libéré !
// 2. Conversion BGRA et allocation GPU hors du verrou monitor
// 2. Conversion BGRA vectorisable (u32) et allocation GPU hors du verrou monitor
if let Some((w, h, raw_arc)) = new_frame_data {
let mut raw_buf = (*raw_arc).clone();
for pixel in raw_buf.chunks_exact_mut(4) {
pixel.swap(0, 2);
// SAFETY: `align_to_mut::<u32>` découpe proprement préfixe, tranche u32 alignée et suffixe.
let (head, pixels_u32, tail) = unsafe { raw_buf.align_to_mut::<u32>() };
if head.is_empty() && tail.is_empty() {
for px in pixels_u32 {
let v = *px;
*px = (v & 0xFF00_FF00) | ((v & 0x00FF_0000) >> 16) | ((v & 0x0000_00FF) << 16);
}
} else {
for pixel in raw_buf.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
}
if let Some(img_buf) = RgbaImage::from_raw(w, h, raw_buf) {
let frame = Frame::new(img_buf);
@@ -330,17 +341,19 @@ impl SteamFrameGpuiApp {
.ok()
.and_then(|p| p.parent().map(|d| d.join("scripts/setup_usb_rndis.sh")))
.filter(|p| p.exists())
.unwrap_or_else(|| {
let candidate = std::path::PathBuf::from("scripts/setup_usb_rndis.sh");
if candidate.exists() {
candidate
.or_else(|| {
let installed = std::path::PathBuf::from("/usr/share/steamframe-fpv/scripts/setup_usb_rndis.sh");
if installed.exists() {
Some(installed)
} else {
std::path::PathBuf::from(concat!(
env!("CARGO_MANIFEST_DIR"),
"/scripts/setup_usb_rndis.sh"
))
let local = std::path::PathBuf::from("scripts/setup_usb_rndis.sh");
local.exists().then_some(local)
}
});
let Some(script_path) = script_path else {
log::error!("[USB RNDIS] Script setup_usb_rndis.sh introuvable à côté du binaire ni dans /usr/share/steamframe-fpv/scripts.");
return;
};
std::thread::spawn(move || {
match Command::new("bash").arg(&script_path).output() {
Ok(out) => {
@@ -358,7 +371,13 @@ impl SteamFrameGpuiApp {
fn configure_radxa_ssh(&self) {
let ch = self.cfg.wifi_channel;
let ip = self.cfg.radxa_vrx_ip.clone();
let Ok(ip) = self.cfg.radxa_vrx_ip.trim().parse::<std::net::IpAddr>() else {
log::error!(
"[Radxa Zero 3W] Adresse IP invalide pour SSH : '{}'",
self.cfg.radxa_vrx_ip
);
return;
};
log::info!(
"[Radxa Zero 3W] Configuration du canal 5.8GHz={} sur root@{}...",
ch,
@@ -371,10 +390,12 @@ impl SteamFrameGpuiApp {
std::thread::spawn(move || {
match Command::new("ssh")
.args([
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=2",
"-o",
"StrictHostKeyChecking=no",
"StrictHostKeyChecking=accept-new",
"--",
&format!("root@{}", ip),
&remote_cmd,
@@ -800,6 +821,20 @@ impl SteamFrameGpuiApp {
rgb(COLOR_CYAN),
)),
)
.child(
div()
.id("btn_vr_menu_quick")
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.controls.toggle_vr_menu();
cx.notify();
}))
.child(self.render_toggle_pill(
"📋 Menu VR",
self.controls.is_vr_menu_open(),
rgb(COLOR_ORANGE),
)),
)
.child(
div()
.id("btn_tare_quick")
@@ -2094,24 +2129,66 @@ impl SteamFrameGpuiApp {
}),
)),
))
// Lentille et FOV
// Champ de vision, Lentille k1/k2 et Distance virtuelle (réglables à chaud en VR)
.child(self.render_setting_row(
"Champ de Vision & Optique",
"Optique & Écran VR (Réglage à chaud)",
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(format!(
"FOV : {}° | Lentille : k1={:.2}, k2={:.2}",
self.cfg.camera_fov_deg, self.cfg.lens_k1, self.cfg.lens_k2
.flex()
.flex_col()
.gap_2()
.p_2p5()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.child(self.render_optical_stepper_row(
"opt_fov",
"FOV Caméra",
format!("{:.0}°", self.cfg.camera_fov_deg),
|cfg, step| {
cfg.camera_fov_deg =
(cfg.camera_fov_deg + step * 5.0).clamp(70.0, 180.0);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_k1",
"Distorsion k1",
format!("{:+.2}", self.cfg.lens_k1),
|cfg, step| {
cfg.lens_k1 = (((cfg.lens_k1 + step * 0.02) * 100.0)
.round()
/ 100.0)
.clamp(-0.50, 0.50);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_k2",
"Distorsion k2",
format!("{:+.2}", self.cfg.lens_k2),
|cfg, step| {
cfg.lens_k2 = (((cfg.lens_k2 + step * 0.01) * 100.0)
.round()
/ 100.0)
.clamp(-0.25, 0.25);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_dist",
"Distance Écran",
format!("{:.1} m", self.cfg.screen_distance_m),
|cfg, step| {
cfg.screen_distance_m = (((cfg.screen_distance_m
+ step * 0.2)
* 10.0)
.round()
/ 10.0)
.clamp(0.8, 4.0);
},
cx,
)),
))
// Distance virtuelle
.child(self.render_setting_row(
"Distance Virtuelle Écran",
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(format!("{:.1} mètres", self.cfg.screen_distance_m)),
)),
))
// 3.4 Carte Télémétrie OSD & MAVLink
@@ -2425,6 +2502,85 @@ impl SteamFrameGpuiApp {
self.controls.set_gear_speed_limits(def);
}
fn sync_optical_params(&self) {
self.controls.update_optical_params(LiveOpticalParams {
projection_mode: ProjectionMode::from_str(&self.cfg.projection_mode),
camera_fov_deg: self.cfg.camera_fov_deg,
lens_k1: self.cfg.lens_k1,
lens_k2: self.cfg.lens_k2,
screen_distance_m: self.cfg.screen_distance_m,
screen_width_m: self.cfg.screen_width_m,
});
}
fn render_optical_stepper_row(
&self,
id_prefix: &'static str,
label: &'static str,
value_text: String,
mutator: fn(&mut AppConfig, f32),
cx: &mut Context<Self>,
) -> impl IntoElement {
let step_btn = |suffix: &'static str, txt: &'static str, step: f32| {
let btn_id = gpui::SharedString::from(format!("btn_opt_{}_{}", id_prefix, suffix));
div()
.id(btn_id)
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(move |this, _, _, cx| {
mutator(&mut this.cfg, step);
this.sync_optical_params();
cx.notify();
}))
.child(txt)
};
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(label),
)
.child(
div()
.flex()
.items_center()
.gap_1p5()
.child(step_btn("m2", "−−", -2.0))
.child(step_btn("m1", "−", -1.0))
.child(
div()
.w(px(64.0))
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_CYAN))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(COLOR_CYAN))
.flex()
.justify_center()
.child(value_text),
)
.child(step_btn("p1", "+", 1.0))
.child(step_btn("p2", "++", 2.0)),
)
}
fn render_gear_stepper_row(
&self,
id_prefix: &'static str,
@@ -3647,11 +3803,20 @@ pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Result
let should_continue = cx
.update(|window, cx| {
if let Some(view) = weak_view.upgrade() {
let mut exit_now = false;
view.update(cx, |this, cx| {
if this.controls.is_exit_requested() {
exit_now = true;
return;
}
if this.sync_from_engine(window) {
cx.notify();
}
});
if exit_now {
window.remove_window();
return false;
}
true
} else {
false
+48 -22
View File
@@ -2,10 +2,12 @@ use chrono::Local;
use log::{Level, LevelFilter, Log, Metadata, Record};
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, SyncSender};
use std::sync::Arc;
use std::thread;
const MAX_LOG_ENTRIES: usize = 1000;
@@ -42,27 +44,55 @@ impl Default for LogBuffer {
}
}
enum FileLogCmd {
Line { text: String, flush: bool },
Flush,
}
/// Logger centralisé capturant tous les événements et erreurs pour l'interface graphique
/// et les enregistrant simultanément dans un fichier persistant sans réouverture synchrone.
/// et les enregistrant sur un thread I/O dédié sans jamais bloquer les boucles temps réel.
pub struct GuiLogger {
buffer: Arc<Mutex<LogBuffer>>,
file_writer: Mutex<Option<BufWriter<File>>>,
file_tx: Option<SyncSender<FileLogCmd>>,
}
impl GuiLogger {
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
let file_writer = OpenOptions::new()
let file_tx = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_path)
.ok()
.map(BufWriter::new);
.and_then(|file| {
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
thread::Builder::new()
.name("fpv-log-writer".into())
.spawn(move || {
let mut writer = BufWriter::new(file);
while let Ok(cmd) = rx.recv() {
match cmd {
FileLogCmd::Line { text, flush } => {
let _ = writer.write_all(text.as_bytes());
if flush {
let _ = writer.flush();
}
}
FileLogCmd::Flush => {
let _ = writer.flush();
}
}
}
let _ = writer.flush();
})
.ok()
.map(|_| tx)
});
let logger = Box::new(Self {
buffer: Arc::clone(&buffer),
file_writer: Mutex::new(file_writer),
file_tx,
});
if log::set_boxed_logger(logger).is_ok() {
@@ -107,19 +137,16 @@ impl Log for GuiLogger {
entry.timestamp, entry.level, entry.target, entry.message
);
// Écriture persistante sur descripteur ouvert avec tampon BufWriter
{
let mut writer_lock = self.file_writer.lock();
if let Some(ref mut writer) = *writer_lock {
let _ = writeln!(
writer,
"[{}] [{:<5}] ({}) {}",
entry.timestamp, entry.level, entry.target, entry.message
);
if record.level() <= Level::Warn {
let _ = writer.flush();
}
}
// Envoi non-bloquant vers le thread d'écriture disque (jamais d'I/O sur thread temps réel)
if let Some(ref tx) = self.file_tx {
let line = format!(
"[{}] [{:<5}] ({}) {}\n",
entry.timestamp, entry.level, entry.target, entry.message
);
let _ = tx.try_send(FileLogCmd::Line {
text: line,
flush: record.level() <= Level::Warn,
});
}
// Ajout dans le tampon de l'interface graphique
@@ -144,9 +171,8 @@ impl Log for GuiLogger {
}
fn flush(&self) {
let mut writer_lock = self.file_writer.lock();
if let Some(ref mut writer) = *writer_lock {
let _ = writer.flush();
if let Some(ref tx) = self.file_tx {
let _ = tx.try_send(FileLogCmd::Flush);
}
}
}
+47 -35
View File
@@ -4,7 +4,6 @@ mod dome_projection;
mod dvr;
mod engine;
mod g29_bridge;
mod gui;
mod gui_gpui;
mod logger;
mod nomad_elrs;
@@ -16,57 +15,70 @@ use anyhow::Result;
use clap::Parser;
use config::AppConfig;
use engine::FpvEngineController;
use gui::SteamFrameGuiApp;
use logger::GuiLogger;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);
extern "C" fn on_termination_signal(_sig: std::ffi::c_int) {
SHUTDOWN_REQUESTED.store(true, Ordering::Release);
}
fn install_signal_handlers() {
extern "C" {
fn signal(sig: std::ffi::c_int, handler: extern "C" fn(std::ffi::c_int)) -> usize;
}
const SIGINT: std::ffi::c_int = 2;
const SIGTERM: std::ffi::c_int = 15;
// SAFETY: `on_termination_signal` est async-signal-safe (uniquement un store atomique sur une statique).
unsafe {
signal(SIGINT, on_termination_signal);
signal(SIGTERM, on_termination_signal);
}
}
fn main() -> Result<()> {
let cfg = AppConfig::parse();
let mut cfg = AppConfig::parse();
let log_buffer = GuiLogger::init(&cfg.log_file);
let mode_label = if cfg.vr_only {
"VR-Only Natif (Mode Gaming OpenXR)"
} else if cfg.no_gui {
"CLI (--no-gui)"
} else {
"GPUI"
};
log::info!(
"=== Démarrage de SteamFrame FPV v{} (Moteur IHM : {}, Fichier journal : {}) ===",
"=== Démarrage de SteamFrame FPV v{} (Mode : {}, Fichier journal : {}) ===",
env!("CARGO_PKG_VERSION"),
cfg.gui_engine,
mode_label,
cfg.log_file
);
if cfg.no_gui {
log::info!("Mode ligne de commande (--no-gui) activé.");
if cfg.no_gui || cfg.vr_only {
install_signal_handlers();
if cfg.vr_only {
cfg.headless = false;
log::info!("Mode VR natif direct (--vr-only) activé : session OpenXR plein casque sans fenêtre 2D.");
} else {
log::info!("Mode ligne de commande (--no-gui) activé. Ctrl+C ou SIGTERM pour un arrêt sécurisé.");
}
let mut engine = FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled);
let control = engine.control_handle();
control.set_preview_active(false);
engine.start(cfg);
let running = Arc::new(AtomicBool::new(true));
while running.load(Ordering::Relaxed) && engine.is_running() {
std::thread::sleep(Duration::from_millis(200));
while !SHUTDOWN_REQUESTED.load(Ordering::Acquire)
&& !control.is_exit_requested()
&& engine.is_running()
{
std::thread::sleep(Duration::from_millis(100));
}
log::info!("[FPV] Arrêt demandé, fermeture sécurisée du moteur FPV...");
engine.stop();
return Ok(());
}
if cfg.gui_engine.eq_ignore_ascii_case("gpui") {
log::info!("Démarrage de l'interface moderne GPU-accélérée (GPUI)...");
return gui_gpui::run_gpui_app(cfg, log_buffer);
}
let native_options = eframe::NativeOptions {
viewport: eframe::egui::ViewportBuilder::default()
.with_title(format!(
"SteamFrame FPV v{} - Eachine Sphere Link & RadioMaster Nomad",
env!("CARGO_PKG_VERSION")
))
.with_inner_size([1220.0, 820.0])
.with_min_inner_size([920.0, 620.0]),
..Default::default()
};
eframe::run_native(
"SteamFrame FPV",
native_options,
Box::new(move |cc| Ok(Box::new(SteamFrameGuiApp::new(cc, cfg, log_buffer)))),
)
.map_err(|e| anyhow::anyhow!("Erreur interface graphique eframe : {}", e))?;
Ok(())
gui_gpui::run_gpui_app(cfg, log_buffer)
}
+486
View File
@@ -397,6 +397,48 @@ impl Drop for TelemetryReceiver {
}
}
/// Pages du Menu Minimaliste VR intégré à l'OSD OpenXR.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VrMenuPage {
#[default]
Main,
Advanced,
}
impl VrMenuPage {
pub const fn item_count(self) -> usize {
match self {
Self::Main => VR_MENU_MAIN_COUNT,
Self::Advanced => VR_MENU_ADV_COUNT,
}
}
}
/// Nombre d'entrées dans le menu principal minimaliste VR (actions essentielles).
pub const VR_MENU_MAIN_COUNT: usize = 8;
/// Nombre d'entrées dans le sous-menu Avancé VR.
pub const VR_MENU_ADV_COUNT: usize = 7;
/// Données d'affichage zéro-allocation (`Copy`) pour le Menu Minimaliste VR dans le casque.
#[derive(Debug, Clone, Copy)]
pub struct VrMenuRenderData {
pub page: VrMenuPage,
pub selected_idx: usize,
pub control_source: ControlSource,
pub head_tracking_on: bool,
pub telemetry_osd_on: bool,
pub projection_label: &'static str,
pub screen_distance_m: f32,
pub lens_k1: f32,
pub camera_fov_deg: f32,
pub dvr_recording: bool,
pub gear_3_max: u16,
pub vibration_pct: u8,
pub wifi_channel: u16,
pub quit_confirm_pending: bool,
pub feedback_msg: Option<(&'static str, bool)>,
}
/// Moteur d'incrustation graphique OSD (HUD vectoriel + police bitmap 5x7 avec contour)
pub struct OsdOverlay;
@@ -569,6 +611,408 @@ impl OsdOverlay {
Self::draw_g29_hud(rgba, width, height, g29, scale, bottom_y);
}
/// Mini-barre discrète affichée dans le casque au démarrage ou en l'absence de signal VRX.
pub fn render_vr_standby_bar(
rgba: &mut [u8],
width: u32,
height: u32,
has_video_stream: bool,
control_source: ControlSource,
dvr_recording: bool,
) {
let scale = (height / 360).max(1);
let s = scale as i32;
let char_w = 6 * s;
let mut bar_buf = StackStr::<64>::new();
let vrx_lbl = if has_video_stream { "VRX OK" } else { "VRX ATTENTE" };
let src_lbl = match control_source {
ControlSource::G29 => "G29",
ControlSource::SteamController => "STEAM",
};
let dvr_lbl = if dvr_recording { " | REC" } else { "" };
let _ = write!(
bar_buf,
"{} | CTRL: {}{} | MENU: OPT/VIEW/MENU",
vrx_lbl, src_lbl, dvr_lbl
);
let text = bar_buf.as_str();
let text_w = text.chars().count() as i32 * char_w;
let pad_x = 10 * s;
let bar_w = (text_w + pad_x * 2).min(width as i32 - 16);
let bar_h = 15 * s;
let bx = (width as i32 - bar_w) / 2;
let by = (height as i32) - bar_h - 14 * s;
Self::darken_rect(rgba, width, height, bx, by, bar_w, bar_h, [8, 14, 24]);
Self::draw_rect_outline(
rgba,
width,
height,
bx,
by,
bar_w,
bar_h,
if has_video_stream {
[0, 220, 255, 255]
} else {
[255, 180, 40, 255]
},
);
let tx = bx + (bar_w - text_w) / 2;
Self::draw_text(
rgba,
width,
height,
tx.max(bx + 4),
by + 4 * s,
text,
scale,
[225, 240, 255, 255],
);
}
/// Dessine le Menu Minimaliste VR superposé (navigable au Volant G29, Steam Controller et Contrôleurs OpenXR).
pub fn render_vr_menu(
rgba: &mut [u8],
width: u32,
height: u32,
menu: &VrMenuRenderData,
) {
let scale = (height / 360).max(1);
let s = scale as i32;
let char_w = 6 * s;
let row_h = 12 * s;
let item_count = menu.page.item_count();
let panel_w = (304 * s).min(width as i32 - 16).max(180);
let header_h = 18 * s;
let footer_h = 20 * s;
let panel_h = (header_h + (item_count as i32 * row_h) + footer_h)
.min(height as i32 - 12);
let px0 = (width as i32 - panel_w) / 2;
let py0 = (height as i32 - panel_h) / 2;
// 1. Fond assombri translucide haute lisibilité (assombrissement 75% + teinte cockpit bleu nuit)
Self::darken_rect(rgba, width, height, px0, py0, panel_w, panel_h, [6, 10, 18]);
// Bandeau titre supérieur
Self::fill_rect(
rgba,
width,
height,
px0 + 1,
py0 + 1,
panel_w - 2,
header_h - 2,
[12, 28, 46, 255],
);
// Double bordure cyan lumineuse
Self::draw_rect_outline(
rgba,
width,
height,
px0,
py0,
panel_w,
panel_h,
[0, 229, 255, 255],
);
Self::draw_rect_outline(
rgba,
width,
height,
px0 + 2,
py0 + 2,
panel_w - 4,
panel_h - 4,
[25, 75, 110, 255],
);
let title = match menu.page {
VrMenuPage::Main => "[ STEAMFRAME VR MENU ]",
VrMenuPage::Advanced => "[ MENU VR : AVANCE ]",
};
let title_x = px0 + (panel_w - (title.len() as i32 * char_w)) / 2;
Self::draw_text(
rgba,
width,
height,
title_x.max(px0 + 6),
py0 + 5 * s,
title,
scale,
[0, 235, 255, 255],
);
let selected = menu.selected_idx % item_count;
for idx in 0..item_count {
let ry = py0 + header_h + (idx as i32 * row_h);
if ry + row_h > py0 + panel_h - footer_h + 2 {
break;
}
let is_sel = idx == selected;
if is_sel {
let is_quit_row = menu.page == VrMenuPage::Main && idx == 7;
let row_bg = if is_quit_row && menu.quit_confirm_pending {
[120, 24, 24, 255]
} else {
[20, 58, 86, 255]
};
Self::fill_rect(
rgba,
width,
height,
px0 + 4,
ry,
panel_w - 8,
row_h - 1,
row_bg,
);
}
let mut label_buf = StackStr::<32>::new();
let mut val_buf = StackStr::<32>::new();
let prefix = if is_sel { "> " } else { " " };
let val_color = match (menu.page, idx) {
// --- PAGE PRINCIPALE MINIMALISTE (8 entrées) ---
(VrMenuPage::Main, 0) => {
let _ = write!(label_buf, "{}SOURCE PILOTAGE", prefix);
let src_lbl = match menu.control_source {
ControlSource::G29 => "< G29 VOLANT >",
ControlSource::SteamController => "< STEAM CTRL >",
};
let _ = write!(val_buf, "{}", src_lbl);
[255, 190, 60, 255]
}
(VrMenuPage::Main, 1) => {
let _ = write!(label_buf, "{}CENTRER VUE HT", prefix);
let _ = write!(val_buf, "[ TARE ]");
[0, 235, 255, 255]
}
(VrMenuPage::Main, 2) => {
let _ = write!(label_buf, "{}PROJECTION VR", prefix);
let _ = write!(val_buf, "< {} >", menu.projection_label);
[100, 225, 255, 255]
}
(VrMenuPage::Main, 3) => {
let _ = write!(label_buf, "{}DISTANCE ECRAN", prefix);
let _ = write!(val_buf, "< {:.1} M >", menu.screen_distance_m);
[235, 240, 250, 255]
}
(VrMenuPage::Main, 4) => {
let _ = write!(label_buf, "{}OSD TELEMETRIE", prefix);
let _ = write!(
val_buf,
"{}",
if menu.telemetry_osd_on { "< ON >" } else { "< OFF >" }
);
if menu.telemetry_osd_on {
[90, 255, 130, 255]
} else {
[160, 175, 195, 255]
}
}
(VrMenuPage::Main, 5) => {
let _ = write!(label_buf, "{}ENREGISTREUR DVR", prefix);
let _ = write!(
val_buf,
"{}",
if menu.dvr_recording { "< REC >" } else { "< STOP >" }
);
if menu.dvr_recording {
[255, 70, 70, 255]
} else {
[180, 190, 205, 255]
}
}
(VrMenuPage::Main, 6) => {
let _ = write!(label_buf, "{}REGLAGES AVANCES", prefix);
let _ = write!(val_buf, "[ OUVRIR > ]");
[160, 215, 255, 255]
}
(VrMenuPage::Main, _) => {
let _ = write!(label_buf, "{}QUITTER L'APP", prefix);
if menu.quit_confirm_pending {
let _ = write!(val_buf, "[ CONFIRMER ! ]");
[255, 80, 80, 255]
} else {
let _ = write!(val_buf, "[ FERMER ]");
[255, 130, 120, 255]
}
}
// --- SOUS-MENU AVANCÉ (7 entrées) ---
(VrMenuPage::Advanced, 0) => {
let _ = write!(label_buf, "{}< RETOUR MENU", prefix);
let _ = write!(val_buf, "[ B / RETOUR ]");
[0, 235, 255, 255]
}
(VrMenuPage::Advanced, 1) => {
let _ = write!(label_buf, "{}SUIVI TETE (HT)", prefix);
let _ = write!(
val_buf,
"{}",
if menu.head_tracking_on { "< ON >" } else { "< OFF >" }
);
if menu.head_tracking_on {
[90, 255, 130, 255]
} else {
[160, 175, 195, 255]
}
}
(VrMenuPage::Advanced, 2) => {
let _ = write!(label_buf, "{}CORRECTION K1", prefix);
let _ = write!(val_buf, "< {:+.2} >", menu.lens_k1);
[235, 240, 250, 255]
}
(VrMenuPage::Advanced, 3) => {
let _ = write!(label_buf, "{}FOV CAMERA", prefix);
let _ = write!(val_buf, "< {:.0}° >", menu.camera_fov_deg);
[235, 240, 250, 255]
}
(VrMenuPage::Advanced, 4) => {
let _ = write!(label_buf, "{}PLAFOND 3E VIT.", prefix);
let _ = write!(val_buf, "< {} >", menu.gear_3_max);
[255, 190, 60, 255]
}
(VrMenuPage::Advanced, 5) => {
let _ = write!(label_buf, "{}VIBRATIONS SC", prefix);
let _ = write!(val_buf, "< {}% >", menu.vibration_pct);
[100, 225, 255, 255]
}
(VrMenuPage::Advanced, _) => {
let _ = write!(label_buf, "{}CANAL RADXA 5.8G", prefix);
let _ = write!(val_buf, "< CH {} >", menu.wifi_channel);
[255, 190, 60, 255]
}
};
let lbl_color = if is_sel {
[255, 255, 255, 255]
} else {
[195, 210, 228, 255]
};
let text_y = ry + 3 * s;
Self::draw_text(
rgba,
width,
height,
px0 + 8 * s,
text_y,
label_buf.as_str(),
scale,
lbl_color,
);
let vx = (px0 + panel_w - 8 * s) - (val_buf.as_str().chars().count() as i32 * char_w);
Self::draw_text(
rgba,
width,
height,
vx.max(px0 + panel_w / 2),
text_y,
val_buf.as_str(),
scale,
val_color,
);
}
// Pied du menu : message de retour (erreur d'armement / confirmation) ou aide touches
let footer_y = py0 + panel_h - footer_h + 6 * s;
if let Some((msg, is_err)) = menu.feedback_msg {
let color = if is_err {
[255, 75, 75, 255]
} else {
[90, 255, 130, 255]
};
let fx = px0 + (panel_w - (msg.chars().count() as i32 * char_w)) / 2;
Self::draw_text(
rgba,
width,
height,
fx.max(px0 + 6),
footer_y,
msg,
scale,
color,
);
} else {
let help = match menu.page {
VrMenuPage::Main => "STICK/DPAD:CHOIX A/G/D:REGLER B:FERMER",
VrMenuPage::Advanced => "G/D:CHANGER A:APPLIQUER B:RETOUR MENU",
};
let hx = px0 + (panel_w - (help.len() as i32 * char_w)) / 2;
Self::draw_text(
rgba,
width,
height,
hx.max(px0 + 6),
footer_y,
help,
scale,
[150, 180, 210, 255],
);
}
}
fn darken_rect(
rgba: &mut [u8],
width: u32,
height: u32,
x: i32,
y: i32,
w: i32,
h: i32,
tint: [u8; 3],
) {
let x0 = x.clamp(0, width as i32) as u32;
let y0 = y.clamp(0, height as i32) as u32;
let x1 = (x + w).clamp(0, width as i32) as u32;
let y1 = (y + h).clamp(0, height as i32) as u32;
for row in y0..y1 {
let row_start = (row * width + x0) as usize * 4;
let row_end = (row * width + x1) as usize * 4;
if row_end <= rgba.len() {
for px in rgba[row_start..row_end].chunks_exact_mut(4) {
px[0] = (px[0] >> 2).saturating_add(tint[0]);
px[1] = (px[1] >> 2).saturating_add(tint[1]);
px[2] = (px[2] >> 2).saturating_add(tint[2]);
px[3] = 255;
}
}
}
}
fn fill_rect(
rgba: &mut [u8],
width: u32,
height: u32,
x: i32,
y: i32,
w: i32,
h: i32,
color: [u8; 4],
) {
let x0 = x.clamp(0, width as i32) as u32;
let y0 = y.clamp(0, height as i32) as u32;
let x1 = (x + w).clamp(0, width as i32) as u32;
let y1 = (y + h).clamp(0, height as i32) as u32;
for row in y0..y1 {
let row_start = (row * width + x0) as usize * 4;
let row_end = (row * width + x1) as usize * 4;
if row_end <= rgba.len() {
for px in rgba[row_start..row_end].chunks_exact_mut(4) {
px.copy_from_slice(&color);
}
}
}
}
fn draw_g29_hud(
rgba: &mut [u8],
width: u32,
@@ -871,6 +1315,11 @@ impl OsdOverlay {
',' => [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b01000],
'*' => [0b00000, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0b00000],
'°' => [0b01100, 0b10010, 0b10010, 0b01100, 0b00000, 0b00000, 0b00000],
'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010],
'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000],
'=' => [0b00000, 0b00000, 0b11111, 0b00000, 0b11111, 0b00000, 0b00000],
'\'' => [0b00100, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000],
'|' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
_ => [0b00000; 7],
}
@@ -892,6 +1341,43 @@ mod tests {
assert_eq!(s4.as_str(), "12°");
}
#[test]
fn test_render_vr_menu_bounds_and_output() {
let mut rgba = vec![100u8; 1280 * 720 * 4];
let mut menu = VrMenuRenderData {
page: VrMenuPage::Main,
selected_idx: 0,
control_source: ControlSource::SteamController,
head_tracking_on: true,
telemetry_osd_on: true,
projection_label: "DOME 140",
screen_distance_m: 1.6,
lens_k1: -0.14,
camera_fov_deg: 140.0,
dvr_recording: false,
gear_3_max: 1220,
vibration_pct: 100,
wifi_channel: 161,
quit_confirm_pending: false,
feedback_msg: Some(("TARE HT OK", false)),
};
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
let center_idx = ((720 / 2) * 1280 + (1280 / 2)) * 4;
assert_ne!(&rgba[center_idx..center_idx + 3], &[100, 100, 100]);
menu.page = VrMenuPage::Advanced;
menu.selected_idx = 6;
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
OsdOverlay::render_vr_standby_bar(
&mut rgba,
1280,
720,
false,
ControlSource::G29,
false,
);
}
#[test]
fn test_parse_datagram_crsf_crc_validation() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
+32 -12
View File
@@ -189,17 +189,17 @@ impl Drop for UsbVideoReceiver {
}
}
/// Construit la description textuelle du pipeline GStreamer selon le mode choisi.
/// Construit la description textuelle du pipeline GStreamer sans interpoler de chaînes externes non sûres
/// (`device`, `address` et `port` sont injectés par `set_property` après création).
fn pipeline_description(p: &PipelineParams) -> String {
let (w, h) = (p.target_width, p.target_height);
if p.usb_video_mode.eq_ignore_ascii_case("uvc") {
return format!(
"v4l2src device={dev} do-timestamp=true ! \
"v4l2src name=uvc_src do-timestamp=true ! \
decodebin ! \
videoconvert ! videoscale ! \
video/x-raw,format=RGBA,width={w},height={h} ! \
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false",
dev = p.uvc_device
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false"
);
}
@@ -224,18 +224,16 @@ fn pipeline_description(p: &PipelineParams) -> String {
};
format!(
"udpsrc address={ip} port={port} buffer-size=4194304 retrieve-sender-address=false ! \
"udpsrc name=udp_src buffer-size=4194304 retrieve-sender-address=false ! \
{depay_and_parse} ! \
{decoder} ! \
videoscale ! videoconvert ! \
video/x-raw,format=RGBA,width={w},height={h} ! \
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false",
ip = p.bind_ip,
port = p.port
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false"
)
}
/// Construit le pipeline, branche l'appsink sur `latest_frame` et le passe en PLAYING.
/// Construit le pipeline, configure les propriétés sources de façon sécurisée, branche l'appsink et passe en PLAYING.
fn build_pipeline(
params: &PipelineParams,
latest_frame: &Arc<Mutex<Option<VideoFrame>>>,
@@ -251,6 +249,24 @@ fn build_pipeline(
.dynamic_cast::<gst::Pipeline>()
.map_err(|_| anyhow::anyhow!("L'élément GStreamer n'est pas un Pipeline"))?;
if params.usb_video_mode.eq_ignore_ascii_case("uvc") {
let uvc_src = pipeline
.by_name("uvc_src")
.context("Élément 'uvc_src' introuvable dans le pipeline")?;
uvc_src.set_property("device", params.uvc_device.trim());
} else {
let parsed_ip: std::net::IpAddr = params
.bind_ip
.trim()
.parse()
.with_context(|| format!("Adresse IP d'écoute vidéo invalide : '{}'", params.bind_ip))?;
let udp_src = pipeline
.by_name("udp_src")
.context("Élément 'udp_src' introuvable dans le pipeline")?;
udp_src.set_property("address", parsed_ip.to_string());
udp_src.set_property("port", params.port as i32);
}
let appsink = pipeline
.by_name("fpv_sink")
.context("Appsink 'fpv_sink' introuvable dans le pipeline")?
@@ -548,7 +564,8 @@ mod tests {
#[test]
fn test_pipeline_description_raw_h264() {
let d = pipeline_description(&params("rndis", "h264", "raw"));
assert!(d.starts_with("udpsrc address=0.0.0.0 port=5600"));
assert!(d.starts_with("udpsrc name=udp_src"));
assert!(!d.contains("0.0.0.0"));
assert!(d.contains("h264parse"));
assert!(d.contains("avdec_h264"));
assert!(!d.contains("rtph264depay"));
@@ -565,8 +582,11 @@ mod tests {
#[test]
fn test_pipeline_description_uvc() {
let d = pipeline_description(&params("UVC", "h264", "raw"));
assert!(d.starts_with("v4l2src device=/dev/video0"));
let mut p = params("UVC", "h264", "raw");
p.uvc_device = "/dev/video0 ! filesink location=/tmp/pwn".into();
let d = pipeline_description(&p);
assert!(d.starts_with("v4l2src name=uvc_src"));
assert!(!d.contains("filesink"));
assert!(!d.contains("udpsrc"));
}
}
+13
View File
@@ -0,0 +1,13 @@
[Desktop Entry]
Version=1.0
Type=Application
Name=SteamFrame FPV (Mode VR)
GenericName=Cockpit VR Natif Steam Frame
Comment=Lancement direct en immersion OpenXR avec Menu Minimaliste VR (Mode Gaming SteamOS)
Exec=/home/deck/projects/steamframe_fpv/launch_vr.sh
Path=/home/deck/projects/steamframe_fpv
Icon=/home/deck/projects/steamframe_fpv/assets/icon.png
Terminal=false
Categories=Game;Video;AudioVideo;
StartupNotify=false
StartupWMClass=steamframe-fpv-vr