formatting edits & doc correction, no functional changes.
[blender.git] / source / blender / python / mathutils / mathutils_Matrix.c
1 /*
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * Contributor(s): Michel Selten & Joseph Gilbert
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/python/mathutils/mathutils_Matrix.c
28  *  \ingroup pymathutils
29  */
30
31
32 #include <Python.h>
33
34 #include "mathutils.h"
35
36 #include "BLI_math.h"
37 #include "BLI_utildefines.h"
38
39 static PyObject *Matrix_copy(MatrixObject *self);
40 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value);
41 static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self);
42
43 /* matrix vector callbacks */
44 int mathutils_matrix_vector_cb_index= -1;
45
46 static int mathutils_matrix_vector_check(BaseMathObject *bmo)
47 {
48         MatrixObject *self= (MatrixObject *)bmo->cb_user;
49         return BaseMath_ReadCallback(self);
50 }
51
52 static int mathutils_matrix_vector_get(BaseMathObject *bmo, int subtype)
53 {
54         MatrixObject *self= (MatrixObject *)bmo->cb_user;
55         int i;
56
57         if (BaseMath_ReadCallback(self) == -1)
58                 return -1;
59
60         for (i=0; i < self->col_size; i++)
61                 bmo->data[i]= self->matrix[subtype][i];
62
63         return 0;
64 }
65
66 static int mathutils_matrix_vector_set(BaseMathObject *bmo, int subtype)
67 {
68         MatrixObject *self= (MatrixObject *)bmo->cb_user;
69         int i;
70
71         if (BaseMath_ReadCallback(self) == -1)
72                 return -1;
73
74         for (i=0; i < self->col_size; i++)
75                 self->matrix[subtype][i]= bmo->data[i];
76
77         (void)BaseMath_WriteCallback(self);
78         return 0;
79 }
80
81 static int mathutils_matrix_vector_get_index(BaseMathObject *bmo, int subtype, int index)
82 {
83         MatrixObject *self= (MatrixObject *)bmo->cb_user;
84
85         if (BaseMath_ReadCallback(self) == -1)
86                 return -1;
87
88         bmo->data[index]= self->matrix[subtype][index];
89         return 0;
90 }
91
92 static int mathutils_matrix_vector_set_index(BaseMathObject *bmo, int subtype, int index)
93 {
94         MatrixObject *self= (MatrixObject *)bmo->cb_user;
95
96         if (BaseMath_ReadCallback(self) == -1)
97                 return -1;
98
99         self->matrix[subtype][index]= bmo->data[index];
100
101         (void)BaseMath_WriteCallback(self);
102         return 0;
103 }
104
105 Mathutils_Callback mathutils_matrix_vector_cb = {
106         mathutils_matrix_vector_check,
107         mathutils_matrix_vector_get,
108         mathutils_matrix_vector_set,
109         mathutils_matrix_vector_get_index,
110         mathutils_matrix_vector_set_index
111 };
112 /* matrix vector callbacks, this is so you can do matrix[i][j] = val  */
113
114 //----------------------------------mathutils.Matrix() -----------------
115 //mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
116 //create a new matrix type
117 static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
118 {
119         if (kwds && PyDict_Size(kwds)) {
120                 PyErr_SetString(PyExc_TypeError,
121                                 "Matrix(): "
122                                 "takes no keyword args");
123                 return NULL;
124         }
125
126         switch(PyTuple_GET_SIZE(args)) {
127                 case 0:
128                         return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW, type);
129                 case 1:
130                 {
131                         PyObject *arg= PyTuple_GET_ITEM(args, 0);
132
133                         /* -1 is an error, size checks will accunt for this */
134                         const unsigned short row_size= PySequence_Size(arg);
135
136                         if (row_size >= 2 && row_size <= 4) {
137                                 PyObject *item= PySequence_GetItem(arg, 0);
138                                 const unsigned short col_size= PySequence_Size(item);
139                                 Py_XDECREF(item);
140
141                                 if (col_size >= 2 && col_size <= 4) {
142                                         /* sane row & col size, new matrix and assign as slice  */
143                                         PyObject *matrix= newMatrixObject(NULL, row_size, col_size, Py_NEW, type);
144                                         if (Matrix_ass_slice((MatrixObject *)matrix, 0, INT_MAX, arg) == 0) {
145                                                 return matrix;
146                                         }
147                                         else { /* matrix ok, slice assignment not */
148                                                 Py_DECREF(matrix);
149                                         }
150                                 }
151                         }
152                 }
153         }
154
155         /* will overwrite error */
156         PyErr_SetString(PyExc_TypeError,
157                         "Matrix(): "
158                         "expects no args or 2-4 numeric sequences");
159         return NULL;
160 }
161
162 static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self)
163 {
164         PyObject *ret= Matrix_copy(self);
165         PyObject *ret_dummy= matrix_func(ret);
166         if (ret_dummy) {
167                 Py_DECREF(ret_dummy);
168                 return (PyObject *)ret;
169         }
170         else { /* error */
171                 Py_DECREF(ret);
172                 return NULL;
173         }
174 }
175
176 /* when a matrix is 4x4 size but initialized as a 3x3, re-assign values for 4x4 */
177 static void matrix_3x3_as_4x4(float mat[16])
178 {
179         mat[10] = mat[8];
180         mat[9] = mat[7];
181         mat[8] = mat[6];
182         mat[7] = 0.0f;
183         mat[6] = mat[5];
184         mat[5] = mat[4];
185         mat[4] = mat[3];
186         mat[3] = 0.0f;
187 }
188
189 /*-----------------------CLASS-METHODS----------------------------*/
190
191 //mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
192 PyDoc_STRVAR(C_Matrix_Rotation_doc,
193 ".. classmethod:: Rotation(angle, size, axis)\n"
194 "\n"
195 "   Create a matrix representing a rotation.\n"
196 "\n"
197 "   :arg angle: The angle of rotation desired, in radians.\n"
198 "   :type angle: float\n"
199 "   :arg size: The size of the rotation matrix to construct [2, 4].\n"
200 "   :type size: int\n"
201 "   :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object\n"
202 "      (optional when size is 2).\n"
203 "   :type axis: string or :class:`Vector`\n"
204 "   :return: A new rotation matrix.\n"
205 "   :rtype: :class:`Matrix`\n"
206 );
207 static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
208 {
209         PyObject *vec= NULL;
210         const char *axis= NULL;
211         int matSize;
212         double angle; /* use double because of precision problems at high values */
213         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
214                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
215
216         if (!PyArg_ParseTuple(args, "di|O", &angle, &matSize, &vec)) {
217                 PyErr_SetString(PyExc_TypeError,
218                                 "Matrix.Rotation(angle, size, axis): "
219                                 "expected float int and a string or vector");
220                 return NULL;
221         }
222
223         if (vec && PyUnicode_Check(vec)) {
224                 axis= _PyUnicode_AsString((PyObject *)vec);
225                 if (axis==NULL || axis[0]=='\0' || axis[1]!='\0' || axis[0] < 'X' || axis[0] > 'Z') {
226                         PyErr_SetString(PyExc_ValueError,
227                                         "Matrix.Rotation(): "
228                                         "3rd argument axis value must be a 3D vector "
229                                         "or a string in 'X', 'Y', 'Z'");
230                         return NULL;
231                 }
232                 else {
233                         /* use the string */
234                         vec= NULL;
235                 }
236         }
237
238         angle= angle_wrap_rad(angle);
239
240         if (matSize != 2 && matSize != 3 && matSize != 4) {
241                 PyErr_SetString(PyExc_ValueError,
242                                 "Matrix.Rotation(): "
243                                 "can only return a 2x2 3x3 or 4x4 matrix");
244                 return NULL;
245         }
246         if (matSize == 2 && (vec != NULL)) {
247                 PyErr_SetString(PyExc_ValueError,
248                                 "Matrix.Rotation(): "
249                                 "cannot create a 2x2 rotation matrix around arbitrary axis");
250                 return NULL;
251         }
252         if ((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
253                 PyErr_SetString(PyExc_ValueError,
254                                 "Matrix.Rotation(): "
255                                 "axis of rotation for 3d and 4d matrices is required");
256                 return NULL;
257         }
258
259         /* check for valid vector/axis above */
260         if (vec) {
261                 float tvec[3];
262
263                 if (mathutils_array_parse(tvec, 3, 3, vec, "Matrix.Rotation(angle, size, axis), invalid 'axis' arg") == -1)
264                         return NULL;
265
266                 axis_angle_to_mat3((float (*)[3])mat, tvec, angle);
267         }
268         else if (matSize == 2) {
269                 const float angle_cos= cosf(angle);
270                 const float angle_sin= sinf(angle);
271
272                 //2D rotation matrix
273                 mat[0] =  angle_cos;
274                 mat[1] =  angle_sin;
275                 mat[2] = -angle_sin;
276                 mat[3] =  angle_cos;
277         }
278         else {
279                 /* valid axis checked above */
280                 single_axis_angle_to_mat3((float (*)[3])mat, axis[0], angle);
281         }
282
283         if (matSize == 4) {
284                 matrix_3x3_as_4x4(mat);
285         }
286         //pass to matrix creation
287         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
288 }
289
290
291 PyDoc_STRVAR(C_Matrix_Translation_doc,
292 ".. classmethod:: Translation(vector)\n"
293 "\n"
294 "   Create a matrix representing a translation.\n"
295 "\n"
296 "   :arg vector: The translation vector.\n"
297 "   :type vector: :class:`Vector`\n"
298 "   :return: An identity matrix with a translation.\n"
299 "   :rtype: :class:`Matrix`\n"
300 );
301 static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
302 {
303         float mat[16], tvec[3];
304
305         if (mathutils_array_parse(tvec, 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1)
306                 return NULL;
307
308         /* create a identity matrix and add translation */
309         unit_m4((float(*)[4]) mat);
310         copy_v3_v3(mat + 12, tvec); /* 12, 13, 14 */
311         return newMatrixObject(mat, 4, 4, Py_NEW, (PyTypeObject *)cls);
312 }
313 //----------------------------------mathutils.Matrix.Scale() -------------
314 //mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
315 PyDoc_STRVAR(C_Matrix_Scale_doc,
316 ".. classmethod:: Scale(factor, size, axis)\n"
317 "\n"
318 "   Create a matrix representing a scaling.\n"
319 "\n"
320 "   :arg factor: The factor of scaling to apply.\n"
321 "   :type factor: float\n"
322 "   :arg size: The size of the scale matrix to construct [2, 4].\n"
323 "   :type size: int\n"
324 "   :arg axis: Direction to influence scale. (optional).\n"
325 "   :type axis: :class:`Vector`\n"
326 "   :return: A new scale matrix.\n"
327 "   :rtype: :class:`Matrix`\n"
328 );
329 static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
330 {
331         PyObject *vec= NULL;
332         int vec_size;
333         float tvec[3];
334         float factor;
335         int matSize;
336         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
337                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
338
339         if (!PyArg_ParseTuple(args, "fi|O:Matrix.Scale", &factor, &matSize, &vec)) {
340                 return NULL;
341         }
342         if (matSize != 2 && matSize != 3 && matSize != 4) {
343                 PyErr_SetString(PyExc_ValueError,
344                                 "Matrix.Scale(): "
345                                 "can only return a 2x2 3x3 or 4x4 matrix");
346                 return NULL;
347         }
348         if (vec) {
349                 vec_size= (matSize == 2 ? 2 : 3);
350                 if (mathutils_array_parse(tvec, vec_size, vec_size, vec, "Matrix.Scale(factor, size, axis), invalid 'axis' arg") == -1) {
351                         return NULL;
352                 }
353         }
354         if (vec == NULL) {      //scaling along axis
355                 if (matSize == 2) {
356                         mat[0] = factor;
357                         mat[3] = factor;
358                 }
359                 else {
360                         mat[0] = factor;
361                         mat[4] = factor;
362                         mat[8] = factor;
363                 }
364         }
365         else { //scaling in arbitrary direction
366                 //normalize arbitrary axis
367                 float norm = 0.0f;
368                 int x;
369                 for (x = 0; x < vec_size; x++) {
370                         norm += tvec[x] * tvec[x];
371                 }
372                 norm = (float) sqrt(norm);
373                 for (x = 0; x < vec_size; x++) {
374                         tvec[x] /= norm;
375                 }
376                 if (matSize == 2) {
377                         mat[0] = 1 + ((factor - 1) *(tvec[0] * tvec[0]));
378                         mat[1] =     ((factor - 1) *(tvec[0] * tvec[1]));
379                         mat[2] =     ((factor - 1) *(tvec[0] * tvec[1]));
380                         mat[3] = 1 + ((factor - 1) *(tvec[1] * tvec[1]));
381                 }
382                 else {
383                         mat[0] = 1 + ((factor - 1) *(tvec[0] * tvec[0]));
384                         mat[1] =     ((factor - 1) *(tvec[0] * tvec[1]));
385                         mat[2] =     ((factor - 1) *(tvec[0] * tvec[2]));
386                         mat[3] =     ((factor - 1) *(tvec[0] * tvec[1]));
387                         mat[4] = 1 + ((factor - 1) *(tvec[1] * tvec[1]));
388                         mat[5] =     ((factor - 1) *(tvec[1] * tvec[2]));
389                         mat[6] =     ((factor - 1) *(tvec[0] * tvec[2]));
390                         mat[7] =     ((factor - 1) *(tvec[1] * tvec[2]));
391                         mat[8] = 1 + ((factor - 1) *(tvec[2] * tvec[2]));
392                 }
393         }
394         if (matSize == 4) {
395                 matrix_3x3_as_4x4(mat);
396         }
397         //pass to matrix creation
398         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
399 }
400 //----------------------------------mathutils.Matrix.OrthoProjection() ---
401 //mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc.
402 PyDoc_STRVAR(C_Matrix_OrthoProjection_doc,
403 ".. classmethod:: OrthoProjection(axis, size)\n"
404 "\n"
405 "   Create a matrix to represent an orthographic projection.\n"
406 "\n"
407 "   :arg axis: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
408 "      where a single axis is for a 2D matrix.\n"
409 "      Or a vector for an arbitrary axis\n"
410 "   :type axis: string or :class:`Vector`\n"
411 "   :arg size: The size of the projection matrix to construct [2, 4].\n"
412 "   :type size: int\n"
413 "   :return: A new projection matrix.\n"
414 "   :rtype: :class:`Matrix`\n"
415 );
416 static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
417 {
418         PyObject *axis;
419
420         int matSize, x;
421         float norm = 0.0f;
422         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
423                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
424
425         if (!PyArg_ParseTuple(args, "Oi:Matrix.OrthoProjection", &axis, &matSize)) {
426                 return NULL;
427         }
428         if (matSize != 2 && matSize != 3 && matSize != 4) {
429                 PyErr_SetString(PyExc_ValueError,
430                                 "Matrix.OrthoProjection(): "
431                                 "can only return a 2x2 3x3 or 4x4 matrix");
432                 return NULL;
433         }
434
435         if (PyUnicode_Check(axis)) {    //ortho projection onto cardinal plane
436                 Py_ssize_t plane_len;
437                 const char *plane= _PyUnicode_AsStringAndSize(axis, &plane_len);
438                 if (matSize == 2) {
439                         if (plane_len == 1 && plane[0]=='X') {
440                                 mat[0]= 1.0f;
441                         }
442                         else if (plane_len == 1 && plane[0]=='Y') {
443                                 mat[3]= 1.0f;
444                         }
445                         else {
446                                 PyErr_Format(PyExc_ValueError,
447                                              "Matrix.OrthoProjection(): "
448                                              "unknown plane, expected: X, Y, not '%.200s'",
449                                              plane);
450                                 return NULL;
451                         }
452                 }
453                 else {
454                         if (plane_len == 2 && plane[0]=='X' && plane[1]=='Y') {
455                                 mat[0]= 1.0f;
456                                 mat[4]= 1.0f;
457                         }
458                         else if (plane_len == 2 && plane[0]=='X' && plane[1]=='Z') {
459                                 mat[0]= 1.0f;
460                                 mat[8]= 1.0f;
461                         }
462                         else if (plane_len == 2 && plane[0]=='Y' && plane[1]=='Z') {
463                                 mat[4]= 1.0f;
464                                 mat[8]= 1.0f;
465                         }
466                         else {
467                                 PyErr_Format(PyExc_ValueError,
468                                              "Matrix.OrthoProjection(): "
469                                              "unknown plane, expected: XY, XZ, YZ, not '%.200s'",
470                                              plane);
471                                 return NULL;
472                         }
473                 }
474         }
475         else {
476                 //arbitrary plane
477
478                 int vec_size= (matSize == 2 ? 2 : 3);
479                 float tvec[4];
480
481                 if (mathutils_array_parse(tvec, vec_size, vec_size, axis, "Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1) {
482                         return NULL;
483                 }
484
485                 //normalize arbitrary axis
486                 for (x = 0; x < vec_size; x++) {
487                         norm += tvec[x] * tvec[x];
488                 }
489                 norm = (float) sqrt(norm);
490                 for (x = 0; x < vec_size; x++) {
491                         tvec[x] /= norm;
492                 }
493                 if (matSize == 2) {
494                         mat[0] = 1 - (tvec[0] * tvec[0]);
495                         mat[1] = -(tvec[0] * tvec[1]);
496                         mat[2] = -(tvec[0] * tvec[1]);
497                         mat[3] = 1 - (tvec[1] * tvec[1]);
498                 }
499                 else if (matSize > 2) {
500                         mat[0] = 1 - (tvec[0] * tvec[0]);
501                         mat[1] = -(tvec[0] * tvec[1]);
502                         mat[2] = -(tvec[0] * tvec[2]);
503                         mat[3] = -(tvec[0] * tvec[1]);
504                         mat[4] = 1 - (tvec[1] * tvec[1]);
505                         mat[5] = -(tvec[1] * tvec[2]);
506                         mat[6] = -(tvec[0] * tvec[2]);
507                         mat[7] = -(tvec[1] * tvec[2]);
508                         mat[8] = 1 - (tvec[2] * tvec[2]);
509                 }
510         }
511         if (matSize == 4) {
512                 matrix_3x3_as_4x4(mat);
513         }
514         //pass to matrix creation
515         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
516 }
517
518 PyDoc_STRVAR(C_Matrix_Shear_doc,
519 ".. classmethod:: Shear(plane, size, factor)\n"
520 "\n"
521 "   Create a matrix to represent an shear transformation.\n"
522 "\n"
523 "   :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
524 "      where a single axis is for a 2D matrix only.\n"
525 "   :type plane: string\n"
526 "   :arg size: The size of the shear matrix to construct [2, 4].\n"
527 "   :type size: int\n"
528 "   :arg factor: The factor of shear to apply. For a 3 or 4 *size* matrix\n"
529 "      pass a pair of floats corrasponding with the *plane* axis.\n"
530 "   :type factor: float or float pair\n"
531 "   :return: A new shear matrix.\n"
532 "   :rtype: :class:`Matrix`\n"
533 );
534 static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
535 {
536         int matSize;
537         const char *plane;
538         PyObject *fac;
539         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
540                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
541
542         if (!PyArg_ParseTuple(args, "siO:Matrix.Shear", &plane, &matSize, &fac)) {
543                 return NULL;
544         }
545         if (matSize != 2 && matSize != 3 && matSize != 4) {
546                 PyErr_SetString(PyExc_ValueError,
547                                 "Matrix.Shear(): "
548                                 "can only return a 2x2 3x3 or 4x4 matrix");
549                 return NULL;
550         }
551
552         if (matSize == 2) {
553                 float const factor= PyFloat_AsDouble(fac);
554
555                 if (factor==-1.0f && PyErr_Occurred()) {
556                         PyErr_SetString(PyExc_TypeError,
557                                         "Matrix.Shear(): "
558                                         "the factor to be a float");
559                         return NULL;
560                 }
561
562                 /* unit */
563                 mat[0] = 1.0f;
564                 mat[3] = 1.0f;
565
566                 if (strcmp(plane, "X") == 0) {
567                         mat[2] = factor;
568                 }
569                 else if (strcmp(plane, "Y") == 0) {
570                         mat[1] = factor;
571                 }
572                 else {
573                         PyErr_SetString(PyExc_ValueError,
574                                         "Matrix.Shear(): "
575                                         "expected: X, Y or wrong matrix size for shearing plane");
576                         return NULL;
577                 }
578         }
579         else {
580                 /* 3 or 4, apply as 3x3, resize later if needed */
581                 float factor[2];
582
583                 if (mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") < 0) {
584                         return NULL;
585                 }
586
587                 /* unit */
588                 mat[0] = 1.0f;
589                 mat[4] = 1.0f;
590                 mat[8] = 1.0f;
591
592                 if (strcmp(plane, "XY") == 0) {
593                         mat[6] = factor[0];
594                         mat[7] = factor[1];
595                 }
596                 else if (strcmp(plane, "XZ") == 0) {
597                         mat[3] = factor[0];
598                         mat[5] = factor[1];
599                 }
600                 else if (strcmp(plane, "YZ") == 0) {
601                         mat[1] = factor[0];
602                         mat[2] = factor[1];
603                 }
604                 else {
605                         PyErr_SetString(PyExc_ValueError,
606                                         "Matrix.Shear(): "
607                                         "expected: X, Y, XY, XZ, YZ");
608                         return NULL;
609                 }
610         }
611
612         if (matSize == 4) {
613                 matrix_3x3_as_4x4(mat);
614         }
615         //pass to matrix creation
616         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
617 }
618
619 void matrix_as_3x3(float mat[3][3], MatrixObject *self)
620 {
621         copy_v3_v3(mat[0], self->matrix[0]);
622         copy_v3_v3(mat[1], self->matrix[1]);
623         copy_v3_v3(mat[2], self->matrix[2]);
624 }
625
626 /* assumes rowsize == colsize is checked and the read callback has run */
627 static float matrix_determinant_internal(MatrixObject *self)
628 {
629         if (self->row_size == 2) {
630                 return determinant_m2(self->matrix[0][0], self->matrix[0][1],
631                                          self->matrix[1][0], self->matrix[1][1]);
632         }
633         else if (self->row_size == 3) {
634                 return determinant_m3(self->matrix[0][0], self->matrix[0][1],
635                                          self->matrix[0][2], self->matrix[1][0],
636                                          self->matrix[1][1], self->matrix[1][2],
637                                          self->matrix[2][0], self->matrix[2][1],
638                                          self->matrix[2][2]);
639         }
640         else {
641                 return determinant_m4((float (*)[4])self->contigPtr);
642         }
643 }
644
645
646 /*-----------------------------METHODS----------------------------*/
647 PyDoc_STRVAR(Matrix_to_quaternion_doc,
648 ".. method:: to_quaternion()\n"
649 "\n"
650 "   Return a quaternion representation of the rotation matrix.\n"
651 "\n"
652 "   :return: Quaternion representation of the rotation matrix.\n"
653 "   :rtype: :class:`Quaternion`\n"
654 );
655 static PyObject *Matrix_to_quaternion(MatrixObject *self)
656 {
657         float quat[4];
658
659         if (BaseMath_ReadCallback(self) == -1)
660                 return NULL;
661
662         /*must be 3-4 cols, 3-4 rows, square matrix*/
663         if ((self->col_size < 3) || (self->row_size < 3) || (self->col_size != self->row_size)) {
664                 PyErr_SetString(PyExc_ValueError,
665                                 "Matrix.to_quat(): "
666                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
667                 return NULL;
668         }
669         if (self->col_size == 3) {
670                 mat3_to_quat(quat, (float (*)[3])self->contigPtr);
671         }
672         else {
673                 mat4_to_quat(quat, (float (*)[4])self->contigPtr);
674         }
675
676         return newQuaternionObject(quat, Py_NEW, NULL);
677 }
678
679 /*---------------------------matrix.toEuler() --------------------*/
680 PyDoc_STRVAR(Matrix_to_euler_doc,
681 ".. method:: to_euler(order, euler_compat)\n"
682 "\n"
683 "   Return an Euler representation of the rotation matrix\n"
684 "   (3x3 or 4x4 matrix only).\n"
685 "\n"
686 "   :arg order: Optional rotation order argument in\n"
687 "      ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
688 "   :type order: string\n"
689 "   :arg euler_compat: Optional euler argument the new euler will be made\n"
690 "      compatible with (no axis flipping between them).\n"
691 "      Useful for converting a series of matrices to animation curves.\n"
692 "   :type euler_compat: :class:`Euler`\n"
693 "   :return: Euler representation of the matrix.\n"
694 "   :rtype: :class:`Euler`\n"
695 );
696 static PyObject *Matrix_to_euler(MatrixObject *self, PyObject *args)
697 {
698         const char *order_str= NULL;
699         short order= EULER_ORDER_XYZ;
700         float eul[3], eul_compatf[3];
701         EulerObject *eul_compat = NULL;
702
703         float tmat[3][3];
704         float (*mat)[3];
705
706         if (BaseMath_ReadCallback(self) == -1)
707                 return NULL;
708
709         if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
710                 return NULL;
711
712         if (eul_compat) {
713                 if (BaseMath_ReadCallback(eul_compat) == -1)
714                         return NULL;
715
716                 copy_v3_v3(eul_compatf, eul_compat->eul);
717         }
718
719         /*must be 3-4 cols, 3-4 rows, square matrix*/
720         if (self->col_size ==3 && self->row_size ==3) {
721                 mat= (float (*)[3])self->contigPtr;
722         }
723         else if (self->col_size ==4 && self->row_size ==4) {
724                 copy_m3_m4(tmat, (float (*)[4])self->contigPtr);
725                 mat= tmat;
726         }
727         else {
728                 PyErr_SetString(PyExc_ValueError,
729                                 "Matrix.to_euler(): "
730                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
731                 return NULL;
732         }
733
734         if (order_str) {
735                 order= euler_order_from_string(order_str, "Matrix.to_euler()");
736
737                 if (order == -1)
738                         return NULL;
739         }
740
741         if (eul_compat) {
742                 if (order == 1) mat3_to_compatible_eul(eul, eul_compatf, mat);
743                 else                    mat3_to_compatible_eulO(eul, eul_compatf, order, mat);
744         }
745         else {
746                 if (order == 1) mat3_to_eul(eul, mat);
747                 else                    mat3_to_eulO(eul, order, mat);
748         }
749
750         return newEulerObject(eul, order, Py_NEW, NULL);
751 }
752
753 PyDoc_STRVAR(Matrix_resize_4x4_doc,
754 ".. method:: resize_4x4()\n"
755 "\n"
756 "   Resize the matrix to 4x4.\n"
757 );
758 static PyObject *Matrix_resize_4x4(MatrixObject *self)
759 {
760         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
761
762         if (self->wrapped==Py_WRAP) {
763                 PyErr_SetString(PyExc_TypeError,
764                                 "Matrix.resize_4x4(): "
765                                 "cannot resize wrapped data - make a copy and resize that");
766                 return NULL;
767         }
768         if (self->cb_user) {
769                 PyErr_SetString(PyExc_TypeError,
770                                 "Matrix.resize_4x4(): "
771                                 "cannot resize owned data - make a copy and resize that");
772                 return NULL;
773         }
774
775         self->contigPtr = PyMem_Realloc(self->contigPtr, (sizeof(float) * 16));
776         if (self->contigPtr == NULL) {
777                 PyErr_SetString(PyExc_MemoryError,
778                                 "Matrix.resize_4x4(): "
779                                 "problem allocating pointer space");
780                 return NULL;
781         }
782         /*set row pointers*/
783         for (x = 0; x < 4; x++) {
784                 self->matrix[x] = self->contigPtr + (x * 4);
785         }
786         /*move data to new spot in array + clean*/
787         for (blank_rows = (4 - self->row_size); blank_rows > 0; blank_rows--) {
788                 for (x = 0; x < 4; x++) {
789                         index = (4 * (self->row_size + (blank_rows - 1))) + x;
790                         if (index == 10 || index == 15) {
791                                 self->contigPtr[index] = 1.0f;
792                         }
793                         else {
794                                 self->contigPtr[index] = 0.0f;
795                         }
796                 }
797         }
798         for (x = 1; x <= self->row_size; x++) {
799                 first_row_elem = (self->col_size * (self->row_size - x));
800                 curr_pos = (first_row_elem + (self->col_size -1));
801                 new_pos = (4 * (self->row_size - x)) + (curr_pos - first_row_elem);
802                 for (blank_columns = (4 - self->col_size); blank_columns > 0; blank_columns--) {
803                         self->contigPtr[new_pos + blank_columns] = 0.0f;
804                 }
805                 for ( ; curr_pos >= first_row_elem; curr_pos--) {
806                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
807                         new_pos--;
808                 }
809         }
810         self->row_size = 4;
811         self->col_size = 4;
812
813         Py_RETURN_NONE;
814 }
815
816 PyDoc_STRVAR(Matrix_to_4x4_doc,
817 ".. method:: to_4x4()\n"
818 "\n"
819 "   Return a 4x4 copy of this matrix.\n"
820 "\n"
821 "   :return: a new matrix.\n"
822 "   :rtype: :class:`Matrix`\n"
823 );
824 static PyObject *Matrix_to_4x4(MatrixObject *self)
825 {
826         if (BaseMath_ReadCallback(self) == -1)
827                 return NULL;
828
829         if (self->col_size==4 && self->row_size==4) {
830                 return (PyObject *)newMatrixObject(self->contigPtr, 4, 4, Py_NEW, Py_TYPE(self));
831         }
832         else if (self->col_size==3 && self->row_size==3) {
833                 float mat[4][4];
834                 copy_m4_m3(mat, (float (*)[3])self->contigPtr);
835                 return (PyObject *)newMatrixObject((float *)mat, 4, 4, Py_NEW, Py_TYPE(self));
836         }
837         /* TODO, 2x2 matrix */
838
839         PyErr_SetString(PyExc_TypeError,
840                         "Matrix.to_4x4(): "
841                         "inappropriate matrix size");
842         return NULL;
843 }
844
845 PyDoc_STRVAR(Matrix_to_3x3_doc,
846 ".. method:: to_3x3()\n"
847 "\n"
848 "   Return a 3x3 copy of this matrix.\n"
849 "\n"
850 "   :return: a new matrix.\n"
851 "   :rtype: :class:`Matrix`\n"
852 );
853 static PyObject *Matrix_to_3x3(MatrixObject *self)
854 {
855         float mat[3][3];
856
857         if (BaseMath_ReadCallback(self) == -1)
858                 return NULL;
859
860         if ((self->col_size < 3) || (self->row_size < 3)) {
861                 PyErr_SetString(PyExc_TypeError,
862                                 "Matrix.to_3x3(): inappropriate matrix size");
863                 return NULL;
864         }
865
866         matrix_as_3x3(mat, self);
867
868         return newMatrixObject((float *)mat, 3, 3, Py_NEW, Py_TYPE(self));
869 }
870
871 PyDoc_STRVAR(Matrix_to_translation_doc,
872 ".. method:: to_translation()\n"
873 "\n"
874 "   Return a the translation part of a 4 row matrix.\n"
875 "\n"
876 "   :return: Return a the translation of a matrix.\n"
877 "   :rtype: :class:`Vector`\n"
878 );
879 static PyObject *Matrix_to_translation(MatrixObject *self)
880 {
881         if (BaseMath_ReadCallback(self) == -1)
882                 return NULL;
883
884         if ((self->col_size < 3) || self->row_size < 4) {
885                 PyErr_SetString(PyExc_TypeError,
886                                 "Matrix.to_translation(): "
887                                 "inappropriate matrix size");
888                 return NULL;
889         }
890
891         return newVectorObject(self->matrix[3], 3, Py_NEW, NULL);
892 }
893
894 PyDoc_STRVAR(Matrix_to_scale_doc,
895 ".. method:: to_scale()\n"
896 "\n"
897 "   Return a the scale part of a 3x3 or 4x4 matrix.\n"
898 "\n"
899 "   :return: Return a the scale of a matrix.\n"
900 "   :rtype: :class:`Vector`\n"
901 "\n"
902 "   .. note:: This method does not return negative a scale on any axis because it is not possible to obtain this data from the matrix alone.\n"
903 );
904 static PyObject *Matrix_to_scale(MatrixObject *self)
905 {
906         float rot[3][3];
907         float mat[3][3];
908         float size[3];
909
910         if (BaseMath_ReadCallback(self) == -1)
911                 return NULL;
912
913         /*must be 3-4 cols, 3-4 rows, square matrix*/
914         if ((self->col_size < 3) || (self->row_size < 3)) {
915                 PyErr_SetString(PyExc_TypeError,
916                                 "Matrix.to_scale(): "
917                                 "inappropriate matrix size, 3x3 minimum size");
918                 return NULL;
919         }
920
921         matrix_as_3x3(mat, self);
922
923         /* compatible mat4_to_loc_rot_size */
924         mat3_to_rot_size(rot, size, mat);
925
926         return newVectorObject(size, 3, Py_NEW, NULL);
927 }
928
929 /*---------------------------matrix.invert() ---------------------*/
930 PyDoc_STRVAR(Matrix_invert_doc,
931 ".. method:: invert()\n"
932 "\n"
933 "   Set the matrix to its inverse.\n"
934 "\n"
935 "   .. note:: :exc:`ValueError` exception is raised.\n"
936 "\n"
937 "   .. seealso:: <http://en.wikipedia.org/wiki/Inverse_matrix>\n"
938 );
939 static PyObject *Matrix_invert(MatrixObject *self)
940 {
941
942         int x, y, z = 0;
943         float det = 0.0f;
944         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f,
945                          0.0f, 0.0f, 0.0f, 0.0f,
946                          0.0f, 0.0f, 0.0f, 0.0f,
947                          0.0f, 0.0f, 0.0f, 1.0f};
948
949         if (BaseMath_ReadCallback(self) == -1)
950                 return NULL;
951
952         if (self->row_size != self->col_size) {
953                 PyErr_SetString(PyExc_TypeError,
954                                 "Matrix.invert(ed): "
955                                 "only square matrices are supported");
956                 return NULL;
957         }
958
959         /*calculate the determinant*/
960         det = matrix_determinant_internal(self);
961
962         if (det != 0) {
963                 /*calculate the classical adjoint*/
964                 if (self->row_size == 2) {
965                         mat[0] = self->matrix[1][1];
966                         mat[1] = -self->matrix[0][1];
967                         mat[2] = -self->matrix[1][0];
968                         mat[3] = self->matrix[0][0];
969                 }
970                 else if (self->row_size == 3) {
971                         adjoint_m3_m3((float (*)[3]) mat,(float (*)[3])self->contigPtr);
972                 }
973                 else if (self->row_size == 4) {
974                         adjoint_m4_m4((float (*)[4]) mat, (float (*)[4])self->contigPtr);
975                 }
976                 /*divide by determinate*/
977                 for (x = 0; x < (self->row_size * self->col_size); x++) {
978                         mat[x] /= det;
979                 }
980                 /*set values*/
981                 for (x = 0; x < self->row_size; x++) {
982                         for (y = 0; y < self->col_size; y++) {
983                                 self->matrix[x][y] = mat[z];
984                                 z++;
985                         }
986                 }
987                 /*transpose
988                 Matrix_transpose(self);*/
989         }
990         else {
991                 PyErr_SetString(PyExc_ValueError,
992                                 "Matrix.invert(ed): "
993                                 "matrix does not have an inverse");
994                 return NULL;
995         }
996
997         (void)BaseMath_WriteCallback(self);
998         Py_RETURN_NONE;
999 }
1000
1001 PyDoc_STRVAR(Matrix_inverted_doc,
1002 ".. method:: inverted()\n"
1003 "\n"
1004 "   Return an inverted copy of the matrix.\n"
1005 "\n"
1006 "   :return: the  inverted matrix.\n"
1007 "   :rtype: :class:`Matrix`\n"
1008 "\n"
1009 "   .. note:: :exc:`ValueError` exception is raised.\n"
1010 );
1011 static PyObject *Matrix_inverted(MatrixObject *self)
1012 {
1013         return matrix__apply_to_copy((PyNoArgsFunction)Matrix_invert, self);
1014 }
1015
1016 PyDoc_STRVAR(Matrix_rotate_doc,
1017 ".. method:: rotate(other)\n"
1018 "\n"
1019 "   Rotates the matrix a by another mathutils value.\n"
1020 "\n"
1021 "   :arg other: rotation component of mathutils value\n"
1022 "   :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
1023 "\n"
1024 "   .. note:: If any of the columns are not unit length this may not have desired results.\n"
1025 );
1026 static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
1027 {
1028         float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
1029
1030         if (BaseMath_ReadCallback(self) == -1)
1031                 return NULL;
1032
1033         if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1)
1034                 return NULL;
1035
1036         if (self->col_size != 3 || self->row_size != 3) {
1037                 PyErr_SetString(PyExc_TypeError,
1038                                 "Matrix.rotate(): "
1039                                 "must have 3x3 dimensions");
1040                 return NULL;
1041         }
1042
1043         matrix_as_3x3(self_rmat, self);
1044         mul_m3_m3m3(rmat, self_rmat, other_rmat);
1045
1046         copy_m3_m3((float (*)[3])(self->contigPtr), rmat);
1047
1048         (void)BaseMath_WriteCallback(self);
1049         Py_RETURN_NONE;
1050 }
1051
1052 /*---------------------------matrix.decompose() ---------------------*/
1053 PyDoc_STRVAR(Matrix_decompose_doc,
1054 ".. method:: decompose()\n"
1055 "\n"
1056 "   Return the location, rotaion and scale components of this matrix.\n"
1057 "\n"
1058 "   :return: loc, rot, scale triple.\n"
1059 "   :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
1060 );
1061 static PyObject *Matrix_decompose(MatrixObject *self)
1062 {
1063         PyObject *ret;
1064         float loc[3];
1065         float rot[3][3];
1066         float quat[4];
1067         float size[3];
1068
1069         if (self->col_size != 4 || self->row_size != 4) {
1070                 PyErr_SetString(PyExc_TypeError,
1071                                 "Matrix.decompose(): "
1072                                 "inappropriate matrix size - expects 4x4 matrix");
1073                 return NULL;
1074         }
1075
1076         if (BaseMath_ReadCallback(self) == -1)
1077                 return NULL;
1078
1079         mat4_to_loc_rot_size(loc, rot, size, (float (*)[4])self->contigPtr);
1080         mat3_to_quat(quat, rot);
1081
1082         ret= PyTuple_New(3);
1083         PyTuple_SET_ITEM(ret, 0, newVectorObject(loc, 3, Py_NEW, NULL));
1084         PyTuple_SET_ITEM(ret, 1, newQuaternionObject(quat, Py_NEW, NULL));
1085         PyTuple_SET_ITEM(ret, 2, newVectorObject(size, 3, Py_NEW, NULL));
1086
1087         return ret;
1088 }
1089
1090
1091
1092 PyDoc_STRVAR(Matrix_lerp_doc,
1093 ".. function:: lerp(other, factor)\n"
1094 "\n"
1095 "   Returns the interpolation of two matrices.\n"
1096 "\n"
1097 "   :arg other: value to interpolate with.\n"
1098 "   :type other: :class:`Matrix`\n"
1099 "   :arg factor: The interpolation value in [0.0, 1.0].\n"
1100 "   :type factor: float\n"
1101 "   :return: The interpolated rotation.\n"
1102 "   :rtype: :class:`Matrix`\n"
1103 );
1104 static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
1105 {
1106         MatrixObject *mat2 = NULL;
1107         float fac, mat[MATRIX_MAX_DIM*MATRIX_MAX_DIM];
1108
1109         if (!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac))
1110                 return NULL;
1111
1112         if (self->row_size != mat2->row_size || self->col_size != mat2->col_size) {
1113                 PyErr_SetString(PyExc_ValueError,
1114                                 "Matrix.lerp(): "
1115                                 "expects both matrix objects of the same dimensions");
1116                 return NULL;
1117         }
1118
1119         if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1)
1120                 return NULL;
1121
1122         /* TODO, different sized matrix */
1123         if (self->row_size==4 && self->col_size==4) {
1124                 blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->contigPtr, (float (*)[4])mat2->contigPtr, fac);
1125         }
1126         else if (self->row_size==3 && self->col_size==3) {
1127                 blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->contigPtr, (float (*)[3])mat2->contigPtr, fac);
1128         }
1129         else {
1130                 PyErr_SetString(PyExc_ValueError,
1131                                 "Matrix.lerp(): "
1132                                 "only 3x3 and 4x4 matrices supported");
1133                 return NULL;
1134         }
1135
1136         return (PyObject*)newMatrixObject(mat, self->row_size, self->col_size, Py_NEW, Py_TYPE(self));
1137 }
1138
1139 /*---------------------------matrix.determinant() ----------------*/
1140 PyDoc_STRVAR(Matrix_determinant_doc,
1141 ".. method:: determinant()\n"
1142 "\n"
1143 "   Return the determinant of a matrix.\n"
1144 "\n"
1145 "   :return: Return a the determinant of a matrix.\n"
1146 "   :rtype: float\n"
1147 "\n"
1148 "   .. seealso:: <http://en.wikipedia.org/wiki/Determinant>\n"
1149 );
1150 static PyObject *Matrix_determinant(MatrixObject *self)
1151 {
1152         if (BaseMath_ReadCallback(self) == -1)
1153                 return NULL;
1154
1155         if (self->row_size != self->col_size) {
1156                 PyErr_SetString(PyExc_TypeError,
1157                                 "Matrix.determinant(): "
1158                                 "only square matrices are supported");
1159                 return NULL;
1160         }
1161
1162         return PyFloat_FromDouble((double)matrix_determinant_internal(self));
1163 }
1164 /*---------------------------matrix.transpose() ------------------*/
1165 PyDoc_STRVAR(Matrix_transpose_doc,
1166 ".. method:: transpose()\n"
1167 "\n"
1168 "   Set the matrix to its transpose.\n"
1169 "\n"
1170 "   .. seealso:: <http://en.wikipedia.org/wiki/Transpose>\n"
1171 );
1172 static PyObject *Matrix_transpose(MatrixObject *self)
1173 {
1174         float t = 0.0f;
1175
1176         if (BaseMath_ReadCallback(self) == -1)
1177                 return NULL;
1178
1179         if (self->row_size != self->col_size) {
1180                 PyErr_SetString(PyExc_TypeError,
1181                                 "Matrix.transpose(d): "
1182                                 "only square matrices are supported");
1183                 return NULL;
1184         }
1185
1186         if (self->row_size == 2) {
1187                 t = self->matrix[1][0];
1188                 self->matrix[1][0] = self->matrix[0][1];
1189                 self->matrix[0][1] = t;
1190         }
1191         else if (self->row_size == 3) {
1192                 transpose_m3((float (*)[3])self->contigPtr);
1193         }
1194         else {
1195                 transpose_m4((float (*)[4])self->contigPtr);
1196         }
1197
1198         (void)BaseMath_WriteCallback(self);
1199         Py_RETURN_NONE;
1200 }
1201
1202 PyDoc_STRVAR(Matrix_transposed_doc,
1203 ".. method:: transposed()\n"
1204 "\n"
1205 "   Return a new, transposed matrix.\n"
1206 "\n"
1207 "   :return: a transposed matrix\n"
1208 "   :rtype: :class:`Matrix`\n"
1209 );
1210 static PyObject *Matrix_transposed(MatrixObject *self)
1211 {
1212         return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
1213 }
1214
1215 /*---------------------------matrix.zero() -----------------------*/
1216 PyDoc_STRVAR(Matrix_zero_doc,
1217 ".. method:: zero()\n"
1218 "\n"
1219 "   Set all the matrix values to zero.\n"
1220 "\n"
1221 "   :return: an instance of itself\n"
1222 "   :rtype: :class:`Matrix`\n"
1223 );
1224 static PyObject *Matrix_zero(MatrixObject *self)
1225 {
1226         fill_vn(self->contigPtr, self->row_size * self->col_size, 0.0f);
1227
1228         if (BaseMath_WriteCallback(self) == -1)
1229                 return NULL;
1230
1231         Py_RETURN_NONE;
1232 }
1233 /*---------------------------matrix.identity(() ------------------*/
1234 PyDoc_STRVAR(Matrix_identity_doc,
1235 ".. method:: identity()\n"
1236 "\n"
1237 "   Set the matrix to the identity matrix.\n"
1238 "\n"
1239 "   .. note:: An object with zero location and rotation, a scale of one,\n"
1240 "      will have an identity matrix.\n"
1241 "\n"
1242 "   .. seealso:: <http://en.wikipedia.org/wiki/Identity_matrix>\n"
1243 );
1244 static PyObject *Matrix_identity(MatrixObject *self)
1245 {
1246         if (BaseMath_ReadCallback(self) == -1)
1247                 return NULL;
1248
1249         if (self->row_size != self->col_size) {
1250                 PyErr_SetString(PyExc_TypeError,
1251                                 "Matrix.identity(): "
1252                                 "only square matrices are supported");
1253                 return NULL;
1254         }
1255
1256         if (self->row_size == 2) {
1257                 self->matrix[0][0] = 1.0f;
1258                 self->matrix[0][1] = 0.0f;
1259                 self->matrix[1][0] = 0.0f;
1260                 self->matrix[1][1] = 1.0f;
1261         }
1262         else if (self->row_size == 3) {
1263                 unit_m3((float (*)[3])self->contigPtr);
1264         }
1265         else {
1266                 unit_m4((float (*)[4])self->contigPtr);
1267         }
1268
1269         if (BaseMath_WriteCallback(self) == -1)
1270                 return NULL;
1271
1272         Py_RETURN_NONE;
1273 }
1274
1275 /*---------------------------Matrix.copy() ------------------*/
1276 PyDoc_STRVAR(Matrix_copy_doc,
1277 ".. method:: copy()\n"
1278 "\n"
1279 "   Returns a copy of this matrix.\n"
1280 "\n"
1281 "   :return: an instance of itself\n"
1282 "   :rtype: :class:`Matrix`\n"
1283 );
1284 static PyObject *Matrix_copy(MatrixObject *self)
1285 {
1286         if (BaseMath_ReadCallback(self) == -1)
1287                 return NULL;
1288
1289         return (PyObject*)newMatrixObject((float (*))self->contigPtr, self->row_size, self->col_size, Py_NEW, Py_TYPE(self));
1290 }
1291
1292 /*----------------------------print object (internal)-------------*/
1293 /*print the object to screen*/
1294 static PyObject *Matrix_repr(MatrixObject *self)
1295 {
1296         int x, y;
1297         PyObject *rows[MATRIX_MAX_DIM]= {NULL};
1298
1299         if (BaseMath_ReadCallback(self) == -1)
1300                 return NULL;
1301
1302         for (x = 0; x < self->row_size; x++) {
1303                 rows[x]= PyTuple_New(self->col_size);
1304                 for (y = 0; y < self->col_size; y++) {
1305                         PyTuple_SET_ITEM(rows[x], y, PyFloat_FromDouble(self->matrix[x][y]));
1306                 }
1307         }
1308         switch(self->row_size) {
1309         case 2: return PyUnicode_FromFormat("Matrix((%R,\n"
1310                                                                                 "        %R))", rows[0], rows[1]);
1311
1312         case 3: return PyUnicode_FromFormat("Matrix((%R,\n"
1313                                                                                 "        %R,\n"
1314                                                                                 "        %R))", rows[0], rows[1], rows[2]);
1315
1316         case 4: return PyUnicode_FromFormat("Matrix((%R,\n"
1317                                                                                 "        %R,\n"
1318                                                                                 "        %R,\n"
1319                                                                                 "        %R))", rows[0], rows[1], rows[2], rows[3]);
1320         }
1321
1322         Py_FatalError("Matrix(): invalid row size!");
1323         return NULL;
1324 }
1325
1326 static PyObject* Matrix_richcmpr(PyObject *a, PyObject *b, int op)
1327 {
1328         PyObject *res;
1329         int ok= -1; /* zero is true */
1330
1331         if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
1332                 MatrixObject *matA= (MatrixObject*)a;
1333                 MatrixObject *matB= (MatrixObject*)b;
1334
1335                 if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1)
1336                         return NULL;
1337
1338                 ok=     (       (matA->col_size == matB->col_size) &&
1339                                 (matA->row_size == matB->row_size) &&
1340                                 EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr, (matA->row_size * matA->col_size), 1)
1341                         ) ? 0 : -1;
1342         }
1343
1344         switch (op) {
1345         case Py_NE:
1346                 ok = !ok; /* pass through */
1347         case Py_EQ:
1348                 res = ok ? Py_False : Py_True;
1349                 break;
1350
1351         case Py_LT:
1352         case Py_LE:
1353         case Py_GT:
1354         case Py_GE:
1355                 res = Py_NotImplemented;
1356                 break;
1357         default:
1358                 PyErr_BadArgument();
1359                 return NULL;
1360         }
1361
1362         return Py_INCREF(res), res;
1363 }
1364
1365 /*---------------------SEQUENCE PROTOCOLS------------------------
1366   ----------------------------len(object)------------------------
1367   sequence length*/
1368 static int Matrix_len(MatrixObject *self)
1369 {
1370         return (self->row_size);
1371 }
1372 /*----------------------------object[]---------------------------
1373   sequence accessor (get)
1374   the wrapped vector gives direct access to the matrix data*/
1375 static PyObject *Matrix_item(MatrixObject *self, int i)
1376 {
1377         if (BaseMath_ReadCallback(self) == -1)
1378                 return NULL;
1379
1380         if (i < 0 || i >= self->row_size) {
1381                 PyErr_SetString(PyExc_IndexError,
1382                                 "matrix[attribute]: "
1383                                 "array index out of range");
1384                 return NULL;
1385         }
1386         return newVectorObject_cb((PyObject *)self, self->col_size, mathutils_matrix_vector_cb_index, i);
1387 }
1388 /*----------------------------object[]-------------------------
1389   sequence accessor (set) */
1390
1391 static int Matrix_ass_item(MatrixObject *self, int i, PyObject *value)
1392 {
1393         float vec[4];
1394         if (BaseMath_ReadCallback(self) == -1)
1395                 return -1;
1396
1397         if (i >= self->row_size || i < 0) {
1398                 PyErr_SetString(PyExc_IndexError,
1399                                 "matrix[attribute] = x: bad column");
1400                 return -1;
1401         }
1402
1403         if (mathutils_array_parse(vec, self->col_size, self->col_size, value, "matrix[i] = value assignment") < 0) {
1404                 return -1;
1405         }
1406
1407         memcpy(self->matrix[i], vec, self->col_size *sizeof(float));
1408
1409         (void)BaseMath_WriteCallback(self);
1410         return 0;
1411 }
1412
1413 /*----------------------------object[z:y]------------------------
1414   sequence slice (get)*/
1415 static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
1416 {
1417
1418         PyObject *tuple;
1419         int count;
1420
1421         if (BaseMath_ReadCallback(self) == -1)
1422                 return NULL;
1423
1424         CLAMP(begin, 0, self->row_size);
1425         CLAMP(end, 0, self->row_size);
1426         begin= MIN2(begin, end);
1427
1428         tuple= PyTuple_New(end - begin);
1429         for (count= begin; count < end; count++) {
1430                 PyTuple_SET_ITEM(tuple, count - begin,
1431                                 newVectorObject_cb((PyObject *)self, self->col_size, mathutils_matrix_vector_cb_index, count));
1432
1433         }
1434
1435         return tuple;
1436 }
1437 /*----------------------------object[z:y]------------------------
1438   sequence slice (set)*/
1439 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
1440 {
1441         PyObject *value_fast= NULL;
1442
1443         if (BaseMath_ReadCallback(self) == -1)
1444                 return -1;
1445
1446         CLAMP(begin, 0, self->row_size);
1447         CLAMP(end, 0, self->row_size);
1448         begin = MIN2(begin, end);
1449
1450         /* non list/tuple cases */
1451         if (!(value_fast=PySequence_Fast(value, "matrix[begin:end] = value"))) {
1452                 /* PySequence_Fast sets the error */
1453                 return -1;
1454         }
1455         else {
1456                 const int size= end - begin;
1457                 int i;
1458                 float mat[16];
1459
1460                 if (PySequence_Fast_GET_SIZE(value_fast) != size) {
1461                         Py_DECREF(value_fast);
1462                         PyErr_SetString(PyExc_ValueError,
1463                                         "matrix[begin:end] = []: "
1464                                         "size mismatch in slice assignment");
1465                         return -1;
1466                 }
1467
1468                 /*parse sub items*/
1469                 for (i = 0; i < size; i++) {
1470                         /*parse each sub sequence*/
1471                         PyObject *item= PySequence_Fast_GET_ITEM(value_fast, i);
1472
1473                         if (mathutils_array_parse(&mat[i * self->col_size], self->col_size, self->col_size, item, "matrix[begin:end] = value assignment") < 0) {
1474                                 return -1;
1475                         }
1476                 }
1477
1478                 Py_DECREF(value_fast);
1479
1480                 /*parsed well - now set in matrix*/
1481                 memcpy(self->contigPtr + (begin * self->col_size), mat, sizeof(float) * (size * self->col_size));
1482
1483                 (void)BaseMath_WriteCallback(self);
1484                 return 0;
1485         }
1486 }
1487 /*------------------------NUMERIC PROTOCOLS----------------------
1488   ------------------------obj + obj------------------------------*/
1489 static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
1490 {
1491         float mat[16];
1492         MatrixObject *mat1 = NULL, *mat2 = NULL;
1493
1494         mat1 = (MatrixObject*)m1;
1495         mat2 = (MatrixObject*)m2;
1496
1497         if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1498                 PyErr_Format(PyExc_TypeError,
1499                              "Matrix addition: (%s + %s) "
1500                              "invalid type for this operation",
1501                              Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
1502                 return NULL;
1503         }
1504
1505         if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1)
1506                 return NULL;
1507
1508         if (mat1->row_size != mat2->row_size || mat1->col_size != mat2->col_size) {
1509                 PyErr_SetString(PyExc_TypeError,
1510                                 "Matrix addition: "
1511                                 "matrices must have the same dimensions for this operation");
1512                 return NULL;
1513         }
1514
1515         add_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->row_size * mat1->col_size);
1516
1517         return newMatrixObject(mat, mat1->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1518 }
1519 /*------------------------obj - obj------------------------------
1520   subtraction*/
1521 static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
1522 {
1523         float mat[16];
1524         MatrixObject *mat1 = NULL, *mat2 = NULL;
1525
1526         mat1 = (MatrixObject*)m1;
1527         mat2 = (MatrixObject*)m2;
1528
1529         if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1530                 PyErr_Format(PyExc_TypeError,
1531                              "Matrix subtraction: (%s - %s) "
1532                              "invalid type for this operation",
1533                              Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name
1534                              );
1535                 return NULL;
1536         }
1537
1538         if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1)
1539                 return NULL;
1540
1541         if (mat1->row_size != mat2->row_size || mat1->col_size != mat2->col_size) {
1542                 PyErr_SetString(PyExc_TypeError,
1543                                 "Matrix addition: "
1544                                 "matrices must have the same dimensions for this operation");
1545                 return NULL;
1546         }
1547
1548         sub_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->row_size * mat1->col_size);
1549
1550         return newMatrixObject(mat, mat1->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1551 }
1552 /*------------------------obj * obj------------------------------
1553   mulplication*/
1554 static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
1555 {
1556         float tmat[16];
1557         mul_vn_vn_fl(tmat, mat->contigPtr, mat->row_size * mat->col_size, scalar);
1558         return newMatrixObject(tmat, mat->row_size, mat->col_size, Py_NEW, Py_TYPE(mat));
1559 }
1560
1561 static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
1562 {
1563         float scalar;
1564
1565         MatrixObject *mat1 = NULL, *mat2 = NULL;
1566
1567         if (MatrixObject_Check(m1)) {
1568                 mat1 = (MatrixObject*)m1;
1569                 if (BaseMath_ReadCallback(mat1) == -1)
1570                         return NULL;
1571         }
1572         if (MatrixObject_Check(m2)) {
1573                 mat2 = (MatrixObject*)m2;
1574                 if (BaseMath_ReadCallback(mat2) == -1)
1575                         return NULL;
1576         }
1577
1578         if (mat1 && mat2) {
1579                 /*MATRIX * MATRIX*/
1580                 float mat[16]= {0.0f, 0.0f, 0.0f, 0.0f,
1581                                                 0.0f, 0.0f, 0.0f, 0.0f,
1582                                                 0.0f, 0.0f, 0.0f, 0.0f,
1583                                                 0.0f, 0.0f, 0.0f, 1.0f};
1584                 double dot = 0.0f;
1585                 int x, y, z;
1586
1587                 for (x = 0; x < mat2->row_size; x++) {
1588                         for (y = 0; y < mat1->col_size; y++) {
1589                                 for (z = 0; z < mat1->row_size; z++) {
1590                                         dot += (mat1->matrix[z][y] * mat2->matrix[x][z]);
1591                                 }
1592                                 mat[((x * mat1->col_size) + y)] = (float)dot;
1593                                 dot = 0.0f;
1594                         }
1595                 }
1596
1597                 return newMatrixObject(mat, mat2->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1598         }
1599         else if (mat2) {
1600                 /*FLOAT/INT * MATRIX */
1601                 if (((scalar= PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred())==0) {
1602                         return matrix_mul_float(mat2, scalar);
1603                 }
1604         }
1605         else if (mat1) {
1606                 /*VEC * MATRIX */
1607                 if (VectorObject_Check(m2)) {
1608                         VectorObject *vec2= (VectorObject *)m2;
1609                         float tvec[4];
1610                         if (BaseMath_ReadCallback(vec2) == -1)
1611                                 return NULL;
1612                         if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
1613                                 return NULL;
1614                         }
1615
1616                         return newVectorObject(tvec, vec2->size, Py_NEW, Py_TYPE(m2));
1617                 }
1618                 /*FLOAT/INT * MATRIX */
1619                 else if (((scalar= PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred())==0) {
1620                         return matrix_mul_float(mat1, scalar);
1621                 }
1622         }
1623         else {
1624                 BLI_assert(!"internal error");
1625         }
1626
1627         PyErr_Format(PyExc_TypeError,
1628                      "Matrix multiplication: "
1629                      "not supported between '%.200s' and '%.200s' types",
1630                      Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
1631         return NULL;
1632 }
1633 static PyObject* Matrix_inv(MatrixObject *self)
1634 {
1635         if (BaseMath_ReadCallback(self) == -1)
1636                 return NULL;
1637
1638         return Matrix_invert(self);
1639 }
1640
1641 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1642 static PySequenceMethods Matrix_SeqMethods = {
1643         (lenfunc) Matrix_len,                                           /* sq_length */
1644         (binaryfunc) NULL,                                                      /* sq_concat */
1645         (ssizeargfunc) NULL,                                            /* sq_repeat */
1646         (ssizeargfunc) Matrix_item,                                     /* sq_item */
1647         (ssizessizeargfunc) NULL,                                       /* sq_slice, deprecated */
1648         (ssizeobjargproc) Matrix_ass_item,                      /* sq_ass_item */
1649         (ssizessizeobjargproc) NULL,                            /* sq_ass_slice, deprecated */
1650         (objobjproc) NULL,                                                      /* sq_contains */
1651         (binaryfunc) NULL,                                                      /* sq_inplace_concat */
1652         (ssizeargfunc) NULL,                                            /* sq_inplace_repeat */
1653 };
1654
1655
1656 static PyObject *Matrix_subscript(MatrixObject* self, PyObject* item)
1657 {
1658         if (PyIndex_Check(item)) {
1659                 Py_ssize_t i;
1660                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1661                 if (i == -1 && PyErr_Occurred())
1662                         return NULL;
1663                 if (i < 0)
1664                         i += self->row_size;
1665                 return Matrix_item(self, i);
1666         }
1667         else if (PySlice_Check(item)) {
1668                 Py_ssize_t start, stop, step, slicelength;
1669
1670                 if (PySlice_GetIndicesEx((void *)item, self->row_size, &start, &stop, &step, &slicelength) < 0)
1671                         return NULL;
1672
1673                 if (slicelength <= 0) {
1674                         return PyTuple_New(0);
1675                 }
1676                 else if (step == 1) {
1677                         return Matrix_slice(self, start, stop);
1678                 }
1679                 else {
1680                         PyErr_SetString(PyExc_IndexError,
1681                                         "slice steps not supported with matrices");
1682                         return NULL;
1683                 }
1684         }
1685         else {
1686                 PyErr_Format(PyExc_TypeError,
1687                              "matrix indices must be integers, not %.200s",
1688                              Py_TYPE(item)->tp_name);
1689                 return NULL;
1690         }
1691 }
1692
1693 static int Matrix_ass_subscript(MatrixObject* self, PyObject* item, PyObject* value)
1694 {
1695         if (PyIndex_Check(item)) {
1696                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1697                 if (i == -1 && PyErr_Occurred())
1698                         return -1;
1699                 if (i < 0)
1700                         i += self->row_size;
1701                 return Matrix_ass_item(self, i, value);
1702         }
1703         else if (PySlice_Check(item)) {
1704                 Py_ssize_t start, stop, step, slicelength;
1705
1706                 if (PySlice_GetIndicesEx((void *)item, self->row_size, &start, &stop, &step, &slicelength) < 0)
1707                         return -1;
1708
1709                 if (step == 1)
1710                         return Matrix_ass_slice(self, start, stop, value);
1711                 else {
1712                         PyErr_SetString(PyExc_IndexError,
1713                                         "slice steps not supported with matrices");
1714                         return -1;
1715                 }
1716         }
1717         else {
1718                 PyErr_Format(PyExc_TypeError,
1719                              "matrix indices must be integers, not %.200s",
1720                              Py_TYPE(item)->tp_name);
1721                 return -1;
1722         }
1723 }
1724
1725 static PyMappingMethods Matrix_AsMapping = {
1726         (lenfunc)Matrix_len,
1727         (binaryfunc)Matrix_subscript,
1728         (objobjargproc)Matrix_ass_subscript
1729 };
1730
1731
1732 static PyNumberMethods Matrix_NumMethods = {
1733                 (binaryfunc)    Matrix_add,     /*nb_add*/
1734                 (binaryfunc)    Matrix_sub,     /*nb_subtract*/
1735                 (binaryfunc)    Matrix_mul,     /*nb_multiply*/
1736                 NULL,                                                   /*nb_remainder*/
1737                 NULL,                                                   /*nb_divmod*/
1738                 NULL,                                                   /*nb_power*/
1739                 (unaryfunc)     0,      /*nb_negative*/
1740                 (unaryfunc)     0,      /*tp_positive*/
1741                 (unaryfunc)     0,      /*tp_absolute*/
1742                 (inquiry)       0,      /*tp_bool*/
1743                 (unaryfunc)     Matrix_inv,     /*nb_invert*/
1744                 NULL,                           /*nb_lshift*/
1745                 (binaryfunc)0,  /*nb_rshift*/
1746                 NULL,                           /*nb_and*/
1747                 NULL,                           /*nb_xor*/
1748                 NULL,                           /*nb_or*/
1749                 NULL,                           /*nb_int*/
1750                 NULL,                           /*nb_reserved*/
1751                 NULL,                           /*nb_float*/
1752                 NULL,                           /* nb_inplace_add */
1753                 NULL,                           /* nb_inplace_subtract */
1754                 NULL,                           /* nb_inplace_multiply */
1755                 NULL,                           /* nb_inplace_remainder */
1756                 NULL,                           /* nb_inplace_power */
1757                 NULL,                           /* nb_inplace_lshift */
1758                 NULL,                           /* nb_inplace_rshift */
1759                 NULL,                           /* nb_inplace_and */
1760                 NULL,                           /* nb_inplace_xor */
1761                 NULL,                           /* nb_inplace_or */
1762                 NULL,                           /* nb_floor_divide */
1763                 NULL,                           /* nb_true_divide */
1764                 NULL,                           /* nb_inplace_floor_divide */
1765                 NULL,                           /* nb_inplace_true_divide */
1766                 NULL,                           /* nb_index */
1767 };
1768
1769 static PyObject *Matrix_getRowSize(MatrixObject *self, void *UNUSED(closure))
1770 {
1771         return PyLong_FromLong((long) self->row_size);
1772 }
1773
1774 static PyObject *Matrix_getColSize(MatrixObject *self, void *UNUSED(closure))
1775 {
1776         return PyLong_FromLong((long) self->col_size);
1777 }
1778
1779 static PyObject *Matrix_median_scale_get(MatrixObject *self, void *UNUSED(closure))
1780 {
1781         float mat[3][3];
1782
1783         if (BaseMath_ReadCallback(self) == -1)
1784                 return NULL;
1785
1786         /*must be 3-4 cols, 3-4 rows, square matrix*/
1787         if ((self->col_size < 3) || (self->row_size < 3)) {
1788                 PyErr_SetString(PyExc_AttributeError,
1789                                 "Matrix.median_scale: "
1790                                 "inappropriate matrix size, 3x3 minimum");
1791                 return NULL;
1792         }
1793
1794         matrix_as_3x3(mat, self);
1795
1796         return PyFloat_FromDouble(mat3_to_scale(mat));
1797 }
1798
1799 static PyObject *Matrix_is_negative_get(MatrixObject *self, void *UNUSED(closure))
1800 {
1801         if (BaseMath_ReadCallback(self) == -1)
1802                 return NULL;
1803
1804         /*must be 3-4 cols, 3-4 rows, square matrix*/
1805         if (self->col_size == 4 && self->row_size == 4)
1806                 return PyBool_FromLong(is_negative_m4((float (*)[4])self->contigPtr));
1807         else if (self->col_size == 3 && self->row_size == 3)
1808                 return PyBool_FromLong(is_negative_m3((float (*)[3])self->contigPtr));
1809         else {
1810                 PyErr_SetString(PyExc_AttributeError,
1811                                 "Matrix.is_negative: "
1812                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1813                 return NULL;
1814         }
1815 }
1816
1817 static PyObject *Matrix_is_orthogonal_get(MatrixObject *self, void *UNUSED(closure))
1818 {
1819         if (BaseMath_ReadCallback(self) == -1)
1820                 return NULL;
1821
1822         /*must be 3-4 cols, 3-4 rows, square matrix*/
1823         if (self->col_size == 4 && self->row_size == 4)
1824                 return PyBool_FromLong(is_orthogonal_m4((float (*)[4])self->contigPtr));
1825         else if (self->col_size == 3 && self->row_size == 3)
1826                 return PyBool_FromLong(is_orthogonal_m3((float (*)[3])self->contigPtr));
1827         else {
1828                 PyErr_SetString(PyExc_AttributeError,
1829                                 "Matrix.is_orthogonal: "
1830                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1831                 return NULL;
1832         }
1833 }
1834
1835 /*****************************************************************************/
1836 /* Python attributes get/set structure:                                      */
1837 /*****************************************************************************/
1838 static PyGetSetDef Matrix_getseters[] = {
1839         {(char *)"row_size", (getter)Matrix_getRowSize, (setter)NULL, (char *)"The row size of the matrix (readonly).\n\n:type: int", NULL},
1840         {(char *)"col_size", (getter)Matrix_getColSize, (setter)NULL, (char *)"The column size of the matrix (readonly).\n\n:type: int", NULL},
1841         {(char *)"median_scale", (getter)Matrix_median_scale_get, (setter)NULL, (char *)"The average scale applied to each axis (readonly).\n\n:type: float", NULL},
1842         {(char *)"is_negative", (getter)Matrix_is_negative_get, (setter)NULL, (char *)"True if this matrix results in a negative scale, 3x3 and 4x4 only, (readonly).\n\n:type: bool", NULL},
1843         {(char *)"is_orthogonal", (getter)Matrix_is_orthogonal_get, (setter)NULL, (char *)"True if this matrix is orthogonal, 3x3 and 4x4 only, (readonly).\n\n:type: bool", NULL},
1844         {(char *)"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, (char *)BaseMathObject_Wrapped_doc, NULL},
1845         {(char *)"owner",(getter)BaseMathObject_getOwner, (setter)NULL, (char *)BaseMathObject_Owner_doc, NULL},
1846         {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
1847 };
1848
1849 /*-----------------------METHOD DEFINITIONS ----------------------*/
1850 static struct PyMethodDef Matrix_methods[] = {
1851         /* derived values */
1852         {"determinant", (PyCFunction) Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
1853         {"decompose", (PyCFunction) Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
1854
1855         /* in place only */
1856         {"zero", (PyCFunction) Matrix_zero, METH_NOARGS, Matrix_zero_doc},
1857         {"identity", (PyCFunction) Matrix_identity, METH_NOARGS, Matrix_identity_doc},
1858
1859         /* operate on original or copy */
1860         {"transpose", (PyCFunction) Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
1861         {"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
1862         {"invert", (PyCFunction) Matrix_invert, METH_NOARGS, Matrix_invert_doc},
1863         {"inverted", (PyCFunction) Matrix_inverted, METH_NOARGS, Matrix_inverted_doc},
1864         {"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
1865         // TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc},
1866         {"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
1867         {"resize_4x4", (PyCFunction) Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
1868         {"rotate", (PyCFunction) Matrix_rotate, METH_O, Matrix_rotate_doc},
1869
1870         /* return converted representation */
1871         {"to_euler", (PyCFunction) Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
1872         {"to_quaternion", (PyCFunction) Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
1873         {"to_scale", (PyCFunction) Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
1874         {"to_translation", (PyCFunction) Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
1875
1876         /* operation between 2 or more types  */
1877         {"lerp", (PyCFunction) Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
1878         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1879         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1880
1881         /* class methods */
1882         {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
1883         {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
1884         {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
1885         {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
1886         {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection,  METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
1887         {NULL, NULL, 0, NULL}
1888 };
1889
1890 /*------------------PY_OBECT DEFINITION--------------------------*/
1891 PyDoc_STRVAR(matrix_doc,
1892 "This object gives access to Matrices in Blender."
1893 );
1894 PyTypeObject matrix_Type = {
1895         PyVarObject_HEAD_INIT(NULL, 0)
1896         "mathutils.Matrix",                                     /*tp_name*/
1897         sizeof(MatrixObject),                           /*tp_basicsize*/
1898         0,                                                                      /*tp_itemsize*/
1899         (destructor)BaseMathObject_dealloc,     /*tp_dealloc*/
1900         NULL,                                                           /*tp_print*/
1901         NULL,                                                           /*tp_getattr*/
1902         NULL,                                                           /*tp_setattr*/
1903         NULL,                                                           /*tp_compare*/
1904         (reprfunc) Matrix_repr,                         /*tp_repr*/
1905         &Matrix_NumMethods,                                     /*tp_as_number*/
1906         &Matrix_SeqMethods,                                     /*tp_as_sequence*/
1907         &Matrix_AsMapping,                                      /*tp_as_mapping*/
1908         NULL,                                                           /*tp_hash*/
1909         NULL,                                                           /*tp_call*/
1910         NULL,                                                           /*tp_str*/
1911         NULL,                                                           /*tp_getattro*/
1912         NULL,                                                           /*tp_setattro*/
1913         NULL,                                                           /*tp_as_buffer*/
1914         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
1915         matrix_doc,                                                     /*tp_doc*/
1916         (traverseproc)BaseMathObject_traverse,  //tp_traverse
1917         (inquiry)BaseMathObject_clear,  //tp_clear
1918         (richcmpfunc)Matrix_richcmpr,           /*tp_richcompare*/
1919         0,                                                                      /*tp_weaklistoffset*/
1920         NULL,                                                           /*tp_iter*/
1921         NULL,                                                           /*tp_iternext*/
1922         Matrix_methods,                                         /*tp_methods*/
1923         NULL,                                                           /*tp_members*/
1924         Matrix_getseters,                                       /*tp_getset*/
1925         NULL,                                                           /*tp_base*/
1926         NULL,                                                           /*tp_dict*/
1927         NULL,                                                           /*tp_descr_get*/
1928         NULL,                                                           /*tp_descr_set*/
1929         0,                                                                      /*tp_dictoffset*/
1930         NULL,                                                           /*tp_init*/
1931         NULL,                                                           /*tp_alloc*/
1932         Matrix_new,                                                     /*tp_new*/
1933         NULL,                                                           /*tp_free*/
1934         NULL,                                                           /*tp_is_gc*/
1935         NULL,                                                           /*tp_bases*/
1936         NULL,                                                           /*tp_mro*/
1937         NULL,                                                           /*tp_cache*/
1938         NULL,                                                           /*tp_subclasses*/
1939         NULL,                                                           /*tp_weaklist*/
1940         NULL                                                            /*tp_del*/
1941 };
1942
1943 /*------------------------newMatrixObject (internal)-------------
1944 creates a new matrix object
1945 self->matrix     self->contiguous_ptr (reference to data.xxx)
1946            [0]------------->[0]
1947                                                 [1]
1948                                                 [2]
1949            [1]------------->[3]
1950                                                 [4]
1951                                                 [5]
1952
1953 self->matrix[1][1] = self->contigPtr[4] */
1954
1955 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1956  (i.e. it was allocated elsewhere by MEM_mallocN())
1957   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1958  (i.e. it must be created here with PyMEM_malloc())*/
1959 PyObject *newMatrixObject(float *mat, const unsigned short rowSize, const unsigned short colSize, int type, PyTypeObject *base_type)
1960 {
1961         MatrixObject *self;
1962         int x, row, col;
1963
1964         /*matrix objects can be any 2-4row x 2-4col matrix*/
1965         if (rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4) {
1966                 PyErr_SetString(PyExc_RuntimeError,
1967                                 "Matrix(): "
1968                                 "row and column sizes must be between 2 and 4");
1969                 return NULL;
1970         }
1971
1972         self= base_type ?       (MatrixObject *)base_type->tp_alloc(base_type, 0) :
1973                                                 (MatrixObject *)PyObject_GC_New(MatrixObject, &matrix_Type);
1974
1975         if (self) {
1976                 self->row_size = rowSize;
1977                 self->col_size = colSize;
1978
1979                 /* init callbacks as NULL */
1980                 self->cb_user= NULL;
1981                 self->cb_type= self->cb_subtype= 0;
1982
1983                 if (type == Py_WRAP) {
1984                         self->contigPtr = mat;
1985                         /*pointer array points to contigous memory*/
1986                         for (x = 0; x < rowSize; x++) {
1987                                 self->matrix[x] = self->contigPtr + (x * colSize);
1988                         }
1989                         self->wrapped = Py_WRAP;
1990                 }
1991                 else if (type == Py_NEW) {
1992                         self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1993                         if (self->contigPtr == NULL) { /*allocation failure*/
1994                                 PyErr_SetString(PyExc_MemoryError,
1995                                                 "Matrix(): "
1996                                                 "problem allocating pointer space");
1997                                 return NULL;
1998                         }
1999                         /*pointer array points to contigous memory*/
2000                         for (x = 0; x < rowSize; x++) {
2001                                 self->matrix[x] = self->contigPtr + (x * colSize);
2002                         }
2003                         /*parse*/
2004                         if (mat) {      /*if a float array passed*/
2005                                 for (row = 0; row < rowSize; row++) {
2006                                         for (col = 0; col < colSize; col++) {
2007                                                 self->matrix[row][col] = mat[(row * colSize) + col];
2008                                         }
2009                                 }
2010                         }
2011                         else if (rowSize == colSize) { /*or if no arguments are passed return identity matrix for square matrices */
2012                                 PyObject *ret_dummy= Matrix_identity(self);
2013                                 Py_DECREF(ret_dummy);
2014                         }
2015                         self->wrapped = Py_NEW;
2016                 }
2017                 else {
2018                         Py_FatalError("Matrix(): invalid type!");
2019                         return NULL;
2020                 }
2021         }
2022         return (PyObject *) self;
2023 }
2024
2025 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
2026 {
2027         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW, NULL);
2028         if (self) {
2029                 Py_INCREF(cb_user);
2030                 self->cb_user=                  cb_user;
2031                 self->cb_type=                  (unsigned char)cb_type;
2032                 self->cb_subtype=               (unsigned char)cb_subtype;
2033                 PyObject_GC_Track(self);
2034         }
2035         return (PyObject *) self;
2036 }