// EXACT layer (design D3): CAD surface constructors built on the curve kernel.
// extrude / loft are exact; revolve / sweep (later in this file) introduce
// rational arcs. References: curvo/src/surface/nurbs_surface.rs (extrude,
// try_loft, try_revolve); geomdl/construct.py, sweeping.py.

///|
/// Extrude a profile curve along a Cartesian `direction` vector. The profile is
/// the u direction; the extrusion is a degree-1 v direction (v=0 profile, v=1
/// profile+direction). Exact.
pub fn NurbsSurface3::extrude(
  profile : NurbsCurve3,
  direction : @f64.DVec3,
) -> NurbsSurface3? {
  let degree_u = profile.bspline.degree
  let knots_u = profile.bspline.knots
  let num_u = profile.bspline.ctrlpts.length()
  let knots_v = match KnotVector::new([0.0, 0.0, 1.0, 1.0]) {
    None => return None
    Some(x) => x
  }
  let grid : FixedArray[@f64.DVec4] = FixedArray::make(num_u * 2, @f64.DVec4::zero())
  for i = 0; i < num_u; i = i + 1 {
    let pw = profile.bspline.ctrlpts[i]
    let w = pw.w
    grid[i * 2] = pw
    grid[i * 2 + 1] = @f64.DVec4::new(
      pw.x + direction.x * w,
      pw.y + direction.y * w,
      pw.z + direction.z * w,
      w,
    )
  }
  NurbsSurface3::new(degree_u, 1, knots_u, knots_v, grid)
}

///|
/// Interpolate homogeneous (DVec4) points with chord-length parameters on their
/// Cartesian xyz, returning control points and the averaged knot vector. Used by
/// loft to blend control-point columns in the v direction (works for rational
/// curves because interpolation is affine in homogeneous space).
fn interpolate_homogeneous(
  points : FixedArray[@f64.DVec4],
  degree : Int,
) -> (FixedArray[@f64.DVec4], KnotVector)? {
  let n = points.length() - 1
  if degree < 1 || n < degree {
    return None
  }
  let uk : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  let mut total = 0.0
  for i = 1; i <= n; i = i + 1 {
    total = total + (points[i].xyz() - points[i - 1].xyz()).length()
  }
  if total == 0.0 {
    return None
  }
  for i = 1; i < n; i = i + 1 {
    uk[i] = uk[i - 1] + (points[i].xyz() - points[i - 1].xyz()).length() / total
  }
  uk[n] = 1.0
  let m = degree + n + 1
  let knots : FixedArray[Double] = FixedArray::make(m + 1, 0.0)
  for i = 0; i <= degree; i = i + 1 {
    knots[i] = 0.0
  }
  for i = n + 1; i <= m; i = i + 1 {
    knots[i] = 1.0
  }
  for j = 1; j <= n - degree; j = j + 1 {
    let mut sum = 0.0
    for i = j; i <= j + degree - 1; i = i + 1 {
      sum = sum + uk[i]
    }
    knots[degree + j] = sum / degree.to_double()
  }
  let kv = match KnotVector::new(knots) {
    None => return None
    Some(x) => x
  }
  let a = dmat(n + 1, n + 1)
  for i = 0; i <= n; i = i + 1 {
    let span = kv.find_span(degree, n, uk[i])
    let basis = kv.basis_funs(span, degree, uk[i])
    for j = 0; j <= degree; j = j + 1 {
      dmat_set(a, i, span - degree + j, basis[j])
    }
  }
  let bx : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  let by : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  let bz : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  let bw : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  for i = 0; i <= n; i = i + 1 {
    bx[i] = points[i].x
    by[i] = points[i].y
    bz[i] = points[i].z
    bw[i] = points[i].w
  }
  let px = match lu_solve(a, bx) {
    None => return None
    Some(x) => x
  }
  let py = match lu_solve(a, by) {
    None => return None
    Some(x) => x
  }
  let pz = match lu_solve(a, bz) {
    None => return None
    Some(x) => x
  }
  let pw = match lu_solve(a, bw) {
    None => return None
    Some(x) => x
  }
  let ctrl : FixedArray[@f64.DVec4] = FixedArray::make(n + 1, @f64.DVec4::zero())
  for i = 0; i <= n; i = i + 1 {
    ctrl[i] = @f64.DVec4::new(px[i], py[i], pz[i], pw[i])
  }
  Some((ctrl, kv))
}

