2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * This is a new part of Blender.
23 * Contributor(s): Joseph Gilbert, Campbell Barton
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/python/mathutils/mathutils.c
29 * \ingroup pymathutils
34 #include "mathutils.h"
37 #include "BLI_utildefines.h"
38 #include "BLI_dynstr.h"
40 PyDoc_STRVAR(M_Mathutils_doc,
41 "This module provides access to matrices, eulers, quaternions and vectors."
43 static int mathutils_array_parse_fast(float *array,
46 const char *error_prefix)
55 if ( ((array[i] = PyFloat_AsDouble((item = PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
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);
67 Py_XDECREF(value_fast);
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)
76 #if 1 /* approx 6x speedup for mathutils types */
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))
83 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
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);
94 PyErr_Format(PyExc_ValueError,
95 "%.200s: sequence size is %d, expected [%d - %d]",
96 error_prefix, size, array_min, array_max);
101 memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
107 PyObject *value_fast = NULL;
109 /* non list/tuple cases */
110 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
111 /* PySequence_Fast sets the error */
115 size = PySequence_Fast_GET_SIZE(value_fast);
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);
124 PyErr_Format(PyExc_ValueError,
125 "%.200s: sequence size is %d, expected [%d - %d]",
126 error_prefix, size, array_min, array_max);
128 Py_DECREF(value_fast);
132 return mathutils_array_parse_fast(array, size, value_fast, error_prefix);
136 int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
140 #if 1 /* approx 6x speedup for mathutils types */
142 if ( (size = VectorObject_Check(value) ? ((VectorObject *)value)->size : 0) ||
143 (size = EulerObject_Check(value) ? 3 : 0) ||
144 (size = QuaternionObject_Check(value) ? 4 : 0) ||
145 (size = ColorObject_Check(value) ? 3 : 0))
147 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
151 if (size < array_min) {
152 PyErr_Format(PyExc_ValueError,
153 "%.200s: sequence size is %d, expected > %d",
154 error_prefix, size, array_min);
158 *array = PyMem_Malloc(size * sizeof(float));
159 memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
165 PyObject *value_fast = NULL;
168 /* non list/tuple cases */
169 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
170 /* PySequence_Fast sets the error */
174 size = PySequence_Fast_GET_SIZE(value_fast);
176 if (size < array_min) {
177 PyErr_Format(PyExc_ValueError,
178 "%.200s: sequence size is %d, expected > %d",
179 error_prefix, size, array_min);
183 *array = PyMem_Malloc(size * sizeof(float));
185 return mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
189 int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
191 if (EulerObject_Check(value)) {
192 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
196 eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
200 else if (QuaternionObject_Check(value)) {
201 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
206 normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
207 quat_to_mat3(rmat, tquat);
211 else if (MatrixObject_Check(value)) {
212 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
215 else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
216 PyErr_Format(PyExc_ValueError,
217 "%.200s: matrix must have minimum 3x3 dimensions",
222 matrix_as_3x3(rmat, (MatrixObject *)value);
228 PyErr_Format(PyExc_TypeError,
229 "%.200s: expected a Euler, Quaternion or Matrix type, "
230 "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
236 //----------------------------------MATRIX FUNCTIONS--------------------
239 /* Utility functions */
241 // LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
242 #define SIGNMASK(i) (-(int)(((unsigned int)(i))>>31))
244 int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
245 { // solid, fast routine across all platforms
246 // with constant time behavior
247 int ai = *(int *)(&af);
248 int bi = *(int *)(&bf);
249 int test = SIGNMASK(ai^bi);
252 assert((0 == test) || (0xFFFFFFFF == test));
253 diff = (ai ^ (test & 0x7fffffff)) - bi;
259 /*---------------------- EXPP_VectorsAreEqual -------------------------
260 Builds on EXPP_FloatsAreEqual to test vectors */
261 int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
264 for (x = 0; x < size; x++) {
265 if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
271 /* dynstr as python string utility funcions, frees 'ds'! */
272 PyObject *mathutils_dynstr_to_py(struct DynStr *ds)
274 const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
275 char *ds_buf = PyMem_Malloc(ds_len + 1);
277 BLI_dynstr_get_cstring_ex(ds, ds_buf);
279 ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
284 /* Mathutils Callbacks */
286 /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
287 static Mathutils_Callback *mathutils_callbacks[8] = {NULL};
289 int Mathutils_RegisterCallback(Mathutils_Callback *cb)
293 /* find the first free slot */
294 for (i = 0; mathutils_callbacks[i]; i++) {
295 if (mathutils_callbacks[i] == cb) /* already registered? */
299 mathutils_callbacks[i] = cb;
303 /* use macros to check for NULL */
304 int _BaseMathObject_ReadCallback(BaseMathObject *self)
306 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
307 if (cb->get(self, self->cb_subtype) != -1)
310 if (!PyErr_Occurred()) {
311 PyErr_Format(PyExc_RuntimeError,
312 "%s read, user has become invalid",
313 Py_TYPE(self)->tp_name);
318 int _BaseMathObject_WriteCallback(BaseMathObject *self)
320 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
321 if (cb->set(self, self->cb_subtype) != -1)
324 if (!PyErr_Occurred()) {
325 PyErr_Format(PyExc_RuntimeError,
326 "%s write, user has become invalid",
327 Py_TYPE(self)->tp_name);
332 int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
334 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
335 if (cb->get_index(self, self->cb_subtype, index) != -1)
338 if (!PyErr_Occurred()) {
339 PyErr_Format(PyExc_RuntimeError,
340 "%s read index, user has become invalid",
341 Py_TYPE(self)->tp_name);
346 int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
348 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
349 if (cb->set_index(self, self->cb_subtype, index) != -1)
352 if (!PyErr_Occurred()) {
353 PyErr_Format(PyExc_RuntimeError,
354 "%s write index, user has become invalid",
355 Py_TYPE(self)->tp_name);
360 /* BaseMathObject generic functions for all mathutils types */
361 char BaseMathObject_owner_doc[] = "The item this is wrapping or None (read-only).";
362 PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *UNUSED(closure))
364 PyObject *ret = self->cb_user ? self->cb_user : Py_None;
369 char BaseMathObject_is_wrapped_doc[] = "True when this object wraps external data (read-only).\n\n:type: boolean";
370 PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *UNUSED(closure))
372 return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1:0);
375 int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
377 Py_VISIT(self->cb_user);
381 int BaseMathObject_clear(BaseMathObject *self)
383 Py_CLEAR(self->cb_user);
387 void BaseMathObject_dealloc(BaseMathObject *self)
389 /* only free non wrapped */
390 if (self->wrapped != Py_WRAP) {
391 PyMem_Free(self->data);
395 PyObject_GC_UnTrack(self);
396 BaseMathObject_clear(self);
399 Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
402 /*----------------------------MODULE INIT-------------------------*/
403 static struct PyMethodDef M_Mathutils_methods[] = {
404 {NULL, NULL, 0, NULL}
407 static struct PyModuleDef M_Mathutils_module_def = {
408 PyModuleDef_HEAD_INIT,
409 "mathutils", /* m_name */
410 M_Mathutils_doc, /* m_doc */
412 M_Mathutils_methods, /* m_methods */
414 NULL, /* m_traverse */
419 PyMODINIT_FUNC PyInit_mathutils(void)
423 PyObject *sys_modules = PyThreadState_GET()->interp->modules;
425 if (PyType_Ready(&vector_Type) < 0)
427 if (PyType_Ready(&matrix_Type) < 0)
429 if (PyType_Ready(&matrix_access_Type) < 0)
431 if (PyType_Ready(&euler_Type) < 0)
433 if (PyType_Ready(&quaternion_Type) < 0)
435 if (PyType_Ready(&color_Type) < 0)
438 submodule = PyModule_Create(&M_Mathutils_module_def);
440 /* each type has its own new() function */
441 PyModule_AddObject(submodule, "Vector", (PyObject *)&vector_Type);
442 PyModule_AddObject(submodule, "Matrix", (PyObject *)&matrix_Type);
443 PyModule_AddObject(submodule, "Euler", (PyObject *)&euler_Type);
444 PyModule_AddObject(submodule, "Quaternion", (PyObject *)&quaternion_Type);
445 PyModule_AddObject(submodule, "Color", (PyObject *)&color_Type);
448 PyModule_AddObject(submodule, "geometry", (item = PyInit_mathutils_geometry()));
449 /* XXX, python doesnt do imports with this usefully yet
450 * 'from mathutils.geometry import PolyFill'
451 * ...fails without this. */
452 PyDict_SetItemString(sys_modules, "mathutils.geometry", item);
455 /* Noise submodule */
456 PyModule_AddObject(submodule, "noise", (item = PyInit_mathutils_noise()));
457 PyDict_SetItemString(sys_modules, "mathutils.noise", item);
460 mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
461 mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
462 mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);