* Added Main.add_object(type, name)
[blender.git] / source / blender / python / generic / euler.c
1 /*
2  * $Id: euler.c 20248 2009-05-18 04:11:54Z 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  * 
24  * Contributor(s): Joseph Gilbert
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include "Mathutils.h"
30
31 #include "BLI_arithb.h"
32 #include "BKE_utildefines.h"
33 #include "BLI_blenlib.h"
34
35
36 //-------------------------DOC STRINGS ---------------------------
37 char Euler_Zero_doc[] = "() - set all values in the euler to 0";
38 char Euler_Unique_doc[] ="() - sets the euler rotation a unique shortest arc rotation - tests for gimbal lock";
39 char Euler_ToMatrix_doc[] =     "() - returns a rotation matrix representing the euler rotation";
40 char Euler_ToQuat_doc[] = "() - returns a quaternion representing the euler rotation";
41 char Euler_Rotate_doc[] = "() - rotate a euler by certain amount around an axis of rotation";
42 char Euler_copy_doc[] = "() - returns a copy of the euler.";
43 char Euler_MakeCompatible_doc[] = "(euler) - Make this user compatible with another (no axis flipping).";
44 //-----------------------METHOD DEFINITIONS ----------------------
45 struct PyMethodDef Euler_methods[] = {
46         {"zero", (PyCFunction) Euler_Zero, METH_NOARGS, Euler_Zero_doc},
47         {"unique", (PyCFunction) Euler_Unique, METH_NOARGS, Euler_Unique_doc},
48         {"toMatrix", (PyCFunction) Euler_ToMatrix, METH_NOARGS, Euler_ToMatrix_doc},
49         {"toQuat", (PyCFunction) Euler_ToQuat, METH_NOARGS, Euler_ToQuat_doc},
50         {"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, Euler_Rotate_doc},
51         {"makeCompatible", (PyCFunction) Euler_MakeCompatible, METH_O, Euler_MakeCompatible_doc},
52         {"__copy__", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
53         {"copy", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
54         {NULL, NULL, 0, NULL}
55 };
56 //-----------------------------METHODS----------------------------
57 //----------------------------Euler.toQuat()----------------------
58 //return a quaternion representation of the euler
59 PyObject *Euler_ToQuat(EulerObject * self)
60 {
61         float eul[3], quat[4];
62         int x;
63
64         for(x = 0; x < 3; x++) {
65                 eul[x] = self->eul[x] * ((float)Py_PI / 180);
66         }
67         EulToQuat(eul, quat);
68         return newQuaternionObject(quat, Py_NEW);
69 }
70 //----------------------------Euler.toMatrix()---------------------
71 //return a matrix representation of the euler
72 PyObject *Euler_ToMatrix(EulerObject * self)
73 {
74         float eul[3];
75         float mat[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
76         int x;
77
78         for(x = 0; x < 3; x++) {
79                 eul[x] = self->eul[x] * ((float)Py_PI / 180);
80         }
81         EulToMat3(eul, (float (*)[3]) mat);
82         return newMatrixObject(mat, 3, 3 , Py_NEW);
83 }
84 //----------------------------Euler.unique()-----------------------
85 //sets the x,y,z values to a unique euler rotation
86 PyObject *Euler_Unique(EulerObject * self)
87 {
88         double heading, pitch, bank;
89         double pi2 =  Py_PI * 2.0f;
90         double piO2 = Py_PI / 2.0f;
91         double Opi2 = 1.0f / pi2;
92
93         //radians
94         heading = self->eul[0] * (float)Py_PI / 180;
95         pitch = self->eul[1] * (float)Py_PI / 180;
96         bank = self->eul[2] * (float)Py_PI / 180;
97
98         //wrap heading in +180 / -180
99         pitch += Py_PI;
100         pitch -= floor(pitch * Opi2) * pi2;
101         pitch -= Py_PI;
102
103
104         if(pitch < -piO2) {
105                 pitch = -Py_PI - pitch;
106                 heading += Py_PI;
107                 bank += Py_PI;
108         } else if(pitch > piO2) {
109                 pitch = Py_PI - pitch;
110                 heading += Py_PI;
111                 bank += Py_PI;
112         }
113         //gimbal lock test
114         if(fabs(pitch) > piO2 - 1e-4) {
115                 heading += bank;
116                 bank = 0.0f;
117         } else {
118                 bank += Py_PI;
119                 bank -= (floor(bank * Opi2)) * pi2;
120                 bank -= Py_PI;
121         }
122
123         heading += Py_PI;
124         heading -= (floor(heading * Opi2)) * pi2;
125         heading -= Py_PI;
126
127         //back to degrees
128         self->eul[0] = (float)(heading * 180 / (float)Py_PI);
129         self->eul[1] = (float)(pitch * 180 / (float)Py_PI);
130         self->eul[2] = (float)(bank * 180 / (float)Py_PI);
131
132         Py_INCREF(self);
133         return (PyObject *)self;
134 }
135 //----------------------------Euler.zero()-------------------------
136 //sets the euler to 0,0,0
137 PyObject *Euler_Zero(EulerObject * self)
138 {
139         self->eul[0] = 0.0;
140         self->eul[1] = 0.0;
141         self->eul[2] = 0.0;
142
143         Py_INCREF(self);
144         return (PyObject *)self;
145 }
146 //----------------------------Euler.rotate()-----------------------
147 //rotates a euler a certain amount and returns the result
148 //should return a unique euler rotation (i.e. no 720 degree pitches :)
149 PyObject *Euler_Rotate(EulerObject * self, PyObject *args)
150 {
151         float angle = 0.0f;
152         char *axis;
153         int x;
154
155         if(!PyArg_ParseTuple(args, "fs", &angle, &axis)){
156                 PyErr_SetString(PyExc_TypeError, "euler.rotate():expected angle (float) and axis (x,y,z)");
157                 return NULL;
158         }
159         if(!STREQ3(axis,"x","y","z")){
160                 PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'x', 'y' or 'z'");
161                 return NULL;
162         }
163
164         //covert to radians
165         angle *= ((float)Py_PI / 180);
166         for(x = 0; x < 3; x++) {
167                 self->eul[x] *= ((float)Py_PI / 180);
168         }
169         euler_rot(self->eul, angle, *axis);
170         //convert back from radians
171         for(x = 0; x < 3; x++) {
172                 self->eul[x] *= (180 / (float)Py_PI);
173         }
174
175         Py_INCREF(self);
176         return (PyObject *)self;
177 }
178
179 PyObject *Euler_MakeCompatible(EulerObject * self, EulerObject *value)
180 {
181         float eul_from_rad[3];
182         int x;
183         
184         if(!EulerObject_Check(value)) {
185                 PyErr_SetString(PyExc_TypeError, "euler.makeCompatible(euler):expected a single euler argument.");
186                 return NULL;
187         }
188         
189         //covert to radians
190         for(x = 0; x < 3; x++) {
191                 self->eul[x] = self->eul[x] * ((float)Py_PI / 180);
192                 eul_from_rad[x] = value->eul[x] * ((float)Py_PI / 180);
193         }
194         compatible_eul(self->eul, eul_from_rad);
195         //convert back from radians
196         for(x = 0; x < 3; x++) {
197                 self->eul[x] *= (180 / (float)Py_PI);
198         }
199         
200         Py_INCREF(self);
201         return (PyObject *)self;
202 }
203
204 //----------------------------Euler.rotate()-----------------------
205 // return a copy of the euler
206 PyObject *Euler_copy(EulerObject * self, PyObject *args)
207 {
208         return newEulerObject(self->eul, Py_NEW);
209 }
210
211
212 //----------------------------dealloc()(internal) ------------------
213 //free the py_object
214 static void Euler_dealloc(EulerObject * self)
215 {
216         //only free py_data
217         if(self->data.py_data){
218                 PyMem_Free(self->data.py_data);
219         }
220         PyObject_DEL(self);
221 }
222
223 //----------------------------print object (internal)--------------
224 //print the object to screen
225 static PyObject *Euler_repr(EulerObject * self)
226 {
227         char str[64];
228         sprintf(str, "[%.6f, %.6f, %.6f](euler)", self->eul[0], self->eul[1], self->eul[2]);
229         return PyUnicode_FromString(str);
230 }
231 //------------------------tp_richcmpr
232 //returns -1 execption, 0 false, 1 true
233 static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
234 {
235         EulerObject *eulA = NULL, *eulB = NULL;
236         int result = 0;
237
238         if (!EulerObject_Check(objectA) || !EulerObject_Check(objectB)){
239                 if (comparison_type == Py_NE){
240                         Py_RETURN_TRUE;
241                 }else{
242                         Py_RETURN_FALSE;
243                 }
244         }
245         eulA = (EulerObject*)objectA;
246         eulB = (EulerObject*)objectB;
247
248         switch (comparison_type){
249                 case Py_EQ:
250                         result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
251                         break;
252                 case Py_NE:
253                         result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
254                         if (result == 0){
255                                 result = 1;
256                         }else{
257                                 result = 0;
258                         }
259                         break;
260                 default:
261                         printf("The result of the comparison could not be evaluated");
262                         break;
263         }
264         if (result == 1){
265                 Py_RETURN_TRUE;
266         }else{
267                 Py_RETURN_FALSE;
268         }
269 }
270 //------------------------tp_doc
271 static char EulerObject_doc[] = "This is a wrapper for euler objects.";
272 //---------------------SEQUENCE PROTOCOLS------------------------
273 //----------------------------len(object)------------------------
274 //sequence length
275 static int Euler_len(EulerObject * self)
276 {
277         return 3;
278 }
279 //----------------------------object[]---------------------------
280 //sequence accessor (get)
281 static PyObject *Euler_item(EulerObject * self, int i)
282 {
283         if(i<0)
284                 i= 3-i;
285         
286         if(i < 0 || i >= 3) {
287                 PyErr_SetString(PyExc_IndexError, "euler[attribute]: array index out of range");
288                 return NULL;
289         }
290         return PyFloat_FromDouble(self->eul[i]);
291
292 }
293 //----------------------------object[]-------------------------
294 //sequence accessor (set)
295 static int Euler_ass_item(EulerObject * self, int i, PyObject * value)
296 {
297         float f = PyFloat_AsDouble(value);
298
299         if(f == -1 && PyErr_Occurred()) { // parsed item not a number
300                 PyErr_SetString(PyExc_TypeError, "euler[attribute] = x: argument not a number");
301                 return -1;
302         }
303
304         if(i<0)
305                 i= 3-i;
306         
307         if(i < 0 || i >= 3){
308                 PyErr_SetString(PyExc_IndexError, "euler[attribute] = x: array assignment index out of range\n");
309                 return -1;
310         }
311         
312         self->eul[i] = f;
313         return 0;
314 }
315 //----------------------------object[z:y]------------------------
316 //sequence slice (get)
317 static PyObject *Euler_slice(EulerObject * self, int begin, int end)
318 {
319         PyObject *list = NULL;
320         int count;
321
322         CLAMP(begin, 0, 3);
323         if (end<0) end= 4+end;
324         CLAMP(end, 0, 3);
325         begin = MIN2(begin,end);
326
327         list = PyList_New(end - begin);
328         for(count = begin; count < end; count++) {
329                 PyList_SetItem(list, count - begin,
330                                 PyFloat_FromDouble(self->eul[count]));
331         }
332
333         return list;
334 }
335 //----------------------------object[z:y]------------------------
336 //sequence slice (set)
337 static int Euler_ass_slice(EulerObject * self, int begin, int end,
338                              PyObject * seq)
339 {
340         int i, y, size = 0;
341         float eul[3];
342         PyObject *e, *f;
343
344         CLAMP(begin, 0, 3);
345         if (end<0) end= 4+end;
346         CLAMP(end, 0, 3);
347         begin = MIN2(begin,end);
348
349         size = PySequence_Length(seq);
350         if(size != (end - begin)){
351                 PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: size mismatch in slice assignment");
352                 return -1;
353         }
354
355         for (i = 0; i < size; i++) {
356                 e = PySequence_GetItem(seq, i);
357                 if (e == NULL) { // Failed to read sequence
358                         PyErr_SetString(PyExc_RuntimeError, "euler[begin:end] = []: unable to read sequence");
359                         return -1;
360                 }
361
362                 f = PyNumber_Float(e);
363                 if(f == NULL) { // parsed item not a number
364                         Py_DECREF(e);
365                         PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: sequence argument not a number");
366                         return -1;
367                 }
368
369                 eul[i] = (float)PyFloat_AS_DOUBLE(f);
370                 Py_DECREF(f);
371                 Py_DECREF(e);
372         }
373         //parsed well - now set in vector
374         for(y = 0; y < 3; y++){
375                 self->eul[begin + y] = eul[y];
376         }
377         return 0;
378 }
379 //-----------------PROTCOL DECLARATIONS--------------------------
380 static PySequenceMethods Euler_SeqMethods = {
381         (inquiry) Euler_len,                                            /* sq_length */
382         (binaryfunc) 0,                                                         /* sq_concat */
383         (ssizeargfunc) 0,                                                               /* sq_repeat */
384         (ssizeargfunc) Euler_item,                                      /* sq_item */
385         (ssizessizeargfunc) Euler_slice,                                /* sq_slice */
386         (ssizeobjargproc) Euler_ass_item,                               /* sq_ass_item */
387         (ssizessizeobjargproc) Euler_ass_slice,                 /* sq_ass_slice */
388 };
389
390
391
392 /*
393  * vector axis, vector.x/y/z/w
394  */
395         
396 static PyObject *Euler_getAxis( EulerObject * self, void *type )
397 {
398         switch( (long)type ) {
399     case 'X':   /* these are backwards, but that how it works */
400                 return PyFloat_FromDouble(self->eul[0]);
401     case 'Y':
402                 return PyFloat_FromDouble(self->eul[1]);
403     case 'Z':
404                 return PyFloat_FromDouble(self->eul[2]);
405         }
406         
407         PyErr_SetString(PyExc_SystemError, "corrupt euler, cannot get axis");
408         return NULL;
409 }
410
411 static int Euler_setAxis( EulerObject * self, PyObject * value, void * type )
412 {
413         float param= (float)PyFloat_AsDouble( value );
414         
415         if (param==-1 && PyErr_Occurred()) {
416                 PyErr_SetString(PyExc_TypeError, "expected a number for the vector axis");
417                 return -1;
418         }
419         
420         switch( (long)type ) {
421     case 'X':   /* these are backwards, but that how it works */
422                 self->eul[0]= param;
423                 break;
424     case 'Y':
425                 self->eul[1]= param;
426                 break;
427     case 'Z':
428                 self->eul[2]= param;
429                 break;
430         }
431
432         return 0;
433 }
434
435 static PyObject *Euler_getWrapped( VectorObject * self, void *type )
436 {
437         if (self->wrapped == Py_WRAP)
438                 Py_RETURN_TRUE;
439         else
440                 Py_RETURN_FALSE;
441 }
442
443
444 /*****************************************************************************/
445 /* Python attributes get/set structure:                                      */
446 /*****************************************************************************/
447 static PyGetSetDef Euler_getseters[] = {
448         {"x",
449          (getter)Euler_getAxis, (setter)Euler_setAxis,
450          "Euler X axis",
451          (void *)'X'},
452         {"y",
453          (getter)Euler_getAxis, (setter)Euler_setAxis,
454          "Euler Y axis",
455          (void *)'Y'},
456         {"z",
457          (getter)Euler_getAxis, (setter)Euler_setAxis,
458          "Euler Z axis",
459          (void *)'Z'},
460         {"wrapped",
461          (getter)Euler_getWrapped, (setter)NULL,
462          "True when this wraps blenders internal data",
463          NULL},
464         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
465 };
466
467 //------------------PY_OBECT DEFINITION--------------------------
468 PyTypeObject euler_Type = {
469 #if (PY_VERSION_HEX >= 0x02060000)
470         PyVarObject_HEAD_INIT(NULL, 0)
471 #else
472         /* python 2.5 and below */
473         PyObject_HEAD_INIT( NULL )  /* required py macro */
474         0,                          /* ob_size */
475 #endif
476         "euler",                                                //tp_name
477         sizeof(EulerObject),                    //tp_basicsize
478         0,                                                              //tp_itemsize
479         (destructor)Euler_dealloc,              //tp_dealloc
480         0,                                                              //tp_print
481         0,                                                              //tp_getattr
482         0,                                                              //tp_setattr
483         0,                                                              //tp_compare
484         (reprfunc) Euler_repr,                  //tp_repr
485         0,                              //tp_as_number
486         &Euler_SeqMethods,                              //tp_as_sequence
487         0,                                                              //tp_as_mapping
488         0,                                                              //tp_hash
489         0,                                                              //tp_call
490         0,                                                              //tp_str
491         0,                                                              //tp_getattro
492         0,                                                              //tp_setattro
493         0,                                                              //tp_as_buffer
494         Py_TPFLAGS_DEFAULT,                             //tp_flags
495         EulerObject_doc,                                //tp_doc
496         0,                                                              //tp_traverse
497         0,                                                              //tp_clear
498         (richcmpfunc)Euler_richcmpr,    //tp_richcompare
499         0,                                                              //tp_weaklistoffset
500         0,                                                              //tp_iter
501         0,                                                              //tp_iternext
502         Euler_methods,                                  //tp_methods
503         0,                                                              //tp_members
504         Euler_getseters,                                //tp_getset
505         0,                                                              //tp_base
506         0,                                                              //tp_dict
507         0,                                                              //tp_descr_get
508         0,                                                              //tp_descr_set
509         0,                                                              //tp_dictoffset
510         0,                                                              //tp_init
511         0,                                                              //tp_alloc
512         0,                                                              //tp_new
513         0,                                                              //tp_free
514         0,                                                              //tp_is_gc
515         0,                                                              //tp_bases
516         0,                                                              //tp_mro
517         0,                                                              //tp_cache
518         0,                                                              //tp_subclasses
519         0,                                                              //tp_weaklist
520         0                                                               //tp_del
521 };
522 //------------------------newEulerObject (internal)-------------
523 //creates a new euler object
524 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
525  (i.e. it was allocated elsewhere by MEM_mallocN())
526   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
527  (i.e. it must be created here with PyMEM_malloc())*/
528 PyObject *newEulerObject(float *eul, int type)
529 {
530         EulerObject *self;
531         int x;
532
533         self = PyObject_NEW(EulerObject, &euler_Type);
534         self->data.blend_data = NULL;
535         self->data.py_data = NULL;
536
537         if(type == Py_WRAP){
538                 self->data.blend_data = eul;
539                 self->eul = self->data.blend_data;
540                 self->wrapped = Py_WRAP;
541         }else if (type == Py_NEW){
542                 self->data.py_data = PyMem_Malloc(3 * sizeof(float));
543                 self->eul = self->data.py_data;
544                 if(!eul) { //new empty
545                         for(x = 0; x < 3; x++) {
546                                 self->eul[x] = 0.0f;
547                         }
548                 }else{
549                         for(x = 0; x < 3; x++){
550                                 self->eul[x] = eul[x];
551                         }
552                 }
553                 self->wrapped = Py_NEW;
554         }else{ //bad type
555                 return NULL;
556         }
557         return (PyObject *)self;
558 }