envelope.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright (c) 2014 The mathutil Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mathutil // import "modernc.org/mathutil"
  5. import (
  6. "math"
  7. )
  8. // Approximation type determines approximation methods used by e.g. Envelope.
  9. type Approximation int
  10. // Specific approximation method tags
  11. const (
  12. _ Approximation = iota
  13. Linear // As named
  14. Sinusoidal // Smooth for all derivations
  15. )
  16. // Envelope is an utility for defining simple curves using a small (usually)
  17. // set of data points. Envelope returns a value defined by x, points and
  18. // approximation. The value of x must be in [0,1) otherwise the result is
  19. // undefined or the function may panic. Points are interpreted as dividing the
  20. // [0,1) interval in len(points)-1 sections, so len(points) must be > 1 or the
  21. // function may panic. According to the left and right points closing/adjacent
  22. // to the section the resulting value is interpolated using the chosen
  23. // approximation method. Unsupported values of approximation are silently
  24. // interpreted as 'Linear'.
  25. func Envelope(x float64, points []float64, approximation Approximation) float64 {
  26. step := 1 / float64(len(points)-1)
  27. fslot := math.Floor(x / step)
  28. mod := x - fslot*step
  29. slot := int(fslot)
  30. l, r := points[slot], points[slot+1]
  31. rmod := mod / step
  32. switch approximation {
  33. case Sinusoidal:
  34. k := (math.Sin(math.Pi*(rmod-0.5)) + 1) / 2
  35. return l + (r-l)*k
  36. case Linear:
  37. fallthrough
  38. default:
  39. return l + (r-l)*rmod
  40. }
  41. }