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(
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 cache.cache_scene(mesh_path.clone());
892 cache.cache_texture(texture_path.clone());
893
894 render::render_headless(object_dir, camera_transform, object_rotation, config)
896}
897
898pub 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
932pub use batch::{
934 BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
935 BatchState, RenderStatus,
936};
937
938pub use render::RenderSession;
941
942pub use render::PersistentRenderer;
948
949pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
967 Ok(BatchRenderer::new(config.clone()))
968}
969
970pub 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
1003pub 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
1044pub 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 for request in requests {
1091 queue_render_request(&mut renderer, request)?;
1092 }
1093
1094 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
1115pub 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 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 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); }
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); }
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); }
1287
1288 #[test]
1289 fn test_ycb_representative_objects() {
1290 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 #[test]
1336 fn test_render_config_tbp_default() {
1337 let config = RenderConfig::tbp_default();
1338 assert_eq!(config.width, 64);
1340 assert_eq!(config.height, 64);
1341 assert!(config.zoom > 0.0);
1343 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 assert!(fov > 0.0);
1370 assert!(fov < PI);
1371
1372 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 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 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 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 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 let point = intrinsics.unproject([32.0, 32.0], 1.0);
1426 assert!((point[0]).abs() < 0.001); assert!((point[1]).abs() < 0.001); assert!((point[2] - 1.0).abs() < 0.001); }
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 assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
1447 assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
1449 assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
1451 assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
1453 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); 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]); }
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 #[test]
1529 fn test_object_rotation_extreme_angles() {
1530 let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
1532 let quat = rot.to_quat();
1533 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 assert_eq!(transform.translation, Vec3::ZERO);
1543 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 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 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); }
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 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 let original = Vec3::new(0.5, -0.3, 2.0);
1610 let projected = intrinsics.project(original).unwrap();
1611
1612 let unprojected = intrinsics.unproject(projected, original.z as f64);
1614
1615 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); }
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 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 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 assert!(doubled.fov_radians() < base.fov_radians());
1690
1691 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 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 assert!(fx_b > fx_a);
1715
1716 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 assert!(bright.key_light_intensity > default.key_light_intensity);
1729
1730 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 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 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 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 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}