///|
/// Loft through a sequence of compatible curves (same degree, knot vector and
/// control-point count). Each control-point column is interpolated in the v
/// direction. degree_v defaults to min(degree_u, num_curves-1). Exact.
pub fn NurbsSurface3::loft(
  curves : Array[NurbsCurve3],
  degree_v? : Int,
) -> NurbsSurface3? {
  if curves.length() < 2 {
    return None
  }
  let degree_u = curves[0].bspline.degree
  let knots_u = curves[0].bspline.knots
  let num_u = curves[0].bspline.ctrlpts.length()
  for k = 1; k < curves.length(); k = k + 1 {
    if curves[k].bspline.degree != degree_u ||
      curves[k].bspline.ctrlpts.length() != num_u ||
      !knots_equal(curves[k].bspline.knots, knots_u) {
      return None
    }
  }
  let dv = match degree_v {
    Some(x) => x
    None => degree_u
  }
  let dv = if dv < curves.length() - 1 { dv } else { curves.length() - 1 }
  if dv < 1 {
    return None
  }
  // Interpolate each control-point column across curves in v.
  let columns : Array[FixedArray[@f64.DVec4]] = []
  let mut knots_v : KnotVector? = None
  for i = 0; i < num_u; i = i + 1 {
    let col : FixedArray[@f64.DVec4] = FixedArray::make(curves.length(), @f64.DVec4::zero())
    for k = 0; k < curves.length(); k = k + 1 {
      col[k] = curves[k].bspline.ctrlpts[i]
    }
    let (ctrl, kv) = match interpolate_homogeneous(col, dv) {
      None => return None
      Some(x) => x
    }
    columns.push(ctrl)
    knots_v = Some(kv)
  }
  let kv_v = match knots_v {
    None => return None
    Some(x) => x
  }
  let num_v = columns[0].length()
  let grid : FixedArray[@f64.DVec4] = FixedArray::make(num_u * num_v, @f64.DVec4::zero())
  for i = 0; i < num_u; i = i + 1 {
    for j = 0; j < num_v; j = j + 1 {
      grid[i * num_v + j] = columns[i][j]
    }
  }
  NurbsSurface3::new(degree_u, dv, knots_u, kv_v, grid)
}

///|
fn knots_equal(a : KnotVector, b : KnotVector) -> Bool {
  if a.knots.length() != b.knots.length() {
    return false
  }
  for i = 0; i < a.knots.length(); i = i + 1 {
    if a.knots[i] != b.knots[i] {
      return false
    }
  }
  true
}

///|
/// Revolve a profile curve around an axis (point `center`, direction `axis`) by
/// angle `theta` (radians, |theta| <= 2pi). The profile is the u direction; the
/// revolution is a rational quadratic-arc v direction split into 1..4 segments
/// (each <= pi/2). The middle control point of each arc sits at radius
/// r / cos(dtheta/2) at the mid-angle (analytic tangent intersection).
/// Reference: curvo try_revolve_by_start_end (start = 0).
pub fn NurbsSurface3::revolve(
  profile : NurbsCurve3,
  center : @f64.DVec3,
  axis : @f64.DVec3,
  theta : Double,
) -> NurbsSurface3? {
  let ax = match axis.try_normalize() {
    None => return None
    Some(x) => x
  }
  let pi = 3.141592653589793
  let abs_theta = theta.abs()
  if abs_theta > 2.0 * pi + 1.0e-9 || abs_theta == 0.0 {
    return None
  }
  let narcs = if abs_theta <= pi / 2.0 {
    1
  } else if abs_theta <= pi {
    2
  } else if abs_theta <= 3.0 * pi / 2.0 {
    3
  } else {
    4
  }
  let num_v = 2 * narcs + 1
  // Revolution knot vector: 0^3, internal (k/narcs)^2, 1^3.
  let kv_arr : FixedArray[Double] = FixedArray::make(6 + 2 * (narcs - 1), 0.0)
  for k = 1; k < narcs; k = k + 1 {
    let frac = k.to_double() / narcs.to_double()
    kv_arr[3 + 2 * (k - 1)] = frac
    kv_arr[3 + 2 * (k - 1) + 1] = frac
  }
  let last = kv_arr.length() - 1
  kv_arr[last] = 1.0
  kv_arr[last - 1] = 1.0
  kv_arr[last - 2] = 1.0
  let knots_v = match KnotVector::new(kv_arr) {
    None => return None
    Some(x) => x
  }
  let dtheta = theta / narcs.to_double()
  let wm = @math.cos(dtheta / 2.0)
  let degree_u = profile.bspline.degree
  let knots_u = profile.bspline.knots
  let num_u = profile.bspline.ctrlpts.length()
  let grid : FixedArray[@f64.DVec4] = FixedArray::make(num_u * num_v, @f64.DVec4::zero())
  for i = 0; i < num_u; i = i + 1 {
    let pw = profile.bspline.ctrlpts[i]
    let w = pw.w
    let p = pw.xyz().scale(1.0 / w)
    let s = (p - center).dot(ax)
    let o = center + ax.scale(s)
    let x = p - o // perpendicular vector, magnitude r
    let r = x.length()
    let y = ax.cross(x) // perpendicular to x and axis, magnitude r
    let base = i * num_v
    if r <= 1.0e-12 {
      // Point on the axis: revolution leaves it fixed.
      for row = 0; row < num_v; row = row + 1 {
        let rw = if row % 2 == 0 { w } else { wm * w }
        grid[base + row] = o.scale(rw).extend_w(rw)
      }
    } else {
      // Row 0: profile point (angle 0).
      grid[base] = p.scale(w).extend_w(w)
      for k = 1; k <= narcs; k = k + 1 {
        let angle = k.to_double() * dtheta
        let p2 = o + x.scale(@math.cos(angle)) + y.scale(@math.sin(angle))
        grid[base + 2 * k] = p2.scale(w).extend_w(w)
        let mid_angle = (k.to_double() - 0.5) * dtheta
        let mid = o +
          (x.scale(@math.cos(mid_angle)) + y.scale(@math.sin(mid_angle))).scale(1.0 / wm)
        let mw = wm * w
        grid[base + 2 * k - 1] = mid.scale(mw).extend_w(mw)
      }
    }
  }
  NurbsSurface3::new(degree_u, 2, knots_u, knots_v, grid)
}

