///|
/// A 3-component vector: `(x, y, z)`.
pub type Vec3 = (Double, Double, Double)

///|
/// An RGBA color, with each component in `[0, 1]`.
#derive(Debug, Eq)
pub(all) struct Rgba {
  /// Red channel in `[0, 1]`.
  r : Double
  /// Green channel in `[0, 1]`.
  g : Double
  /// Blue channel in `[0, 1]`.
  b : Double
  /// Alpha (opacity) channel in `[0, 1]`; `1.0` is fully opaque.
  a : Double
}

///|
/// Creates an RGBA color from channels in `[0, 1]`; `a` defaults to 1.0 (opaque).
pub fn Rgba::new(r : Double, g : Double, b : Double, a~ : Double = 1.0) -> Rgba {
  { r, g, b, a, }
}

///|
/// Creates the opaque orange preset, `(1.0, 0.6, 0.0)`.
pub fn Rgba::orange() -> Rgba {
  { r: 1.0, g: 0.6, b: 0.0, a: 1.0, }
}

///|
/// Creates the opaque steel-blue preset, `(0.2, 0.6, 1.0)`.
pub fn Rgba::blue() -> Rgba {
  { r: 0.2, g: 0.6, b: 1.0, a: 1.0, }
}

///|
/// Creates the opaque dark grey preset, `(0.2, 0.2, 0.2)`.
pub fn Rgba::grey() -> Rgba {
  { r: 0.2, g: 0.2, b: 0.2, a: 1.0, }
}

///|
/// Creates the opaque light grey preset, `(0.75, 0.75, 0.75)`.
pub fn Rgba::silver() -> Rgba {
  { r: 0.75, g: 0.75, b: 0.75, a: 1.0, }
}

///|
/// Creates the opaque purple preset, `(0.5, 0.0, 0.5)`.
pub fn Rgba::purple() -> Rgba {
  { r: 0.5, g: 0.0, b: 0.5, a: 1.0, }
}

///|
/// Creates the opaque magenta preset, `(1.0, 0.0, 1.0)`.
pub fn Rgba::magenta() -> Rgba {
  { r: 1.0, g: 0.0, b: 1.0, a: 1.0, }
}

///|
/// Creates the opaque white preset, `(1.0, 1.0, 1.0)`.
pub fn Rgba::white() -> Rgba {
  { r: 1.0, g: 1.0, b: 1.0, a: 1.0, }
}

///|
/// Creates the opaque black preset, `(0.0, 0.0, 0.0)`.
pub fn Rgba::black() -> Rgba {
  { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }
}

///|
/// Creates the opaque green preset, `(0.0, 0.8, 0.0)`.
pub fn Rgba::green() -> Rgba {
  { r: 0.0, g: 0.8, b: 0.0, a: 1.0, }
}

///|
/// Creates the opaque red preset, `(0.8, 0.0, 0.0)`.
pub fn Rgba::red() -> Rgba {
  { r: 0.8, g: 0.0, b: 0.0, a: 1.0, }
}

///|
/// Creates the opaque cyan preset, `(0.0, 0.8, 0.8)`.
pub fn Rgba::cyan() -> Rgba {
  { r: 0.0, g: 0.8, b: 0.8, a: 1.0, }
}

///|
/// Creates the opaque yellow preset, `(1.0, 1.0, 0.0)`.
pub fn Rgba::yellow() -> Rgba {
  { r: 1.0, g: 1.0, b: 0.0, a: 1.0, }
}

///|
/// A URDF ``: translation in meters and fixed-axis roll/pitch/yaw in
/// radians.
#derive(Debug, Eq)
pub(all) struct Origin {
  /// Translation `(x, y, z)` in metres, resolved in the parent frame.
  xyz : Vec3
  /// Fixed-axis roll/pitch/yaw rotation about X, Y and Z, in radians.
  rpy : Vec3
}

///|
/// Returns the identity origin: zero translation and zero rotation.
pub fn Origin::identity() -> Origin {
  { xyz: (0.0, 0.0, 0.0), rpy: (0.0, 0.0, 0.0), }
}

