diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c
index 327ee4dd1c3..63137e094b7 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.c
+++ b/source/blender/python/mathutils/mathutils_Matrix.c
@@ -1,3619 +1,3621 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
#ifndef MATH_STANDALONE
# include "BLI_dynstr.h"
# include "BLI_string.h"
#endif
typedef enum eMatrixAccess_t {
MAT_ACCESS_ROW,
MAT_ACCESS_COL,
} eMatrixAccess_t;
static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix);
static PyObject *Matrix_copy(MatrixObject *self);
static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args);
static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value);
-static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self);
+static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
+ MatrixObject *self);
static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type);
static int matrix_row_vector_check(MatrixObject *mat, VectorObject *vec, int row)
{
if ((vec->size != mat->num_col) || (row >= mat->num_row)) {
PyErr_SetString(PyExc_AttributeError,
"Matrix(): "
"owner matrix has been resized since this row vector was created");
return 0;
}
else {
return 1;
}
}
static int matrix_col_vector_check(MatrixObject *mat, VectorObject *vec, int col)
{
if ((vec->size != mat->num_row) || (col >= mat->num_col)) {
PyErr_SetString(PyExc_AttributeError,
"Matrix(): "
"owner matrix has been resized since this column vector was created");
return 0;
}
else {
return 1;
}
}
/* ----------------------------------------------------------------------------
* matrix row callbacks
* this is so you can do matrix[i][j] = val OR matrix.row[i][j] = val */
uchar mathutils_matrix_row_cb_index = -1;
static int mathutils_matrix_row_check(BaseMathObject *bmo)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_row_get(BaseMathObject *bmo, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int col;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
return -1;
}
for (col = 0; col < self->num_col; col++) {
bmo->data[col] = MATRIX_ITEM(self, row, col);
}
return 0;
}
static int mathutils_matrix_row_set(BaseMathObject *bmo, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int col;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
return -1;
}
for (col = 0; col < self->num_col; col++) {
MATRIX_ITEM(self, row, col) = bmo->data[col];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
static int mathutils_matrix_row_get_index(BaseMathObject *bmo, int row, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
return -1;
}
bmo->data[col] = MATRIX_ITEM(self, row, col);
return 0;
}
static int mathutils_matrix_row_set_index(BaseMathObject *bmo, int row, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
return -1;
}
MATRIX_ITEM(self, row, col) = bmo->data[col];
(void)BaseMath_WriteCallback(self);
return 0;
}
Mathutils_Callback mathutils_matrix_row_cb = {
mathutils_matrix_row_check,
mathutils_matrix_row_get,
mathutils_matrix_row_set,
mathutils_matrix_row_get_index,
mathutils_matrix_row_set_index,
};
/* ----------------------------------------------------------------------------
* matrix row callbacks
* this is so you can do matrix.col[i][j] = val */
uchar mathutils_matrix_col_cb_index = -1;
static int mathutils_matrix_col_check(BaseMathObject *bmo)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_col_get(BaseMathObject *bmo, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int num_row;
int row;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
return -1;
}
/* for 'translation' size will always be '3' even on 4x4 vec */
num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
for (row = 0; row < num_row; row++) {
bmo->data[row] = MATRIX_ITEM(self, row, col);
}
return 0;
}
static int mathutils_matrix_col_set(BaseMathObject *bmo, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int num_row;
int row;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
return -1;
}
/* for 'translation' size will always be '3' even on 4x4 vec */
num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
for (row = 0; row < num_row; row++) {
MATRIX_ITEM(self, row, col) = bmo->data[row];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
static int mathutils_matrix_col_get_index(BaseMathObject *bmo, int col, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
return -1;
}
bmo->data[row] = MATRIX_ITEM(self, row, col);
return 0;
}
static int mathutils_matrix_col_set_index(BaseMathObject *bmo, int col, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
return -1;
}
MATRIX_ITEM(self, row, col) = bmo->data[row];
(void)BaseMath_WriteCallback(self);
return 0;
}
Mathutils_Callback mathutils_matrix_col_cb = {
mathutils_matrix_col_check,
mathutils_matrix_col_get,
mathutils_matrix_col_set,
mathutils_matrix_col_get_index,
mathutils_matrix_col_set_index,
};
/* ----------------------------------------------------------------------------
* matrix row callbacks
* this is so you can do matrix.translation = val
* note, this is _exactly like matrix.col except the 4th component is always omitted */
uchar mathutils_matrix_translation_cb_index = -1;
static int mathutils_matrix_translation_check(BaseMathObject *bmo)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_translation_get(BaseMathObject *bmo, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int row;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
for (row = 0; row < 3; row++) {
bmo->data[row] = MATRIX_ITEM(self, row, col);
}
return 0;
}
static int mathutils_matrix_translation_set(BaseMathObject *bmo, int col)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
int row;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
for (row = 0; row < 3; row++) {
MATRIX_ITEM(self, row, col) = bmo->data[row];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
static int mathutils_matrix_translation_get_index(BaseMathObject *bmo, int col, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
bmo->data[row] = MATRIX_ITEM(self, row, col);
return 0;
}
static int mathutils_matrix_translation_set_index(BaseMathObject *bmo, int col, int row)
{
MatrixObject *self = (MatrixObject *)bmo->cb_user;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
MATRIX_ITEM(self, row, col) = bmo->data[row];
(void)BaseMath_WriteCallback(self);
return 0;
}
Mathutils_Callback mathutils_matrix_translation_cb = {
mathutils_matrix_translation_check,
mathutils_matrix_translation_get,
mathutils_matrix_translation_set,
mathutils_matrix_translation_get_index,
mathutils_matrix_translation_set_index,
};
/* matrix column callbacks, this is so you can do matrix.translation = Vector() */
/* ----------------------------------mathutils.Matrix() ----------------- */
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
/* create a new matrix type */
static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
if (kwds && PyDict_Size(kwds)) {
PyErr_SetString(PyExc_TypeError,
"Matrix(): "
"takes no keyword args");
return NULL;
}
switch (PyTuple_GET_SIZE(args)) {
case 0:
return Matrix_CreatePyObject(NULL, 4, 4, type);
case 1: {
PyObject *arg = PyTuple_GET_ITEM(args, 0);
/* Input is now as a sequence of rows so length of sequence
* is the number of rows */
/* -1 is an error, size checks will account for this */
const ushort num_row = PySequence_Size(arg);
if (num_row >= 2 && num_row <= 4) {
PyObject *item = PySequence_GetItem(arg, 0);
/* Since each item is a row, number of items is the
* same as the number of columns */
const ushort num_col = PySequence_Size(item);
Py_XDECREF(item);
if (num_col >= 2 && num_col <= 4) {
/* sane row & col size, new matrix and assign as slice */
PyObject *matrix = Matrix_CreatePyObject(NULL, num_col, num_row, type);
if (Matrix_ass_slice((MatrixObject *)matrix, 0, INT_MAX, arg) == 0) {
return matrix;
}
else { /* matrix ok, slice assignment not */
Py_DECREF(matrix);
}
}
}
break;
}
}
/* will overwrite error */
PyErr_SetString(PyExc_TypeError,
"Matrix(): "
"expects no args or a single arg containing 2-4 numeric sequences");
return NULL;
}
-static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self)
+static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
+ MatrixObject *self)
{
PyObject *ret = Matrix_copy(self);
if (ret) {
- PyObject *ret_dummy = matrix_func(ret);
+ PyObject *ret_dummy = matrix_func((MatrixObject *)ret);
if (ret_dummy) {
Py_DECREF(ret_dummy);
- return (PyObject *)ret;
+ return ret;
}
else { /* error */
Py_DECREF(ret);
return NULL;
}
}
else {
/* copy may fail if the read callback errors out */
return NULL;
}
}
/* when a matrix is 4x4 size but initialized as a 3x3, re-assign values for 4x4 */
static void matrix_3x3_as_4x4(float mat[16])
{
mat[10] = mat[8];
mat[9] = mat[7];
mat[8] = mat[6];
mat[7] = 0.0f;
mat[6] = mat[5];
mat[5] = mat[4];
mat[4] = mat[3];
mat[3] = 0.0f;
}
/*-----------------------CLASS-METHODS----------------------------*/
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Identity_doc,
".. classmethod:: Identity(size)\n"
"\n"
" Create an identity matrix.\n"
"\n"
" :arg size: The size of the identity matrix to construct [2, 4].\n"
" :type size: int\n"
" :return: A new identity matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Identity(PyObject *cls, PyObject *args)
{
int matSize;
if (!PyArg_ParseTuple(args, "i:Matrix.Identity", &matSize)) {
return NULL;
}
if (matSize < 2 || matSize > 4) {
PyErr_SetString(PyExc_RuntimeError,
"Matrix.Identity(): "
"size must be between 2 and 4");
return NULL;
}
return Matrix_CreatePyObject(NULL, matSize, matSize, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Matrix_Rotation_doc,
".. classmethod:: Rotation(angle, size, axis)\n"
"\n"
" Create a matrix representing a rotation.\n"
"\n"
" :arg angle: The angle of rotation desired, in radians.\n"
" :type angle: float\n"
" :arg size: The size of the rotation matrix to construct [2, 4].\n"
" :type size: int\n"
" :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object\n"
" (optional when size is 2).\n"
" :type axis: string or :class:`Vector`\n"
" :return: A new rotation matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
{
PyObject *vec = NULL;
const char *axis = NULL;
int matSize;
double angle; /* use double because of precision problems at high values */
float mat[16] = {
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
};
if (!PyArg_ParseTuple(args, "di|O:Matrix.Rotation", &angle, &matSize, &vec)) {
return NULL;
}
if (vec && PyUnicode_Check(vec)) {
axis = _PyUnicode_AsString((PyObject *)vec);
if (axis == NULL || axis[0] == '\0' || axis[1] != '\0' || axis[0] < 'X' || axis[0] > 'Z') {
PyErr_SetString(PyExc_ValueError,
"Matrix.Rotation(): "
"3rd argument axis value must be a 3D vector "
"or a string in 'X', 'Y', 'Z'");
return NULL;
}
else {
/* use the string */
vec = NULL;
}
}
angle = angle_wrap_rad(angle);
if (matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.Rotation(): "
"can only return a 2x2 3x3 or 4x4 matrix");
return NULL;
}
if (matSize == 2 && (vec != NULL)) {
PyErr_SetString(PyExc_ValueError,
"Matrix.Rotation(): "
"cannot create a 2x2 rotation matrix around arbitrary axis");
return NULL;
}
if ((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
PyErr_SetString(PyExc_ValueError,
"Matrix.Rotation(): "
"axis of rotation for 3d and 4d matrices is required");
return NULL;
}
/* check for valid vector/axis above */
if (vec) {
float tvec[3];
if (mathutils_array_parse(
tvec, 3, 3, vec, "Matrix.Rotation(angle, size, axis), invalid 'axis' arg") == -1) {
return NULL;
}
axis_angle_to_mat3((float(*)[3])mat, tvec, angle);
}
else if (matSize == 2) {
angle_to_mat2((float(*)[2])mat, angle);
}
else {
/* valid axis checked above */
axis_angle_to_mat3_single((float(*)[3])mat, axis[0], angle);
}
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
/* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Matrix_Translation_doc,
".. classmethod:: Translation(vector)\n"
"\n"
" Create a matrix representing a translation.\n"
"\n"
" :arg vector: The translation vector.\n"
" :type vector: :class:`Vector`\n"
" :return: An identity matrix with a translation.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
{
float mat[4][4];
unit_m4(mat);
if (mathutils_array_parse(
mat[3], 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1) {
return NULL;
}
return Matrix_CreatePyObject(&mat[0][0], 4, 4, (PyTypeObject *)cls);
}
/* ----------------------------------mathutils.Matrix.Diagonal() ------------- */
PyDoc_STRVAR(C_Matrix_Diagonal_doc,
".. classmethod:: Diagonal(vector)\n"
"\n"
" Create a diagonal (scaling) matrix using the values from the vector.\n"
"\n"
" :arg vector: The vector of values for the diagonal.\n"
" :type vector: :class:`Vector`\n"
" :return: A diagonal matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Diagonal(PyObject *cls, PyObject *value)
{
float mat[16] = {0.0f};
float vec[4];
int size = mathutils_array_parse(
vec, 2, 4, value, "mathutils.Matrix.Diagonal(vector), invalid vector arg");
if (size == -1) {
return NULL;
}
for (int i = 0; i < size; i++) {
mat[size * i + i] = vec[i];
}
return Matrix_CreatePyObject(mat, size, size, (PyTypeObject *)cls);
}
/* ----------------------------------mathutils.Matrix.Scale() ------------- */
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Scale_doc,
".. classmethod:: Scale(factor, size, axis)\n"
"\n"
" Create a matrix representing a scaling.\n"
"\n"
" :arg factor: The factor of scaling to apply.\n"
" :type factor: float\n"
" :arg size: The size of the scale matrix to construct [2, 4].\n"
" :type size: int\n"
" :arg axis: Direction to influence scale. (optional).\n"
" :type axis: :class:`Vector`\n"
" :return: A new scale matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
{
PyObject *vec = NULL;
int vec_size;
float tvec[3];
float factor;
int matSize;
float mat[16] = {
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
};
if (!PyArg_ParseTuple(args, "fi|O:Matrix.Scale", &factor, &matSize, &vec)) {
return NULL;
}
if (matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.Scale(): "
"can only return a 2x2 3x3 or 4x4 matrix");
return NULL;
}
if (vec) {
vec_size = (matSize == 2 ? 2 : 3);
if (mathutils_array_parse(tvec,
vec_size,
vec_size,
vec,
"Matrix.Scale(factor, size, axis), invalid 'axis' arg") == -1) {
return NULL;
}
}
if (vec == NULL) { /* scaling along axis */
if (matSize == 2) {
mat[0] = factor;
mat[3] = factor;
}
else {
mat[0] = factor;
mat[4] = factor;
mat[8] = factor;
}
}
else {
/* scaling in arbitrary direction
* normalize arbitrary axis */
float norm = 0.0f;
int x;
for (x = 0; x < vec_size; x++) {
norm += tvec[x] * tvec[x];
}
norm = sqrtf(norm);
for (x = 0; x < vec_size; x++) {
tvec[x] /= norm;
}
if (matSize == 2) {
mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
mat[2] = ((factor - 1) * (tvec[0] * tvec[1]));
mat[3] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
}
else {
mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
mat[2] = ((factor - 1) * (tvec[0] * tvec[2]));
mat[3] = ((factor - 1) * (tvec[0] * tvec[1]));
mat[4] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
mat[5] = ((factor - 1) * (tvec[1] * tvec[2]));
mat[6] = ((factor - 1) * (tvec[0] * tvec[2]));
mat[7] = ((factor - 1) * (tvec[1] * tvec[2]));
mat[8] = 1 + ((factor - 1) * (tvec[2] * tvec[2]));
}
}
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
/* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
/* ----------------------------------mathutils.Matrix.OrthoProjection() --- */
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_OrthoProjection_doc,
".. classmethod:: OrthoProjection(axis, size)\n"
"\n"
" Create a matrix to represent an orthographic projection.\n"
"\n"
" :arg axis: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
" where a single axis is for a 2D matrix.\n"
" Or a vector for an arbitrary axis\n"
" :type axis: string or :class:`Vector`\n"
" :arg size: The size of the projection matrix to construct [2, 4].\n"
" :type size: int\n"
" :return: A new projection matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
{
PyObject *axis;
int matSize, x;
float norm = 0.0f;
float mat[16] = {
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
};
if (!PyArg_ParseTuple(args, "Oi:Matrix.OrthoProjection", &axis, &matSize)) {
return NULL;
}
if (matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.OrthoProjection(): "
"can only return a 2x2 3x3 or 4x4 matrix");
return NULL;
}
if (PyUnicode_Check(axis)) { /* ortho projection onto cardinal plane */
Py_ssize_t plane_len;
const char *plane = _PyUnicode_AsStringAndSize(axis, &plane_len);
if (matSize == 2) {
if (plane_len == 1 && plane[0] == 'X') {
mat[0] = 1.0f;
}
else if (plane_len == 1 && plane[0] == 'Y') {
mat[3] = 1.0f;
}
else {
PyErr_Format(PyExc_ValueError,
"Matrix.OrthoProjection(): "
"unknown plane, expected: X, Y, not '%.200s'",
plane);
return NULL;
}
}
else {
if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Y') {
mat[0] = 1.0f;
mat[4] = 1.0f;
}
else if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Z') {
mat[0] = 1.0f;
mat[8] = 1.0f;
}
else if (plane_len == 2 && plane[0] == 'Y' && plane[1] == 'Z') {
mat[4] = 1.0f;
mat[8] = 1.0f;
}
else {
PyErr_Format(PyExc_ValueError,
"Matrix.OrthoProjection(): "
"unknown plane, expected: XY, XZ, YZ, not '%.200s'",
plane);
return NULL;
}
}
}
else {
/* arbitrary plane */
int vec_size = (matSize == 2 ? 2 : 3);
float tvec[4];
if (mathutils_array_parse(tvec,
vec_size,
vec_size,
axis,
"Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1) {
return NULL;
}
/* normalize arbitrary axis */
for (x = 0; x < vec_size; x++) {
norm += tvec[x] * tvec[x];
}
norm = sqrtf(norm);
for (x = 0; x < vec_size; x++) {
tvec[x] /= norm;
}
if (matSize == 2) {
mat[0] = 1 - (tvec[0] * tvec[0]);
mat[1] = -(tvec[0] * tvec[1]);
mat[2] = -(tvec[0] * tvec[1]);
mat[3] = 1 - (tvec[1] * tvec[1]);
}
else if (matSize > 2) {
mat[0] = 1 - (tvec[0] * tvec[0]);
mat[1] = -(tvec[0] * tvec[1]);
mat[2] = -(tvec[0] * tvec[2]);
mat[3] = -(tvec[0] * tvec[1]);
mat[4] = 1 - (tvec[1] * tvec[1]);
mat[5] = -(tvec[1] * tvec[2]);
mat[6] = -(tvec[0] * tvec[2]);
mat[7] = -(tvec[1] * tvec[2]);
mat[8] = 1 - (tvec[2] * tvec[2]);
}
}
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
/* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Matrix_Shear_doc,
".. classmethod:: Shear(plane, size, factor)\n"
"\n"
" Create a matrix to represent an shear transformation.\n"
"\n"
" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
" where a single axis is for a 2D matrix only.\n"
" :type plane: string\n"
" :arg size: The size of the shear matrix to construct [2, 4].\n"
" :type size: int\n"
" :arg factor: The factor of shear to apply. For a 3 or 4 *size* matrix\n"
" pass a pair of floats corresponding with the *plane* axis.\n"
" :type factor: float or float pair\n"
" :return: A new shear matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
{
int matSize;
const char *plane;
PyObject *fac;
float mat[16] = {
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
};
if (!PyArg_ParseTuple(args, "siO:Matrix.Shear", &plane, &matSize, &fac)) {
return NULL;
}
if (matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.Shear(): "
"can only return a 2x2 3x3 or 4x4 matrix");
return NULL;
}
if (matSize == 2) {
float const factor = PyFloat_AsDouble(fac);
if (factor == -1.0f && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"Matrix.Shear(): "
"the factor to be a float");
return NULL;
}
/* unit */
mat[0] = 1.0f;
mat[3] = 1.0f;
if (STREQ(plane, "X")) {
mat[2] = factor;
}
else if (STREQ(plane, "Y")) {
mat[1] = factor;
}
else {
PyErr_SetString(PyExc_ValueError,
"Matrix.Shear(): "
"expected: X, Y or wrong matrix size for shearing plane");
return NULL;
}
}
else {
/* 3 or 4, apply as 3x3, resize later if needed */
float factor[2];
if (mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") == -1) {
return NULL;
}
/* unit */
mat[0] = 1.0f;
mat[4] = 1.0f;
mat[8] = 1.0f;
if (STREQ(plane, "XY")) {
mat[6] = factor[0];
mat[7] = factor[1];
}
else if (STREQ(plane, "XZ")) {
mat[3] = factor[0];
mat[5] = factor[1];
}
else if (STREQ(plane, "YZ")) {
mat[1] = factor[0];
mat[2] = factor[1];
}
else {
PyErr_SetString(PyExc_ValueError,
"Matrix.Shear(): "
"expected: X, Y, XY, XZ, YZ");
return NULL;
}
}
if (matSize == 4) {
matrix_3x3_as_4x4(mat);
}
/* pass to matrix creation */
return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
void matrix_as_3x3(float mat[3][3], MatrixObject *self)
{
copy_v3_v3(mat[0], MATRIX_COL_PTR(self, 0));
copy_v3_v3(mat[1], MATRIX_COL_PTR(self, 1));
copy_v3_v3(mat[2], MATRIX_COL_PTR(self, 2));
}
static void matrix_copy(MatrixObject *mat_dst, const MatrixObject *mat_src)
{
BLI_assert((mat_dst->num_col == mat_src->num_col) && (mat_dst->num_row == mat_src->num_row));
BLI_assert(mat_dst != mat_src);
memcpy(mat_dst->matrix, mat_src->matrix, sizeof(float) * (mat_dst->num_col * mat_dst->num_row));
}
static void matrix_unit_internal(MatrixObject *self)
{
const int mat_size = sizeof(float) * (self->num_col * self->num_row);
memset(self->matrix, 0x0, mat_size);
const int col_row_max = min_ii(self->num_col, self->num_row);
const int num_row = self->num_row;
for (int col = 0; col < col_row_max; col++) {
self->matrix[(col * num_row) + col] = 1.0f;
}
}
/* transposes memory layout, rol/col's don't have to match */
static void matrix_transpose_internal(float mat_dst_fl[], const MatrixObject *mat_src)
{
ushort col, row;
uint i = 0;
for (row = 0; row < mat_src->num_row; row++) {
for (col = 0; col < mat_src->num_col; col++) {
mat_dst_fl[i++] = MATRIX_ITEM(mat_src, row, col);
}
}
}
/* assumes rowsize == colsize is checked and the read callback has run */
static float matrix_determinant_internal(const MatrixObject *self)
{
if (self->num_col == 2) {
return determinant_m2(MATRIX_ITEM(self, 0, 0),
MATRIX_ITEM(self, 0, 1),
MATRIX_ITEM(self, 1, 0),
MATRIX_ITEM(self, 1, 1));
}
else if (self->num_col == 3) {
return determinant_m3(MATRIX_ITEM(self, 0, 0),
MATRIX_ITEM(self, 0, 1),
MATRIX_ITEM(self, 0, 2),
MATRIX_ITEM(self, 1, 0),
MATRIX_ITEM(self, 1, 1),
MATRIX_ITEM(self, 1, 2),
MATRIX_ITEM(self, 2, 0),
MATRIX_ITEM(self, 2, 1),
MATRIX_ITEM(self, 2, 2));
}
else {
return determinant_m4((float(*)[4])self->matrix);
}
}
static void adjoint_matrix_n(float *mat_dst, const float *mat_src, const ushort dim)
{
/* calculate the classical adjoint */
switch (dim) {
case 2: {
adjoint_m2_m2((float(*)[2])mat_dst, (float(*)[2])mat_src);
break;
}
case 3: {
adjoint_m3_m3((float(*)[3])mat_dst, (float(*)[3])mat_src);
break;
}
case 4: {
adjoint_m4_m4((float(*)[4])mat_dst, (float(*)[4])mat_src);
break;
}
default:
BLI_assert(0);
}
}
static void matrix_invert_with_det_n_internal(float *mat_dst,
const float *mat_src,
const float det,
const ushort dim)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
ushort i, j, k;
BLI_assert(det != 0.0f);
adjoint_matrix_n(mat, mat_src, dim);
/* divide by determinant & set values */
k = 0;
for (i = 0; i < dim; i++) { /* num_col */
for (j = 0; j < dim; j++) { /* num_row */
mat_dst[MATRIX_ITEM_INDEX_NUMROW(dim, j, i)] = mat[k++] / det;
}
}
}
/**
* \param r_mat: can be from ``self->matrix`` or not.
*/
static bool matrix_invert_internal(const MatrixObject *self, float *r_mat)
{
float det;
BLI_assert(self->num_col == self->num_row);
det = matrix_determinant_internal(self);
if (det != 0.0f) {
matrix_invert_with_det_n_internal(r_mat, self->matrix, det, self->num_col);
return true;
}
else {
return false;
}
}
/**
* Similar to ``matrix_invert_internal`` but should never error.
* \param r_mat: can be from ``self->matrix`` or not.
*/
static void matrix_invert_safe_internal(const MatrixObject *self, float *r_mat)
{
float det;
float *in_mat = self->matrix;
BLI_assert(self->num_col == self->num_row);
det = matrix_determinant_internal(self);
if (det == 0.0f) {
const float eps = PSEUDOINVERSE_EPSILON;
/* We will copy self->matrix into r_mat (if needed),
* and modify it in place to add diagonal epsilon. */
in_mat = r_mat;
switch (self->num_col) {
case 2: {
float(*mat)[2] = (float(*)[2])in_mat;
if (in_mat != self->matrix) {
copy_m2_m2(mat, (float(*)[2])self->matrix);
}
mat[0][0] += eps;
mat[1][1] += eps;
if (UNLIKELY((det = determinant_m2(mat[0][0], mat[0][1], mat[1][0], mat[1][1])) == 0.0f)) {
unit_m2(mat);
det = 1.0f;
}
break;
}
case 3: {
float(*mat)[3] = (float(*)[3])in_mat;
if (in_mat != self->matrix) {
copy_m3_m3(mat, (float(*)[3])self->matrix);
}
mat[0][0] += eps;
mat[1][1] += eps;
mat[2][2] += eps;
if (UNLIKELY((det = determinant_m3_array(mat)) == 0.0f)) {
unit_m3(mat);
det = 1.0f;
}
break;
}
case 4: {
float(*mat)[4] = (float(*)[4])in_mat;
if (in_mat != self->matrix) {
copy_m4_m4(mat, (float(*)[4])self->matrix);
}
mat[0][0] += eps;
mat[1][1] += eps;
mat[2][2] += eps;
mat[3][3] += eps;
if (UNLIKELY(det = determinant_m4(mat)) == 0.0f) {
unit_m4(mat);
det = 1.0f;
}
break;
}
default:
BLI_assert(0);
}
}
matrix_invert_with_det_n_internal(r_mat, in_mat, det, self->num_col);
}
/*-----------------------------METHODS----------------------------*/
PyDoc_STRVAR(Matrix_to_quaternion_doc,
".. method:: to_quaternion()\n"
"\n"
" Return a quaternion representation of the rotation matrix.\n"
"\n"
" :return: Quaternion representation of the rotation matrix.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Matrix_to_quaternion(MatrixObject *self)
{
float quat[4];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/* must be 3-4 cols, 3-4 rows, square matrix */
if ((self->num_row < 3) || (self->num_col < 3) || (self->num_row != self->num_col)) {
PyErr_SetString(PyExc_ValueError,
"Matrix.to_quat(): "
"inappropriate matrix size - expects 3x3 or 4x4 matrix");
return NULL;
}
if (self->num_row == 3) {
mat3_to_quat(quat, (float(*)[3])self->matrix);
}
else {
mat4_to_quat(quat, (float(*)[4])self->matrix);
}
return Quaternion_CreatePyObject(quat, NULL);
}
/*---------------------------matrix.toEuler() --------------------*/
PyDoc_STRVAR(Matrix_to_euler_doc,
".. method:: to_euler(order, euler_compat)\n"
"\n"
" Return an Euler representation of the rotation matrix\n"
" (3x3 or 4x4 matrix only).\n"
"\n"
" :arg order: Optional rotation order argument in\n"
" ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
" :type order: string\n"
" :arg euler_compat: Optional euler argument the new euler will be made\n"
" compatible with (no axis flipping between them).\n"
" Useful for converting a series of matrices to animation curves.\n"
" :type euler_compat: :class:`Euler`\n"
" :return: Euler representation of the matrix.\n"
" :rtype: :class:`Euler`\n");
static PyObject *Matrix_to_euler(MatrixObject *self, PyObject *args)
{
const char *order_str = NULL;
short order = EULER_ORDER_XYZ;
float eul[3], eul_compatf[3];
EulerObject *eul_compat = NULL;
float mat[3][3];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
return NULL;
}
if (eul_compat) {
if (BaseMath_ReadCallback(eul_compat) == -1) {
return NULL;
}
copy_v3_v3(eul_compatf, eul_compat->eul);
}
/*must be 3-4 cols, 3-4 rows, square matrix */
if (self->num_row == 3 && self->num_col == 3) {
copy_m3_m3(mat, (float(*)[3])self->matrix);
}
else if (self->num_row == 4 && self->num_col == 4) {
copy_m3_m4(mat, (float(*)[4])self->matrix);
}
else {
PyErr_SetString(PyExc_ValueError,
"Matrix.to_euler(): "
"inappropriate matrix size - expects 3x3 or 4x4 matrix");
return NULL;
}
if (order_str) {
order = euler_order_from_string(order_str, "Matrix.to_euler()");
if (order == -1) {
return NULL;
}
}
normalize_m3(mat);
if (eul_compat) {
if (order == 1) {
mat3_normalized_to_compatible_eul(eul, eul_compatf, mat);
}
else {
mat3_normalized_to_compatible_eulO(eul, eul_compatf, order, mat);
}
}
else {
if (order == 1) {
mat3_normalized_to_eul(eul, mat);
}
else {
mat3_normalized_to_eulO(eul, order, mat);
}
}
return Euler_CreatePyObject(eul, order, NULL);
}
PyDoc_STRVAR(Matrix_resize_4x4_doc,
".. method:: resize_4x4()\n"
"\n"
" Resize the matrix to 4x4.\n");
static PyObject *Matrix_resize_4x4(MatrixObject *self)
{
float mat[4][4];
int col;
if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
PyErr_SetString(PyExc_ValueError,
"Matrix.resize_4x4(): "
"cannot resize wrapped data - make a copy and resize that");
return NULL;
}
if (self->cb_user) {
PyErr_SetString(PyExc_ValueError,
"Matrix.resize_4x4(): "
"cannot resize owned data - make a copy and resize that");
return NULL;
}
self->matrix = PyMem_Realloc(self->matrix, (sizeof(float) * (MATRIX_MAX_DIM * MATRIX_MAX_DIM)));
if (self->matrix == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Matrix.resize_4x4(): "
"problem allocating pointer space");
return NULL;
}
unit_m4(mat);
for (col = 0; col < self->num_col; col++) {
memcpy(mat[col], MATRIX_COL_PTR(self, col), self->num_row * sizeof(float));
}
copy_m4_m4((float(*)[4])self->matrix, (float(*)[4])mat);
self->num_col = 4;
self->num_row = 4;
Py_RETURN_NONE;
}
static PyObject *Matrix_to_NxN(MatrixObject *self, const int num_col, const int num_row)
{
const int mat_size = sizeof(float) * (num_col * num_row);
MatrixObject *pymat = (MatrixObject *)Matrix_CreatePyObject_alloc(
PyMem_Malloc(mat_size), num_col, num_row, Py_TYPE(self));
if ((self->num_row == num_row) && (self->num_col == num_col)) {
memcpy(pymat->matrix, self->matrix, mat_size);
}
else {
if ((self->num_col < num_col) || (self->num_row < num_row)) {
matrix_unit_internal(pymat);
}
const int col_len_src = min_ii(num_col, self->num_col);
const int row_len_src = min_ii(num_row, self->num_row);
for (int col = 0; col < col_len_src; col++) {
memcpy(
&pymat->matrix[col * num_row], MATRIX_COL_PTR(self, col), sizeof(float) * row_len_src);
}
}
return (PyObject *)pymat;
}
PyDoc_STRVAR(Matrix_to_2x2_doc,
".. method:: to_2x2()\n"
"\n"
" Return a 2x2 copy of this matrix.\n"
"\n"
" :return: a new matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_to_2x2(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Matrix_to_NxN(self, 2, 2);
}
PyDoc_STRVAR(Matrix_to_3x3_doc,
".. method:: to_3x3()\n"
"\n"
" Return a 3x3 copy of this matrix.\n"
"\n"
" :return: a new matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_to_3x3(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Matrix_to_NxN(self, 3, 3);
}
PyDoc_STRVAR(Matrix_to_4x4_doc,
".. method:: to_4x4()\n"
"\n"
" Return a 4x4 copy of this matrix.\n"
"\n"
" :return: a new matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_to_4x4(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Matrix_to_NxN(self, 4, 4);
}
PyDoc_STRVAR(Matrix_to_translation_doc,
".. method:: to_translation()\n"
"\n"
" Return the translation part of a 4 row matrix.\n"
"\n"
" :return: Return the translation of a matrix.\n"
" :rtype: :class:`Vector`\n");
static PyObject *Matrix_to_translation(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if ((self->num_row < 3) || self->num_col < 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.to_translation(): "
"inappropriate matrix size");
return NULL;
}
return Vector_CreatePyObject(MATRIX_COL_PTR(self, 3), 3, NULL);
}
PyDoc_STRVAR(Matrix_to_scale_doc,
".. method:: to_scale()\n"
"\n"
" Return the scale part of a 3x3 or 4x4 matrix.\n"
"\n"
" :return: Return the scale of a matrix.\n"
" :rtype: :class:`Vector`\n"
"\n"
" .. note:: This method does not return a negative scale on any axis because it is "
"not possible to obtain this data from the matrix alone.\n");
static PyObject *Matrix_to_scale(MatrixObject *self)
{
float rot[3][3];
float mat[3][3];
float size[3];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 3-4 cols, 3-4 rows, square matrix */
if ((self->num_row < 3) || (self->num_col < 3)) {
PyErr_SetString(PyExc_ValueError,
"Matrix.to_scale(): "
"inappropriate matrix size, 3x3 minimum size");
return NULL;
}
matrix_as_3x3(mat, self);
/* compatible mat4_to_loc_rot_size */
mat3_to_rot_size(rot, size, mat);
return Vector_CreatePyObject(size, 3, NULL);
}
/*---------------------------matrix.invert() ---------------------*/
/* re-usable checks for invert */
static bool matrix_invert_is_compat(const MatrixObject *self)
{
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.invert(ed): "
"only square matrices are supported");
return false;
}
else {
return true;
}
}
static bool matrix_invert_args_check(const MatrixObject *self, PyObject *args, bool check_type)
{
switch (PyTuple_GET_SIZE(args)) {
case 0:
return true;
case 1:
if (check_type) {
const MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
if (!MatrixObject_Check(fallback)) {
PyErr_SetString(PyExc_TypeError,
"Matrix.invert: "
"expects a matrix argument or nothing");
return false;
}
if ((self->num_col != fallback->num_col) || (self->num_row != fallback->num_row)) {
PyErr_SetString(PyExc_TypeError,
"Matrix.invert: "
"matrix argument has different dimensions");
return false;
}
}
return true;
default:
PyErr_SetString(PyExc_ValueError,
"Matrix.invert(ed): "
"takes at most one argument");
return false;
}
}
static void matrix_invert_raise_degenerate(void)
{
PyErr_SetString(PyExc_ValueError,
"Matrix.invert(ed): "
"matrix does not have an inverse");
}
PyDoc_STRVAR(
Matrix_invert_doc,
".. method:: invert(fallback=None)\n"
"\n"
" Set the matrix to its inverse.\n"
"\n"
" :arg fallback: Set the matrix to this value when the inverse cannot be calculated\n"
" (instead of raising a :exc:`ValueError` exception).\n"
" :type fallback: :class:`Matrix`\n"
"\n"
" .. seealso:: `Inverse matrix <https://en.wikipedia.org/wiki/Inverse_matrix>`__ on "
"Wikipedia.\n");
static PyObject *Matrix_invert(MatrixObject *self, PyObject *args)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (matrix_invert_is_compat(self) == false) {
return NULL;
}
if (matrix_invert_args_check(self, args, true) == false) {
return NULL;
}
if (matrix_invert_internal(self, self->matrix)) {
/* pass */
}
else {
if (PyTuple_GET_SIZE(args) == 1) {
MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
if (BaseMath_ReadCallback(fallback) == -1) {
return NULL;
}
if (self != fallback) {
matrix_copy(self, fallback);
}
}
else {
matrix_invert_raise_degenerate();
return NULL;
}
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_inverted_doc,
".. method:: inverted(fallback=None)\n"
"\n"
" Return an inverted copy of the matrix.\n"
"\n"
" :arg fallback: return this when the inverse can't be calculated\n"
" (instead of raising a :exc:`ValueError`).\n"
" :type fallback: any\n"
" :return: the inverted matrix or fallback when given.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_inverted(MatrixObject *self, PyObject *args)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (matrix_invert_args_check(self, args, false) == false) {
return NULL;
}
if (matrix_invert_is_compat(self) == false) {
return NULL;
}
if (matrix_invert_internal(self, mat)) {
/* pass */
}
else {
if (PyTuple_GET_SIZE(args) == 1) {
PyObject *fallback = PyTuple_GET_ITEM(args, 0);
Py_INCREF(fallback);
return fallback;
}
else {
matrix_invert_raise_degenerate();
return NULL;
}
}
return Matrix_copy_notest(self, mat);
}
static PyObject *Matrix_inverted_noargs(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (matrix_invert_is_compat(self) == false) {
return NULL;
}
if (matrix_invert_internal(self, self->matrix)) {
/* pass */
}
else {
matrix_invert_raise_degenerate();
return NULL;
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
Matrix_invert_safe_doc,
".. method:: invert_safe()\n"
"\n"
" Set the matrix to its inverse, will never error.\n"
" If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
"to get an invertible one.\n"
" If tweaked matrix is still degenerated, set to the identity matrix instead.\n"
"\n"
" .. seealso:: `Inverse Matrix <https://en.wikipedia.org/wiki/Inverse_matrix>`__ on "
"Wikipedia.\n");
static PyObject *Matrix_invert_safe(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (matrix_invert_is_compat(self) == false) {
return NULL;
}
matrix_invert_safe_internal(self, self->matrix);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_inverted_safe_doc,
".. method:: inverted_safe()\n"
"\n"
" Return an inverted copy of the matrix, will never error.\n"
" If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
"to get an invertible one.\n"
" If tweaked matrix is still degenerated, return the identity matrix instead.\n"
"\n"
" :return: the inverted matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_inverted_safe(MatrixObject *self)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (matrix_invert_is_compat(self) == false) {
return NULL;
}
matrix_invert_safe_internal(self, mat);
return Matrix_copy_notest(self, mat);
}
/*---------------------------matrix.adjugate() ---------------------*/
PyDoc_STRVAR(
Matrix_adjugate_doc,
".. method:: adjugate()\n"
"\n"
" Set the matrix to its adjugate.\n"
"\n"
" .. note:: When the matrix cannot be adjugated a :exc:`ValueError` exception is raised.\n"
"\n"
" .. seealso:: `Adjugate matrix <https://en.wikipedia.org/wiki/Adjugate_matrix>`__ on "
"Wikipedia.\n");
static PyObject *Matrix_adjugate(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.adjugate(d): "
"only square matrices are supported");
return NULL;
}
/* calculate the classical adjoint */
if (self->num_col <= 4) {
adjoint_matrix_n(self->matrix, self->matrix, self->num_col);
}
else {
PyErr_Format(
PyExc_ValueError, "Matrix adjugate(d): size (%d) unsupported", (int)self->num_col);
return NULL;
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
Matrix_adjugated_doc,
".. method:: adjugated()\n"
"\n"
" Return an adjugated copy of the matrix.\n"
"\n"
" :return: the adjugated matrix.\n"
" :rtype: :class:`Matrix`\n"
"\n"
" .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n");
static PyObject *Matrix_adjugated(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_adjugate, self);
+ return matrix__apply_to_copy(Matrix_adjugate, self);
}
PyDoc_STRVAR(
Matrix_rotate_doc,
".. method:: rotate(other)\n"
"\n"
" Rotates the matrix by another mathutils value.\n"
"\n"
" :arg other: rotation component of mathutils value\n"
" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
"\n"
" .. note:: If any of the columns are not unit length this may not have desired results.\n");
static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
{
float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1) {
return NULL;
}
if (self->num_row != 3 || self->num_col != 3) {
PyErr_SetString(PyExc_ValueError,
"Matrix.rotate(): "
"must have 3x3 dimensions");
return NULL;
}
matrix_as_3x3(self_rmat, self);
mul_m3_m3m3(rmat, other_rmat, self_rmat);
copy_m3_m3((float(*)[3])(self->matrix), rmat);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
/*---------------------------matrix.decompose() ---------------------*/
PyDoc_STRVAR(Matrix_decompose_doc,
".. method:: decompose()\n"
"\n"
" Return the translation, rotation, and scale components of this matrix.\n"
"\n"
" :return: tuple of translation, rotation, and scale\n"
" :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)");
static PyObject *Matrix_decompose(MatrixObject *self)
{
PyObject *ret;
float loc[3];
float rot[3][3];
float quat[4];
float size[3];
if (self->num_row != 4 || self->num_col != 4) {
PyErr_SetString(PyExc_ValueError,
"Matrix.decompose(): "
"inappropriate matrix size - expects 4x4 matrix");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
mat4_to_loc_rot_size(loc, rot, size, (float(*)[4])self->matrix);
mat3_to_quat(quat, rot);
ret = PyTuple_New(3);
PyTuple_SET_ITEMS(ret,
Vector_CreatePyObject(loc, 3, NULL),
Quaternion_CreatePyObject(quat, NULL),
Vector_CreatePyObject(size, 3, NULL));
return ret;
}
PyDoc_STRVAR(Matrix_lerp_doc,
".. function:: lerp(other, factor)\n"
"\n"
" Returns the interpolation of two matrices. Uses polar decomposition, see"
" \"Matrix Animation and Polar Decomposition\", Shoemake and Duff, 1992.\n"
"\n"
" :arg other: value to interpolate with.\n"
" :type other: :class:`Matrix`\n"
" :arg factor: The interpolation value in [0.0, 1.0].\n"
" :type factor: float\n"
" :return: The interpolated matrix.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
{
MatrixObject *mat2 = NULL;
float fac, mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
if (!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac)) {
return NULL;
}
if (self->num_col != mat2->num_col || self->num_row != mat2->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.lerp(): "
"expects both matrix objects of the same dimensions");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
/* TODO, different sized matrix */
if (self->num_col == 4 && self->num_row == 4) {
#ifdef MATH_STANDALONE
blend_m4_m4m4((float(*)[4])mat, (float(*)[4])self->matrix, (float(*)[4])mat2->matrix, fac);
#else
interp_m4_m4m4((float(*)[4])mat, (float(*)[4])self->matrix, (float(*)[4])mat2->matrix, fac);
#endif
}
else if (self->num_col == 3 && self->num_row == 3) {
#ifdef MATH_STANDALONE
blend_m3_m3m3((float(*)[3])mat, (float(*)[3])self->matrix, (float(*)[3])mat2->matrix, fac);
#else
interp_m3_m3m3((float(*)[3])mat, (float(*)[3])self->matrix, (float(*)[3])mat2->matrix, fac);
#endif
}
else {
PyErr_SetString(PyExc_ValueError,
"Matrix.lerp(): "
"only 3x3 and 4x4 matrices supported");
return NULL;
}
return Matrix_CreatePyObject(mat, self->num_col, self->num_row, Py_TYPE(self));
}
/*---------------------------matrix.determinant() ----------------*/
PyDoc_STRVAR(
Matrix_determinant_doc,
".. method:: determinant()\n"
"\n"
" Return the determinant of a matrix.\n"
"\n"
" :return: Return the determinant of a matrix.\n"
" :rtype: float\n"
"\n"
" .. seealso:: `Determinant <https://en.wikipedia.org/wiki/Determinant>`__ on Wikipedia.\n");
static PyObject *Matrix_determinant(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.determinant(): "
"only square matrices are supported");
return NULL;
}
return PyFloat_FromDouble((double)matrix_determinant_internal(self));
}
/*---------------------------matrix.transpose() ------------------*/
PyDoc_STRVAR(
Matrix_transpose_doc,
".. method:: transpose()\n"
"\n"
" Set the matrix to its transpose.\n"
"\n"
" .. seealso:: `Transpose <https://en.wikipedia.org/wiki/Transpose>`__ on Wikipedia.\n");
static PyObject *Matrix_transpose(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.transpose(d): "
"only square matrices are supported");
return NULL;
}
if (self->num_col == 2) {
const float t = MATRIX_ITEM(self, 1, 0);
MATRIX_ITEM(self, 1, 0) = MATRIX_ITEM(self, 0, 1);
MATRIX_ITEM(self, 0, 1) = t;
}
else if (self->num_col == 3) {
transpose_m3((float(*)[3])self->matrix);
}
else {
transpose_m4((float(*)[4])self->matrix);
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_transposed_doc,
".. method:: transposed()\n"
"\n"
" Return a new, transposed matrix.\n"
"\n"
" :return: a transposed matrix\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_transposed(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
+ return matrix__apply_to_copy(Matrix_transpose, self);
}
/*---------------------------matrix.normalize() ------------------*/
PyDoc_STRVAR(Matrix_normalize_doc,
".. method:: normalize()\n"
"\n"
" Normalize each of the matrix columns.\n");
static PyObject *Matrix_normalize(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.normalize(): "
"only square matrices are supported");
return NULL;
}
if (self->num_col == 3) {
normalize_m3((float(*)[3])self->matrix);
}
else if (self->num_col == 4) {
normalize_m4((float(*)[4])self->matrix);
}
else {
PyErr_SetString(PyExc_ValueError,
"Matrix.normalize(): "
"can only use a 3x3 or 4x4 matrix");
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_normalized_doc,
".. method:: normalized()\n"
"\n"
" Return a column normalized matrix\n"
"\n"
" :return: a column normalized matrix\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_normalized(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_normalize, self);
+ return matrix__apply_to_copy(Matrix_normalize, self);
}
/*---------------------------matrix.zero() -----------------------*/
PyDoc_STRVAR(Matrix_zero_doc,
".. method:: zero()\n"
"\n"
" Set all the matrix values to zero.\n"
"\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_zero(MatrixObject *self)
{
if (BaseMath_Prepare_ForWrite(self) == -1) {
return NULL;
}
copy_vn_fl(self->matrix, self->num_col * self->num_row, 0.0f);
if (BaseMath_WriteCallback(self) == -1) {
return NULL;
}
Py_RETURN_NONE;
}
/*---------------------------matrix.identity(() ------------------*/
static void matrix_identity_internal(MatrixObject *self)
{
BLI_assert((self->num_col == self->num_row) && (self->num_row <= 4));
if (self->num_col == 2) {
unit_m2((float(*)[2])self->matrix);
}
else if (self->num_col == 3) {
unit_m3((float(*)[3])self->matrix);
}
else {
unit_m4((float(*)[4])self->matrix);
}
}
PyDoc_STRVAR(Matrix_identity_doc,
".. method:: identity()\n"
"\n"
" Set the matrix to the identity matrix.\n"
"\n"
" .. note:: An object with a location and rotation of zero, and a scale of one\n"
" will have an identity matrix.\n"
"\n"
" .. seealso:: `Identity matrix <https://en.wikipedia.org/wiki/Identity_matrix>`__ "
"on Wikipedia.\n");
static PyObject *Matrix_identity(MatrixObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (self->num_col != self->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix.identity(): "
"only square matrices are supported");
return NULL;
}
matrix_identity_internal(self);
if (BaseMath_WriteCallback(self) == -1) {
return NULL;
}
Py_RETURN_NONE;
}
/*---------------------------Matrix.copy() ------------------*/
static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix)
{
return Matrix_CreatePyObject((float *)matrix, self->num_col, self->num_row, Py_TYPE(self));
}
PyDoc_STRVAR(Matrix_copy_doc,
".. method:: copy()\n"
"\n"
" Returns a copy of this matrix.\n"
"\n"
" :return: an instance of itself\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Matrix_copy(MatrixObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Matrix_copy_notest(self, self->matrix);
}
static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args)
{
if (!PyC_CheckArgs_DeepCopy(args)) {
return NULL;
}
return Matrix_copy(self);
}
/*----------------------------print object (internal)-------------*/
/* print the object to screen */
static PyObject *Matrix_repr(MatrixObject *self)
{
int col, row;
PyObject *rows[MATRIX_MAX_DIM] = {NULL};
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
for (row = 0; row < self->num_row; row++) {
rows[row] = PyTuple_New(self->num_col);
for (col = 0; col < self->num_col; col++) {
PyTuple_SET_ITEM(rows[row], col, PyFloat_FromDouble(MATRIX_ITEM(self, row, col)));
}
}
switch (self->num_row) {
case 2:
return PyUnicode_FromFormat(
"Matrix((%R,\n"
" %R))",
rows[0],
rows[1]);
case 3:
return PyUnicode_FromFormat(
"Matrix((%R,\n"
" %R,\n"
" %R))",
rows[0],
rows[1],
rows[2]);
case 4:
return PyUnicode_FromFormat(
"Matrix((%R,\n"
" %R,\n"
" %R,\n"
" %R))",
rows[0],
rows[1],
rows[2],
rows[3]);
}
Py_FatalError("Matrix(): invalid row size!");
return NULL;
}
#ifndef MATH_STANDALONE
static PyObject *Matrix_str(MatrixObject *self)
{
DynStr *ds;
int maxsize[MATRIX_MAX_DIM];
int row, col;
char dummy_buf[64];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
ds = BLI_dynstr_new();
/* First determine the maximum width for each column */
for (col = 0; col < self->num_col; col++) {
maxsize[col] = 0;
for (row = 0; row < self->num_row; row++) {
int size = BLI_snprintf(dummy_buf, sizeof(dummy_buf), "%.4f", MATRIX_ITEM(self, row, col));
maxsize[col] = max_ii(maxsize[col], size);
}
}
/* Now write the unicode string to be printed */
BLI_dynstr_appendf(ds, "<Matrix %dx%d (", self->num_row, self->num_col);
for (row = 0; row < self->num_row; row++) {
for (col = 0; col < self->num_col; col++) {
BLI_dynstr_appendf(ds, col ? ", %*.4f" : "%*.4f", maxsize[col], MATRIX_ITEM(self, row, col));
}
BLI_dynstr_append(ds, row + 1 != self->num_row ? ")\n (" : ")");
}
BLI_dynstr_append(ds, ">");
return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
static PyObject *Matrix_richcmpr(PyObject *a, PyObject *b, int op)
{
PyObject *res;
int ok = -1; /* zero is true */
if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
MatrixObject *matA = (MatrixObject *)a;
MatrixObject *matB = (MatrixObject *)b;
if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1) {
return NULL;
}
ok = ((matA->num_row == matB->num_row) && (matA->num_col == matB->num_col) &&
EXPP_VectorsAreEqual(matA->matrix, matB->matrix, (matA->num_col * matA->num_row), 1)) ?
0 :
-1;
}
switch (op) {
case Py_NE:
ok = !ok;
ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
case Py_LT:
case Py_LE:
case Py_GT:
case Py_GE:
res = Py_NotImplemented;
break;
default:
PyErr_BadArgument();
return NULL;
}
return Py_INCREF_RET(res);
}
static Py_hash_t Matrix_hash(MatrixObject *self)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (BaseMathObject_Prepare_ForHash(self) == -1) {
return -1;
}
matrix_transpose_internal(mat, self);
return mathutils_array_hash(mat, self->num_row * self->num_col);
}
/*---------------------SEQUENCE PROTOCOLS------------------------
* ----------------------------len(object)------------------------
* sequence length */
static int Matrix_len(MatrixObject *self)
{
return self->num_row;
}
/*----------------------------object[]---------------------------
* sequence accessor (get)
* the wrapped vector gives direct access to the matrix data */
static PyObject *Matrix_item_row(MatrixObject *self, int row)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (row < 0 || row >= self->num_row) {
PyErr_SetString(PyExc_IndexError,
"matrix[attribute]: "
"array index out of range");
return NULL;
}
return Vector_CreatePyObject_cb(
(PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, row);
}
/* same but column access */
static PyObject *Matrix_item_col(MatrixObject *self, int col)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (col < 0 || col >= self->num_col) {
PyErr_SetString(PyExc_IndexError,
"matrix[attribute]: "
"array index out of range");
return NULL;
}
return Vector_CreatePyObject_cb(
(PyObject *)self, self->num_row, mathutils_matrix_col_cb_index, col);
}
/*----------------------------object[]-------------------------
* sequence accessor (set) */
static int Matrix_ass_item_row(MatrixObject *self, int row, PyObject *value)
{
int col;
float vec[MATRIX_MAX_DIM];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (row >= self->num_row || row < 0) {
PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad row");
return -1;
}
if (mathutils_array_parse(
vec, self->num_col, self->num_col, value, "matrix[i] = value assignment") == -1) {
return -1;
}
/* Since we are assigning a row we cannot memcpy */
for (col = 0; col < self->num_col; col++) {
MATRIX_ITEM(self, row, col) = vec[col];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
static int Matrix_ass_item_col(MatrixObject *self, int col, PyObject *value)
{
int row;
float vec[MATRIX_MAX_DIM];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if (col >= self->num_col || col < 0) {
PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad col");
return -1;
}
if (mathutils_array_parse(
vec, self->num_row, self->num_row, value, "matrix[i] = value assignment") == -1) {
return -1;
}
/* Since we are assigning a row we cannot memcpy */
for (row = 0; row < self->num_row; row++) {
MATRIX_ITEM(self, row, col) = vec[row];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
/*----------------------------object[z:y]------------------------
* sequence slice (get)*/
static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
{
PyObject *tuple;
int count;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
CLAMP(begin, 0, self->num_row);
CLAMP(end, 0, self->num_row);
begin = MIN2(begin, end);
tuple = PyTuple_New(end - begin);
for (count = begin; count < end; count++) {
PyTuple_SET_ITEM(tuple,
count - begin,
Vector_CreatePyObject_cb(
(PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, count));
}
return tuple;
}
/*----------------------------object[z:y]------------------------
* sequence slice (set)*/
static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
{
PyObject *value_fast;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
CLAMP(begin, 0, self->num_row);
CLAMP(end, 0, self->num_row);
begin = MIN2(begin, end);
/* non list/tuple cases */
if (!(value_fast = PySequence_Fast(value, "matrix[begin:end] = value"))) {
/* PySequence_Fast sets the error */
return -1;
}
else {
PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
const int size = end - begin;
int row, col;
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
float vec[4];
if (PySequence_Fast_GET_SIZE(value_fast) != size) {
Py_DECREF(value_fast);
PyErr_SetString(PyExc_ValueError,
"matrix[begin:end] = []: "
"size mismatch in slice assignment");
return -1;
}
memcpy(mat, self->matrix, self->num_col * self->num_row * sizeof(float));
/* parse sub items */
for (row = begin; row < end; row++) {
/* parse each sub sequence */
PyObject *item = value_fast_items[row - begin];
if (mathutils_array_parse(
vec, self->num_col, self->num_col, item, "matrix[begin:end] = value assignment") ==
-1) {
Py_DECREF(value_fast);
return -1;
}
for (col = 0; col < self->num_col; col++) {
mat[col * self->num_row + row] = vec[col];
}
}
Py_DECREF(value_fast);
/*parsed well - now set in matrix*/
memcpy(self->matrix, mat, self->num_col * self->num_row * sizeof(float));
(void)BaseMath_WriteCallback(self);
return 0;
}
}
/*------------------------NUMERIC PROTOCOLS----------------------
*------------------------obj + obj------------------------------*/
static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
MatrixObject *mat1 = NULL, *mat2 = NULL;
mat1 = (MatrixObject *)m1;
mat2 = (MatrixObject *)m2;
if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
PyErr_Format(PyExc_TypeError,
"Matrix addition: (%s + %s) "
"invalid type for this operation",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix addition: "
"matrices must have the same dimensions for this operation");
return NULL;
}
add_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
}
/*------------------------obj - obj------------------------------
* subtraction */
static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
{
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
MatrixObject *mat1 = NULL, *mat2 = NULL;
mat1 = (MatrixObject *)m1;
mat2 = (MatrixObject *)m2;
if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
PyErr_Format(PyExc_TypeError,
"Matrix subtraction: (%s - %s) "
"invalid type for this operation",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
PyErr_SetString(PyExc_ValueError,
"Matrix addition: "
"matrices must have the same dimensions for this operation");
return NULL;
}
sub_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
}
/*------------------------obj * obj------------------------------
* element-wise multiplication */
static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
{
float tmat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
mul_vn_vn_fl(tmat, mat->matrix, mat->num_col * mat->num_row, scalar);
return Matrix_CreatePyObject(tmat, mat->num_col, mat->num_row, Py_TYPE(mat));
}
static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
{
float scalar;
MatrixObject *mat1 = NULL, *mat2 = NULL;
if (MatrixObject_Check(m1)) {
mat1 = (MatrixObject *)m1;
if (BaseMath_ReadCallback(mat1) == -1) {
return NULL;
}
}
if (MatrixObject_Check(m2)) {
mat2 = (MatrixObject *)m2;
if (BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
}
if (mat1 && mat2) {
#ifdef USE_MATHUTILS_ELEM_MUL
/* MATRIX * MATRIX */
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
PyErr_SetString(PyExc_ValueError,
"matrix1 * matrix2: matrix1 number of rows/columns "
"and the matrix2 number of rows/columns must be the same");
return NULL;
}
mul_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
#endif
}
else if (mat2) {
/*FLOAT/INT * MATRIX */
if (((scalar = PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred()) == 0) {
return matrix_mul_float(mat2, scalar);
}
}
else if (mat1) {
/* MATRIX * FLOAT/INT */
if (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0) {
return matrix_mul_float(mat1, scalar);
}
}
PyErr_Format(PyExc_TypeError,
"Element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
/*------------------------obj *= obj------------------------------
* In place element-wise multiplication */
static PyObject *Matrix_imul(PyObject *m1, PyObject *m2)
{
float scalar;
MatrixObject *mat1 = NULL, *mat2 = NULL;
if (MatrixObject_Check(m1)) {
mat1 = (MatrixObject *)m1;
if (BaseMath_ReadCallback(mat1) == -1) {
return NULL;
}
}
if (MatrixObject_Check(m2)) {
mat2 = (MatrixObject *)m2;
if (BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
}
if (mat1 && mat2) {
#ifdef USE_MATHUTILS_ELEM_MUL
/* MATRIX *= MATRIX */
if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
PyErr_SetString(PyExc_ValueError,
"matrix1 *= matrix2: matrix1 number of rows/columns "
"and the matrix2 number of rows/columns must be the same");
return NULL;
}
mul_vn_vn(mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
#else
PyErr_Format(PyExc_TypeError,
"In place element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
#endif
}
else if (mat1 && (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0)) {
/* MATRIX *= FLOAT/INT */
mul_vn_fl(mat1->matrix, mat1->num_row * mat1->num_col, scalar);
}
else {
PyErr_Format(PyExc_TypeError,
"In place element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
(void)BaseMath_WriteCallback(mat1);
Py_INCREF(m1);
return m1;
}
/*------------------------obj @ obj------------------------------
* matrix multiplication */
static PyObject *Matrix_matmul(PyObject *m1, PyObject *m2)
{
int vec_size;
MatrixObject *mat1 = NULL, *mat2 = NULL;
if (MatrixObject_Check(m1)) {
mat1 = (MatrixObject *)m1;
if (BaseMath_ReadCallback(mat1) == -1) {
return NULL;
}
}
if (MatrixObject_Check(m2)) {
mat2 = (MatrixObject *)m2;
if (BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
}
if (mat1 && mat2) {
/* MATRIX @ MATRIX */
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
int col, row, item;
if (mat1->num_col != mat2->num_row) {
PyErr_SetString(PyExc_ValueError,
"matrix1 * matrix2: matrix1 number of columns "
"and the matrix2 number of rows must be the same");
return NULL;
}
for (col = 0; col < mat2->num_col; col++) {
for (row = 0; row < mat1->num_row; row++) {
double dot = 0.0f;
for (item = 0; item < mat1->num_col; item++) {
dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
}
mat[(col * mat1->num_row) + row] = (float)dot;
}
}
return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
}
else if (mat1) {
/* MATRIX @ VECTOR */
if (VectorObject_Check(m2)) {
VectorObject *vec2 = (VectorObject *)m2;
float tvec[MATRIX_MAX_DIM];
if (BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
return NULL;
}
if (mat1->num_col == 4 && vec2->size == 3) {
vec_size = 3;
}
else {
vec_size = mat1->num_row;
}
return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(m2));
}
}
PyErr_Format(PyExc_TypeError,
"Matrix multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
/*------------------------obj @= obj------------------------------
* In place matrix multiplication */
static PyObject *Matrix_imatmul(PyObject *m1, PyObject *m2)
{
MatrixObject *mat1 = NULL, *mat2 = NULL;
if (MatrixObject_Check(m1)) {
mat1 = (MatrixObject *)m1;
if (BaseMath_ReadCallback(mat1) == -1) {
return NULL;
}
}
if (MatrixObject_Check(m2)) {
mat2 = (MatrixObject *)m2;
if (BaseMath_ReadCallback(mat2) == -1) {
return NULL;
}
}
if (mat1 && mat2) {
/* MATRIX @= MATRIX */
float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
int col, row, item;
if (mat1->num_col != mat2->num_row) {
PyErr_SetString(PyExc_ValueError,
"matrix1 * matrix2: matrix1 number of columns "
"and the matrix2 number of rows must be the same");
return NULL;
}
for (col = 0; col < mat2->num_col; col++) {
for (row = 0; row < mat1->num_row; row++) {
double dot = 0.0f;
for (item = 0; item < mat1->num_col; item++) {
dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
}
/* store in new matrix as overwriting original at this point will cause
* subsequent iterations to use incorrect values */
mat[(col * mat1->num_row) + row] = (float)dot;
}
}
/* copy matrix back */
memcpy(mat1->matrix, mat, (mat1->num_row * mat1->num_col) * sizeof(float));
}
else {
PyErr_Format(PyExc_TypeError,
"In place matrix multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(m1)->tp_name,
Py_TYPE(m2)->tp_name);
return NULL;
}
(void)BaseMath_WriteCallback(mat1);
Py_INCREF(m1);
return m1;
}
/*-----------------PROTOCOL DECLARATIONS--------------------------*/
static PySequenceMethods Matrix_SeqMethods = {
(lenfunc)Matrix_len, /* sq_length */
(binaryfunc)NULL, /* sq_concat */
(ssizeargfunc)NULL, /* sq_repeat */
(ssizeargfunc)Matrix_item_row, /* sq_item */
(ssizessizeargfunc)NULL, /* sq_slice, deprecated */
(ssizeobjargproc)Matrix_ass_item_row, /* sq_ass_item */
(ssizessizeobjargproc)NULL, /* sq_ass_slice, deprecated */
(objobjproc)NULL, /* sq_contains */
(binaryfunc)NULL, /* sq_inplace_concat */
(ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyObject *Matrix_subscript(MatrixObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return NULL;
}
if (i < 0) {
i += self->num_row;
}
return Matrix_item_row(self, i);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
return NULL;
}
if (slicelength <= 0) {
return PyTuple_New(0);
}
else if (step == 1) {
return Matrix_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrices");
return NULL;
}
}
else {
PyErr_Format(
PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return NULL;
}
}
static int Matrix_ass_subscript(MatrixObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
if (i < 0) {
i += self->num_row;
}
return Matrix_ass_item_row(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
return -1;
}
if (step == 1) {
return Matrix_ass_slice(self, start, stop, value);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrices");
return -1;
}
}
else {
PyErr_Format(
PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return -1;
}
}
static PyMappingMethods Matrix_AsMapping = {
(lenfunc)Matrix_len,
(binaryfunc)Matrix_subscript,
(objobjargproc)Matrix_ass_subscript,
};
static PyNumberMethods Matrix_NumMethods = {
(binaryfunc)Matrix_add, /*nb_add*/
(binaryfunc)Matrix_sub, /*nb_subtract*/
(binaryfunc)Matrix_mul, /*nb_multiply*/
NULL, /*nb_remainder*/
NULL, /*nb_divmod*/
NULL, /*nb_power*/
(unaryfunc)0, /*nb_negative*/
(unaryfunc)0, /*tp_positive*/
(unaryfunc)0, /*tp_absolute*/
(inquiry)0, /*tp_bool*/
(unaryfunc)Matrix_inverted_noargs, /*nb_invert*/
NULL, /*nb_lshift*/
(binaryfunc)0, /*nb_rshift*/
NULL, /*nb_and*/
NULL, /*nb_xor*/
NULL, /*nb_or*/
NULL, /*nb_int*/
NULL, /*nb_reserved*/
NULL, /*nb_float*/
NULL, /* nb_inplace_add */
NULL, /* nb_inplace_subtract */
(binaryfunc)Matrix_imul, /* nb_inplace_multiply */
NULL, /* nb_inplace_remainder */
NULL, /* nb_inplace_power */
NULL, /* nb_inplace_lshift */
NULL, /* nb_inplace_rshift */
NULL, /* nb_inplace_and */
NULL, /* nb_inplace_xor */
NULL, /* nb_inplace_or */
NULL, /* nb_floor_divide */
NULL, /* nb_true_divide */
NULL, /* nb_inplace_floor_divide */
NULL, /* nb_inplace_true_divide */
NULL, /* nb_index */
(binaryfunc)Matrix_matmul, /* nb_matrix_multiply */
(binaryfunc)Matrix_imatmul, /* nb_inplace_matrix_multiply */
};
PyDoc_STRVAR(Matrix_translation_doc, "The translation component of the matrix.\n\n:type: Vector");
static PyObject *Matrix_translation_get(MatrixObject *self, void *UNUSED(closure))
{
PyObject *ret;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 4x4 square matrix*/
if (self->num_row != 4 || self->num_col != 4) {
PyErr_SetString(PyExc_AttributeError,
"Matrix.translation: "
"inappropriate matrix size, must be 4x4");
return NULL;
}
ret = (PyObject *)Vector_CreatePyObject_cb(
(PyObject *)self, 3, mathutils_matrix_translation_cb_index, 3);
return ret;
}
static int Matrix_translation_set(MatrixObject *self, PyObject *value, void *UNUSED(closure))
{
float tvec[3];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
/*must be 4x4 square matrix*/
if (self->num_row != 4 || self->num_col != 4) {
PyErr_SetString(PyExc_AttributeError,
"Matrix.translation: "
"inappropriate matrix size, must be 4x4");
return -1;
}
if ((mathutils_array_parse(tvec, 3, 3, value, "Matrix.translation")) == -1) {
return -1;
}
copy_v3_v3(((float(*)[4])self->matrix)[3], tvec);
(void)BaseMath_WriteCallback(self);
return 0;
}
PyDoc_STRVAR(Matrix_row_doc,
"Access the matrix by rows (default), (read-only).\n\n:type: Matrix Access");
static PyObject *Matrix_row_get(MatrixObject *self, void *UNUSED(closure))
{
return MatrixAccess_CreatePyObject(self, MAT_ACCESS_ROW);
}
PyDoc_STRVAR(
Matrix_col_doc,
"Access the matrix by columns, 3x3 and 4x4 only, (read-only).\n\n:type: Matrix Access");
static PyObject *Matrix_col_get(MatrixObject *self, void *UNUSED(closure))
{
return MatrixAccess_CreatePyObject(self, MAT_ACCESS_COL);
}
PyDoc_STRVAR(Matrix_median_scale_doc,
"The average scale applied to each axis (read-only).\n\n:type: float");
static PyObject *Matrix_median_scale_get(MatrixObject *self, void *UNUSED(closure))
{
float mat[3][3];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
if ((self->num_row < 3) || (self->num_col < 3)) {
PyErr_SetString(PyExc_AttributeError,
"Matrix.median_scale: "
"inappropriate matrix size, 3x3 minimum");
return NULL;
}
matrix_as_3x3(mat, self);
return PyFloat_FromDouble(mat3_to_scale(mat));
}
PyDoc_STRVAR(Matrix_is_negative_doc,
"True if this matrix results in a negative scale, 3x3 and 4x4 only, "
"(read-only).\n\n:type: bool");
static PyObject *Matrix_is_negative_get(MatrixObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
if (self->num_row == 4 && self->num_col == 4) {
return PyBool_FromLong(is_negative_m4((float(*)[4])self->matrix));
}
else if (self->num_row == 3 && self->num_col == 3) {
return PyBool_FromLong(is_negative_m3((float(*)[3])self->matrix));
}
else {
PyErr_SetString(PyExc_AttributeError,
"Matrix.is_negative: "
"inappropriate matrix size - expects 3x3 or 4x4 matrix");
return NULL;
}
}
PyDoc_STRVAR(Matrix_is_orthogonal_doc,
"True if this matrix is orthogonal, 3x3 and 4x4 only, (read-only).\n\n:type: bool");
static PyObject *Matrix_is_orthogonal_get(MatrixObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
if (self->num_row == 4 && self->num_col == 4) {
return PyBool_FromLong(is_orthonormal_m4((float(*)[4])self->matrix));
}
else if (self->num_row == 3 && self->num_col == 3) {
return PyBool_FromLong(is_orthonormal_m3((float(*)[3])self->matrix));
}
else {
PyErr_SetString(PyExc_AttributeError,
"Matrix.is_orthogonal: "
"inappropriate matrix size - expects 3x3 or 4x4 matrix");
return NULL;
}
}
PyDoc_STRVAR(Matrix_is_orthogonal_axis_vectors_doc,
"True if this matrix has got orthogonal axis vectors, 3x3 and 4x4 only, "
"(read-only).\n\n:type: bool");
static PyObject *Matrix_is_orthogonal_axis_vectors_get(MatrixObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
if (self->num_row == 4 && self->num_col == 4) {
return PyBool_FromLong(is_orthogonal_m4((float(*)[4])self->matrix));
}
else if (self->num_row == 3 && self->num_col == 3) {
return PyBool_FromLong(is_orthogonal_m3((float(*)[3])self->matrix));
}
else {
PyErr_SetString(PyExc_AttributeError,
"Matrix.is_orthogonal_axis_vectors: "
"inappropriate matrix size - expects 3x3 or 4x4 matrix");
return NULL;
}
}
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Matrix_getseters[] = {
{"median_scale", (getter)Matrix_median_scale_get, (setter)NULL, Matrix_median_scale_doc, NULL},
{"translation",
(getter)Matrix_translation_get,
(setter)Matrix_translation_set,
Matrix_translation_doc,
NULL},
{"row", (getter)Matrix_row_get, (setter)NULL, Matrix_row_doc, NULL},
{"col", (getter)Matrix_col_get, (setter)NULL, Matrix_col_doc, NULL},
{"is_negative", (getter)Matrix_is_negative_get, (setter)NULL, Matrix_is_negative_doc, NULL},
{"is_orthogonal",
(getter)Matrix_is_orthogonal_get,
(setter)NULL,
Matrix_is_orthogonal_doc,
NULL},
{"is_orthogonal_axis_vectors",
(getter)Matrix_is_orthogonal_axis_vectors_get,
(setter)NULL,
Matrix_is_orthogonal_axis_vectors_doc,
NULL},
{"is_wrapped",
(getter)BaseMathObject_is_wrapped_get,
(setter)NULL,
BaseMathObject_is_wrapped_doc,
NULL},
{"is_frozen",
(getter)BaseMathObject_is_frozen_get,
(setter)NULL,
BaseMathObject_is_frozen_doc,
NULL},
{"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/*-----------------------METHOD DEFINITIONS ----------------------*/
static struct PyMethodDef Matrix_methods[] = {
/* derived values */
{"determinant", (PyCFunction)Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
{"decompose", (PyCFunction)Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
/* in place only */
{"zero", (PyCFunction)Matrix_zero, METH_NOARGS, Matrix_zero_doc},
{"identity", (PyCFunction)Matrix_identity, METH_NOARGS, Matrix_identity_doc},
/* operate on original or copy */
{"transpose", (PyCFunction)Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
{"transposed", (PyCFunction)Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
{"normalize", (PyCFunction)Matrix_normalize, METH_NOARGS, Matrix_normalize_doc},
{"normalized", (PyCFunction)Matrix_normalized, METH_NOARGS, Matrix_normalized_doc},
{"invert", (PyCFunction)Matrix_invert, METH_VARARGS, Matrix_invert_doc},
{"inverted", (PyCFunction)Matrix_inverted, METH_VARARGS, Matrix_inverted_doc},
{"invert_safe", (PyCFunction)Matrix_invert_safe, METH_NOARGS, Matrix_invert_safe_doc},
{"inverted_safe", (PyCFunction)Matrix_inverted_safe, METH_NOARGS, Matrix_inverted_safe_doc},
{"adjugate", (PyCFunction)Matrix_adjugate, METH_NOARGS, Matrix_adjugate_doc},
{"adjugated", (PyCFunction)Matrix_adjugated, METH_NOARGS, Matrix_adjugated_doc},
{"to_2x2", (PyCFunction)Matrix_to_2x2, METH_NOARGS, Matrix_to_2x2_doc},
{"to_3x3", (PyCFunction)Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
{"to_4x4", (PyCFunction)Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
/* TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc}, */
{"resize_4x4", (PyCFunction)Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
{"rotate", (PyCFunction)Matrix_rotate, METH_O, Matrix_rotate_doc},
/* return converted representation */
{"to_euler", (PyCFunction)Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
{"to_quaternion", (PyCFunction)Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
{"to_scale", (PyCFunction)Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
{"to_translation", (PyCFunction)Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
/* operation between 2 or more types */
{"lerp", (PyCFunction)Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
{"copy", (PyCFunction)Matrix_copy, METH_NOARGS, Matrix_copy_doc},
{"__copy__", (PyCFunction)Matrix_copy, METH_NOARGS, Matrix_copy_doc},
{"__deepcopy__", (PyCFunction)Matrix_deepcopy, METH_VARARGS, Matrix_copy_doc},
/* base-math methods */
{"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
/* class methods */
{"Identity", (PyCFunction)C_Matrix_Identity, METH_VARARGS | METH_CLASS, C_Matrix_Identity_doc},
{"Rotation", (PyCFunction)C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
{"Scale", (PyCFunction)C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
{"Shear", (PyCFunction)C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
{"Diagonal", (PyCFunction)C_Matrix_Diagonal, METH_O | METH_CLASS, C_Matrix_Diagonal_doc},
{"Translation",
(PyCFunction)C_Matrix_Translation,
METH_O | METH_CLASS,
C_Matrix_Translation_doc},
{"OrthoProjection",
(PyCFunction)C_Matrix_OrthoProjection,
METH_VARARGS | METH_CLASS,
C_Matrix_OrthoProjection_doc},
{NULL, NULL, 0, NULL},
};
/*------------------PY_OBECT DEFINITION--------------------------*/
PyDoc_STRVAR(
matrix_doc,
".. class:: Matrix([rows])\n"
"\n"
" This object gives access to Matrices in Blender, supporting square and rectangular\n"
" matrices from 2x2 up to 4x4.\n"
"\n"
" :param rows: Sequence of rows.\n"
" When omitted, a 4x4 identity matrix is constructed.\n"
" :type rows: 2d number sequence\n");
PyTypeObject matrix_Type = {
PyVarObject_HEAD_INIT(NULL, 0) "Matrix", /*tp_name*/
sizeof(MatrixObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)BaseMathObject_dealloc, /*tp_dealloc*/
(printfunc)NULL, /*tp_print*/
NULL, /*tp_getattr*/
NULL, /*tp_setattr*/
NULL, /*tp_compare*/
(reprfunc)Matrix_repr, /*tp_repr*/
&Matrix_NumMethods, /*tp_as_number*/
&Matrix_SeqMethods, /*tp_as_sequence*/
&Matrix_AsMapping, /*tp_as_mapping*/
(hashfunc)Matrix_hash, /*tp_hash*/
NULL, /*tp_call*/
#ifndef MATH_STANDALONE
(reprfunc)Matrix_str, /*tp_str*/
#else
NULL, /*tp_str*/
#endif
NULL, /*tp_getattro*/
NULL, /*tp_setattro*/
NULL, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
matrix_doc, /*tp_doc*/
(traverseproc)BaseMathObject_traverse, /* tp_traverse */
(inquiry)BaseMathObject_clear, /*tp_clear*/
(richcmpfunc)Matrix_richcmpr, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
NULL, /*tp_iter*/
NULL, /*tp_iternext*/
Matrix_methods, /*tp_methods*/
NULL, /*tp_members*/
Matrix_getseters, /*tp_getset*/
NULL, /*tp_base*/
NULL, /*tp_dict*/
NULL, /*tp_descr_get*/
NULL, /*tp_descr_set*/
0, /*tp_dictoffset*/
NULL, /*tp_init*/
NULL, /*tp_alloc*/
Matrix_new, /*tp_new*/
NULL, /*tp_free*/
NULL, /*tp_is_gc*/
NULL, /*tp_bases*/
NULL, /*tp_mro*/
NULL, /*tp_cache*/
NULL, /*tp_subclasses*/
NULL, /*tp_weaklist*/
NULL, /*tp_del*/
};
PyObject *Matrix_CreatePyObject(const float *mat,
const ushort num_col,
const ushort num_row,
PyTypeObject *base_type)
{
MatrixObject *self;
float *mat_alloc;
/* matrix objects can be any 2-4row x 2-4col matrix */
if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
PyErr_SetString(PyExc_RuntimeError,
"Matrix(): "
"row and column sizes must be between 2 and 4");
return NULL;
}
mat_alloc = PyMem_Malloc(num_col * num_row * sizeof(float));
if (UNLIKELY(mat_alloc == NULL)) {
PyErr_SetString(PyExc_MemoryError,
"Matrix(): "
"problem allocating data");
return NULL;
}
self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
if (self) {
self->matrix = mat_alloc;
self->num_col = num_col;
self->num_row = num_row;
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
if (mat) { /*if a float array passed*/
memcpy(self->matrix, mat, num_col * num_row * sizeof(float));
}
else if (num_col == num_row) {
/* or if no arguments are passed return identity matrix for square matrices */
matrix_identity_internal(self);
}
else {
/* otherwise zero everything */
memset(self->matrix, 0, num_col * num_row * sizeof(float));
}
self->flag = BASE_MATH_FLAG_DEFAULT;
}
else {
PyMem_Free(mat_alloc);
}
return (PyObject *)self;
}
PyObject *Matrix_CreatePyObject_wrap(float *mat,
const ushort num_col,
const ushort num_row,
PyTypeObject *base_type)
{
MatrixObject *self;
/* matrix objects can be any 2-4row x 2-4col matrix */
if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
PyErr_SetString(PyExc_RuntimeError,
"Matrix(): "
"row and column sizes must be between 2 and 4");
return NULL;
}
self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
if (self) {
self->num_col = num_col;
self->num_row = num_row;
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
self->matrix = mat;
self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
}
return (PyObject *)self;
}
PyObject *Matrix_CreatePyObject_cb(
PyObject *cb_user, const ushort num_col, const ushort num_row, uchar cb_type, uchar cb_subtype)
{
MatrixObject *self = (MatrixObject *)Matrix_CreatePyObject(NULL, num_col, num_row, NULL);
if (self) {
Py_INCREF(cb_user);
self->cb_user = cb_user;
self->cb_type = cb_type;
self->cb_subtype = cb_subtype;
PyObject_GC_Track(self);
}
return (PyObject *)self;
}
/**
* \param mat: Initialized matrix value to use in-place, allocated with #PyMem_Malloc
*/
PyObject *Matrix_CreatePyObject_alloc(float *mat,
const ushort num_col,
const ushort num_row,
PyTypeObject *base_type)
{
MatrixObject *self;
self = (MatrixObject *)Matrix_CreatePyObject_wrap(mat, num_col, num_row, base_type);
if (self) {
self->flag &= ~BASE_MATH_FLAG_IS_WRAP;
}
return (PyObject *)self;
}
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*/
static bool Matrix_ParseCheck(MatrixObject *pymat)
{
if (!MatrixObject_Check(pymat)) {
PyErr_Format(
PyExc_TypeError, "expected a mathutils.Matrix, not a %.200s", Py_TYPE(pymat)->tp_name);
return 0;
}
/* sets error */
if (BaseMath_ReadCallback(pymat) == -1) {
return 0;
}
return 1;
}
int Matrix_ParseAny(PyObject *o, void *p)
{
MatrixObject **pymat_p = p;
MatrixObject *pymat = (MatrixObject *)o;
if (!Matrix_ParseCheck(pymat)) {
return 0;
}
*pymat_p = pymat;
return 1;
}
int Matrix_Parse2x2(PyObject *o, void *p)
{
MatrixObject **pymat_p = p;
MatrixObject *pymat = (MatrixObject *)o;
if (!Matrix_ParseCheck(pymat)) {
return 0;
}
if ((pymat->num_col != 2) || (pymat->num_row != 2)) {
PyErr_SetString(PyExc_ValueError, "matrix must be 2x2");
return 0;
}
*pymat_p = pymat;
return 1;
}
int Matrix_Parse3x3(PyObject *o, void *p)
{
MatrixObject **pymat_p = p;
MatrixObject *pymat = (MatrixObject *)o;
if (!Matrix_ParseCheck(pymat)) {
return 0;
}
if ((pymat->num_col != 3) || (pymat->num_row != 3)) {
PyErr_SetString(PyExc_ValueError, "matrix must be 3x3");
return 0;
}
*pymat_p = pymat;
return 1;
}
int Matrix_Parse4x4(PyObject *o, void *p)
{
MatrixObject **pymat_p = p;
MatrixObject *pymat = (MatrixObject *)o;
if (!Matrix_ParseCheck(pymat)) {
return 0;
}
if ((pymat->num_col != 4) || (pymat->num_row != 4)) {
PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
return 0;
}
*pymat_p = pymat;
return 1;
}
/* ----------------------------------------------------------------------------
* special type for alternate access */
typedef struct {
PyObject_HEAD /* required python macro */
MatrixObject *matrix_user;
eMatrixAccess_t type;
} MatrixAccessObject;
static int MatrixAccess_traverse(MatrixAccessObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->matrix_user);
return 0;
}
static int MatrixAccess_clear(MatrixAccessObject *self)
{
Py_CLEAR(self->matrix_user);
return 0;
}
static void MatrixAccess_dealloc(MatrixAccessObject *self)
{
if (self->matrix_user) {
PyObject_GC_UnTrack(self);
MatrixAccess_clear(self);
}
Py_TYPE(self)->tp_free(self);
}
/* sequence access */
static int MatrixAccess_len(MatrixAccessObject *self)
{
return (self->type == MAT_ACCESS_ROW) ? self->matrix_user->num_row : self->matrix_user->num_col;
}
static PyObject *MatrixAccess_slice(MatrixAccessObject *self, int begin, int end)
{
PyObject *tuple;
int count;
/* row/col access */
MatrixObject *matrix_user = self->matrix_user;
int matrix_access_len;
PyObject *(*Matrix_item_new)(MatrixObject *, int);
if (self->type == MAT_ACCESS_ROW) {
matrix_access_len = matrix_user->num_row;
Matrix_item_new = Matrix_item_row;
}
else { /* MAT_ACCESS_ROW */
matrix_access_len = matrix_user->num_col;
Matrix_item_new = Matrix_item_col;
}
CLAMP(begin, 0, matrix_access_len);
if (end < 0) {
end = (matrix_access_len + 1) + end;
}
CLAMP(end, 0, matrix_access_len);
begin = MIN2(begin, end);
tuple = PyTuple_New(end - begin);
for (count = begin; count < end; count++) {
PyTuple_SET_ITEM(tuple, count - begin, Matrix_item_new(matrix_user, count));
}
return tuple;
}
static PyObject *MatrixAccess_subscript(MatrixAccessObject *self, PyObject *item)
{
MatrixObject *matrix_user = self->matrix_user;
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return NULL;
}
if (self->type == MAT_ACCESS_ROW) {
if (i < 0) {
i += matrix_user->num_row;
}
return Matrix_item_row(matrix_user, i);
}
else { /* MAT_ACCESS_ROW */
if (i < 0) {
i += matrix_user->num_col;
}
return Matrix_item_col(matrix_user, i);
}
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, MatrixAccess_len(self), &start, &stop, &step, &slicelength) <
0) {
return NULL;
}
if (slicelength <= 0) {
return PyTuple_New(0);
}
else if (step == 1) {
return MatrixAccess_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrix accessors");
return NULL;
}
}
else {
PyErr_Format(
PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return NULL;
}
}
static int MatrixAccess_ass_subscript(MatrixAccessObject *self, PyObject *item, PyObject *value)
{
MatrixObject *matrix_user = self->matrix_user;
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
if (self->type == MAT_ACCESS_ROW) {
if (i < 0) {
i += matrix_user->num_row;
}
return Matrix_ass_item_row(matrix_user, i, value);
}
else { /* MAT_ACCESS_ROW */
if (i < 0) {
i += matrix_user->num_col;
}
return Matrix_ass_item_col(matrix_user, i, value);
}
}
/* TODO, slice */
else {
PyErr_Format(
PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return -1;
}
}
static PyObject *MatrixAccess_iter(MatrixAccessObject *self)
{
/* Try get values from a collection */
PyObject *ret;
PyObject *iter = NULL;
ret = MatrixAccess_slice(self, 0, MATRIX_MAX_DIM);
/* we know this is a tuple so no need to PyIter_Check
* otherwise it could be NULL (unlikely) if conversion failed */
if (ret) {
iter = PyObject_GetIter(ret);
Py_DECREF(ret);
}
return iter;
}
static PyMappingMethods MatrixAccess_AsMapping = {
(lenfunc)MatrixAccess_len,
(binaryfunc)MatrixAccess_subscript,
(objobjargproc)MatrixAccess_ass_subscript,
};
PyTypeObject matrix_access_Type = {
PyVarObject_HEAD_INIT(NULL, 0) "MatrixAccess", /*tp_name*/
sizeof(MatrixAccessObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)MatrixAccess_dealloc, /*tp_dealloc*/
(printfunc)NULL, /*tp_print*/
NULL, /*tp_getattr*/
NULL, /*tp_setattr*/
NULL, /*tp_compare*/
NULL, /*tp_repr*/
NULL, /*tp_as_number*/
NULL /*&MatrixAccess_SeqMethods*/ /* TODO */, /*tp_as_sequence*/
&MatrixAccess_AsMapping, /*tp_as_mapping*/
NULL, /*tp_hash*/
NULL, /*tp_call*/
NULL, /*tp_str*/
NULL, /*tp_getattro*/
NULL, /*tp_setattro*/
NULL, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
NULL, /*tp_doc*/
(traverseproc)MatrixAccess_traverse, /*tp_traverse*/
(inquiry)MatrixAccess_clear, /*tp_clear*/
NULL /* (richcmpfunc)MatrixAccess_richcmpr */ /* TODO*/, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
(getiterfunc)MatrixAccess_iter, /* getiterfunc tp_iter; */
};
static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type)
{
MatrixAccessObject *matrix_access = (MatrixAccessObject *)PyObject_GC_New(MatrixObject,
&matrix_access_Type);
matrix_access->matrix_user = matrix;
Py_INCREF(matrix);
matrix_access->type = type;
return (PyObject *)matrix_access;
}
/* end special access
* -------------------------------------------------------------------------- */
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c
index 39d84c1ac96..7ce0ea5f249 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.c
+++ b/source/blender/python/mathutils/mathutils_Quaternion.c
@@ -1,1670 +1,1672 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
#ifndef MATH_STANDALONE
# include "BLI_dynstr.h"
#endif
#define QUAT_SIZE 4
-static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self);
+static PyObject *quat__apply_to_copy(PyObject *(*quat_func)(QuaternionObject *),
+ QuaternionObject *self);
static void quat__axis_angle_sanitize(float axis[3], float *angle);
static PyObject *Quaternion_copy(QuaternionObject *self);
static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args);
/* -----------------------------METHODS------------------------------ */
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Quaternion_to_tuple_ext(QuaternionObject *self, int ndigits)
{
PyObject *ret;
int i;
ret = PyTuple_New(QUAT_SIZE);
if (ndigits >= 0) {
for (i = 0; i < QUAT_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->quat[i], ndigits)));
}
}
else {
for (i = 0; i < QUAT_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->quat[i]));
}
}
return ret;
}
PyDoc_STRVAR(Quaternion_to_euler_doc,
".. method:: to_euler(order, euler_compat)\n"
"\n"
" Return Euler representation of the quaternion.\n"
"\n"
" :arg order: Optional rotation order argument in\n"
" ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
" :type order: string\n"
" :arg euler_compat: Optional euler argument the new euler will be made\n"
" compatible with (no axis flipping between them).\n"
" Useful for converting a series of matrices to animation curves.\n"
" :type euler_compat: :class:`Euler`\n"
" :return: Euler representation of the quaternion.\n"
" :rtype: :class:`Euler`\n");
static PyObject *Quaternion_to_euler(QuaternionObject *self, PyObject *args)
{
float tquat[4];
float eul[3];
const char *order_str = NULL;
short order = EULER_ORDER_XYZ;
EulerObject *eul_compat = NULL;
if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (order_str) {
order = euler_order_from_string(order_str, "Matrix.to_euler()");
if (order == -1) {
return NULL;
}
}
normalize_qt_qt(tquat, self->quat);
if (eul_compat) {
if (BaseMath_ReadCallback(eul_compat) == -1) {
return NULL;
}
if (order == EULER_ORDER_XYZ) {
quat_to_compatible_eul(eul, eul_compat->eul, tquat);
}
else {
quat_to_compatible_eulO(eul, eul_compat->eul, order, tquat);
}
}
else {
if (order == EULER_ORDER_XYZ) {
quat_to_eul(eul, tquat);
}
else {
quat_to_eulO(eul, order, tquat);
}
}
return Euler_CreatePyObject(eul, order, NULL);
}
PyDoc_STRVAR(Quaternion_to_matrix_doc,
".. method:: to_matrix()\n"
"\n"
" Return a matrix representation of the quaternion.\n"
"\n"
" :return: A 3x3 rotation matrix representation of the quaternion.\n"
" :rtype: :class:`Matrix`\n");
static PyObject *Quaternion_to_matrix(QuaternionObject *self)
{
float mat[9]; /* all values are set */
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
quat_to_mat3((float(*)[3])mat, self->quat);
return Matrix_CreatePyObject(mat, 3, 3, NULL);
}
PyDoc_STRVAR(Quaternion_to_axis_angle_doc,
".. method:: to_axis_angle()\n"
"\n"
" Return the axis, angle representation of the quaternion.\n"
"\n"
" :return: axis, angle.\n"
" :rtype: (:class:`Vector`, float) pair\n");
static PyObject *Quaternion_to_axis_angle(QuaternionObject *self)
{
PyObject *ret;
float tquat[4];
float axis[3];
float angle;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
normalize_qt_qt(tquat, self->quat);
quat_to_axis_angle(axis, &angle, tquat);
quat__axis_angle_sanitize(axis, &angle);
ret = PyTuple_New(2);
PyTuple_SET_ITEMS(ret, Vector_CreatePyObject(axis, 3, NULL), PyFloat_FromDouble(angle));
return ret;
}
PyDoc_STRVAR(Quaternion_to_swing_twist_doc,
".. method:: to_swing_twist(axis)\n"
"\n"
" Split the rotation into a swing quaternion with the specified\n"
" axis fixed at zero, and the remaining twist rotation angle.\n"
"\n"
" :arg axis: twist axis as a string in ['X', 'Y', 'Z']\n"
" :return: swing, twist angle.\n"
" :rtype: (:class:`Quaternion`, float) pair\n");
static PyObject *Quaternion_to_swing_twist(QuaternionObject *self, PyObject *axis_arg)
{
PyObject *ret;
const char *axis_str = NULL;
float swing[4], twist;
int axis;
if (axis_arg && PyUnicode_Check(axis_arg)) {
axis_str = _PyUnicode_AsString(axis_arg);
}
if (axis_str && axis_str[0] >= 'X' && axis_str[0] <= 'Z' && axis_str[1] == 0) {
axis = axis_str[0] - 'X';
}
else {
PyErr_SetString(PyExc_ValueError,
"Quaternion.to_swing_twist(): "
"the axis argument must be "
"a string in 'X', 'Y', 'Z'");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
twist = quat_split_swing_and_twist(self->quat, axis, swing, NULL);
ret = PyTuple_New(2);
PyTuple_SET_ITEMS(
ret, Quaternion_CreatePyObject(swing, Py_TYPE(self)), PyFloat_FromDouble(twist));
return ret;
}
PyDoc_STRVAR(
Quaternion_to_exponential_map_doc,
".. method:: to_exponential_map()\n"
"\n"
" Return the exponential map representation of the quaternion.\n"
"\n"
" This representation consist of the rotation axis multiplied by the rotation angle.\n"
" Such a representation is useful for interpolation between multiple orientations.\n"
"\n"
" :return: exponential map.\n"
" :rtype: :class:`Vector` of size 3\n"
"\n"
" To convert back to a quaternion, pass it to the :class:`Quaternion` constructor.\n");
static PyObject *Quaternion_to_exponential_map(QuaternionObject *self)
{
float expmap[3];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
quat_to_expmap(expmap, self->quat);
return Vector_CreatePyObject(expmap, 3, NULL);
}
PyDoc_STRVAR(Quaternion_cross_doc,
".. method:: cross(other)\n"
"\n"
" Return the cross product of this quaternion and another.\n"
"\n"
" :arg other: The other quaternion to perform the cross product with.\n"
" :type other: :class:`Quaternion`\n"
" :return: The cross product.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_cross(QuaternionObject *self, PyObject *value)
{
float quat[QUAT_SIZE], tquat[QUAT_SIZE];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(
tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.cross(other), invalid 'other' arg") ==
-1) {
return NULL;
}
mul_qt_qtqt(quat, self->quat, tquat);
return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_dot_doc,
".. method:: dot(other)\n"
"\n"
" Return the dot product of this quaternion and another.\n"
"\n"
" :arg other: The other quaternion to perform the dot product with.\n"
" :type other: :class:`Quaternion`\n"
" :return: The dot product.\n"
" :rtype: float\n");
static PyObject *Quaternion_dot(QuaternionObject *self, PyObject *value)
{
float tquat[QUAT_SIZE];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(
tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.dot(other), invalid 'other' arg") ==
-1) {
return NULL;
}
return PyFloat_FromDouble(dot_qtqt(self->quat, tquat));
}
PyDoc_STRVAR(Quaternion_rotation_difference_doc,
".. function:: rotation_difference(other)\n"
"\n"
" Returns a quaternion representing the rotational difference.\n"
"\n"
" :arg other: second quaternion.\n"
" :type other: :class:`Quaternion`\n"
" :return: the rotational difference between the two quat rotations.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_rotation_difference(QuaternionObject *self, PyObject *value)
{
float tquat[QUAT_SIZE], quat[QUAT_SIZE];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(tquat,
QUAT_SIZE,
QUAT_SIZE,
value,
"Quaternion.difference(other), invalid 'other' arg") == -1) {
return NULL;
}
rotation_between_quats_to_quat(quat, self->quat, tquat);
return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_slerp_doc,
".. function:: slerp(other, factor)\n"
"\n"
" Returns the interpolation of two quaternions.\n"
"\n"
" :arg other: value to interpolate with.\n"
" :type other: :class:`Quaternion`\n"
" :arg factor: The interpolation value in [0.0, 1.0].\n"
" :type factor: float\n"
" :return: The interpolated rotation.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_slerp(QuaternionObject *self, PyObject *args)
{
PyObject *value;
float tquat[QUAT_SIZE], quat[QUAT_SIZE], fac;
if (!PyArg_ParseTuple(args, "Of:slerp", &value, &fac)) {
PyErr_SetString(PyExc_TypeError,
"quat.slerp(): "
"expected Quaternion types and float");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(
tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.slerp(other), invalid 'other' arg") ==
-1) {
return NULL;
}
if (fac > 1.0f || fac < 0.0f) {
PyErr_SetString(PyExc_ValueError,
"quat.slerp(): "
"interpolation factor must be between 0.0 and 1.0");
return NULL;
}
interp_qt_qtqt(quat, self->quat, tquat, fac);
return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_rotate_doc,
".. method:: rotate(other)\n"
"\n"
" Rotates the quaternion by another mathutils value.\n"
"\n"
" :arg other: rotation component of mathutils value\n"
" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n");
static PyObject *Quaternion_rotate(QuaternionObject *self, PyObject *value)
{
float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
float tquat[4], length;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (mathutils_any_to_rotmat(other_rmat, value, "Quaternion.rotate(value)") == -1) {
return NULL;
}
length = normalize_qt_qt(tquat, self->quat);
quat_to_mat3(self_rmat, tquat);
mul_m3_m3m3(rmat, other_rmat, self_rmat);
mat3_to_quat(self->quat, rmat);
mul_qt_fl(self->quat, length); /* maintain length after rotating */
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_make_compatible_doc,
".. method:: make_compatible(other)\n"
"\n"
" Make this quaternion compatible with another,\n"
" so interpolating between them works as intended.\n");
static PyObject *Quaternion_make_compatible(QuaternionObject *self, PyObject *value)
{
float quat[QUAT_SIZE];
float tquat[QUAT_SIZE];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (mathutils_array_parse(tquat,
QUAT_SIZE,
QUAT_SIZE,
value,
"Quaternion.make_compatible(other), invalid 'other' arg") == -1) {
return NULL;
}
/* Can only operate on unit length quaternions. */
const float quat_len = normalize_qt_qt(quat, self->quat);
quat_to_compatible_quat(self->quat, quat, tquat);
mul_qt_fl(self->quat, quat_len);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
/* ----------------------------Quaternion.normalize()---------------- */
/* Normalize the quaternion. This may change the angle as well as the
* rotation axis, as all of (w, x, y, z) are scaled. */
PyDoc_STRVAR(Quaternion_normalize_doc,
".. function:: normalize()\n"
"\n"
" Normalize the quaternion.\n");
static PyObject *Quaternion_normalize(QuaternionObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
normalize_qt(self->quat);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_normalized_doc,
".. function:: normalized()\n"
"\n"
" Return a new normalized quaternion.\n"
"\n"
" :return: a normalized copy.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_normalized(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
+ return quat__apply_to_copy(Quaternion_normalize, self);
}
PyDoc_STRVAR(Quaternion_invert_doc,
".. function:: invert()\n"
"\n"
" Set the quaternion to its inverse.\n");
static PyObject *Quaternion_invert(QuaternionObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
invert_qt(self->quat);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_inverted_doc,
".. function:: inverted()\n"
"\n"
" Return a new, inverted quaternion.\n"
"\n"
" :return: the inverted value.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_inverted(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
+ return quat__apply_to_copy(Quaternion_invert, self);
}
PyDoc_STRVAR(Quaternion_identity_doc,
".. function:: identity()\n"
"\n"
" Set the quaternion to an identity quaternion.\n"
"\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_identity(QuaternionObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
unit_qt(self->quat);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_negate_doc,
".. function:: negate()\n"
"\n"
" Set the quaternion to its negative.\n"
"\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_negate(QuaternionObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
mul_qt_fl(self->quat, -1.0f);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_conjugate_doc,
".. function:: conjugate()\n"
"\n"
" Set the quaternion to its conjugate (negate x, y, z).\n");
static PyObject *Quaternion_conjugate(QuaternionObject *self)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
conjugate_qt(self->quat);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_conjugated_doc,
".. function:: conjugated()\n"
"\n"
" Return a new conjugated quaternion.\n"
"\n"
" :return: a new quaternion.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_conjugated(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
+ return quat__apply_to_copy(Quaternion_conjugate, self);
}
PyDoc_STRVAR(Quaternion_copy_doc,
".. function:: copy()\n"
"\n"
" Returns a copy of this quaternion.\n"
"\n"
" :return: A copy of the quaternion.\n"
" :rtype: :class:`Quaternion`\n"
"\n"
" .. note:: use this to get a copy of a wrapped quaternion with\n"
" no reference to the original data.\n");
static PyObject *Quaternion_copy(QuaternionObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Quaternion_CreatePyObject(self->quat, Py_TYPE(self));
}
static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args)
{
if (!PyC_CheckArgs_DeepCopy(args)) {
return NULL;
}
return Quaternion_copy(self);
}
/* print the object to screen */
static PyObject *Quaternion_repr(QuaternionObject *self)
{
PyObject *ret, *tuple;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
tuple = Quaternion_to_tuple_ext(self, -1);
ret = PyUnicode_FromFormat("Quaternion(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Quaternion_str(QuaternionObject *self)
{
DynStr *ds;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
ds = BLI_dynstr_new();
BLI_dynstr_appendf(ds,
"<Quaternion (w=%.4f, x=%.4f, y=%.4f, z=%.4f)>",
self->quat[0],
self->quat[1],
self->quat[2],
self->quat[3]);
return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
static PyObject *Quaternion_richcmpr(PyObject *a, PyObject *b, int op)
{
PyObject *res;
int ok = -1; /* zero is true */
if (QuaternionObject_Check(a) && QuaternionObject_Check(b)) {
QuaternionObject *quatA = (QuaternionObject *)a;
QuaternionObject *quatB = (QuaternionObject *)b;
if (BaseMath_ReadCallback(quatA) == -1 || BaseMath_ReadCallback(quatB) == -1) {
return NULL;
}
ok = (EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1)) ? 0 : -1;
}
switch (op) {
case Py_NE:
ok = !ok;
ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
case Py_LT:
case Py_LE:
case Py_GT:
case Py_GE:
res = Py_NotImplemented;
break;
default:
PyErr_BadArgument();
return NULL;
}
return Py_INCREF_RET(res);
}
static Py_hash_t Quaternion_hash(QuaternionObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (BaseMathObject_Prepare_ForHash(self) == -1) {
return -1;
}
return mathutils_array_hash(self->quat, QUAT_SIZE);
}
/* ---------------------SEQUENCE PROTOCOLS------------------------ */
/* ----------------------------len(object)------------------------ */
/* sequence length */
static int Quaternion_len(QuaternionObject *UNUSED(self))
{
return QUAT_SIZE;
}
/* ----------------------------object[]--------------------------- */
/* sequence accessor (get) */
static PyObject *Quaternion_item(QuaternionObject *self, int i)
{
if (i < 0) {
i = QUAT_SIZE - i;
}
if (i < 0 || i >= QUAT_SIZE) {
PyErr_SetString(PyExc_IndexError,
"quaternion[attribute]: "
"array index out of range");
return NULL;
}
if (BaseMath_ReadIndexCallback(self, i) == -1) {
return NULL;
}
return PyFloat_FromDouble(self->quat[i]);
}
/* ----------------------------object[]------------------------- */
/* sequence accessor (set) */
static int Quaternion_ass_item(QuaternionObject *self, int i, PyObject *ob)
{
float f;
if (BaseMath_Prepare_ForWrite(self) == -1) {
return -1;
}
f = (float)PyFloat_AsDouble(ob);
if (f == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"quaternion[index] = x: "
"assigned value not a number");
return -1;
}
if (i < 0) {
i = QUAT_SIZE - i;
}
if (i < 0 || i >= QUAT_SIZE) {
PyErr_SetString(PyExc_IndexError,
"quaternion[attribute] = x: "
"array assignment index out of range");
return -1;
}
self->quat[i] = f;
if (BaseMath_WriteIndexCallback(self, i) == -1) {
return -1;
}
return 0;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (get) */
static PyObject *Quaternion_slice(QuaternionObject *self, int begin, int end)
{
PyObject *tuple;
int count;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
CLAMP(begin, 0, QUAT_SIZE);
if (end < 0) {
end = (QUAT_SIZE + 1) + end;
}
CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin, end);
tuple = PyTuple_New(end - begin);
for (count = begin; count < end; count++) {
PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->quat[count]));
}
return tuple;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (set) */
static int Quaternion_ass_slice(QuaternionObject *self, int begin, int end, PyObject *seq)
{
int i, size;
float quat[QUAT_SIZE];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
CLAMP(begin, 0, QUAT_SIZE);
if (end < 0) {
end = (QUAT_SIZE + 1) + end;
}
CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin, end);
if ((size = mathutils_array_parse(
quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1) {
return -1;
}
if (size != (end - begin)) {
PyErr_SetString(PyExc_ValueError,
"quaternion[begin:end] = []: "
"size mismatch in slice assignment");
return -1;
}
/* parsed well - now set in vector */
for (i = 0; i < size; i++) {
self->quat[begin + i] = quat[i];
}
(void)BaseMath_WriteCallback(self);
return 0;
}
static PyObject *Quaternion_subscript(QuaternionObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return NULL;
}
if (i < 0) {
i += QUAT_SIZE;
}
return Quaternion_item(self, i);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0) {
return NULL;
}
if (slicelength <= 0) {
return PyTuple_New(0);
}
else if (step == 1) {
return Quaternion_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with quaternions");
return NULL;
}
}
else {
PyErr_Format(PyExc_TypeError,
"quaternion indices must be integers, not %.200s",
Py_TYPE(item)->tp_name);
return NULL;
}
}
static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
if (i < 0) {
i += QUAT_SIZE;
}
return Quaternion_ass_item(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0) {
return -1;
}
if (step == 1) {
return Quaternion_ass_slice(self, start, stop, value);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with quaternion");
return -1;
}
}
else {
PyErr_Format(PyExc_TypeError,
"quaternion indices must be integers, not %.200s",
Py_TYPE(item)->tp_name);
return -1;
}
}
/* ------------------------NUMERIC PROTOCOLS---------------------- */
/* ------------------------obj + obj------------------------------ */
/* addition */
static PyObject *Quaternion_add(PyObject *q1, PyObject *q2)
{
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
PyErr_Format(PyExc_TypeError,
"Quaternion addition: (%s + %s) "
"invalid type for this operation",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
quat1 = (QuaternionObject *)q1;
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
}
/* ------------------------obj - obj------------------------------ */
/* subtraction */
static PyObject *Quaternion_sub(PyObject *q1, PyObject *q2)
{
int x;
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
PyErr_Format(PyExc_TypeError,
"Quaternion subtraction: (%s - %s) "
"invalid type for this operation",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
quat1 = (QuaternionObject *)q1;
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
for (x = 0; x < QUAT_SIZE; x++) {
quat[x] = quat1->quat[x] - quat2->quat[x];
}
return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
}
static PyObject *quat_mul_float(QuaternionObject *quat, const float scalar)
{
float tquat[4];
copy_qt_qt(tquat, quat->quat);
mul_qt_fl(tquat, scalar);
return Quaternion_CreatePyObject(tquat, Py_TYPE(quat));
}
/*------------------------obj * obj------------------------------
* multiplication */
static PyObject *Quaternion_mul(PyObject *q1, PyObject *q2)
{
float scalar;
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (QuaternionObject_Check(q1)) {
quat1 = (QuaternionObject *)q1;
if (BaseMath_ReadCallback(quat1) == -1) {
return NULL;
}
}
if (QuaternionObject_Check(q2)) {
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
}
if (quat1 && quat2) { /* QUAT * QUAT (element-wise product) */
#ifdef USE_MATHUTILS_ELEM_MUL
float quat[QUAT_SIZE];
mul_vn_vnvn(quat, quat1->quat, quat2->quat, QUAT_SIZE);
return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
#endif
}
/* the only case this can happen (for a supported type is "FLOAT * QUAT") */
else if (quat2) { /* FLOAT * QUAT */
if (((scalar = PyFloat_AsDouble(q1)) == -1.0f && PyErr_Occurred()) == 0) {
return quat_mul_float(quat2, scalar);
}
}
else if (quat1) { /* QUAT * FLOAT */
if ((((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
return quat_mul_float(quat1, scalar);
}
}
PyErr_Format(PyExc_TypeError,
"Element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
/*------------------------obj *= obj------------------------------
* in-place multiplication */
static PyObject *Quaternion_imul(PyObject *q1, PyObject *q2)
{
float scalar;
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (QuaternionObject_Check(q1)) {
quat1 = (QuaternionObject *)q1;
if (BaseMath_ReadCallback(quat1) == -1) {
return NULL;
}
}
if (QuaternionObject_Check(q2)) {
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
}
if (quat1 && quat2) { /* QUAT *= QUAT (inplace element-wise product) */
#ifdef USE_MATHUTILS_ELEM_MUL
mul_vn_vn(quat1->quat, quat2->quat, QUAT_SIZE);
#else
PyErr_Format(PyExc_TypeError,
"In place element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
#endif
}
else if (quat1 && (((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
/* QUAT *= FLOAT */
mul_qt_fl(quat1->quat, scalar);
}
else {
PyErr_Format(PyExc_TypeError,
"Element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
(void)BaseMath_WriteCallback(quat1);
Py_INCREF(q1);
return q1;
}
/*------------------------obj @ obj------------------------------
* quaternion multiplication */
static PyObject *Quaternion_matmul(PyObject *q1, PyObject *q2)
{
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (QuaternionObject_Check(q1)) {
quat1 = (QuaternionObject *)q1;
if (BaseMath_ReadCallback(quat1) == -1) {
return NULL;
}
}
if (QuaternionObject_Check(q2)) {
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
}
if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
mul_qt_qtqt(quat, quat1->quat, quat2->quat);
return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
}
else if (quat1) {
/* QUAT @ VEC */
if (VectorObject_Check(q2)) {
VectorObject *vec2 = (VectorObject *)q2;
float tvec[3];
if (vec2->size != 3) {
PyErr_SetString(PyExc_ValueError,
"Vector multiplication: "
"only 3D vector rotations (with quats) "
"currently supported");
return NULL;
}
if (BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
copy_v3_v3(tvec, vec2->vec);
mul_qt_v3(quat1->quat, tvec);
return Vector_CreatePyObject(tvec, 3, Py_TYPE(vec2));
}
}
PyErr_Format(PyExc_TypeError,
"Quaternion multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
/*------------------------obj @= obj------------------------------
* in-place quaternion multiplication */
static PyObject *Quaternion_imatmul(PyObject *q1, PyObject *q2)
{
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if (QuaternionObject_Check(q1)) {
quat1 = (QuaternionObject *)q1;
if (BaseMath_ReadCallback(quat1) == -1) {
return NULL;
}
}
if (QuaternionObject_Check(q2)) {
quat2 = (QuaternionObject *)q2;
if (BaseMath_ReadCallback(quat2) == -1) {
return NULL;
}
}
if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
mul_qt_qtqt(quat, quat1->quat, quat2->quat);
copy_qt_qt(quat1->quat, quat);
}
else {
PyErr_Format(PyExc_TypeError,
"In place quaternion multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(q1)->tp_name,
Py_TYPE(q2)->tp_name);
return NULL;
}
(void)BaseMath_WriteCallback(quat1);
Py_INCREF(q1);
return q1;
}
/* -obj
* returns the negative of this object*/
static PyObject *Quaternion_neg(QuaternionObject *self)
{
float tquat[QUAT_SIZE];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
negate_v4_v4(tquat, self->quat);
return Quaternion_CreatePyObject(tquat, Py_TYPE(self));
}
/* -----------------PROTOCOL DECLARATIONS-------------------------- */
static PySequenceMethods Quaternion_SeqMethods = {
(lenfunc)Quaternion_len, /* sq_length */
(binaryfunc)NULL, /* sq_concat */
(ssizeargfunc)NULL, /* sq_repeat */
(ssizeargfunc)Quaternion_item, /* sq_item */
(ssizessizeargfunc)NULL, /* sq_slice, deprecated */
(ssizeobjargproc)Quaternion_ass_item, /* sq_ass_item */
(ssizessizeobjargproc)NULL, /* sq_ass_slice, deprecated */
(objobjproc)NULL, /* sq_contains */
(binaryfunc)NULL, /* sq_inplace_concat */
(ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyMappingMethods Quaternion_AsMapping = {
(lenfunc)Quaternion_len,
(binaryfunc)Quaternion_subscript,
(objobjargproc)Quaternion_ass_subscript,
};
static PyNumberMethods Quaternion_NumMethods = {
(binaryfunc)Quaternion_add, /*nb_add*/
(binaryfunc)Quaternion_sub, /*nb_subtract*/
(binaryfunc)Quaternion_mul, /*nb_multiply*/
NULL, /*nb_remainder*/
NULL, /*nb_divmod*/
NULL, /*nb_power*/
(unaryfunc)Quaternion_neg, /*nb_negative*/
(unaryfunc)Quaternion_copy, /*tp_positive*/
(unaryfunc)0, /*tp_absolute*/
(inquiry)0, /*tp_bool*/
(unaryfunc)0, /*nb_invert*/
NULL, /*nb_lshift*/
(binaryfunc)0, /*nb_rshift*/
NULL, /*nb_and*/
NULL, /*nb_xor*/
NULL, /*nb_or*/
NULL, /*nb_int*/
NULL, /*nb_reserved*/
NULL, /*nb_float*/
NULL, /* nb_inplace_add */
NULL, /* nb_inplace_subtract */
(binaryfunc)Quaternion_imul, /* nb_inplace_multiply */
NULL, /* nb_inplace_remainder */
NULL, /* nb_inplace_power */
NULL, /* nb_inplace_lshift */
NULL, /* nb_inplace_rshift */
NULL, /* nb_inplace_and */
NULL, /* nb_inplace_xor */
NULL, /* nb_inplace_or */
NULL, /* nb_floor_divide */
NULL, /* nb_true_divide */
NULL, /* nb_inplace_floor_divide */
NULL, /* nb_inplace_true_divide */
NULL, /* nb_index */
(binaryfunc)Quaternion_matmul, /* nb_matrix_multiply */
(binaryfunc)Quaternion_imatmul, /* nb_inplace_matrix_multiply */
};
PyDoc_STRVAR(Quaternion_axis_doc, "Quaternion axis value.\n\n:type: float");
static PyObject *Quaternion_axis_get(QuaternionObject *self, void *type)
{
return Quaternion_item(self, POINTER_AS_INT(type));
}
static int Quaternion_axis_set(QuaternionObject *self, PyObject *value, void *type)
{
return Quaternion_ass_item(self, POINTER_AS_INT(type), value);
}
PyDoc_STRVAR(Quaternion_magnitude_doc, "Size of the quaternion (read-only).\n\n:type: float");
static PyObject *Quaternion_magnitude_get(QuaternionObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return PyFloat_FromDouble(sqrtf(dot_qtqt(self->quat, self->quat)));
}
PyDoc_STRVAR(Quaternion_angle_doc, "Angle of the quaternion.\n\n:type: float");
static PyObject *Quaternion_angle_get(QuaternionObject *self, void *UNUSED(closure))
{
float tquat[4];
float angle;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
normalize_qt_qt(tquat, self->quat);
angle = 2.0f * saacos(tquat[0]);
quat__axis_angle_sanitize(NULL, &angle);
return PyFloat_FromDouble(angle);
}
static int Quaternion_angle_set(QuaternionObject *self, PyObject *value, void *UNUSED(closure))
{
float tquat[4];
float len;
float axis[3], angle_dummy;
float angle;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
len = normalize_qt_qt(tquat, self->quat);
quat_to_axis_angle(axis, &angle_dummy, tquat);
angle = PyFloat_AsDouble(value);
if (angle == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "Quaternion.angle = value: float expected");
return -1;
}
angle = angle_wrap_rad(angle);
quat__axis_angle_sanitize(axis, &angle);
axis_angle_to_quat(self->quat, axis, angle);
mul_qt_fl(self->quat, len);
if (BaseMath_WriteCallback(self) == -1) {
return -1;
}
return 0;
}
PyDoc_STRVAR(Quaternion_axis_vector_doc, "Quaternion axis as a vector.\n\n:type: :class:`Vector`");
static PyObject *Quaternion_axis_vector_get(QuaternionObject *self, void *UNUSED(closure))
{
float tquat[4];
float axis[3];
float angle_dummy;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
normalize_qt_qt(tquat, self->quat);
quat_to_axis_angle(axis, &angle_dummy, tquat);
quat__axis_angle_sanitize(axis, NULL);
return Vector_CreatePyObject(axis, 3, NULL);
}
static int Quaternion_axis_vector_set(QuaternionObject *self,
PyObject *value,
void *UNUSED(closure))
{
float tquat[4];
float len;
float axis[3];
float angle;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
len = normalize_qt_qt(tquat, self->quat);
quat_to_axis_angle(axis, &angle, tquat); /* axis value is unused */
if (mathutils_array_parse(axis, 3, 3, value, "quat.axis = other") == -1) {
return -1;
}
quat__axis_angle_sanitize(axis, &angle);
axis_angle_to_quat(self->quat, axis, angle);
mul_qt_fl(self->quat, len);
if (BaseMath_WriteCallback(self) == -1) {
return -1;
}
return 0;
}
/* ----------------------------------mathutils.Quaternion() -------------- */
static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *seq = NULL;
double angle = 0.0f;
float quat[QUAT_SIZE];
unit_qt(quat);
if (kwds && PyDict_Size(kwds)) {
PyErr_SetString(PyExc_TypeError,
"mathutils.Quaternion(): "
"takes no keyword args");
return NULL;
}
if (!PyArg_ParseTuple(args, "|Od:mathutils.Quaternion", &seq, &angle)) {
return NULL;
}
switch (PyTuple_GET_SIZE(args)) {
case 0:
break;
case 1: {
int size;
if ((size = mathutils_array_parse(quat, 3, QUAT_SIZE, seq, "mathutils.Quaternion()")) ==
-1) {
return NULL;
}
if (size == 4) {
/* 4d: Quaternion (common case) */
}
else {
/* 3d: Interpret as exponential map */
BLI_assert(size == 3);
expmap_to_quat(quat, quat);
}
break;
}
case 2: {
float axis[3];
if (mathutils_array_parse(axis, 3, 3, seq, "mathutils.Quaternion()") == -1) {
return NULL;
}
angle = angle_wrap_rad(angle); /* clamp because of precision issues */
axis_angle_to_quat(quat, axis, angle);
break;
/* PyArg_ParseTuple assures no more than 2 */
}
}
return Quaternion_CreatePyObject(quat, type);
}
-static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self)
+static PyObject *quat__apply_to_copy(PyObject *(*quat_func)(QuaternionObject *),
+ QuaternionObject *self)
{
PyObject *ret = Quaternion_copy(self);
- PyObject *ret_dummy = quat_func(ret);
+ PyObject *ret_dummy = quat_func((QuaternionObject *)ret);
if (ret_dummy) {
Py_DECREF(ret_dummy);
return ret;
}
else { /* error */
Py_DECREF(ret);
return NULL;
}
}
/* axis vector suffers from precision errors, use this function to ensure */
static void quat__axis_angle_sanitize(float axis[3], float *angle)
{
if (axis) {
if (is_zero_v3(axis) || !isfinite(axis[0]) || !isfinite(axis[1]) || !isfinite(axis[2])) {
axis[0] = 1.0f;
axis[1] = 0.0f;
axis[2] = 0.0f;
}
else if (EXPP_FloatsAreEqual(axis[0], 0.0f, 10) && EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
EXPP_FloatsAreEqual(axis[2], 0.0f, 10)) {
axis[0] = 1.0f;
}
}
if (angle) {
if (!isfinite(*angle)) {
*angle = 0.0f;
}
}
}
/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Quaternion_methods[] = {
/* in place only */
{"identity", (PyCFunction)Quaternion_identity, METH_NOARGS, Quaternion_identity_doc},
{"negate", (PyCFunction)Quaternion_negate, METH_NOARGS, Quaternion_negate_doc},
/* operate on original or copy */
{"conjugate", (PyCFunction)Quaternion_conjugate, METH_NOARGS, Quaternion_conjugate_doc},
{"conjugated", (PyCFunction)Quaternion_conjugated, METH_NOARGS, Quaternion_conjugated_doc},
{"invert", (PyCFunction)Quaternion_invert, METH_NOARGS, Quaternion_invert_doc},
{"inverted", (PyCFunction)Quaternion_inverted, METH_NOARGS, Quaternion_inverted_doc},
{"normalize", (PyCFunction)Quaternion_normalize, METH_NOARGS, Quaternion_normalize_doc},
{"normalized", (PyCFunction)Quaternion_normalized, METH_NOARGS, Quaternion_normalized_doc},
/* return converted representation */
{"to_euler", (PyCFunction)Quaternion_to_euler, METH_VARARGS, Quaternion_to_euler_doc},
{"to_matrix", (PyCFunction)Quaternion_to_matrix, METH_NOARGS, Quaternion_to_matrix_doc},
{"to_axis_angle",
(PyCFunction)Quaternion_to_axis_angle,
METH_NOARGS,
Quaternion_to_axis_angle_doc},
{"to_swing_twist",
(PyCFunction)Quaternion_to_swing_twist,
METH_O,
Quaternion_to_swing_twist_doc},
{"to_exponential_map",
(PyCFunction)Quaternion_to_exponential_map,
METH_NOARGS,
Quaternion_to_exponential_map_doc},
/* operation between 2 or more types */
{"cross", (PyCFunction)Quaternion_cross, METH_O, Quaternion_cross_doc},
{"dot", (PyCFunction)Quaternion_dot, METH_O, Quaternion_dot_doc},
{"rotation_difference",
(PyCFunction)Quaternion_rotation_difference,
METH_O,
Quaternion_rotation_difference_doc},
{"slerp", (PyCFunction)Quaternion_slerp, METH_VARARGS, Quaternion_slerp_doc},
{"rotate", (PyCFunction)Quaternion_rotate, METH_O, Quaternion_rotate_doc},
{"make_compatible",
(PyCFunction)Quaternion_make_compatible,
METH_O,
Quaternion_make_compatible_doc},
/* base-math methods */
{"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
{"copy", (PyCFunction)Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
{"__copy__", (PyCFunction)Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
{"__deepcopy__", (PyCFunction)Quaternion_deepcopy, METH_VARARGS, Quaternion_copy_doc},
{NULL, NULL, 0, NULL},
};
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Quaternion_getseters[] = {
{"w",
(getter)Quaternion_axis_get,
(setter)Quaternion_axis_set,
Quaternion_axis_doc,
(void *)0},
{"x",
(getter)Quaternion_axis_get,
(setter)Quaternion_axis_set,
Quaternion_axis_doc,
(void *)1},
{"y",
(getter)Quaternion_axis_get,
(setter)Quaternion_axis_set,
Quaternion_axis_doc,
(void *)2},
{"z",
(getter)Quaternion_axis_get,
(setter)Quaternion_axis_set,
Quaternion_axis_doc,
(void *)3},
{"magnitude", (getter)Quaternion_magnitude_get, (setter)NULL, Quaternion_magnitude_doc, NULL},
{"angle",
(getter)Quaternion_angle_get,
(setter)Quaternion_angle_set,
Quaternion_angle_doc,
NULL},
{"axis",
(getter)Quaternion_axis_vector_get,
(setter)Quaternion_axis_vector_set,
Quaternion_axis_vector_doc,
NULL},
{"is_wrapped",
(getter)BaseMathObject_is_wrapped_get,
(setter)NULL,
BaseMathObject_is_wrapped_doc,
NULL},
{"is_frozen",
(getter)BaseMathObject_is_frozen_get,
(setter)NULL,
BaseMathObject_is_frozen_doc,
NULL},
{"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(quaternion_doc,
".. class:: Quaternion([seq, [angle]])\n"
"\n"
" This object gives access to Quaternions in Blender.\n"
"\n"
" :param seq: size 3 or 4\n"
" :type seq: :class:`Vector`\n"
" :param angle: rotation angle, in radians\n"
" :type angle: float\n"
"\n"
" The constructor takes arguments in various forms:\n"
"\n"
" (), *no args*\n"
" Create an identity quaternion\n"
" (*wxyz*)\n"
" Create a quaternion from a ``(w, x, y, z)`` vector.\n"
" (*exponential_map*)\n"
" Create a quaternion from a 3d exponential map vector.\n"
"\n"
" .. seealso:: :meth:`to_exponential_map`\n"
" (*axis, angle*)\n"
" Create a quaternion representing a rotation of *angle* radians over *axis*.\n"
"\n"
" .. seealso:: :meth:`to_axis_angle`\n");
PyTypeObject quaternion_Type = {
PyVarObject_HEAD_INIT(NULL, 0) "Quaternion", /* tp_name */
sizeof(QuaternionObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)BaseMathObject_dealloc, /* tp_dealloc */
(printfunc)NULL, /* tp_print */
NULL, /* tp_getattr */
NULL, /* tp_setattr */
NULL, /* tp_compare */
(reprfunc)Quaternion_repr, /* tp_repr */
&Quaternion_NumMethods, /* tp_as_number */
&Quaternion_SeqMethods, /* tp_as_sequence */
&Quaternion_AsMapping, /* tp_as_mapping */
(hashfunc)Quaternion_hash, /* tp_hash */
NULL, /* tp_call */
#ifndef MATH_STANDALONE
(reprfunc)Quaternion_str, /* tp_str */
#else
NULL, /* tp_str */
#endif
NULL, /* tp_getattro */
NULL, /* tp_setattro */
NULL, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
quaternion_doc, /* tp_doc */
(traverseproc)BaseMathObject_traverse, /* tp_traverse */
(inquiry)BaseMathObject_clear, /* tp_clear */
(richcmpfunc)Quaternion_richcmpr, /* tp_richcompare */
0, /* tp_weaklistoffset */
NULL, /* tp_iter */
NULL, /* tp_iternext */
Quaternion_methods, /* tp_methods */
NULL, /* tp_members */
Quaternion_getseters, /* tp_getset */
NULL, /* tp_base */
NULL, /* tp_dict */
NULL, /* tp_descr_get */
NULL, /* tp_descr_set */
0, /* tp_dictoffset */
NULL, /* tp_init */
NULL, /* tp_alloc */
Quaternion_new, /* tp_new */
NULL, /* tp_free */
NULL, /* tp_is_gc */
NULL, /* tp_bases */
NULL, /* tp_mro */
NULL, /* tp_cache */
NULL, /* tp_subclasses */
NULL, /* tp_weaklist */
NULL, /* tp_del */
};
PyObject *Quaternion_CreatePyObject(const float quat[4], PyTypeObject *base_type)
{
QuaternionObject *self;
float *quat_alloc;
quat_alloc = PyMem_Malloc(QUAT_SIZE * sizeof(float));
if (UNLIKELY(quat_alloc == NULL)) {
PyErr_SetString(PyExc_MemoryError,
"Quaternion(): "
"problem allocating data");
return NULL;
}
self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
if (self) {
self->quat = quat_alloc;
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
/* NEW */
if (!quat) { /* new empty */
unit_qt(self->quat);
}
else {
copy_qt_qt(self->quat, quat);
}
self->flag = BASE_MATH_FLAG_DEFAULT;
}
else {
PyMem_Free(quat_alloc);
}
return (PyObject *)self;
}
PyObject *Quaternion_CreatePyObject_wrap(float quat[4], PyTypeObject *base_type)
{
QuaternionObject *self;
self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
if (self) {
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
/* WRAP */
self->quat = quat;
self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
}
return (PyObject *)self;
}
PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user, uchar cb_type, uchar cb_subtype)
{
QuaternionObject *self = (QuaternionObject *)Quaternion_CreatePyObject(NULL, NULL);
if (self) {
Py_INCREF(cb_user);
self->cb_user = cb_user;
self->cb_type = cb_type;
self->cb_subtype = cb_subtype;
PyObject_GC_Track(self);
}
return (PyObject *)self;
}
diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c
index ace7480ee81..15ae811fd91 100644
--- a/source/blender/python/mathutils/mathutils_Vector.c
+++ b/source/blender/python/mathutils/mathutils_Vector.c
@@ -1,3247 +1,3247 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "../generic/py_capi_utils.h"
#ifndef MATH_STANDALONE
# include "BLI_dynstr.h"
#endif
/**
* Higher dimensions are supported, for many common operations
* (dealing with vector/matrix multiply or handling as 3D locations)
* stack memory is used with a fixed size - defined here.
*/
#define MAX_DIMENSIONS 4
/* Swizzle axes get packed into a single value that is used as a closure. Each
* axis uses SWIZZLE_BITS_PER_AXIS bits. The first bit (SWIZZLE_VALID_AXIS) is
* used as a sentinel: if it is unset, the axis is not valid. */
#define SWIZZLE_BITS_PER_AXIS 3
#define SWIZZLE_VALID_AXIS 0x4
#define SWIZZLE_AXIS 0x3
static PyObject *Vector_copy(VectorObject *self);
static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args);
static PyObject *Vector_to_tuple_ex(VectorObject *self, int ndigits);
static int row_vector_multiplication(float rvec[MAX_DIMENSIONS],
VectorObject *vec,
MatrixObject *mat);
/**
* Supports 2D, 3D, and 4D vector objects both int and float values
* accepted. Mixed float and int values accepted. Ints are parsed to float
*/
static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
float *vec = NULL;
int size = 3; /* default to a 3D vector */
if (kwds && PyDict_Size(kwds)) {
PyErr_SetString(PyExc_TypeError,
"Vector(): "
"takes no keyword args");
return NULL;
}
switch (PyTuple_GET_SIZE(args)) {
case 0:
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector(): "
"problem allocating pointer space");
return NULL;
}
copy_vn_fl(vec, size, 0.0f);
break;
case 1:
if ((size = mathutils_array_parse_alloc(
&vec, 2, PyTuple_GET_ITEM(args, 0), "mathutils.Vector()")) == -1) {
return NULL;
}
break;
default:
PyErr_SetString(PyExc_TypeError,
"mathutils.Vector(): "
"more than a single arg given");
return NULL;
}
return Vector_CreatePyObject_alloc(vec, size, type);
}
-static PyObject *vec__apply_to_copy(PyNoArgsFunction vec_func, VectorObject *self)
+static PyObject *vec__apply_to_copy(PyObject *(*vec_func)(VectorObject *), VectorObject *self)
{
PyObject *ret = Vector_copy(self);
- PyObject *ret_dummy = vec_func(ret);
+ PyObject *ret_dummy = vec_func((VectorObject *)ret);
if (ret_dummy) {
Py_DECREF(ret_dummy);
return (PyObject *)ret;
}
else { /* error */
Py_DECREF(ret);
return NULL;
}
}
/*-----------------------CLASS-METHODS----------------------------*/
PyDoc_STRVAR(C_Vector_Fill_doc,
".. classmethod:: Fill(size, fill=0.0)\n"
"\n"
" Create a vector of length size with all values set to fill.\n"
"\n"
" :arg size: The length of the vector to be created.\n"
" :type size: int\n"
" :arg fill: The value used to fill the vector.\n"
" :type fill: float\n");
static PyObject *C_Vector_Fill(PyObject *cls, PyObject *args)
{
float *vec;
int size;
float fill = 0.0f;
if (!PyArg_ParseTuple(args, "i|f:Vector.Fill", &size, &fill)) {
return NULL;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
return NULL;
}
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.Fill(): "
"problem allocating pointer space");
return NULL;
}
copy_vn_fl(vec, size, fill);
return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Vector_Range_doc,
".. classmethod:: Range(start=0, stop, step=1)\n"
"\n"
" Create a filled with a range of values.\n"
"\n"
" :arg start: The start of the range used to fill the vector.\n"
" :type start: int\n"
" :arg stop: The end of the range used to fill the vector.\n"
" :type stop: int\n"
" :arg step: The step between successive values in the vector.\n"
" :type step: int\n");
static PyObject *C_Vector_Range(PyObject *cls, PyObject *args)
{
float *vec;
int stop, size;
int start = 0;
int step = 1;
if (!PyArg_ParseTuple(args, "i|ii:Vector.Range", &start, &stop, &step)) {
return NULL;
}
switch (PyTuple_GET_SIZE(args)) {
case 1:
size = start;
start = 0;
break;
case 2:
if (start >= stop) {
PyErr_SetString(PyExc_RuntimeError,
"Start value is larger "
"than the stop value");
return NULL;
}
size = stop - start;
break;
default:
if (start >= stop) {
PyErr_SetString(PyExc_RuntimeError,
"Start value is larger "
"than the stop value");
return NULL;
}
size = (stop - start);
if ((size % step) != 0) {
size += step;
}
size /= step;
break;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
return NULL;
}
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.Range(): "
"problem allocating pointer space");
return NULL;
}
range_vn_fl(vec, size, (float)start, (float)step);
return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Vector_Linspace_doc,
".. classmethod:: Linspace(start, stop, size)\n"
"\n"
" Create a vector of the specified size which is filled with linearly spaced "
"values between start and stop values.\n"
"\n"
" :arg start: The start of the range used to fill the vector.\n"
" :type start: int\n"
" :arg stop: The end of the range used to fill the vector.\n"
" :type stop: int\n"
" :arg size: The size of the vector to be created.\n"
" :type size: int\n");
static PyObject *C_Vector_Linspace(PyObject *cls, PyObject *args)
{
float *vec;
int size;
float start, end, step;
if (!PyArg_ParseTuple(args, "ffi:Vector.Linspace", &start, &end, &size)) {
return NULL;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector.Linspace(): invalid size");
return NULL;
}
step = (end - start) / (float)(size - 1);
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.Linspace(): "
"problem allocating pointer space");
return NULL;
}
range_vn_fl(vec, size, start, step);
return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
PyDoc_STRVAR(
C_Vector_Repeat_doc,
".. classmethod:: Repeat(vector, size)\n"
"\n"
" Create a vector by repeating the values in vector until the required size is reached.\n"
"\n"
" :arg tuple: The vector to draw values from.\n"
" :type tuple: :class:`mathutils.Vector`\n"
" :arg size: The size of the vector to be created.\n"
" :type size: int\n");
static PyObject *C_Vector_Repeat(PyObject *cls, PyObject *args)
{
float *vec;
float *iter_vec = NULL;
int i, size, value_size;
PyObject *value;
if (!PyArg_ParseTuple(args, "Oi:Vector.Repeat", &value, &size)) {
return NULL;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector.Repeat(): invalid size");
return NULL;
}
if ((value_size = mathutils_array_parse_alloc(
&iter_vec, 2, value, "Vector.Repeat(vector, size), invalid 'vector' arg")) == -1) {
return NULL;
}
if (iter_vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.Repeat(): "
"problem allocating pointer space");
return NULL;
}
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyMem_Free(iter_vec);
PyErr_SetString(PyExc_MemoryError,
"Vector.Repeat(): "
"problem allocating pointer space");
return NULL;
}
i = 0;
while (i < size) {
vec[i] = iter_vec[i % value_size];
i++;
}
PyMem_Free(iter_vec);
return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
/*-----------------------------METHODS---------------------------- */
PyDoc_STRVAR(Vector_zero_doc,
".. method:: zero()\n"
"\n"
" Set all values to zero.\n");
static PyObject *Vector_zero(VectorObject *self)
{
if (BaseMath_Prepare_ForWrite(self) == -1) {
return NULL;
}
copy_vn_fl(self->vec, self->size, 0.0f);
if (BaseMath_WriteCallback(self) == -1) {
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_normalize_doc,
".. method:: normalize()\n"
"\n"
" Normalize the vector, making the length of the vector always 1.0.\n"
"\n"
" .. warning:: Normalizing a vector where all values are zero has no effect.\n"
"\n"
" .. note:: Normalize works for vectors of all sizes,\n"
" however 4D Vectors w axis is left untouched.\n");
static PyObject *Vector_normalize(VectorObject *self)
{
int size = (self->size == 4 ? 3 : self->size);
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
normalize_vn(self->vec, size);
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_normalized_doc,
".. method:: normalized()\n"
"\n"
" Return a new, normalized vector.\n"
"\n"
" :return: a normalized copy of the vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_normalized(VectorObject *self)
{
- return vec__apply_to_copy((PyNoArgsFunction)Vector_normalize, self);
+ return vec__apply_to_copy(Vector_normalize, self);
}
PyDoc_STRVAR(Vector_resize_doc,
".. method:: resize(size=3)\n"
"\n"
" Resize the vector to have size number of elements.\n");
static PyObject *Vector_resize(VectorObject *self, PyObject *value)
{
int size;
if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize(): "
"cannot resize wrapped data - only python vectors");
return NULL;
}
if (self->cb_user) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize(): "
"cannot resize a vector that has an owner");
return NULL;
}
if ((size = PyC_Long_AsI32(value)) == -1) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize(size): "
"expected size argument to be an integer");
return NULL;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector.resize(): invalid size");
return NULL;
}
self->vec = PyMem_Realloc(self->vec, (size * sizeof(float)));
if (self->vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.resize(): "
"problem allocating pointer space");
return NULL;
}
/* If the vector has increased in length, set all new elements to 0.0f */
if (size > self->size) {
copy_vn_fl(self->vec + self->size, size - self->size, 0.0f);
}
self->size = size;
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resized_doc,
".. method:: resized(size=3)\n"
"\n"
" Return a resized copy of the vector with size number of elements.\n"
"\n"
" :return: a new vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_resized(VectorObject *self, PyObject *value)
{
int size;
float *vec;
if ((size = PyLong_AsLong(value)) == -1) {
return NULL;
}
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector.resized(): invalid size");
return NULL;
}
vec = PyMem_Malloc(size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.resized(): "
"problem allocating pointer space");
return NULL;
}
copy_vn_fl(vec, size, 0.0f);
memcpy(vec, self->vec, self->size * sizeof(float));
return Vector_CreatePyObject_alloc(vec, size, NULL);
}
PyDoc_STRVAR(Vector_resize_2d_doc,
".. method:: resize_2d()\n"
"\n"
" Resize the vector to 2D (x, y).\n");
static PyObject *Vector_resize_2d(VectorObject *self)
{
if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_2d(): "
"cannot resize wrapped data - only python vectors");
return NULL;
}
if (self->cb_user) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_2d(): "
"cannot resize a vector that has an owner");
return NULL;
}
self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 2));
if (self->vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.resize_2d(): "
"problem allocating pointer space");
return NULL;
}
self->size = 2;
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resize_3d_doc,
".. method:: resize_3d()\n"
"\n"
" Resize the vector to 3D (x, y, z).\n");
static PyObject *Vector_resize_3d(VectorObject *self)
{
if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_3d(): "
"cannot resize wrapped data - only python vectors");
return NULL;
}
if (self->cb_user) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_3d(): "
"cannot resize a vector that has an owner");
return NULL;
}
self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 3));
if (self->vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.resize_3d(): "
"problem allocating pointer space");
return NULL;
}
if (self->size == 2) {
self->vec[2] = 0.0f;
}
self->size = 3;
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resize_4d_doc,
".. method:: resize_4d()\n"
"\n"
" Resize the vector to 4D (x, y, z, w).\n");
static PyObject *Vector_resize_4d(VectorObject *self)
{
if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_4d(): "
"cannot resize wrapped data - only python vectors");
return NULL;
}
if (self->cb_user) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize_4d(): "
"cannot resize a vector that has an owner");
return NULL;
}
self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 4));
if (self->vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector.resize_4d(): "
"problem allocating pointer space");
return NULL;
}
if (self->size == 2) {
self->vec[2] = 0.0f;
self->vec[3] = 1.0f;
}
else if (self->size == 3) {
self->vec[3] = 1.0f;
}
self->size = 4;
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_to_2d_doc,
".. method:: to_2d()\n"
"\n"
" Return a 2d copy of the vector.\n"
"\n"
" :return: a new vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_to_2d(VectorObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Vector_CreatePyObject(self->vec, 2, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_3d_doc,
".. method:: to_3d()\n"
"\n"
" Return a 3d copy of the vector.\n"
"\n"
" :return: a new vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_to_3d(VectorObject *self)
{
float tvec[3] = {0.0f};
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 3));
return Vector_CreatePyObject(tvec, 3, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_4d_doc,
".. method:: to_4d()\n"
"\n"
" Return a 4d copy of the vector.\n"
"\n"
" :return: a new vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_to_4d(VectorObject *self)
{
float tvec[4] = {0.0f, 0.0f, 0.0f, 1.0f};
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 4));
return Vector_CreatePyObject(tvec, 4, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_tuple_doc,
".. method:: to_tuple(precision=-1)\n"
"\n"
" Return this vector as a tuple with.\n"
"\n"
" :arg precision: The number to round the value to in [-1, 21].\n"
" :type precision: int\n"
" :return: the values of the vector rounded by *precision*\n"
" :rtype: tuple\n");
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Vector_to_tuple_ex(VectorObject *self, int ndigits)
{
PyObject *ret;
int i;
ret = PyTuple_New(self->size);
if (ndigits >= 0) {
for (i = 0; i < self->size; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->vec[i], ndigits)));
}
}
else {
for (i = 0; i < self->size; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->vec[i]));
}
}
return ret;
}
static PyObject *Vector_to_tuple(VectorObject *self, PyObject *args)
{
int ndigits = 0;
if (!PyArg_ParseTuple(args, "|i:to_tuple", &ndigits)) {
return NULL;
}
if (ndigits > 22 || ndigits < 0) {
PyErr_SetString(PyExc_ValueError,
"Vector.to_tuple(ndigits): "
"ndigits must be between 0 and 21");
return NULL;
}
if (PyTuple_GET_SIZE(args) == 0) {
ndigits = -1;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Vector_to_tuple_ex(self, ndigits);
}
PyDoc_STRVAR(Vector_to_track_quat_doc,
".. method:: to_track_quat(track, up)\n"
"\n"
" Return a quaternion rotation from the vector and the track and up axis.\n"
"\n"
" :arg track: Track axis in ['X', 'Y', 'Z', '-X', '-Y', '-Z'].\n"
" :type track: string\n"
" :arg up: Up axis in ['X', 'Y', 'Z'].\n"
" :type up: string\n"
" :return: rotation from the vector and the track and up axis.\n"
" :rtype: :class:`Quaternion`\n");
static PyObject *Vector_to_track_quat(VectorObject *self, PyObject *args)
{
float vec[3], quat[4];
const char *strack = NULL;
const char *sup = NULL;
short track = 2, up = 1;
if (!PyArg_ParseTuple(args, "|ss:to_track_quat", &strack, &sup)) {
return NULL;
}
if (self->size != 3) {
PyErr_SetString(PyExc_TypeError,
"Vector.to_track_quat(): "
"only for 3D vectors");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (strack) {
const char *axis_err_msg = "only X, -X, Y, -Y, Z or -Z for track axis";
if (strlen(strack) == 2) {
if (strack[0] == '-') {
switch (strack[1]) {
case 'X':
track = 3;
break;
case 'Y':
track = 4;
break;
case 'Z':
track = 5;
break;
default:
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
else {
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
else if (strlen(strack) == 1) {
switch (strack[0]) {
case '-':
case 'X':
track = 0;
break;
case 'Y':
track = 1;
break;
case 'Z':
track = 2;
break;
default:
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
else {
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
if (sup) {
const char *axis_err_msg = "only X, Y or Z for up axis";
if (strlen(sup) == 1) {
switch (*sup) {
case 'X':
up = 0;
break;
case 'Y':
up = 1;
break;
case 'Z':
up = 2;
break;
default:
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
else {
PyErr_SetString(PyExc_ValueError, axis_err_msg);
return NULL;
}
}
if (track == up) {
PyErr_SetString(PyExc_ValueError, "Can't have the same axis for track and up");
return NULL;
}
/* Flip vector around, since #vec_to_quat expect a vector from target to tracking object
* and the python function expects the inverse (a vector to the target). */
negate_v3_v3(vec, self->vec);
vec_to_quat(quat, vec, track, up);
return Quaternion_CreatePyObject(quat, NULL);
}
PyDoc_STRVAR(
Vector_orthogonal_doc,
".. method:: orthogonal()\n"
"\n"
" Return a perpendicular vector.\n"
"\n"
" :return: a new vector 90 degrees from this vector.\n"
" :rtype: :class:`Vector`\n"
"\n"
" .. note:: the axis is undefined, only use when any orthogonal vector is acceptable.\n");
static PyObject *Vector_orthogonal(VectorObject *self)
{
float vec[3];
if (self->size > 3) {
PyErr_SetString(PyExc_TypeError,
"Vector.orthogonal(): "
"Vector must be 3D or 2D");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (self->size == 3) {
ortho_v3_v3(vec, self->vec);
}
else {
ortho_v2_v2(vec, self->vec);
}
return Vector_CreatePyObject(vec, self->size, Py_TYPE(self));
}
/**
* Vector.reflect(mirror): return a reflected vector on the mirror normal.
* <pre>
* vec - ((2 * dot(vec, mirror)) * mirror)
* </pre>
*/
PyDoc_STRVAR(Vector_reflect_doc,
".. method:: reflect(mirror)\n"
"\n"
" Return the reflection vector from the *mirror* argument.\n"
"\n"
" :arg mirror: This vector could be a normal from the reflecting surface.\n"
" :type mirror: :class:`Vector`\n"
" :return: The reflected vector matching the size of this vector.\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_reflect(VectorObject *self, PyObject *value)
{
int value_size;
float mirror[3], vec[3];
float reflect[3] = {0.0f};
float tvec[MAX_DIMENSIONS];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if ((value_size = mathutils_array_parse(
tvec, 2, 4, value, "Vector.reflect(other), invalid 'other' arg")) == -1) {
return NULL;
}
if (self->size < 2 || self->size > 4) {
PyErr_SetString(PyExc_ValueError, "Vector must be 2D, 3D or 4D");
return NULL;
}
mirror[0] = tvec[0];
mirror[1] = tvec[1];
mirror[2] = (value_size > 2) ? tvec[2] : 0.0f;
vec[0] = self->vec[0];
vec[1] = self->vec[1];
vec[2] = (value_size > 2) ? self->vec[2] : 0.0f;
normalize_v3(mirror);
reflect_v3_v3v3(reflect, vec, mirror);
return Vector_CreatePyObject(reflect, self->size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_cross_doc,
".. method:: cross(other)\n"
"\n"
" Return the cross product of this vector and another.\n"
"\n"
" :arg other: The other vector to perform the cross product with.\n"
" :type other: :class:`Vector`\n"
" :return: The cross product.\n"
" :rtype: :class:`Vector` or float when 2D vectors are used\n"
"\n"
" .. note:: both vectors must be 2D or 3D\n");
static PyObject *Vector_cross(VectorObject *self, PyObject *value)
{
PyObject *ret;
float tvec[3];
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (self->size > 3) {
PyErr_SetString(PyExc_ValueError, "Vector must be 2D or 3D");
return NULL;
}
if (mathutils_array_parse(
tvec, self->size, self->size, value, "Vector.cross(other), invalid 'other' arg") == -1) {
return NULL;
}
if (self->size == 3) {
ret = Vector_CreatePyObject(NULL, 3, Py_TYPE(self));
cross_v3_v3v3(((VectorObject *)ret)->vec, self->vec, tvec);
}
else {
/* size == 2 */
ret = PyFloat_FromDouble(cross_v2v2(self->vec, tvec));
}
return ret;
}
PyDoc_STRVAR(Vector_dot_doc,
".. method:: dot(other)\n"
"\n"
" Return the dot product of this vector and another.\n"
"\n"
" :arg other: The other vector to perform the dot product with.\n"
" :type other: :class:`Vector`\n"
" :return: The dot product.\n"
" :rtype: float\n");
static PyObject *Vector_dot(VectorObject *self, PyObject *value)
{
float *tvec;
PyObject *ret;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse_alloc(
&tvec, self->size, value, "Vector.dot(other), invalid 'other' arg") == -1) {
return NULL;
}
ret = PyFloat_FromDouble(dot_vn_vn(self->vec, tvec, self->size));
PyMem_Free(tvec);
return ret;
}
PyDoc_STRVAR(
Vector_angle_doc,
".. function:: angle(other, fallback=None)\n"
"\n"
" Return the angle between two vectors.\n"
"\n"
" :arg other: another vector to compare the angle with\n"
" :type other: :class:`Vector`\n"
" :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
" (instead of raising a :exc:`ValueError`).\n"
" :type fallback: any\n"
" :return: angle in radians or fallback when given\n"
" :rtype: float\n");
static PyObject *Vector_angle(VectorObject *self, PyObject *args)
{
const int size = MIN2(self->size, 3); /* 4D angle makes no sense */
float tvec[MAX_DIMENSIONS];
PyObject *value;
double dot = 0.0f, dot_self = 0.0f, dot_other = 0.0f;
int x;
PyObject *fallback = NULL;
if (!PyArg_ParseTuple(args, "O|O:angle", &value, &fallback)) {
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/* don't use clamped size, rule of thumb is vector sizes must match,
* even though n this case 'w' is ignored */
if (mathutils_array_parse(
tvec, self->size, self->size, value, "Vector.angle(other), invalid 'other' arg") == -1) {
return NULL;
}
if (self->size > 4) {
PyErr_SetString(PyExc_ValueError, "Vector must be 2D, 3D or 4D");
return NULL;
}
for (x = 0; x < size; x++) {
dot_self += (double)self->vec[x] * (double)self->vec[x];
dot_other += (double)tvec[x] * (double)tvec[x];
dot += (double)self->vec[x] * (double)tvec[x];
}
if (!dot_self || !dot_other) {
/* avoid exception */
if (fallback) {
Py_INCREF(fallback);
return fallback;
}
else {
PyErr_SetString(PyExc_ValueError,
"Vector.angle(other): "
"zero length vectors have no valid angle");
return NULL;
}
}
return PyFloat_FromDouble(saacos(dot / (sqrt(dot_self) * sqrt(dot_other))));
}
PyDoc_STRVAR(
Vector_angle_signed_doc,
".. function:: angle_signed(other, fallback)\n"
"\n"
" Return the signed angle between two 2D vectors (clockwise is positive).\n"
"\n"
" :arg other: another vector to compare the angle with\n"
" :type other: :class:`Vector`\n"
" :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
" (instead of raising a :exc:`ValueError`).\n"
" :type fallback: any\n"
" :return: angle in radians or fallback when given\n"
" :rtype: float\n");
static PyObject *Vector_angle_signed(VectorObject *self, PyObject *args)
{
float tvec[2];
PyObject *value;
PyObject *fallback = NULL;
if (!PyArg_ParseTuple(args, "O|O:angle_signed", &value, &fallback)) {
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(
tvec, 2, 2, value, "Vector.angle_signed(other), invalid 'other' arg") == -1) {
return NULL;
}
if (self->size != 2) {
PyErr_SetString(PyExc_ValueError, "Vector must be 2D");
return NULL;
}
if (is_zero_v2(self->vec) || is_zero_v2(tvec)) {
/* avoid exception */
if (fallback) {
Py_INCREF(fallback);
return fallback;
}
else {
PyErr_SetString(PyExc_ValueError,
"Vector.angle_signed(other): "
"zero length vectors have no valid angle");
return NULL;
}
}
return PyFloat_FromDouble(angle_signed_v2v2(self->vec, tvec));
}
PyDoc_STRVAR(Vector_rotation_difference_doc,
".. function:: rotation_difference(other)\n"
"\n"
" Returns a quaternion representing the rotational difference between this\n"
" vector and another.\n"
"\n"
" :arg other: second vector.\n"
" :type other: :class:`Vector`\n"
" :return: the rotational difference between the two vectors.\n"
" :rtype: :class:`Quaternion`\n"
"\n"
" .. note:: 2D vectors raise an :exc:`AttributeError`.\n");
static PyObject *Vector_rotation_difference(VectorObject *self, PyObject *value)
{
float quat[4], vec_a[3], vec_b[3];
if (self->size < 3 || self->size > 4) {
PyErr_SetString(PyExc_ValueError,
"vec.difference(value): "
"expects both vectors to be size 3 or 4");
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse(
vec_b, 3, MAX_DIMENSIONS, value, "Vector.difference(other), invalid 'other' arg") ==
-1) {
return NULL;
}
normalize_v3_v3(vec_a, self->vec);
normalize_v3(vec_b);
rotation_between_vecs_to_quat(quat, vec_a, vec_b);
return Quaternion_CreatePyObject(quat, NULL);
}
PyDoc_STRVAR(Vector_project_doc,
".. function:: project(other)\n"
"\n"
" Return the projection of this vector onto the *other*.\n"
"\n"
" :arg other: second vector.\n"
" :type other: :class:`Vector`\n"
" :return: the parallel projection vector\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_project(VectorObject *self, PyObject *value)
{
const int size = self->size;
float *tvec;
double dot = 0.0f, dot2 = 0.0f;
int x;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse_alloc(
&tvec, size, value, "Vector.project(other), invalid 'other' arg") == -1) {
return NULL;
}
/* get dot products */
for (x = 0; x < size; x++) {
dot += (double)(self->vec[x] * tvec[x]);
dot2 += (double)(tvec[x] * tvec[x]);
}
/* projection */
dot /= dot2;
for (x = 0; x < size; x++) {
tvec[x] *= (float)dot;
}
return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_lerp_doc,
".. function:: lerp(other, factor)\n"
"\n"
" Returns the interpolation of two vectors.\n"
"\n"
" :arg other: value to interpolate with.\n"
" :type other: :class:`Vector`\n"
" :arg factor: The interpolation value in [0.0, 1.0].\n"
" :type factor: float\n"
" :return: The interpolated vector.\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_lerp(VectorObject *self, PyObject *args)
{
const int size = self->size;
PyObject *value = NULL;
float fac;
float *tvec;
if (!PyArg_ParseTuple(args, "Of:lerp", &value, &fac)) {
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (mathutils_array_parse_alloc(&tvec, size, value, "Vector.lerp(other), invalid 'other' arg") ==
-1) {
return NULL;
}
interp_vn_vn(tvec, self->vec, 1.0f - fac, size);
return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_slerp_doc,
".. function:: slerp(other, factor, fallback=None)\n"
"\n"
" Returns the interpolation of two non-zero vectors (spherical coordinates).\n"
"\n"
" :arg other: value to interpolate with.\n"
" :type other: :class:`Vector`\n"
" :arg factor: The interpolation value typically in [0.0, 1.0].\n"
" :type factor: float\n"
" :arg fallback: return this when the vector can't be calculated (zero length "
"vector or direct opposites),\n"
" (instead of raising a :exc:`ValueError`).\n"
" :type fallback: any\n"
" :return: The interpolated vector.\n"
" :rtype: :class:`Vector`\n");
static PyObject *Vector_slerp(VectorObject *self, PyObject *args)
{
const int size = self->size;
PyObject *value = NULL;
float fac, cosom, w[2];
float self_vec[3], other_vec[3], ret_vec[3];
float self_len_sq, other_len_sq;
int x;
PyObject *fallback = NULL;
if (!PyArg_ParseTuple(args, "Of|O:slerp", &value, &fac, &fallback)) {
return NULL;
}
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
if (self->size > 3) {
PyErr_SetString(PyExc_ValueError, "Vector must be 2D or 3D");
return NULL;
}
if (mathutils_array_parse(
other_vec, size, size, value, "Vector.slerp(other), invalid 'other' arg") == -1) {
return NULL;
}
self_len_sq = normalize_vn_vn(self_vec, self->vec, size);
other_len_sq = normalize_vn(other_vec, size);
/* use fallbacks for zero length vectors */
if (UNLIKELY((self_len_sq < FLT_EPSILON) || (other_len_sq < FLT_EPSILON))) {
/* avoid exception */
if (fallback) {
Py_INCREF(fallback);
return fallback;
}
else {
PyErr_SetString(PyExc_ValueError,
"Vector.slerp(): "
"zero length vectors unsupported");
return NULL;
}
}
/* We have sane state, execute slerp */
cosom = (float)dot_vn_vn(self_vec, other_vec, size);
/* direct opposite, can't slerp */
if (UNLIKELY(cosom < (-1.0f + FLT_EPSILON))) {
/* avoid exception */
if (fallback) {
Py_INCREF(fallback);
return fallback;
}
else {
PyErr_SetString(PyExc_ValueError,
"Vector.slerp(): "
"opposite vectors unsupported");
return NULL;
}
}
interp_dot_slerp(fac, cosom, w);
for (x = 0; x < size; x++) {
ret_vec[x] = (w[0] * self_vec[x]) + (w[1] * other_vec[x]);
}
return Vector_CreatePyObject(ret_vec, size, Py_TYPE(self));
}
PyDoc_STRVAR(
Vector_rotate_doc,
".. function:: rotate(other)\n"
"\n"
" Rotate the vector by a rotation value.\n"
"\n"
" .. note:: 2D vectors are a special case that can only be rotated by a 2x2 matrix.\n"
"\n"
" :arg other: rotation component of mathutils value\n"
" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n");
static PyObject *Vector_rotate(VectorObject *self, PyObject *value)
{
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return NULL;
}
if (self->size == 2) {
/* Special case for 2D Vector with 2x2 matrix, so we avoid resizing it to a 3x3. */
float other_rmat[2][2];
MatrixObject *pymat;
if (!Matrix_Parse2x2(value, &pymat)) {
return NULL;
}
normalize_m2_m2(other_rmat, (const float(*)[2])pymat->matrix);
/* Equivalent to a rotation along the Z axis. */
mul_m2_v2(other_rmat, self->vec);
}
else {
float other_rmat[3][3];
if (mathutils_any_to_rotmat(other_rmat, value, "Vector.rotate(value)") == -1) {
return NULL;
}
mul_m3_v3(other_rmat, self->vec);
}
(void)BaseMath_WriteCallback(self);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_copy_doc,
".. function:: copy()\n"
"\n"
" Returns a copy of this vector.\n"
"\n"
" :return: A copy of the vector.\n"
" :rtype: :class:`Vector`\n"
"\n"
" .. note:: use this to get a copy of a wrapped vector with\n"
" no reference to the original data.\n");
static PyObject *Vector_copy(VectorObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return Vector_CreatePyObject(self->vec, self->size, Py_TYPE(self));
}
static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args)
{
if (!PyC_CheckArgs_DeepCopy(args)) {
return NULL;
}
return Vector_copy(self);
}
static PyObject *Vector_repr(VectorObject *self)
{
PyObject *ret, *tuple;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
tuple = Vector_to_tuple_ex(self, -1);
ret = PyUnicode_FromFormat("Vector(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Vector_str(VectorObject *self)
{
int i;
DynStr *ds;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
ds = BLI_dynstr_new();
BLI_dynstr_append(ds, "<Vector (");
for (i = 0; i < self->size; i++) {
BLI_dynstr_appendf(ds, i ? ", %.4f" : "%.4f", self->vec[i]);
}
BLI_dynstr_append(ds, ")>");
return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
/* Sequence Protocol */
/* sequence length len(vector) */
static int Vector_len(VectorObject *self)
{
return self->size;
}
/* sequence accessor (get): vector[index] */
static PyObject *vector_item_internal(VectorObject *self, int i, const bool is_attr)
{
if (i < 0) {
i = self->size - i;
}
if (i < 0 || i >= self->size) {
if (is_attr) {
PyErr_Format(PyExc_AttributeError,
"Vector.%c: unavailable on %dd vector",
*(((const char *)"xyzw") + i),
self->size);
}
else {
PyErr_SetString(PyExc_IndexError, "vector[index]: out of range");
}
return NULL;
}
if (BaseMath_ReadIndexCallback(self, i) == -1) {
return NULL;
}
return PyFloat_FromDouble(self->vec[i]);
}
static PyObject *Vector_item(VectorObject *self, int i)
{
return vector_item_internal(self, i, false);
}
/* sequence accessor (set): vector[index] = value */
static int vector_ass_item_internal(VectorObject *self, int i, PyObject *value, const bool is_attr)
{
float scalar;
if (BaseMath_Prepare_ForWrite(self) == -1) {
return -1;
}
if ((scalar = PyFloat_AsDouble(value)) == -1.0f && PyErr_Occurred()) {
/* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"vector[index] = x: "
"assigned value not a number");
return -1;
}
if (i < 0) {
i = self->size - i;
}
if (i < 0 || i >= self->size) {
if (is_attr) {
PyErr_Format(PyExc_AttributeError,
"Vector.%c = x: unavailable on %dd vector",
*(((const char *)"xyzw") + i),
self->size);
}
else {
PyErr_SetString(PyExc_IndexError,
"vector[index] = x: "
"assignment index out of range");
}
return -1;
}
self->vec[i] = scalar;
if (BaseMath_WriteIndexCallback(self, i) == -1) {
return -1;
}
return 0;
}
static int Vector_ass_item(VectorObject *self, int i, PyObject *value)
{
return vector_ass_item_internal(self, i, value, false);
}
/* sequence slice (get): vector[a:b] */
static PyObject *Vector_slice(VectorObject *self, int begin, int end)
{
PyObject *tuple;
int count;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
CLAMP(begin, 0, self->size);
if (end < 0) {
end = self->size + end + 1;
}
CLAMP(end, 0, self->size);
begin = MIN2(begin, end);
tuple = PyTuple_New(end - begin);
for (count = begin; count < end; count++) {
PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->vec[count]));
}
return tuple;
}
/* sequence slice (set): vector[a:b] = value */
static int Vector_ass_slice(VectorObject *self, int begin, int end, PyObject *seq)
{
int size = 0;
float *vec = NULL;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
CLAMP(begin, 0, self->size);
CLAMP(end, 0, self->size);
begin = MIN2(begin, end);
size = (end - begin);
if (mathutils_array_parse_alloc(&vec, size, seq, "vector[begin:end] = [...]") == -1) {
return -1;
}
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"vec[:] = seq: "
"problem allocating pointer space");
return -1;
}
/*parsed well - now set in vector*/
memcpy(self->vec + begin, vec, size * sizeof(float));
PyMem_Free(vec);
if (BaseMath_WriteCallback(self) == -1) {
return -1;
}
return 0;
}
/* Numeric Protocols */
/* addition: obj + obj */
static PyObject *Vector_add(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
float *vec = NULL;
if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
PyErr_Format(PyExc_AttributeError,
"Vector addition: (%s + %s) "
"invalid type for this operation",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
vec1 = (VectorObject *)v1;
vec2 = (VectorObject *)v2;
if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
/*VECTOR + VECTOR*/
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector addition: "
"vectors must have the same dimensions for this operation");
return NULL;
}
vec = PyMem_Malloc(vec1->size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector(): "
"problem allocating pointer space");
return NULL;
}
add_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* addition in-place: obj += obj */
static PyObject *Vector_iadd(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
PyErr_Format(PyExc_AttributeError,
"Vector addition: (%s += %s) "
"invalid type for this operation",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
vec1 = (VectorObject *)v1;
vec2 = (VectorObject *)v2;
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector addition: "
"vectors must have the same dimensions for this operation");
return NULL;
}
if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
add_vn_vn(vec1->vec, vec2->vec, vec1->size);
(void)BaseMath_WriteCallback(vec1);
Py_INCREF(v1);
return v1;
}
/* subtraction: obj - obj */
static PyObject *Vector_sub(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
float *vec;
if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
PyErr_Format(PyExc_AttributeError,
"Vector subtraction: (%s - %s) "
"invalid type for this operation",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
vec1 = (VectorObject *)v1;
vec2 = (VectorObject *)v2;
if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector subtraction: "
"vectors must have the same dimensions for this operation");
return NULL;
}
vec = PyMem_Malloc(vec1->size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"Vector(): "
"problem allocating pointer space");
return NULL;
}
sub_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* subtraction in-place: obj -= obj */
static PyObject *Vector_isub(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
PyErr_Format(PyExc_AttributeError,
"Vector subtraction: (%s -= %s) "
"invalid type for this operation",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
vec1 = (VectorObject *)v1;
vec2 = (VectorObject *)v2;
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector subtraction: "
"vectors must have the same dimensions for this operation");
return NULL;
}
if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
sub_vn_vn(vec1->vec, vec2->vec, vec1->size);
(void)BaseMath_WriteCallback(vec1);
Py_INCREF(v1);
return v1;
}
/*------------------------obj * obj------------------------------
* multiplication */
/**
* Column vector multiplication (Matrix * Vector).
* <pre>
* [1][4][7] [a]
* [2][5][8] * [b]
* [3][6][9] [c]
* </pre>
*
* \note Vector/Matrix multiplication is not commutative.
* \note Assume read callbacks have been done first.
*/
int column_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat)
{
float vec_cpy[MAX_DIMENSIONS];
int row, col, z = 0;
if (mat->num_col != vec->size) {
if (mat->num_col == 4 && vec->size == 3) {
vec_cpy[3] = 1.0f;
}
else {
PyErr_SetString(PyExc_ValueError,
"matrix * vector: "
"len(matrix.col) and len(vector) must be the same, "
"except for 4x4 matrix * 3D vector.");
return -1;
}
}
memcpy(vec_cpy, vec->vec, vec->size * sizeof(float));
r_vec[3] = 1.0f;
for (row = 0; row < mat->num_row; row++) {
double dot = 0.0f;
for (col = 0; col < mat->num_col; col++) {
dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[col]);
}
r_vec[z++] = (float)dot;
}
return 0;
}
static PyObject *vector_mul_float(VectorObject *vec, const float scalar)
{
float *tvec = PyMem_Malloc(vec->size * sizeof(float));
if (tvec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"vec * float: "
"problem allocating pointer space");
return NULL;
}
mul_vn_vn_fl(tvec, vec->vec, vec->size, scalar);
return Vector_CreatePyObject_alloc(tvec, vec->size, Py_TYPE(vec));
}
#ifdef USE_MATHUTILS_ELEM_MUL
static PyObject *vector_mul_vec(VectorObject *vec1, VectorObject *vec2)
{
float *tvec = PyMem_Malloc(vec1->size * sizeof(float));
if (tvec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"vec * vec: "
"problem allocating pointer space");
return NULL;
}
mul_vn_vnvn(tvec, vec1->vec, vec2->vec, vec1->size);
return Vector_CreatePyObject_alloc(tvec, vec1->size, Py_TYPE(vec1));
}
#endif
static PyObject *Vector_mul(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
float scalar;
if (VectorObject_Check(v1)) {
vec1 = (VectorObject *)v1;
if (BaseMath_ReadCallback(vec1) == -1) {
return NULL;
}
}
if (VectorObject_Check(v2)) {
vec2 = (VectorObject *)v2;
if (BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
}
/* Intentionally don't support (Quaternion) here, uses reverse order instead. */
/* make sure v1 is always the vector */
if (vec1 && vec2) {
#ifdef USE_MATHUTILS_ELEM_MUL
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_ValueError,
"Vector multiplication: "
"vectors must have the same dimensions for this operation");
return NULL;
}
/* element-wise product */
return vector_mul_vec(vec1, vec2);
#endif
}
else if (vec1) {
if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* VEC * FLOAT */
return vector_mul_float(vec1, scalar);
}
}
else if (vec2) {
if (((scalar = PyFloat_AsDouble(v1)) == -1.0f && PyErr_Occurred()) == 0) { /* FLOAT * VEC */
return vector_mul_float(vec2, scalar);
}
}
PyErr_Format(PyExc_TypeError,
"Element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
/* multiplication in-place: obj *= obj */
static PyObject *Vector_imul(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
float scalar;
if (VectorObject_Check(v1)) {
vec1 = (VectorObject *)v1;
if (BaseMath_ReadCallback(vec1) == -1) {
return NULL;
}
}
if (VectorObject_Check(v2)) {
vec2 = (VectorObject *)v2;
if (BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
}
if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
return NULL;
}
/* Intentionally don't support (Quaternion, Matrix) here, uses reverse order instead. */
if (vec1 && vec2) {
#ifdef USE_MATHUTILS_ELEM_MUL
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_ValueError,
"Vector multiplication: "
"vectors must have the same dimensions for this operation");
return NULL;
}
/* element-wise product inplace */
mul_vn_vn(vec1->vec, vec2->vec, vec1->size);
#else
PyErr_Format(PyExc_TypeError,
"In place element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
#endif
}
else if (vec1 && (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) ==
0)) { /* VEC *= FLOAT */
mul_vn_fl(vec1->vec, vec1->size, scalar);
}
else {
PyErr_Format(PyExc_TypeError,
"In place element-wise multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
(void)BaseMath_WriteCallback(vec1);
Py_INCREF(v1);
return v1;
}
static PyObject *Vector_matmul(PyObject *v1, PyObject *v2)
{
VectorObject *vec1 = NULL, *vec2 = NULL;
int vec_size;
if (VectorObject_Check(v1)) {
vec1 = (VectorObject *)v1;
if (BaseMath_ReadCallback(vec1) == -1) {
return NULL;
}
}
if (VectorObject_Check(v2)) {
vec2 = (VectorObject *)v2;
if (BaseMath_ReadCallback(vec2) == -1) {
return NULL;
}
}
/* Intentionally don't support (Quaternion) here, uses reverse order instead. */
/* make sure v1 is always the vector */
if (vec1 && vec2) {
if (vec1->size != vec2->size) {
PyErr_SetString(PyExc_ValueError,
"Vector multiplication: "
"vectors must have the same dimensions for this operation");
return NULL;
}
/*dot product*/
return PyFloat_FromDouble(dot_vn_vn(vec1->vec, vec2->vec, vec1->size));
}
else if (vec1) {
if (MatrixObject_Check(v2)) {
/* VEC @ MATRIX */
float tvec[MAX_DIMENSIONS];
if (BaseMath_ReadCallback((MatrixObject *)v2) == -1) {
return NULL;
}
if (row_vector_multiplication(tvec, vec1, (MatrixObject *)v2) == -1) {
return NULL;
}
if (((MatrixObject *)v2)->num_row == 4 && vec1->size == 3) {
vec_size = 3;
}
else {
vec_size = ((MatrixObject *)v2)->num_col;
}
return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(vec1));
}
}
PyErr_Format(PyExc_TypeError,
"Vector multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
static PyObject *Vector_imatmul(PyObject *v1, PyObject *v2)
{
PyErr_Format(PyExc_TypeError,
"In place vector multiplication: "
"not supported between '%.200s' and '%.200s' types",
Py_TYPE(v1)->tp_name,
Py_TYPE(v2)->tp_name);
return NULL;
}
/* divid: obj / obj */
static PyObject *Vector_div(PyObject *v1, PyObject *v2)
{
float *vec = NULL, scalar;
VectorObject *vec1 = NULL;
if (!VectorObject_Check(v1)) { /* not a vector */
PyErr_SetString(PyExc_TypeError,
"Vector division: "
"Vector must be divided by a float");
return NULL;
}
vec1 = (VectorObject *)v1; /* vector */
if (BaseMath_ReadCallback(vec1) == -1) {
return NULL;
}
if ((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) {
/* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"Vector division: "
"Vector must be divided by a float");
return NULL;
}
if (scalar == 0.0f) {
PyErr_SetString(PyExc_ZeroDivisionError,
"Vector division: "
"divide by zero error");
return NULL;
}
vec = PyMem_Malloc(vec1->size * sizeof(float));
if (vec == NULL) {
PyErr_SetString(PyExc_MemoryError,
"vec / value: "
"problem allocating pointer space");
return NULL;
}
mul_vn_vn_fl(vec, vec1->vec, vec1->size, 1.0f / scalar);
return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* divide in-place: obj /= obj */
static PyObject *Vector_idiv(PyObject *v1, PyObject *v2)
{
float scalar;
VectorObject *vec1 = (VectorObject *)v1;
if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
return NULL;
}
if ((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) {
/* parsed item not a number */
PyErr_SetString(PyExc_TypeError,
"Vector division: "
"Vector must be divided by a float");
return NULL;
}
if (scalar == 0.0f) {
PyErr_SetString(PyExc_ZeroDivisionError,
"Vector division: "
"divide by zero error");
return NULL;
}
mul_vn_fl(vec1->vec, vec1->size, 1.0f / scalar);
(void)BaseMath_WriteCallback(vec1);
Py_INCREF(v1);
return v1;
}
/* -obj
* returns the negative of this object*/
static PyObject *Vector_neg(VectorObject *self)
{
float *tvec;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
tvec = PyMem_Malloc(self->size * sizeof(float));
negate_vn_vn(tvec, self->vec, self->size);
return Vector_CreatePyObject_alloc(tvec, self->size, Py_TYPE(self));
}
/*------------------------tp_richcmpr
* returns -1 exception, 0 false, 1 true */
static PyObject *Vector_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
{
VectorObject *vecA = NULL, *vecB = NULL;
int result = 0;
double epsilon = 0.000001f;
double lenA, lenB;
if (!VectorObject_Check(objectA) || !VectorObject_Check(objectB)) {
if (comparison_type == Py_NE) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
vecA = (VectorObject *)objectA;
vecB = (VectorObject *)objectB;
if (BaseMath_ReadCallback(vecA) == -1 || BaseMath_ReadCallback(vecB) == -1) {
return NULL;
}
if (vecA->size != vecB->size) {
if (comparison_type == Py_NE) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
switch (comparison_type) {
case Py_LT:
lenA = len_squared_vn(vecA->vec, vecA->size);
lenB = len_squared_vn(vecB->vec, vecB->size);
if (lenA < lenB) {
result = 1;
}
break;
case Py_LE:
lenA = len_squared_vn(vecA->vec, vecA->size);
lenB = len_squared_vn(vecB->vec, vecB->size);
if (lenA < lenB) {
result = 1;
}
else {
result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
}
break;
case Py_EQ:
result = EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
break;
case Py_NE:
result = !EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
break;
case Py_GT:
lenA = len_squared_vn(vecA->vec, vecA->size);
lenB = len_squared_vn(vecB->vec, vecB->size);
if (lenA > lenB) {
result = 1;
}
break;
case Py_GE:
lenA = len_squared_vn(vecA->vec, vecA->size);
lenB = len_squared_vn(vecB->vec, vecB->size);
if (lenA > lenB) {
result = 1;
}
else {
result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
}
break;
default:
printf("The result of the comparison could not be evaluated");
break;
}
if (result == 1) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
static Py_hash_t Vector_hash(VectorObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return -1;
}
if (BaseMathObject_Prepare_ForHash(self) == -1) {
return -1;
}
return mathutils_array_hash(self->vec, self->size);
}
/*-----------------PROTCOL DECLARATIONS--------------------------*/
static PySequenceMethods Vector_SeqMethods = {
(lenfunc)Vector_len, /* sq_length */
(binaryfunc)NULL, /* sq_concat */
(ssizeargfunc)NULL, /* sq_repeat */
(ssizeargfunc)Vector_item, /* sq_item */
NULL, /* py3 deprecated slice func */
(ssizeobjargproc)Vector_ass_item, /* sq_ass_item */
NULL, /* py3 deprecated slice assign func */
(objobjproc)NULL, /* sq_contains */
(binaryfunc)NULL, /* sq_inplace_concat */
(ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyObject *Vector_subscript(VectorObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return NULL;
}
if (i < 0) {
i += self->size;
}
return Vector_item(self, i);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
return NULL;
}
if (slicelength <= 0) {
return PyTuple_New(0);
}
else if (step == 1) {
return Vector_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
return NULL;
}
}
else {
PyErr_Format(
PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return NULL;
}
}
static int Vector_ass_subscript(VectorObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
if (i < 0) {
i += self->size;
}
return Vector_ass_item(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
return -1;
}
if (step == 1) {
return Vector_ass_slice(self, start, stop, value);
}
else {
PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
return -1;
}
}
else {
PyErr_Format(
PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
return -1;
}
}
static PyMappingMethods Vector_AsMapping = {
(lenfunc)Vector_len,
(binaryfunc)Vector_subscript,
(objobjargproc)Vector_ass_subscript,
};
static PyNumberMethods Vector_NumMethods = {
(binaryfunc)Vector_add, /*nb_add*/
(binaryfunc)Vector_sub, /*nb_subtract*/
(binaryfunc)Vector_mul, /*nb_multiply*/
NULL, /*nb_remainder*/
NULL, /*nb_divmod*/
NULL, /*nb_power*/
(unaryfunc)Vector_neg, /*nb_negative*/
(unaryfunc)Vector_copy, /*tp_positive*/
(unaryfunc)NULL, /*tp_absolute*/
(inquiry)NULL, /*tp_bool*/
(unaryfunc)NULL, /*nb_invert*/
NULL, /*nb_lshift*/
(binaryfunc)NULL, /*nb_rshift*/
NULL, /*nb_and*/
NULL, /*nb_xor*/
NULL, /*nb_or*/
NULL, /*nb_int*/
NULL, /*nb_reserved*/
NULL, /*nb_float*/
Vector_iadd, /* nb_inplace_add */
Vector_isub, /* nb_inplace_subtract */
Vector_imul, /* nb_inplace_multiply */
NULL, /* nb_inplace_remainder */
NULL, /* nb_inplace_power */
NULL, /* nb_inplace_lshift */
NULL, /* nb_inplace_rshift */
NULL, /* nb_inplace_and */
NULL, /* nb_inplace_xor */
NULL, /* nb_inplace_or */
NULL, /* nb_floor_divide */
Vector_div, /* nb_true_divide */
NULL, /* nb_inplace_floor_divide */
Vector_idiv, /* nb_inplace_true_divide */
NULL, /* nb_index */
(binaryfunc)Vector_matmul, /* nb_matrix_multiply */
(binaryfunc)Vector_imatmul, /* nb_inplace_matrix_multiply */
};
/*------------------PY_OBECT DEFINITION--------------------------*/
/* vector axis, vector.x/y/z/w */
PyDoc_STRVAR(Vector_axis_x_doc, "Vector X axis.\n\n:type: float");
PyDoc_STRVAR(Vector_axis_y_doc, "Vector Y axis.\n\n:type: float");
PyDoc_STRVAR(Vector_axis_z_doc, "Vector Z axis (3D Vectors only).\n\n:type: float");
PyDoc_STRVAR(Vector_axis_w_doc, "Vector W axis (4D Vectors only).\n\n:type: float");
static PyObject *Vector_axis_get(VectorObject *self, void *type)
{
return vector_item_internal(self, POINTER_AS_INT(type), true);
}
static int Vector_axis_set(VectorObject *self, PyObject *value, void *type)
{
return vector_ass_item_internal(self, POINTER_AS_INT(type), value, true);
}
/* vector.length */
PyDoc_STRVAR(Vector_length_doc, "Vector Length.\n\n:type: float");
static PyObject *Vector_length_get(VectorObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return PyFloat_FromDouble(sqrt(dot_vn_vn(self->vec, self->vec, self->size)));
}
static int Vector_length_set(VectorObject *self, PyObject *value)
{
double dot = 0.0f, param;
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
if ((param = PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "length must be set to a number");
return -1;
}
if (param < 0.0) {
PyErr_SetString(PyExc_ValueError, "cannot set a vectors length to a negative value");
return -1;
}
if (param == 0.0) {
copy_vn_fl(self->vec, self->size, 0.0f);
return 0;
}
dot = dot_vn_vn(self->vec, self->vec, self->size);
if (!dot) {
/* cant sqrt zero */
return 0;
}
dot = sqrt(dot);
if (dot == param) {
return 0;
}
dot = dot / param;
mul_vn_fl(self->vec, self->size, 1.0 / dot);
(void)BaseMath_WriteCallback(self); /* checked already */
return 0;
}
/* vector.length_squared */
PyDoc_STRVAR(Vector_length_squared_doc, "Vector length squared (v.dot(v)).\n\n:type: float");
static PyObject *Vector_length_squared_get(VectorObject *self, void *UNUSED(closure))
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
return PyFloat_FromDouble(dot_vn_vn(self->vec, self->vec, self->size));
}
/**
* Python script used to make swizzle array:
*
* \code{.py}
* SWIZZLE_BITS_PER_AXIS = 3
* SWIZZLE_VALID_AXIS = 0x4
*
* axis_dict = {}
* axis_pos = {'x': 0, 'y': 1, 'z': 2, 'w': 3}
* axis_chars = 'xyzw'
* while len(axis_chars) >= 2:
* for axis_0 in axis_chars:
* axis_0_pos = axis_pos[axis_0]
* for axis_1 in axis_chars:
* axis_1_pos = axis_pos[axis_1]
* axis_dict[axis_0 + axis_1] = (
* '((%s | SWIZZLE_VALID_AXIS) | '
* '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS))' %
* (axis_0_pos, axis_1_pos))
* if len(axis_chars) > 2:
* for axis_2 in axis_chars:
* axis_2_pos = axis_pos[axis_2]
* axis_dict[axis_0 + axis_1 + axis_2] = (
* '((%s | SWIZZLE_VALID_AXIS) | '
* '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
* '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))' %
* (axis_0_pos, axis_1_pos, axis_2_pos))
* if len(axis_chars) > 3:
* for axis_3 in axis_chars:
* axis_3_pos = axis_pos[axis_3]
* axis_dict[axis_0 + axis_1 + axis_2 + axis_3] = (
* '((%s | SWIZZLE_VALID_AXIS) | '
* '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
* '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)) | '
* '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3))) '
* %
* (axis_0_pos, axis_1_pos, axis_2_pos, axis_3_pos))
*
* axis_chars = axis_chars[:-1]
* items = list(axis_dict.items())
* items.sort(
* key=lambda a: a[0].replace('x', '0').replace('y', '1').replace('z', '2').replace('w', '3')
* )
*
* unique = set()
* for key, val in items:
* num = eval(val)
* set_str = 'Vector_swizzle_set' if (len(set(key)) == len(key)) else 'NULL'
* key_args = ', '.join(["'%s'" % c for c in key.upper()])
* print('\t{"%s", %s(getter)Vector_swizzle_get, (setter)%s, NULL, SWIZZLE%d(%s)},' %
* (key, (' ' * (4 - len(key))), set_str, len(key), key_args))
* unique.add(num)
*
* if len(unique) != len(items):
* print("ERROR, duplicate values found")
* \endcode
*/
/**
* Get a new Vector according to the provided swizzle bits.
*/
static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
{
size_t axis_to;
size_t axis_from;
float vec[MAX_DIMENSIONS];
uint swizzleClosure;
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
/* Unpack the axes from the closure into an array. */
axis_to = 0;
swizzleClosure = POINTER_AS_INT(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS) {
axis_from = swizzleClosure & SWIZZLE_AXIS;
if (axis_from >= self->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector swizzle: "
"specified axis not present");
return NULL;
}
vec[axis_to] = self->vec[axis_from];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axis_to++;
}
return Vector_CreatePyObject(vec, axis_to, Py_TYPE(self));
}
/**
* Set the items of this vector using a swizzle.
* - If value is a vector or list this operates like an array copy, except that
* the destination is effectively re-ordered as defined by the swizzle. At
* most min(len(source), len(dest)) values will be copied.
* - If the value is scalar, it is copied to all axes listed in the swizzle.
* - If an axis appears more than once in the swizzle, the final occurrence is
* the one that determines its value.
*
* \return 0 on success and -1 on failure. On failure, the vector will be unchanged.
*/
static int Vector_swizzle_set(VectorObject *self, PyObject *value, void *closure)
{
size_t size_from;
float scalarVal;
size_t axis_from;
size_t axis_to;
uint swizzleClosure;
float tvec[MAX_DIMENSIONS];
float vec_assign[MAX_DIMENSIONS];
if (BaseMath_ReadCallback_ForWrite(self) == -1) {
return -1;
}
/* Check that the closure can be used with this vector: even 2D vectors have
* swizzles defined for axes z and w, but they would be invalid. */
swizzleClosure = POINTER_AS_INT(closure);
axis_from = 0;
while (swizzleClosure & SWIZZLE_VALID_AXIS) {
axis_to = swizzleClosure & SWIZZLE_AXIS;
if (axis_to >= self->size) {
PyErr_SetString(PyExc_AttributeError,
"Vector swizzle: "
"specified axis not present");
return -1;
}
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axis_from++;
}
if (((scalarVal = PyFloat_AsDouble(value)) == -1 && PyErr_Occurred()) == 0) {
int i;
for (i = 0; i < MAX_DIMENSIONS; i++) {
vec_assign[i] = scalarVal;
}
size_from = axis_from;
}
else if (((void)PyErr_Clear()), /* run but ignore the result */
(size_from = mathutils_array_parse(
vec_assign, 2, 4, value, "mathutils.Vector.**** = swizzle assignment")) == -1) {
return -1;
}
if (axis_from != size_from) {
PyErr_SetString(PyExc_AttributeError, "Vector swizzle: size does not match swizzle");
return -1;
}
/* Copy vector contents onto swizzled axes. */
axis_from = 0;
swizzleClosure = POINTER_AS_INT(closure);
/* We must first copy current vec into tvec, else some org values may be lost.
* See [#31760].
* Assuming self->size can't be higher than MAX_DIMENSIONS! */
memcpy(tvec, self->vec, self->size * sizeof(float));
while (swizzleClosure & SWIZZLE_VALID_AXIS) {
axis_to = swizzleClosure & SWIZZLE_AXIS;
tvec[axis_to] = vec_assign[axis_from];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axis_from++;
}
/* We must copy back the whole tvec into vec, else some changes may be lost (e.g. xz...).
* See [#31760]. */
memcpy(self->vec, tvec, self->size * sizeof(float));
/* continue with BaseMathObject_WriteCallback at the end */
if (BaseMath_WriteCallback(self) == -1) {
return -1;
}
else {
return 0;
}
}
#define _SWIZZLE1(a) ((a) | SWIZZLE_VALID_AXIS)
#define _SWIZZLE2(a, b) (_SWIZZLE1(a) | (((b) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS)))
#define _SWIZZLE3(a, b, c) \
(_SWIZZLE2(a, b) | (((c) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))
#define _SWIZZLE4(a, b, c, d) \
(_SWIZZLE3(a, b, c) | (((d) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3)))
#define SWIZZLE2(a, b) POINTER_FROM_INT(_SWIZZLE2(a, b))
#define SWIZZLE3(a, b, c) POINTER_FROM_INT(_SWIZZLE3(a, b, c))
#define SWIZZLE4(a, b, c, d) POINTER_FROM_INT(_SWIZZLE4(a, b, c, d))
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Vector_getseters[] = {
{"x", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_x_doc, (void *)0},
{"y", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_y_doc, (void *)1},
{"z", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_z_doc, (void *)2},
{"w", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_w_doc, (void *)3},
{"length", (getter)Vector_length_get, (setter)Vector_length_set, Vector_length_doc, NULL},
{"length_squared",
(getter)Vector_length_squared_get,
(setter)NULL,
Vector_length_squared_doc,
NULL},
{"magnitude", (getter)Vector_length_get, (setter)Vector_length_set, Vector_length_doc, NULL},
{"is_wrapped",
(getter)BaseMathObject_is_wrapped_get,
(setter)NULL,
BaseMathObject_is_wrapped_doc,
NULL},
{"is_frozen",
(getter)BaseMathObject_is_frozen_get,
(setter)NULL,
BaseMathObject_is_frozen_doc,
NULL},
{"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
/* autogenerated swizzle attrs, see Python script above */
{"xx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(0, 0)},
{"xxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 0)},
{"xxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 0)},
{"xxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 1)},
{"xxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 2)},
{"xxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 3)},
{"xxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 1)},
{"xxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 0)},
{"xxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 1)},
{"xxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 2)},
{"xxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 3)},
{"xxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 2)},
{"xxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 0)},
{"xxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 1)},
{"xxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 2)},
{"xxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 3)},
{"xxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 3)},
{"xxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 0)},
{"xxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 1)},
{"xxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 2)},
{"xxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 3)},
{"xy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 1)},
{"xyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 0)},
{"xyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 0)},
{"xyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 1)},
{"xyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 2)},
{"xyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 3)},
{"xyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 1)},
{"xyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 0)},
{"xyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 1)},
{"xyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 2)},
{"xyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 3)},
{"xyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 2)},
{"xyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 0)},
{"xyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 1)},
{"xyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 2)},
{"xyzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 2, 3)},
{"xyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 3)},
{"xywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 0)},
{"xywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 1)},
{"xywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 3, 2)},
{"xyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 3)},
{"xz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 2)},
{"xzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 0)},
{"xzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 0)},
{"xzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 1)},
{"xzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 2)},
{"xzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 3)},
{"xzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 1)},
{"xzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 0)},
{"xzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 1)},
{"xzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 2)},
{"xzyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 1, 3)},
{"xzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 2)},
{"xzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 0)},
{"xzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 1)},
{"xzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 2)},
{"xzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 3)},
{"xzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 3)},
{"xzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 0)},
{"xzwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 3, 1)},
{"xzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 2)},
{"xzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 3)},
{"xw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 3)},
{"xwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 0)},
{"xwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 0)},
{"xwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 1)},
{"xwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 2)},
{"xwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 3)},
{"xwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 1)},
{"xwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 0)},
{"xwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 1)},
{"xwyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 1, 2)},
{"xwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 3)},
{"xwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 2)},
{"xwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 0)},
{"xwzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 2, 1)},
{"xwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 2)},
{"xwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 3)},
{"xww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 3)},
{"xwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 0)},
{"xwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 1)},
{"xwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 2)},
{"xwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 3)},
{"yx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 0)},
{"yxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 0)},
{"yxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 0)},
{"yxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 1)},
{"yxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 2)},
{"yxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 3)},
{"yxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 1)},
{"yxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 0)},
{"yxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 1)},
{"yxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 2)},
{"yxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 3)},
{"yxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 2)},
{"yxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 0)},
{"yxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 1)},
{"yxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 2)},
{"yxzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 2, 3)},
{"yxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 3)},
{"yxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 0)},
{"yxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 1)},
{"yxwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 3, 2)},
{"yxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 3)},
{"yy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(1, 1)},
{"yyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 0)},
{"yyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 0)},
{"yyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 1)},
{"yyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 2)},
{"yyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 3)},
{"yyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 1)},
{"yyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 0)},
{"yyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 1)},
{"yyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 2)},
{"yyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 3)},
{"yyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 2)},
{"yyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 0)},
{"yyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 1)},
{"yyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 2)},
{"yyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 3)},
{"yyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 3)},
{"yywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 0)},
{"yywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 1)},
{"yywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 2)},
{"yyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 3)},
{"yz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 2)},
{"yzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 0)},
{"yzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 0)},
{"yzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 1)},
{"yzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 2)},
{"yzxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 0, 3)},
{"yzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 1)},
{"yzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 0)},
{"yzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 1)},
{"yzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 2)},
{"yzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 3)},
{"yzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 2)},
{"yzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 0)},
{"yzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 1)},
{"yzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 2)},
{"yzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 3)},
{"yzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 3)},
{"yzwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 3, 0)},
{"yzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 1)},
{"yzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 2)},
{"yzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 3)},
{"yw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 3)},
{"ywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 0)},
{"ywxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 0)},
{"ywxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 1)},
{"ywxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 0, 2)},
{"ywxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 3)},
{"ywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 1)},
{"ywyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 0)},
{"ywyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 1)},
{"ywyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 2)},
{"ywyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 3)},
{"ywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 2)},
{"ywzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 2, 0)},
{"ywzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 1)},
{"ywzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 2)},
{"ywzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 3)},
{"yww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 3)},
{"ywwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 0)},
{"ywwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 1)},
{"ywwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 2)},
{"ywww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 3)},
{"zx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 0)},
{"zxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 0)},
{"zxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 0)},
{"zxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 1)},
{"zxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 2)},
{"zxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 3)},
{"zxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 1)},
{"zxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 0)},
{"zxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 1)},
{"zxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 2)},
{"zxyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 1, 3)},
{"zxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 2)},
{"zxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 0)},
{"zxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 1)},
{"zxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 2)},
{"zxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 3)},
{"zxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 3)},
{"zxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 0)},
{"zxwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 3, 1)},
{"zxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 2)},
{"zxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 3)},
{"zy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 1)},
{"zyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 0)},
{"zyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 0)},
{"zyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 1)},
{"zyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 2)},
{"zyxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 0, 3)},
{"zyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 1)},
{"zyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 0)},
{"zyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 1)},
{"zyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 2)},
{"zyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 3)},
{"zyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 2)},
{"zyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 0)},
{"zyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 1)},
{"zyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 2)},
{"zyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 3)},
{"zyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 3)},
{"zywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 3, 0)},
{"zywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 1)},
{"zywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 2)},
{"zyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 3)},
{"zz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(2, 2)},
{"zzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 0)},
{"zzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 0)},
{"zzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 1)},
{"zzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 2)},
{"zzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 3)},
{"zzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 1)},
{"zzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 0)},
{"zzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 1)},
{"zzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 2)},
{"zzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 3)},
{"zzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 2)},
{"zzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 0)},
{"zzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 1)},
{"zzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 2)},
{"zzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 3)},
{"zzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 3)},
{"zzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 0)},
{"zzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 1)},
{"zzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 2)},
{"zzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 3)},
{"zw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 3)},
{"zwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 0)},
{"zwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 0)},
{"zwxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 0, 1)},
{"zwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 2)},
{"zwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 3)},
{"zwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 1)},
{"zwyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 1, 0)},
{"zwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 1)},
{"zwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 2)},
{"zwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 3)},
{"zwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 2)},
{"zwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 0)},
{"zwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 1)},
{"zwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 2)},
{"zwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 3)},
{"zww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 3)},
{"zwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 0)},
{"zwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 1)},
{"zwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 2)},
{"zwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 3)},
{"wx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 0)},
{"wxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 0)},
{"wxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 0)},
{"wxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 1)},
{"wxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 2)},
{"wxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 3)},
{"wxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 1)},
{"wxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 0)},
{"wxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 1)},
{"wxyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 1, 2)},
{"wxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 3)},
{"wxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 2)},
{"wxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 0)},
{"wxzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 2, 1)},
{"wxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 2)},
{"wxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 3)},
{"wxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 3)},
{"wxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 0)},
{"wxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 1)},
{"wxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 2)},
{"wxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 3)},
{"wy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 1)},
{"wyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 0)},
{"wyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 0)},
{"wyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 1)},
{"wyxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 0, 2)},
{"wyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 3)},
{"wyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 1)},
{"wyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 0)},
{"wyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 1)},
{"wyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 2)},
{"wyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 3)},
{"wyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 2)},
{"wyzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 2, 0)},
{"wyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 1)},
{"wyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 2)},
{"wyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 3)},
{"wyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 3)},
{"wywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 0)},
{"wywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 1)},
{"wywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 2)},
{"wyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 3)},
{"wz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 2)},
{"wzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 0)},
{"wzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 0)},
{"wzxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 0, 1)},
{"wzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 2)},
{"wzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 3)},
{"wzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 1)},
{"wzyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 1, 0)},
{"wzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 1)},
{"wzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 2)},
{"wzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 3)},
{"wzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 2)},
{"wzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 0)},
{"wzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 1)},
{"wzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 2)},
{"wzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 3)},
{"wzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 3)},
{"wzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 0)},
{"wzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 1)},
{"wzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 2)},
{"wzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 3)},
{"ww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(3, 3)},
{"wwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 0)},
{"wwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 0)},
{"wwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 1)},
{"wwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 2)},
{"wwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 3)},
{"wwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 1)},
{"wwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 0)},
{"wwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 1)},
{"wwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 2)},
{"wwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 3)},
{"wwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 2)},
{"wwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 0)},
{"wwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 1)},
{"wwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 2)},
{"wwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 3)},
{"www", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 3)},
{"wwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 0)},
{"wwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 1)},
{"wwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 2)},
{"wwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 3)},
#undef AXIS_FROM_CHAR
#undef SWIZZLE1
#undef SWIZZLE2
#undef SWIZZLE3
#undef SWIZZLE4
#undef _SWIZZLE1
#undef _SWIZZLE2
#undef _SWIZZLE3
#undef _SWIZZLE4
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/**
* Row vector multiplication - (Vector * Matrix)
* <pre>
* [x][y][z] * [1][4][7]
* [2][5][8]
* [3][6][9]
* </pre>
* \note vector/matrix multiplication is not commutative.
*/
static int row_vector_multiplication(float r_vec[MAX_DIMENSIONS],
VectorObject *vec,
MatrixObject *mat)
{
float vec_cpy[MAX_DIMENSIONS];
int row, col, z = 0, vec_size = vec->size;
if (mat->num_row != vec_size) {
if (mat->num_row == 4 && vec_size == 3) {
vec_cpy[3] = 1.0f;
}
else {
PyErr_SetString(PyExc_ValueError,
"vector * matrix: matrix column size "
"and the vector size must be the same");
return -1;
}
}
if (BaseMath_ReadCallback(vec) == -1 || BaseMath_ReadCallback(mat) == -1) {
return -1;
}
memcpy(vec_cpy, vec->vec, vec_size * sizeof(float));
r_vec[3] = 1.0f;
/* muliplication */
for (col = 0; col < mat->num_col; col++) {
double dot = 0.0;
for (row = 0; row < mat->num_row; row++) {
dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[row]);
}
r_vec[z++] = (float)dot;
}
return 0;
}
/*----------------------------Vector.negate() -------------------- */
PyDoc_STRVAR(Vector_negate_doc,
".. method:: negate()\n"
"\n"
" Set all values to their negative.\n");
static PyObject *Vector_negate(VectorObject *self)
{
if (BaseMath_ReadCallback(self) == -1) {
return NULL;
}
negate_vn(self->vec, self->size);
(void)BaseMath_WriteCallback(self); /* already checked for error */
Py_RETURN_NONE;
}
static struct PyMethodDef Vector_methods[] = {
/* Class Methods */
{"Fill", (PyCFunction)C_Vector_Fill, METH_VARARGS | METH_CLASS, C_Vector_Fill_doc},
{"Range", (PyCFunction)C_Vector_Range, METH_VARARGS | METH_CLASS, C_Vector_Range_doc},
{"Linspace", (PyCFunction)C_Vector_Linspace, METH_VARARGS | METH_CLASS, C_Vector_Linspace_doc},
{"Repeat", (PyCFunction)C_Vector_Repeat, METH_VARARGS | METH_CLASS, C_Vector_Repeat_doc},
/* in place only */
{"zero", (PyCFunction)Vector_zero, METH_NOARGS, Vector_zero_doc},
{"negate", (PyCFunction)Vector_negate, METH_NOARGS, Vector_negate_doc},
/* operate on original or copy */
{"normalize", (PyCFunction)Vector_normalize, METH_NOARGS, Vector_normalize_doc},
{"normalized", (PyCFunction)Vector_normalized, METH_NOARGS, Vector_normalized_doc},
{"resize", (PyCFunction)Vector_resize, METH_O, Vector_resize_doc},
{"resized", (PyCFunction)Vector_resized, METH_O, Vector_resized_doc},
{"to_2d", (PyCFunction)Vector_to_2d, METH_NOARGS, Vector_to_2d_doc},
{"resize_2d", (PyCFunction)Vector_resize_2d, METH_NOARGS, Vector_resize_2d_doc},
{"to_3d", (PyCFunction)Vector_to_3d, METH_NOARGS, Vector_to_3d_doc},
{"resize_3d", (PyCFunction)Vector_resize_3d, METH_NOARGS, Vector_resize_3d_doc},
{"to_4d", (PyCFunction)Vector_to_4d, METH_NOARGS, Vector_to_4d_doc},
{"resize_4d", (PyCFunction)Vector_resize_4d, METH_NOARGS, Vector_resize_4d_doc},
{"to_tuple", (PyCFunction)Vector_to_tuple, METH_VARARGS, Vector_to_tuple_doc},
{"to_track_quat", (PyCFunction)Vector_to_track_quat, METH_VARARGS, Vector_to_track_quat_doc},
{"orthogonal", (PyCFunction)Vector_orthogonal, METH_NOARGS, Vector_orthogonal_doc},
/* operation between 2 or more types */
{"reflect", (PyCFunction)Vector_reflect, METH_O, Vector_reflect_doc},
{"cross", (PyCFunction)Vector_cross, METH_O, Vector_cross_doc},
{"dot", (PyCFunction)Vector_dot, METH_O, Vector_dot_doc},
{"angle", (PyCFunction)Vector_angle, METH_VARARGS, Vector_angle_doc},
{"angle_signed", (PyCFunction)Vector_angle_signed, METH_VARARGS, Vector_angle_signed_doc},
{"rotation_difference",
(PyCFunction)Vector_rotation_difference,
METH_O,
Vector_rotation_difference_doc},
{"project", (PyCFunction)Vector_project, METH_O, Vector_project_doc},
{"lerp", (PyCFunction)Vector_lerp, METH_VARARGS, Vector_lerp_doc},
{"slerp", (PyCFunction)Vector_slerp, METH_VARARGS, Vector_slerp_doc},
{"rotate", (PyCFunction)Vector_rotate, METH_O, Vector_rotate_doc},
/* base-math methods */
{"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
{"copy", (PyCFunction)Vector_copy, METH_NOARGS, Vector_copy_doc},
{"__copy__", (PyCFunction)Vector_copy, METH_NOARGS, NULL},
{"__deepcopy__", (PyCFunction)Vector_deepcopy, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL},
};
/**
* Note:
* #Py_TPFLAGS_CHECKTYPES allows us to avoid casting all types to Vector when coercing
* but this means for eg that (vec * mat) and (mat * vec)
* both get sent to Vector_mul and it needs to sort out the order
*/
PyDoc_STRVAR(vector_doc,
".. class:: Vector(seq)\n"
"\n"
" This object gives access to Vectors in Blender.\n"
"\n"
" :param seq: Components of the vector, must be a sequence of at least two\n"
" :type seq: sequence of numbers\n");
PyTypeObject vector_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* For printing, in format "<module>.<name>" */
"Vector", /* char *tp_name; */
sizeof(VectorObject), /* int tp_basicsize; */
0, /* tp_itemsize; For allocation */
/* Methods to implement standard operations */
(destructor)BaseMathObject_dealloc, /* destructor tp_dealloc; */
(printfunc)NULL, /* printfunc tp_print; */
NULL, /* getattrfunc tp_getattr; */
NULL, /* setattrfunc tp_setattr; */
NULL, /* cmpfunc tp_compare; */
(reprfunc)Vector_repr, /* reprfunc tp_repr; */
/* Method suites for standard classes */
&Vector_NumMethods, /* PyNumberMethods *tp_as_number; */
&Vector_SeqMethods, /* PySequenceMethods *tp_as_sequence; */
&Vector_AsMapping, /* PyMappingMethods *tp_as_mapping; */
/* More standard operations (here for binary compatibility) */
(hashfunc)Vector_hash, /* hashfunc tp_hash; */
NULL, /* ternaryfunc tp_call; */
#ifndef MATH_STANDALONE
(reprfunc)Vector_str, /* reprfunc tp_str; */
#else
NULL, /* reprfunc tp_str; */
#endif
NULL, /* getattrofunc tp_getattro; */
NULL, /* setattrofunc tp_setattro; */
/* Functions to access object as input/output buffer */
NULL, /* PyBufferProcs *tp_as_buffer; */
/*** Flags to define presence of optional/expanded features ***/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
vector_doc, /* char *tp_doc; Documentation string */
/*** Assigned meaning in release 2.0 ***/
/* call function for all accessible objects */
(traverseproc)BaseMathObject_traverse, /* tp_traverse */
/* delete references to contained objects */
(inquiry)BaseMathObject_clear, /* tp_clear */
/*** Assigned meaning in release 2.1 ***/
/*** rich comparisons ***/
(richcmpfunc)Vector_richcmpr, /* richcmpfunc tp_richcompare; */
/*** weak reference enabler ***/
0, /* long tp_weaklistoffset; */
/*** Added in release 2.2 ***/
/* Iterators */
NULL, /* getiterfunc tp_iter; */
NULL, /* iternextfunc tp_iternext; */
/*** Attribute descriptor and subclassing stuff ***/
Vector_methods, /* struct PyMethodDef *tp_methods; */
NULL, /* struct PyMemberDef *tp_members; */
Vector_getseters, /* struct PyGetSetDef *tp_getset; */
NULL, /* struct _typeobject *tp_base; */
NULL, /* PyObject *tp_dict; */
NULL, /* descrgetfunc tp_descr_get; */
NULL, /* descrsetfunc tp_descr_set; */
0, /* long tp_dictoffset; */
NULL, /* initproc tp_init; */
NULL, /* allocfunc tp_alloc; */
Vector_new, /* newfunc tp_new; */
/* Low-level free-memory routine */
NULL, /* freefunc tp_free; */
/* For PyObject_IS_GC */
NULL, /* inquiry tp_is_gc; */
NULL, /* PyObject *tp_bases; */
/* method resolution order */
NULL, /* PyObject *tp_mro; */
NULL, /* PyObject *tp_cache; */
NULL, /* PyObject *tp_subclasses; */
NULL, /* PyObject *tp_weaklist; */
NULL,
};
PyObject *Vector_CreatePyObject(const float *vec, const int size, PyTypeObject *base_type)
{
VectorObject *self;
float *vec_alloc;
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
return NULL;
}
vec_alloc = PyMem_Malloc(size * sizeof(float));
if (UNLIKELY(vec_alloc == NULL)) {
PyErr_SetString(PyExc_MemoryError,
"Vector(): "
"problem allocating data");
return NULL;
}
self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
if (self) {
self->vec = vec_alloc;
self->size = size;
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
if (vec) {
memcpy(self->vec, vec, size * sizeof(float));
}
else { /* new empty */
copy_vn_fl(self->vec, size, 0.0f);
if (size == 4) { /* do the homogeneous thing */
self->vec[3] = 1.0f;
}
}
self->flag = BASE_MATH_FLAG_DEFAULT;
}
else {
PyMem_Free(vec_alloc);
}
return (PyObject *)self;
}
/**
* Create a vector that wraps existing memory.
*
* \param vec: Use this vector in-place.
*/
PyObject *Vector_CreatePyObject_wrap(float *vec, const int size, PyTypeObject *base_type)
{
VectorObject *self;
if (size < 2) {
PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
return NULL;
}
self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
if (self) {
self->size = size;
/* init callbacks as NULL */
self->cb_user = NULL;
self->cb_type = self->cb_subtype = 0;
self->vec = vec;
self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
}
return (PyObject *)self;
}
/**
* Create a vector where the value is defined by registered callbacks,
* see: #Mathutils_RegisterCallback
*/
PyObject *Vector_CreatePyObject_cb(PyObject *cb_user, int size, uchar cb_type, uchar cb_subtype)
{
VectorObject *self = (VectorObject *)Vector_CreatePyObject(NULL, size, NULL);
if (self) {
Py_INCREF(cb_user);
self->cb_user = cb_user;
self->cb_type = cb_type;
self->cb_subtype = cb_subtype;
PyObject_GC_Track(self);
}
return (PyObject *)self;
}
/**
* \param vec: Initialized vector value to use in-place, allocated with #PyMem_Malloc
*/
PyObject *Vector_CreatePyObject_alloc(float *vec, const int size, PyTypeObject *base_type)
{
VectorObject *self;
self = (VectorObject *)Vector_CreatePyObject_wrap(vec, size, base_type);
if (self) {
self->flag &= ~BASE_MATH_FLAG_IS_WRAP;
}
return (PyObject *)self;
}