///|
/// Rotate `v` by the rotation taking unit vector `from` to unit vector `to`
/// (rotation-minimizing transport), via a quaternion about `from x to`.
fn transport_frame(
  n_prev : @f64.DVec3,
  t_prev : @f64.DVec3,
  t_cur : @f64.DVec3,
) -> @f64.DVec3 {
  let axis = t_prev.cross(t_cur)
  let len = axis.length()
  if len < 1.0e-12 {
    return n_prev
  }
  let mut d = t_prev.dot(t_cur)
  if d > 1.0 {
    d = 1.0
  }
  if d < -1.0 {
    d = -1.0
  }
  let angle = @math.acos(d)
  let q = @f64.DQuat::from_axis_angle(axis.scale(1.0 / len), angle)
  q.mul_vec3(n_prev)
}

///|
/// A reference unit normal perpendicular to unit tangent `t`.
fn reference_normal(t : @f64.DVec3) -> @f64.DVec3 {
  let ref_vec = if t.z.abs() < 0.9 {
    @f64.DVec3::unit_z()
  } else {
    @f64.DVec3::unit_x()
  }
  ref_vec.cross(t).normalize()
}

///|
/// Sweep a profile curve along a path (spine) using rotation-minimizing
/// (parallel-transport) frames. The profile is rigidly carried along the path:
/// its coordinates relative to the start frame are re-expressed in each sampled
/// frame, and the transformed profiles are lofted. Exact for a straight path;
/// a sampled approximation for curved paths (increase `samples` for accuracy).
pub fn NurbsSurface3::sweep(
  profile : NurbsCurve3,
  path : NurbsCurve3,
  samples? : Int = 16,
) -> NurbsSurface3? {
  if samples < 1 {
    return None
  }
  let n = path.bspline.ctrlpts.length() - 1
  let knots = path.bspline.knots.knots
  let u0 = knots[path.bspline.degree]
  let u1 = knots[n + 1]
  // Initial frame at the path start.
  let p0 = match path.point_at(u0) {
    None => return None
    Some(x) => x
  }
  let t0 = match path.derivatives(u0, 1) {
    None => return None
    Some(d) => match d[1].try_normalize() {
      None => return None
      Some(x) => x
    }
  }
  let n0 = reference_normal(t0)
  let b0 = t0.cross(n0)
  let profiles : Array[NurbsCurve3] = []
  let mut prev_t = t0
  let mut prev_n = n0
  for k = 0; k <= samples; k = k + 1 {
    let u = u0 + (u1 - u0) * (k.to_double() / samples.to_double())
    let pk = match path.point_at(u) {
      None => return None
      Some(x) => x
    }
    let tk = match path.derivatives(u, 1) {
      None => return None
      Some(d) => match d[1].try_normalize() {
        None => return None
        Some(x) => x
      }
    }
    let nk = if k == 0 { n0 } else { transport_frame(prev_n, prev_t, tk) }
    let bk = tk.cross(nk)
    // Transform each homogeneous profile control point into the current frame.
    let num = profile.bspline.ctrlpts.length()
    let new_pts : FixedArray[@f64.DVec4] = FixedArray::make(num, @f64.DVec4::zero())
    for i = 0; i < num; i = i + 1 {
      let pw = profile.bspline.ctrlpts[i]
      let w = pw.w
      let q = pw.xyz().scale(1.0 / w)
      let rel = q - p0
      let lx = rel.dot(n0)
      let ly = rel.dot(b0)
      let lz = rel.dot(t0)
      let qk = pk + nk.scale(lx) + bk.scale(ly) + tk.scale(lz)
      new_pts[i] = qk.scale(w).extend_w(w)
    }
    let transformed = match NurbsCurve3::new_homogeneous(
      profile.bspline.degree,
      profile.bspline.knots,
      new_pts,
    ) {
      None => return None
      Some(x) => x
    }
    profiles.push(transformed)
    prev_t = tk
    prev_n = nk
  }
  NurbsSurface3::loft(profiles)
}