///|
/// Creates an origin from a translation in metres and fixed-axis roll/pitch/yaw in radians; both default to zero.
pub fn Origin::new(
  xyz~ : Vec3 = (0.0, 0.0, 0.0),
  rpy~ : Vec3 = (0.0, 0.0, 0.0),
) -> Origin {
  { xyz, rpy, }
}

///|
/// Builds an origin from millimeter translations and degree rotations, which
/// is the natural input unit for CAD-authored components.
pub fn Origin::from_mm_deg(
  x~ : Double = 0.0,
  y~ : Double = 0.0,
  z~ : Double = 0.0,
  rx_deg~ : Double = 0.0,
  ry_deg~ : Double = 0.0,
  rz_deg~ : Double = 0.0,
) -> Origin {
  let d = @math.PI / 180.0
  {
    xyz: (x * 0.001, y * 0.001, z * 0.001),
    rpy: (rx_deg * d, ry_deg * d, rz_deg * d),
  }
}

///|
/// Returns true when every translation and rotation component is within 1e-12 of zero.
pub fn Origin::is_identity(self : Origin) -> Bool {
  let (x, y, z) = self.xyz
  let (r, p, w) = self.rpy
  x.abs() < 1.0e-12 &&
  y.abs() < 1.0e-12 &&
  z.abs() < 1.0e-12 &&
  r.abs() < 1.0e-12 &&
  p.abs() < 1.0e-12 &&
  w.abs() < 1.0e-12
}

///|
/// The shape of a link's visual or collision geometry.
#derive(Debug, Eq)
pub(all) enum Geometry {
  /// Box with dimensions `(sx, sy, sz)` in meters.
  Box(Vec3)
  /// Cylinder with `(radius, length)` in meters, axis along local Z.
  Cylinder(Double, Double)
  /// Sphere with `radius` in meters.
  Sphere(Double)
  /// Mesh file with an optional `(sx, sy, sz)` scale.
  Mesh(String, Vec3?)
}

///|
/// Creates a box geometry with side lengths `sx`, `sy`, `sz` in metres.
pub fn Geometry::box(sx : Double, sy : Double, sz : Double) -> Geometry {
  Box((sx, sy, sz))
}

///|
/// Creates a box geometry from side lengths in millimetres, converted to metres.
pub fn Geometry::box_mm(
  sx_mm : Double,
  sy_mm : Double,
  sz_mm : Double,
) -> Geometry {
  Box((sx_mm * 0.001, sy_mm * 0.001, sz_mm * 0.001))
}

///|
/// Creates a cylinder with `radius` and `length` in metres, its axis along the local Z axis.
pub fn Geometry::cylinder(radius : Double, length : Double) -> Geometry {
  Cylinder(radius, length)
}

///|
/// Creates a cylinder from `radius_mm` and `length_mm` in millimetres, converted to metres; axis along local Z.
pub fn Geometry::cylinder_mm(
  radius_mm : Double,
  length_mm : Double,
) -> Geometry {
  Cylinder(radius_mm * 0.001, length_mm * 0.001)
}

///|
/// Creates a sphere with `radius` in metres.
pub fn Geometry::sphere(radius : Double) -> Geometry {
  Sphere(radius)
}

///|
/// Creates a sphere from `radius_mm` in millimetres, converted to metres.
pub fn Geometry::sphere_mm(radius_mm : Double) -> Geometry {
  Sphere(radius_mm * 0.001)
}

///|
/// Creates a mesh geometry referencing `filename` (resolved by the consumer, typically relative to the URDF file) with an optional per-axis scale.
pub fn Geometry::mesh(filename : String, scale~ : Vec3? = None) -> Geometry {
  Mesh(filename, scale)
}

///|
/// Creates a mesh geometry referencing `filename` (typically in millimetre units) with a uniform 0.001 scale, yielding metre-sized geometry.
pub fn Geometry::mesh_mm(filename : String) -> Geometry {
  Mesh(filename, Some((0.001, 0.001, 0.001)))
}

///|
/// A named material with an optional color and texture.
#derive(Debug, Eq)
pub(all) struct Material {
  /// Material name; referenced by link visuals via URDF's ``.
  name : String
  /// Optional RGBA color applied to the surface; channels in `[0, 1]`.
  color : Rgba?
  /// Optional path or URI of the texture image, resolved like mesh filenames.
  texture : String?
}

