matrix.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package gg
  2. import "math"
  3. type Matrix struct {
  4. XX, YX, XY, YY, X0, Y0 float64
  5. }
  6. func Identity() Matrix {
  7. return Matrix{
  8. 1, 0,
  9. 0, 1,
  10. 0, 0,
  11. }
  12. }
  13. func Translate(x, y float64) Matrix {
  14. return Matrix{
  15. 1, 0,
  16. 0, 1,
  17. x, y,
  18. }
  19. }
  20. func Scale(x, y float64) Matrix {
  21. return Matrix{
  22. x, 0,
  23. 0, y,
  24. 0, 0,
  25. }
  26. }
  27. func Rotate(angle float64) Matrix {
  28. c := math.Cos(angle)
  29. s := math.Sin(angle)
  30. return Matrix{
  31. c, s,
  32. -s, c,
  33. 0, 0,
  34. }
  35. }
  36. func Shear(x, y float64) Matrix {
  37. return Matrix{
  38. 1, y,
  39. x, 1,
  40. 0, 0,
  41. }
  42. }
  43. func (a Matrix) Multiply(b Matrix) Matrix {
  44. return Matrix{
  45. a.XX*b.XX + a.YX*b.XY,
  46. a.XX*b.YX + a.YX*b.YY,
  47. a.XY*b.XX + a.YY*b.XY,
  48. a.XY*b.YX + a.YY*b.YY,
  49. a.X0*b.XX + a.Y0*b.XY + b.X0,
  50. a.X0*b.YX + a.Y0*b.YY + b.Y0,
  51. }
  52. }
  53. func (a Matrix) TransformVector(x, y float64) (tx, ty float64) {
  54. tx = a.XX*x + a.XY*y
  55. ty = a.YX*x + a.YY*y
  56. return
  57. }
  58. func (a Matrix) TransformPoint(x, y float64) (tx, ty float64) {
  59. tx = a.XX*x + a.XY*y + a.X0
  60. ty = a.YX*x + a.YY*y + a.Y0
  61. return
  62. }
  63. func (a Matrix) Translate(x, y float64) Matrix {
  64. return Translate(x, y).Multiply(a)
  65. }
  66. func (a Matrix) Scale(x, y float64) Matrix {
  67. return Scale(x, y).Multiply(a)
  68. }
  69. func (a Matrix) Rotate(angle float64) Matrix {
  70. return Rotate(angle).Multiply(a)
  71. }
  72. func (a Matrix) Shear(x, y float64) Matrix {
  73. return Shear(x, y).Multiply(a)
  74. }