Vec.hs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE FlexibleInstances #-}
  3. module Vec
  4. ( Vec
  5. , Vec2
  6. , Vec3
  7. , vcycle
  8. , vadd
  9. , vsub
  10. , vmul
  11. , vdiv
  12. , vnegate
  13. , vmag
  14. , vdist
  15. , vproject
  16. , v2rotate
  17. , v3rotate
  18. , vlerp
  19. ) where
  20. class Vec a where
  21. vcycle :: a -> a
  22. vadd :: a -> a -> a
  23. vsub :: a -> a -> a
  24. vsub a b = vadd a $ vnegate b
  25. vmul :: a -> Double -> a
  26. vdiv :: a -> Double -> a
  27. vdiv a b = vmul a (1 / b)
  28. vnegate :: a -> a
  29. vmag :: a -> Double
  30. vdist :: a -> a -> Double
  31. vdist a b = vmag (vsub a b)
  32. type Vec2 = (Double, Double)
  33. type Vec3 = (Double, Double, Double)
  34. instance Vec Vec3 where
  35. vcycle (x, y, z) = (y, z, x)
  36. vadd (x, y, z) (a, b, c) = (x + a, y + b, z + c)
  37. vmul (x, y, z) a = (x * a, y * a, z * a)
  38. vnegate (x, y, z) = (-x, -y, -z)
  39. vmag (x, y, z) = sqrt $ x * x + y * y + z * z
  40. instance Vec Vec2 where
  41. vcycle (x, y) = (y, x)
  42. vadd (x, y) (a, b) = (x + a, y + b)
  43. vmul (x, y) a = (x * a, y * a)
  44. vnegate (x, y) = (-x, -y)
  45. vmag (x, y) = sqrt $ x * x + y * y
  46. vproject :: Vec3 -> Vec2
  47. vproject (x, y, z) = vdiv (x, y) (1 + z)
  48. v2rotate :: Vec2 -> Double -> Vec2
  49. v2rotate (x, y) t = (x * (cos t) - y * (sin t), x * (sin t) + y * (cos t))
  50. v3rotate :: Vec3 -> Vec3 -> Vec3
  51. v3rotate v (a, b, c) = rx a $ ry b $ rz c v
  52. where
  53. rx t (x, y, z) = (x, fst $ v2rotate (y, z) t, snd $ v2rotate (y, z) t)
  54. ry t (x, y, z) = (fst $ v2rotate (x, z) t, y, snd $ v2rotate (x, z) t)
  55. rz t (x, y, z) = (fst $ v2rotate (x, y) t, snd $ v2rotate (x, y) t, z)
  56. vlerp :: Vec v => v -> v -> Double -> v
  57. vlerp a b c = vadd a $ vmul (vsub b a) c