///|
/// Creates a material with the given `name`; `color` and `texture` are both optional.
pub fn Material::new(
  name : String,
  color~ : Rgba? = None,
  texture~ : String? = None,
) -> Material {
  { name, color, texture, }
}

///|
/// Creates a material with the given RGBA color and no texture.
pub fn Material::color_only(name : String, color : Rgba) -> Material {
  { name, color: Some(color), texture: None, }
}

///|
/// A verbatim XML element, used to preserve extension tags (``,
/// ``, ``, ...) across parse/serialize roundtrips.
#derive(Debug, Eq)
pub(all) struct RawXmlNode {
  /// The element's tag name, e.g. `"gazebo"`.
  tag : String
  /// Attribute name/value pairs in source order.
  attrs : Array[(String, String)]
  /// Raw text content of the element; empty when the element has no text.
  text : String
  /// Child elements, in source order.
  children : Array[RawXmlNode]
}

///|
/// A visual element on a link.
#derive(Debug, Eq)
pub(all) struct Visual {
  /// Optional name identifying this visual within the link.
  name : String?
  /// Pose of the geometry relative to the link frame; translation in metres, rotation in radians.
  origin : Origin
  /// The shape to render.
  geometry : Geometry
  /// Optional material to render with; may reference a material declared on the robot.
  material : Material?
}

///|
/// A collision element on a link.
#derive(Debug, Eq)
pub(all) struct Collision {
  /// Optional name identifying this collision element within the link.
  name : String?
  /// Pose of the geometry relative to the link frame; translation in metres, rotation in radians.
  origin : Origin
  /// The shape to test for collisions.
  geometry : Geometry
}

///|
/// The symmetric 3x3 inertia tensor of a rigid body.
#derive(Debug, Eq)
pub(all) struct Inertia {
  /// Moment of inertia about the x axis, in kg*m^2.
  ixx : Double
  /// Product of inertia Ixy, in kg*m^2.
  ixy : Double
  /// Product of inertia Ixz, in kg*m^2.
  ixz : Double
  /// Moment of inertia about the y axis, in kg*m^2.
  iyy : Double
  /// Product of inertia Iyz, in kg*m^2.
  iyz : Double
  /// Moment of inertia about the z axis, in kg*m^2.
  izz : Double
}

///|
/// Returns the zero tensor: every component, including the products of inertia, is zero.
pub fn Inertia::zero() -> Inertia {
  { ixx: 0.0, ixy: 0.0, ixz: 0.0, iyy: 0.0, iyz: 0.0, izz: 0.0, }
}

///|
/// Creates a diagonal tensor from the three principal moments in kg*m^2; all Ixy/Ixz/Iyz products are zero.
pub fn Inertia::diagonal(ixx : Double, iyy : Double, izz : Double) -> Inertia {
  { ixx, ixy: 0.0, ixz: 0.0, iyy, iyz: 0.0, izz, }
}

///|
/// Creates a tensor from explicit components in kg*m^2; the off-diagonal products default to zero.
pub fn Inertia::new(
  ixx~ : Double,
  iyy~ : Double,
  izz~ : Double,
  ixy~ : Double = 0.0,
  ixz~ : Double = 0.0,
  iyz~ : Double = 0.0,
) -> Inertia {
  { ixx, ixy, ixz, iyy, iyz, izz, }
}

///|
/// The inertial properties of a link: center-of-mass frame, mass, and tensor.
#derive(Debug, Eq)
pub(all) struct Inertial {
  /// Pose of the center-of-mass frame relative to the link frame; translation in metres, rotation in radians.
  origin : Origin
  /// Mass of the link in kilograms.
  mass : Double
  /// Inertia tensor about the center-of-mass frame, in kg*m^2.
  inertia : Inertia
}

///|
/// A rigid link in the robot tree.
#derive(Debug, Eq)
pub(all) struct Link {
  /// Unique link name within the robot; referenced by joints, transmissions, and other links.
  name : String
  /// Optional inertial properties; required for dynamics but commonly omitted for static models.
  inertial : Inertial?
  /// Visual geometries to render, in declaration order.
  visuals : Array[Visual]
  /// Collision geometries used for collision checking and dynamics; may differ from the visuals.
  collisions : Array[Collision]
  /// Extension elements preserved verbatim for round-tripping.
  extra : Array[RawXmlNode]
}

