1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! INTERNALDOC: This contains module [`Transform`], [`MirrorAxis`] and the core mirror logic.
// User docs finished
// TODO: MirrorDocs
use itertools::Itertools;
use nalgebra::{vector, Matrix3, Rotation3, Vector3};

#[cfg(feature = "urdf")]
use crate::to_rdf::to_urdf::ToURDF;
#[cfg(feature = "xml")]
use quick_xml::{events::attributes::Attribute, name::QName};

#[derive(Debug, PartialEq, Clone, Copy, Default)]
/// A `Transform` type to represent the transform from the parent coordinate system to a new coordinate system.
///
/// A transform starts from the origin of the parent element and first translates to the origin of the child element,
///  after which a new coordinate system gets by rotating the parent coordinate system over the specified `roll`, `pitch` and `yaw` angles.
///
/// The `translation` is applied first and uses the axes of the parent coordinate system. The translation is specified in meters.
///
/// The `rotation` is applied next and rotates the parent axes with the specified `roll`, `pitch` and yaw` `angles in radians
///
/// In URDF this element is often refered to as `origin`.
pub struct Transform {
	/// The translation of origin of the new coordinate system in meters.
	pub translation: Option<(f32, f32, f32)>,
	/// The rotation of the new coordinate system in radians.
	pub rotation: Option<(f32, f32, f32)>,
}

impl Transform {
	/// Creates a new `Transform`.
	///
	/// Creates a new `Transform` from a tuple of cartesian coordinates in meters as `f32` and a tuple of roll-pitch-yaw angles in radians as `f32`.
	///
	/// # Example
	///
	/// ```
	/// use robot_description_builder::Transform;
	/// use std::f32::consts::PI;
	/// let transform = Transform::new((1., 1000., 0.), (0., PI, 0.));
	///
	/// assert_eq!(
	///     transform,
	///     Transform {
	///        translation: Some((1., 1000., 0.)),
	///        rotation: Some((0., PI, 0.)),
	///     }
	/// )
	/// ```
	pub fn new(xyz: (f32, f32, f32), rpy: (f32, f32, f32)) -> Self {
		Self {
			translation: Some(xyz),
			rotation: Some(rpy),
		}
	}

	/// Creates a new `Transform` from cartesian x, y and z coordinates.
	///
	/// Creates a new `Transform` from a tuple of cartesian coordinates in meters as `f32` and leaves the other values at the default.
	///
	/// # Example
	///
	/// ```
	/// use robot_description_builder::Transform;
	/// let transform = Transform::new_translation( -0.6, 10., 900.);
	///
	/// assert_eq!(
	///     transform,
	///     Transform {
	///        translation: Some((-0.6, 10., 900.)),
	///        rotation: None,
	///     }
	/// )
	/// ```
	pub fn new_translation(x: f32, y: f32, z: f32) -> Self {
		Self {
			translation: Some((x, y, z)),
			..Default::default()
		}
	}

	/// Creates a new `Transform` from roll-pitch-yaw angles
	///
	/// Creates a new `Transform` from the roll-pitch-yaw angles in radians as `f32` and leaves the other values at the default.
	///
	/// # Example
	///
	/// ```
	/// use robot_description_builder::Transform;
	/// use std::f32::consts::PI;
	/// let transform = Transform::new_rotation( 0., PI, 0.);
	///
	/// assert_eq!(
	///     transform,
	///     Transform {
	///        translation: None,
	///        rotation: Some((0., PI, 0.)),
	///     }
	/// )
	/// ```
	pub fn new_rotation(r: f32, p: f32, y: f32) -> Self {
		Self {
			rotation: Some((r, p, y)),
			..Default::default()
		}
	}

