// Vector-space abstraction for the generic B-spline kernel (design D2).
//
// The kernel writes every knot/degree/evaluation algorithm ONCE against this
// trait, then instantiates it for DVec2 / DVec3 / DVec4. NURBS is the perspective
// projection of a homogeneous (DVec4) B-spline, so rational evaluation is a single
// division by w at the very end (Piegl & Tiller factorization).
//
// Method names are prefixed `v*` to avoid clashing with the inherent DVec*
// methods and the core `Add`/`Mul` operator traits.

///|
pub trait VecSpace {
  vzero() -> Self
  vadd(Self, Self) -> Self
  vscale(Self, Double) -> Self
  vlength(Self) -> Double
}

///|
/// Distance induced by the vector-space norm (used by tolerance-driven knot
/// removal in the approximate layer).
pub fn[V : VecSpace] vdistance(a : V, b : V) -> Double {
  a.vadd(b.vscale(-1.0)).vlength()
}

///|
pub impl VecSpace for @f64.DVec2 with vzero() {
  @f64.DVec2::zero()
}

///|
pub impl VecSpace for @f64.DVec2 with vadd(self, other) {
  self + other
}

///|
pub impl VecSpace for @f64.DVec2 with vscale(self, s) {
  @f64.DVec2::scale(self, s)
}

///|
pub impl VecSpace for @f64.DVec2 with vlength(self) {
  @f64.DVec2::length(self)
}

///|
pub impl VecSpace for @f64.DVec3 with vzero() {
  @f64.DVec3::zero()
}

///|
pub impl VecSpace for @f64.DVec3 with vadd(self, other) {
  self + other
}

///|
pub impl VecSpace for @f64.DVec3 with vscale(self, s) {
  @f64.DVec3::scale(self, s)
}

///|
pub impl VecSpace for @f64.DVec3 with vlength(self) {
  @f64.DVec3::length(self)
}

///|
pub impl VecSpace for @f64.DVec4 with vzero() {
  @f64.DVec4::zero()
}

///|
pub impl VecSpace for @f64.DVec4 with vadd(self, other) {
  self + other
}

///|
pub impl VecSpace for @f64.DVec4 with vscale(self, s) {
  @f64.DVec4::scale(self, s)
}

///|
pub impl VecSpace for @f64.DVec4 with vlength(self) {
  @f64.DVec4::length(self)
}

///|
/// Generic linear interpolation — the simplest algorithm that exercises the
/// trait. Used as the D2 feasibility probe before building the full kernel.
pub fn[V : VecSpace] vlerp(a : V, b : V, t : Double) -> V {
  a.vscale(1.0 - t).vadd(b.vscale(t))
}

///|
/// Generic affine combination of a slice with weights (de Boor's inner loop
/// shape). Validates that generic code can fold over a FixedArray of V.
pub fn[V : VecSpace] vcombine(points : FixedArray[V], weights : FixedArray[Double]) -> V {
  let mut acc = V::vzero()
  for i = 0; i < points.length(); i = i + 1 {
    acc = acc.vadd(points[i].vscale(weights[i]))
  }
  acc
}