Merge from 2.5 r20991 through r21037
[blender.git] / source / blender / python / generic / matrix.c
1 /*
2  * $Id: matrix.c 20249 2009-05-18 04:27:48Z campbellbarton $
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Michel Selten & Joseph Gilbert
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include "Mathutils.h"
29
30 #include "BKE_utildefines.h"
31 #include "BLI_arithb.h"
32 #include "BLI_blenlib.h"
33
34 /*-------------------------DOC STRINGS ---------------------------*/
35 static char Matrix_Zero_doc[] = "() - set all values in the matrix to 0";
36 static char Matrix_Identity_doc[] = "() - set the square matrix to it's identity matrix";
37 static char Matrix_Transpose_doc[] = "() - set the matrix to it's transpose";
38 static char Matrix_Determinant_doc[] = "() - return the determinant of the matrix";
39 static char Matrix_Invert_doc[] =  "() - set the matrix to it's inverse if an inverse is possible";
40 static char Matrix_TranslationPart_doc[] = "() - return a vector encompassing the translation of the matrix";
41 static char Matrix_RotationPart_doc[] = "() - return a vector encompassing the rotation of the matrix";
42 static char Matrix_scalePart_doc[] = "() - convert matrix to a 3D vector";
43 static char Matrix_Resize4x4_doc[] = "() - resize the matrix to a 4x4 square matrix";
44 static char Matrix_toEuler_doc[] = "(eul_compat) - convert matrix to a euler angle rotation, optional euler argument that the new euler will be made compatible with.";
45 static char Matrix_toQuat_doc[] = "() - convert matrix to a quaternion rotation";
46 static char Matrix_copy_doc[] = "() - return a copy of the matrix";
47
48 static PyObject *Matrix_Zero( MatrixObject * self );
49 static PyObject *Matrix_Identity( MatrixObject * self );
50 static PyObject *Matrix_Transpose( MatrixObject * self );
51 static PyObject *Matrix_Determinant( MatrixObject * self );
52 static PyObject *Matrix_Invert( MatrixObject * self );
53 static PyObject *Matrix_TranslationPart( MatrixObject * self );
54 static PyObject *Matrix_RotationPart( MatrixObject * self );
55 static PyObject *Matrix_scalePart( MatrixObject * self );
56 static PyObject *Matrix_Resize4x4( MatrixObject * self );
57 static PyObject *Matrix_toEuler( MatrixObject * self, PyObject *args );
58 static PyObject *Matrix_toQuat( MatrixObject * self );
59 static PyObject *Matrix_copy( MatrixObject * self );
60
61 /*-----------------------METHOD DEFINITIONS ----------------------*/
62 static struct PyMethodDef Matrix_methods[] = {
63         {"zero", (PyCFunction) Matrix_Zero, METH_NOARGS, Matrix_Zero_doc},
64         {"identity", (PyCFunction) Matrix_Identity, METH_NOARGS, Matrix_Identity_doc},
65         {"transpose", (PyCFunction) Matrix_Transpose, METH_NOARGS, Matrix_Transpose_doc},
66         {"determinant", (PyCFunction) Matrix_Determinant, METH_NOARGS, Matrix_Determinant_doc},
67         {"invert", (PyCFunction) Matrix_Invert, METH_NOARGS, Matrix_Invert_doc},
68         {"translationPart", (PyCFunction) Matrix_TranslationPart, METH_NOARGS, Matrix_TranslationPart_doc},
69         {"rotationPart", (PyCFunction) Matrix_RotationPart, METH_NOARGS, Matrix_RotationPart_doc},
70         {"scalePart", (PyCFunction) Matrix_scalePart, METH_NOARGS, Matrix_scalePart_doc},
71         {"resize4x4", (PyCFunction) Matrix_Resize4x4, METH_NOARGS, Matrix_Resize4x4_doc},
72         {"toEuler", (PyCFunction) Matrix_toEuler, METH_VARARGS, Matrix_toEuler_doc},
73         {"toQuat", (PyCFunction) Matrix_toQuat, METH_NOARGS, Matrix_toQuat_doc},
74         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
75         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
76         {NULL, NULL, 0, NULL}
77 };
78
79 //----------------------------------Mathutils.Matrix() -----------------
80 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
81 //create a new matrix type
82 static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
83 {
84         PyObject *argObject, *m, *s;
85         MatrixObject *mat;
86         int argSize, seqSize = 0, i, j;
87         float matrix[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
88                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
89         float scalar;
90
91         argSize = PyTuple_GET_SIZE(args);
92         if(argSize > 4){        //bad arg nums
93                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
94                 return NULL;
95         } else if (argSize == 0) { //return empty 4D matrix
96                 return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW);
97         }else if (argSize == 1){
98                 //copy constructor for matrix objects
99                 argObject = PyTuple_GET_ITEM(args, 0);
100                 if(MatrixObject_Check(argObject)){
101                         mat = (MatrixObject*)argObject;
102
103                         argSize = mat->rowSize; //rows
104                         seqSize = mat->colSize; //col
105                         for(i = 0; i < (seqSize * argSize); i++){
106                                 matrix[i] = mat->contigPtr[i];
107                         }
108                 }
109         }else{ //2-4 arguments (all seqs? all same size?)
110                 for(i =0; i < argSize; i++){
111                         argObject = PyTuple_GET_ITEM(args, i);
112                         if (PySequence_Check(argObject)) { //seq?
113                                 if(seqSize){ //0 at first
114                                         if(PySequence_Length(argObject) != seqSize){ //seq size not same
115                                                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
116                                                 return NULL;
117                                         }
118                                 }
119                                 seqSize = PySequence_Length(argObject);
120                         }else{ //arg not a sequence
121                                 PyErr_SetString(PyExc_TypeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
122                                 return NULL;
123                         }
124                 }
125                 //all is well... let's continue parsing
126                 for (i = 0; i < argSize; i++){
127                         m = PyTuple_GET_ITEM(args, i);
128                         if (m == NULL) { // Failed to read sequence
129                                 PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
130                                 return NULL;
131                         }
132
133                         for (j = 0; j < seqSize; j++) {
134                                 s = PySequence_GetItem(m, j);
135                                 if (s == NULL) { // Failed to read sequence
136                                         PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
137                                         return NULL;
138                                 }
139                                 
140                                 scalar= (float)PyFloat_AsDouble(s);
141                                 Py_DECREF(s);
142                                 
143                                 if(scalar==-1 && PyErr_Occurred()) { // parsed item is not a number
144                                         PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
145                                         return NULL;
146                                 }
147
148                                 matrix[(seqSize*i)+j]= scalar;
149                         }
150                 }
151         }
152         return newMatrixObject(matrix, argSize, seqSize, Py_NEW);
153 }
154
155 /*-----------------------------METHODS----------------------------*/
156 /*---------------------------Matrix.toQuat() ---------------------*/
157 static PyObject *Matrix_toQuat(MatrixObject * self)
158 {
159         float quat[4];
160
161         /*must be 3-4 cols, 3-4 rows, square matrix*/
162         if(self->colSize < 3 || self->rowSize < 3 || (self->colSize != self->rowSize)) {
163                 PyErr_SetString(PyExc_AttributeError, "Matrix.toQuat(): inappropriate matrix size - expects 3x3 or 4x4 matrix");
164                 return NULL;
165         } 
166         if(self->colSize == 3){
167         Mat3ToQuat((float (*)[3])*self->matrix, quat);
168         }else{
169                 Mat4ToQuat((float (*)[4])*self->matrix, quat);
170         }
171         
172         return newQuaternionObject(quat, Py_NEW);
173 }
174 /*---------------------------Matrix.toEuler() --------------------*/
175 PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
176 {
177         float eul[3], eul_compatf[3];
178         EulerObject *eul_compat = NULL;
179         int x;
180         
181         if(!PyArg_ParseTuple(args, "|O!:toEuler", &euler_Type, &eul_compat))
182                 return NULL;
183         
184         if(eul_compat) {
185                 for(x = 0; x < 3; x++) {
186                         eul_compatf[x] = eul_compat->eul[x] * ((float)Py_PI / 180);
187                 }
188         }
189         
190         /*must be 3-4 cols, 3-4 rows, square matrix*/
191         if(self->colSize ==3 && self->rowSize ==3) {
192                 if(eul_compat)  Mat3ToCompatibleEul((float (*)[3])*self->matrix, eul, eul_compatf);
193                 else                    Mat3ToEul((float (*)[3])*self->matrix, eul);
194         }else if (self->colSize ==4 && self->rowSize ==4) {
195                 float tempmat3[3][3];
196                 Mat3CpyMat4(tempmat3, (float (*)[4])*self->matrix);
197                 Mat3ToEul(tempmat3, eul);
198                 if(eul_compat)  Mat3ToCompatibleEul(tempmat3, eul, eul_compatf);
199                 else                    Mat3ToEul(tempmat3, eul);
200                 
201         }else {
202                 PyErr_SetString(PyExc_AttributeError, "Matrix.toEuler(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
203                 return NULL;
204         }
205         /*have to convert to degrees*/
206         for(x = 0; x < 3; x++) {
207                 eul[x] *= (float) (180 / Py_PI);
208         }
209         return newEulerObject(eul, Py_NEW);
210 }
211 /*---------------------------Matrix.resize4x4() ------------------*/
212 PyObject *Matrix_Resize4x4(MatrixObject * self)
213 {
214         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
215
216         if(self->data.blend_data){
217                 PyErr_SetString(PyExc_TypeError, "cannot resize wrapped data - only python matrices");
218                 return NULL;
219         }
220
221         self->data.py_data = PyMem_Realloc(self->data.py_data, (sizeof(float) * 16));
222         if(self->data.py_data == NULL) {
223                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
224                 return NULL;
225         }
226         self->contigPtr = self->data.py_data;  /*force*/
227         self->matrix = PyMem_Realloc(self->matrix, (sizeof(float *) * 4));
228         if(self->matrix == NULL) {
229                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
230                 return NULL;
231         }
232         /*set row pointers*/
233         for(x = 0; x < 4; x++) {
234                 self->matrix[x] = self->contigPtr + (x * 4);
235         }
236         /*move data to new spot in array + clean*/
237         for(blank_rows = (4 - self->rowSize); blank_rows > 0; blank_rows--){
238                 for(x = 0; x < 4; x++){
239                         index = (4 * (self->rowSize + (blank_rows - 1))) + x;
240                         if (index == 10 || index == 15){
241                                 self->contigPtr[index] = 1.0f;
242                         }else{
243                                 self->contigPtr[index] = 0.0f;
244                         }
245                 }
246         }
247         for(x = 1; x <= self->rowSize; x++){
248                 first_row_elem = (self->colSize * (self->rowSize - x));
249                 curr_pos = (first_row_elem + (self->colSize -1));
250                 new_pos = (4 * (self->rowSize - x )) + (curr_pos - first_row_elem);
251                 for(blank_columns = (4 - self->colSize); blank_columns > 0; blank_columns--){
252                         self->contigPtr[new_pos + blank_columns] = 0.0f;
253                 }
254                 for(curr_pos = curr_pos; curr_pos >= first_row_elem; curr_pos--){
255                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
256                         new_pos--;
257                 }
258         }
259         self->rowSize = 4;
260         self->colSize = 4;
261         
262         Py_INCREF(self);
263         return (PyObject *)self;
264 }
265 /*---------------------------Matrix.translationPart() ------------*/
266 PyObject *Matrix_TranslationPart(MatrixObject * self)
267 {
268         float vec[4];
269
270         if(self->colSize < 3 || self->rowSize < 4){
271                 PyErr_SetString(PyExc_AttributeError, "Matrix.translationPart: inappropriate matrix size");
272                 return NULL;
273         }
274
275         vec[0] = self->matrix[3][0];
276         vec[1] = self->matrix[3][1];
277         vec[2] = self->matrix[3][2];
278
279         return newVectorObject(vec, 3, Py_NEW);
280 }
281 /*---------------------------Matrix.rotationPart() ---------------*/
282 PyObject *Matrix_RotationPart(MatrixObject * self)
283 {
284         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
285                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
286
287         if(self->colSize < 3 || self->rowSize < 3){
288                 PyErr_SetString(PyExc_AttributeError, "Matrix.rotationPart: inappropriate matrix size\n");
289                 return NULL;
290         }
291
292         mat[0] = self->matrix[0][0];
293         mat[1] = self->matrix[0][1];
294         mat[2] = self->matrix[0][2];
295         mat[3] = self->matrix[1][0];
296         mat[4] = self->matrix[1][1];
297         mat[5] = self->matrix[1][2];
298         mat[6] = self->matrix[2][0];
299         mat[7] = self->matrix[2][1];
300         mat[8] = self->matrix[2][2];
301
302         return newMatrixObject(mat, 3, 3, Py_NEW);
303 }
304 /*---------------------------Matrix.scalePart() --------------------*/
305 PyObject *Matrix_scalePart(MatrixObject * self)
306 {
307         float scale[3], rot[3];
308         float mat[3][3], imat[3][3], tmat[3][3];
309
310         /*must be 3-4 cols, 3-4 rows, square matrix*/
311         if(self->colSize == 4 && self->rowSize == 4)
312                 Mat3CpyMat4(mat, (float (*)[4])*self->matrix);
313         else if(self->colSize == 3 && self->rowSize == 3)
314                 Mat3CpyMat3(mat, (float (*)[3])*self->matrix);
315         else {
316                 PyErr_SetString(PyExc_AttributeError, "Matrix.scalePart(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
317                 return NULL;
318         }
319         /* functionality copied from editobject.c apply_obmat */
320         Mat3ToEul(mat, rot);
321         EulToMat3(rot, tmat);
322         Mat3Inv(imat, tmat);
323         Mat3MulMat3(tmat, imat, mat);
324         
325         scale[0]= tmat[0][0];
326         scale[1]= tmat[1][1];
327         scale[2]= tmat[2][2];
328         return newVectorObject(scale, 3, Py_NEW);
329 }
330 /*---------------------------Matrix.invert() ---------------------*/
331 PyObject *Matrix_Invert(MatrixObject * self)
332 {
333         
334         int x, y, z = 0;
335         float det = 0.0f;
336         PyObject *f = NULL;
337         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
338                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
339
340         if(self->rowSize != self->colSize){
341                 PyErr_SetString(PyExc_AttributeError, "Matrix.invert(ed): only square matrices are supported");
342                 return NULL;
343         }
344
345         /*calculate the determinant*/
346         f = Matrix_Determinant(self);
347         det = (float)PyFloat_AS_DOUBLE(f); /*Increfs, so we need to decref*/
348         Py_DECREF(f);
349
350         if(det != 0) {
351                 /*calculate the classical adjoint*/
352                 if(self->rowSize == 2) {
353                         mat[0] = self->matrix[1][1];
354                         mat[1] = -self->matrix[0][1];
355                         mat[2] = -self->matrix[1][0];
356                         mat[3] = self->matrix[0][0];
357                 } else if(self->rowSize == 3) {
358                         Mat3Adj((float (*)[3]) mat,(float (*)[3]) *self->matrix);
359                 } else if(self->rowSize == 4) {
360                         Mat4Adj((float (*)[4]) mat, (float (*)[4]) *self->matrix);
361                 }
362                 /*divide by determinate*/
363                 for(x = 0; x < (self->rowSize * self->colSize); x++) {
364                         mat[x] /= det;
365                 }
366                 /*set values*/
367                 for(x = 0; x < self->rowSize; x++) {
368                         for(y = 0; y < self->colSize; y++) {
369                                 self->matrix[x][y] = mat[z];
370                                 z++;
371                         }
372                 }
373                 /*transpose
374                 Matrix_Transpose(self);*/
375         } else {
376                 PyErr_SetString(PyExc_ValueError, "matrix does not have an inverse");
377                 return NULL;
378         }
379         
380         Py_INCREF(self);
381         return (PyObject *)self;
382 }
383
384
385 /*---------------------------Matrix.determinant() ----------------*/
386 PyObject *Matrix_Determinant(MatrixObject * self)
387 {
388         float det = 0.0f;
389
390         if(self->rowSize != self->colSize){
391                 PyErr_SetString(PyExc_AttributeError, "Matrix.determinant: only square matrices are supported");
392                 return NULL;
393         }
394
395         if(self->rowSize == 2) {
396                 det = Det2x2(self->matrix[0][0], self->matrix[0][1],
397                                          self->matrix[1][0], self->matrix[1][1]);
398         } else if(self->rowSize == 3) {
399                 det = Det3x3(self->matrix[0][0], self->matrix[0][1],
400                                          self->matrix[0][2], self->matrix[1][0],
401                                          self->matrix[1][1], self->matrix[1][2],
402                                          self->matrix[2][0], self->matrix[2][1],
403                                          self->matrix[2][2]);
404         } else {
405                 det = Det4x4((float (*)[4]) *self->matrix);
406         }
407
408         return PyFloat_FromDouble( (double) det );
409 }
410 /*---------------------------Matrix.transpose() ------------------*/
411 PyObject *Matrix_Transpose(MatrixObject * self)
412 {
413         float t = 0.0f;
414
415         if(self->rowSize != self->colSize){
416                 PyErr_SetString(PyExc_AttributeError, "Matrix.transpose(d): only square matrices are supported");
417                 return NULL;
418         }
419
420         if(self->rowSize == 2) {
421                 t = self->matrix[1][0];
422                 self->matrix[1][0] = self->matrix[0][1];
423                 self->matrix[0][1] = t;
424         } else if(self->rowSize == 3) {
425                 Mat3Transp((float (*)[3])*self->matrix);
426         } else {
427                 Mat4Transp((float (*)[4])*self->matrix);
428         }
429
430         Py_INCREF(self);
431         return (PyObject *)self;
432 }
433
434
435 /*---------------------------Matrix.zero() -----------------------*/
436 PyObject *Matrix_Zero(MatrixObject * self)
437 {
438         int row, col;
439
440         for(row = 0; row < self->rowSize; row++) {
441                 for(col = 0; col < self->colSize; col++) {
442                         self->matrix[row][col] = 0.0f;
443                 }
444         }
445         Py_INCREF(self);
446         return (PyObject *)self;
447 }
448 /*---------------------------Matrix.identity(() ------------------*/
449 PyObject *Matrix_Identity(MatrixObject * self)
450 {
451         if(self->rowSize != self->colSize){
452                 PyErr_SetString(PyExc_AttributeError, "Matrix.identity: only square matrices are supported\n");
453                 return NULL;
454         }
455
456         if(self->rowSize == 2) {
457                 self->matrix[0][0] = 1.0f;
458                 self->matrix[0][1] = 0.0f;
459                 self->matrix[1][0] = 0.0f;
460                 self->matrix[1][1] = 1.0f;
461         } else if(self->rowSize == 3) {
462                 Mat3One((float (*)[3]) *self->matrix);
463         } else {
464                 Mat4One((float (*)[4]) *self->matrix);
465         }
466
467         Py_INCREF(self);
468         return (PyObject *)self;
469 }
470
471 /*---------------------------Matrix.inverted() ------------------*/
472 PyObject *Matrix_copy(MatrixObject * self)
473 {
474         return (PyObject*)(MatrixObject*)newMatrixObject((float (*))*self->matrix, self->rowSize, self->colSize, Py_NEW);
475 }
476
477 /*----------------------------dealloc()(internal) ----------------*/
478 /*free the py_object*/
479 static void Matrix_dealloc(MatrixObject * self)
480 {
481         PyMem_Free(self->matrix);
482         /*only free py_data*/
483         if(self->data.py_data){
484                 PyMem_Free(self->data.py_data);
485         }
486         PyObject_DEL(self);
487 }
488
489 /*----------------------------print object (internal)-------------*/
490 /*print the object to screen*/
491 static PyObject *Matrix_repr(MatrixObject * self)
492 {
493         int x, y;
494         char buffer[48], str[1024];
495
496         BLI_strncpy(str,"",1024);
497         for(x = 0; x < self->rowSize; x++){
498                 sprintf(buffer, "[");
499                 strcat(str,buffer);
500                 for(y = 0; y < (self->colSize - 1); y++) {
501                         sprintf(buffer, "%.6f, ", self->matrix[x][y]);
502                         strcat(str,buffer);
503                 }
504                 if(x < (self->rowSize-1)){
505                         sprintf(buffer, "%.6f](matrix [row %d])\n", self->matrix[x][y], x);
506                         strcat(str,buffer);
507                 }else{
508                         sprintf(buffer, "%.6f](matrix [row %d])", self->matrix[x][y], x);
509                         strcat(str,buffer);
510                 }
511         }
512
513         return PyUnicode_FromString(str);
514 }
515 /*------------------------tp_richcmpr*/
516 /*returns -1 execption, 0 false, 1 true*/
517 static PyObject* Matrix_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
518 {
519         MatrixObject *matA = NULL, *matB = NULL;
520         int result = 0;
521
522         if (!MatrixObject_Check(objectA) || !MatrixObject_Check(objectB)){
523                 if (comparison_type == Py_NE){
524                         Py_RETURN_TRUE;
525                 }else{
526                         Py_RETURN_FALSE;
527                 }
528         }
529         matA = (MatrixObject*)objectA;
530         matB = (MatrixObject*)objectB;
531
532         if (matA->colSize != matB->colSize || matA->rowSize != matB->rowSize){
533                 if (comparison_type == Py_NE){
534                         Py_RETURN_TRUE;
535                 }else{
536                         Py_RETURN_FALSE;
537                 }
538         }
539
540         switch (comparison_type){
541                 case Py_EQ:
542                         /*contigPtr is basically a really long vector*/
543                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
544                                 (matA->rowSize * matA->colSize), 1);
545                         break;
546                 case Py_NE:
547                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
548                                 (matA->rowSize * matA->colSize), 1);
549                         if (result == 0){
550                                 result = 1;
551                         }else{
552                                 result = 0;
553                         }
554                         break;
555                 default:
556                         printf("The result of the comparison could not be evaluated");
557                         break;
558         }
559         if (result == 1){
560                 Py_RETURN_TRUE;
561         }else{
562                 Py_RETURN_FALSE;
563         }
564 }
565 /*------------------------tp_doc*/
566 static char MatrixObject_doc[] = "This is a wrapper for matrix objects.";
567 /*---------------------SEQUENCE PROTOCOLS------------------------
568   ----------------------------len(object)------------------------
569   sequence length*/
570 static int Matrix_len(MatrixObject * self)
571 {
572         return (self->rowSize);
573 }
574 /*----------------------------object[]---------------------------
575   sequence accessor (get)
576   the wrapped vector gives direct access to the matrix data*/
577 static PyObject *Matrix_item(MatrixObject * self, int i)
578 {
579         if(i < 0 || i >= self->rowSize) {
580                 PyErr_SetString(PyExc_IndexError, "matrix[attribute]: array index out of range");
581                 return NULL;
582         }
583         return newVectorObject(self->matrix[i], self->colSize, Py_WRAP);
584 }
585 /*----------------------------object[]-------------------------
586   sequence accessor (set)*/
587 static int Matrix_ass_item(MatrixObject * self, int i, PyObject * ob)
588 {
589         int y, x, size = 0;
590         float vec[4];
591         PyObject *m, *f;
592
593         if(i >= self->rowSize || i < 0){
594                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad row\n");
595                 return -1;
596         }
597
598         if(PySequence_Check(ob)){
599                 size = PySequence_Length(ob);
600                 if(size != self->colSize){
601                         PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad sequence size\n");
602                         return -1;
603                 }
604                 for (x = 0; x < size; x++) {
605                         m = PySequence_GetItem(ob, x);
606                         if (m == NULL) { /*Failed to read sequence*/
607                                 PyErr_SetString(PyExc_RuntimeError, "matrix[attribute] = x: unable to read sequence\n");
608                                 return -1;
609                         }
610
611                         f = PyNumber_Float(m);
612                         if(f == NULL) { /*parsed item not a number*/
613                                 Py_DECREF(m);
614                                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: sequence argument not a number\n");
615                                 return -1;
616                         }
617
618                         vec[x] = (float)PyFloat_AS_DOUBLE(f);
619                         Py_DECREF(m);
620                         Py_DECREF(f);
621                 }
622                 /*parsed well - now set in matrix*/
623                 for(y = 0; y < size; y++){
624                         self->matrix[i][y] = vec[y];
625                 }
626                 return 0;
627         }else{
628                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: expects a sequence of column size\n");
629                 return -1;
630         }
631 }
632 /*----------------------------object[z:y]------------------------
633   sequence slice (get)*/
634 static PyObject *Matrix_slice(MatrixObject * self, int begin, int end)
635 {
636
637         PyObject *list = NULL;
638         int count;
639
640         CLAMP(begin, 0, self->rowSize);
641         CLAMP(end, 0, self->rowSize);
642         begin = MIN2(begin,end);
643
644         list = PyList_New(end - begin);
645         for(count = begin; count < end; count++) {
646                 PyList_SetItem(list, count - begin,
647                                 newVectorObject(self->matrix[count], self->colSize, Py_WRAP));
648         }
649
650         return list;
651 }
652 /*----------------------------object[z:y]------------------------
653   sequence slice (set)*/
654 static int Matrix_ass_slice(MatrixObject * self, int begin, int end,
655                              PyObject * seq)
656 {
657         int i, x, y, size, sub_size = 0;
658         float mat[16], f;
659         PyObject *subseq;
660         PyObject *m;
661
662         CLAMP(begin, 0, self->rowSize);
663         CLAMP(end, 0, self->rowSize);
664         begin = MIN2(begin,end);
665
666         if(PySequence_Check(seq)){
667                 size = PySequence_Length(seq);
668                 if(size != (end - begin)){
669                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
670                         return -1;
671                 }
672                 /*parse sub items*/
673                 for (i = 0; i < size; i++) {
674                         /*parse each sub sequence*/
675                         subseq = PySequence_GetItem(seq, i);
676                         if (subseq == NULL) { /*Failed to read sequence*/
677                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence");
678                                 return -1;
679                         }
680
681                         if(PySequence_Check(subseq)){
682                                 /*subsequence is also a sequence*/
683                                 sub_size = PySequence_Length(subseq);
684                                 if(sub_size != self->colSize){
685                                         Py_DECREF(subseq);
686                                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
687                                         return -1;
688                                 }
689                                 for (y = 0; y < sub_size; y++) {
690                                         m = PySequence_GetItem(subseq, y);
691                                         if (m == NULL) { /*Failed to read sequence*/
692                                                 Py_DECREF(subseq);
693                                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence\n");
694                                                 return -1;
695                                         }
696                                         
697                                         f = PyFloat_AsDouble(m); /* faster to assume a float and raise an error after */
698                                         if(f == -1 && PyErr_Occurred()) { /*parsed item not a number*/
699                                                 Py_DECREF(m);
700                                                 Py_DECREF(subseq);
701                                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: sequence argument not a number\n");
702                                                 return -1;
703                                         }
704
705                                         mat[(i * self->colSize) + y] = f;
706                                         Py_DECREF(m);
707                                 }
708                         }else{
709                                 Py_DECREF(subseq);
710                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
711                                 return -1;
712                         }
713                         Py_DECREF(subseq);
714                 }
715                 /*parsed well - now set in matrix*/
716                 for(x = 0; x < (size * sub_size); x++){
717                         self->matrix[begin + (int)floor(x / self->colSize)][x % self->colSize] = mat[x];
718                 }
719                 return 0;
720         }else{
721                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
722                 return -1;
723         }
724 }
725 /*------------------------NUMERIC PROTOCOLS----------------------
726   ------------------------obj + obj------------------------------*/
727 static PyObject *Matrix_add(PyObject * m1, PyObject * m2)
728 {
729         int x, y;
730         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
731                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
732         MatrixObject *mat1 = NULL, *mat2 = NULL;
733
734         mat1 = (MatrixObject*)m1;
735         mat2 = (MatrixObject*)m2;
736
737         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
738                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
739                 return NULL;
740         }
741         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
742                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
743                 return NULL;
744         }
745
746         for(x = 0; x < mat1->rowSize; x++) {
747                 for(y = 0; y < mat1->colSize; y++) {
748                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] + mat2->matrix[x][y];
749                 }
750         }
751
752         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
753 }
754 /*------------------------obj - obj------------------------------
755   subtraction*/
756 static PyObject *Matrix_sub(PyObject * m1, PyObject * m2)
757 {
758         int x, y;
759         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
760                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
761         MatrixObject *mat1 = NULL, *mat2 = NULL;
762
763         mat1 = (MatrixObject*)m1;
764         mat2 = (MatrixObject*)m2;
765
766         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
767                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
768                 return NULL;
769         }
770         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
771                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
772                 return NULL;
773         }
774
775         for(x = 0; x < mat1->rowSize; x++) {
776                 for(y = 0; y < mat1->colSize; y++) {
777                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] - mat2->matrix[x][y];
778                 }
779         }
780
781         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
782 }
783 /*------------------------obj * obj------------------------------
784   mulplication*/
785 static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
786 {
787         int x, y, z;
788         float scalar;
789         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
790                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
791         double dot = 0.0f;
792         MatrixObject *mat1 = NULL, *mat2 = NULL;
793
794         if(MatrixObject_Check(m1))      mat1 = (MatrixObject*)m1;
795         if(MatrixObject_Check(m2))      mat2 = (MatrixObject*)m2;
796
797         if(mat1 && mat2) { /*MATRIX * MATRIX*/
798                 if(mat1->colSize != mat2->rowSize){
799                         PyErr_SetString(PyExc_AttributeError,"Matrix multiplication: matrix A rowsize must equal matrix B colsize");
800                         return NULL;
801                 }
802                 for(x = 0; x < mat1->rowSize; x++) {
803                         for(y = 0; y < mat2->colSize; y++) {
804                                 for(z = 0; z < mat1->colSize; z++) {
805                                         dot += (mat1->matrix[x][z] * mat2->matrix[z][y]);
806                                 }
807                                 mat[((x * mat1->rowSize) + y)] = (float)dot;
808                                 dot = 0.0f;
809                         }
810                 }
811                 
812                 return newMatrixObject(mat, mat1->rowSize, mat2->colSize, Py_NEW);
813         }
814         
815         if(mat1==NULL){
816                 scalar=PyFloat_AsDouble(m1); // may not be a float...
817                 if ((scalar == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX, this line annoys theeth, lets see if he finds it */
818                         for(x = 0; x < mat2->rowSize; x++) {
819                                 for(y = 0; y < mat2->colSize; y++) {
820                                         mat[((x * mat2->colSize) + y)] = scalar * mat2->matrix[x][y];
821                                 }
822                         }
823                         return newMatrixObject(mat, mat2->rowSize, mat2->colSize, Py_NEW);
824                 }
825                 
826                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
827                 return NULL;
828         }
829         else /* if(mat1) { */ {
830                 
831                 if(VectorObject_Check(m2)) { /* MATRIX*VECTOR */
832                         return column_vector_multiplication(mat1, (VectorObject *)m2);
833                 }
834                 else {
835                         scalar= PyFloat_AsDouble(m2);
836                         if ((scalar == -1.0 && PyErr_Occurred())==0) { /* MATRIX*FLOAT/INT */
837                                 for(x = 0; x < mat1->rowSize; x++) {
838                                         for(y = 0; y < mat1->colSize; y++) {
839                                                 mat[((x * mat1->colSize) + y)] = scalar * mat1->matrix[x][y];
840                                         }
841                                 }
842                                 return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
843                         }
844                 }
845                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
846                 return NULL;
847         }
848
849         PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation\n");
850         return NULL;
851 }
852 static PyObject* Matrix_inv(MatrixObject *self)
853 {
854         return Matrix_Invert(self);
855 }
856
857 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
858 static PySequenceMethods Matrix_SeqMethods = {
859         (inquiry) Matrix_len,                                   /* sq_length */
860         (binaryfunc) 0,                                                 /* sq_concat */
861         (ssizeargfunc) 0,                                                       /* sq_repeat */
862         (ssizeargfunc) Matrix_item,                             /* sq_item */
863         (ssizessizeargfunc) Matrix_slice,                       /* sq_slice */
864         (ssizeobjargproc) Matrix_ass_item,              /* sq_ass_item */
865         (ssizessizeobjargproc) Matrix_ass_slice,        /* sq_ass_slice */
866 };
867 static PyNumberMethods Matrix_NumMethods = {
868         (binaryfunc) Matrix_add,                                /* __add__ */
869         (binaryfunc) Matrix_sub,                                /* __sub__ */
870         (binaryfunc) Matrix_mul,                                /* __mul__ */
871         (binaryfunc) 0,                                                 /* __div__ */
872         (binaryfunc) 0,                                                 /* __mod__ */
873         (binaryfunc) 0,                                                 /* __divmod__ */
874         (ternaryfunc) 0,                                                /* __pow__ */
875         (unaryfunc) 0,                                                  /* __neg__ */
876         (unaryfunc) 0,                                                  /* __pos__ */
877         (unaryfunc) 0,                                                  /* __abs__ */
878         (inquiry) 0,                                                    /* __nonzero__ */
879         (unaryfunc) Matrix_inv,                                 /* __invert__ */
880         (binaryfunc) 0,                                                 /* __lshift__ */
881         (binaryfunc) 0,                                                 /* __rshift__ */
882         (binaryfunc) 0,                                                 /* __and__ */
883         (binaryfunc) 0,                                                 /* __xor__ */
884         (binaryfunc) 0,                                                 /* __or__ */
885         /*(coercion)*/ 0,                                                       /* __coerce__ */
886         (unaryfunc) 0,                                                  /* __int__ */
887         (unaryfunc) 0,                                                  /* __long__ */
888         (unaryfunc) 0,                                                  /* __float__ */
889         (unaryfunc) 0,                                                  /* __oct__ */
890         (unaryfunc) 0,                                                  /* __hex__ */
891 };
892
893 static PyObject *Matrix_getRowSize( MatrixObject * self, void *type )
894 {
895         return PyLong_FromLong((long) self->rowSize);
896 }
897
898 static PyObject *Matrix_getColSize( MatrixObject * self, void *type )
899 {
900         return PyLong_FromLong((long) self->colSize);
901 }
902
903 static PyObject *Matrix_getWrapped( MatrixObject * self, void *type )
904 {
905         if (self->wrapped == Py_WRAP)
906                 Py_RETURN_TRUE;
907         else
908                 Py_RETURN_FALSE;
909 }
910
911 /*****************************************************************************/
912 /* Python attributes get/set structure:                                      */
913 /*****************************************************************************/
914 static PyGetSetDef Matrix_getseters[] = {
915         {"rowSize", (getter)Matrix_getRowSize, (setter)NULL, "", NULL},
916         {"colSize", (getter)Matrix_getColSize, (setter)NULL, "", NULL},
917         {"wrapped", (getter)Matrix_getWrapped, (setter)NULL, "", NULL},
918         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
919 };
920
921 /*------------------PY_OBECT DEFINITION--------------------------*/
922 PyTypeObject matrix_Type = {
923 #if (PY_VERSION_HEX >= 0x02060000)
924         PyVarObject_HEAD_INIT(NULL, 0)
925 #else
926         /* python 2.5 and below */
927         PyObject_HEAD_INIT( NULL )  /* required py macro */
928         0,                          /* ob_size */
929 #endif
930         "matrix",                                               /*tp_name*/
931         sizeof(MatrixObject),                   /*tp_basicsize*/
932         0,                                                              /*tp_itemsize*/
933         (destructor)Matrix_dealloc,             /*tp_dealloc*/
934         0,                                                              /*tp_print*/
935         0,                                                              /*tp_getattr*/
936         0,                                                              /*tp_setattr*/
937         0,                                                              /*tp_compare*/
938         (reprfunc) Matrix_repr,                 /*tp_repr*/
939         &Matrix_NumMethods,                             /*tp_as_number*/
940         &Matrix_SeqMethods,                             /*tp_as_sequence*/
941         0,                                                              /*tp_as_mapping*/
942         0,                                                              /*tp_hash*/
943         0,                                                              /*tp_call*/
944         0,                                                              /*tp_str*/
945         0,                                                              /*tp_getattro*/
946         0,                                                              /*tp_setattro*/
947         0,                                                              /*tp_as_buffer*/
948         Py_TPFLAGS_DEFAULT,                             /*tp_flags*/
949         MatrixObject_doc,                               /*tp_doc*/
950         0,                                                              /*tp_traverse*/
951         0,                                                              /*tp_clear*/
952         (richcmpfunc)Matrix_richcmpr,   /*tp_richcompare*/
953         0,                                                              /*tp_weaklistoffset*/
954         0,                                                              /*tp_iter*/
955         0,                                                              /*tp_iternext*/
956         Matrix_methods,                                 /*tp_methods*/
957         0,                                                              /*tp_members*/
958         Matrix_getseters,                               /*tp_getset*/
959         0,                                                              /*tp_base*/
960         0,                                                              /*tp_dict*/
961         0,                                                              /*tp_descr_get*/
962         0,                                                              /*tp_descr_set*/
963         0,                                                              /*tp_dictoffset*/
964         0,                                                              /*tp_init*/
965         0,                                                              /*tp_alloc*/
966         Matrix_new,                                             /*tp_new*/
967         0,                                                              /*tp_free*/
968         0,                                                              /*tp_is_gc*/
969         0,                                                              /*tp_bases*/
970         0,                                                              /*tp_mro*/
971         0,                                                              /*tp_cache*/
972         0,                                                              /*tp_subclasses*/
973         0,                                                              /*tp_weaklist*/
974         0                                                               /*tp_del*/
975 };
976
977 /*------------------------newMatrixObject (internal)-------------
978 creates a new matrix object
979 self->matrix     self->contiguous_ptr (reference to data.xxx)
980        [0]------------->[0]
981                         [1]
982                         [2]
983        [1]------------->[3]
984                         [4]
985                         [5]
986                      ....
987 self->matrix[1][1] = self->contiguous_ptr[4] = self->data.xxx_data[4]*/
988
989 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
990  (i.e. it was allocated elsewhere by MEM_mallocN())
991   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
992  (i.e. it must be created here with PyMEM_malloc())*/
993 PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type)
994 {
995         MatrixObject *self;
996         int x, row, col;
997
998         /*matrix objects can be any 2-4row x 2-4col matrix*/
999         if(rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4){
1000                 PyErr_SetString(PyExc_RuntimeError, "matrix(): row and column sizes must be between 2 and 4");
1001                 return NULL;
1002         }
1003
1004         self = PyObject_NEW(MatrixObject, &matrix_Type);
1005         self->data.blend_data = NULL;
1006         self->data.py_data = NULL;
1007         self->rowSize = rowSize;
1008         self->colSize = colSize;
1009
1010         if(type == Py_WRAP){
1011                 self->data.blend_data = mat;
1012                 self->contigPtr = self->data.blend_data;
1013                 /*create pointer array*/
1014                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1015                 if(self->matrix == NULL) { /*allocation failure*/
1016                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1017                         return NULL;
1018                 }
1019                 /*pointer array points to contigous memory*/
1020                 for(x = 0; x < rowSize; x++) {
1021                         self->matrix[x] = self->contigPtr + (x * colSize);
1022                 }
1023                 self->wrapped = Py_WRAP;
1024         }else if (type == Py_NEW){
1025                 self->data.py_data = PyMem_Malloc(rowSize * colSize * sizeof(float));
1026                 if(self->data.py_data == NULL) { /*allocation failure*/
1027                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space\n");
1028                         return NULL;
1029                 }
1030                 self->contigPtr = self->data.py_data;
1031                 /*create pointer array*/
1032                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1033                 if(self->matrix == NULL) { /*allocation failure*/
1034                         PyMem_Free(self->data.py_data);
1035                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1036                         return NULL;
1037                 }
1038                 /*pointer array points to contigous memory*/
1039                 for(x = 0; x < rowSize; x++) {
1040                         self->matrix[x] = self->contigPtr + (x * colSize);
1041                 }
1042                 /*parse*/
1043                 if(mat) {       /*if a float array passed*/
1044                         for(row = 0; row < rowSize; row++) {
1045                                 for(col = 0; col < colSize; col++) {
1046                                         self->matrix[row][col] = mat[(row * colSize) + col];
1047                                 }
1048                         }
1049                 } else if (rowSize == colSize ) { /*or if no arguments are passed return identity matrix for square matrices */
1050                         Matrix_Identity(self);
1051                         Py_DECREF(self);
1052                 }
1053                 self->wrapped = Py_NEW;
1054         }else{ /*bad type*/
1055                 return NULL;
1056         }
1057         return (PyObject *) self;
1058 }