package path import ( "fmt" "git.wtrh.nl/patterns/gopatterns/pkg/pattern/point" "github.com/tdewolff/canvas" splines "gitlab.com/Achilleshiel/gosplines" ) const resolution = 40 // Spline defines a smooth curved path through points. type Spline struct { Path start, end point.Point } // NewSpline returns a new spline through points. Start and end points can be provided as // the start and stop direction of the spline. When start or end point arguments are left nil there // are no constraints on the direction. func NewSpline(start, end point.Point, points ...point.Point) Spline { s := Spline{ Path: NewPath(points...), start: start, end: end, } if start == nil && len(points) > 1 { s.start = points[0] } if end == nil && len(points) > 1 { s.end = points[len(points)-1] } return s } // Draw the spline to the provided [canvas.Canvas]. func (p Spline) Draw(c *canvas.Canvas) error { if len(p.points) < 2 { return nil } x := make([]float64, len(p.points)) y := make([]float64, len(p.points)) for i, point := range p.points { x[i], y[i] = point.Vector().Values() } diffStart := p.start.Vector().Subtract(p.points[0].Vector()) diffEnd := p.points[len(p.points)-1].Vector().Subtract(p.end.Vector()) xCoefficient, err := splines.SolveSplineWithConstraint(x, diffStart.X, diffEnd.X) if err != nil { return fmt.Errorf("unable to calculate coefficients for x: %w", err) } yCoefficient, err := splines.SolveSplineWithConstraint(y, diffStart.Y, diffEnd.Y) if err != nil { return fmt.Errorf("unable to calculate coefficients for y: %w", err) } points := make([]point.Point, 0, len(x)*resolution) stepSize := 1.0 / float64(resolution-1) for i := range len(p.points) - 1 { points = append(points, p.points[i]) for t := stepSize; t < 1.0; t += stepSize { xCalculated := xCoefficient[i].Calculate(t) yCalculated := yCoefficient[i].Calculate(t) points = append(points, point.NewAbsolutePoint(xCalculated, yCalculated, 0, "0")) } } points = append(points, p.points[len(p.points)-1]) err = NewPath(points...).Draw(c) if err != nil { return fmt.Errorf("draw spline points to canvas: %w", err) } return nil }