1use bevy::prelude::*;
54use std::f32::consts::PI;
55use std::path::Path;
56
57mod render;
60
61pub mod batch;
63
64pub mod backend;
66
67pub mod cache;
69
70pub mod fixtures;
72
73pub use ycbust::{
75 self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
76 TBP_STANDARD_OBJECTS,
77};
78
79pub 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 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 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 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 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 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 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
151pub fn initialize() {
185 use std::sync::atomic::{AtomicBool, Ordering};
187 static INITIALIZED: AtomicBool = AtomicBool::new(false);
188
189 if !INITIALIZED.swap(true, Ordering::SeqCst) {
190 let config = backend::BackendConfig::new();
192 config.apply_env();
193 }
194}
195
196#[derive(Clone, Debug, PartialEq)]
199pub struct ObjectRotation {
200 pub pitch: f64,
202 pub yaw: f64,
204 pub roll: f64,
206}
207
208impl ObjectRotation {
209 pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
211 Self { pitch, yaw, roll }
212 }
213
214 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 pub fn identity() -> Self {
225 Self::new(0.0, 0.0, 0.0)
226 }
227
228 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 pub fn tbp_known_orientations() -> Vec<Self> {
241 vec![
242 Self::from_array([0.0, 0.0, 0.0]), Self::from_array([0.0, 90.0, 0.0]), Self::from_array([0.0, 180.0, 0.0]), Self::from_array([0.0, 270.0, 0.0]), Self::from_array([90.0, 0.0, 0.0]), Self::from_array([-90.0, 0.0, 0.0]), 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 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 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#[derive(Clone, Debug)]
286pub struct ViewpointConfig {
287 pub radius: f32,
289 pub yaw_count: usize,
291 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 pitch_angles_deg: vec![-30.0, 0.0, 30.0],
303 }
304 }
305}
306
307impl ViewpointConfig {
308 pub fn viewpoint_count(&self) -> usize {
310 self.yaw_count * self.pitch_angles_deg.len()
311 }
312}
313
314#[derive(Clone, Debug, Resource)]
316pub struct SensorConfig {
317 pub viewpoints: ViewpointConfig,
319 pub object_rotations: Vec<ObjectRotation>,
321 pub output_dir: String,
323 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 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 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 pub fn total_captures(&self) -> usize {
361 self.viewpoints.viewpoint_count() * self.object_rotations.len()
362 }
363}
364
365pub 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 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#[derive(Component)]
397pub struct CaptureTarget;
398
399#[derive(Component)]
401pub struct CaptureCamera;
402
403#[derive(Clone, Debug, PartialEq)]
411pub struct RenderConfig {
412 pub width: u32,
414 pub height: u32,
416 pub zoom: f32,
419 pub near_plane: f32,
421 pub far_plane: f32,
423 pub lighting: LightingConfig,
425}
426
427#[derive(Clone, Debug, PartialEq)]
431pub struct LightingConfig {
432 pub ambient_brightness: f32,
434 pub key_light_intensity: f32,
436 pub key_light_position: [f32; 3],
438 pub fill_light_intensity: f32,
440 pub fill_light_position: [f32; 3],
442 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 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 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 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 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 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 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 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 pub fn intrinsics(&self) -> CameraIntrinsics {
566 let base_hfov_rad = 90.0_f64.to_radians();
567 let fx_norm = (base_hfov_rad / 2.0).tan() / self.zoom as f64;
569 let fx = (self.width as f64 / 2.0) / fx_norm;
571 let fy = fx; 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#[derive(Clone, Debug, PartialEq)]
586pub struct CameraIntrinsics {
587 pub focal_length: [f64; 2],
589 pub principal_point: [f64; 2],
591 pub image_size: [u32; 2],
593}
594
595impl CameraIntrinsics {
596 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 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#[derive(Clone, Debug)]
616pub struct RenderOutput {
617 pub rgba: Vec<u8>,
619 pub depth: Vec<f64>,
623 pub width: u32,
625 pub height: u32,
627 pub intrinsics: CameraIntrinsics,
629 pub camera_transform: Transform,
631 pub object_rotation: ObjectRotation,
633}
634
635impl RenderOutput {
636 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 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 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 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 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#[derive(Debug, Clone)]
693pub enum RenderError {
694 MeshNotFound(String),
696 TextureNotFound(String),
698 FileNotFound { path: String, reason: String },
700 FileWriteFailed { path: String, reason: String },
702 DirectoryCreationFailed { path: String, reason: String },
704 RenderFailed(String),
706 InvalidConfig(String),
708 InvalidInput(String),
710 SerializationError(String),
712 DataParsingError(String),
714 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
746pub fn render_to_buffer(
771 object_dir: &Path,
772 camera_transform: &Transform,
773 object_rotation: &ObjectRotation,
774 config: &RenderConfig,
775) -> Result<RenderOutput, RenderError> {
776 render::render_headless(object_dir, camera_transform, object_rotation, config)
778}
779
780pub 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
811pub fn render_to_buffer_cached(
879 object_dir: &Path,
880 camera_transform: &Transform,
881 object_rotation: &ObjectRotation,
882 config: &RenderConfig,
883 cache: &mut cache::ModelCache,
884) -> Result<RenderOutput, RenderError> {
885 let mesh_path = object_dir.join("google_16k/textured.obj");
886 let texture_path = object_dir.join("google_16k/texture_map.png");
887
888 cache.cache_scene(mesh_path.clone());
890 cache.cache_texture(texture_path.clone());
891
892 render::render_headless(object_dir, camera_transform, object_rotation, config)
894}
895
896pub fn render_to_files(
913 object_dir: &Path,
914 camera_transform: &Transform,
915 object_rotation: &ObjectRotation,
916 config: &RenderConfig,
917 rgba_path: &Path,
918 depth_path: &Path,
919) -> Result<(), RenderError> {
920 render::render_to_files(
921 object_dir,
922 camera_transform,
923 object_rotation,
924 config,
925 rgba_path,
926 depth_path,
927 )
928}
929
930pub use batch::{
932 BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
933 BatchState, RenderStatus,
934};
935
936pub use render::RenderSession;
939
940pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
958 Ok(BatchRenderer::new(config.clone()))
959}
960
961pub fn queue_render_request(
986 renderer: &mut BatchRenderer,
987 request: BatchRenderRequest,
988) -> Result<(), RenderError> {
989 renderer
990 .queue_request(request)
991 .map_err(|e| RenderError::RenderFailed(e.to_string()))
992}
993
994pub fn render_next_in_batch(
1016 renderer: &mut BatchRenderer,
1017 _timeout_ms: u32,
1018) -> Result<Option<BatchRenderOutput>, RenderError> {
1019 if let Some(request) = renderer.pending_requests.pop_front() {
1020 let output = render_to_buffer(
1021 &request.object_dir,
1022 &request.viewpoint,
1023 &request.object_rotation,
1024 &request.render_config,
1025 )?;
1026 let batch_output = BatchRenderOutput::from_render_output(request, output);
1027 renderer.completed_results.push(batch_output.clone());
1028 renderer.renders_processed += 1;
1029 Ok(Some(batch_output))
1030 } else {
1031 Ok(None)
1032 }
1033}
1034
1035pub fn render_batch(
1054 requests: Vec<BatchRenderRequest>,
1055 config: &BatchRenderConfig,
1056) -> Result<Vec<BatchRenderOutput>, RenderError> {
1057 if requests.is_empty() {
1058 return Ok(Vec::new());
1059 }
1060
1061 if requests.len() > 1 && requests_share_batch_context(&requests) {
1062 let first_request = requests[0].clone();
1063 let viewpoints: Vec<Transform> = requests.iter().map(|request| request.viewpoint).collect();
1064 let outputs = render::render_headless_sequence(
1065 &first_request.object_dir,
1066 &viewpoints,
1067 &first_request.object_rotation,
1068 &first_request.render_config,
1069 )?;
1070
1071 return Ok(requests
1072 .into_iter()
1073 .zip(outputs)
1074 .map(|(request, output)| BatchRenderOutput::from_render_output(request, output))
1075 .collect());
1076 }
1077
1078 let mut renderer = create_batch_renderer(config)?;
1079
1080 for request in requests {
1082 queue_render_request(&mut renderer, request)?;
1083 }
1084
1085 let mut results = Vec::new();
1087 while let Some(output) = render_next_in_batch(&mut renderer, config.frame_timeout_ms)? {
1088 results.push(output);
1089 }
1090
1091 Ok(results)
1092}
1093
1094fn requests_share_batch_context(requests: &[BatchRenderRequest]) -> bool {
1095 let Some(first) = requests.first() else {
1096 return true;
1097 };
1098
1099 requests.iter().all(|request| {
1100 request.object_dir == first.object_dir
1101 && request.object_rotation == first.object_rotation
1102 && request.render_config == first.render_config
1103 })
1104}
1105
1106pub use bevy::prelude::{Quat, Transform, Vec3};
1108
1109#[cfg(test)]
1110mod tests {
1111 use super::*;
1112
1113 #[test]
1114 fn test_object_rotation_identity() {
1115 let rot = ObjectRotation::identity();
1116 assert_eq!(rot.pitch, 0.0);
1117 assert_eq!(rot.yaw, 0.0);
1118 assert_eq!(rot.roll, 0.0);
1119 }
1120
1121 #[test]
1122 fn test_object_rotation_from_array() {
1123 let rot = ObjectRotation::from_array([10.0, 20.0, 30.0]);
1124 assert_eq!(rot.pitch, 10.0);
1125 assert_eq!(rot.yaw, 20.0);
1126 assert_eq!(rot.roll, 30.0);
1127 }
1128
1129 #[test]
1130 fn test_requests_share_batch_context_for_homogeneous_batch() {
1131 let config = RenderConfig::tbp_default();
1132 let request = BatchRenderRequest {
1133 object_dir: "/tmp/ycb/003_cracker_box".into(),
1134 viewpoint: Transform::IDENTITY,
1135 object_rotation: ObjectRotation::identity(),
1136 render_config: config.clone(),
1137 };
1138
1139 assert!(requests_share_batch_context(&[
1140 request.clone(),
1141 BatchRenderRequest {
1142 viewpoint: Transform::from_xyz(1.0, 0.0, 0.0),
1143 ..request
1144 },
1145 ]));
1146 }
1147
1148 #[test]
1149 fn test_requests_share_batch_context_rejects_mixed_objects() {
1150 let config = RenderConfig::tbp_default();
1151 let request = BatchRenderRequest {
1152 object_dir: "/tmp/ycb/003_cracker_box".into(),
1153 viewpoint: Transform::IDENTITY,
1154 object_rotation: ObjectRotation::identity(),
1155 render_config: config.clone(),
1156 };
1157
1158 assert!(!requests_share_batch_context(&[
1159 request.clone(),
1160 BatchRenderRequest {
1161 object_dir: "/tmp/ycb/005_tomato_soup_can".into(),
1162 ..request
1163 },
1164 ]));
1165 }
1166
1167 #[test]
1168 fn test_tbp_benchmark_rotations() {
1169 let rotations = ObjectRotation::tbp_benchmark_rotations();
1170 assert_eq!(rotations.len(), 3);
1171 assert_eq!(rotations[0], ObjectRotation::from_array([0.0, 0.0, 0.0]));
1172 assert_eq!(rotations[1], ObjectRotation::from_array([0.0, 90.0, 0.0]));
1173 assert_eq!(rotations[2], ObjectRotation::from_array([0.0, 180.0, 0.0]));
1174 }
1175
1176 #[test]
1177 fn test_tbp_known_orientations_count() {
1178 let orientations = ObjectRotation::tbp_known_orientations();
1179 assert_eq!(orientations.len(), 14);
1180 }
1181
1182 #[test]
1183 fn test_rotation_to_quat() {
1184 let rot = ObjectRotation::identity();
1185 let quat = rot.to_quat();
1186 assert!((quat.w - 1.0).abs() < 0.001);
1188 assert!(quat.x.abs() < 0.001);
1189 assert!(quat.y.abs() < 0.001);
1190 assert!(quat.z.abs() < 0.001);
1191 }
1192
1193 #[test]
1194 fn test_rotation_90_yaw() {
1195 let rot = ObjectRotation::new(0.0, 90.0, 0.0);
1196 let quat = rot.to_quat();
1197 assert!((quat.w - 0.707).abs() < 0.01);
1199 assert!((quat.y - 0.707).abs() < 0.01);
1200 }
1201
1202 #[test]
1203 fn test_viewpoint_config_default() {
1204 let config = ViewpointConfig::default();
1205 assert_eq!(config.radius, 0.5);
1206 assert_eq!(config.yaw_count, 8);
1207 assert_eq!(config.pitch_angles_deg.len(), 3);
1208 }
1209
1210 #[test]
1211 fn test_viewpoint_count() {
1212 let config = ViewpointConfig::default();
1213 assert_eq!(config.viewpoint_count(), 24); }
1215
1216 #[test]
1217 fn test_generate_viewpoints_count() {
1218 let config = ViewpointConfig::default();
1219 let viewpoints = generate_viewpoints(&config);
1220 assert_eq!(viewpoints.len(), 24);
1221 }
1222
1223 #[test]
1224 fn test_viewpoints_spherical_radius() {
1225 let config = ViewpointConfig::default();
1226 let viewpoints = generate_viewpoints(&config);
1227
1228 for (i, transform) in viewpoints.iter().enumerate() {
1229 let actual_radius = transform.translation.length();
1230 assert!(
1231 (actual_radius - config.radius).abs() < 0.001,
1232 "Viewpoint {} has incorrect radius: {} (expected {})",
1233 i,
1234 actual_radius,
1235 config.radius
1236 );
1237 }
1238 }
1239
1240 #[test]
1241 fn test_viewpoints_looking_at_origin() {
1242 let config = ViewpointConfig::default();
1243 let viewpoints = generate_viewpoints(&config);
1244
1245 for (i, transform) in viewpoints.iter().enumerate() {
1246 let forward = transform.forward();
1247 let to_origin = (Vec3::ZERO - transform.translation).normalize();
1248 let dot = forward.dot(to_origin);
1249 assert!(
1250 dot > 0.99,
1251 "Viewpoint {} not looking at origin, dot product: {}",
1252 i,
1253 dot
1254 );
1255 }
1256 }
1257
1258 #[test]
1259 fn test_sensor_config_default() {
1260 let config = SensorConfig::default();
1261 assert_eq!(config.object_rotations.len(), 1);
1262 assert_eq!(config.total_captures(), 24);
1263 }
1264
1265 #[test]
1266 fn test_sensor_config_tbp_benchmark() {
1267 let config = SensorConfig::tbp_benchmark();
1268 assert_eq!(config.object_rotations.len(), 3);
1269 assert_eq!(config.total_captures(), 72); }
1271
1272 #[test]
1273 fn test_sensor_config_tbp_full() {
1274 let config = SensorConfig::tbp_full_training();
1275 assert_eq!(config.object_rotations.len(), 14);
1276 assert_eq!(config.total_captures(), 336); }
1278
1279 #[test]
1280 fn test_ycb_representative_objects() {
1281 assert_eq!(crate::ycb::REPRESENTATIVE_OBJECTS.len(), 3);
1283 assert!(crate::ycb::REPRESENTATIVE_OBJECTS.contains(&"003_cracker_box"));
1284 }
1285
1286 #[test]
1287 fn test_ycb_tbp_standard_objects() {
1288 assert_eq!(crate::ycb::TBP_STANDARD_OBJECTS.len(), 10);
1289 assert!(crate::ycb::TBP_STANDARD_OBJECTS.contains(&"025_mug"));
1290 }
1291
1292 #[test]
1293 fn test_ycb_tbp_similar_objects() {
1294 assert_eq!(crate::ycb::TBP_SIMILAR_OBJECTS.len(), 10);
1295 assert!(crate::ycb::TBP_SIMILAR_OBJECTS.contains(&"003_cracker_box"));
1296 }
1297
1298 #[test]
1299 fn test_ycb_object_mesh_path() {
1300 let path = crate::ycb::object_mesh_path("/tmp/ycb", "003_cracker_box");
1301 assert_eq!(
1302 path,
1303 std::path::Path::new("/tmp/ycb")
1304 .join("003_cracker_box")
1305 .join("google_16k")
1306 .join("textured.obj")
1307 );
1308 }
1309
1310 #[test]
1311 fn test_ycb_object_texture_path() {
1312 let path = crate::ycb::object_texture_path("/tmp/ycb", "003_cracker_box");
1313 assert_eq!(
1314 path,
1315 std::path::Path::new("/tmp/ycb")
1316 .join("003_cracker_box")
1317 .join("google_16k")
1318 .join("texture_map.png")
1319 );
1320 }
1321
1322 #[test]
1327 fn test_render_config_tbp_default() {
1328 let config = RenderConfig::tbp_default();
1329 assert_eq!(config.width, 64);
1331 assert_eq!(config.height, 64);
1332 assert!(config.zoom > 0.0);
1334 assert!(config.near_plane > 0.0);
1336 assert!(config.far_plane > config.near_plane);
1337 }
1338
1339 #[test]
1340 fn test_render_config_preview() {
1341 let config = RenderConfig::preview();
1342 assert_eq!(config.width, 256);
1343 assert_eq!(config.height, 256);
1344 }
1345
1346 #[test]
1347 fn test_render_config_default_is_tbp() {
1348 let default = RenderConfig::default();
1349 let tbp = RenderConfig::tbp_default();
1350 assert_eq!(default.width, tbp.width);
1351 assert_eq!(default.height, tbp.height);
1352 }
1353
1354 #[test]
1355 fn test_render_config_fov() {
1356 let config = RenderConfig::tbp_default();
1357 let fov = config.fov_radians();
1358 assert!(fov > 0.0);
1361 assert!(fov < PI);
1362
1363 let zoomed = RenderConfig {
1365 zoom: config.zoom * 2.0,
1366 ..config
1367 };
1368 assert!(zoomed.fov_radians() < fov);
1369 }
1370
1371 #[test]
1372 fn test_render_config_intrinsics() {
1373 let config = RenderConfig::tbp_default();
1374 let intrinsics = config.intrinsics();
1375
1376 assert_eq!(intrinsics.image_size, [config.width, config.height]);
1378 assert_eq!(
1379 intrinsics.principal_point,
1380 [config.width as f64 / 2.0, config.height as f64 / 2.0]
1381 );
1382 assert_eq!(intrinsics.focal_length[0], intrinsics.focal_length[1]);
1384 assert!(intrinsics.focal_length[0] > 0.0);
1385 }
1386
1387 #[test]
1388 fn test_camera_intrinsics_project() {
1389 let intrinsics = CameraIntrinsics {
1390 focal_length: [100.0, 100.0],
1391 principal_point: [32.0, 32.0],
1392 image_size: [64, 64],
1393 };
1394
1395 let center = intrinsics.project(Vec3::new(0.0, 0.0, 1.0));
1397 assert!(center.is_some());
1398 let [x, y] = center.unwrap();
1399 assert!((x - 32.0).abs() < 0.001);
1400 assert!((y - 32.0).abs() < 0.001);
1401
1402 let behind = intrinsics.project(Vec3::new(0.0, 0.0, -1.0));
1404 assert!(behind.is_none());
1405 }
1406
1407 #[test]
1408 fn test_camera_intrinsics_unproject() {
1409 let intrinsics = CameraIntrinsics {
1410 focal_length: [100.0, 100.0],
1411 principal_point: [32.0, 32.0],
1412 image_size: [64, 64],
1413 };
1414
1415 let point = intrinsics.unproject([32.0, 32.0], 1.0);
1417 assert!((point[0]).abs() < 0.001); assert!((point[1]).abs() < 0.001); assert!((point[2] - 1.0).abs() < 0.001); }
1421
1422 #[test]
1423 fn test_render_output_get_rgba() {
1424 let output = RenderOutput {
1425 rgba: vec![
1426 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1427 ],
1428 depth: vec![1.0, 2.0, 3.0, 4.0],
1429 width: 2,
1430 height: 2,
1431 intrinsics: RenderConfig::tbp_default().intrinsics(),
1432 camera_transform: Transform::IDENTITY,
1433 object_rotation: ObjectRotation::identity(),
1434 };
1435
1436 assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
1438 assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
1440 assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
1442 assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
1444 assert_eq!(output.get_rgba(2, 0), None);
1446 }
1447
1448 #[test]
1449 fn test_render_output_get_depth() {
1450 let output = RenderOutput {
1451 rgba: vec![0u8; 16],
1452 depth: vec![1.0, 2.0, 3.0, 4.0],
1453 width: 2,
1454 height: 2,
1455 intrinsics: RenderConfig::tbp_default().intrinsics(),
1456 camera_transform: Transform::IDENTITY,
1457 object_rotation: ObjectRotation::identity(),
1458 };
1459
1460 assert_eq!(output.get_depth(0, 0), Some(1.0));
1461 assert_eq!(output.get_depth(1, 0), Some(2.0));
1462 assert_eq!(output.get_depth(0, 1), Some(3.0));
1463 assert_eq!(output.get_depth(1, 1), Some(4.0));
1464 assert_eq!(output.get_depth(2, 0), None);
1465 }
1466
1467 #[test]
1468 fn test_render_output_to_rgb_image() {
1469 let output = RenderOutput {
1470 rgba: vec![
1471 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1472 ],
1473 depth: vec![1.0, 2.0, 3.0, 4.0],
1474 width: 2,
1475 height: 2,
1476 intrinsics: RenderConfig::tbp_default().intrinsics(),
1477 camera_transform: Transform::IDENTITY,
1478 object_rotation: ObjectRotation::identity(),
1479 };
1480
1481 let image = output.to_rgb_image();
1482 assert_eq!(image.len(), 2); assert_eq!(image[0].len(), 2); assert_eq!(image[0][0], [255, 0, 0]); assert_eq!(image[0][1], [0, 255, 0]); assert_eq!(image[1][0], [0, 0, 255]); assert_eq!(image[1][1], [255, 255, 255]); }
1489
1490 #[test]
1491 fn test_render_output_to_depth_image() {
1492 let output = RenderOutput {
1493 rgba: vec![0u8; 16],
1494 depth: vec![1.0, 2.0, 3.0, 4.0],
1495 width: 2,
1496 height: 2,
1497 intrinsics: RenderConfig::tbp_default().intrinsics(),
1498 camera_transform: Transform::IDENTITY,
1499 object_rotation: ObjectRotation::identity(),
1500 };
1501
1502 let depth_image = output.to_depth_image();
1503 assert_eq!(depth_image.len(), 2);
1504 assert_eq!(depth_image[0], vec![1.0, 2.0]);
1505 assert_eq!(depth_image[1], vec![3.0, 4.0]);
1506 }
1507
1508 #[test]
1509 fn test_render_error_display() {
1510 let err = RenderError::MeshNotFound("/path/to/mesh.obj".to_string());
1511 assert!(err.to_string().contains("Mesh not found"));
1512 assert!(err.to_string().contains("/path/to/mesh.obj"));
1513 }
1514
1515 #[test]
1520 fn test_object_rotation_extreme_angles() {
1521 let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
1523 let quat = rot.to_quat();
1524 assert!((quat.length() - 1.0).abs() < 0.001);
1526 }
1527
1528 #[test]
1529 fn test_object_rotation_to_transform() {
1530 let rot = ObjectRotation::new(45.0, 90.0, 0.0);
1531 let transform = rot.to_transform();
1532 assert_eq!(transform.translation, Vec3::ZERO);
1534 assert!(transform.rotation != Quat::IDENTITY);
1536 }
1537
1538 #[test]
1539 fn test_viewpoint_config_single_viewpoint() {
1540 let config = ViewpointConfig {
1541 radius: 1.0,
1542 yaw_count: 1,
1543 pitch_angles_deg: vec![0.0],
1544 };
1545 assert_eq!(config.viewpoint_count(), 1);
1546 let viewpoints = generate_viewpoints(&config);
1547 assert_eq!(viewpoints.len(), 1);
1548 let pos = viewpoints[0].translation;
1550 assert!((pos.x).abs() < 0.001);
1551 assert!((pos.y).abs() < 0.001);
1552 assert!((pos.z - 1.0).abs() < 0.001);
1553 }
1554
1555 #[test]
1556 fn test_viewpoint_radius_scaling() {
1557 let config1 = ViewpointConfig {
1558 radius: 0.5,
1559 yaw_count: 4,
1560 pitch_angles_deg: vec![0.0],
1561 };
1562 let config2 = ViewpointConfig {
1563 radius: 2.0,
1564 yaw_count: 4,
1565 pitch_angles_deg: vec![0.0],
1566 };
1567
1568 let v1 = generate_viewpoints(&config1);
1569 let v2 = generate_viewpoints(&config2);
1570
1571 for (vp1, vp2) in v1.iter().zip(v2.iter()) {
1573 let ratio = vp2.translation.length() / vp1.translation.length();
1574 assert!((ratio - 4.0).abs() < 0.01); }
1576 }
1577
1578 #[test]
1579 fn test_camera_intrinsics_project_at_z_zero() {
1580 let intrinsics = CameraIntrinsics {
1581 focal_length: [100.0, 100.0],
1582 principal_point: [32.0, 32.0],
1583 image_size: [64, 64],
1584 };
1585
1586 let result = intrinsics.project(Vec3::new(1.0, 1.0, 0.0));
1588 assert!(result.is_none());
1589 }
1590
1591 #[test]
1592 fn test_camera_intrinsics_roundtrip() {
1593 let intrinsics = CameraIntrinsics {
1594 focal_length: [100.0, 100.0],
1595 principal_point: [32.0, 32.0],
1596 image_size: [64, 64],
1597 };
1598
1599 let original = Vec3::new(0.5, -0.3, 2.0);
1601 let projected = intrinsics.project(original).unwrap();
1602
1603 let unprojected = intrinsics.unproject(projected, original.z as f64);
1605
1606 assert!((unprojected[0] - original.x as f64).abs() < 0.001); assert!((unprojected[1] - original.y as f64).abs() < 0.001); assert!((unprojected[2] - original.z as f64).abs() < 0.001); }
1611
1612 #[test]
1613 fn test_render_output_empty() {
1614 let output = RenderOutput {
1615 rgba: vec![],
1616 depth: vec![],
1617 width: 0,
1618 height: 0,
1619 intrinsics: RenderConfig::tbp_default().intrinsics(),
1620 camera_transform: Transform::IDENTITY,
1621 object_rotation: ObjectRotation::identity(),
1622 };
1623
1624 assert_eq!(output.get_rgba(0, 0), None);
1626 assert_eq!(output.get_depth(0, 0), None);
1627 assert!(output.to_rgb_image().is_empty());
1628 assert!(output.to_depth_image().is_empty());
1629 }
1630
1631 #[test]
1632 fn test_render_output_1x1() {
1633 let output = RenderOutput {
1634 rgba: vec![128, 64, 32, 255],
1635 depth: vec![0.5],
1636 width: 1,
1637 height: 1,
1638 intrinsics: RenderConfig::tbp_default().intrinsics(),
1639 camera_transform: Transform::IDENTITY,
1640 object_rotation: ObjectRotation::identity(),
1641 };
1642
1643 assert_eq!(output.get_rgba(0, 0), Some([128, 64, 32, 255]));
1644 assert_eq!(output.get_depth(0, 0), Some(0.5));
1645 assert_eq!(output.get_rgb(0, 0), Some([128, 64, 32]));
1646
1647 let rgb_img = output.to_rgb_image();
1648 assert_eq!(rgb_img.len(), 1);
1649 assert_eq!(rgb_img[0].len(), 1);
1650 assert_eq!(rgb_img[0][0], [128, 64, 32]);
1651 }
1652
1653 #[test]
1654 fn test_render_config_high_res() {
1655 let config = RenderConfig::high_res();
1656 assert_eq!(config.width, 512);
1657 assert_eq!(config.height, 512);
1658
1659 let intrinsics = config.intrinsics();
1660 assert_eq!(intrinsics.image_size, [512, 512]);
1661 assert_eq!(intrinsics.principal_point, [256.0, 256.0]);
1662 }
1663
1664 #[test]
1665 fn test_render_config_zoom_affects_fov() {
1666 let base = RenderConfig {
1671 zoom: 2.0,
1672 ..RenderConfig::tbp_default()
1673 };
1674 let doubled = RenderConfig {
1675 zoom: 4.0,
1676 ..RenderConfig::tbp_default()
1677 };
1678
1679 assert!(doubled.fov_radians() < base.fov_radians());
1681
1682 let base_half_tan = (base.fov_radians() / 2.0).tan();
1684 let doubled_half_tan = (doubled.fov_radians() / 2.0).tan();
1685 assert!((base_half_tan / doubled_half_tan - 2.0).abs() < 1e-4);
1686 }
1687
1688 #[test]
1689 fn test_render_config_zoom_affects_intrinsics() {
1690 let a = RenderConfig {
1693 zoom: 2.0,
1694 ..RenderConfig::tbp_default()
1695 };
1696 let b = RenderConfig {
1697 zoom: 4.0,
1698 ..RenderConfig::tbp_default()
1699 };
1700
1701 let fx_a = a.intrinsics().focal_length[0];
1702 let fx_b = b.intrinsics().focal_length[0];
1703
1704 assert!(fx_b > fx_a);
1706
1707 assert!((fx_a / a.zoom as f64 - fx_b / b.zoom as f64).abs() < 1e-9);
1709 }
1710
1711 #[test]
1712 fn test_lighting_config_variants() {
1713 let default = LightingConfig::default();
1714 let bright = LightingConfig::bright();
1715 let soft = LightingConfig::soft();
1716 let unlit = LightingConfig::unlit();
1717
1718 assert!(bright.key_light_intensity > default.key_light_intensity);
1720
1721 assert_eq!(unlit.key_light_intensity, 0.0);
1723 assert_eq!(unlit.fill_light_intensity, 0.0);
1724 assert_eq!(unlit.ambient_brightness, 1.0);
1725
1726 assert!(soft.key_light_intensity < default.key_light_intensity);
1728 }
1729
1730 #[test]
1731 fn test_all_render_error_variants() {
1732 let errors = vec![
1733 RenderError::MeshNotFound("mesh.obj".to_string()),
1734 RenderError::TextureNotFound("texture.png".to_string()),
1735 RenderError::RenderFailed("GPU error".to_string()),
1736 RenderError::InvalidConfig("bad config".to_string()),
1737 ];
1738
1739 for err in errors {
1740 let msg = err.to_string();
1742 assert!(!msg.is_empty());
1743 }
1744 }
1745
1746 #[test]
1747 fn test_tbp_known_orientations_unique() {
1748 let orientations = ObjectRotation::tbp_known_orientations();
1749
1750 let quats: Vec<Quat> = orientations.iter().map(|r| r.to_quat()).collect();
1752
1753 for (i, q1) in quats.iter().enumerate() {
1754 for (j, q2) in quats.iter().enumerate() {
1755 if i != j {
1756 let dot = q1.dot(*q2).abs();
1758 assert!(
1759 dot < 0.999,
1760 "Orientations {} and {} produce same quaternion",
1761 i,
1762 j
1763 );
1764 }
1765 }
1766 }
1767 }
1768}