style cleanup: comments
[blender.git] / source / blender / python / mathutils / mathutils.c
1 /* 
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * This is a new part of Blender.
22  *
23  * Contributor(s): Joseph Gilbert, Campbell Barton
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/python/mathutils/mathutils.c
29  *  \ingroup pymathutils
30  */
31
32 #include <Python.h>
33
34 #include "mathutils.h"
35
36 #include "BLI_math.h"
37 #include "BLI_utildefines.h"
38 #include "BLI_dynstr.h"
39
40 PyDoc_STRVAR(M_Mathutils_doc,
41 "This module provides access to matrices, eulers, quaternions and vectors."
42 );
43 static int mathutils_array_parse_fast(float *array,
44                                       int size,
45                                       PyObject *value_fast,
46                                       const char *error_prefix)
47 {
48         PyObject *item;
49
50         int i;
51
52         i = size;
53         do {
54                 i--;
55                 if (((array[i] = PyFloat_AsDouble((item = PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
56                     PyErr_Occurred())
57                 {
58                         PyErr_Format(PyExc_TypeError,
59                                      "%.200s: sequence index %d expected a number, "
60                                      "found '%.200s' type, ",
61                                      error_prefix, i, Py_TYPE(item)->tp_name);
62                         Py_DECREF(value_fast);
63                         return -1;
64                 }
65         } while (i);
66
67         Py_XDECREF(value_fast);
68         return size;
69 }
70
71 /* helper functionm returns length of the 'value', -1 on error */
72 int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
73 {
74         int size;
75
76 #if 1 /* approx 6x speedup for mathutils types */
77
78         if ((size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
79             (size = EulerObject_Check(value)      ? 3 : 0) ||
80             (size = QuaternionObject_Check(value) ? 4 : 0) ||
81             (size = ColorObject_Check(value)      ? 3 : 0))
82         {
83                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
84                         return -1;
85                 }
86
87                 if (size > array_max || size < array_min) {
88                         if (array_max == array_min) {
89                                 PyErr_Format(PyExc_ValueError,
90                                              "%.200s: sequence size is %d, expected %d",
91                                              error_prefix, size, array_max);
92                         }
93                         else {
94                                 PyErr_Format(PyExc_ValueError,
95                                              "%.200s: sequence size is %d, expected [%d - %d]",
96                                              error_prefix, size, array_min, array_max);
97                         }
98                         return -1;
99                 }
100
101                 memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
102                 return size;
103         }
104         else
105 #endif
106         {
107                 PyObject *value_fast = NULL;
108
109                 /* non list/tuple cases */
110                 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
111                         /* PySequence_Fast sets the error */
112                         return -1;
113                 }
114
115                 size = PySequence_Fast_GET_SIZE(value_fast);
116
117                 if (size > array_max || size < array_min) {
118                         if (array_max == array_min) {
119                                 PyErr_Format(PyExc_ValueError,
120                                              "%.200s: sequence size is %d, expected %d",
121                                              error_prefix, size, array_max);
122                         }
123                         else {
124                                 PyErr_Format(PyExc_ValueError,
125                                              "%.200s: sequence size is %d, expected [%d - %d]",
126                                              error_prefix, size, array_min, array_max);
127                         }
128                         Py_DECREF(value_fast);
129                         return -1;
130                 }
131
132                 return mathutils_array_parse_fast(array, size, value_fast, error_prefix);
133         }
134 }
135
136 /* on error, -1 is returned and no allocation is made */
137 int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
138 {
139         int size;
140
141 #if 1 /* approx 6x speedup for mathutils types */
142
143         if ((size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
144             (size = EulerObject_Check(value)      ? 3 : 0) ||
145             (size = QuaternionObject_Check(value) ? 4 : 0) ||
146             (size = ColorObject_Check(value)      ? 3 : 0))
147         {
148                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
149                         return -1;
150                 }
151
152                 if (size < array_min) {
153                         PyErr_Format(PyExc_ValueError,
154                                      "%.200s: sequence size is %d, expected > %d",
155                                      error_prefix, size, array_min);
156                         return -1;
157                 }
158                 
159                 *array = PyMem_Malloc(size * sizeof(float));
160                 memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
161                 return size;
162         }
163         else
164 #endif
165         {
166                 PyObject *value_fast = NULL;
167                 // *array = NULL;
168                 int ret;
169
170                 /* non list/tuple cases */
171                 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
172                         /* PySequence_Fast sets the error */
173                         return -1;
174                 }
175
176                 size = PySequence_Fast_GET_SIZE(value_fast);
177
178                 if (size < array_min) {
179                         PyErr_Format(PyExc_ValueError,
180                                      "%.200s: sequence size is %d, expected > %d",
181                                      error_prefix, size, array_min);
182                         return -1;
183                 }
184
185                 *array = PyMem_Malloc(size * sizeof(float));
186
187                 ret = mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
188
189                 if (ret == -1) {
190                         PyMem_Free(*array);
191                 }
192
193                 return ret;
194         }
195 }
196
197 /* parse an array of vectors */
198 int mathutils_array_parse_alloc_v(float **array, int array_dim, PyObject *value, const char *error_prefix)
199 {
200         PyObject *value_fast = NULL;
201         int i, size;
202
203         /* non list/tuple cases */
204         if (!(value_fast = PySequence_Fast(value, error_prefix))) {
205                 /* PySequence_Fast sets the error */
206                 return -1;
207         }
208
209         size = PySequence_Fast_GET_SIZE(value_fast);
210
211         if (size != 0) {
212                 float *fp;
213
214                 fp = *array = PyMem_Malloc(size * array_dim * sizeof(float));
215
216                 for (i = 0; i < size; i++, fp += array_dim) {
217                         PyObject *item = PySequence_Fast_GET_ITEM(value, i);
218
219                         if (mathutils_array_parse(fp, array_dim, array_dim, item, error_prefix) == -1) {
220                                 PyMem_Free(*array);
221                                 *array = NULL;
222                                 size = -1;
223                                 break;
224                         }
225                 }
226         }
227
228         Py_DECREF(value_fast);
229         return size;
230 }
231
232 int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
233 {
234         if (EulerObject_Check(value)) {
235                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
236                         return -1;
237                 }
238                 else {
239                         eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
240                         return 0;
241                 }
242         }
243         else if (QuaternionObject_Check(value)) {
244                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
245                         return -1;
246                 }
247                 else {
248                         float tquat[4];
249                         normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
250                         quat_to_mat3(rmat, tquat);
251                         return 0;
252                 }
253         }
254         else if (MatrixObject_Check(value)) {
255                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
256                         return -1;
257                 }
258                 else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
259                         PyErr_Format(PyExc_ValueError,
260                                      "%.200s: matrix must have minimum 3x3 dimensions",
261                                      error_prefix);
262                         return -1;
263                 }
264                 else {
265                         matrix_as_3x3(rmat, (MatrixObject *)value);
266                         normalize_m3(rmat);
267                         return 0;
268                 }
269         }
270         else {
271                 PyErr_Format(PyExc_TypeError,
272                              "%.200s: expected a Euler, Quaternion or Matrix type, "
273                              "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
274                 return -1;
275         }
276 }
277
278
279 /* ----------------------------------MATRIX FUNCTIONS-------------------- */
280
281
282 /* Utility functions */
283
284 /* LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon */
285 #define SIGNMASK(i) (-(int)(((unsigned int)(i)) >> 31))
286
287 int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
288 {
289         /* solid, fast routine across all platforms
290          * with constant time behavior */
291         int ai = *(int *)(&af);
292         int bi = *(int *)(&bf);
293         int test = SIGNMASK(ai ^ bi);
294         int diff, v1, v2;
295
296         assert((0 == test) || (0xFFFFFFFF == test));
297         diff = (ai ^ (test & 0x7fffffff)) - bi;
298         v1 = maxDiff + diff;
299         v2 = maxDiff - diff;
300         return (v1 | v2) >= 0;
301 }
302
303 /*---------------------- EXPP_VectorsAreEqual -------------------------
304  * Builds on EXPP_FloatsAreEqual to test vectors */
305 int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
306 {
307         int x;
308         for (x = 0; x < size; x++) {
309                 if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
310                         return 0;
311         }
312         return 1;
313 }
314
315 /* dynstr as python string utility funcions, frees 'ds'! */
316 PyObject *mathutils_dynstr_to_py(struct DynStr *ds)
317 {
318         const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
319         char *ds_buf     = PyMem_Malloc(ds_len + 1);
320         PyObject *ret;
321         BLI_dynstr_get_cstring_ex(ds, ds_buf);
322         BLI_dynstr_free(ds);
323         ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
324         PyMem_Free(ds_buf);
325         return ret;
326 }
327
328 /* silly function, we dont use arg. just check its compatible with __deepcopy__ */
329 int mathutils_deepcopy_args_check(PyObject *args)
330 {
331         PyObject *dummy_pydict;
332         return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0;
333 }
334
335 /* Mathutils Callbacks */
336
337 /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
338 #define MATHUTILS_TOT_CB 10
339 static Mathutils_Callback *mathutils_callbacks[MATHUTILS_TOT_CB] = {NULL};
340
341 unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb)
342 {
343         unsigned char i;
344         
345         /* find the first free slot */
346         for (i = 0; mathutils_callbacks[i]; i++) {
347                 if (mathutils_callbacks[i] == cb) /* already registered? */
348                         return i;
349         }
350
351         BLI_assert(i + 1 < MATHUTILS_TOT_CB);
352
353         mathutils_callbacks[i] = cb;
354         return i;
355 }
356
357 /* use macros to check for NULL */
358 int _BaseMathObject_ReadCallback(BaseMathObject *self)
359 {
360         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
361         if (LIKELY(cb->get(self, self->cb_subtype) != -1)) {
362                 return 0;
363         }
364
365         if (!PyErr_Occurred()) {
366                 PyErr_Format(PyExc_RuntimeError,
367                              "%s read, user has become invalid",
368                              Py_TYPE(self)->tp_name);
369         }
370         return -1;
371 }
372
373 int _BaseMathObject_WriteCallback(BaseMathObject *self)
374 {
375         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
376         if (LIKELY(cb->set(self, self->cb_subtype) != -1)) {
377                 return 0;
378         }
379
380         if (!PyErr_Occurred()) {
381                 PyErr_Format(PyExc_RuntimeError,
382                              "%s write, user has become invalid",
383                              Py_TYPE(self)->tp_name);
384         }
385         return -1;
386 }
387
388 int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
389 {
390         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
391         if (LIKELY(cb->get_index(self, self->cb_subtype, index) != -1)) {
392                 return 0;
393         }
394
395         if (!PyErr_Occurred()) {
396                 PyErr_Format(PyExc_RuntimeError,
397                              "%s read index, user has become invalid",
398                              Py_TYPE(self)->tp_name);
399         }
400         return -1;
401 }
402
403 int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
404 {
405         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
406         if (LIKELY(cb->set_index(self, self->cb_subtype, index) != -1)) {
407                 return 0;
408         }
409
410         if (!PyErr_Occurred()) {
411                 PyErr_Format(PyExc_RuntimeError,
412                              "%s write index, user has become invalid",
413                              Py_TYPE(self)->tp_name);
414         }
415         return -1;
416 }
417
418 /* BaseMathObject generic functions for all mathutils types */
419 char BaseMathObject_owner_doc[] = "The item this is wrapping or None  (read-only).";
420 PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *UNUSED(closure))
421 {
422         PyObject *ret = self->cb_user ? self->cb_user : Py_None;
423         Py_INCREF(ret);
424         return ret;
425 }
426
427 char BaseMathObject_is_wrapped_doc[] = "True when this object wraps external data (read-only).\n\n:type: boolean";
428 PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *UNUSED(closure))
429 {
430         return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1 : 0);
431 }
432
433 int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
434 {
435         Py_VISIT(self->cb_user);
436         return 0;
437 }
438
439 int BaseMathObject_clear(BaseMathObject *self)
440 {
441         Py_CLEAR(self->cb_user);
442         return 0;
443 }
444
445 void BaseMathObject_dealloc(BaseMathObject *self)
446 {
447         /* only free non wrapped */
448         if (self->wrapped != Py_WRAP) {
449                 PyMem_Free(self->data);
450         }
451
452         if (self->cb_user) {
453                 PyObject_GC_UnTrack(self);
454                 BaseMathObject_clear(self);
455         }
456
457         Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
458 }
459
460 /*----------------------------MODULE INIT-------------------------*/
461 static struct PyMethodDef M_Mathutils_methods[] = {
462         {NULL, NULL, 0, NULL}
463 };
464
465 static struct PyModuleDef M_Mathutils_module_def = {
466         PyModuleDef_HEAD_INIT,
467         "mathutils",  /* m_name */
468         M_Mathutils_doc,  /* m_doc */
469         0,  /* m_size */
470         M_Mathutils_methods,  /* m_methods */
471         NULL,  /* m_reload */
472         NULL,  /* m_traverse */
473         NULL,  /* m_clear */
474         NULL,  /* m_free */
475 };
476
477 PyMODINIT_FUNC PyInit_mathutils(void)
478 {
479         PyObject *mod;
480         PyObject *submodule;
481         PyObject *sys_modules = PyThreadState_GET()->interp->modules;
482
483         if (PyType_Ready(&vector_Type) < 0)
484                 return NULL;
485         if (PyType_Ready(&matrix_Type) < 0)
486                 return NULL;
487         if (PyType_Ready(&matrix_access_Type) < 0)
488                 return NULL;
489         if (PyType_Ready(&euler_Type) < 0)
490                 return NULL;
491         if (PyType_Ready(&quaternion_Type) < 0)
492                 return NULL;
493         if (PyType_Ready(&color_Type) < 0)
494                 return NULL;
495
496         mod = PyModule_Create(&M_Mathutils_module_def);
497         
498         /* each type has its own new() function */
499         PyModule_AddObject(mod, vector_Type.tp_name,     (PyObject *)&vector_Type);
500         PyModule_AddObject(mod, matrix_Type.tp_name,     (PyObject *)&matrix_Type);
501         PyModule_AddObject(mod, euler_Type.tp_name,      (PyObject *)&euler_Type);
502         PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
503         PyModule_AddObject(mod, color_Type.tp_name,      (PyObject *)&color_Type);
504         
505         /* submodule */
506         PyModule_AddObject(mod, "geometry",       (submodule = PyInit_mathutils_geometry()));
507         /* XXX, python doesnt do imports with this usefully yet
508          * 'from mathutils.geometry import PolyFill'
509          * ...fails without this. */
510         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
511         Py_INCREF(submodule);
512
513         /* Noise submodule */
514         PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
515         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
516         Py_INCREF(submodule);
517
518         mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
519         mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
520         mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);
521
522         return mod;
523 }