Skip to main content

bevy_sensor/
lib.rs

1//! bevy-sensor: Multi-view rendering for YCB object dataset
2//!
3//! This library provides Bevy-based rendering of 3D objects from multiple viewpoints,
4//! designed to match TBP (Thousand Brains Project) habitat sensor conventions for
5//! use in neocortx sensorimotor learning experiments.
6//!
7//! # Headless Rendering (NEW)
8//!
9//! Render directly to memory buffers for use in sensorimotor learning:
10//!
11//! ```ignore
12//! use bevy_sensor::{render_to_buffer, RenderConfig, ViewpointConfig, ObjectRotation};
13//! use std::path::Path;
14//!
15//! let config = RenderConfig::tbp_default(); // 64x64, RGBD
16//! let viewpoint = bevy_sensor::generate_viewpoints(&ViewpointConfig::default())[0];
17//! let rotation = ObjectRotation::identity();
18//!
19//! let output = render_to_buffer(
20//!     Path::new("/tmp/ycb/003_cracker_box"),
21//!     &viewpoint,
22//!     &rotation,
23//!     &config,
24//! )?;
25//!
26//! // output.rgba: Vec<u8> - RGBA pixels (64*64*4 bytes)
27//! // output.depth: Vec<f32> - Depth values (64*64 floats)
28//! ```
29//!
30//! # File-based Capture (Legacy)
31//!
32//! ```ignore
33//! use bevy_sensor::{SensorConfig, ViewpointConfig, ObjectRotation};
34//!
35//! let config = SensorConfig {
36//!     viewpoints: ViewpointConfig::default(),
37//!     object_rotations: ObjectRotation::tbp_benchmark_rotations(),
38//!     ..Default::default()
39//! };
40//! ```
41//!
42//! # YCB Dataset
43//!
44//! Download YCB models programmatically:
45//!
46//! ```ignore
47//! use bevy_sensor::ycb::{download_models, Subset};
48//!
49//! // Download representative subset (3 objects)
50//! download_models("/tmp/ycb", Subset::Representative).await?;
51//! ```
52
53use bevy::prelude::*;
54use std::f32::consts::PI;
55use std::path::Path;
56
57// Headless rendering implementation
58// Full GPU rendering requires a display - see render module for details
59mod render;
60
61// Batch rendering API for efficient multi-viewpoint rendering
62pub mod batch;
63
64// WebGPU and cross-platform backend support
65pub mod backend;
66
67// Model caching system for efficient multi-viewpoint rendering
68pub mod cache;
69
70// Test fixtures for pre-rendered images (CI/CD support)
71pub mod fixtures;
72
73// Re-export ycbust types for convenience
74pub use ycbust::{
75    self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
76    TBP_STANDARD_OBJECTS,
77};
78
79/// YCB dataset utilities
80pub mod ycb {
81    pub use ycbust::{
82        download_ycb, DownloadOptions, Subset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
83        TBP_STANDARD_OBJECTS,
84    };
85
86    use std::path::Path;
87
88    /// Download YCB models to the specified directory.
89    ///
90    /// # Arguments
91    /// * `output_dir` - Directory to download models to
92    /// * `subset` - Which subset of objects to download
93    ///
94    /// # Example
95    /// ```ignore
96    /// use bevy_sensor::ycb::{download_models, Subset};
97    ///
98    /// download_models("/tmp/ycb", Subset::Representative).await?;
99    /// ```
100    pub async fn download_models<P: AsRef<Path>>(
101        output_dir: P,
102        subset: Subset,
103    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
104        download_ycb(subset, output_dir.as_ref(), DownloadOptions::default()).await?;
105        Ok(())
106    }
107
108    /// Download YCB models with custom options.
109    pub async fn download_models_with_options<P: AsRef<Path>>(
110        output_dir: P,
111        subset: Subset,
112        options: DownloadOptions,
113    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
114        download_ycb(subset, output_dir.as_ref(), options).await?;
115        Ok(())
116    }
117
118    /// Download specific YCB objects by object ID using the standard `google_16k` meshes.
119    ///
120    /// Thin wrapper over [`ycbust::download_objects`] (added upstream in v0.3.3):
121    /// preserves this crate's ergonomic `P: AsRef<Path>` surface while delegating
122    /// skip / resume / integrity / parallelism to the upstream implementation.
123    pub async fn download_objects<P: AsRef<Path>>(
124        output_dir: P,
125        object_ids: &[&str],
126    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
127        ycbust::download_objects(object_ids, output_dir.as_ref(), DownloadOptions::default())
128            .await?;
129        Ok(())
130    }
131
132    /// Check if YCB models exist at the given path
133    pub fn models_exist<P: AsRef<Path>>(output_dir: P) -> bool {
134        ycbust::object_mesh_path(output_dir.as_ref(), "003_cracker_box").exists()
135    }
136
137    /// Get the path to a specific YCB object's OBJ file
138    pub fn object_mesh_path<P: AsRef<Path>>(output_dir: P, object_id: &str) -> std::path::PathBuf {
139        ycbust::object_mesh_path(output_dir.as_ref(), object_id)
140    }
141
142    /// Get the path to a specific YCB object's texture file
143    pub fn object_texture_path<P: AsRef<Path>>(
144        output_dir: P,
145        object_id: &str,
146    ) -> std::path::PathBuf {
147        ycbust::object_texture_path(output_dir.as_ref(), object_id)
148    }
149}
150
151/// Initialize bevy-sensor rendering backend configuration.
152///
153/// **IMPORTANT**: Call this function ONCE at the start of your application,
154/// before any rendering operations, especially when using bevy-sensor as a library.
155///
156/// This ensures proper backend selection (WebGPU for WSL2, Vulkan for Linux, etc.)
157/// and is critical for GPU rendering on WSL2 environments.
158///
159/// # Why This Matters
160///
161/// The WGPU rendering backend caches its backend selection early during initialization.
162/// When bevy-sensor is used as a library, environment variables must be set BEFORE
163/// any GPU rendering code runs. This function does that automatically.
164///
165/// # Example
166///
167/// ```ignore
168/// use bevy_sensor;
169///
170/// fn main() {
171///     // Initialize FIRST, before any rendering
172///     bevy_sensor::initialize();
173///
174///     // Now use the rendering API
175///     let output = bevy_sensor::render_to_buffer(
176///         object_dir, &viewpoint, &rotation, &config
177///     )?;
178/// }
179/// ```
180///
181/// # Calling Multiple Times
182///
183/// Safe to call multiple times - subsequent calls are no-ops after the first call.
184pub fn initialize() {
185    // Use a OnceCell equivalent to ensure this only runs once
186    use std::sync::atomic::{AtomicBool, Ordering};
187    static INITIALIZED: AtomicBool = AtomicBool::new(false);
188
189    if !INITIALIZED.swap(true, Ordering::SeqCst) {
190        // First call - initialize backend
191        let config = backend::BackendConfig::new();
192        config.apply_env();
193    }
194}
195
196/// Object rotation in Euler angles (degrees), matching TBP benchmark format.
197/// Format: [pitch, yaw, roll] or [x, y, z] rotation.
198#[derive(Clone, Debug, PartialEq)]
199pub struct ObjectRotation {
200    /// Rotation around X-axis (pitch) in degrees
201    pub pitch: f64,
202    /// Rotation around Y-axis (yaw) in degrees
203    pub yaw: f64,
204    /// Rotation around Z-axis (roll) in degrees
205    pub roll: f64,
206}
207
208impl ObjectRotation {
209    /// Create a new rotation from Euler angles in degrees
210    pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
211        Self { pitch, yaw, roll }
212    }
213
214    /// Create from TBP-style array [pitch, yaw, roll] in degrees
215    pub fn from_array(arr: [f64; 3]) -> Self {
216        Self {
217            pitch: arr[0],
218            yaw: arr[1],
219            roll: arr[2],
220        }
221    }
222
223    /// Identity rotation (no rotation)
224    pub fn identity() -> Self {
225        Self::new(0.0, 0.0, 0.0)
226    }
227
228    /// TBP benchmark rotations: [0,0,0], [0,90,0], [0,180,0]
229    /// Used in shorter YCB experiments to reduce computational load.
230    pub fn tbp_benchmark_rotations() -> Vec<Self> {
231        vec![
232            Self::from_array([0.0, 0.0, 0.0]),
233            Self::from_array([0.0, 90.0, 0.0]),
234            Self::from_array([0.0, 180.0, 0.0]),
235        ]
236    }
237
238    /// TBP 14 known orientations (cube faces and corners)
239    /// These are the orientations objects are learned in during training.
240    pub fn tbp_known_orientations() -> Vec<Self> {
241        vec![
242            // 6 cube faces (90° rotations around each axis)
243            Self::from_array([0.0, 0.0, 0.0]),   // Front
244            Self::from_array([0.0, 90.0, 0.0]),  // Right
245            Self::from_array([0.0, 180.0, 0.0]), // Back
246            Self::from_array([0.0, 270.0, 0.0]), // Left
247            Self::from_array([90.0, 0.0, 0.0]),  // Top
248            Self::from_array([-90.0, 0.0, 0.0]), // Bottom
249            // 8 cube corners (45° rotations)
250            Self::from_array([45.0, 45.0, 0.0]),
251            Self::from_array([45.0, 135.0, 0.0]),
252            Self::from_array([45.0, 225.0, 0.0]),
253            Self::from_array([45.0, 315.0, 0.0]),
254            Self::from_array([-45.0, 45.0, 0.0]),
255            Self::from_array([-45.0, 135.0, 0.0]),
256            Self::from_array([-45.0, 225.0, 0.0]),
257            Self::from_array([-45.0, 315.0, 0.0]),
258        ]
259    }
260
261    /// Convert to Bevy Quat (converts f64 to f32 for Bevy compatibility)
262    pub fn to_quat(&self) -> Quat {
263        Quat::from_euler(
264            EulerRot::XYZ,
265            (self.pitch as f32).to_radians(),
266            (self.yaw as f32).to_radians(),
267            (self.roll as f32).to_radians(),
268        )
269    }
270
271    /// Convert to Bevy Transform (rotation only, no translation)
272    pub fn to_transform(&self) -> Transform {
273        Transform::from_rotation(self.to_quat())
274    }
275}
276
277impl Default for ObjectRotation {
278    fn default() -> Self {
279        Self::identity()
280    }
281}
282
283/// Configuration for viewpoint generation matching TBP habitat sensor behavior.
284/// Uses spherical coordinates to capture objects from multiple elevations.
285#[derive(Clone, Debug)]
286pub struct ViewpointConfig {
287    /// Distance from camera to object center (meters)
288    pub radius: f32,
289    /// Number of horizontal positions (yaw angles) around the object
290    pub yaw_count: usize,
291    /// Elevation angles in degrees (pitch). Positive = above, negative = below.
292    pub pitch_angles_deg: Vec<f32>,
293}
294
295impl Default for ViewpointConfig {
296    fn default() -> Self {
297        Self {
298            radius: 0.5,
299            yaw_count: 8,
300            // Three elevations: below (-30°), level (0°), above (+30°)
301            // This matches TBP's look_up/look_down capability
302            pitch_angles_deg: vec![-30.0, 0.0, 30.0],
303        }
304    }
305}
306
307impl ViewpointConfig {
308    /// Total number of viewpoints this config will generate
309    pub fn viewpoint_count(&self) -> usize {
310        self.yaw_count * self.pitch_angles_deg.len()
311    }
312}
313
314/// Full sensor configuration for capture sessions
315#[derive(Clone, Debug, Resource)]
316pub struct SensorConfig {
317    /// Viewpoint configuration (camera positions)
318    pub viewpoints: ViewpointConfig,
319    /// Object rotations to capture (each rotation generates a full viewpoint set)
320    pub object_rotations: Vec<ObjectRotation>,
321    /// Output directory for captures
322    pub output_dir: String,
323    /// Filename pattern (use {view} for view index, {rot} for rotation index)
324    pub filename_pattern: String,
325}
326
327impl Default for SensorConfig {
328    fn default() -> Self {
329        Self {
330            viewpoints: ViewpointConfig::default(),
331            object_rotations: vec![ObjectRotation::identity()],
332            output_dir: ".".to_string(),
333            filename_pattern: "capture_{rot}_{view}.png".to_string(),
334        }
335    }
336}
337
338impl SensorConfig {
339    /// Create config for TBP benchmark comparison (3 rotations × 24 viewpoints = 72 captures)
340    pub fn tbp_benchmark() -> Self {
341        Self {
342            viewpoints: ViewpointConfig::default(),
343            object_rotations: ObjectRotation::tbp_benchmark_rotations(),
344            output_dir: ".".to_string(),
345            filename_pattern: "capture_{rot}_{view}.png".to_string(),
346        }
347    }
348
349    /// Create config for full TBP training (14 rotations × 24 viewpoints = 336 captures)
350    pub fn tbp_full_training() -> Self {
351        Self {
352            viewpoints: ViewpointConfig::default(),
353            object_rotations: ObjectRotation::tbp_known_orientations(),
354            output_dir: ".".to_string(),
355            filename_pattern: "capture_{rot}_{view}.png".to_string(),
356        }
357    }
358
359    /// Total number of captures this config will generate
360    pub fn total_captures(&self) -> usize {
361        self.viewpoints.viewpoint_count() * self.object_rotations.len()
362    }
363}
364
365/// Generate camera viewpoints using spherical coordinates.
366///
367/// Spherical coordinate system (matching TBP habitat sensor conventions):
368/// - Yaw: horizontal rotation around Y-axis (0° to 360°)
369/// - Pitch: elevation angle from horizontal plane (-90° to +90°)
370/// - Radius: distance from origin (object center)
371pub fn generate_viewpoints(config: &ViewpointConfig) -> Vec<Transform> {
372    let mut views = Vec::with_capacity(config.viewpoint_count());
373
374    for pitch_deg in &config.pitch_angles_deg {
375        let pitch = pitch_deg.to_radians();
376
377        for i in 0..config.yaw_count {
378            let yaw = (i as f32) * 2.0 * PI / (config.yaw_count as f32);
379
380            // Spherical to Cartesian conversion (Y-up coordinate system)
381            // x = r * cos(pitch) * sin(yaw)
382            // y = r * sin(pitch)
383            // z = r * cos(pitch) * cos(yaw)
384            let x = config.radius * pitch.cos() * yaw.sin();
385            let y = config.radius * pitch.sin();
386            let z = config.radius * pitch.cos() * yaw.cos();
387
388            let transform = Transform::from_xyz(x, y, z).looking_at(Vec3::ZERO, Vec3::Y);
389            views.push(transform);
390        }
391    }
392    views
393}
394
395/// Marker component for the target object being captured
396#[derive(Component)]
397pub struct CaptureTarget;
398
399/// Marker component for the capture camera
400#[derive(Component)]
401pub struct CaptureCamera;
402
403// ============================================================================
404// Headless Rendering API (NEW)
405// ============================================================================
406
407/// Configuration for headless rendering.
408///
409/// Matches TBP habitat sensor defaults: 64x64 resolution with RGBD output.
410#[derive(Clone, Debug, PartialEq)]
411pub struct RenderConfig {
412    /// Image width in pixels (default: 64)
413    pub width: u32,
414    /// Image height in pixels (default: 64)
415    pub height: u32,
416    /// Zoom factor affecting field of view (default: 1.0)
417    /// Use >1 to zoom in (narrower FOV), <1 to zoom out (wider FOV)
418    pub zoom: f32,
419    /// Near clipping plane in meters (default: 0.01)
420    pub near_plane: f32,
421    /// Far clipping plane in meters (default: 10.0)
422    pub far_plane: f32,
423    /// Lighting configuration
424    pub lighting: LightingConfig,
425}
426
427/// Lighting configuration for rendering.
428///
429/// Controls ambient light and point lights in the scene.
430#[derive(Clone, Debug, PartialEq)]
431pub struct LightingConfig {
432    /// Ambient light brightness (0.0 - 1.0, default: 0.3)
433    pub ambient_brightness: f32,
434    /// Key light intensity in lumens (default: 1500.0)
435    pub key_light_intensity: f32,
436    /// Key light position [x, y, z] (default: [4.0, 8.0, 4.0])
437    pub key_light_position: [f32; 3],
438    /// Fill light intensity in lumens (default: 500.0)
439    pub fill_light_intensity: f32,
440    /// Fill light position [x, y, z] (default: [-4.0, 2.0, -4.0])
441    pub fill_light_position: [f32; 3],
442    /// Enable shadows (default: false for performance)
443    pub shadows_enabled: bool,
444}
445
446impl Default for LightingConfig {
447    fn default() -> Self {
448        Self {
449            ambient_brightness: 0.3,
450            key_light_intensity: 1500.0,
451            key_light_position: [4.0, 8.0, 4.0],
452            fill_light_intensity: 500.0,
453            fill_light_position: [-4.0, 2.0, -4.0],
454            shadows_enabled: false,
455        }
456    }
457}
458
459impl LightingConfig {
460    /// Bright lighting for clear visibility
461    pub fn bright() -> Self {
462        Self {
463            ambient_brightness: 0.5,
464            key_light_intensity: 2000.0,
465            key_light_position: [4.0, 8.0, 4.0],
466            fill_light_intensity: 800.0,
467            fill_light_position: [-4.0, 2.0, -4.0],
468            shadows_enabled: false,
469        }
470    }
471
472    /// Soft lighting with minimal shadows
473    pub fn soft() -> Self {
474        Self {
475            ambient_brightness: 0.4,
476            key_light_intensity: 1000.0,
477            key_light_position: [3.0, 6.0, 3.0],
478            fill_light_intensity: 600.0,
479            fill_light_position: [-3.0, 3.0, -3.0],
480            shadows_enabled: false,
481        }
482    }
483
484    /// Unlit mode - ambient only, no point lights
485    pub fn unlit() -> Self {
486        Self {
487            ambient_brightness: 1.0,
488            key_light_intensity: 0.0,
489            key_light_position: [0.0, 0.0, 0.0],
490            fill_light_intensity: 0.0,
491            fill_light_position: [0.0, 0.0, 0.0],
492            shadows_enabled: false,
493        }
494    }
495}
496
497impl Default for RenderConfig {
498    fn default() -> Self {
499        Self::tbp_default()
500    }
501}
502
503impl RenderConfig {
504    /// TBP-compatible 64x64 RGBD patch sensor configuration.
505    ///
506    /// Matches TBP's habitat distant patch sensor: 64x64 resolution with
507    /// zoom=10 (90° base HFOV → ~9° effective FOV), producing a tight view
508    /// of the object's surface patch.
509    ///
510    /// TBP ref: `missing_depthto3d_sensor2_semantic0.yaml` (zoom=10)
511    pub fn tbp_default() -> Self {
512        Self {
513            width: 64,
514            height: 64,
515            zoom: 4.0,
516            near_plane: 0.01,
517            far_plane: 10.0,
518            lighting: LightingConfig::default(),
519        }
520    }
521
522    /// Higher resolution configuration for debugging and visualization.
523    pub fn preview() -> Self {
524        Self {
525            width: 256,
526            height: 256,
527            zoom: 1.0,
528            near_plane: 0.01,
529            far_plane: 10.0,
530            lighting: LightingConfig::default(),
531        }
532    }
533
534    /// High resolution configuration for detailed captures.
535    pub fn high_res() -> Self {
536        Self {
537            width: 512,
538            height: 512,
539            zoom: 1.0,
540            near_plane: 0.01,
541            far_plane: 10.0,
542            lighting: LightingConfig::default(),
543        }
544    }
545
546    /// Calculate vertical field of view in radians based on zoom.
547    ///
548    /// TBP zooms by dividing the focal length, not the angle:
549    ///   `fx_norm = tan(hfov/2) / zoom`
550    /// This is equivalent to `fov = 2 * atan(tan(hfov/2) / zoom)`.
551    /// With hfov=90° and zoom=10, effective FOV ≈ 11.4° (not 9°).
552    pub fn fov_radians(&self) -> f32 {
553        let base_hfov_rad = 90.0_f32.to_radians();
554        let half_tan = (base_hfov_rad / 2.0).tan() / self.zoom;
555        2.0 * half_tan.atan()
556    }
557
558    /// Compute camera intrinsics for use with neocortx.
559    ///
560    /// Returns focal length and principal point based on resolution and FOV.
561    /// Matches TBP Python: `fx = tan(hfov/2) / zoom` in normalized [-1,1] space,
562    /// converted to pixel space: `fx_pixel = (width/2) / fx_normalized`.
563    ///
564    /// TBP ref: `transforms.py:440` `fx = np.tan(hfov[i] / 2.0) / zoom`
565    pub fn intrinsics(&self) -> CameraIntrinsics {
566        let base_hfov_rad = 90.0_f64.to_radians();
567        // TBP normalized focal length: fx_norm = tan(hfov/2) / zoom
568        let fx_norm = (base_hfov_rad / 2.0).tan() / self.zoom as f64;
569        // Convert to pixel focal length: fx_pixel = (width/2) / fx_norm
570        let fx = (self.width as f64 / 2.0) / fx_norm;
571        let fy = fx; // Square pixels (TBP adjusts fy for aspect ratio, but we use 64x64)
572
573        CameraIntrinsics {
574            focal_length: [fx, fy],
575            principal_point: [self.width as f64 / 2.0, self.height as f64 / 2.0],
576            image_size: [self.width, self.height],
577        }
578    }
579}
580
581/// Camera intrinsic parameters for 3D reconstruction.
582///
583/// Compatible with neocortx's VisionIntrinsics format.
584/// Uses f64 for TBP numerical precision compatibility.
585#[derive(Clone, Debug, PartialEq)]
586pub struct CameraIntrinsics {
587    /// Focal length in pixels (fx, fy)
588    pub focal_length: [f64; 2],
589    /// Principal point (cx, cy) - typically image center
590    pub principal_point: [f64; 2],
591    /// Image dimensions (width, height)
592    pub image_size: [u32; 2],
593}
594
595impl CameraIntrinsics {
596    /// Project a 3D point to 2D pixel coordinates.
597    pub fn project(&self, point: Vec3) -> Option<[f64; 2]> {
598        if point.z <= 0.0 {
599            return None;
600        }
601        let x = (point.x as f64 / point.z as f64) * self.focal_length[0] + self.principal_point[0];
602        let y = (point.y as f64 / point.z as f64) * self.focal_length[1] + self.principal_point[1];
603        Some([x, y])
604    }
605
606    /// Unproject a 2D pixel to a 3D point at given depth.
607    pub fn unproject(&self, pixel: [f64; 2], depth: f64) -> [f64; 3] {
608        let x = (pixel[0] - self.principal_point[0]) / self.focal_length[0] * depth;
609        let y = (pixel[1] - self.principal_point[1]) / self.focal_length[1] * depth;
610        [x, y, depth]
611    }
612}
613
614/// Output from headless rendering containing RGBA and depth data.
615#[derive(Clone, Debug)]
616pub struct RenderOutput {
617    /// RGBA pixel data in row-major order (width * height * 4 bytes)
618    pub rgba: Vec<u8>,
619    /// Depth values in meters, row-major order (width * height f64s)
620    /// Values are linear depth from camera, not normalized.
621    /// Uses f64 for TBP numerical precision compatibility.
622    pub depth: Vec<f64>,
623    /// Image width in pixels
624    pub width: u32,
625    /// Image height in pixels
626    pub height: u32,
627    /// Camera intrinsics used for this render
628    pub intrinsics: CameraIntrinsics,
629    /// Camera transform (world position and orientation)
630    pub camera_transform: Transform,
631    /// Object rotation applied during render
632    pub object_rotation: ObjectRotation,
633}
634
635impl RenderOutput {
636    /// Get RGBA pixel at (x, y). Returns None if out of bounds.
637    pub fn get_rgba(&self, x: u32, y: u32) -> Option<[u8; 4]> {
638        if x >= self.width || y >= self.height {
639            return None;
640        }
641        let idx = ((y * self.width + x) * 4) as usize;
642        Some([
643            self.rgba[idx],
644            self.rgba[idx + 1],
645            self.rgba[idx + 2],
646            self.rgba[idx + 3],
647        ])
648    }
649
650    /// Get depth value at (x, y) in meters. Returns None if out of bounds.
651    pub fn get_depth(&self, x: u32, y: u32) -> Option<f64> {
652        if x >= self.width || y >= self.height {
653            return None;
654        }
655        let idx = (y * self.width + x) as usize;
656        Some(self.depth[idx])
657    }
658
659    /// Get RGB pixel (without alpha) at (x, y).
660    pub fn get_rgb(&self, x: u32, y: u32) -> Option<[u8; 3]> {
661        self.get_rgba(x, y).map(|rgba| [rgba[0], rgba[1], rgba[2]])
662    }
663
664    /// Convert to neocortx-compatible image format: Vec<Vec<[u8; 3]>>
665    pub fn to_rgb_image(&self) -> Vec<Vec<[u8; 3]>> {
666        let mut image = Vec::with_capacity(self.height as usize);
667        for y in 0..self.height {
668            let mut row = Vec::with_capacity(self.width as usize);
669            for x in 0..self.width {
670                row.push(self.get_rgb(x, y).unwrap_or([0, 0, 0]));
671            }
672            image.push(row);
673        }
674        image
675    }
676
677    /// Convert depth to neocortx-compatible format: Vec<Vec<f64>>
678    pub fn to_depth_image(&self) -> Vec<Vec<f64>> {
679        let mut image = Vec::with_capacity(self.height as usize);
680        for y in 0..self.height {
681            let mut row = Vec::with_capacity(self.width as usize);
682            for x in 0..self.width {
683                row.push(self.get_depth(x, y).unwrap_or(0.0));
684            }
685            image.push(row);
686        }
687        image
688    }
689}
690
691/// Errors that can occur during rendering and file operations.
692#[derive(Debug, Clone)]
693pub enum RenderError {
694    /// Object mesh file not found
695    MeshNotFound(String),
696    /// Object texture file not found
697    TextureNotFound(String),
698    /// Generic file not found error
699    FileNotFound { path: String, reason: String },
700    /// File write failed
701    FileWriteFailed { path: String, reason: String },
702    /// Directory creation failed
703    DirectoryCreationFailed { path: String, reason: String },
704    /// Bevy rendering failed
705    RenderFailed(String),
706    /// Invalid configuration
707    InvalidConfig(String),
708    /// Invalid input parameters
709    InvalidInput(String),
710    /// JSON serialization/deserialization error
711    SerializationError(String),
712    /// Binary data parsing error
713    DataParsingError(String),
714    /// Render timeout
715    RenderTimeout { duration_secs: u64 },
716}
717
718impl std::fmt::Display for RenderError {
719    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
720        match self {
721            RenderError::MeshNotFound(path) => write!(f, "Mesh not found: {}", path),
722            RenderError::TextureNotFound(path) => write!(f, "Texture not found: {}", path),
723            RenderError::FileNotFound { path, reason } => {
724                write!(f, "File not found at {}: {}", path, reason)
725            }
726            RenderError::FileWriteFailed { path, reason } => {
727                write!(f, "Failed to write file {}: {}", path, reason)
728            }
729            RenderError::DirectoryCreationFailed { path, reason } => {
730                write!(f, "Failed to create directory {}: {}", path, reason)
731            }
732            RenderError::RenderFailed(msg) => write!(f, "Render failed: {}", msg),
733            RenderError::InvalidConfig(msg) => write!(f, "Invalid config: {}", msg),
734            RenderError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
735            RenderError::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
736            RenderError::DataParsingError(msg) => write!(f, "Data parsing error: {}", msg),
737            RenderError::RenderTimeout { duration_secs } => {
738                write!(f, "Render timeout after {} seconds", duration_secs)
739            }
740        }
741    }
742}
743
744impl std::error::Error for RenderError {}
745
746/// Render a YCB object to an in-memory buffer.
747///
748/// This is the primary API for headless rendering. It spawns a minimal Bevy app,
749/// renders a single frame, extracts the RGBA and depth data, and shuts down.
750///
751/// # Arguments
752/// * `object_dir` - Path to YCB object directory (e.g., "/tmp/ycb/003_cracker_box")
753/// * `camera_transform` - Camera position and orientation (use `generate_viewpoints`)
754/// * `object_rotation` - Rotation to apply to the object
755/// * `config` - Render configuration (resolution, depth range, etc.)
756///
757/// # Example
758/// ```ignore
759/// use bevy_sensor::{render_to_buffer, RenderConfig, ViewpointConfig, ObjectRotation};
760/// use std::path::Path;
761///
762/// let viewpoints = bevy_sensor::generate_viewpoints(&ViewpointConfig::default());
763/// let output = render_to_buffer(
764///     Path::new("/tmp/ycb/003_cracker_box"),
765///     &viewpoints[0],
766///     &ObjectRotation::identity(),
767///     &RenderConfig::tbp_default(),
768/// )?;
769/// ```
770pub fn render_to_buffer(
771    object_dir: &Path,
772    camera_transform: &Transform,
773    object_rotation: &ObjectRotation,
774    config: &RenderConfig,
775) -> Result<RenderOutput, RenderError> {
776    // Use the actual Bevy headless renderer
777    render::render_headless(object_dir, camera_transform, object_rotation, config)
778}
779
780/// Render all viewpoints and rotations for a YCB object.
781///
782/// Convenience function that renders all combinations of viewpoints and rotations.
783///
784/// # Arguments
785/// * `object_dir` - Path to YCB object directory
786/// * `viewpoint_config` - Viewpoint configuration (camera positions)
787/// * `rotations` - Object rotations to render
788/// * `render_config` - Render configuration
789///
790/// # Returns
791/// Vector of RenderOutput, one per viewpoint × rotation combination.
792pub fn render_all_viewpoints(
793    object_dir: &Path,
794    viewpoint_config: &ViewpointConfig,
795    rotations: &[ObjectRotation],
796    render_config: &RenderConfig,
797) -> Result<Vec<RenderOutput>, RenderError> {
798    let viewpoints = generate_viewpoints(viewpoint_config);
799    let mut outputs = Vec::with_capacity(viewpoints.len() * rotations.len());
800
801    for rotation in rotations {
802        for viewpoint in &viewpoints {
803            let output = render_to_buffer(object_dir, viewpoint, rotation, render_config)?;
804            outputs.push(output);
805        }
806    }
807
808    Ok(outputs)
809}
810
811/// Render with model caching support for efficient multi-viewpoint rendering.
812///
813/// This function tracks which models have been loaded and provides performance
814/// insights. It still spins up a fresh headless `App` per call. For workloads
815/// that render many frames against the same object/config, prefer
816/// `RenderSession` (homogeneous batches per episode) or `PersistentRenderer`
817/// (one frame per call, scene held loaded across calls — built for surface-
818/// policy feedback loops).
819///
820/// # Arguments
821/// * `object_dir` - Path to YCB object directory
822/// * `camera_transform` - Camera position and orientation
823/// * `object_rotation` - Rotation to apply to the object
824/// * `config` - Render configuration
825/// * `cache` - Model cache to track loaded assets
826///
827/// # Returns
828/// RenderOutput with rendered RGBA and depth data
829///
830/// # Example
831/// ```ignore
832/// use bevy_sensor::{render_to_buffer_cached, cache::ModelCache, RenderConfig, ObjectRotation};
833/// use std::path::PathBuf;
834///
835/// let mut cache = ModelCache::new();
836/// let object_dir = PathBuf::from("/tmp/ycb/003_cracker_box");
837/// let config = RenderConfig::tbp_default();
838/// let viewpoints = bevy_sensor::generate_viewpoints(&ViewpointConfig::default());
839///
840/// // First render: loads from disk and caches
841/// let output1 = render_to_buffer_cached(
842///     &object_dir,
843///     &viewpoints[0],
844///     &ObjectRotation::identity(),
845///     &config,
846///     &mut cache,
847/// )?;
848///
849/// // Subsequent renders: tracks in cache
850/// for viewpoint in &viewpoints[1..] {
851///     let output = render_to_buffer_cached(
852///         &object_dir,
853///         viewpoint,
854///         &ObjectRotation::identity(),
855///         &config,
856///         &mut cache,
857///     )?;
858/// }
859/// ```
860///
861/// # Note
862/// This function uses the same rendering engine as `render_to_buffer()`. The current
863/// batch API preserves ordering and output structure but does not yet reuse a live
864/// Bevy renderer across calls.
865///
866/// ```ignore
867/// use bevy_sensor::{render_batch, batch::BatchRenderRequest, BatchRenderConfig, RenderConfig, ObjectRotation};
868///
869/// let requests: Vec<_> = viewpoints.iter().map(|vp| {
870///     BatchRenderRequest {
871///         object_dir: object_dir.clone(),
872///         viewpoint: *vp,
873///         object_rotation: ObjectRotation::identity(),
874///         render_config: RenderConfig::tbp_default(),
875///     }
876/// }).collect();
877///
878/// let outputs = render_batch(requests, &BatchRenderConfig::default())?;
879/// ```
880pub fn render_to_buffer_cached(
881    object_dir: &Path,
882    camera_transform: &Transform,
883    object_rotation: &ObjectRotation,
884    config: &RenderConfig,
885    cache: &mut cache::ModelCache,
886) -> Result<RenderOutput, RenderError> {
887    let mesh_path = object_dir.join("google_16k/textured.obj");
888    let texture_path = object_dir.join("google_16k/texture_map.png");
889
890    // Track in cache
891    cache.cache_scene(mesh_path.clone());
892    cache.cache_texture(texture_path.clone());
893
894    // Render using standard pipeline
895    render::render_headless(object_dir, camera_transform, object_rotation, config)
896}
897
898/// Render directly to files (for subprocess mode).
899///
900/// This function is designed for subprocess rendering where the process will exit
901/// after rendering. It saves RGBA and depth data directly to the specified files
902/// before the process terminates.
903///
904/// # Arguments
905/// * `object_dir` - Path to YCB object directory
906/// * `camera_transform` - Camera position and orientation
907/// * `object_rotation` - Rotation to apply to the object
908/// * `config` - Render configuration
909/// * `rgba_path` - Output path for RGBA PNG
910/// * `depth_path` - Output path for depth data (raw f32 bytes)
911///
912/// # Note
913/// This function may call `std::process::exit(0)` and not return.
914pub fn render_to_files(
915    object_dir: &Path,
916    camera_transform: &Transform,
917    object_rotation: &ObjectRotation,
918    config: &RenderConfig,
919    rgba_path: &Path,
920    depth_path: &Path,
921) -> Result<(), RenderError> {
922    render::render_to_files(
923        object_dir,
924        camera_transform,
925        object_rotation,
926        config,
927        rgba_path,
928        depth_path,
929    )
930}
931
932// Re-export batch types for convenient API access
933pub use batch::{
934    BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
935    BatchState, RenderStatus,
936};
937
938/// Persistent batch render session. See the module docs in `render::RenderSession`
939/// for lifetime, thread-affinity, and config-invariance guarantees.
940pub use render::RenderSession;
941
942/// Per-step persistent renderer for feedback loops. See the module docs in
943/// `render::PersistentRenderer` for lifetime, thread-affinity, and
944/// object/config-invariance guarantees. Built for the surface-policy use case
945/// in neocortx where a fixed object is rendered from a moving camera many
946/// times per episode (issue #65).
947pub use render::PersistentRenderer;
948
949/// Create a new batch renderer helper for multi-viewpoint workflows.
950///
951/// The current implementation stores queued requests and executes them sequentially via
952/// `render_to_buffer()`. It does not yet keep a persistent Bevy app alive across renders.
953///
954/// # Arguments
955/// * `config` - Batch rendering configuration
956///
957/// # Returns
958/// A BatchRenderer instance ready to queue render requests
959///
960/// # Example
961/// ```ignore
962/// use bevy_sensor::{create_batch_renderer, queue_render_request, render_next_in_batch, BatchRenderConfig};
963///
964/// let mut renderer = create_batch_renderer(&BatchRenderConfig::default())?;
965/// ```
966pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
967    Ok(BatchRenderer::new(config.clone()))
968}
969
970/// Queue a render request for batch processing.
971///
972/// Adds a render request to the batch queue. Requests are processed in order
973/// when you call render_next_in_batch().
974///
975/// # Arguments
976/// * `renderer` - The batch renderer instance
977/// * `request` - The render request
978///
979/// # Returns
980/// Ok if queued successfully, Err if queue is full
981///
982/// # Example
983/// ```ignore
984/// use bevy_sensor::{batch::BatchRenderRequest, RenderConfig, ObjectRotation};
985/// use std::path::PathBuf;
986///
987/// queue_render_request(&mut renderer, BatchRenderRequest {
988///     object_dir: PathBuf::from("/tmp/ycb/003_cracker_box"),
989///     viewpoint: camera_transform,
990///     object_rotation: ObjectRotation::identity(),
991///     render_config: RenderConfig::tbp_default(),
992/// })?;
993/// ```
994pub fn queue_render_request(
995    renderer: &mut BatchRenderer,
996    request: BatchRenderRequest,
997) -> Result<(), RenderError> {
998    renderer
999        .queue_request(request)
1000        .map_err(|e| RenderError::RenderFailed(e.to_string()))
1001}
1002
1003/// Process and execute the next render in the batch queue.
1004///
1005/// Executes a single queued request via `render_to_buffer()`. Returns None when the queue
1006/// is empty. Use this in a loop to process all queued renders in a stable order.
1007///
1008/// # Arguments
1009/// * `renderer` - The batch renderer instance
1010/// * `timeout_ms` - Timeout in milliseconds for this render
1011///
1012/// # Returns
1013/// Some(output) if a render completed, None if queue is empty
1014///
1015/// # Example
1016/// ```ignore
1017/// loop {
1018///     match render_next_in_batch(&mut renderer, 500)? {
1019///         Some(output) => println!("Render complete: {:?}", output.status),
1020///         None => break, // All renders done
1021///     }
1022/// }
1023/// ```
1024pub fn render_next_in_batch(
1025    renderer: &mut BatchRenderer,
1026    _timeout_ms: u32,
1027) -> Result<Option<BatchRenderOutput>, RenderError> {
1028    if let Some(request) = renderer.pending_requests.pop_front() {
1029        let output = render_to_buffer(
1030            &request.object_dir,
1031            &request.viewpoint,
1032            &request.object_rotation,
1033            &request.render_config,
1034        )?;
1035        let batch_output = BatchRenderOutput::from_render_output(request, output);
1036        renderer.completed_results.push(batch_output.clone());
1037        renderer.renders_processed += 1;
1038        Ok(Some(batch_output))
1039    } else {
1040        Ok(None)
1041    }
1042}
1043
1044/// Render multiple requests in batch (convenience function).
1045///
1046/// Queues all requests and executes them in batch, returning all results.
1047/// Simpler than manage queue + loop for one-off batches.
1048///
1049/// # Arguments
1050/// * `requests` - Vector of render requests
1051/// * `config` - Batch rendering configuration
1052///
1053/// # Returns
1054/// Vector of BatchRenderOutput results in same order as input
1055///
1056/// # Example
1057/// ```ignore
1058/// use bevy_sensor::{render_batch, batch::BatchRenderRequest, BatchRenderConfig};
1059///
1060/// let results = render_batch(requests, &BatchRenderConfig::default())?;
1061/// ```
1062pub fn render_batch(
1063    requests: Vec<BatchRenderRequest>,
1064    config: &BatchRenderConfig,
1065) -> Result<Vec<BatchRenderOutput>, RenderError> {
1066    if requests.is_empty() {
1067        return Ok(Vec::new());
1068    }
1069
1070    if requests.len() > 1 && requests_share_batch_context(&requests) {
1071        let first_request = requests[0].clone();
1072        let viewpoints: Vec<Transform> = requests.iter().map(|request| request.viewpoint).collect();
1073        let outputs = render::render_headless_sequence(
1074            &first_request.object_dir,
1075            &viewpoints,
1076            &first_request.object_rotation,
1077            &first_request.render_config,
1078        )?;
1079
1080        return Ok(requests
1081            .into_iter()
1082            .zip(outputs)
1083            .map(|(request, output)| BatchRenderOutput::from_render_output(request, output))
1084            .collect());
1085    }
1086
1087    let mut renderer = create_batch_renderer(config)?;
1088
1089    // Queue all requests
1090    for request in requests {
1091        queue_render_request(&mut renderer, request)?;
1092    }
1093
1094    // Execute all and collect results
1095    let mut results = Vec::new();
1096    while let Some(output) = render_next_in_batch(&mut renderer, config.frame_timeout_ms)? {
1097        results.push(output);
1098    }
1099
1100    Ok(results)
1101}
1102
1103fn requests_share_batch_context(requests: &[BatchRenderRequest]) -> bool {
1104    let Some(first) = requests.first() else {
1105        return true;
1106    };
1107
1108    requests.iter().all(|request| {
1109        request.object_dir == first.object_dir
1110            && request.object_rotation == first.object_rotation
1111            && request.render_config == first.render_config
1112    })
1113}
1114
1115// Re-export bevy types that consumers will need
1116pub use bevy::prelude::{Quat, Transform, Vec3};
1117
1118#[cfg(test)]
1119mod tests {
1120    use super::*;
1121
1122    #[test]
1123    fn test_object_rotation_identity() {
1124        let rot = ObjectRotation::identity();
1125        assert_eq!(rot.pitch, 0.0);
1126        assert_eq!(rot.yaw, 0.0);
1127        assert_eq!(rot.roll, 0.0);
1128    }
1129
1130    #[test]
1131    fn test_object_rotation_from_array() {
1132        let rot = ObjectRotation::from_array([10.0, 20.0, 30.0]);
1133        assert_eq!(rot.pitch, 10.0);
1134        assert_eq!(rot.yaw, 20.0);
1135        assert_eq!(rot.roll, 30.0);
1136    }
1137
1138    #[test]
1139    fn test_requests_share_batch_context_for_homogeneous_batch() {
1140        let config = RenderConfig::tbp_default();
1141        let request = BatchRenderRequest {
1142            object_dir: "/tmp/ycb/003_cracker_box".into(),
1143            viewpoint: Transform::IDENTITY,
1144            object_rotation: ObjectRotation::identity(),
1145            render_config: config.clone(),
1146        };
1147
1148        assert!(requests_share_batch_context(&[
1149            request.clone(),
1150            BatchRenderRequest {
1151                viewpoint: Transform::from_xyz(1.0, 0.0, 0.0),
1152                ..request
1153            },
1154        ]));
1155    }
1156
1157    #[test]
1158    fn test_requests_share_batch_context_rejects_mixed_objects() {
1159        let config = RenderConfig::tbp_default();
1160        let request = BatchRenderRequest {
1161            object_dir: "/tmp/ycb/003_cracker_box".into(),
1162            viewpoint: Transform::IDENTITY,
1163            object_rotation: ObjectRotation::identity(),
1164            render_config: config.clone(),
1165        };
1166
1167        assert!(!requests_share_batch_context(&[
1168            request.clone(),
1169            BatchRenderRequest {
1170                object_dir: "/tmp/ycb/005_tomato_soup_can".into(),
1171                ..request
1172            },
1173        ]));
1174    }
1175
1176    #[test]
1177    fn test_tbp_benchmark_rotations() {
1178        let rotations = ObjectRotation::tbp_benchmark_rotations();
1179        assert_eq!(rotations.len(), 3);
1180        assert_eq!(rotations[0], ObjectRotation::from_array([0.0, 0.0, 0.0]));
1181        assert_eq!(rotations[1], ObjectRotation::from_array([0.0, 90.0, 0.0]));
1182        assert_eq!(rotations[2], ObjectRotation::from_array([0.0, 180.0, 0.0]));
1183    }
1184
1185    #[test]
1186    fn test_tbp_known_orientations_count() {
1187        let orientations = ObjectRotation::tbp_known_orientations();
1188        assert_eq!(orientations.len(), 14);
1189    }
1190
1191    #[test]
1192    fn test_rotation_to_quat() {
1193        let rot = ObjectRotation::identity();
1194        let quat = rot.to_quat();
1195        // Identity quaternion should be approximately (1, 0, 0, 0)
1196        assert!((quat.w - 1.0).abs() < 0.001);
1197        assert!(quat.x.abs() < 0.001);
1198        assert!(quat.y.abs() < 0.001);
1199        assert!(quat.z.abs() < 0.001);
1200    }
1201
1202    #[test]
1203    fn test_rotation_90_yaw() {
1204        let rot = ObjectRotation::new(0.0, 90.0, 0.0);
1205        let quat = rot.to_quat();
1206        // 90° Y rotation: w ≈ 0.707, y ≈ 0.707
1207        assert!((quat.w - 0.707).abs() < 0.01);
1208        assert!((quat.y - 0.707).abs() < 0.01);
1209    }
1210
1211    #[test]
1212    fn test_viewpoint_config_default() {
1213        let config = ViewpointConfig::default();
1214        assert_eq!(config.radius, 0.5);
1215        assert_eq!(config.yaw_count, 8);
1216        assert_eq!(config.pitch_angles_deg.len(), 3);
1217    }
1218
1219    #[test]
1220    fn test_viewpoint_count() {
1221        let config = ViewpointConfig::default();
1222        assert_eq!(config.viewpoint_count(), 24); // 8 × 3
1223    }
1224
1225    #[test]
1226    fn test_generate_viewpoints_count() {
1227        let config = ViewpointConfig::default();
1228        let viewpoints = generate_viewpoints(&config);
1229        assert_eq!(viewpoints.len(), 24);
1230    }
1231
1232    #[test]
1233    fn test_viewpoints_spherical_radius() {
1234        let config = ViewpointConfig::default();
1235        let viewpoints = generate_viewpoints(&config);
1236
1237        for (i, transform) in viewpoints.iter().enumerate() {
1238            let actual_radius = transform.translation.length();
1239            assert!(
1240                (actual_radius - config.radius).abs() < 0.001,
1241                "Viewpoint {} has incorrect radius: {} (expected {})",
1242                i,
1243                actual_radius,
1244                config.radius
1245            );
1246        }
1247    }
1248
1249    #[test]
1250    fn test_viewpoints_looking_at_origin() {
1251        let config = ViewpointConfig::default();
1252        let viewpoints = generate_viewpoints(&config);
1253
1254        for (i, transform) in viewpoints.iter().enumerate() {
1255            let forward = transform.forward();
1256            let to_origin = (Vec3::ZERO - transform.translation).normalize();
1257            let dot = forward.dot(to_origin);
1258            assert!(
1259                dot > 0.99,
1260                "Viewpoint {} not looking at origin, dot product: {}",
1261                i,
1262                dot
1263            );
1264        }
1265    }
1266
1267    #[test]
1268    fn test_sensor_config_default() {
1269        let config = SensorConfig::default();
1270        assert_eq!(config.object_rotations.len(), 1);
1271        assert_eq!(config.total_captures(), 24);
1272    }
1273
1274    #[test]
1275    fn test_sensor_config_tbp_benchmark() {
1276        let config = SensorConfig::tbp_benchmark();
1277        assert_eq!(config.object_rotations.len(), 3);
1278        assert_eq!(config.total_captures(), 72); // 3 rotations × 24 viewpoints
1279    }
1280
1281    #[test]
1282    fn test_sensor_config_tbp_full() {
1283        let config = SensorConfig::tbp_full_training();
1284        assert_eq!(config.object_rotations.len(), 14);
1285        assert_eq!(config.total_captures(), 336); // 14 rotations × 24 viewpoints
1286    }
1287
1288    #[test]
1289    fn test_ycb_representative_objects() {
1290        // Verify representative objects are defined
1291        assert_eq!(crate::ycb::REPRESENTATIVE_OBJECTS.len(), 3);
1292        assert!(crate::ycb::REPRESENTATIVE_OBJECTS.contains(&"003_cracker_box"));
1293    }
1294
1295    #[test]
1296    fn test_ycb_tbp_standard_objects() {
1297        assert_eq!(crate::ycb::TBP_STANDARD_OBJECTS.len(), 10);
1298        assert!(crate::ycb::TBP_STANDARD_OBJECTS.contains(&"025_mug"));
1299    }
1300
1301    #[test]
1302    fn test_ycb_tbp_similar_objects() {
1303        assert_eq!(crate::ycb::TBP_SIMILAR_OBJECTS.len(), 10);
1304        assert!(crate::ycb::TBP_SIMILAR_OBJECTS.contains(&"003_cracker_box"));
1305    }
1306
1307    #[test]
1308    fn test_ycb_object_mesh_path() {
1309        let path = crate::ycb::object_mesh_path("/tmp/ycb", "003_cracker_box");
1310        assert_eq!(
1311            path,
1312            std::path::Path::new("/tmp/ycb")
1313                .join("003_cracker_box")
1314                .join("google_16k")
1315                .join("textured.obj")
1316        );
1317    }
1318
1319    #[test]
1320    fn test_ycb_object_texture_path() {
1321        let path = crate::ycb::object_texture_path("/tmp/ycb", "003_cracker_box");
1322        assert_eq!(
1323            path,
1324            std::path::Path::new("/tmp/ycb")
1325                .join("003_cracker_box")
1326                .join("google_16k")
1327                .join("texture_map.png")
1328        );
1329    }
1330
1331    // =========================================================================
1332    // Headless Rendering API Tests
1333    // =========================================================================
1334
1335    #[test]
1336    fn test_render_config_tbp_default() {
1337        let config = RenderConfig::tbp_default();
1338        // TBP spec: 64x64 patch sensor resolution
1339        assert_eq!(config.width, 64);
1340        assert_eq!(config.height, 64);
1341        // Zoom is a divisor in the FOV formula — must be positive
1342        assert!(config.zoom > 0.0);
1343        // Clipping planes must form a valid, positive range
1344        assert!(config.near_plane > 0.0);
1345        assert!(config.far_plane > config.near_plane);
1346    }
1347
1348    #[test]
1349    fn test_render_config_preview() {
1350        let config = RenderConfig::preview();
1351        assert_eq!(config.width, 256);
1352        assert_eq!(config.height, 256);
1353    }
1354
1355    #[test]
1356    fn test_render_config_default_is_tbp() {
1357        let default = RenderConfig::default();
1358        let tbp = RenderConfig::tbp_default();
1359        assert_eq!(default.width, tbp.width);
1360        assert_eq!(default.height, tbp.height);
1361    }
1362
1363    #[test]
1364    fn test_render_config_fov() {
1365        let config = RenderConfig::tbp_default();
1366        let fov = config.fov_radians();
1367        // FOV must be a valid positive angle strictly less than π for any
1368        // positive zoom — no cameras with ≥180° FOV.
1369        assert!(fov > 0.0);
1370        assert!(fov < PI);
1371
1372        // Zoom in should reduce FOV (tighter view).
1373        let zoomed = RenderConfig {
1374            zoom: config.zoom * 2.0,
1375            ..config
1376        };
1377        assert!(zoomed.fov_radians() < fov);
1378    }
1379
1380    #[test]
1381    fn test_render_config_intrinsics() {
1382        let config = RenderConfig::tbp_default();
1383        let intrinsics = config.intrinsics();
1384
1385        // Image size matches config; principal point at image center.
1386        assert_eq!(intrinsics.image_size, [config.width, config.height]);
1387        assert_eq!(
1388            intrinsics.principal_point,
1389            [config.width as f64 / 2.0, config.height as f64 / 2.0]
1390        );
1391        // Square pixels: fx == fy.
1392        assert_eq!(intrinsics.focal_length[0], intrinsics.focal_length[1]);
1393        assert!(intrinsics.focal_length[0] > 0.0);
1394    }
1395
1396    #[test]
1397    fn test_camera_intrinsics_project() {
1398        let intrinsics = CameraIntrinsics {
1399            focal_length: [100.0, 100.0],
1400            principal_point: [32.0, 32.0],
1401            image_size: [64, 64],
1402        };
1403
1404        // Point at origin of camera frame projects to principal point
1405        let center = intrinsics.project(Vec3::new(0.0, 0.0, 1.0));
1406        assert!(center.is_some());
1407        let [x, y] = center.unwrap();
1408        assert!((x - 32.0).abs() < 0.001);
1409        assert!((y - 32.0).abs() < 0.001);
1410
1411        // Point behind camera returns None
1412        let behind = intrinsics.project(Vec3::new(0.0, 0.0, -1.0));
1413        assert!(behind.is_none());
1414    }
1415
1416    #[test]
1417    fn test_camera_intrinsics_unproject() {
1418        let intrinsics = CameraIntrinsics {
1419            focal_length: [100.0, 100.0],
1420            principal_point: [32.0, 32.0],
1421            image_size: [64, 64],
1422        };
1423
1424        // Unproject principal point at depth 1.0
1425        let point = intrinsics.unproject([32.0, 32.0], 1.0);
1426        assert!((point[0]).abs() < 0.001); // x
1427        assert!((point[1]).abs() < 0.001); // y
1428        assert!((point[2] - 1.0).abs() < 0.001); // z
1429    }
1430
1431    #[test]
1432    fn test_render_output_get_rgba() {
1433        let output = RenderOutput {
1434            rgba: vec![
1435                255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1436            ],
1437            depth: vec![1.0, 2.0, 3.0, 4.0],
1438            width: 2,
1439            height: 2,
1440            intrinsics: RenderConfig::tbp_default().intrinsics(),
1441            camera_transform: Transform::IDENTITY,
1442            object_rotation: ObjectRotation::identity(),
1443        };
1444
1445        // Top-left: red
1446        assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
1447        // Top-right: green
1448        assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
1449        // Bottom-left: blue
1450        assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
1451        // Bottom-right: white
1452        assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
1453        // Out of bounds
1454        assert_eq!(output.get_rgba(2, 0), None);
1455    }
1456
1457    #[test]
1458    fn test_render_output_get_depth() {
1459        let output = RenderOutput {
1460            rgba: vec![0u8; 16],
1461            depth: vec![1.0, 2.0, 3.0, 4.0],
1462            width: 2,
1463            height: 2,
1464            intrinsics: RenderConfig::tbp_default().intrinsics(),
1465            camera_transform: Transform::IDENTITY,
1466            object_rotation: ObjectRotation::identity(),
1467        };
1468
1469        assert_eq!(output.get_depth(0, 0), Some(1.0));
1470        assert_eq!(output.get_depth(1, 0), Some(2.0));
1471        assert_eq!(output.get_depth(0, 1), Some(3.0));
1472        assert_eq!(output.get_depth(1, 1), Some(4.0));
1473        assert_eq!(output.get_depth(2, 0), None);
1474    }
1475
1476    #[test]
1477    fn test_render_output_to_rgb_image() {
1478        let output = RenderOutput {
1479            rgba: vec![
1480                255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1481            ],
1482            depth: vec![1.0, 2.0, 3.0, 4.0],
1483            width: 2,
1484            height: 2,
1485            intrinsics: RenderConfig::tbp_default().intrinsics(),
1486            camera_transform: Transform::IDENTITY,
1487            object_rotation: ObjectRotation::identity(),
1488        };
1489
1490        let image = output.to_rgb_image();
1491        assert_eq!(image.len(), 2); // 2 rows
1492        assert_eq!(image[0].len(), 2); // 2 columns
1493        assert_eq!(image[0][0], [255, 0, 0]); // Red
1494        assert_eq!(image[0][1], [0, 255, 0]); // Green
1495        assert_eq!(image[1][0], [0, 0, 255]); // Blue
1496        assert_eq!(image[1][1], [255, 255, 255]); // White
1497    }
1498
1499    #[test]
1500    fn test_render_output_to_depth_image() {
1501        let output = RenderOutput {
1502            rgba: vec![0u8; 16],
1503            depth: vec![1.0, 2.0, 3.0, 4.0],
1504            width: 2,
1505            height: 2,
1506            intrinsics: RenderConfig::tbp_default().intrinsics(),
1507            camera_transform: Transform::IDENTITY,
1508            object_rotation: ObjectRotation::identity(),
1509        };
1510
1511        let depth_image = output.to_depth_image();
1512        assert_eq!(depth_image.len(), 2);
1513        assert_eq!(depth_image[0], vec![1.0, 2.0]);
1514        assert_eq!(depth_image[1], vec![3.0, 4.0]);
1515    }
1516
1517    #[test]
1518    fn test_render_error_display() {
1519        let err = RenderError::MeshNotFound("/path/to/mesh.obj".to_string());
1520        assert!(err.to_string().contains("Mesh not found"));
1521        assert!(err.to_string().contains("/path/to/mesh.obj"));
1522    }
1523
1524    // =========================================================================
1525    // Edge Case Tests
1526    // =========================================================================
1527
1528    #[test]
1529    fn test_object_rotation_extreme_angles() {
1530        // Test angles beyond 360 degrees
1531        let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
1532        let quat = rot.to_quat();
1533        // Quaternion should still be valid (normalized)
1534        assert!((quat.length() - 1.0).abs() < 0.001);
1535    }
1536
1537    #[test]
1538    fn test_object_rotation_to_transform() {
1539        let rot = ObjectRotation::new(45.0, 90.0, 0.0);
1540        let transform = rot.to_transform();
1541        // Transform should have no translation
1542        assert_eq!(transform.translation, Vec3::ZERO);
1543        // Should have rotation
1544        assert!(transform.rotation != Quat::IDENTITY);
1545    }
1546
1547    #[test]
1548    fn test_viewpoint_config_single_viewpoint() {
1549        let config = ViewpointConfig {
1550            radius: 1.0,
1551            yaw_count: 1,
1552            pitch_angles_deg: vec![0.0],
1553        };
1554        assert_eq!(config.viewpoint_count(), 1);
1555        let viewpoints = generate_viewpoints(&config);
1556        assert_eq!(viewpoints.len(), 1);
1557        // Single viewpoint at yaw=0, pitch=0 should be at (0, 0, radius)
1558        let pos = viewpoints[0].translation;
1559        assert!((pos.x).abs() < 0.001);
1560        assert!((pos.y).abs() < 0.001);
1561        assert!((pos.z - 1.0).abs() < 0.001);
1562    }
1563
1564    #[test]
1565    fn test_viewpoint_radius_scaling() {
1566        let config1 = ViewpointConfig {
1567            radius: 0.5,
1568            yaw_count: 4,
1569            pitch_angles_deg: vec![0.0],
1570        };
1571        let config2 = ViewpointConfig {
1572            radius: 2.0,
1573            yaw_count: 4,
1574            pitch_angles_deg: vec![0.0],
1575        };
1576
1577        let v1 = generate_viewpoints(&config1);
1578        let v2 = generate_viewpoints(&config2);
1579
1580        // Viewpoints should scale proportionally
1581        for (vp1, vp2) in v1.iter().zip(v2.iter()) {
1582            let ratio = vp2.translation.length() / vp1.translation.length();
1583            assert!((ratio - 4.0).abs() < 0.01); // 2.0 / 0.5 = 4.0
1584        }
1585    }
1586
1587    #[test]
1588    fn test_camera_intrinsics_project_at_z_zero() {
1589        let intrinsics = CameraIntrinsics {
1590            focal_length: [100.0, 100.0],
1591            principal_point: [32.0, 32.0],
1592            image_size: [64, 64],
1593        };
1594
1595        // Point at z=0 should return None (division by zero protection)
1596        let result = intrinsics.project(Vec3::new(1.0, 1.0, 0.0));
1597        assert!(result.is_none());
1598    }
1599
1600    #[test]
1601    fn test_camera_intrinsics_roundtrip() {
1602        let intrinsics = CameraIntrinsics {
1603            focal_length: [100.0, 100.0],
1604            principal_point: [32.0, 32.0],
1605            image_size: [64, 64],
1606        };
1607
1608        // Project a 3D point
1609        let original = Vec3::new(0.5, -0.3, 2.0);
1610        let projected = intrinsics.project(original).unwrap();
1611
1612        // Unproject back with the same depth (convert f32 to f64)
1613        let unprojected = intrinsics.unproject(projected, original.z as f64);
1614
1615        // Should get back approximately the same point
1616        assert!((unprojected[0] - original.x as f64).abs() < 0.001); // x
1617        assert!((unprojected[1] - original.y as f64).abs() < 0.001); // y
1618        assert!((unprojected[2] - original.z as f64).abs() < 0.001); // z
1619    }
1620
1621    #[test]
1622    fn test_render_output_empty() {
1623        let output = RenderOutput {
1624            rgba: vec![],
1625            depth: vec![],
1626            width: 0,
1627            height: 0,
1628            intrinsics: RenderConfig::tbp_default().intrinsics(),
1629            camera_transform: Transform::IDENTITY,
1630            object_rotation: ObjectRotation::identity(),
1631        };
1632
1633        // Should handle empty gracefully
1634        assert_eq!(output.get_rgba(0, 0), None);
1635        assert_eq!(output.get_depth(0, 0), None);
1636        assert!(output.to_rgb_image().is_empty());
1637        assert!(output.to_depth_image().is_empty());
1638    }
1639
1640    #[test]
1641    fn test_render_output_1x1() {
1642        let output = RenderOutput {
1643            rgba: vec![128, 64, 32, 255],
1644            depth: vec![0.5],
1645            width: 1,
1646            height: 1,
1647            intrinsics: RenderConfig::tbp_default().intrinsics(),
1648            camera_transform: Transform::IDENTITY,
1649            object_rotation: ObjectRotation::identity(),
1650        };
1651
1652        assert_eq!(output.get_rgba(0, 0), Some([128, 64, 32, 255]));
1653        assert_eq!(output.get_depth(0, 0), Some(0.5));
1654        assert_eq!(output.get_rgb(0, 0), Some([128, 64, 32]));
1655
1656        let rgb_img = output.to_rgb_image();
1657        assert_eq!(rgb_img.len(), 1);
1658        assert_eq!(rgb_img[0].len(), 1);
1659        assert_eq!(rgb_img[0][0], [128, 64, 32]);
1660    }
1661
1662    #[test]
1663    fn test_render_config_high_res() {
1664        let config = RenderConfig::high_res();
1665        assert_eq!(config.width, 512);
1666        assert_eq!(config.height, 512);
1667
1668        let intrinsics = config.intrinsics();
1669        assert_eq!(intrinsics.image_size, [512, 512]);
1670        assert_eq!(intrinsics.principal_point, [256.0, 256.0]);
1671    }
1672
1673    #[test]
1674    fn test_render_config_zoom_affects_fov() {
1675        // The formula fov = 2·atan(tan(base_hfov/2)/zoom) has an exact
1676        // invariant: tan(fov/2) * zoom is constant. So doubling zoom
1677        // halves tan(fov/2). (This is NOT the same as halving fov itself,
1678        // which only holds as a small-angle approximation.)
1679        let base = RenderConfig {
1680            zoom: 2.0,
1681            ..RenderConfig::tbp_default()
1682        };
1683        let doubled = RenderConfig {
1684            zoom: 4.0,
1685            ..RenderConfig::tbp_default()
1686        };
1687
1688        // Higher zoom → tighter FOV (monotonicity).
1689        assert!(doubled.fov_radians() < base.fov_radians());
1690
1691        // Exact invariant: tan(fov/2) scales as 1/zoom.
1692        let base_half_tan = (base.fov_radians() / 2.0).tan();
1693        let doubled_half_tan = (doubled.fov_radians() / 2.0).tan();
1694        assert!((base_half_tan / doubled_half_tan - 2.0).abs() < 1e-4);
1695    }
1696
1697    #[test]
1698    fn test_render_config_zoom_affects_intrinsics() {
1699        // The formula fx = (width/2)·zoom/tan(base_hfov/2) is linear in
1700        // zoom for fixed width/base_hfov, so fx/zoom is constant.
1701        let a = RenderConfig {
1702            zoom: 2.0,
1703            ..RenderConfig::tbp_default()
1704        };
1705        let b = RenderConfig {
1706            zoom: 4.0,
1707            ..RenderConfig::tbp_default()
1708        };
1709
1710        let fx_a = a.intrinsics().focal_length[0];
1711        let fx_b = b.intrinsics().focal_length[0];
1712
1713        // Monotonic: higher zoom → larger focal length.
1714        assert!(fx_b > fx_a);
1715
1716        // Exact linearity: fx/zoom is constant across configs.
1717        assert!((fx_a / a.zoom as f64 - fx_b / b.zoom as f64).abs() < 1e-9);
1718    }
1719
1720    #[test]
1721    fn test_lighting_config_variants() {
1722        let default = LightingConfig::default();
1723        let bright = LightingConfig::bright();
1724        let soft = LightingConfig::soft();
1725        let unlit = LightingConfig::unlit();
1726
1727        // Bright should have higher intensity than default
1728        assert!(bright.key_light_intensity > default.key_light_intensity);
1729
1730        // Unlit should have no point lights
1731        assert_eq!(unlit.key_light_intensity, 0.0);
1732        assert_eq!(unlit.fill_light_intensity, 0.0);
1733        assert_eq!(unlit.ambient_brightness, 1.0);
1734
1735        // Soft should have lower intensity
1736        assert!(soft.key_light_intensity < default.key_light_intensity);
1737    }
1738
1739    #[test]
1740    fn test_all_render_error_variants() {
1741        let errors = vec![
1742            RenderError::MeshNotFound("mesh.obj".to_string()),
1743            RenderError::TextureNotFound("texture.png".to_string()),
1744            RenderError::RenderFailed("GPU error".to_string()),
1745            RenderError::InvalidConfig("bad config".to_string()),
1746        ];
1747
1748        for err in errors {
1749            // All variants should have Display impl
1750            let msg = err.to_string();
1751            assert!(!msg.is_empty());
1752        }
1753    }
1754
1755    #[test]
1756    fn test_tbp_known_orientations_unique() {
1757        let orientations = ObjectRotation::tbp_known_orientations();
1758
1759        // All 14 orientations should produce unique quaternions
1760        let quats: Vec<Quat> = orientations.iter().map(|r| r.to_quat()).collect();
1761
1762        for (i, q1) in quats.iter().enumerate() {
1763            for (j, q2) in quats.iter().enumerate() {
1764                if i != j {
1765                    // Quaternions should be different (accounting for q == -q equivalence)
1766                    let dot = q1.dot(*q2).abs();
1767                    assert!(
1768                        dot < 0.999,
1769                        "Orientations {} and {} produce same quaternion",
1770                        i,
1771                        j
1772                    );
1773                }
1774            }
1775        }
1776    }
1777}