/// Modes de projection VR pour l'affichage du flux Eachine Sphere Link (140° FOV) #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProjectionMode { /// Dôme sphérique 140° (`XR_KHR_composition_layer_equirect2` + correction optique grand-angle) Dome140, /// Écran incurvé cylindrique 140° (`XR_KHR_composition_layer_cylinder`) Cylinder140, /// Écran plat verrouillé sur la tête (`XrCompositionLayerQuad`) FlatQuad, } impl ProjectionMode { pub fn from_str(s: &str) -> Self { match s.to_lowercase().as_str() { "cylinder" | "cyl" => Self::Cylinder140, "flat" | "quad" => Self::FlatQuad, _ => Self::Dome140, } } pub fn label(&self) -> &'static str { match self { Self::Dome140 => "DOME 140", Self::Cylinder140 => "CYL 140", Self::FlatQuad => "QUAD", } } } /// Table de correspondance (LUT) précalculée pour corriger la distorsion en barillet /// de la lentille M12 140° de l'Eachine Sphere Link et la projeter sur le dôme VR. pub struct DomeWarpLut { width: u32, height: u32, fov_deg: f32, k1: f32, k2: f32, src_pixel_offsets: Vec, enabled: bool, } impl DomeWarpLut { pub fn new(width: u32, height: u32, fov_deg: f32, k1: f32, k2: f32) -> Self { let enabled = width > 0 && height > 0 && (k1.abs() > 1e-4 || k2.abs() > 1e-4); if !enabled { return Self { width, height, fov_deg, k1, k2, src_pixel_offsets: Vec::new(), enabled: false, }; } let total_pixels = (width as usize).saturating_mul(height as usize); let mut src_pixel_offsets = Vec::with_capacity(total_pixels); let aspect = width as f32 / height as f32; // Normalisation douce liée au FOV : à 140° le facteur de référence vaut 1.0 // (évite le recadrage/étirement des bords lorsque fov_deg < 140°). let fov_scale = (fov_deg.clamp(60.0, 180.0) / 140.0).clamp(0.75, 1.15); for y in 0..height { let ny = ((y as f32 + 0.5) / height as f32) * 2.0 - 1.0; for x in 0..width { let nx = ((x as f32 + 0.5) / width as f32) * 2.0 - 1.0; // Rayon normalisé dans [0..1] aux bords pour éviter tout repliement polynomial // même avec k1 = -0.50 dans les coins 16:9. let rx = nx * (aspect / aspect.max(1.0)); let ry = ny / aspect.max(1.0); let r2 = (rx * rx + ry * ry).min(1.5); let r4 = r2 * r2; let poly = (1.0 + k1 * r2 + k2 * r4).clamp(0.25, 2.5); let factor = poly / fov_scale; let src_nx = (nx * factor + 1.0) * 0.5; let src_ny = (ny * factor + 1.0) * 0.5; let sx = (src_nx * (width as f32 - 1.0)) .round() .clamp(0.0, (width - 1) as f32) as u32; let sy = (src_ny * (height as f32 - 1.0)) .round() .clamp(0.0, (height - 1) as f32) as u32; let pixel_offset = sy * width + sx; src_pixel_offsets.push(pixel_offset); } } Self { width, height, fov_deg, k1, k2, src_pixel_offsets, enabled: true, } } /// Vérifie rapidement si la table courante correspond déjà aux paramètres optiques demandés pub fn matches_params(&self, width: u32, height: u32, fov_deg: f32, k1: f32, k2: f32) -> bool { self.width == width && self.height == height && (self.fov_deg - fov_deg).abs() < 1e-4 && (self.k1 - k1).abs() < 1e-4 && (self.k2 - k2).abs() < 1e-4 } #[inline] pub fn apply(&self, input_rgba: &[u8], output_rgba: &mut [u8]) { let total_pixels = (self.width * self.height) as usize; let expected_bytes = total_pixels * 4; if !self.enabled || input_rgba.len() < expected_bytes || output_rgba.len() < expected_bytes { let copy_len = output_rgba.len().min(input_rgba.len()); output_rgba[..copy_len].copy_from_slice(&input_rgba[..copy_len]); 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::() }; let (dst_head, dst_u32, dst_tail) = unsafe { output_rgba[..expected_bytes].align_to_mut::() }; 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 for (dst_pixel_idx, &src_pixel_idx) in self.src_pixel_offsets.iter().enumerate() { let src_byte = (src_pixel_idx as usize) * 4; let dst_byte = dst_pixel_idx * 4; output_rgba[dst_byte..dst_byte + 4] .copy_from_slice(&input_rgba[src_byte..src_byte + 4]); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_projection_mode_parsing() { assert_eq!(ProjectionMode::from_str("dome"), ProjectionMode::Dome140); assert_eq!(ProjectionMode::from_str("DOME"), ProjectionMode::Dome140); assert_eq!(ProjectionMode::from_str("cylinder"), ProjectionMode::Cylinder140); assert_eq!(ProjectionMode::from_str("cyl"), ProjectionMode::Cylinder140); assert_eq!(ProjectionMode::from_str("flat"), ProjectionMode::FlatQuad); assert_eq!(ProjectionMode::from_str("quad"), ProjectionMode::FlatQuad); assert_eq!(ProjectionMode::from_str("unknown"), ProjectionMode::Dome140); } #[test] fn test_dome_warp_lut_disabled() { let lut = DomeWarpLut::new(64, 64, 140.0, 0.0, 0.0); assert!(!lut.enabled); let input = vec![42u8; 64 * 64 * 4]; let mut output = vec![0u8; 64 * 64 * 4]; lut.apply(&input, &mut output); assert_eq!(output, input); } #[test] fn test_dome_warp_lut_barrel_correction() { let width = 128; let height = 72; let lut = DomeWarpLut::new(width, height, 140.0, -0.14, 0.03); assert!(lut.enabled); assert_eq!(lut.src_pixel_offsets.len(), (width * height) as usize); // Vérifier que tous les indices de pixels restent strictement dans les limites de l'image let max_valid_pixel = width * height - 1; for &offset in &lut.src_pixel_offsets { assert!(offset <= max_valid_pixel, "Offset pixel {} dépasse le nombre de pixels", offset); } let mut input = vec![128u8; (width * height * 4) as usize]; // Marquer le centre let center_offset = ((height / 2 * width + width / 2) * 4) as usize; input[center_offset] = 255; let mut output = vec![0u8; (width * height * 4) as usize]; lut.apply(&input, &mut output); // Le centre ne doit pas subir de déplacement extrême assert_eq!(output[center_offset], 255); } #[test] fn test_dome_warp_lut_performance_720p() { let width = 1280; let height = 720; let lut = DomeWarpLut::new(width, height, 140.0, -0.14, 0.03); assert!(lut.enabled); let input = vec![100u8; (width * height * 4) as usize]; let mut output = vec![0u8; (width * height * 4) as usize]; // Échauffement lut.apply(&input, &mut output); let start = std::time::Instant::now(); let iterations = 10; for _ in 0..iterations { lut.apply(&input, &mut output); } let elapsed = start.elapsed(); let avg_ms = elapsed.as_secs_f64() * 1000.0 / (iterations as f64); println!("Temps moyen dé-distorsion DomeWarpLut 1280x720 : {:.2} ms", avg_ms); let max_allowed = if cfg!(debug_assertions) { 50.0 } else { 3.0 }; assert!(avg_ms < max_allowed, "Dé-distorsion trop lente: {:.2} ms (seuil: {:.2} ms)", avg_ms, max_allowed); } }