diff --git a/src/com/annimon/graphics/Matrix.java b/src/com/annimon/graphics/Matrix.java new file mode 100644 index 0000000..327e35c --- /dev/null +++ b/src/com/annimon/graphics/Matrix.java @@ -0,0 +1,109 @@ +package com.annimon.graphics; + +/** + * + * @author aNNiMON + */ +public class Matrix { + + public static Matrix createRotationMatrix(double a) { + Matrix mtx = new Matrix( + Math.cos(a), Math.sin(a), 0, + -Math.sin(a), Math.cos(a), 0, + 0, 0, 1); + return mtx; + } + + public static Matrix createTranslateMatrix(double tx, double ty) { + Matrix mtx = new Matrix( + 1, 0, tx, + 0, 1, ty, + 0, 0, 1); + return mtx; + } + + private final double[][] m; + + public Matrix() { + m = new double[][] { + {1, 0, 0}, + {0, 1, 0}, + {0, 0, 1} + }; + } + + public Matrix(double[][] m) { + this.m = m; + } + + public Matrix(double a11, double a12, double a13, + double a21, double a22, double a23, + double a31, double a32, double a33) { + m = new double[][] { + { a11, a12, a13 }, + { a21, a22, a23 }, + { a31, a32, a33 } + }; + } + + public void reset() { + for (int i = 0; i < m.length; i++) { + m[0][i] = 0; + m[1][i] = 0; + m[2][i] = 0; + } + m[0][0] = m[1][1] = m[2][2] = 1; + } + + public void translate(double tx, double ty) { + m[0][2] += tx; + m[1][2] += ty; + } + + public void multiply(double s) { + for (int i = 0; i < m.length; i++) { + for (int j = 0; j < m[i].length; j++) { + m[i][j] *= s; + } + } + } + + public Matrix multiply(Matrix other) { + final int rowsA = m.length; + final int columnsA = m[0].length; + final int columnsB = other.m.length; + if (columnsB != columnsA) { + throw new RuntimeException("Размеры матриц не совпадают"); + } + + double[][] matrixC = new double[rowsA][columnsB]; + for (int i = 0; i < rowsA; i++) { + for (int j = 0; j < columnsB; j++) { + for (int k = 0; k < columnsA; k++) { + matrixC[i][j] += m[i][k] * other.m[k][j]; + } + } + } + + return new Matrix(matrixC); + } + + public void add(Matrix other) { + for (int i = 0; i < m.length; i++) { + for (int j = 0; j < m[i].length; j++) { + m[i][j] *= other.m[i][j]; + } + } + } + + public final double[] applyTransform(double[] vector) { + final int size = m.length; + double[] result = new double[3]; + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + result[i] += (m[i][j] * vector[j]); + } + } + return result; + } +}