///|
/// The kind of motion a joint permits.
#derive(Debug, Eq)
pub(all) enum JointType {
  Revolute
  Continuous
  Prismatic
  Fixed
  Floating
  Planar
}

///|
/// Returns the URDF attribute string for this joint type, e.g. `"revolute"`.
pub fn JointType::to_urdf_str(self : JointType) -> String {
  match self {
    Revolute => "revolute"
    Continuous => "continuous"
    Prismatic => "prismatic"
    Fixed => "fixed"
    Floating => "floating"
    Planar => "planar"
  }
}

///|
/// Parses a URDF joint type attribute; returns None for unrecognized strings.
pub fn JointType::from_urdf_str(s : String) -> JointType? {
  match s {
    "revolute" => Some(Revolute)
    "continuous" => Some(Continuous)
    "prismatic" => Some(Prismatic)
    "fixed" => Some(Fixed)
    "floating" => Some(Floating)
    "planar" => Some(Planar)
    _ => None
  }
}

///|
/// Joint travel limits.
#derive(Debug, Eq)
pub(all) struct JointLimit {
  /// Lower travel limit in radians for revolute joints or metres for prismatic joints; None means unbounded below.
  lower : Double?
  /// Upper travel limit in radians for revolute joints or metres for prismatic joints; None means unbounded above.
  upper : Double?
  /// Maximum effort the joint may exert: newton-metres for revolute joints, newtons for prismatic joints.
  effort : Double
  /// Maximum joint velocity: radians per second for revolute joints, metres per second for prismatic joints.
  velocity : Double
}

///|
/// Creates joint limits; `effort` and `velocity` are required, `lower`/`upper` are optional (omit for continuous joints).
pub fn JointLimit::new(
  effort~ : Double,
  velocity~ : Double,
  lower~ : Double? = None,
  upper~ : Double? = None,
) -> JointLimit {
  { lower, upper, effort, velocity, }
}

///|
/// Joint damping and friction.
#derive(Debug, Eq)
pub(all) struct JointDynamics {
  /// Viscous damping coefficient in N*m*s/rad for revolute joints or N*s/m for prismatic joints.
  damping : Double
  /// Coulomb friction coefficient in N*m for revolute joints or N for prismatic joints.
  friction : Double
}

///|
/// Creates joint dynamics coefficients in joint-appropriate units; both default to 0.0.
pub fn JointDynamics::new(
  damping~ : Double = 0.0,
  friction~ : Double = 0.0,
) -> JointDynamics {
  { damping, friction, }
}

///|
/// Joint calibration reference positions.
#derive(Debug, Eq)
pub(all) struct JointCalibration {
  /// Joint position at which the calibration rising edge trips, in the joint's position unit (radians or metres).
  rising : Double?
  /// Joint position at which the calibration falling edge trips, in the joint's position unit (radians or metres).
  falling : Double?
}

///|
/// Joint safety controller limits.
#derive(Debug, Eq)
pub(all) struct SafetyController {
  /// Lower soft limit in the joint's position unit (radians for revolute, metres for prismatic); must lie above the hard lower limit.
  soft_lower_limit : Double
  /// Upper soft limit in the joint's position unit (radians for revolute, metres for prismatic); must lie below the hard upper limit.
  soft_upper_limit : Double
  /// Gain of the safety controller's position feedback term.
  k_position : Double
  /// Gain of the safety controller's velocity feedback term.
  k_velocity : Double
}

///|
/// A joint whose motion is derived from another joint.
#derive(Debug, Eq)
pub(all) struct JointMimic {
  /// Name of the joint to mimic; must reference another joint in the robot.
  joint : String
  /// Scale factor applied to the mimicked joint's position; 1.0 reproduces it exactly.
  multiplier : Double
  /// Constant offset added after scaling, in the mimicked joint's position unit (radians or metres).
  offset : Double
}

///|
/// Creates a mimic declaration for `joint`; `multiplier` defaults to 1.0 and `offset` to 0.0.
pub fn JointMimic::new(
  joint : String,
  multiplier~ : Double = 1.0,
  offset~ : Double = 0.0,
) -> JointMimic {
  { joint, multiplier, offset, }
}