	/// A function to check if any of the fields are set.
	///
	/// It doesn't check if the some fields have the default value, since it can be format depended.
	///
	/// # Example
	/// ```rust
	/// # use robot_description_builder::Transform;
	/// assert!(Transform {
	///     translation: Some((1., 2., 3.)),
	///     rotation: Some((4., 5., 6.))
	/// }
	/// .contains_some());
	///
	/// assert!(Transform {
	///     translation: Some((1., 2., 3.)),
	///     ..Default::default()
	/// }
	/// .contains_some());
	///
	/// assert!(Transform {
	///     rotation: Some((4., 5., 6.)),
	///     ..Default::default()
	/// }
	/// .contains_some());
	///
	/// assert!(!Transform::default().contains_some())
	/// ```
	pub fn contains_some(&self) -> bool {
		self.translation.is_some() || self.rotation.is_some()
	}
}

impl Mirror for Transform {
	fn mirrored(&self, mirror_matrix: &Matrix3<f32>) -> Self {
		Transform {
			translation: self.translation.as_ref().map(|(x, y, z)| {
				let old_translation = vector![*x, *y, *z];
				(mirror_matrix * old_translation)
					.component_mul(&Vector3::from_iterator(old_translation.iter().map(|val| {
						if val.is_normal() {
							1.
						} else {
							0.
						}
					}))) // TODO: Perfomance enhancements are probably possible.
					.iter()
					.copied()
					.collect_tuple()
					.unwrap() // Unwrapping here to ensure that we collect to a Tuple3 | TODO: Change to expect? or remove
			}),
			rotation: self.rotation,
		}
	}
}

impl MirrorUpdater for Transform {
	fn update_mirror_matrix(&self, mirror_matrix: &Matrix3<f32>) -> Matrix3<f32> {
		match self.rotation.as_ref() {
			Some(rpy) => {
				Rotation3::from_euler_angles(rpy.0, rpy.1, rpy.2)
					* mirror_matrix * Rotation3::from_euler_angles(rpy.0, rpy.1, rpy.2).inverse()
			}
			None => *mirror_matrix,
		}
	}
}

#[cfg(feature = "urdf")]
impl ToURDF for Transform {
	fn to_urdf(
		&self,
		writer: &mut quick_xml::Writer<std::io::Cursor<Vec<u8>>>,
		_urdf_config: &crate::to_rdf::to_urdf::URDFConfig,
	) -> Result<(), quick_xml::Error> {
		let mut element = writer.create_element("origin");
		if let Some(translation) = self.translation {
			element = element.with_attribute(Attribute {
				key: QName(b"xyz"),
				value: format!("{} {} {}", translation.0, translation.1, translation.2)
					.as_bytes()
					.into(),
			})
		}

		if let Some(rotation) = self.rotation {
			element = element.with_attribute(Attribute {
				key: QName(b"rpy"),
				value: format!("{} {} {}", rotation.0, rotation.1, rotation.2)
					.as_bytes()
					.into(),
			});
		}

		element.write_empty()?;
		Ok(())
	}
}

impl From<Transform> for crate::joint::JointTransformMode {
	fn from(value: Transform) -> Self {
		Self::Direct(value)
	}
}

/// A `MirrorAxis` enum to represent a plane to mirror about.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MirrorAxis {
	/// Mirror about to X = 0 plane.
	X,
	/// Mirror about to Y = 0 plane.
	Y,
	/// Mirror about to Z = 0 plane.
	Z,
}

impl From<MirrorAxis> for Matrix3<f32> {
	fn from(value: MirrorAxis) -> Self {
		let diag = match value {
			MirrorAxis::X => (-1., 1., 1.),
			MirrorAxis::Y => (1., -1., 1.),
			MirrorAxis::Z => (1., 1., -1.),
		};

		Matrix3::from_diagonal(&Vector3::new(diag.0, diag.1, diag.2))
	}
}

/// A mirrorable type
///
/// Types implementing `Mirror` are able to be [`mirrored`](Mirror::mirrored), given an `mirror_matrix`.
pub(crate) trait Mirror {
	/// Returns a mirrored clone of itself
	///
	/// TODO: EXAMPLE
	fn mirrored(&self, mirror_matrix: &Matrix3<f32>) -> Self;
}

