Cycles: svn merge -r41531:41613 ^/trunk/blender
[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, 0.0f, 0.0f, 0.0f, 0.0f,
945                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
946
947         if (BaseMath_ReadCallback(self) == -1)
948                 return NULL;
949
950         if (self->row_size != self->col_size) {
951                 PyErr_SetString(PyExc_TypeError,
952                                 "Matrix.invert(ed): "
953                                 "only square matrices are supported");
954                 return NULL;
955         }
956
957         /*calculate the determinant*/
958         det = matrix_determinant_internal(self);
959
960         if (det != 0) {
961                 /*calculate the classical adjoint*/
962                 if (self->row_size == 2) {
963                         mat[0] = self->matrix[1][1];
964                         mat[1] = -self->matrix[0][1];
965                         mat[2] = -self->matrix[1][0];
966                         mat[3] = self->matrix[0][0];
967                 } else if (self->row_size == 3) {
968                         adjoint_m3_m3((float (*)[3]) mat,(float (*)[3])self->contigPtr);
969                 } else if (self->row_size == 4) {
970                         adjoint_m4_m4((float (*)[4]) mat, (float (*)[4])self->contigPtr);
971                 }
972                 /*divide by determinate*/
973                 for (x = 0; x < (self->row_size * self->col_size); x++) {
974                         mat[x] /= det;
975                 }
976                 /*set values*/
977                 for (x = 0; x < self->row_size; x++) {
978                         for (y = 0; y < self->col_size; y++) {
979                                 self->matrix[x][y] = mat[z];
980                                 z++;
981                         }
982                 }
983                 /*transpose
984                 Matrix_transpose(self);*/
985         }
986         else {
987                 PyErr_SetString(PyExc_ValueError,
988                                 "Matrix.invert(ed): "
989                                 "matrix does not have an inverse");
990                 return NULL;
991         }
992
993         (void)BaseMath_WriteCallback(self);
994         Py_RETURN_NONE;
995 }
996
997 PyDoc_STRVAR(Matrix_inverted_doc,
998 ".. method:: inverted()\n"
999 "\n"
1000 "   Return an inverted copy of the matrix.\n"
1001 "\n"
1002 "   :return: the  inverted matrix.\n"
1003 "   :rtype: :class:`Matrix`\n"
1004 "\n"
1005 "   .. note:: :exc:`ValueError` exception is raised.\n"
1006 );
1007 static PyObject *Matrix_inverted(MatrixObject *self)
1008 {
1009         return matrix__apply_to_copy((PyNoArgsFunction)Matrix_invert, self);
1010 }
1011
1012 PyDoc_STRVAR(Matrix_rotate_doc,
1013 ".. method:: rotate(other)\n"
1014 "\n"
1015 "   Rotates the matrix a by another mathutils value.\n"
1016 "\n"
1017 "   :arg other: rotation component of mathutils value\n"
1018 "   :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
1019 "\n"
1020 "   .. note:: If any of the columns are not unit length this may not have desired results.\n"
1021 );
1022 static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
1023 {
1024         float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
1025
1026         if (BaseMath_ReadCallback(self) == -1)
1027                 return NULL;
1028
1029         if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1)
1030                 return NULL;
1031
1032         if (self->col_size != 3 || self->row_size != 3) {
1033                 PyErr_SetString(PyExc_TypeError,
1034                                 "Matrix.rotate(): "
1035                                 "must have 3x3 dimensions");
1036                 return NULL;
1037         }
1038
1039         matrix_as_3x3(self_rmat, self);
1040         mul_m3_m3m3(rmat, self_rmat, other_rmat);
1041
1042         copy_m3_m3((float (*)[3])(self->contigPtr), rmat);
1043
1044         (void)BaseMath_WriteCallback(self);
1045         Py_RETURN_NONE;
1046 }
1047
1048 /*---------------------------matrix.decompose() ---------------------*/
1049 PyDoc_STRVAR(Matrix_decompose_doc,
1050 ".. method:: decompose()\n"
1051 "\n"
1052 "   Return the location, rotaion and scale components of this matrix.\n"
1053 "\n"
1054 "   :return: loc, rot, scale triple.\n"
1055 "   :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
1056 );
1057 static PyObject *Matrix_decompose(MatrixObject *self)
1058 {
1059         PyObject *ret;
1060         float loc[3];
1061         float rot[3][3];
1062         float quat[4];
1063         float size[3];
1064
1065         if (self->col_size != 4 || self->row_size != 4) {
1066                 PyErr_SetString(PyExc_TypeError,
1067                                 "Matrix.decompose(): "
1068                                 "inappropriate matrix size - expects 4x4 matrix");
1069                 return NULL;
1070         }
1071
1072         if (BaseMath_ReadCallback(self) == -1)
1073                 return NULL;
1074
1075         mat4_to_loc_rot_size(loc, rot, size, (float (*)[4])self->contigPtr);
1076         mat3_to_quat(quat, rot);
1077
1078         ret= PyTuple_New(3);
1079         PyTuple_SET_ITEM(ret, 0, newVectorObject(loc, 3, Py_NEW, NULL));
1080         PyTuple_SET_ITEM(ret, 1, newQuaternionObject(quat, Py_NEW, NULL));
1081         PyTuple_SET_ITEM(ret, 2, newVectorObject(size, 3, Py_NEW, NULL));
1082
1083         return ret;
1084 }
1085
1086
1087
1088 PyDoc_STRVAR(Matrix_lerp_doc,
1089 ".. function:: lerp(other, factor)\n"
1090 "\n"
1091 "   Returns the interpolation of two matrices.\n"
1092 "\n"
1093 "   :arg other: value to interpolate with.\n"
1094 "   :type other: :class:`Matrix`\n"
1095 "   :arg factor: The interpolation value in [0.0, 1.0].\n"
1096 "   :type factor: float\n"
1097 "   :return: The interpolated rotation.\n"
1098 "   :rtype: :class:`Matrix`\n"
1099 );
1100 static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
1101 {
1102         MatrixObject *mat2 = NULL;
1103         float fac, mat[MATRIX_MAX_DIM*MATRIX_MAX_DIM];
1104
1105         if (!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac))
1106                 return NULL;
1107
1108         if (self->row_size != mat2->row_size || self->col_size != mat2->col_size) {
1109                 PyErr_SetString(PyExc_ValueError,
1110                                 "Matrix.lerp(): "
1111                                 "expects both matrix objects of the same dimensions");
1112                 return NULL;
1113         }
1114
1115         if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1)
1116                 return NULL;
1117
1118         /* TODO, different sized matrix */
1119         if (self->row_size==4 && self->col_size==4) {
1120                 blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->contigPtr, (float (*)[4])mat2->contigPtr, fac);
1121         }
1122         else if (self->row_size==3 && self->col_size==3) {
1123                 blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->contigPtr, (float (*)[3])mat2->contigPtr, fac);
1124         }
1125         else {
1126                 PyErr_SetString(PyExc_ValueError,
1127                                 "Matrix.lerp(): "
1128                                 "only 3x3 and 4x4 matrices supported");
1129                 return NULL;
1130         }
1131
1132         return (PyObject*)newMatrixObject(mat, self->row_size, self->col_size, Py_NEW, Py_TYPE(self));
1133 }
1134
1135 /*---------------------------matrix.determinant() ----------------*/
1136 PyDoc_STRVAR(Matrix_determinant_doc,
1137 ".. method:: determinant()\n"
1138 "\n"
1139 "   Return the determinant of a matrix.\n"
1140 "\n"
1141 "   :return: Return a the determinant of a matrix.\n"
1142 "   :rtype: float\n"
1143 "\n"
1144 "   .. seealso:: <http://en.wikipedia.org/wiki/Determinant>\n"
1145 );
1146 static PyObject *Matrix_determinant(MatrixObject *self)
1147 {
1148         if (BaseMath_ReadCallback(self) == -1)
1149                 return NULL;
1150
1151         if (self->row_size != self->col_size) {
1152                 PyErr_SetString(PyExc_TypeError,
1153                                 "Matrix.determinant(): "
1154                                 "only square matrices are supported");
1155                 return NULL;
1156         }
1157
1158         return PyFloat_FromDouble((double)matrix_determinant_internal(self));
1159 }
1160 /*---------------------------matrix.transpose() ------------------*/
1161 PyDoc_STRVAR(Matrix_transpose_doc,
1162 ".. method:: transpose()\n"
1163 "\n"
1164 "   Set the matrix to its transpose.\n"
1165 "\n"
1166 "   .. seealso:: <http://en.wikipedia.org/wiki/Transpose>\n"
1167 );
1168 static PyObject *Matrix_transpose(MatrixObject *self)
1169 {
1170         float t = 0.0f;
1171
1172         if (BaseMath_ReadCallback(self) == -1)
1173                 return NULL;
1174
1175         if (self->row_size != self->col_size) {
1176                 PyErr_SetString(PyExc_TypeError,
1177                                 "Matrix.transpose(d): "
1178                                 "only square matrices are supported");
1179                 return NULL;
1180         }
1181
1182         if (self->row_size == 2) {
1183                 t = self->matrix[1][0];
1184                 self->matrix[1][0] = self->matrix[0][1];
1185                 self->matrix[0][1] = t;
1186         } else if (self->row_size == 3) {
1187                 transpose_m3((float (*)[3])self->contigPtr);
1188         }
1189         else {
1190                 transpose_m4((float (*)[4])self->contigPtr);
1191         }
1192
1193         (void)BaseMath_WriteCallback(self);
1194         Py_RETURN_NONE;
1195 }
1196
1197 PyDoc_STRVAR(Matrix_transposed_doc,
1198 ".. method:: transposed()\n"
1199 "\n"
1200 "   Return a new, transposed matrix.\n"
1201 "\n"
1202 "   :return: a transposed matrix\n"
1203 "   :rtype: :class:`Matrix`\n"
1204 );
1205 static PyObject *Matrix_transposed(MatrixObject *self)
1206 {
1207         return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
1208 }
1209
1210 /*---------------------------matrix.zero() -----------------------*/
1211 PyDoc_STRVAR(Matrix_zero_doc,
1212 ".. method:: zero()\n"
1213 "\n"
1214 "   Set all the matrix values to zero.\n"
1215 "\n"
1216 "   :return: an instance of itself\n"
1217 "   :rtype: :class:`Matrix`\n"
1218 );
1219 static PyObject *Matrix_zero(MatrixObject *self)
1220 {
1221         fill_vn(self->contigPtr, self->row_size * self->col_size, 0.0f);
1222
1223         if (BaseMath_WriteCallback(self) == -1)
1224                 return NULL;
1225
1226         Py_RETURN_NONE;
1227 }
1228 /*---------------------------matrix.identity(() ------------------*/
1229 PyDoc_STRVAR(Matrix_identity_doc,
1230 ".. method:: identity()\n"
1231 "\n"
1232 "   Set the matrix to the identity matrix.\n"
1233 "\n"
1234 "   .. note:: An object with zero location and rotation, a scale of one,\n"
1235 "      will have an identity matrix.\n"
1236 "\n"
1237 "   .. seealso:: <http://en.wikipedia.org/wiki/Identity_matrix>\n"
1238 );
1239 static PyObject *Matrix_identity(MatrixObject *self)
1240 {
1241         if (BaseMath_ReadCallback(self) == -1)
1242                 return NULL;
1243
1244         if (self->row_size != self->col_size) {
1245                 PyErr_SetString(PyExc_TypeError,
1246                                 "Matrix.identity(): "
1247                                 "only square matrices are supported");
1248                 return NULL;
1249         }
1250
1251         if (self->row_size == 2) {
1252                 self->matrix[0][0] = 1.0f;
1253                 self->matrix[0][1] = 0.0f;
1254                 self->matrix[1][0] = 0.0f;
1255                 self->matrix[1][1] = 1.0f;
1256         } else if (self->row_size == 3) {
1257                 unit_m3((float (*)[3])self->contigPtr);
1258         }
1259         else {
1260                 unit_m4((float (*)[4])self->contigPtr);
1261         }
1262
1263         if (BaseMath_WriteCallback(self) == -1)
1264                 return NULL;
1265
1266         Py_RETURN_NONE;
1267 }
1268
1269 /*---------------------------Matrix.copy() ------------------*/
1270 PyDoc_STRVAR(Matrix_copy_doc,
1271 ".. method:: copy()\n"
1272 "\n"
1273 "   Returns a copy of this matrix.\n"
1274 "\n"
1275 "   :return: an instance of itself\n"
1276 "   :rtype: :class:`Matrix`\n"
1277 );
1278 static PyObject *Matrix_copy(MatrixObject *self)
1279 {
1280         if (BaseMath_ReadCallback(self) == -1)
1281                 return NULL;
1282
1283         return (PyObject*)newMatrixObject((float (*))self->contigPtr, self->row_size, self->col_size, Py_NEW, Py_TYPE(self));
1284 }
1285
1286 /*----------------------------print object (internal)-------------*/
1287 /*print the object to screen*/
1288 static PyObject *Matrix_repr(MatrixObject *self)
1289 {
1290         int x, y;
1291         PyObject *rows[MATRIX_MAX_DIM]= {NULL};
1292
1293         if (BaseMath_ReadCallback(self) == -1)
1294                 return NULL;
1295
1296         for (x = 0; x < self->row_size; x++) {
1297                 rows[x]= PyTuple_New(self->col_size);
1298                 for (y = 0; y < self->col_size; y++) {
1299                         PyTuple_SET_ITEM(rows[x], y, PyFloat_FromDouble(self->matrix[x][y]));
1300                 }
1301         }
1302         switch(self->row_size) {
1303         case 2: return PyUnicode_FromFormat("Matrix((%R,\n"
1304                                                                                 "        %R))", rows[0], rows[1]);
1305
1306         case 3: return PyUnicode_FromFormat("Matrix((%R,\n"
1307                                                                                 "        %R,\n"
1308                                                                                 "        %R))", rows[0], rows[1], rows[2]);
1309
1310         case 4: return PyUnicode_FromFormat("Matrix((%R,\n"
1311                                                                                 "        %R,\n"
1312                                                                                 "        %R,\n"
1313                                                                                 "        %R))", rows[0], rows[1], rows[2], rows[3]);
1314         }
1315
1316         Py_FatalError("Matrix(): invalid row size!");
1317         return NULL;
1318 }
1319
1320 static PyObject* Matrix_richcmpr(PyObject *a, PyObject *b, int op)
1321 {
1322         PyObject *res;
1323         int ok= -1; /* zero is true */
1324
1325         if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
1326                 MatrixObject *matA= (MatrixObject*)a;
1327                 MatrixObject *matB= (MatrixObject*)b;
1328
1329                 if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1)
1330                         return NULL;
1331
1332                 ok=     (       (matA->col_size == matB->col_size) &&
1333                                 (matA->row_size == matB->row_size) &&
1334                                 EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr, (matA->row_size * matA->col_size), 1)
1335                         ) ? 0 : -1;
1336         }
1337
1338         switch (op) {
1339         case Py_NE:
1340                 ok = !ok; /* pass through */
1341         case Py_EQ:
1342                 res = ok ? Py_False : Py_True;
1343                 break;
1344
1345         case Py_LT:
1346         case Py_LE:
1347         case Py_GT:
1348         case Py_GE:
1349                 res = Py_NotImplemented;
1350                 break;
1351         default:
1352                 PyErr_BadArgument();
1353                 return NULL;
1354         }
1355
1356         return Py_INCREF(res), res;
1357 }
1358
1359 /*---------------------SEQUENCE PROTOCOLS------------------------
1360   ----------------------------len(object)------------------------
1361   sequence length*/
1362 static int Matrix_len(MatrixObject *self)
1363 {
1364         return (self->row_size);
1365 }
1366 /*----------------------------object[]---------------------------
1367   sequence accessor (get)
1368   the wrapped vector gives direct access to the matrix data*/
1369 static PyObject *Matrix_item(MatrixObject *self, int i)
1370 {
1371         if (BaseMath_ReadCallback(self) == -1)
1372                 return NULL;
1373
1374         if (i < 0 || i >= self->row_size) {
1375                 PyErr_SetString(PyExc_IndexError,
1376                                 "matrix[attribute]: "
1377                                 "array index out of range");
1378                 return NULL;
1379         }
1380         return newVectorObject_cb((PyObject *)self, self->col_size, mathutils_matrix_vector_cb_index, i);
1381 }
1382 /*----------------------------object[]-------------------------
1383   sequence accessor (set) */
1384
1385 static int Matrix_ass_item(MatrixObject *self, int i, PyObject *value)
1386 {
1387         float vec[4];
1388         if (BaseMath_ReadCallback(self) == -1)
1389                 return -1;
1390
1391         if (i >= self->row_size || i < 0) {
1392                 PyErr_SetString(PyExc_IndexError,
1393                                 "matrix[attribute] = x: bad column");
1394                 return -1;
1395         }
1396
1397         if (mathutils_array_parse(vec, self->col_size, self->col_size, value, "matrix[i] = value assignment") < 0) {
1398                 return -1;
1399         }
1400
1401         memcpy(self->matrix[i], vec, self->col_size *sizeof(float));
1402
1403         (void)BaseMath_WriteCallback(self);
1404         return 0;
1405 }
1406
1407 /*----------------------------object[z:y]------------------------
1408   sequence slice (get)*/
1409 static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
1410 {
1411
1412         PyObject *tuple;
1413         int count;
1414
1415         if (BaseMath_ReadCallback(self) == -1)
1416                 return NULL;
1417
1418         CLAMP(begin, 0, self->row_size);
1419         CLAMP(end, 0, self->row_size);
1420         begin= MIN2(begin, end);
1421
1422         tuple= PyTuple_New(end - begin);
1423         for (count= begin; count < end; count++) {
1424                 PyTuple_SET_ITEM(tuple, count - begin,
1425                                 newVectorObject_cb((PyObject *)self, self->col_size, mathutils_matrix_vector_cb_index, count));
1426
1427         }
1428
1429         return tuple;
1430 }
1431 /*----------------------------object[z:y]------------------------
1432   sequence slice (set)*/
1433 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
1434 {
1435         PyObject *value_fast= NULL;
1436
1437         if (BaseMath_ReadCallback(self) == -1)
1438                 return -1;
1439
1440         CLAMP(begin, 0, self->row_size);
1441         CLAMP(end, 0, self->row_size);
1442         begin = MIN2(begin, end);
1443
1444         /* non list/tuple cases */
1445         if (!(value_fast=PySequence_Fast(value, "matrix[begin:end] = value"))) {
1446                 /* PySequence_Fast sets the error */
1447                 return -1;
1448         }
1449         else {
1450                 const int size= end - begin;
1451                 int i;
1452                 float mat[16];
1453
1454                 if (PySequence_Fast_GET_SIZE(value_fast) != size) {
1455                         Py_DECREF(value_fast);
1456                         PyErr_SetString(PyExc_ValueError,
1457                                         "matrix[begin:end] = []: "
1458                                         "size mismatch in slice assignment");
1459                         return -1;
1460                 }
1461
1462                 /*parse sub items*/
1463                 for (i = 0; i < size; i++) {
1464                         /*parse each sub sequence*/
1465                         PyObject *item= PySequence_Fast_GET_ITEM(value_fast, i);
1466
1467                         if (mathutils_array_parse(&mat[i * self->col_size], self->col_size, self->col_size, item, "matrix[begin:end] = value assignment") < 0) {
1468                                 return -1;
1469                         }
1470                 }
1471
1472                 Py_DECREF(value_fast);
1473
1474                 /*parsed well - now set in matrix*/
1475                 memcpy(self->contigPtr + (begin * self->col_size), mat, sizeof(float) * (size * self->col_size));
1476
1477                 (void)BaseMath_WriteCallback(self);
1478                 return 0;
1479         }
1480 }
1481 /*------------------------NUMERIC PROTOCOLS----------------------
1482   ------------------------obj + obj------------------------------*/
1483 static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
1484 {
1485         float mat[16];
1486         MatrixObject *mat1 = NULL, *mat2 = NULL;
1487
1488         mat1 = (MatrixObject*)m1;
1489         mat2 = (MatrixObject*)m2;
1490
1491         if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1492                 PyErr_SetString(PyExc_TypeError,
1493                                 "Matrix addition: "
1494                                 "arguments not valid for this operation");
1495                 return NULL;
1496         }
1497
1498         if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1)
1499                 return NULL;
1500
1501         if (mat1->row_size != mat2->row_size || mat1->col_size != mat2->col_size) {
1502                 PyErr_SetString(PyExc_TypeError,
1503                                 "Matrix addition: "
1504                                 "matrices must have the same dimensions for this operation");
1505                 return NULL;
1506         }
1507
1508         add_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->row_size * mat1->col_size);
1509
1510         return newMatrixObject(mat, mat1->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1511 }
1512 /*------------------------obj - obj------------------------------
1513   subtraction*/
1514 static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
1515 {
1516         float mat[16];
1517         MatrixObject *mat1 = NULL, *mat2 = NULL;
1518
1519         mat1 = (MatrixObject*)m1;
1520         mat2 = (MatrixObject*)m2;
1521
1522         if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1523                 PyErr_SetString(PyExc_TypeError,
1524                                 "Matrix addition: "
1525                                 "arguments not valid for this operation");
1526                 return NULL;
1527         }
1528
1529         if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1)
1530                 return NULL;
1531
1532         if (mat1->row_size != mat2->row_size || mat1->col_size != mat2->col_size) {
1533                 PyErr_SetString(PyExc_TypeError,
1534                                 "Matrix addition: "
1535                                 "matrices must have the same dimensions for this operation");
1536                 return NULL;
1537         }
1538
1539         sub_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->row_size * mat1->col_size);
1540
1541         return newMatrixObject(mat, mat1->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1542 }
1543 /*------------------------obj * obj------------------------------
1544   mulplication*/
1545 static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
1546 {
1547         float tmat[16];
1548         mul_vn_vn_fl(tmat, mat->contigPtr, mat->row_size * mat->col_size, scalar);
1549         return newMatrixObject(tmat, mat->row_size, mat->col_size, Py_NEW, Py_TYPE(mat));
1550 }
1551
1552 static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
1553 {
1554         float scalar;
1555
1556         MatrixObject *mat1 = NULL, *mat2 = NULL;
1557
1558         if (MatrixObject_Check(m1)) {
1559                 mat1 = (MatrixObject*)m1;
1560                 if (BaseMath_ReadCallback(mat1) == -1)
1561                         return NULL;
1562         }
1563         if (MatrixObject_Check(m2)) {
1564                 mat2 = (MatrixObject*)m2;
1565                 if (BaseMath_ReadCallback(mat2) == -1)
1566                         return NULL;
1567         }
1568
1569         if (mat1 && mat2) {
1570                 /*MATRIX * MATRIX*/
1571                 float mat[16]= {0.0f, 0.0f, 0.0f, 0.0f,
1572                                                 0.0f, 0.0f, 0.0f, 0.0f,
1573                                                 0.0f, 0.0f, 0.0f, 0.0f,
1574                                                 0.0f, 0.0f, 0.0f, 1.0f};
1575                 double dot = 0.0f;
1576                 int x, y, z;
1577
1578                 for (x = 0; x < mat2->row_size; x++) {
1579                         for (y = 0; y < mat1->col_size; y++) {
1580                                 for (z = 0; z < mat1->row_size; z++) {
1581                                         dot += (mat1->matrix[z][y] * mat2->matrix[x][z]);
1582                                 }
1583                                 mat[((x * mat1->col_size) + y)] = (float)dot;
1584                                 dot = 0.0f;
1585                         }
1586                 }
1587
1588                 return newMatrixObject(mat, mat2->row_size, mat1->col_size, Py_NEW, Py_TYPE(mat1));
1589         }
1590         else if (mat2) {
1591                 /*FLOAT/INT * MATRIX */
1592                 if (((scalar= PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred())==0) {
1593                         return matrix_mul_float(mat2, scalar);
1594                 }
1595         }
1596         else if (mat1) {
1597                 /*VEC * MATRIX */
1598                 if (VectorObject_Check(m2)) {
1599                         VectorObject *vec2= (VectorObject *)m2;
1600                         float tvec[4];
1601                         if (BaseMath_ReadCallback(vec2) == -1)
1602                                 return NULL;
1603                         if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
1604                                 return NULL;
1605                         }
1606
1607                         return newVectorObject(tvec, vec2->size, Py_NEW, Py_TYPE(m2));
1608                 }
1609                 /*FLOAT/INT * MATRIX */
1610                 else if (((scalar= PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred())==0) {
1611                         return matrix_mul_float(mat1, scalar);
1612                 }
1613         }
1614         else {
1615                 BLI_assert(!"internal error");
1616         }
1617
1618         PyErr_Format(PyExc_TypeError,
1619                      "Matrix multiplication: "
1620                      "not supported between '%.200s' and '%.200s' types",
1621                      Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
1622         return NULL;
1623 }
1624 static PyObject* Matrix_inv(MatrixObject *self)
1625 {
1626         if (BaseMath_ReadCallback(self) == -1)
1627                 return NULL;
1628
1629         return Matrix_invert(self);
1630 }
1631
1632 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1633 static PySequenceMethods Matrix_SeqMethods = {
1634         (lenfunc) Matrix_len,                                           /* sq_length */
1635         (binaryfunc) NULL,                                                      /* sq_concat */
1636         (ssizeargfunc) NULL,                                            /* sq_repeat */
1637         (ssizeargfunc) Matrix_item,                                     /* sq_item */
1638         (ssizessizeargfunc) NULL,                                       /* sq_slice, deprecated */
1639         (ssizeobjargproc) Matrix_ass_item,                      /* sq_ass_item */
1640         (ssizessizeobjargproc) NULL,                            /* sq_ass_slice, deprecated */
1641         (objobjproc) NULL,                                                      /* sq_contains */
1642         (binaryfunc) NULL,                                                      /* sq_inplace_concat */
1643         (ssizeargfunc) NULL,                                            /* sq_inplace_repeat */
1644 };
1645
1646
1647 static PyObject *Matrix_subscript(MatrixObject* self, PyObject* item)
1648 {
1649         if (PyIndex_Check(item)) {
1650                 Py_ssize_t i;
1651                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1652                 if (i == -1 && PyErr_Occurred())
1653                         return NULL;
1654                 if (i < 0)
1655                         i += self->row_size;
1656                 return Matrix_item(self, i);
1657         } else if (PySlice_Check(item)) {
1658                 Py_ssize_t start, stop, step, slicelength;
1659
1660                 if (PySlice_GetIndicesEx((void *)item, self->row_size, &start, &stop, &step, &slicelength) < 0)
1661                         return NULL;
1662
1663                 if (slicelength <= 0) {
1664                         return PyTuple_New(0);
1665                 }
1666                 else if (step == 1) {
1667                         return Matrix_slice(self, start, stop);
1668                 }
1669                 else {
1670                         PyErr_SetString(PyExc_IndexError,
1671                                         "slice steps not supported with matrices");
1672                         return NULL;
1673                 }
1674         }
1675         else {
1676                 PyErr_Format(PyExc_TypeError,
1677                              "matrix indices must be integers, not %.200s",
1678                              Py_TYPE(item)->tp_name);
1679                 return NULL;
1680         }
1681 }
1682
1683 static int Matrix_ass_subscript(MatrixObject* self, PyObject* item, PyObject* value)
1684 {
1685         if (PyIndex_Check(item)) {
1686                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1687                 if (i == -1 && PyErr_Occurred())
1688                         return -1;
1689                 if (i < 0)
1690                         i += self->row_size;
1691                 return Matrix_ass_item(self, i, value);
1692         }
1693         else if (PySlice_Check(item)) {
1694                 Py_ssize_t start, stop, step, slicelength;
1695
1696                 if (PySlice_GetIndicesEx((void *)item, self->row_size, &start, &stop, &step, &slicelength) < 0)
1697                         return -1;
1698
1699                 if (step == 1)
1700                         return Matrix_ass_slice(self, start, stop, value);
1701                 else {
1702                         PyErr_SetString(PyExc_IndexError,
1703                                         "slice steps not supported with matrices");
1704                         return -1;
1705                 }
1706         }
1707         else {
1708                 PyErr_Format(PyExc_TypeError,
1709                              "matrix indices must be integers, not %.200s",
1710                              Py_TYPE(item)->tp_name);
1711                 return -1;
1712         }
1713 }
1714
1715 static PyMappingMethods Matrix_AsMapping = {
1716         (lenfunc)Matrix_len,
1717         (binaryfunc)Matrix_subscript,
1718         (objobjargproc)Matrix_ass_subscript
1719 };
1720
1721
1722 static PyNumberMethods Matrix_NumMethods = {
1723                 (binaryfunc)    Matrix_add,     /*nb_add*/
1724                 (binaryfunc)    Matrix_sub,     /*nb_subtract*/
1725                 (binaryfunc)    Matrix_mul,     /*nb_multiply*/
1726                 NULL,                                                   /*nb_remainder*/
1727                 NULL,                                                   /*nb_divmod*/
1728                 NULL,                                                   /*nb_power*/
1729                 (unaryfunc)     0,      /*nb_negative*/
1730                 (unaryfunc)     0,      /*tp_positive*/
1731                 (unaryfunc)     0,      /*tp_absolute*/
1732                 (inquiry)       0,      /*tp_bool*/
1733                 (unaryfunc)     Matrix_inv,     /*nb_invert*/
1734                 NULL,                           /*nb_lshift*/
1735                 (binaryfunc)0,  /*nb_rshift*/
1736                 NULL,                           /*nb_and*/
1737                 NULL,                           /*nb_xor*/
1738                 NULL,                           /*nb_or*/
1739                 NULL,                           /*nb_int*/
1740                 NULL,                           /*nb_reserved*/
1741                 NULL,                           /*nb_float*/
1742                 NULL,                           /* nb_inplace_add */
1743                 NULL,                           /* nb_inplace_subtract */
1744                 NULL,                           /* nb_inplace_multiply */
1745                 NULL,                           /* nb_inplace_remainder */
1746                 NULL,                           /* nb_inplace_power */
1747                 NULL,                           /* nb_inplace_lshift */
1748                 NULL,                           /* nb_inplace_rshift */
1749                 NULL,                           /* nb_inplace_and */
1750                 NULL,                           /* nb_inplace_xor */
1751                 NULL,                           /* nb_inplace_or */
1752                 NULL,                           /* nb_floor_divide */
1753                 NULL,                           /* nb_true_divide */
1754                 NULL,                           /* nb_inplace_floor_divide */
1755                 NULL,                           /* nb_inplace_true_divide */
1756                 NULL,                           /* nb_index */
1757 };
1758
1759 static PyObject *Matrix_getRowSize(MatrixObject *self, void *UNUSED(closure))
1760 {
1761         return PyLong_FromLong((long) self->row_size);
1762 }
1763
1764 static PyObject *Matrix_getColSize(MatrixObject *self, void *UNUSED(closure))
1765 {
1766         return PyLong_FromLong((long) self->col_size);
1767 }
1768
1769 static PyObject *Matrix_median_scale_get(MatrixObject *self, void *UNUSED(closure))
1770 {
1771         float mat[3][3];
1772
1773         if (BaseMath_ReadCallback(self) == -1)
1774                 return NULL;
1775
1776         /*must be 3-4 cols, 3-4 rows, square matrix*/
1777         if ((self->col_size < 3) || (self->row_size < 3)) {
1778                 PyErr_SetString(PyExc_AttributeError,
1779                                 "Matrix.median_scale: "
1780                                 "inappropriate matrix size, 3x3 minimum");
1781                 return NULL;
1782         }
1783
1784         matrix_as_3x3(mat, self);
1785
1786         return PyFloat_FromDouble(mat3_to_scale(mat));
1787 }
1788
1789 static PyObject *Matrix_is_negative_get(MatrixObject *self, void *UNUSED(closure))
1790 {
1791         if (BaseMath_ReadCallback(self) == -1)
1792                 return NULL;
1793
1794         /*must be 3-4 cols, 3-4 rows, square matrix*/
1795         if (self->col_size == 4 && self->row_size == 4)
1796                 return PyBool_FromLong(is_negative_m4((float (*)[4])self->contigPtr));
1797         else if (self->col_size == 3 && self->row_size == 3)
1798                 return PyBool_FromLong(is_negative_m3((float (*)[3])self->contigPtr));
1799         else {
1800                 PyErr_SetString(PyExc_AttributeError,
1801                                 "Matrix.is_negative: "
1802                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1803                 return NULL;
1804         }
1805 }
1806
1807 static PyObject *Matrix_is_orthogonal_get(MatrixObject *self, void *UNUSED(closure))
1808 {
1809         if (BaseMath_ReadCallback(self) == -1)
1810                 return NULL;
1811
1812         /*must be 3-4 cols, 3-4 rows, square matrix*/
1813         if (self->col_size == 4 && self->row_size == 4)
1814                 return PyBool_FromLong(is_orthogonal_m4((float (*)[4])self->contigPtr));
1815         else if (self->col_size == 3 && self->row_size == 3)
1816                 return PyBool_FromLong(is_orthogonal_m3((float (*)[3])self->contigPtr));
1817         else {
1818                 PyErr_SetString(PyExc_AttributeError,
1819                                 "Matrix.is_orthogonal: "
1820                                 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1821                 return NULL;
1822         }
1823 }
1824
1825 /*****************************************************************************/
1826 /* Python attributes get/set structure:                                      */
1827 /*****************************************************************************/
1828 static PyGetSetDef Matrix_getseters[] = {
1829         {(char *)"row_size", (getter)Matrix_getRowSize, (setter)NULL, (char *)"The row size of the matrix (readonly).\n\n:type: int", NULL},
1830         {(char *)"col_size", (getter)Matrix_getColSize, (setter)NULL, (char *)"The column size of the matrix (readonly).\n\n:type: int", NULL},
1831         {(char *)"median_scale", (getter)Matrix_median_scale_get, (setter)NULL, (char *)"The average scale applied to each axis (readonly).\n\n:type: float", NULL},
1832         {(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},
1833         {(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},
1834         {(char *)"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, (char *)BaseMathObject_Wrapped_doc, NULL},
1835         {(char *)"owner",(getter)BaseMathObject_getOwner, (setter)NULL, (char *)BaseMathObject_Owner_doc, NULL},
1836         {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
1837 };
1838
1839 /*-----------------------METHOD DEFINITIONS ----------------------*/
1840 static struct PyMethodDef Matrix_methods[] = {
1841         /* derived values */
1842         {"determinant", (PyCFunction) Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
1843         {"decompose", (PyCFunction) Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
1844
1845         /* in place only */
1846         {"zero", (PyCFunction) Matrix_zero, METH_NOARGS, Matrix_zero_doc},
1847         {"identity", (PyCFunction) Matrix_identity, METH_NOARGS, Matrix_identity_doc},
1848
1849         /* operate on original or copy */
1850         {"transpose", (PyCFunction) Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
1851         {"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
1852         {"invert", (PyCFunction) Matrix_invert, METH_NOARGS, Matrix_invert_doc},
1853         {"inverted", (PyCFunction) Matrix_inverted, METH_NOARGS, Matrix_inverted_doc},
1854         {"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
1855         // TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc},
1856         {"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
1857         {"resize_4x4", (PyCFunction) Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
1858         {"rotate", (PyCFunction) Matrix_rotate, METH_O, Matrix_rotate_doc},
1859
1860         /* return converted representation */
1861         {"to_euler", (PyCFunction) Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
1862         {"to_quaternion", (PyCFunction) Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
1863         {"to_scale", (PyCFunction) Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
1864         {"to_translation", (PyCFunction) Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
1865
1866         /* operation between 2 or more types  */
1867         {"lerp", (PyCFunction) Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
1868         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1869         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1870
1871         /* class methods */
1872         {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
1873         {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
1874         {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
1875         {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
1876         {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection,  METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
1877         {NULL, NULL, 0, NULL}
1878 };
1879
1880 /*------------------PY_OBECT DEFINITION--------------------------*/
1881 PyDoc_STRVAR(matrix_doc,
1882 "This object gives access to Matrices in Blender."
1883 );
1884 PyTypeObject matrix_Type = {
1885         PyVarObject_HEAD_INIT(NULL, 0)
1886         "mathutils.Matrix",                                     /*tp_name*/
1887         sizeof(MatrixObject),                           /*tp_basicsize*/
1888         0,                                                                      /*tp_itemsize*/
1889         (destructor)BaseMathObject_dealloc,     /*tp_dealloc*/
1890         NULL,                                                           /*tp_print*/
1891         NULL,                                                           /*tp_getattr*/
1892         NULL,                                                           /*tp_setattr*/
1893         NULL,                                                           /*tp_compare*/
1894         (reprfunc) Matrix_repr,                         /*tp_repr*/
1895         &Matrix_NumMethods,                                     /*tp_as_number*/
1896         &Matrix_SeqMethods,                                     /*tp_as_sequence*/
1897         &Matrix_AsMapping,                                      /*tp_as_mapping*/
1898         NULL,                                                           /*tp_hash*/
1899         NULL,                                                           /*tp_call*/
1900         NULL,                                                           /*tp_str*/
1901         NULL,                                                           /*tp_getattro*/
1902         NULL,                                                           /*tp_setattro*/
1903         NULL,                                                           /*tp_as_buffer*/
1904         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
1905         matrix_doc,                                                     /*tp_doc*/
1906         (traverseproc)BaseMathObject_traverse,  //tp_traverse
1907         (inquiry)BaseMathObject_clear,  //tp_clear
1908         (richcmpfunc)Matrix_richcmpr,           /*tp_richcompare*/
1909         0,                                                                      /*tp_weaklistoffset*/
1910         NULL,                                                           /*tp_iter*/
1911         NULL,                                                           /*tp_iternext*/
1912         Matrix_methods,                                         /*tp_methods*/
1913         NULL,                                                           /*tp_members*/
1914         Matrix_getseters,                                       /*tp_getset*/
1915         NULL,                                                           /*tp_base*/
1916         NULL,                                                           /*tp_dict*/
1917         NULL,                                                           /*tp_descr_get*/
1918         NULL,                                                           /*tp_descr_set*/
1919         0,                                                                      /*tp_dictoffset*/
1920         NULL,                                                           /*tp_init*/
1921         NULL,                                                           /*tp_alloc*/
1922         Matrix_new,                                                     /*tp_new*/
1923         NULL,                                                           /*tp_free*/
1924         NULL,                                                           /*tp_is_gc*/
1925         NULL,                                                           /*tp_bases*/
1926         NULL,                                                           /*tp_mro*/
1927         NULL,                                                           /*tp_cache*/
1928         NULL,                                                           /*tp_subclasses*/
1929         NULL,                                                           /*tp_weaklist*/
1930         NULL                                                            /*tp_del*/
1931 };
1932
1933 /*------------------------newMatrixObject (internal)-------------
1934 creates a new matrix object
1935 self->matrix     self->contiguous_ptr (reference to data.xxx)
1936            [0]------------->[0]
1937                                                 [1]
1938                                                 [2]
1939            [1]------------->[3]
1940                                                 [4]
1941                                                 [5]
1942
1943 self->matrix[1][1] = self->contigPtr[4] */
1944
1945 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1946  (i.e. it was allocated elsewhere by MEM_mallocN())
1947   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1948  (i.e. it must be created here with PyMEM_malloc())*/
1949 PyObject *newMatrixObject(float *mat, const unsigned short rowSize, const unsigned short colSize, int type, PyTypeObject *base_type)
1950 {
1951         MatrixObject *self;
1952         int x, row, col;
1953
1954         /*matrix objects can be any 2-4row x 2-4col matrix*/
1955         if (rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4) {
1956                 PyErr_SetString(PyExc_RuntimeError,
1957                                 "Matrix(): "
1958                                 "row and column sizes must be between 2 and 4");
1959                 return NULL;
1960         }
1961
1962         self= base_type ?       (MatrixObject *)base_type->tp_alloc(base_type, 0) :
1963                                                 (MatrixObject *)PyObject_GC_New(MatrixObject, &matrix_Type);
1964
1965         if (self) {
1966                 self->row_size = rowSize;
1967                 self->col_size = colSize;
1968
1969                 /* init callbacks as NULL */
1970                 self->cb_user= NULL;
1971                 self->cb_type= self->cb_subtype= 0;
1972
1973                 if (type == Py_WRAP) {
1974                         self->contigPtr = mat;
1975                         /*pointer array points to contigous memory*/
1976                         for (x = 0; x < rowSize; x++) {
1977                                 self->matrix[x] = self->contigPtr + (x * colSize);
1978                         }
1979                         self->wrapped = Py_WRAP;
1980                 }
1981                 else if (type == Py_NEW) {
1982                         self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1983                         if (self->contigPtr == NULL) { /*allocation failure*/
1984                                 PyErr_SetString(PyExc_MemoryError,
1985                                                 "Matrix(): "
1986                                                 "problem allocating pointer space");
1987                                 return NULL;
1988                         }
1989                         /*pointer array points to contigous memory*/
1990                         for (x = 0; x < rowSize; x++) {
1991                                 self->matrix[x] = self->contigPtr + (x * colSize);
1992                         }
1993                         /*parse*/
1994                         if (mat) {      /*if a float array passed*/
1995                                 for (row = 0; row < rowSize; row++) {
1996                                         for (col = 0; col < colSize; col++) {
1997                                                 self->matrix[row][col] = mat[(row * colSize) + col];
1998                                         }
1999                                 }
2000                         }
2001                         else if (rowSize == colSize) { /*or if no arguments are passed return identity matrix for square matrices */
2002                                 PyObject *ret_dummy= Matrix_identity(self);
2003                                 Py_DECREF(ret_dummy);
2004                         }
2005                         self->wrapped = Py_NEW;
2006                 }
2007                 else {
2008                         Py_FatalError("Matrix(): invalid type!");
2009                         return NULL;
2010                 }
2011         }
2012         return (PyObject *) self;
2013 }
2014
2015 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
2016 {
2017         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW, NULL);
2018         if (self) {
2019                 Py_INCREF(cb_user);
2020                 self->cb_user=                  cb_user;
2021                 self->cb_type=                  (unsigned char)cb_type;
2022                 self->cb_subtype=               (unsigned char)cb_subtype;
2023                 PyObject_GC_Track(self);
2024         }
2025         return (PyObject *) self;
2026 }