///|
/// A kinematic joint connecting a parent link to a child link.
#derive(Debug, Eq)
pub(all) struct Joint {
  /// Unique joint name within the robot.
  name : String
  /// Kind of motion the joint permits; see JointType.
  joint_type : JointType
  /// Pose of the joint (child) frame relative to the parent link frame; translation in metres, rotation in radians.
  origin : Origin
  /// Name of the parent link.
  parent : String
  /// Name of the child link.
  child : String
  /// Axis of rotation or translation expressed in the joint frame; defaults to `(1, 0, 0)` when omitted in URDF.
  axis : Vec3
  /// Travel, effort and velocity limits; required for revolute and prismatic joints, unused for fixed joints.
  limit : JointLimit?
  /// Optional damping and friction coefficients.
  dynamics : JointDynamics?
  /// Optional calibration reference positions.
  calibration : JointCalibration?
  /// Optional safety-controller soft limits and gains.
  safety_controller : SafetyController?
  /// Optional mimic declaration tying this joint's motion to another joint's.
  mimic : JointMimic?
  /// Extension elements preserved verbatim for round-tripping.
  extra : Array[RawXmlNode]
}

///|
/// A transmission joint entry.
#derive(Debug, Eq)
pub(all) struct TransmissionJoint {
  /// Name of the joint this entry binds; must reference a joint in the robot.
  name : String
  /// Hardware interface names (e.g. `"position"`, `"velocity"`, `"effort"`) the joint commands through.
  hardware_interfaces : Array[String]
}

///|
/// A transmission actuator entry.
#derive(Debug, Eq)
pub(all) struct Actuator {
  /// Name identifying the actuator; referenced by controllers and transmissions.
  name : String
  /// Hardware interface names (e.g. `"position"`, `"velocity"`, `"effort"`) the actuator commands through.
  hardware_interfaces : Array[String]
  /// Ratio of actuator shaft rotation to joint rotation (dimensionless); values greater than 1 indicate a reduction.
  mechanical_reduction : Double?
}

///|
/// A `ros_control` transmission description.
#derive(Debug, Eq)
pub(all) struct Transmission {
  /// Unique transmission name.
  name : String
  /// Transmission type identifier, e.g. `"transmission_interface/SimpleTransmission"`, as written in the `` element.
  trans_type : String
  /// Joints participating in the transmission.
  joints : Array[TransmissionJoint]
  /// Actuators driving the transmission.
  actuators : Array[Actuator]
}

///|
/// A closed-chain constraint between two link frames. Anchors are metres in
/// each link's local frame.
#derive(Debug, Eq)
pub(all) struct LoopConstraint {
  /// Unique constraint name.
  name : String
  /// Name of the first link the constraint connects.
  body1 : String
  /// Anchor point on the first link, in metres in that link's local frame.
  anchor1 : Vec3
  /// Name of the second link the constraint connects.
  body2 : String
  /// Anchor point on the second link, in metres in that link's local frame.
  anchor2 : Vec3
}

///|
/// LoopConstraint::connect builds a closed-chain constraint.
pub fn LoopConstraint::connect(
  name~ : String,
  body1~ : String,
  anchor1~ : Vec3,
  body2~ : String,
  anchor2~ : Vec3,
) -> LoopConstraint {
  { name, body1, anchor1, body2, anchor2, }
}

///|
/// A complete URDF robot model.
#derive(Debug, Eq)
pub(all) struct Robot {
  /// Robot name written to the `` attribute.
  name : String
  /// Optional model version.
  version : String?
  /// Free-form documentation emitted as an XML comment above the robot element.
  documentation : String
  /// Named visual materials referenced by link visuals.
  materials : Array[Material]
  /// Rigid links, each with visuals, collisions and inertial properties.
  links : Array[Link]
  /// Kinematic joints connecting the links.
  joints : Array[Joint]
  /// Actuated joint transmission declarations.
  transmissions : Array[Transmission]
  /// Closed-chain constraints. URDF keeps them as comments; MJCF emits
  /// ``.
  loop_constraints : Array[LoopConstraint]
  /// Extension nodes preserved verbatim for round-tripping.
  extra : Array[RawXmlNode]
}