/// A type which can change the `mirror_matrix` for its children.
///
/// TODO: IMPROVE/FINISH DOCS
///
/// Types implementing `MirrorUpdater` can be [`mirrored`](Mirror::mirrored). As a result of this mirror the `mirror_matrix` changes.
pub(crate) trait MirrorUpdater: Sized + Mirror {
	/// Get the updated `mirror_matrix` which should be used for all children.
	fn update_mirror_matrix(&self, mirror_matrix: &Matrix3<f32>) -> Matrix3<f32>;

	/// Return a mirrored clone of itself and the updated `mirror_matrix`.
	fn mirrored_update_matrix(&self, mirror_matrix: &Matrix3<f32>) -> (Self, Matrix3<f32>) {
		(
			self.mirrored(mirror_matrix),
			self.update_mirror_matrix(mirror_matrix),
		)
	}
}

#[cfg(test)]
mod tests {
	use super::Transform;
	use std::f32::consts::{FRAC_PI_2, FRAC_PI_4};
	use test_log::test;

	mod mirror {
		use super::{test, *};
		use crate::transform::{MirrorAxis, MirrorUpdater};
		use nalgebra::{matrix, vector, Matrix3};

		fn test_mirror(
			transform: Transform,
			mirror_axis: MirrorAxis,
			result: (Transform, Matrix3<f32>),
		) {
			assert_eq!(
				transform.mirrored_update_matrix(&mirror_axis.into()),
				result
			)
		}

		fn test_all_mirrors(transform: Transform, results: [(Transform, Matrix3<f32>); 3]) {
			results
				.into_iter()
				.enumerate()
				.map(|(index, result)| {
					(
						match index {
							0 => MirrorAxis::X,
							1 => MirrorAxis::Y,
							2 => MirrorAxis::Z,
							_ => unreachable!(),
						},
						result,
					)
				})
				.for_each(|(mirror_axis, result)| test_mirror(transform, mirror_axis, result))
		}

		fn test_all_mirrors_angle_var(
			transform: Transform,
			angle: f32,
			results: [(Transform, [Matrix3<f32>; 3]); 3],
		) {
			for i in 0..2 {
				let rotation = match i {
					0 => (angle, 0., 0.),
					1 => (0., angle, 0.),
					2 => (0., 0., angle),
					_ => unreachable!(),
				};

				test_all_mirrors(
					Transform {
						rotation: Some(rotation),
						..transform.clone()
					},
					[
						(
							Transform {
								rotation: Some(rotation),
								..results[0].0
							},
							results[0].1[i],
						),
						(
							Transform {
								rotation: Some(rotation),
								..results[1].0
							},
							results[1].1[i],
						),
						(
							Transform {
								rotation: Some(rotation),
								..results[2].0
							},
							results[2].1[i],
						),
					],
				)
			}
		}

		#[test]
		fn uniaxial_no_rotation() {
			// X
			test_all_mirrors(
				Transform::new_translation(2., 0., 0.),
				[
					(
						Transform {
							translation: Some((-2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			// Y
			test_all_mirrors(
				Transform::new_translation(0., 0.5, 0.),
				[
					(
						Transform {
							translation: Some((0., 0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((0., -0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			// Z
			test_all_mirrors(
				Transform::new_translation(0., 0., -900.),
				[
					(
						Transform {
							translation: Some((0., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0., 900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);
		}

		#[test]
		#[ignore = "Is this necessary?"]
		fn uniaxial_unirotation() {
			test_all_mirrors_angle_var(
				Transform::new_translation(2., 0., 0.),
				FRAC_PI_2,
				[
					(
						Transform::new_translation(-2., 0., 0.),
						[
							matrix![
								-1., 0., 0.;
								0., 1., 0.;
								0., 0., 1.;
							],
							Matrix3::from_diagonal(&vector![-1., 1., 1.]),
							Matrix3::from_diagonal(&vector![-1., 1., 1.]),
						],
					),
					(
						Transform::new_translation(2., 0., 0.),
						[
							matrix![
								1., 0. ,0.;
								0., 1., 0.;
								0. ,0. ,-1.;
							],
							Matrix3::from_diagonal(&vector![1., -1., 1.]),
							Matrix3::from_diagonal(&vector![1., -1., 1.]),
						],
					),
					(
						Transform::new_translation(2., 0., 0.),
						[
							Matrix3::from_diagonal(&vector![1., 1., -1.]),
							Matrix3::from_diagonal(&vector![1., 1., -1.]),
							Matrix3::from_diagonal(&vector![1., 1., -1.]),
						],
					),
				],
			);

			test_all_mirrors(
				Transform::new_translation(2., 0., 0.),
				[
					(
						Transform {
							translation: Some((-2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((2., 0., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			// Y
			test_all_mirrors(
				Transform::new((0., 0.5, 0.), (FRAC_PI_2, 0., FRAC_PI_4)),
				[
					(
						Transform {
							translation: Some((0., 0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((0., -0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0.5, 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			// Z
			test_all_mirrors(
				Transform::new_translation(0., 0., -900.),
				[
					(
						Transform {
							translation: Some((0., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0., 900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);
		}

		#[test]
		fn multiaxial_no_rotation() {
			test_all_mirrors(
				Transform::new_translation(2., 3., 0.),
				[
					(
						Transform {
							translation: Some((-2., 3., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((2., -3., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((2., 3., 0.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			test_all_mirrors(
				Transform::new_translation(0., 0.5, 7.),
				[
					(
						Transform {
							translation: Some((0., 0.5, 7.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((0., -0.5, 7.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((0., 0.5, -7.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			test_all_mirrors(
				Transform::new_translation(120., 0., -900.),
				[
					(
						Transform {
							translation: Some((-120., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((120., 0., -900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((120., 0., 900.)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			);

			test_all_mirrors(
				Transform::new_translation(3., 4., 5.0005),
				[
					(
						Transform {
							translation: Some((-3., 4., 5.0005)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![-1., 1., 1.]),
					),
					(
						Transform {
							translation: Some((3., -4., 5.0005)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., -1., 1.]),
					),
					(
						Transform {
							translation: Some((3., 4., -5.0005)),
							rotation: None,
						},
						Matrix3::from_diagonal(&vector![1., 1., -1.]),
					),
				],
			)
		}

		#[test]
		#[ignore = "Is this necessary?"]
		fn multiaxial_rotation() {
			todo!()
		}
	}

	#[cfg(feature = "urdf")]
	mod to_urdf {
		use super::{test, Transform};
		use crate::to_rdf::to_urdf::{ToURDF, URDFConfig};
		use std::io::Seek;

		fn test_to_urdf_transform(transform: Transform, result: String, urdf_config: &URDFConfig) {
			let mut writer = quick_xml::Writer::new(std::io::Cursor::new(Vec::new()));
			assert!(transform.to_urdf(&mut writer, urdf_config).is_ok());

			writer.get_mut().rewind().unwrap();
			assert_eq!(
				std::io::read_to_string(writer.into_inner()).unwrap(),
				result
			)
		}

		#[test]
		fn translation_only() {
			test_to_urdf_transform(
				Transform {
					translation: Some((1.2, 2.3, 3.4)),
					..Default::default()
				},
				String::from(r#"<origin xyz="1.2 2.3 3.4"/>"#),
				&URDFConfig::default(),
			);
		}

		#[test]
		fn rotation_only() {
			test_to_urdf_transform(
				Transform {
					rotation: Some((1.2, 2.3, 3.4)),
					..Default::default()
				},
				String::from(r#"<origin rpy="1.2 2.3 3.4"/>"#),
				&URDFConfig::default(),
			);
		}

		#[test]
		fn translation_rotatation() {
			test_to_urdf_transform(
				Transform {
					translation: Some((1.23, 2.34, 3.45)),
					rotation: Some((4.56, 5.67, 6.78)),
				},
				String::from(r#"<origin xyz="1.23 2.34 3.45" rpy="4.56 5.67 6.78"/>"#),
				&URDFConfig::default(),
			);
		}
	}
}