Blender V5.3
mathutils_Matrix.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10
11#include <Python.h>
12
13#include "mathutils.hh"
14
15#include "BLI_math_matrix_c.hh"
17#include "BLI_math_vector_c.hh"
18#include "BLI_utildefines.hh"
19
22
23#ifndef MATH_STANDALONE
24# include "BLI_dynstr.hh"
25# include "BLI_string_utf8.hh"
26#endif
27
28namespace blender {
29
34
35static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix);
36static PyObject *Matrix_copy(MatrixObject *self);
37static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args);
38static int Matrix_ass_slice(MatrixObject *self,
39 Py_ssize_t start,
40 Py_ssize_t step,
41 Py_ssize_t slice_length,
42 PyObject *value);
43static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
44 MatrixObject *self);
45static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type);
46
47/* -------------------------------------------------------------------- */
50
51static int matrix_row_vector_check(MatrixObject *mat, VectorObject *vec, int row)
52{
53 if ((vec->vec_num != mat->col_num) || (row >= mat->row_num)) {
54 PyErr_SetString(PyExc_AttributeError,
55 "Matrix(): "
56 "owner matrix has been resized since this row vector was created");
57 return 0;
58 }
59
60 return 1;
61}
62
63static int matrix_col_vector_check(MatrixObject *mat, VectorObject *vec, int col)
64{
65 if ((vec->vec_num != mat->row_num) || (col >= mat->col_num)) {
66 PyErr_SetString(PyExc_AttributeError,
67 "Matrix(): "
68 "owner matrix has been resized since this column vector was created");
69 return 0;
70 }
71
72 return 1;
73}
74
76static void matrix_3x3_as_4x4(float mat[16])
77{
78 mat[10] = mat[8];
79 mat[9] = mat[7];
80 mat[8] = mat[6];
81 mat[7] = 0.0f;
82 mat[6] = mat[5];
83 mat[5] = mat[4];
84 mat[4] = mat[3];
85 mat[3] = 0.0f;
86}
87
88void matrix_as_3x3(float mat[3][3], MatrixObject *self)
89{
90 copy_v3_v3(mat[0], MATRIX_COL_PTR(self, 0));
91 copy_v3_v3(mat[1], MATRIX_COL_PTR(self, 1));
92 copy_v3_v3(mat[2], MATRIX_COL_PTR(self, 2));
93}
94
95static void matrix_copy(MatrixObject *mat_dst, const MatrixObject *mat_src)
96{
97 BLI_assert((mat_dst->col_num == mat_src->col_num) && (mat_dst->row_num == mat_src->row_num));
98 BLI_assert(mat_dst != mat_src);
99
100 memcpy(mat_dst->matrix, mat_src->matrix, sizeof(float) * (mat_dst->col_num * mat_dst->row_num));
101}
102
104{
105 const int mat_size = sizeof(float) * (self->col_num * self->row_num);
106 memset(self->matrix, 0x0, mat_size);
107 const int col_row_max = min_ii(self->col_num, self->row_num);
108 const int row_num = self->row_num;
109 for (int col = 0; col < col_row_max; col++) {
110 self->matrix[(col * row_num) + col] = 1.0f;
111 }
112}
113
115static void matrix_transpose_internal(float mat_dst_fl[], const MatrixObject *mat_src)
116{
117 ushort col, row;
118 uint i = 0;
119
120 for (row = 0; row < mat_src->row_num; row++) {
121 for (col = 0; col < mat_src->col_num; col++) {
122 mat_dst_fl[i++] = MATRIX_ITEM(mat_src, row, col);
123 }
124 }
125}
126
129{
130 if (self->col_num == 2) {
131 return determinant_m2(MATRIX_ITEM(self, 0, 0),
132 MATRIX_ITEM(self, 0, 1),
133 MATRIX_ITEM(self, 1, 0),
134 MATRIX_ITEM(self, 1, 1));
135 }
136 if (self->col_num == 3) {
137 return determinant_m3(MATRIX_ITEM(self, 0, 0),
138 MATRIX_ITEM(self, 0, 1),
139 MATRIX_ITEM(self, 0, 2),
140 MATRIX_ITEM(self, 1, 0),
141 MATRIX_ITEM(self, 1, 1),
142 MATRIX_ITEM(self, 1, 2),
143 MATRIX_ITEM(self, 2, 0),
144 MATRIX_ITEM(self, 2, 1),
145 MATRIX_ITEM(self, 2, 2));
146 }
147
148 return determinant_m4(reinterpret_cast<const float (*)[4]>(self->matrix));
149}
150
151static void adjoint_matrix_n(float *mat_dst, const float *mat_src, const ushort dim)
152{
153 /* calculate the classical adjoint */
154 switch (dim) {
155 case 2: {
156 adjoint_m2_m2(reinterpret_cast<float (*)[2]>(mat_dst),
157 reinterpret_cast<const float (*)[2]>(mat_src));
158 break;
159 }
160 case 3: {
161 adjoint_m3_m3(reinterpret_cast<float (*)[3]>(mat_dst),
162 reinterpret_cast<const float (*)[3]>(mat_src));
163 break;
164 }
165 case 4: {
166 adjoint_m4_m4(reinterpret_cast<float (*)[4]>(mat_dst),
167 reinterpret_cast<const float (*)[4]>(mat_src));
168 break;
169 }
170 default:
172 break;
173 }
174}
175
176static void matrix_invert_with_det_n_internal(float *mat_dst,
177 const float *mat_src,
178 const float det,
179 const ushort dim)
180{
181 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
182 ushort i, j, k;
183
184 BLI_assert(det != 0.0f);
185
186 adjoint_matrix_n(mat, mat_src, dim);
187
188 /* divide by determinant & set values */
189 k = 0;
190 for (i = 0; i < dim; i++) { /* col_num */
191 for (j = 0; j < dim; j++) { /* row_num */
192 mat_dst[MATRIX_ITEM_INDEX_NUMROW(dim, j, i)] = mat[k++] / det;
193 }
194 }
195}
196
200static bool matrix_invert_internal(const MatrixObject *self, float *r_mat)
201{
202 float det;
203 BLI_assert(self->col_num == self->row_num);
204 det = matrix_determinant_internal(self);
205
206 if (det != 0.0f) {
207 matrix_invert_with_det_n_internal(r_mat, self->matrix, det, self->col_num);
208 return true;
209 }
210
211 return false;
212}
213
218static void matrix_invert_safe_internal(const MatrixObject *self, float *r_mat)
219{
220 float det;
221 float *in_mat = self->matrix;
222 BLI_assert(self->col_num == self->row_num);
223 det = matrix_determinant_internal(self);
224
225 if (det == 0.0f) {
226 const float eps = PSEUDOINVERSE_EPSILON;
227
228 /* We will copy self->matrix into r_mat (if needed),
229 * and modify it in place to add diagonal epsilon. */
230 in_mat = r_mat;
231
232 switch (self->col_num) {
233 case 2: {
234 float (*mat)[2] = reinterpret_cast<float (*)[2]>(in_mat);
235
236 if (in_mat != self->matrix) {
237 copy_m2_m2(mat, reinterpret_cast<const float (*)[2]>(self->matrix));
238 }
239 mat[0][0] += eps;
240 mat[1][1] += eps;
241
242 if ((det = determinant_m2(mat[0][0], mat[0][1], mat[1][0], mat[1][1])) == 0.0f)
243 [[unlikely]]
244 {
245 unit_m2(mat);
246 det = 1.0f;
247 }
248 break;
249 }
250 case 3: {
251 float (*mat)[3] = reinterpret_cast<float (*)[3]>(in_mat);
252
253 if (in_mat != self->matrix) {
254 copy_m3_m3(mat, reinterpret_cast<const float (*)[3]>(self->matrix));
255 }
256 mat[0][0] += eps;
257 mat[1][1] += eps;
258 mat[2][2] += eps;
259
260 if ((det = determinant_m3_array(mat)) == 0.0f) [[unlikely]] {
261 unit_m3(mat);
262 det = 1.0f;
263 }
264 break;
265 }
266 case 4: {
267 float (*mat)[4] = reinterpret_cast<float (*)[4]>(in_mat);
268
269 if (in_mat != self->matrix) {
270 copy_m4_m4(mat, reinterpret_cast<const float (*)[4]>(self->matrix));
271 }
272 mat[0][0] += eps;
273 mat[1][1] += eps;
274 mat[2][2] += eps;
275 mat[3][3] += eps;
276
277 if (UNLIKELY(det = determinant_m4(mat)) == 0.0f) {
278 unit_m4(mat);
279 det = 1.0f;
280 }
281 break;
282 }
283 default:
285 }
286 }
287
288 matrix_invert_with_det_n_internal(r_mat, in_mat, det, self->col_num);
289}
290
291static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
292 MatrixObject *self)
293{
294 PyObject *ret = Matrix_copy(self);
295 if (ret) {
296 PyObject *ret_dummy = matrix_func(reinterpret_cast<MatrixObject *>(ret));
297 if (ret_dummy) {
298 Py_DECREF(ret_dummy);
299 return ret;
300 }
301 /* error */
302 Py_DECREF(ret);
303 return nullptr;
304 }
305
306 /* copy may fail if the read callback errors out */
307 return nullptr;
308}
309
311{
312 for (int row = 0; row < self->row_num; row++) {
313 for (int col = 0; col < self->col_num; col++) {
314 if (MATRIX_ITEM(self, row, col) != ((row != col) ? 0.0f : 1.0f)) {
315 return false;
316 }
317 }
318 }
319 return true;
320}
321
323
324/* -------------------------------------------------------------------- */
328
330
332{
333 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
334 return BaseMath_ReadCallback(self);
335}
336
338{
339 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
340 int col;
341
342 if (BaseMath_ReadCallback(self) == -1) {
343 return -1;
344 }
345 if (!matrix_row_vector_check(self, reinterpret_cast<VectorObject *>(bmo), row)) {
346 return -1;
347 }
348
349 for (col = 0; col < self->col_num; col++) {
350 bmo->data[col] = MATRIX_ITEM(self, row, col);
351 }
352
353 return 0;
354}
355
357{
358 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
359 int col;
360
361 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
362 return -1;
363 }
364 if (!matrix_row_vector_check(self, reinterpret_cast<VectorObject *>(bmo), row)) {
365 return -1;
366 }
367
368 for (col = 0; col < self->col_num; col++) {
369 MATRIX_ITEM(self, row, col) = bmo->data[col];
370 }
371
372 (void)BaseMath_WriteCallback(self);
373 return 0;
374}
375
376static int mathutils_matrix_row_get_index(BaseMathObject *bmo, int row, int col)
377{
378 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
379
380 if (BaseMath_ReadCallback(self) == -1) {
381 return -1;
382 }
383 if (!matrix_row_vector_check(self, reinterpret_cast<VectorObject *>(bmo), row)) {
384 return -1;
385 }
386
387 bmo->data[col] = MATRIX_ITEM(self, row, col);
388 return 0;
389}
390
391static int mathutils_matrix_row_set_index(BaseMathObject *bmo, int row, int col)
392{
393 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
394
395 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
396 return -1;
397 }
398 if (!matrix_row_vector_check(self, reinterpret_cast<VectorObject *>(bmo), row)) {
399 return -1;
400 }
401
402 MATRIX_ITEM(self, row, col) = bmo->data[col];
403
404 (void)BaseMath_WriteCallback(self);
405 return 0;
406}
407
415
417
418/* -------------------------------------------------------------------- */
422
424
426{
427 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
428 return BaseMath_ReadCallback(self);
429}
430
432{
433 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
434 int row_num;
435 int row;
436
437 if (BaseMath_ReadCallback(self) == -1) {
438 return -1;
439 }
440 if (!matrix_col_vector_check(self, reinterpret_cast<VectorObject *>(bmo), col)) {
441 return -1;
442 }
443
444 /* for 'translation' `vec_num` will always be '3' even on 4x4 vec */
445 row_num = min_ii(self->row_num, (reinterpret_cast<const VectorObject *>(bmo))->vec_num);
446
447 for (row = 0; row < row_num; row++) {
448 bmo->data[row] = MATRIX_ITEM(self, row, col);
449 }
450
451 return 0;
452}
453
455{
456 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
457 int row_num;
458 int row;
459
460 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
461 return -1;
462 }
463 if (!matrix_col_vector_check(self, reinterpret_cast<VectorObject *>(bmo), col)) {
464 return -1;
465 }
466
467 /* for 'translation' `vec_num` will always be '3' even on 4x4 vec */
468 row_num = min_ii(self->row_num, (reinterpret_cast<const VectorObject *>(bmo))->vec_num);
469
470 for (row = 0; row < row_num; row++) {
471 MATRIX_ITEM(self, row, col) = bmo->data[row];
472 }
473
474 (void)BaseMath_WriteCallback(self);
475 return 0;
476}
477
478static int mathutils_matrix_col_get_index(BaseMathObject *bmo, int col, int row)
479{
480 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
481
482 if (BaseMath_ReadCallback(self) == -1) {
483 return -1;
484 }
485 if (!matrix_col_vector_check(self, reinterpret_cast<VectorObject *>(bmo), col)) {
486 return -1;
487 }
488
489 bmo->data[row] = MATRIX_ITEM(self, row, col);
490 return 0;
491}
492
493static int mathutils_matrix_col_set_index(BaseMathObject *bmo, int col, int row)
494{
495 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
496
497 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
498 return -1;
499 }
500 if (!matrix_col_vector_check(self, reinterpret_cast<VectorObject *>(bmo), col)) {
501 return -1;
502 }
503
504 MATRIX_ITEM(self, row, col) = bmo->data[row];
505
506 (void)BaseMath_WriteCallback(self);
507 return 0;
508}
509
517
519
520/* -------------------------------------------------------------------- */
526
528
530{
531 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
532 return BaseMath_ReadCallback(self);
533}
534
536{
537 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
538 int row;
539
540 if (BaseMath_ReadCallback(self) == -1) {
541 return -1;
542 }
543
544 for (row = 0; row < 3; row++) {
545 bmo->data[row] = MATRIX_ITEM(self, row, col);
546 }
547
548 return 0;
549}
550
552{
553 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
554 int row;
555
556 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
557 return -1;
558 }
559
560 for (row = 0; row < 3; row++) {
561 MATRIX_ITEM(self, row, col) = bmo->data[row];
562 }
563
564 (void)BaseMath_WriteCallback(self);
565 return 0;
566}
567
569{
570 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
571
572 if (BaseMath_ReadCallback(self) == -1) {
573 return -1;
574 }
575
576 bmo->data[row] = MATRIX_ITEM(self, row, col);
577 return 0;
578}
579
581{
582 MatrixObject *self = reinterpret_cast<MatrixObject *>(bmo->cb_user);
583
584 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
585 return -1;
586 }
587
588 MATRIX_ITEM(self, row, col) = bmo->data[row];
589
590 (void)BaseMath_WriteCallback(self);
591 return 0;
592}
593
601
603
604/* -------------------------------------------------------------------- */
607
608static PyObject *Matrix_vectorcall(PyObject *type,
609 PyObject *const *args,
610 const size_t nargsf,
611 PyObject *kwnames)
612{
613 if (kwnames && PyTuple_GET_SIZE(kwnames)) [[unlikely]] {
614 PyErr_SetString(PyExc_TypeError,
615 "Matrix(): "
616 "takes no keyword args");
617 return nullptr;
618 }
619
620 switch (PyVectorcall_NARGS(nargsf)) {
621 case 0: {
622 return Matrix_CreatePyObject(nullptr, 4, 4, reinterpret_cast<PyTypeObject *>(type));
623 }
624 case 1: {
625 PyObject *arg = args[0];
626
627 /* Input is now as a sequence of rows so length of sequence
628 * is the number of rows */
629 /* -1 is an error, size checks will account for this */
630 const ushort row_num = PySequence_Size(arg);
631
632 if (row_num >= 2 && row_num <= 4) {
633 PyObject *item = PySequence_GetItem(arg, 0);
634 /* Since each item is a row, number of items is the
635 * same as the number of columns */
636 const ushort col_num = PySequence_Size(item);
637 Py_XDECREF(item);
638
639 if (col_num >= 2 && col_num <= 4) {
640 /* Sane row & col size, new matrix and assign as slice. */
641 PyObject *matrix = Matrix_CreatePyObject(
642 nullptr, col_num, row_num, reinterpret_cast<PyTypeObject *>(type));
643 if (Matrix_ass_slice(reinterpret_cast<MatrixObject *>(matrix), 0, 1, row_num, arg) == 0)
644 {
645 return matrix;
646 }
647 /* matrix ok, slice assignment not */
648 Py_DECREF(matrix);
649 }
650 }
651 break;
652 }
653 }
654
655 /* will overwrite error */
656 PyErr_SetString(PyExc_TypeError,
657 "mathutils.Matrix(): "
658 "expects no args or a single arg containing 2-4 numeric sequences");
659 return nullptr;
660}
661
662static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
663{
664 /* Only called on sub-classes. */
665 if (kwds && PyDict_GET_SIZE(kwds)) [[unlikely]] {
666 PyErr_SetString(PyExc_TypeError,
667 "mathutils.Matrix(): "
668 "takes no keyword args");
669 return nullptr;
670 }
671 PyObject *const *args_array = &PyTuple_GET_ITEM(args, 0);
672 const size_t args_array_num = PyTuple_GET_SIZE(args);
673 return Matrix_vectorcall(
674 reinterpret_cast<PyObject *>(type), args_array, args_array_num, nullptr);
675}
676
678
679/* -------------------------------------------------------------------- */
682
685 /* Wrap. */
686 C_Matrix_Identity_doc,
687 ".. classmethod:: Identity(size, /)\n"
688 "\n"
689 " Create an identity matrix.\n"
690 "\n"
691 " :param size: The size of the identity matrix to construct [2, 4].\n"
692 " :type size: int\n"
693 " :return: A new identity matrix.\n"
694 " :rtype: :class:`Matrix`\n");
695static PyObject *C_Matrix_Identity(PyObject *cls, PyObject *args)
696{
697 int matSize;
698
699 if (!PyArg_ParseTuple(args,
700 "i" /* `size` */
701 ":Matrix.Identity",
702 &matSize))
703 {
704 return nullptr;
705 }
706
707 if (matSize < 2 || matSize > 4) {
708 PyErr_SetString(PyExc_RuntimeError,
709 "Matrix.Identity(): "
710 "size must be between 2 and 4");
711 return nullptr;
712 }
713
714 return Matrix_CreatePyObject(nullptr, matSize, matSize, reinterpret_cast<PyTypeObject *>(cls));
715}
716
719 /* Wrap. */
720 C_Matrix_Rotation_doc,
721 ".. classmethod:: Rotation(angle, size, axis=None, /)\n"
722 "\n"
723 " Create a matrix representing a rotation.\n"
724 "\n"
725 " :param angle: The angle of rotation desired, in radians.\n"
726 " :type angle: float\n"
727 " :param size: The size of the rotation matrix to construct [2, 4].\n"
728 " :type size: int\n"
729 " :param axis: Axis of rotation: a single-character string ('X', 'Y' or 'Z')\n"
730 " or a 3D vector. Required for ``size`` 3 or 4. Must be None (or omitted)\n"
731 " when ``size`` is 2 - 2D rotation has no axis.\n"
732 " :type axis: Literal['X', 'Y', 'Z'] | Sequence[float] | None\n"
733 " :return: A new rotation matrix.\n"
734 " :rtype: :class:`Matrix`\n");
735static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
736{
737 PyObject *vec = Py_None;
738 const char *axis = nullptr;
739 int matSize;
740 double angle; /* Use double because of precision problems at high values. */
741 float mat[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
742
743 if (!PyArg_ParseTuple(args,
744 "d" /* `angle` */
745 "i" /* `size` */
746 "|" /* Optional arguments. */
747 "O" /* `axis` */
748 ":Matrix.Rotation",
749 &angle,
750 &matSize,
751 &vec))
752 {
753 return nullptr;
754 }
755
756 if (vec != Py_None && PyUnicode_Check(vec)) {
757 axis = PyUnicode_AsUTF8(vec);
758 if (axis == nullptr || axis[0] == '\0' || axis[1] != '\0' || axis[0] < 'X' || axis[0] > 'Z') {
759 PyErr_SetString(PyExc_ValueError,
760 "Matrix.Rotation(): "
761 "3rd argument axis value must be a 3D vector "
762 "or a string in 'X', 'Y', 'Z'");
763 return nullptr;
764 }
765
766 /* use the string */
767 vec = Py_None;
768 }
769
771
772 if (!ELEM(matSize, 2, 3, 4)) {
773 PyErr_SetString(PyExc_ValueError,
774 "Matrix.Rotation(): "
775 "can only return a 2x2 3x3 or 4x4 matrix");
776 return nullptr;
777 }
778 if (matSize == 2 && (vec != Py_None)) {
779 PyErr_SetString(PyExc_ValueError,
780 "Matrix.Rotation(): "
781 "cannot create a 2x2 rotation matrix around arbitrary axis");
782 return nullptr;
783 }
784 if (ELEM(matSize, 3, 4) && (axis == nullptr) && (vec == Py_None)) {
785 PyErr_SetString(PyExc_ValueError,
786 "Matrix.Rotation(): "
787 "axis of rotation for 3d and 4d matrices is required");
788 return nullptr;
789 }
790
791 /* check for valid vector/axis above */
792 if (vec != Py_None) {
793 float tvec[3];
794
796 tvec, 3, 3, vec, "Matrix.Rotation(angle, size, axis), invalid 'axis' arg") == -1)
797 {
798 return nullptr;
799 }
800
801 axis_angle_to_mat3(reinterpret_cast<float (*)[3]>(mat), tvec, angle);
802 }
803 else if (matSize == 2) {
804 angle_to_mat2(reinterpret_cast<float (*)[2]>(mat), angle);
805 }
806 else {
807 /* valid axis checked above */
808 axis_angle_to_mat3_single(reinterpret_cast<float (*)[3]>(mat), axis[0], angle);
809 }
810
811 if (matSize == 4) {
813 }
814 /* pass to matrix creation */
815 return Matrix_CreatePyObject(mat, matSize, matSize, reinterpret_cast<PyTypeObject *>(cls));
816}
817
820 /* Wrap. */
821 C_Matrix_Translation_doc,
822 ".. classmethod:: Translation(vector, /)\n"
823 "\n"
824 " Create a matrix representing a translation.\n"
825 "\n"
826 " :param vector: The translation vector.\n"
827 " :type vector: Sequence[float]\n"
828 " :return: An identity matrix with a translation.\n"
829 " :rtype: :class:`Matrix`\n");
830static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
831{
832 float mat[4][4];
833
834 unit_m4(mat);
835
837 mat[3], 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1)
838 {
839 return nullptr;
840 }
841
842 return Matrix_CreatePyObject(&mat[0][0], 4, 4, reinterpret_cast<PyTypeObject *>(cls));
843}
844
846 /* Wrap. */
847 C_Matrix_Diagonal_doc,
848 ".. classmethod:: Diagonal(vector, /)\n"
849 "\n"
850 " Create a diagonal (scaling) matrix using the values from the vector.\n"
851 "\n"
852 " :param vector: The vector of values for the diagonal.\n"
853 " :type vector: Sequence[float]\n"
854 " :return: A diagonal matrix.\n"
855 " :rtype: :class:`Matrix`\n");
857static PyObject *C_Matrix_Diagonal(PyObject *cls, PyObject *value)
858{
859 float mat[16] = {0.0f};
860 float vec[4];
861
862 int size = mathutils_array_parse(
863 vec, 2, 4, value, "mathutils.Matrix.Diagonal(vector), invalid vector arg");
864
865 if (size == -1) {
866 return nullptr;
867 }
868
869 for (int i = 0; i < size; i++) {
870 mat[size * i + i] = vec[i];
871 }
872
873 return Matrix_CreatePyObject(mat, size, size, reinterpret_cast<PyTypeObject *>(cls));
874}
875
878 /* Wrap. */
879 C_Matrix_Scale_doc,
880 ".. classmethod:: Scale(factor, size, axis=None, /)\n"
881 "\n"
882 " Create a matrix representing a scaling.\n"
883 "\n"
884 " :param factor: The factor of scaling to apply.\n"
885 " :type factor: float\n"
886 " :param size: The size of the scale matrix to construct [2, 4].\n"
887 " :type size: int\n"
888 " :param axis: Direction along which to scale. When None (or omitted),\n"
889 " ``factor`` is applied uniformly along all axes.\n"
890 " :type axis: Sequence[float] | None\n"
891 " :return: A new scale matrix.\n"
892 " :rtype: :class:`Matrix`\n");
893static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
894{
895 PyObject *vec = Py_None;
896 int vec_num;
897 float tvec[3];
898 float factor;
899 int matSize;
900 float mat[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
901
902 if (!PyArg_ParseTuple(args,
903 "f" /* `factor` */
904 "i" /* `size` */
905 "|" /* Optional arguments. */
906 "O" /* `axis` */
907 ":Matrix.Scale",
908 &factor,
909 &matSize,
910 &vec))
911 {
912 return nullptr;
913 }
914 if (!ELEM(matSize, 2, 3, 4)) {
915 PyErr_SetString(PyExc_ValueError,
916 "Matrix.Scale(): "
917 "can only return a 2x2 3x3 or 4x4 matrix");
918 return nullptr;
919 }
920 if (vec != Py_None) {
921 vec_num = (matSize == 2 ? 2 : 3);
923 tvec, vec_num, vec_num, vec, "Matrix.Scale(factor, size, axis), invalid 'axis' arg") ==
924 -1)
925 {
926 return nullptr;
927 }
928 }
929 if (vec == Py_None) { /* scaling along axis */
930 if (matSize == 2) {
931 mat[0] = factor;
932 mat[3] = factor;
933 }
934 else {
935 mat[0] = factor;
936 mat[4] = factor;
937 mat[8] = factor;
938 }
939 }
940 else {
941 /* scaling in arbitrary direction
942 * normalize arbitrary axis */
943 float norm = 0.0f;
944 int x;
945 for (x = 0; x < vec_num; x++) {
946 norm += tvec[x] * tvec[x];
947 }
948 norm = sqrtf(norm);
949 for (x = 0; x < vec_num; x++) {
950 tvec[x] /= norm;
951 }
952 if (matSize == 2) {
953 mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
954 mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
955 mat[2] = ((factor - 1) * (tvec[0] * tvec[1]));
956 mat[3] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
957 }
958 else {
959 mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
960 mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
961 mat[2] = ((factor - 1) * (tvec[0] * tvec[2]));
962 mat[3] = ((factor - 1) * (tvec[0] * tvec[1]));
963 mat[4] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
964 mat[5] = ((factor - 1) * (tvec[1] * tvec[2]));
965 mat[6] = ((factor - 1) * (tvec[0] * tvec[2]));
966 mat[7] = ((factor - 1) * (tvec[1] * tvec[2]));
967 mat[8] = 1 + ((factor - 1) * (tvec[2] * tvec[2]));
968 }
969 }
970 if (matSize == 4) {
972 }
973 /* pass to matrix creation */
974 return Matrix_CreatePyObject(mat, matSize, matSize, reinterpret_cast<PyTypeObject *>(cls));
975}
976
978 /* Wrap. */
979 C_Matrix_OrthoProjection_doc,
980 ".. classmethod:: OrthoProjection(axis, size, /)\n"
981 "\n"
982 " Create a matrix to represent an orthographic projection.\n"
983 "\n"
984 " :param axis: An axis string,\n"
985 " where a single axis is for a 2D matrix.\n"
986 " Or a vector for an arbitrary axis\n"
987 " :type axis: Literal['X', 'Y', 'XY', 'XZ', 'YZ'] | Sequence[float]\n"
988 " :param size: The size of the projection matrix to construct [2, 4].\n"
989 " :type size: int\n"
990 " :return: A new projection matrix.\n"
991 " :rtype: :class:`Matrix`\n");
992static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
993{
994 PyObject *axis;
995
996 int matSize, x;
997 float norm = 0.0f;
998 float mat[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
999
1000 if (!PyArg_ParseTuple(args,
1001 "O" /* `axis` */
1002 "i" /* `size` */
1003 ":Matrix.OrthoProjection",
1004 &axis,
1005 &matSize))
1006 {
1007 return nullptr;
1008 }
1009 if (!ELEM(matSize, 2, 3, 4)) {
1010 PyErr_SetString(PyExc_ValueError,
1011 "Matrix.OrthoProjection(): "
1012 "can only return a 2x2 3x3 or 4x4 matrix");
1013 return nullptr;
1014 }
1015
1016 if (PyUnicode_Check(axis)) { /* ortho projection onto cardinal plane */
1017 Py_ssize_t plane_len;
1018 const char *plane = PyUnicode_AsUTF8AndSize(axis, &plane_len);
1019 if (matSize == 2) {
1020 if (plane_len == 1 && plane[0] == 'X') {
1021 mat[0] = 1.0f;
1022 }
1023 else if (plane_len == 1 && plane[0] == 'Y') {
1024 mat[3] = 1.0f;
1025 }
1026 else {
1027 PyErr_Format(PyExc_ValueError,
1028 "Matrix.OrthoProjection(): "
1029 "unknown plane, expected: X, Y, not '%.200s'",
1030 plane);
1031 return nullptr;
1032 }
1033 }
1034 else {
1035 if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Y') {
1036 mat[0] = 1.0f;
1037 mat[4] = 1.0f;
1038 }
1039 else if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Z') {
1040 mat[0] = 1.0f;
1041 mat[8] = 1.0f;
1042 }
1043 else if (plane_len == 2 && plane[0] == 'Y' && plane[1] == 'Z') {
1044 mat[4] = 1.0f;
1045 mat[8] = 1.0f;
1046 }
1047 else {
1048 PyErr_Format(PyExc_ValueError,
1049 "Matrix.OrthoProjection(): "
1050 "unknown plane, expected: XY, XZ, YZ, not '%.200s'",
1051 plane);
1052 return nullptr;
1053 }
1054 }
1055 }
1056 else {
1057 /* arbitrary plane */
1058
1059 const int vec_num = (matSize == 2 ? 2 : 3);
1060 float tvec[4];
1061
1062 if (mathutils_array_parse(tvec,
1063 vec_num,
1064 vec_num,
1065 axis,
1066 "Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1)
1067 {
1068 return nullptr;
1069 }
1070
1071 /* normalize arbitrary axis */
1072 for (x = 0; x < vec_num; x++) {
1073 norm += tvec[x] * tvec[x];
1074 }
1075 norm = sqrtf(norm);
1076 for (x = 0; x < vec_num; x++) {
1077 tvec[x] /= norm;
1078 }
1079 if (matSize == 2) {
1080 mat[0] = 1 - (tvec[0] * tvec[0]);
1081 mat[1] = -(tvec[0] * tvec[1]);
1082 mat[2] = -(tvec[0] * tvec[1]);
1083 mat[3] = 1 - (tvec[1] * tvec[1]);
1084 }
1085 else if (matSize > 2) {
1086 mat[0] = 1 - (tvec[0] * tvec[0]);
1087 mat[1] = -(tvec[0] * tvec[1]);
1088 mat[2] = -(tvec[0] * tvec[2]);
1089 mat[3] = -(tvec[0] * tvec[1]);
1090 mat[4] = 1 - (tvec[1] * tvec[1]);
1091 mat[5] = -(tvec[1] * tvec[2]);
1092 mat[6] = -(tvec[0] * tvec[2]);
1093 mat[7] = -(tvec[1] * tvec[2]);
1094 mat[8] = 1 - (tvec[2] * tvec[2]);
1095 }
1096 }
1097 if (matSize == 4) {
1098 matrix_3x3_as_4x4(mat);
1099 }
1100 /* pass to matrix creation */
1101 return Matrix_CreatePyObject(mat, matSize, matSize, reinterpret_cast<PyTypeObject *>(cls));
1102}
1103
1106 /* Wrap. */
1107 C_Matrix_Shear_doc,
1108 ".. classmethod:: Shear(plane, size, factor, /)\n"
1109 "\n"
1110 " Create a matrix to represent a shear transformation.\n"
1111 "\n"
1112 " :param plane: An axis string,\n"
1113 " where a single axis is for a 2D matrix only.\n"
1114 " :type plane: Literal['X', 'Y', 'XY', 'XZ', 'YZ']\n"
1115 " :param size: The size of the shear matrix to construct [2, 4].\n"
1116 " :type size: int\n"
1117 " :param factor: The factor of shear to apply. "
1118 "For a 2 *size* matrix use a single float. "
1119 "For a 3 or 4 *size* matrix pass a pair of floats corresponding with the *plane* axis.\n"
1120 " :type factor: float | Sequence[float]\n"
1121 " :return: A new shear matrix.\n"
1122 " :rtype: :class:`Matrix`\n");
1123static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
1124{
1125 int matSize;
1126 const char *plane;
1127 PyObject *fac;
1128 float mat[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
1129
1130 if (!PyArg_ParseTuple(args,
1131 "s" /* `plane` */
1132 "i" /* `size` */
1133 "O" /* `factor` */
1134 ":Matrix.Shear",
1135 &plane,
1136 &matSize,
1137 &fac))
1138 {
1139 return nullptr;
1140 }
1141 if (!ELEM(matSize, 2, 3, 4)) {
1142 PyErr_SetString(PyExc_ValueError,
1143 "Matrix.Shear(): "
1144 "can only return a 2x2 3x3 or 4x4 matrix");
1145 return nullptr;
1146 }
1147
1148 if (matSize == 2) {
1149 float const factor = PyFloat_AsDouble(fac);
1150
1151 if (factor == -1.0f && PyErr_Occurred()) {
1152 PyErr_SetString(PyExc_TypeError,
1153 "Matrix.Shear(): "
1154 "the factor to be a float");
1155 return nullptr;
1156 }
1157
1158 /* unit */
1159 mat[0] = 1.0f;
1160 mat[3] = 1.0f;
1161
1162 if (STREQ(plane, "X")) {
1163 mat[2] = factor;
1164 }
1165 else if (STREQ(plane, "Y")) {
1166 mat[1] = factor;
1167 }
1168 else {
1169 PyErr_SetString(PyExc_ValueError,
1170 "Matrix.Shear(): "
1171 "expected: X, Y or wrong matrix size for shearing plane");
1172 return nullptr;
1173 }
1174 }
1175 else {
1176 /* 3 or 4, apply as 3x3, resize later if needed */
1177 float factor[2];
1178
1179 if (mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") == -1) {
1180 return nullptr;
1181 }
1182
1183 /* unit */
1184 mat[0] = 1.0f;
1185 mat[4] = 1.0f;
1186 mat[8] = 1.0f;
1187
1188 if (STREQ(plane, "XY")) {
1189 mat[6] = factor[0];
1190 mat[7] = factor[1];
1191 }
1192 else if (STREQ(plane, "XZ")) {
1193 mat[3] = factor[0];
1194 mat[5] = factor[1];
1195 }
1196 else if (STREQ(plane, "YZ")) {
1197 mat[1] = factor[0];
1198 mat[2] = factor[1];
1199 }
1200 else {
1201 PyErr_SetString(PyExc_ValueError,
1202 "Matrix.Shear(): "
1203 "expected: X, Y, XY, XZ, YZ");
1204 return nullptr;
1205 }
1206 }
1207
1208 if (matSize == 4) {
1209 matrix_3x3_as_4x4(mat);
1210 }
1211 /* pass to matrix creation */
1212 return Matrix_CreatePyObject(mat, matSize, matSize, reinterpret_cast<PyTypeObject *>(cls));
1213}
1214
1216 /* Wrap. */
1217 C_Matrix_LocRotScale_doc,
1218 ".. classmethod:: LocRotScale(location, rotation, scale, /)\n"
1219 "\n"
1220 " Create a matrix combining translation, rotation and scale,\n"
1221 " acting as the inverse of the decompose() method.\n"
1222 "\n"
1223 " Any of the inputs may be replaced with None if not needed.\n"
1224 "\n"
1225 " :param location: The translation component.\n"
1226 " :type location: Sequence[float] | None\n"
1227 " :param rotation: The rotation component as a "
1228 "3x3 matrix, quaternion, euler or None for no rotation.\n"
1229 " :type rotation: :class:`Matrix` | :class:`Quaternion` | :class:`Euler` | None\n"
1230 " :param scale: The scale component.\n"
1231 " :type scale: Sequence[float] | None\n"
1232 " :return: Combined transformation as a 4x4 matrix. \n"
1233 " :rtype: :class:`Matrix`\n");
1234static PyObject *C_Matrix_LocRotScale(PyObject *cls, PyObject *args)
1235{
1236 PyObject *loc_obj, *rot_obj, *scale_obj;
1237 float mat[4][4], loc[3];
1238
1239 if (!PyArg_ParseTuple(args,
1240 "O" /* `location` */
1241 "O" /* `rotation` */
1242 "O" /* `scale` */
1243 ":Matrix.LocRotScale",
1244 &loc_obj,
1245 &rot_obj,
1246 &scale_obj))
1247 {
1248 return nullptr;
1249 }
1250
1251 /* Decode location. */
1252 if (loc_obj == Py_None) {
1253 zero_v3(loc);
1254 }
1255 else if (mathutils_array_parse(
1256 loc, 3, 3, loc_obj, "Matrix.LocRotScale(), invalid location argument") == -1)
1257 {
1258 return nullptr;
1259 }
1260
1261 /* Decode rotation. */
1262 if (rot_obj == Py_None) {
1263 unit_m4(mat);
1264 }
1265 else if (QuaternionObject_Check(rot_obj)) {
1266 QuaternionObject *quat_obj = reinterpret_cast<QuaternionObject *>(rot_obj);
1267
1268 if (BaseMath_ReadCallback(quat_obj) == -1) {
1269 return nullptr;
1270 }
1271
1272 quat_to_mat4(mat, quat_obj->quat);
1273 }
1274 else if (EulerObject_Check(rot_obj)) {
1275 EulerObject *eul_obj = reinterpret_cast<EulerObject *>(rot_obj);
1276
1277 if (BaseMath_ReadCallback(eul_obj) == -1) {
1278 return nullptr;
1279 }
1280
1281 eulO_to_mat4(mat, eul_obj->eul, eul_obj->order);
1282 }
1283 else if (MatrixObject_Check(rot_obj)) {
1284 MatrixObject *mat_obj = reinterpret_cast<MatrixObject *>(rot_obj);
1285
1286 if (BaseMath_ReadCallback(mat_obj) == -1) {
1287 return nullptr;
1288 }
1289
1290 if (mat_obj->col_num == 3 && mat_obj->row_num == 3) {
1291 copy_m4_m3(mat, reinterpret_cast<const float (*)[3]>(mat_obj->matrix));
1292 }
1293 else {
1294 PyErr_SetString(PyExc_ValueError,
1295 "Matrix.LocRotScale(): "
1296 "inappropriate rotation matrix size - expects 3x3 matrix");
1297 return nullptr;
1298 }
1299 }
1300 else {
1301 PyErr_SetString(PyExc_ValueError,
1302 "Matrix.LocRotScale(): "
1303 "rotation argument must be Matrix, Quaternion, Euler or None");
1304 return nullptr;
1305 }
1306
1307 /* Decode scale. */
1308 if (scale_obj != Py_None) {
1309 float scale[3];
1310
1312 scale, 3, 3, scale_obj, "Matrix.LocRotScale(), invalid scale argument") == -1)
1313 {
1314 return nullptr;
1315 }
1316
1317 rescale_m4(mat, scale);
1318 }
1319
1320 copy_v3_v3(mat[3], loc);
1321
1322 return Matrix_CreatePyObject(&mat[0][0], 4, 4, reinterpret_cast<PyTypeObject *>(cls));
1323}
1324
1326
1327/* -------------------------------------------------------------------- */
1330
1332 /* Wrap. */
1333 Matrix_to_quaternion_doc,
1334 ".. method:: to_quaternion()\n"
1335 "\n"
1336 " Return a quaternion representation of the rotation matrix.\n"
1337 "\n"
1338 " :return: Quaternion representation of the rotation matrix.\n"
1339 " :rtype: :class:`Quaternion`\n");
1340static PyObject *Matrix_to_quaternion(MatrixObject *self)
1341{
1342 float quat[4];
1343
1344 if (BaseMath_ReadCallback(self) == -1) {
1345 return nullptr;
1346 }
1347
1348 /* must be 3-4 cols, 3-4 rows, square matrix */
1349 if ((self->row_num < 3) || (self->col_num < 3) || (self->row_num != self->col_num)) {
1350 PyErr_SetString(PyExc_ValueError,
1351 "Matrix.to_quat(): "
1352 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1353 return nullptr;
1354 }
1355 if (self->row_num == 3) {
1356 mat3_to_quat(quat, reinterpret_cast<const float (*)[3]>(self->matrix));
1357 }
1358 else {
1359 mat4_to_quat(quat, reinterpret_cast<const float (*)[4]>(self->matrix));
1360 }
1361 return Quaternion_CreatePyObject(quat, nullptr);
1362}
1363
1365
1366/* -------------------------------------------------------------------- */
1369
1371 /* Wrap. */
1372 Matrix_to_euler_doc,
1373 ".. method:: to_euler(order='XYZ', euler_compat=None, /)\n"
1374 "\n"
1375 " Return an Euler representation of the rotation matrix\n"
1376 " (3x3 or 4x4 matrix only).\n"
1377 "\n"
1378 " :param order: A rotation order string.\n"
1379 " :type order: Literal['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']\n"
1380 " :param euler_compat: Optional euler argument the new euler will be made\n"
1381 " compatible with (no axis flipping between them).\n"
1382 " Useful for converting a series of matrices to animation curves.\n"
1383 " :type euler_compat: :class:`Euler` | None\n"
1384 " :return: Euler representation of the matrix.\n"
1385 " :rtype: :class:`Euler`\n");
1386static PyObject *Matrix_to_euler(MatrixObject *self, PyObject *args)
1387{
1388 const char *order_str = nullptr;
1389 short order = EULER_ORDER_XYZ;
1390 float eul[3], eul_compatf[3];
1391 EulerObject *eul_compat = nullptr;
1392 PyC_TypeOrNone eul_compat_or_none = PyC_TYPE_OR_NONE_INIT(&euler_Type, &eul_compat);
1393
1394 float mat[3][3];
1395
1396 if (BaseMath_ReadCallback(self) == -1) {
1397 return nullptr;
1398 }
1399
1400 static const char *_keywords[] = {"", "", nullptr};
1401 static _PyArg_Parser _parser = {
1402 "|" /* Optional arguments. */
1403 "s" /* `order` */
1404 "O&" /* `euler_compat` */
1405 ":to_euler",
1406 _keywords,
1407 nullptr,
1408 };
1409 if (!_PyArg_ParseTupleAndKeywordsFast(
1410 args, nullptr, &_parser, &order_str, PyC_ParseTypeOrNone, &eul_compat_or_none))
1411 {
1412 return nullptr;
1413 }
1414
1415 if (eul_compat) {
1416 if (BaseMath_ReadCallback(eul_compat) == -1) {
1417 return nullptr;
1418 }
1419
1420 copy_v3_v3(eul_compatf, eul_compat->eul);
1421 }
1422
1423 /* Must be 3-4 cols, 3-4 rows, square matrix. */
1424 if (self->row_num == 3 && self->col_num == 3) {
1425 copy_m3_m3(mat, reinterpret_cast<const float (*)[3]>(self->matrix));
1426 }
1427 else if (self->row_num == 4 && self->col_num == 4) {
1428 copy_m3_m4(mat, reinterpret_cast<const float (*)[4]>(self->matrix));
1429 }
1430 else {
1431 PyErr_SetString(PyExc_ValueError,
1432 "Matrix.to_euler(): "
1433 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
1434 return nullptr;
1435 }
1436
1437 if (order_str) {
1438 order = euler_order_from_string(order_str, "Matrix.to_euler()");
1439
1440 if (order == -1) {
1441 return nullptr;
1442 }
1443 }
1444
1445 normalize_m3(mat);
1446
1447 if (eul_compat) {
1448 if (order == 1) {
1449 mat3_normalized_to_compatible_eul(eul, eul_compatf, mat);
1450 }
1451 else {
1452 mat3_normalized_to_compatible_eulO(eul, eul_compatf, order, mat);
1453 }
1454 }
1455 else {
1456 if (order == 1) {
1457 mat3_normalized_to_eul(eul, mat);
1458 }
1459 else {
1460 mat3_normalized_to_eulO(eul, order, mat);
1461 }
1462 }
1463
1464 return Euler_CreatePyObject(eul, order, nullptr);
1465}
1466
1468
1469/* -------------------------------------------------------------------- */
1472
1474 /* Wrap. */
1475 Matrix_resize_4x4_doc,
1476 ".. method:: resize_4x4()\n"
1477 "\n"
1478 " Resize the matrix to 4x4.\n");
1479static PyObject *Matrix_resize_4x4(MatrixObject *self)
1480{
1481 float mat[4][4];
1482 int col;
1483
1484 if (BaseMathObject_Prepare_ForResize(self, "Matrix.resize_4x4()") == -1) [[unlikely]] {
1485 /* An exception has been raised. */
1486 return nullptr;
1487 }
1488
1489 self->matrix = static_cast<float *>(
1490 PyMem_Realloc(self->matrix, (sizeof(float) * (MATRIX_MAX_DIM * MATRIX_MAX_DIM))));
1491 if (self->matrix == nullptr) {
1492 PyErr_SetString(PyExc_MemoryError,
1493 "Matrix.resize_4x4(): "
1494 "problem allocating pointer space");
1495 return nullptr;
1496 }
1497
1498 unit_m4(mat);
1499
1500 for (col = 0; col < self->col_num; col++) {
1501 memcpy(mat[col], MATRIX_COL_PTR(self, col), self->row_num * sizeof(float));
1502 }
1503
1504 copy_m4_m4(reinterpret_cast<float (*)[4]>(self->matrix), const_cast<const float (*)[4]>(mat));
1505
1506 self->col_num = 4;
1507 self->row_num = 4;
1508
1509 Py_RETURN_NONE;
1510}
1511
1513
1514/* -------------------------------------------------------------------- */
1517
1518static PyObject *Matrix_to_NxN(MatrixObject *self, const int col_num, const int row_num)
1519{
1520 const int mat_size = sizeof(float) * (col_num * row_num);
1521 MatrixObject *pymat = reinterpret_cast<MatrixObject *>(Matrix_CreatePyObject_alloc(
1522 static_cast<float *>(PyMem_Malloc(mat_size)), col_num, row_num, Py_TYPE(self)));
1523
1524 if ((self->row_num == row_num) && (self->col_num == col_num)) {
1525 memcpy(pymat->matrix, self->matrix, mat_size);
1526 }
1527 else {
1528 if ((self->col_num < col_num) || (self->row_num < row_num)) {
1529 matrix_unit_internal(pymat);
1530 }
1531 const int col_len_src = min_ii(col_num, self->col_num);
1532 const int row_len_src = min_ii(row_num, self->row_num);
1533 for (int col = 0; col < col_len_src; col++) {
1534 memcpy(
1535 &pymat->matrix[col * row_num], MATRIX_COL_PTR(self, col), sizeof(float) * row_len_src);
1536 }
1537 }
1538 return reinterpret_cast<PyObject *>(pymat);
1539}
1540
1542 /* Wrap. */
1543 Matrix_to_2x2_doc,
1544 ".. method:: to_2x2()\n"
1545 "\n"
1546 " Return a 2x2 copy of this matrix.\n"
1547 "\n"
1548 " :return: a new matrix.\n"
1549 " :rtype: :class:`Matrix`\n");
1550static PyObject *Matrix_to_2x2(MatrixObject *self)
1551{
1552 if (BaseMath_ReadCallback(self) == -1) {
1553 return nullptr;
1554 }
1555 return Matrix_to_NxN(self, 2, 2);
1556}
1557
1559 /* Wrap. */
1560 Matrix_to_3x3_doc,
1561 ".. method:: to_3x3()\n"
1562 "\n"
1563 " Return a 3x3 copy of this matrix.\n"
1564 "\n"
1565 " :return: a new matrix.\n"
1566 " :rtype: :class:`Matrix`\n");
1567static PyObject *Matrix_to_3x3(MatrixObject *self)
1568{
1569 if (BaseMath_ReadCallback(self) == -1) {
1570 return nullptr;
1571 }
1572 return Matrix_to_NxN(self, 3, 3);
1573}
1574
1576 /* Wrap. */
1577 Matrix_to_4x4_doc,
1578 ".. method:: to_4x4()\n"
1579 "\n"
1580 " Return a 4x4 copy of this matrix.\n"
1581 "\n"
1582 " :return: a new matrix.\n"
1583 " :rtype: :class:`Matrix`\n");
1584static PyObject *Matrix_to_4x4(MatrixObject *self)
1585{
1586
1587 if (BaseMath_ReadCallback(self) == -1) {
1588 return nullptr;
1589 }
1590 return Matrix_to_NxN(self, 4, 4);
1591}
1592
1594
1595/* -------------------------------------------------------------------- */
1598
1600 /* Wrap. */
1601 Matrix_to_translation_doc,
1602 ".. method:: to_translation()\n"
1603 "\n"
1604 " Return the translation part of a 4x4 matrix.\n"
1605 "\n"
1606 " :return: Return the translation of a matrix.\n"
1607 " :rtype: :class:`Vector`\n");
1609{
1610 if (BaseMath_ReadCallback(self) == -1) {
1611 return nullptr;
1612 }
1613
1614 if ((self->row_num < 3) || self->col_num < 4) {
1615 PyErr_SetString(PyExc_ValueError,
1616 "Matrix.to_translation(): "
1617 "inappropriate matrix size");
1618 return nullptr;
1619 }
1620
1621 return Vector_CreatePyObject(MATRIX_COL_PTR(self, 3), 3, nullptr);
1622}
1623
1625 /* Wrap. */
1626 Matrix_to_scale_doc,
1627 ".. method:: to_scale()\n"
1628 "\n"
1629 " Return the scale part of a 3x3 or 4x4 matrix.\n"
1630 "\n"
1631 " :return: Return the scale of a matrix.\n"
1632 " :rtype: :class:`Vector`\n"
1633 "\n"
1634 " .. note:: This method does not return a negative scale on any axis because it is "
1635 "not possible to obtain this data from the matrix alone.\n");
1636static PyObject *Matrix_to_scale(MatrixObject *self)
1637{
1638 float rot[3][3];
1639 float mat[3][3];
1640 float size[3];
1641
1642 if (BaseMath_ReadCallback(self) == -1) {
1643 return nullptr;
1644 }
1645
1646 /* Must be 3-4 cols, 3-4 rows, square matrix. */
1647 if ((self->row_num < 3) || (self->col_num < 3)) {
1648 PyErr_SetString(PyExc_ValueError,
1649 "Matrix.to_scale(): "
1650 "inappropriate matrix size, 3x3 minimum size");
1651 return nullptr;
1652 }
1653
1654 matrix_as_3x3(mat, self);
1655
1656 /* compatible mat4_to_loc_rot_size */
1657 mat3_to_rot_size(rot, size, mat);
1658
1659 return Vector_CreatePyObject(size, 3, nullptr);
1660}
1661
1663
1664/* -------------------------------------------------------------------- */
1667
1670{
1671 if (self->col_num != self->row_num) {
1672 PyErr_SetString(PyExc_ValueError,
1673 "Matrix.invert(ed): "
1674 "only square matrices are supported");
1675 return false;
1676 }
1677
1678 return true;
1679}
1680
1681static bool matrix_invert_args_check(const MatrixObject *self, PyObject *args, bool check_type)
1682{
1683 switch (PyTuple_GET_SIZE(args)) {
1684 case 0: {
1685 return true;
1686 }
1687 case 1: {
1688 PyObject *arg = PyTuple_GET_ITEM(args, 0);
1689 if (arg == Py_None) {
1690 return true;
1691 }
1692 if (check_type) {
1693 const MatrixObject *fallback = reinterpret_cast<const MatrixObject *>(arg);
1694 if (!MatrixObject_Check(fallback)) {
1695 PyErr_SetString(PyExc_TypeError,
1696 "Matrix.invert: "
1697 "expects a matrix argument or nothing");
1698 return false;
1699 }
1700
1701 if ((self->col_num != fallback->col_num) || (self->row_num != fallback->row_num)) {
1702 PyErr_SetString(PyExc_TypeError,
1703 "Matrix.invert: "
1704 "matrix argument has different dimensions");
1705 return false;
1706 }
1707 }
1708
1709 return true;
1710 }
1711 default: {
1712 PyErr_SetString(PyExc_ValueError,
1713 "Matrix.invert(ed): "
1714 "takes at most one argument");
1715 return false;
1716 }
1717 }
1718}
1719
1721{
1722 PyErr_SetString(PyExc_ValueError,
1723 "Matrix.invert(ed): "
1724 "matrix does not have an inverse");
1725}
1726
1728 /* Wrap. */
1729 Matrix_invert_doc,
1730 ".. method:: invert(fallback=None, /)\n"
1731 "\n"
1732 " Set the matrix to its inverse.\n"
1733 "\n"
1734 " :param fallback: Set the matrix to this value when the inverse cannot be calculated\n"
1735 " (instead of raising a :exc:`ValueError` exception).\n"
1736 " :type fallback: :class:`Matrix` | None\n"
1737 "\n"
1738 " .. seealso:: `Inverse matrix <https://en.wikipedia.org/wiki/Inverse_matrix>`__ on "
1739 "Wikipedia.\n");
1740static PyObject *Matrix_invert(MatrixObject *self, PyObject *args)
1741{
1742 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
1743 return nullptr;
1744 }
1745
1746 if (matrix_invert_is_compat(self) == false) {
1747 return nullptr;
1748 }
1749
1750 if (matrix_invert_args_check(self, args, true) == false) {
1751 return nullptr;
1752 }
1753
1754 if (!matrix_invert_internal(self, self->matrix)) {
1755 PyObject *arg;
1756 if (PyTuple_GET_SIZE(args) == 1 && ((arg = PyTuple_GET_ITEM(args, 0)) != Py_None)) {
1757 MatrixObject *fallback = reinterpret_cast<MatrixObject *>(arg);
1758
1759 if (BaseMath_ReadCallback(fallback) == -1) {
1760 return nullptr;
1761 }
1762
1763 if (self != fallback) {
1764 matrix_copy(self, fallback);
1765 }
1766 }
1767 else {
1769 return nullptr;
1770 }
1771 }
1772
1773 (void)BaseMath_WriteCallback(self);
1774 Py_RETURN_NONE;
1775}
1776
1778 /* Wrap. */
1779 Matrix_inverted_doc,
1780 ".. method:: inverted(fallback=None, /)\n"
1781 "\n"
1782 " Return an inverted copy of the matrix.\n"
1783 "\n"
1784 " :param fallback: return this when the inverse can't be calculated\n"
1785 " (instead of raising a :exc:`ValueError`).\n"
1786 " :type fallback: Any\n"
1787 " :return: The inverted matrix or fallback when given.\n"
1788 " :rtype: :class:`Matrix` | Any\n");
1789static PyObject *Matrix_inverted(MatrixObject *self, PyObject *args)
1790{
1791 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
1792
1793 if (BaseMath_ReadCallback(self) == -1) {
1794 return nullptr;
1795 }
1796
1797 if (matrix_invert_args_check(self, args, false) == false) {
1798 return nullptr;
1799 }
1800
1801 if (matrix_invert_is_compat(self) == false) {
1802 return nullptr;
1803 }
1804
1805 if (matrix_invert_internal(self, mat)) {
1806 /* pass */
1807 }
1808 else {
1809 PyObject *arg;
1810 if (PyTuple_GET_SIZE(args) == 1 && ((arg = PyTuple_GET_ITEM(args, 0)) != Py_None)) {
1811 Py_INCREF(arg);
1812 return arg;
1813 }
1814
1816 return nullptr;
1817 }
1818
1819 return Matrix_copy_notest(self, mat);
1820}
1821
1823{
1824 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
1825 return nullptr;
1826 }
1827
1828 if (matrix_invert_is_compat(self) == false) {
1829 return nullptr;
1830 }
1831
1832 if (matrix_invert_internal(self, self->matrix)) {
1833 /* pass */
1834 }
1835 else {
1837 return nullptr;
1838 }
1839
1840 (void)BaseMath_WriteCallback(self);
1841 Py_RETURN_NONE;
1842}
1843
1845 /* Wrap. */
1846 Matrix_invert_safe_doc,
1847 ".. method:: invert_safe()\n"
1848 "\n"
1849 " Set the matrix to its inverse, will never error.\n"
1850 " If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
1851 "to get an invertible one.\n"
1852 " If tweaked matrix is still degenerated, set to the identity matrix instead.\n"
1853 "\n"
1854 " .. seealso:: `Inverse Matrix <https://en.wikipedia.org/wiki/Inverse_matrix>`__ on "
1855 "Wikipedia.\n");
1856static PyObject *Matrix_invert_safe(MatrixObject *self)
1857{
1858 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
1859 return nullptr;
1860 }
1861
1862 if (matrix_invert_is_compat(self) == false) {
1863 return nullptr;
1864 }
1865
1866 matrix_invert_safe_internal(self, self->matrix);
1867
1868 (void)BaseMath_WriteCallback(self);
1869 Py_RETURN_NONE;
1870}
1871
1873 /* Wrap. */
1874 Matrix_inverted_safe_doc,
1875 ".. method:: inverted_safe()\n"
1876 "\n"
1877 " Return an inverted copy of the matrix, will never error.\n"
1878 " If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
1879 "to get an invertible one.\n"
1880 " If tweaked matrix is still degenerated, return the identity matrix instead.\n"
1881 "\n"
1882 " :return: the inverted matrix.\n"
1883 " :rtype: :class:`Matrix`\n");
1884static PyObject *Matrix_inverted_safe(MatrixObject *self)
1885{
1886 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
1887
1888 if (BaseMath_ReadCallback(self) == -1) {
1889 return nullptr;
1890 }
1891
1892 if (matrix_invert_is_compat(self) == false) {
1893 return nullptr;
1894 }
1895
1896 matrix_invert_safe_internal(self, mat);
1897
1898 return Matrix_copy_notest(self, mat);
1899}
1900
1902
1903/* -------------------------------------------------------------------- */
1906
1908 /* Wrap. */
1909 Matrix_adjugate_doc,
1910 ".. method:: adjugate()\n"
1911 "\n"
1912 " Set the matrix to its adjugate.\n"
1913 "\n"
1914 " :raises ValueError: if the matrix cannot be adjugated.\n"
1915 "\n"
1916 " .. seealso:: `Adjugate matrix <https://en.wikipedia.org/wiki/Adjugate_matrix>`__ on "
1917 "Wikipedia.\n");
1918static PyObject *Matrix_adjugate(MatrixObject *self)
1919{
1920 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
1921 return nullptr;
1922 }
1923
1924 if (self->col_num != self->row_num) {
1925 PyErr_SetString(PyExc_ValueError,
1926 "Matrix.adjugate(d): "
1927 "only square matrices are supported");
1928 return nullptr;
1929 }
1930
1931 /* calculate the classical adjoint */
1932 if (self->col_num <= 4) {
1933 adjoint_matrix_n(self->matrix, self->matrix, self->col_num);
1934 }
1935 else {
1936 PyErr_Format(
1937 PyExc_ValueError, "Matrix adjugate(d): size (%d) unsupported", int(self->col_num));
1938 return nullptr;
1939 }
1940
1941 (void)BaseMath_WriteCallback(self);
1942 Py_RETURN_NONE;
1943}
1944
1946 /* Wrap. */
1947 Matrix_adjugated_doc,
1948 ".. method:: adjugated()\n"
1949 "\n"
1950 " Return an adjugated copy of the matrix.\n"
1951 "\n"
1952 " :return: the adjugated matrix.\n"
1953 " :rtype: :class:`Matrix`\n"
1954 " :raises ValueError: if the matrix cannot be adjugated\n");
1955static PyObject *Matrix_adjugated(MatrixObject *self)
1956{
1958}
1959
1961 /* Wrap. */
1962 Matrix_rotate_doc,
1963 ".. method:: rotate(other, /)\n"
1964 "\n"
1965 " Rotates the matrix by another mathutils value.\n"
1966 "\n"
1967 " .. note:: The matrix must be 3x3.\n"
1968 "\n"
1969 " .. note:: If any of the columns are not unit length this may not have desired results.\n"
1970 "\n"
1971 " :param other: rotation component of mathutils value\n"
1972 " :type other: :class:`Euler` | :class:`Quaternion` | :class:`Matrix`\n");
1973static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
1974{
1975 float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
1976
1977 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
1978 return nullptr;
1979 }
1980
1981 if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1) {
1982 return nullptr;
1983 }
1984
1985 if (self->row_num != 3 || self->col_num != 3) {
1986 PyErr_SetString(PyExc_ValueError,
1987 "Matrix.rotate(): "
1988 "must have 3x3 dimensions");
1989 return nullptr;
1990 }
1991
1992 matrix_as_3x3(self_rmat, self);
1993 mul_m3_m3m3(rmat, other_rmat, self_rmat);
1994
1995 copy_m3_m3(reinterpret_cast<float (*)[3]>(self->matrix), rmat);
1996
1997 (void)BaseMath_WriteCallback(self);
1998 Py_RETURN_NONE;
1999}
2000
2002
2003/* -------------------------------------------------------------------- */
2006
2008 /* Wrap. */
2009 Matrix_decompose_doc,
2010 ".. method:: decompose()\n"
2011 "\n"
2012 " Return the translation, rotation, and scale components of this 4x4 matrix.\n"
2013 "\n"
2014 " :return: Tuple of translation, rotation, and scale.\n"
2015 " :rtype: tuple[:class:`Vector`, :class:`Quaternion`, :class:`Vector`]\n");
2016static PyObject *Matrix_decompose(MatrixObject *self)
2017{
2018 PyObject *ret;
2019 float loc[3];
2020 float rot[3][3];
2021 float quat[4];
2022 float size[3];
2023
2024 if (self->row_num != 4 || self->col_num != 4) {
2025 PyErr_SetString(PyExc_ValueError,
2026 "Matrix.decompose(): "
2027 "inappropriate matrix size - expects 4x4 matrix");
2028 return nullptr;
2029 }
2030
2031 if (BaseMath_ReadCallback(self) == -1) {
2032 return nullptr;
2033 }
2034
2035 mat4_to_loc_rot_size(loc, rot, size, reinterpret_cast<const float (*)[4]>(self->matrix));
2037
2038 ret = PyTuple_New(3);
2040 Vector_CreatePyObject(loc, 3, nullptr),
2041 Quaternion_CreatePyObject(quat, nullptr),
2042 Vector_CreatePyObject(size, 3, nullptr));
2043 return ret;
2044}
2045
2047
2048/* -------------------------------------------------------------------- */
2051
2053 /* Wrap. */
2054 Matrix_lerp_doc,
2055 ".. method:: lerp(other, factor, /)\n"
2056 "\n"
2057 " Returns the interpolation of two matrices. Uses polar decomposition, see "
2058 "\"Matrix Animation and Polar Decomposition\", Shoemake and Duff, 1992.\n"
2059 "\n"
2060 " :param other: value to interpolate with.\n"
2061 " :type other: :class:`Matrix`\n"
2062 " :param factor: The interpolation value in [0.0, 1.0].\n"
2063 " :type factor: float\n"
2064 " :return: The interpolated matrix.\n"
2065 " :rtype: :class:`Matrix`\n");
2066static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
2067{
2068 MatrixObject *mat2 = nullptr;
2069 float fac, mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
2070
2071 if (!PyArg_ParseTuple(args,
2072 "O!" /* `other` */
2073 "f" /* `factor` */
2074 ":lerp",
2075 &matrix_Type,
2076 &mat2,
2077 &fac))
2078 {
2079 return nullptr;
2080 }
2081
2082 if (self->col_num != mat2->col_num || self->row_num != mat2->row_num) {
2083 PyErr_SetString(PyExc_ValueError,
2084 "Matrix.lerp(): "
2085 "expects both matrix objects of the same dimensions");
2086 return nullptr;
2087 }
2088
2089 if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1) {
2090 return nullptr;
2091 }
2092
2093 /* TODO: different sized matrix. */
2094 if (self->col_num == 4 && self->row_num == 4) {
2095#ifdef MATH_STANDALONE
2096 blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->matrix, (float (*)[4])mat2->matrix, fac);
2097#else
2098 interp_m4_m4m4(reinterpret_cast<float (*)[4]>(mat),
2099 reinterpret_cast<float (*)[4]>(self->matrix),
2100 reinterpret_cast<float (*)[4]>(mat2->matrix),
2101 fac);
2102#endif
2103 }
2104 else if (self->col_num == 3 && self->row_num == 3) {
2105#ifdef MATH_STANDALONE
2106 blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->matrix, (float (*)[3])mat2->matrix, fac);
2107#else
2108 interp_m3_m3m3(reinterpret_cast<float (*)[3]>(mat),
2109 reinterpret_cast<float (*)[3]>(self->matrix),
2110 reinterpret_cast<float (*)[3]>(mat2->matrix),
2111 fac);
2112#endif
2113 }
2114 else {
2115 PyErr_SetString(PyExc_ValueError,
2116 "Matrix.lerp(): "
2117 "only 3x3 and 4x4 matrices supported");
2118 return nullptr;
2119 }
2120
2121 return Matrix_CreatePyObject(mat, self->col_num, self->row_num, Py_TYPE(self));
2122}
2123
2125 /* Wrap. */
2126 Matrix_determinant_doc,
2127 ".. method:: determinant()\n"
2128 "\n"
2129 " Return the determinant of a matrix.\n"
2130 "\n"
2131 " :return: Return the determinant of a matrix.\n"
2132 " :rtype: float\n"
2133 "\n"
2134 " .. seealso:: `Determinant <https://en.wikipedia.org/wiki/Determinant>`__ on Wikipedia.\n");
2135static PyObject *Matrix_determinant(MatrixObject *self)
2136{
2137 if (BaseMath_ReadCallback(self) == -1) {
2138 return nullptr;
2139 }
2140
2141 if (self->col_num != self->row_num) {
2142 PyErr_SetString(PyExc_ValueError,
2143 "Matrix.determinant(): "
2144 "only square matrices are supported");
2145 return nullptr;
2146 }
2147
2148 return PyFloat_FromDouble(double(matrix_determinant_internal(self)));
2149}
2150
2152
2153/* -------------------------------------------------------------------- */
2156
2158 /* Wrap. */
2159 Matrix_transpose_doc,
2160 ".. method:: transpose()\n"
2161 "\n"
2162 " Set the matrix to its transpose.\n"
2163 "\n"
2164 " .. seealso:: `Transpose <https://en.wikipedia.org/wiki/Transpose>`__ on Wikipedia.\n");
2165static PyObject *Matrix_transpose(MatrixObject *self)
2166{
2167 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2168 return nullptr;
2169 }
2170
2171 if (self->col_num != self->row_num) {
2172 PyErr_SetString(PyExc_ValueError,
2173 "Matrix.transpose(d): "
2174 "only square matrices are supported");
2175 return nullptr;
2176 }
2177
2178 if (self->col_num == 2) {
2179 const float t = MATRIX_ITEM(self, 1, 0);
2180 MATRIX_ITEM(self, 1, 0) = MATRIX_ITEM(self, 0, 1);
2181 MATRIX_ITEM(self, 0, 1) = t;
2182 }
2183 else if (self->col_num == 3) {
2184 transpose_m3(reinterpret_cast<float (*)[3]>(self->matrix));
2185 }
2186 else {
2187 transpose_m4(reinterpret_cast<float (*)[4]>(self->matrix));
2188 }
2189
2190 (void)BaseMath_WriteCallback(self);
2191 Py_RETURN_NONE;
2192}
2193
2195 /* Wrap. */
2196 Matrix_transposed_doc,
2197 ".. method:: transposed()\n"
2198 "\n"
2199 " Return a new, transposed matrix.\n"
2200 "\n"
2201 " :return: a transposed matrix\n"
2202 " :rtype: :class:`Matrix`\n");
2203static PyObject *Matrix_transposed(MatrixObject *self)
2204{
2206}
2207
2209
2210/* -------------------------------------------------------------------- */
2213
2215 /* Wrap. */
2216 Matrix_normalize_doc,
2217 ".. method:: normalize()\n"
2218 "\n"
2219 " Normalize each of the matrix columns (3x3 and 4x4 only).\n"
2220 "\n"
2221 " .. note:: for 4x4 matrices, the 4th column (translation) is left untouched.\n");
2222static PyObject *Matrix_normalize(MatrixObject *self)
2223{
2224 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2225 return nullptr;
2226 }
2227
2228 if (self->col_num != self->row_num) {
2229 PyErr_SetString(PyExc_ValueError,
2230 "Matrix.normalize(): "
2231 "only square matrices are supported");
2232 return nullptr;
2233 }
2234
2235 if (self->col_num == 3) {
2236 normalize_m3(reinterpret_cast<float (*)[3]>(self->matrix));
2237 }
2238 else if (self->col_num == 4) {
2239 normalize_m4(reinterpret_cast<float (*)[4]>(self->matrix));
2240 }
2241 else {
2242 PyErr_SetString(PyExc_ValueError,
2243 "Matrix.normalize(): "
2244 "can only use a 3x3 or 4x4 matrix");
2245 }
2246
2247 (void)BaseMath_WriteCallback(self);
2248 Py_RETURN_NONE;
2249}
2250
2252 /* Wrap. */
2253 Matrix_normalized_doc,
2254 ".. method:: normalized()\n"
2255 "\n"
2256 " Return a column normalized matrix (3x3 and 4x4 only).\n"
2257 "\n"
2258 " :return: a column normalized matrix\n"
2259 " :rtype: :class:`Matrix`\n"
2260 "\n"
2261 " .. note:: for 4x4 matrices, the 4th column (translation) is left untouched.\n");
2262static PyObject *Matrix_normalized(MatrixObject *self)
2263{
2265}
2266
2268
2269/* -------------------------------------------------------------------- */
2272
2274 /* Wrap. */
2275 Matrix_zero_doc,
2276 ".. method:: zero()\n"
2277 "\n"
2278 " Set all the matrix values to zero.\n");
2279static PyObject *Matrix_zero(MatrixObject *self)
2280{
2281 if (BaseMath_Prepare_ForWrite(self) == -1) {
2282 return nullptr;
2283 }
2284
2285 std::fill_n(self->matrix, self->col_num * self->row_num, 0.0f);
2286
2287 if (BaseMath_WriteCallback(self) == -1) {
2288 return nullptr;
2289 }
2290
2291 Py_RETURN_NONE;
2292}
2293
2295
2296/* -------------------------------------------------------------------- */
2299
2301{
2302 BLI_assert((self->col_num == self->row_num) && (self->row_num <= 4));
2303
2304 if (self->col_num == 2) {
2305 unit_m2(reinterpret_cast<float (*)[2]>(self->matrix));
2306 }
2307 else if (self->col_num == 3) {
2308 unit_m3(reinterpret_cast<float (*)[3]>(self->matrix));
2309 }
2310 else {
2311 unit_m4(reinterpret_cast<float (*)[4]>(self->matrix));
2312 }
2313}
2314
2316 /* Wrap. */
2317 Matrix_identity_doc,
2318 ".. method:: identity()\n"
2319 "\n"
2320 " Set the matrix to the identity matrix.\n"
2321 "\n"
2322 " .. note:: An object with a location and rotation of zero, and a scale of one\n"
2323 " will have an identity matrix.\n"
2324 "\n"
2325 " .. seealso:: `Identity matrix <https://en.wikipedia.org/wiki/Identity_matrix>`__ "
2326 "on Wikipedia.\n");
2327static PyObject *Matrix_identity(MatrixObject *self)
2328{
2329 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2330 return nullptr;
2331 }
2332
2333 if (self->col_num != self->row_num) {
2334 PyErr_SetString(PyExc_ValueError,
2335 "Matrix.identity(): "
2336 "only square matrices are supported");
2337 return nullptr;
2338 }
2339
2341
2342 if (BaseMath_WriteCallback(self) == -1) {
2343 return nullptr;
2344 }
2345
2346 Py_RETURN_NONE;
2347}
2348
2350
2351/* -------------------------------------------------------------------- */
2354
2356static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix)
2357{
2358 return Matrix_CreatePyObject(matrix, self->col_num, self->row_num, Py_TYPE(self));
2359}
2360
2362 /* Wrap. */
2363 Matrix_copy_doc,
2364 ".. method:: copy()\n"
2365 "\n"
2366 " Returns a copy of this matrix.\n"
2367 "\n"
2368 " :return: A copy of the matrix.\n"
2369 " :rtype: :class:`Matrix`\n");
2370static PyObject *Matrix_copy(MatrixObject *self)
2371{
2372 if (BaseMath_ReadCallback(self) == -1) {
2373 return nullptr;
2374 }
2375
2376 return Matrix_copy_notest(self, self->matrix);
2377}
2378
2380static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args)
2381{
2382 if (!PyC_CheckArgs_DeepCopy(args)) {
2383 return nullptr;
2384 }
2385 return Matrix_copy(self);
2386}
2387
2389
2390/* -------------------------------------------------------------------- */
2393
2394static PyObject *Matrix_repr(MatrixObject *self)
2395{
2396 int col, row;
2397 PyObject *rows[MATRIX_MAX_DIM] = {nullptr};
2398
2399 if (BaseMath_ReadCallback(self) == -1) {
2400 return nullptr;
2401 }
2402
2403 for (row = 0; row < self->row_num; row++) {
2404 rows[row] = PyTuple_New(self->col_num);
2405 for (col = 0; col < self->col_num; col++) {
2406 PyTuple_SET_ITEM(rows[row], col, PyFloat_FromDouble(MATRIX_ITEM(self, row, col)));
2407 }
2408 }
2409
2410 PyObject *result = nullptr;
2411 switch (self->row_num) {
2412 case 2: {
2413 result = PyUnicode_FromFormat(
2414 "Matrix((%R,\n"
2415 " %R))",
2416 rows[0],
2417 rows[1]);
2418 break;
2419 }
2420 case 3: {
2421 result = PyUnicode_FromFormat(
2422 "Matrix((%R,\n"
2423 " %R,\n"
2424 " %R))",
2425 rows[0],
2426 rows[1],
2427 rows[2]);
2428 break;
2429 }
2430 case 4: {
2431 result = PyUnicode_FromFormat(
2432 "Matrix((%R,\n"
2433 " %R,\n"
2434 " %R,\n"
2435 " %R))",
2436 rows[0],
2437 rows[1],
2438 rows[2],
2439 rows[3]);
2440 break;
2441 }
2442 default: {
2443 Py_FatalError("Matrix(): invalid row size!");
2444 break;
2445 }
2446 }
2447
2448 for (row = 0; row < self->row_num; row++) {
2449 Py_DECREF(rows[row]);
2450 }
2451
2452 return result;
2453}
2454
2455#ifndef MATH_STANDALONE
2456static PyObject *Matrix_str(MatrixObject *self)
2457{
2458 DynStr *ds;
2459
2460 int maxsize[MATRIX_MAX_DIM];
2461 int row, col;
2462
2463 char dummy_buf[64];
2464
2465 if (BaseMath_ReadCallback(self) == -1) {
2466 return nullptr;
2467 }
2468
2469 ds = BLI_dynstr_new();
2470
2471 /* First determine the maximum width for each column */
2472 for (col = 0; col < self->col_num; col++) {
2473 maxsize[col] = 0;
2474 for (row = 0; row < self->row_num; row++) {
2475 const int size = SNPRINTF_UTF8_RLEN(dummy_buf, "%.4f", MATRIX_ITEM(self, row, col));
2476 maxsize[col] = max_ii(maxsize[col], size);
2477 }
2478 }
2479
2480 /* Now write the unicode string to be printed */
2481 BLI_dynstr_appendf(ds, "<Matrix %dx%d (", self->row_num, self->col_num);
2482 for (row = 0; row < self->row_num; row++) {
2483 for (col = 0; col < self->col_num; col++) {
2484 BLI_dynstr_appendf(ds, col ? ", %*.4f" : "%*.4f", maxsize[col], MATRIX_ITEM(self, row, col));
2485 }
2486 BLI_dynstr_append(ds, row + 1 != self->row_num ? ")\n (" : ")");
2487 }
2488 BLI_dynstr_append(ds, ">");
2489
2490 return mathutils_dynstr_to_py(ds); /* frees ds */
2491}
2492#endif
2493
2495
2496/* -------------------------------------------------------------------- */
2499
2500static int Matrix_getbuffer(PyObject *obj, Py_buffer *view, int flags)
2501{
2502 MatrixObject *self = reinterpret_cast<MatrixObject *>(obj);
2503 if (BaseMath_Prepare_ForBufferAccess(self, view, flags) == -1) [[unlikely]] {
2504 return -1;
2505 }
2506 if (BaseMath_ReadCallback(self) == -1) [[unlikely]] {
2507 return -1;
2508 }
2509
2510 memset(view, 0, sizeof(*view));
2511
2512 view->obj = reinterpret_cast<PyObject *>(self);
2513 view->buf = static_cast<void *>(self->matrix);
2514 view->len = Py_ssize_t(self->row_num * self->col_num * sizeof(float));
2515 view->itemsize = sizeof(float);
2516 if ((flags & PyBUF_WRITABLE) == 0) {
2517 view->readonly = 1;
2518 }
2519 if (flags & PyBUF_FORMAT) {
2520 view->format = const_cast<char *>("f");
2521 }
2522 if (flags & PyBUF_ND) {
2523 view->ndim = 2;
2524 view->shape = MEM_new_array_uninitialized<Py_ssize_t>(size_t(view->ndim), __func__);
2525 view->shape[0] = self->row_num;
2526 view->shape[1] = self->col_num;
2527 }
2528 if (flags & PyBUF_STRIDES) {
2529 view->strides = MEM_new_array_uninitialized<Py_ssize_t>(size_t(view->ndim), __func__);
2530 view->strides[0] = sizeof(float); /* step between lines in column-major */
2531 view->strides[1] = Py_ssize_t(self->row_num) * sizeof(float); /* step between columns */
2532 }
2533
2534 self->flag |= BASE_MATH_FLAG_HAS_BUFFER_VIEW;
2535
2536 Py_INCREF(self);
2537 return 0;
2538}
2539
2540static void Matrix_releasebuffer(PyObject * /*exporter*/, Py_buffer *view)
2541{
2542 MatrixObject *self = reinterpret_cast<MatrixObject *>(view->obj);
2543 self->flag &= ~BASE_MATH_FLAG_HAS_BUFFER_VIEW;
2544
2545 if (view->readonly == 0) {
2546 if (BaseMath_WriteCallback(self) == -1) [[unlikely]] {
2547 PyErr_Print();
2548 }
2549 }
2550 MEM_SAFE_DELETE(view->shape);
2551 MEM_SAFE_DELETE(view->strides);
2552}
2553
2554static PyBufferProcs Matrix_as_buffer = {
2555 static_cast<getbufferproc>(Matrix_getbuffer),
2556 static_cast<releasebufferproc>(Matrix_releasebuffer),
2557};
2558
2560
2561/* -------------------------------------------------------------------- */
2564
2565static PyObject *Matrix_richcmpr(PyObject *a, PyObject *b, int op)
2566{
2567 PyObject *res;
2568 int ok = -1; /* zero is true */
2569
2571 MatrixObject *matA = reinterpret_cast<MatrixObject *>(a);
2572 MatrixObject *matB = reinterpret_cast<MatrixObject *>(b);
2573
2574 if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1) {
2575 return nullptr;
2576 }
2577
2578 ok = ((matA->row_num == matB->row_num) && (matA->col_num == matB->col_num) &&
2579 EXPP_VectorsAreEqual(matA->matrix, matB->matrix, (matA->col_num * matA->row_num), 1)) ?
2580 0 :
2581 -1;
2582 }
2583
2584 switch (op) {
2585 case Py_NE: {
2586 ok = !ok;
2588 }
2589 case Py_EQ: {
2590 res = ok ? Py_False : Py_True;
2591 break;
2592 }
2593 case Py_LT:
2594 case Py_LE:
2595 case Py_GT:
2596 case Py_GE: {
2597 res = Py_NotImplemented;
2598 break;
2599 }
2600 default: {
2601 PyErr_BadArgument();
2602 return nullptr;
2603 }
2604 }
2605
2606 return Py_NewRef(res);
2607}
2608
2610
2611/* -------------------------------------------------------------------- */
2614
2615static Py_hash_t Matrix_hash(MatrixObject *self)
2616{
2617 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
2618
2619 if (BaseMath_ReadCallback(self) == -1) {
2620 return -1;
2621 }
2622
2623 if (BaseMathObject_Prepare_ForHash(self) == -1) {
2624 return -1;
2625 }
2626
2627 matrix_transpose_internal(mat, self);
2628
2629 return mathutils_array_hash(mat, self->row_num * self->col_num);
2630}
2631
2633
2634/* -------------------------------------------------------------------- */
2637
2639static Py_ssize_t Matrix_len(MatrixObject *self)
2640{
2641 return self->row_num;
2642}
2643
2648static PyObject *Matrix_item_row(MatrixObject *self, Py_ssize_t row)
2649{
2650 /* Read-only: write through the returned wrapper is prevented by its own set callback. */
2651 if (BaseMath_ReadCallback(self) == -1) {
2652 return nullptr;
2653 }
2654
2655 if (row < 0 || row >= self->row_num) {
2656 PyErr_SetString(PyExc_IndexError,
2657 "matrix[attribute]: "
2658 "array index out of range");
2659 return nullptr;
2660 }
2662 reinterpret_cast<PyObject *>(self), self->col_num, mathutils_matrix_row_cb_index, row);
2663}
2664
2668static PyObject *Matrix_item_col(MatrixObject *self, Py_ssize_t col)
2669{
2670 /* Read-only: write through the returned wrapper is prevented by its own set callback. */
2671 if (BaseMath_ReadCallback(self) == -1) {
2672 return nullptr;
2673 }
2674
2675 if (col < 0 || col >= self->col_num) {
2676 PyErr_SetString(PyExc_IndexError,
2677 "matrix[attribute]: "
2678 "array index out of range");
2679 return nullptr;
2680 }
2682 reinterpret_cast<PyObject *>(self), self->row_num, mathutils_matrix_col_cb_index, col);
2683}
2684
2686static int Matrix_ass_item_row(MatrixObject *self, Py_ssize_t row, PyObject *value)
2687{
2688 int col;
2689 float vec[MATRIX_MAX_DIM];
2690 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2691 return -1;
2692 }
2693
2694 if (row >= self->row_num || row < 0) {
2695 PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad row");
2696 return -1;
2697 }
2698
2700 vec, self->col_num, self->col_num, value, "matrix[i] = value assignment") == -1)
2701 {
2702 return -1;
2703 }
2704
2705 /* Since we are assigning a row we cannot memcpy */
2706 for (col = 0; col < self->col_num; col++) {
2707 MATRIX_ITEM(self, row, col) = vec[col];
2708 }
2709
2710 (void)BaseMath_WriteCallback(self);
2711 return 0;
2712}
2713
2715static int Matrix_ass_item_col(MatrixObject *self, int col, PyObject *value)
2716{
2717 int row;
2718 float vec[MATRIX_MAX_DIM];
2719 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2720 return -1;
2721 }
2722
2723 if (col >= self->col_num || col < 0) {
2724 PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad col");
2725 return -1;
2726 }
2727
2729 vec, self->row_num, self->row_num, value, "matrix[i] = value assignment") == -1)
2730 {
2731 return -1;
2732 }
2733
2734 /* Since we are assigning a row we cannot memcpy */
2735 for (row = 0; row < self->row_num; row++) {
2736 MATRIX_ITEM(self, row, col) = vec[row];
2737 }
2738
2739 (void)BaseMath_WriteCallback(self);
2740 return 0;
2741}
2742
2747static PyObject *Matrix_slice(MatrixObject *self,
2748 Py_ssize_t start,
2749 Py_ssize_t step,
2750 Py_ssize_t slice_length)
2751{
2752 if (BaseMath_ReadCallback(self) == -1) {
2753 return nullptr;
2754 }
2755
2756 PyObject *tuple = PyTuple_New(slice_length);
2757 Py_ssize_t index = start;
2758 for (Py_ssize_t i = 0; i < slice_length; i++, index += step) {
2759 BLI_assert(index >= 0 && index < self->row_num);
2760 PyTuple_SET_ITEM(tuple,
2761 i,
2763 (PyObject *)self, self->col_num, mathutils_matrix_row_cb_index, index));
2764 }
2765 return tuple;
2766}
2767
2774 Py_ssize_t start,
2775 Py_ssize_t step,
2776 Py_ssize_t slice_length,
2777 PyObject *value)
2778{
2779 /* Subset writes merge into existing values, so sync the source first. */
2780 if (mathutils_slice_is_subset(start, step, slice_length, self->row_num)) {
2781 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
2782 return -1;
2783 }
2784 }
2785 else {
2786 if (BaseMath_Prepare_ForWrite(self) == -1) {
2787 return -1;
2788 }
2789 }
2790
2791 PyObject *value_fast = PySequence_Fast(value, "matrix[slice] = value");
2792 if (value_fast == nullptr) {
2793 return -1;
2794 }
2795
2796 const Py_ssize_t value_num = PySequence_Fast_GET_SIZE(value_fast);
2797 if (value_num != slice_length) {
2798 Py_DECREF(value_fast);
2799 PyErr_Format(PyExc_ValueError,
2800 "matrix[slice] = value: sequence size is %zd, expected %zd",
2801 value_num,
2802 slice_length);
2803 return -1;
2804 }
2805
2806 /* Stage parsed rows so a mid-sequence parse failure cannot leave the matrix
2807 * half-written: only commit after every row has parsed successfully. */
2808 BLI_assert(slice_length <= MATRIX_MAX_DIM);
2810 float staging[MATRIX_MAX_DIM][MATRIX_MAX_DIM];
2811 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
2812
2813 for (Py_ssize_t i = 0; i < slice_length; i++) {
2814 if (mathutils_array_parse(staging[i],
2815 self->col_num,
2816 self->col_num,
2817 value_fast_items[i],
2818 "matrix[slice] = value") == -1)
2819 {
2820 Py_DECREF(value_fast);
2821 return -1;
2822 }
2823 }
2824
2825 Py_DECREF(value_fast);
2826
2827 /* Commit. */
2828 Py_ssize_t index = start;
2829 for (Py_ssize_t i = 0; i < slice_length; i++, index += step) {
2830 BLI_assert(index >= 0 && index < self->row_num);
2831 for (int col = 0; col < self->col_num; col++) {
2832 MATRIX_ITEM(self, index, col) = staging[i][col];
2833 }
2834 }
2835
2836 (void)BaseMath_WriteCallback(self);
2837 return 0;
2838}
2839
2841static PyObject *Matrix_subscript(MatrixObject *self, PyObject *item)
2842{
2843 if (PyIndex_Check(item)) {
2844 Py_ssize_t i;
2845 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2846 if (i == -1 && PyErr_Occurred()) {
2847 return nullptr;
2848 }
2849 if (i < 0) {
2850 i += self->row_num;
2851 }
2852 return Matrix_item_row(self, i);
2853 }
2854 if (PySlice_Check(item)) {
2855 Py_ssize_t start, stop, step, slice_length;
2856
2857 if (PySlice_GetIndicesEx(item, self->row_num, &start, &stop, &step, &slice_length) < 0) {
2858 return nullptr;
2859 }
2860
2861 return Matrix_slice(self, start, step, slice_length);
2862 }
2863
2864 PyErr_Format(
2865 PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
2866 return nullptr;
2867}
2868
2870static int Matrix_ass_subscript(MatrixObject *self, PyObject *item, PyObject *value)
2871{
2872 if (PyIndex_Check(item)) {
2873 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2874 if (i == -1 && PyErr_Occurred()) {
2875 return -1;
2876 }
2877 if (i < 0) {
2878 i += self->row_num;
2879 }
2880 return Matrix_ass_item_row(self, i, value);
2881 }
2882 if (PySlice_Check(item)) {
2883 Py_ssize_t start, stop, step, slice_length;
2884
2885 if (PySlice_GetIndicesEx(item, self->row_num, &start, &stop, &step, &slice_length) < 0) {
2886 return -1;
2887 }
2888
2889 return Matrix_ass_slice(self, start, step, slice_length, value);
2890 }
2891
2892 PyErr_Format(
2893 PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
2894 return -1;
2895}
2896
2898
2899/* -------------------------------------------------------------------- */
2902
2904static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
2905{
2906 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
2907 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
2908
2909 mat1 = reinterpret_cast<MatrixObject *>(m1);
2910 mat2 = reinterpret_cast<MatrixObject *>(m2);
2911
2912 if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
2913 PyErr_Format(PyExc_TypeError,
2914 "Matrix addition: (%s + %s) "
2915 "invalid type for this operation",
2916 Py_TYPE(m1)->tp_name,
2917 Py_TYPE(m2)->tp_name);
2918 return nullptr;
2919 }
2920
2921 if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
2922 return nullptr;
2923 }
2924
2925 if (mat1->col_num != mat2->col_num || mat1->row_num != mat2->row_num) {
2926 PyErr_SetString(PyExc_ValueError,
2927 "Matrix addition: "
2928 "matrices must have the same dimensions for this operation");
2929 return nullptr;
2930 }
2931
2932 add_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->col_num * mat1->row_num);
2933
2934 return Matrix_CreatePyObject(mat, mat1->col_num, mat1->row_num, Py_TYPE(mat1));
2935}
2936
2938static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
2939{
2940 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
2941 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
2942
2943 mat1 = reinterpret_cast<MatrixObject *>(m1);
2944 mat2 = reinterpret_cast<MatrixObject *>(m2);
2945
2946 if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
2947 PyErr_Format(PyExc_TypeError,
2948 "Matrix subtraction: (%s - %s) "
2949 "invalid type for this operation",
2950 Py_TYPE(m1)->tp_name,
2951 Py_TYPE(m2)->tp_name);
2952 return nullptr;
2953 }
2954
2955 if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
2956 return nullptr;
2957 }
2958
2959 if (mat1->col_num != mat2->col_num || mat1->row_num != mat2->row_num) {
2960 PyErr_SetString(PyExc_ValueError,
2961 "Matrix addition: "
2962 "matrices must have the same dimensions for this operation");
2963 return nullptr;
2964 }
2965
2966 sub_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->col_num * mat1->row_num);
2967
2968 return Matrix_CreatePyObject(mat, mat1->col_num, mat1->row_num, Py_TYPE(mat1));
2969}
2970
2972static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
2973{
2974 float tmat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
2975 mul_vn_vn_fl(tmat, mat->matrix, mat->col_num * mat->row_num, scalar);
2976 return Matrix_CreatePyObject(tmat, mat->col_num, mat->row_num, Py_TYPE(mat));
2977}
2978
2979static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
2980{
2981 float scalar;
2982
2983 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
2984
2985 if (MatrixObject_Check(m1)) {
2986 mat1 = reinterpret_cast<MatrixObject *>(m1);
2987 if (BaseMath_ReadCallback(mat1) == -1) {
2988 return nullptr;
2989 }
2990 }
2991 if (MatrixObject_Check(m2)) {
2992 mat2 = reinterpret_cast<MatrixObject *>(m2);
2993 if (BaseMath_ReadCallback(mat2) == -1) {
2994 return nullptr;
2995 }
2996 }
2997
2998 if (mat1 && mat2) {
2999 /* MATRIX * MATRIX */
3000 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
3001
3002 if ((mat1->row_num != mat2->row_num) || (mat1->col_num != mat2->col_num)) {
3003 PyErr_SetString(PyExc_ValueError,
3004 "matrix1 * matrix2: matrix1 number of rows/columns "
3005 "and the matrix2 number of rows/columns must be the same");
3006 return nullptr;
3007 }
3008
3009 mul_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->col_num * mat1->row_num);
3010
3011 return Matrix_CreatePyObject(mat, mat2->col_num, mat1->row_num, Py_TYPE(mat1));
3012 }
3013 if (mat2) {
3014 /* FLOAT/INT * MATRIX */
3015 if (((scalar = PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred()) == 0) {
3016 return matrix_mul_float(mat2, scalar);
3017 }
3018 }
3019 else if (mat1) {
3020 /* MATRIX * FLOAT/INT */
3021 if (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0) {
3022 return matrix_mul_float(mat1, scalar);
3023 }
3024 }
3025
3026 PyErr_Format(PyExc_TypeError,
3027 "Element-wise multiplication: "
3028 "not supported between '%.200s' and '%.200s' types",
3029 Py_TYPE(m1)->tp_name,
3030 Py_TYPE(m2)->tp_name);
3031 return nullptr;
3032}
3033
3035static PyObject *Matrix_imul(PyObject *m1, PyObject *m2)
3036{
3037 float scalar;
3038
3039 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
3040
3041 if (MatrixObject_Check(m1)) {
3042 mat1 = reinterpret_cast<MatrixObject *>(m1);
3043 if (BaseMath_ReadCallback(mat1) == -1) {
3044 return nullptr;
3045 }
3046 }
3047 if (MatrixObject_Check(m2)) {
3048 mat2 = reinterpret_cast<MatrixObject *>(m2);
3049 if (BaseMath_ReadCallback(mat2) == -1) {
3050 return nullptr;
3051 }
3052 }
3053
3054 if (mat1 && mat2) {
3055 /* MATRIX *= MATRIX */
3056 if ((mat1->row_num != mat2->row_num) || (mat1->col_num != mat2->col_num)) {
3057 PyErr_SetString(PyExc_ValueError,
3058 "matrix1 *= matrix2: matrix1 number of rows/columns "
3059 "and the matrix2 number of rows/columns must be the same");
3060 return nullptr;
3061 }
3062
3063 mul_vn_vn(mat1->matrix, mat2->matrix, mat1->col_num * mat1->row_num);
3064 }
3065 else if (mat1 && (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0)) {
3066 /* MATRIX *= FLOAT/INT */
3067 mul_vn_fl(mat1->matrix, mat1->row_num * mat1->col_num, scalar);
3068 }
3069 else {
3070 PyErr_Format(PyExc_TypeError,
3071 "In place element-wise multiplication: "
3072 "not supported between '%.200s' and '%.200s' types",
3073 Py_TYPE(m1)->tp_name,
3074 Py_TYPE(m2)->tp_name);
3075 return nullptr;
3076 }
3077
3078 (void)BaseMath_WriteCallback(mat1);
3079 Py_INCREF(m1);
3080 return m1;
3081}
3082
3084static PyObject *Matrix_matmul(PyObject *m1, PyObject *m2)
3085{
3086 int vec_num;
3087
3088 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
3089
3090 if (MatrixObject_Check(m1)) {
3091 mat1 = reinterpret_cast<MatrixObject *>(m1);
3092 if (BaseMath_ReadCallback(mat1) == -1) {
3093 return nullptr;
3094 }
3095 }
3096 if (MatrixObject_Check(m2)) {
3097 mat2 = reinterpret_cast<MatrixObject *>(m2);
3098 if (BaseMath_ReadCallback(mat2) == -1) {
3099 return nullptr;
3100 }
3101 }
3102
3103 if (mat1 && mat2) {
3104 /* MATRIX @ MATRIX */
3105 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
3106
3107 int col, row, item;
3108
3109 if (mat1->col_num != mat2->row_num) {
3110 PyErr_SetString(PyExc_ValueError,
3111 "matrix1 * matrix2: matrix1 number of columns "
3112 "and the matrix2 number of rows must be the same");
3113 return nullptr;
3114 }
3115
3116 for (col = 0; col < mat2->col_num; col++) {
3117 for (row = 0; row < mat1->row_num; row++) {
3118 double dot = 0.0f;
3119 for (item = 0; item < mat1->col_num; item++) {
3120 dot += double(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
3121 }
3122 mat[(col * mat1->row_num) + row] = float(dot);
3123 }
3124 }
3125
3126 return Matrix_CreatePyObject(mat, mat2->col_num, mat1->row_num, Py_TYPE(mat1));
3127 }
3128 if (mat1) {
3129 /* MATRIX @ VECTOR */
3130 if (VectorObject_Check(m2)) {
3131 VectorObject *vec2 = reinterpret_cast<VectorObject *>(m2);
3132 float tvec[MATRIX_MAX_DIM];
3133 if (BaseMath_ReadCallback(vec2) == -1) {
3134 return nullptr;
3135 }
3136 if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
3137 return nullptr;
3138 }
3139
3140 if (mat1->col_num == 4 && vec2->vec_num == 3) {
3141 vec_num = 3;
3142 }
3143 else {
3144 vec_num = mat1->row_num;
3145 }
3146
3147 return Vector_CreatePyObject(tvec, vec_num, Py_TYPE(m2));
3148 }
3149 }
3150
3151 PyErr_Format(PyExc_TypeError,
3152 "Matrix multiplication: "
3153 "not supported between '%.200s' and '%.200s' types",
3154 Py_TYPE(m1)->tp_name,
3155 Py_TYPE(m2)->tp_name);
3156 return nullptr;
3157}
3158
3160static PyObject *Matrix_imatmul(PyObject *m1, PyObject *m2)
3161{
3162 MatrixObject *mat1 = nullptr, *mat2 = nullptr;
3163
3164 if (MatrixObject_Check(m1)) {
3165 mat1 = reinterpret_cast<MatrixObject *>(m1);
3166 if (BaseMath_ReadCallback(mat1) == -1) {
3167 return nullptr;
3168 }
3169 }
3170 if (MatrixObject_Check(m2)) {
3171 mat2 = reinterpret_cast<MatrixObject *>(m2);
3172 if (BaseMath_ReadCallback(mat2) == -1) {
3173 return nullptr;
3174 }
3175 }
3176
3177 if (mat1 && mat2) {
3178 /* MATRIX @= MATRIX */
3179 float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
3180 int col, row, item;
3181
3182 if (mat1->col_num != mat2->row_num) {
3183 PyErr_SetString(PyExc_ValueError,
3184 "matrix1 * matrix2: matrix1 number of columns "
3185 "and the matrix2 number of rows must be the same");
3186 return nullptr;
3187 }
3188
3189 for (col = 0; col < mat2->col_num; col++) {
3190 for (row = 0; row < mat1->row_num; row++) {
3191 double dot = 0.0f;
3192 for (item = 0; item < mat1->col_num; item++) {
3193 dot += double(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
3194 }
3195 /* store in new matrix as overwriting original at this point will cause
3196 * subsequent iterations to use incorrect values */
3197 mat[(col * mat1->row_num) + row] = float(dot);
3198 }
3199 }
3200
3201 /* copy matrix back */
3202 memcpy(mat1->matrix, mat, (mat1->row_num * mat1->col_num) * sizeof(float));
3203 }
3204 else {
3205 PyErr_Format(PyExc_TypeError,
3206 "In place matrix multiplication: "
3207 "not supported between '%.200s' and '%.200s' types",
3208 Py_TYPE(m1)->tp_name,
3209 Py_TYPE(m2)->tp_name);
3210 return nullptr;
3211 }
3212
3213 (void)BaseMath_WriteCallback(mat1);
3214 Py_INCREF(m1);
3215 return m1;
3216}
3217
3219
3220/* -------------------------------------------------------------------- */
3223
3224static PySequenceMethods Matrix_SeqMethods = {
3225 /*sq_length*/ reinterpret_cast<lenfunc>(Matrix_len),
3226 /*sq_concat*/ nullptr,
3227 /*sq_repeat*/ nullptr,
3228 /*sq_item*/ reinterpret_cast<ssizeargfunc>(Matrix_item_row),
3229 /*was_sq_slice*/ nullptr, /* DEPRECATED. */
3230 /*sq_ass_item*/ reinterpret_cast<ssizeobjargproc>(Matrix_ass_item_row),
3231 /*was_sq_ass_slice*/ nullptr, /* DEPRECATED. */
3232 /*sq_contains*/ nullptr,
3233 /*sq_inplace_concat*/ nullptr,
3234 /*sq_inplace_repeat*/ nullptr,
3235};
3236
3237static PyMappingMethods Matrix_AsMapping = {
3238 /*mp_length*/ reinterpret_cast<lenfunc>(Matrix_len),
3239 /*mp_subscript*/ reinterpret_cast<binaryfunc>(Matrix_subscript),
3240 /*mp_ass_subscript*/ reinterpret_cast<objobjargproc>(Matrix_ass_subscript),
3241};
3242
3243static PyNumberMethods Matrix_NumMethods = {
3244 /*nb_add*/ static_cast<binaryfunc>(Matrix_add),
3245 /*nb_subtract*/ static_cast<binaryfunc>(Matrix_sub),
3246 /*nb_multiply*/ static_cast<binaryfunc>(Matrix_mul),
3247 /*nb_remainder*/ nullptr,
3248 /*nb_divmod*/ nullptr,
3249 /*nb_power*/ nullptr,
3250 /*nb_negative*/ nullptr,
3251 /*nb_positive*/ nullptr,
3252 /*nb_absolute*/ nullptr,
3253 /*nb_bool*/ nullptr,
3254 /*nb_invert*/ reinterpret_cast<unaryfunc>(Matrix_inverted_noargs),
3255 /*nb_lshift*/ nullptr,
3256 /*nb_rshift*/ nullptr,
3257 /*nb_and*/ nullptr,
3258 /*nb_xor*/ nullptr,
3259 /*nb_or*/ nullptr,
3260 /*nb_int*/ nullptr,
3261 /*nb_reserved*/ nullptr,
3262 /*nb_float*/ nullptr,
3263 /*nb_inplace_add*/ nullptr,
3264 /*nb_inplace_subtract*/ nullptr,
3265 /*nb_inplace_multiply*/ static_cast<binaryfunc>(Matrix_imul),
3266 /*nb_inplace_remainder*/ nullptr,
3267 /*nb_inplace_power*/ nullptr,
3268 /*nb_inplace_lshift*/ nullptr,
3269 /*nb_inplace_rshift*/ nullptr,
3270 /*nb_inplace_and*/ nullptr,
3271 /*nb_inplace_xor*/ nullptr,
3272 /*nb_inplace_or*/ nullptr,
3273 /*nb_floor_divide*/ nullptr,
3274 /*nb_true_divide*/ nullptr,
3275 /*nb_inplace_floor_divide*/ nullptr,
3276 /*nb_inplace_true_divide*/ nullptr,
3277 /*nb_index*/ nullptr,
3278 /*nb_matrix_multiply*/ static_cast<binaryfunc>(Matrix_matmul),
3279 /*nb_inplace_matrix_multiply*/ static_cast<binaryfunc>(Matrix_imatmul),
3280};
3281
3283
3284/* -------------------------------------------------------------------- */
3287
3289 /* Wrap. */
3290 Matrix_translation_doc,
3291 "The translation component of the matrix.\n"
3292 "\n"
3293 ":type: :class:`Vector`\n");
3294static PyObject *Matrix_translation_get(MatrixObject *self, void * /*closure*/)
3295{
3296 PyObject *ret;
3297
3298 if (BaseMath_ReadCallback(self) == -1) {
3299 return nullptr;
3300 }
3301
3302 /* Must be 4x4 square matrix. */
3303 if (self->row_num != 4 || self->col_num != 4) {
3304 PyErr_SetString(PyExc_AttributeError,
3305 "Matrix.translation: "
3306 "inappropriate matrix size, must be 4x4");
3307 return nullptr;
3308 }
3309
3311 reinterpret_cast<PyObject *>(self), 3, mathutils_matrix_translation_cb_index, 3);
3312
3313 return ret;
3314}
3315
3316static int Matrix_translation_set(MatrixObject *self, PyObject *value, void * /*closure*/)
3317{
3318 float tvec[3];
3319
3320 if (BaseMath_ReadCallback_ForWrite(self) == -1) {
3321 return -1;
3322 }
3323
3324 /* Must be 4x4 square matrix. */
3325 if (self->row_num != 4 || self->col_num != 4) {
3326 PyErr_SetString(PyExc_AttributeError,
3327 "Matrix.translation: "
3328 "inappropriate matrix size, must be 4x4");
3329 return -1;
3330 }
3331
3332 if (mathutils_array_parse(tvec, 3, 3, value, "Matrix.translation") == -1) {
3333 return -1;
3334 }
3335
3336 copy_v3_v3((reinterpret_cast<float (*)[4]>(self->matrix))[3], tvec);
3337
3338 (void)BaseMath_WriteCallback(self);
3339
3340 return 0;
3341}
3342
3344 /* Wrap. */
3345 Matrix_row_doc,
3346 "Access the matrix by rows (default), (read-only).\n"
3347 "\n"
3348 ":type: :class:`MatrixAccess`\n");
3349static PyObject *Matrix_row_get(MatrixObject *self, void * /*closure*/)
3350{
3352}
3353
3355 /* Wrap. */
3356 Matrix_col_doc,
3357 "Access the matrix by columns (read-only).\n"
3358 "\n"
3359 ":type: :class:`MatrixAccess`\n");
3360static PyObject *Matrix_col_get(MatrixObject *self, void * /*closure*/)
3361{
3363}
3364
3366 /* Wrap. */
3367 Matrix_median_scale_doc,
3368 "The average scale applied to each axis (read-only).\n"
3369 "\n"
3370 ":type: float\n");
3371static PyObject *Matrix_median_scale_get(MatrixObject *self, void * /*closure*/)
3372{
3373 float mat[3][3];
3374
3375 if (BaseMath_ReadCallback(self) == -1) {
3376 return nullptr;
3377 }
3378
3379 /* Must be 3-4 cols, 3-4 rows, square matrix. */
3380 if ((self->row_num < 3) || (self->col_num < 3)) {
3381 PyErr_SetString(PyExc_AttributeError,
3382 "Matrix.median_scale: "
3383 "inappropriate matrix size, 3x3 minimum");
3384 return nullptr;
3385 }
3386
3387 matrix_as_3x3(mat, self);
3388
3389 return PyFloat_FromDouble(mat3_to_scale(mat));
3390}
3391
3393 /* Wrap. */
3394 Matrix_is_identity_doc,
3395 "True if this is an identity matrix (read-only).\n"
3396 "\n"
3397 ":type: bool\n");
3398static PyObject *Matrix_is_identity_get(MatrixObject *self, void * /*closure*/)
3399{
3400 if (BaseMath_ReadCallback(self) == -1) {
3401 return nullptr;
3402 }
3403 return PyBool_FromLong(matrix_is_identity(self));
3404}
3405
3407 /* Wrap. */
3408 Matrix_is_negative_doc,
3409 "True if this matrix results in a negative scale, 3x3 and 4x4 only, "
3410 "(read-only).\n"
3411 "\n"
3412 ":type: bool\n");
3413static PyObject *Matrix_is_negative_get(MatrixObject *self, void * /*closure*/)
3414{
3415 if (BaseMath_ReadCallback(self) == -1) {
3416 return nullptr;
3417 }
3418
3419 /* Must be 3-4 cols, 3-4 rows, square matrix. */
3420 if (self->row_num == 4 && self->col_num == 4) {
3421 return PyBool_FromLong(is_negative_m4(reinterpret_cast<const float (*)[4]>(self->matrix)));
3422 }
3423 if (self->row_num == 3 && self->col_num == 3) {
3424 return PyBool_FromLong(is_negative_m3(reinterpret_cast<const float (*)[3]>(self->matrix)));
3425 }
3426
3427 PyErr_SetString(PyExc_AttributeError,
3428 "Matrix.is_negative: "
3429 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
3430 return nullptr;
3431}
3432
3434 /* Wrap. */
3435 Matrix_is_orthogonal_doc,
3436 "True if this matrix is orthogonal, 3x3 and 4x4 only, (read-only).\n"
3437 "\n"
3438 ":type: bool\n");
3439static PyObject *Matrix_is_orthogonal_get(MatrixObject *self, void * /*closure*/)
3440{
3441 if (BaseMath_ReadCallback(self) == -1) {
3442 return nullptr;
3443 }
3444
3445 /* Must be 3-4 cols, 3-4 rows, square matrix. */
3446 if (self->row_num == 4 && self->col_num == 4) {
3447 return PyBool_FromLong(is_orthonormal_m4(reinterpret_cast<const float (*)[4]>(self->matrix)));
3448 }
3449 if (self->row_num == 3 && self->col_num == 3) {
3450 return PyBool_FromLong(is_orthonormal_m3(reinterpret_cast<const float (*)[3]>(self->matrix)));
3451 }
3452
3453 PyErr_SetString(PyExc_AttributeError,
3454 "Matrix.is_orthogonal: "
3455 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
3456 return nullptr;
3457}
3458
3460 /* Wrap. */
3461 Matrix_is_orthogonal_axis_vectors_doc,
3462 "True if this matrix has orthogonal axis vectors, 3x3 and 4x4 only, "
3463 "(read-only).\n"
3464 "\n"
3465 ":type: bool\n");
3466static PyObject *Matrix_is_orthogonal_axis_vectors_get(MatrixObject *self, void * /*closure*/)
3467{
3468 if (BaseMath_ReadCallback(self) == -1) {
3469 return nullptr;
3470 }
3471
3472 /* Must be 3-4 cols, 3-4 rows, square matrix. */
3473 if (self->row_num == 4 && self->col_num == 4) {
3474 return PyBool_FromLong(is_orthogonal_m4(reinterpret_cast<const float (*)[4]>(self->matrix)));
3475 }
3476 if (self->row_num == 3 && self->col_num == 3) {
3477 return PyBool_FromLong(is_orthogonal_m3(reinterpret_cast<const float (*)[3]>(self->matrix)));
3478 }
3479
3480 PyErr_SetString(PyExc_AttributeError,
3481 "Matrix.is_orthogonal_axis_vectors: "
3482 "inappropriate matrix size - expects 3x3 or 4x4 matrix");
3483 return nullptr;
3484}
3485
3487
3488/* -------------------------------------------------------------------- */
3491
3492static PyGetSetDef Matrix_getseters[] = {
3493 {"median_scale",
3494 reinterpret_cast<getter>(Matrix_median_scale_get),
3495 static_cast<setter>(nullptr),
3496 Matrix_median_scale_doc,
3497 nullptr},
3498 {"translation",
3499 reinterpret_cast<getter>(Matrix_translation_get),
3500 reinterpret_cast<setter>(Matrix_translation_set),
3501 Matrix_translation_doc,
3502 nullptr},
3503 {"row",
3504 reinterpret_cast<getter>(Matrix_row_get),
3505 static_cast<setter>(nullptr),
3506 Matrix_row_doc,
3507 nullptr},
3508 {"col",
3509 reinterpret_cast<getter>(Matrix_col_get),
3510 static_cast<setter>(nullptr),
3511 Matrix_col_doc,
3512 nullptr},
3513 {"is_identity",
3514 reinterpret_cast<getter>(Matrix_is_identity_get),
3515 static_cast<setter>(nullptr),
3516 Matrix_is_identity_doc,
3517 nullptr},
3518 {"is_negative",
3519 reinterpret_cast<getter>(Matrix_is_negative_get),
3520 static_cast<setter>(nullptr),
3521 Matrix_is_negative_doc,
3522 nullptr},
3523 {"is_orthogonal",
3524 reinterpret_cast<getter>(Matrix_is_orthogonal_get),
3525 static_cast<setter>(nullptr),
3526 Matrix_is_orthogonal_doc,
3527 nullptr},
3528 {"is_orthogonal_axis_vectors",
3529 reinterpret_cast<getter>(Matrix_is_orthogonal_axis_vectors_get),
3530 static_cast<setter>(nullptr),
3531 Matrix_is_orthogonal_axis_vectors_doc,
3532 nullptr},
3533 {"is_wrapped",
3534 reinterpret_cast<getter>(BaseMathObject_is_wrapped_get),
3535 static_cast<setter>(nullptr),
3537 nullptr},
3538 {"is_frozen",
3539 reinterpret_cast<getter>(BaseMathObject_is_frozen_get),
3540 static_cast<setter>(nullptr),
3542 nullptr},
3543 {"is_valid",
3544 reinterpret_cast<getter>(BaseMathObject_is_valid_get),
3545 static_cast<setter>(nullptr),
3547 nullptr},
3548 {"owner",
3549 reinterpret_cast<getter>(BaseMathObject_owner_get),
3550 static_cast<setter>(nullptr),
3552 nullptr},
3553 {nullptr, nullptr, nullptr, nullptr, nullptr} /* Sentinel */
3554};
3555
3557
3558/* -------------------------------------------------------------------- */
3561
3562#ifdef __GNUC__
3563# ifdef __clang__
3564# pragma clang diagnostic push
3565# pragma clang diagnostic ignored "-Wcast-function-type"
3566# else
3567# pragma GCC diagnostic push
3568# pragma GCC diagnostic ignored "-Wcast-function-type"
3569# endif
3570#endif
3571
3572static PyMethodDef Matrix_methods[] = {
3573 /* Derived values. */
3574 {"determinant",
3575 reinterpret_cast<PyCFunction>(Matrix_determinant),
3576 METH_NOARGS,
3577 Matrix_determinant_doc},
3578 {"decompose",
3579 reinterpret_cast<PyCFunction>(Matrix_decompose),
3580 METH_NOARGS,
3581 Matrix_decompose_doc},
3582
3583 /* In place only. */
3584 {"zero", reinterpret_cast<PyCFunction>(Matrix_zero), METH_NOARGS, Matrix_zero_doc},
3585 {"identity", reinterpret_cast<PyCFunction>(Matrix_identity), METH_NOARGS, Matrix_identity_doc},
3586
3587 /* Operate on original or copy. */
3588 {"transpose",
3589 reinterpret_cast<PyCFunction>(Matrix_transpose),
3590 METH_NOARGS,
3591 Matrix_transpose_doc},
3592 {"transposed",
3593 reinterpret_cast<PyCFunction>(Matrix_transposed),
3594 METH_NOARGS,
3595 Matrix_transposed_doc},
3596 {"normalize",
3597 reinterpret_cast<PyCFunction>(Matrix_normalize),
3598 METH_NOARGS,
3599 Matrix_normalize_doc},
3600 {"normalized",
3601 reinterpret_cast<PyCFunction>(Matrix_normalized),
3602 METH_NOARGS,
3603 Matrix_normalized_doc},
3604 {"invert", reinterpret_cast<PyCFunction>(Matrix_invert), METH_VARARGS, Matrix_invert_doc},
3605 {"inverted",
3606 reinterpret_cast<PyCFunction>(Matrix_inverted),
3607 METH_VARARGS,
3608 Matrix_inverted_doc},
3609 {"invert_safe",
3610 reinterpret_cast<PyCFunction>(Matrix_invert_safe),
3611 METH_NOARGS,
3612 Matrix_invert_safe_doc},
3613 {"inverted_safe",
3614 reinterpret_cast<PyCFunction>(Matrix_inverted_safe),
3615 METH_NOARGS,
3616 Matrix_inverted_safe_doc},
3617 {"adjugate", reinterpret_cast<PyCFunction>(Matrix_adjugate), METH_NOARGS, Matrix_adjugate_doc},
3618 {"adjugated",
3619 reinterpret_cast<PyCFunction>(Matrix_adjugated),
3620 METH_NOARGS,
3621 Matrix_adjugated_doc},
3622 {"to_2x2", reinterpret_cast<PyCFunction>(Matrix_to_2x2), METH_NOARGS, Matrix_to_2x2_doc},
3623 {"to_3x3", reinterpret_cast<PyCFunction>(Matrix_to_3x3), METH_NOARGS, Matrix_to_3x3_doc},
3624 {"to_4x4", reinterpret_cast<PyCFunction>(Matrix_to_4x4), METH_NOARGS, Matrix_to_4x4_doc},
3625 /* TODO: {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc}, */
3626 {"resize_4x4",
3627 reinterpret_cast<PyCFunction>(Matrix_resize_4x4),
3628 METH_NOARGS,
3629 Matrix_resize_4x4_doc},
3630 {"rotate", reinterpret_cast<PyCFunction>(Matrix_rotate), METH_O, Matrix_rotate_doc},
3631
3632 /* Return converted representation. */
3633 {"to_euler",
3634 reinterpret_cast<PyCFunction>(Matrix_to_euler),
3635 METH_VARARGS,
3636 Matrix_to_euler_doc},
3637 {"to_quaternion",
3638 reinterpret_cast<PyCFunction>(Matrix_to_quaternion),
3639 METH_NOARGS,
3640 Matrix_to_quaternion_doc},
3641 {"to_scale", reinterpret_cast<PyCFunction>(Matrix_to_scale), METH_NOARGS, Matrix_to_scale_doc},
3642 {"to_translation",
3643 reinterpret_cast<PyCFunction>(Matrix_to_translation),
3644 METH_NOARGS,
3645 Matrix_to_translation_doc},
3646
3647 /* Operation between 2 or more types. */
3648 {"lerp", reinterpret_cast<PyCFunction>(Matrix_lerp), METH_VARARGS, Matrix_lerp_doc},
3649 {"copy", reinterpret_cast<PyCFunction>(Matrix_copy), METH_NOARGS, Matrix_copy_doc},
3650 {"__copy__", reinterpret_cast<PyCFunction>(Matrix_copy), METH_NOARGS, Matrix_copy_doc},
3651 {"__deepcopy__",
3652 reinterpret_cast<PyCFunction>(Matrix_deepcopy),
3653 METH_VARARGS,
3654 Matrix_copy_doc},
3655
3656 /* Base-math methods. */
3657 {"freeze",
3658 reinterpret_cast<PyCFunction>(BaseMathObject_freeze),
3659 METH_NOARGS,
3661
3662 /* Class methods. */
3663 {"Identity",
3664 static_cast<PyCFunction>(C_Matrix_Identity),
3665 METH_VARARGS | METH_CLASS,
3666 C_Matrix_Identity_doc},
3667 {"Rotation",
3668 static_cast<PyCFunction>(C_Matrix_Rotation),
3669 METH_VARARGS | METH_CLASS,
3670 C_Matrix_Rotation_doc},
3671 {"Scale",
3672 static_cast<PyCFunction>(C_Matrix_Scale),
3673 METH_VARARGS | METH_CLASS,
3674 C_Matrix_Scale_doc},
3675 {"Shear",
3676 static_cast<PyCFunction>(C_Matrix_Shear),
3677 METH_VARARGS | METH_CLASS,
3678 C_Matrix_Shear_doc},
3679 {"Diagonal",
3680 static_cast<PyCFunction>(C_Matrix_Diagonal),
3681 METH_O | METH_CLASS,
3682 C_Matrix_Diagonal_doc},
3683 {"Translation",
3684 static_cast<PyCFunction>(C_Matrix_Translation),
3685 METH_O | METH_CLASS,
3686 C_Matrix_Translation_doc},
3687 {"OrthoProjection",
3688 static_cast<PyCFunction>(C_Matrix_OrthoProjection),
3689 METH_VARARGS | METH_CLASS,
3690 C_Matrix_OrthoProjection_doc},
3691 {"LocRotScale",
3692 static_cast<PyCFunction>(C_Matrix_LocRotScale),
3693 METH_VARARGS | METH_CLASS,
3694 C_Matrix_LocRotScale_doc},
3695 {nullptr, nullptr, 0, nullptr},
3696};
3697
3698#ifdef __GNUC__
3699# ifdef __clang__
3700# pragma clang diagnostic pop
3701# else
3702# pragma GCC diagnostic pop
3703# endif
3704#endif
3705
3707
3708/* -------------------------------------------------------------------- */
3711
3712#ifdef MATH_STANDALONE
3713# define Matrix_str nullptr
3714#endif
3715
3717 /* Wrap. */
3718 matrix_doc,
3719 ".. class:: Matrix(rows=((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), /)\n"
3720 "\n"
3721 " This object gives access to Matrices in Blender, supporting square and rectangular\n"
3722 " matrices from 2x2 up to 4x4.\n"
3723 "\n"
3724 " :param rows: Sequence of rows.\n"
3725 " :type rows: Sequence[Sequence[float]]\n");
3726PyTypeObject matrix_Type = {
3727 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
3728 /*tp_name*/ "Matrix",
3729 /*tp_basicsize*/ sizeof(MatrixObject),
3730 /*tp_itemsize*/ 0,
3731 /*tp_dealloc*/ reinterpret_cast<destructor>(BaseMathObject_dealloc),
3732 /*tp_vectorcall_offset*/ 0,
3733 /*tp_getattr*/ nullptr,
3734 /*tp_setattr*/ nullptr,
3735 /*tp_as_async*/ nullptr,
3736 /*tp_repr*/ reinterpret_cast<reprfunc>(Matrix_repr),
3737 /*tp_as_number*/ &Matrix_NumMethods,
3738 /*tp_as_sequence*/ &Matrix_SeqMethods,
3739 /*tp_as_mapping*/ &Matrix_AsMapping,
3740 /*tp_hash*/ reinterpret_cast<hashfunc>(Matrix_hash),
3741 /*tp_call*/ nullptr,
3742 /*tp_str*/ reinterpret_cast<reprfunc>(Matrix_str),
3743 /*tp_getattro*/ nullptr,
3744 /*tp_setattro*/ nullptr,
3745 /*tp_as_buffer*/ &Matrix_as_buffer,
3746 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
3747 /*tp_doc*/ matrix_doc,
3748 /*tp_traverse*/ reinterpret_cast<traverseproc>(BaseMathObject_traverse),
3749 /*tp_clear*/ reinterpret_cast<inquiry>(BaseMathObject_clear),
3750 /*tp_richcompare*/ static_cast<richcmpfunc>(Matrix_richcmpr),
3751 /*tp_weaklistoffset*/ 0,
3752 /*tp_iter*/ nullptr,
3753 /*tp_iternext*/ nullptr,
3754 /*tp_methods*/ Matrix_methods,
3755 /*tp_members*/ nullptr,
3756 /*tp_getset*/ Matrix_getseters,
3757 /*tp_base*/ nullptr,
3758 /*tp_dict*/ nullptr,
3759 /*tp_descr_get*/ nullptr,
3760 /*tp_descr_set*/ nullptr,
3761 /*tp_dictoffset*/ 0,
3762 /*tp_init*/ nullptr,
3763 /*tp_alloc*/ nullptr,
3764 /*tp_new*/ Matrix_new,
3765 /*tp_free*/ nullptr,
3766 /*tp_is_gc*/ reinterpret_cast<inquiry>(BaseMathObject_is_gc),
3767 /*tp_bases*/ nullptr,
3768 /*tp_mro*/ nullptr,
3769 /*tp_cache*/ nullptr,
3770 /*tp_subclasses*/ nullptr,
3771 /*tp_weaklist*/ nullptr,
3772 /*tp_del*/ nullptr,
3773 /*tp_version_tag*/ 0,
3774 /*tp_finalize*/ nullptr,
3775 /*tp_vectorcall*/ Matrix_vectorcall,
3776};
3777
3778#ifdef MATH_STANDALONE
3779# undef Matrix_str
3780#endif
3781
3783
3784/* -------------------------------------------------------------------- */
3787
3788PyObject *Matrix_CreatePyObject(const float *mat,
3789 const ushort col_num,
3790 const ushort row_num,
3791 PyTypeObject *base_type)
3792{
3793 MatrixObject *self;
3794 float *mat_alloc;
3795
3796 /* matrix objects can be any 2-4row x 2-4col matrix */
3797 if (col_num < 2 || col_num > 4 || row_num < 2 || row_num > 4) {
3798 PyErr_SetString(PyExc_RuntimeError,
3799 "Matrix(): "
3800 "row and column sizes must be between 2 and 4");
3801 return nullptr;
3802 }
3803
3804 mat_alloc = static_cast<float *>(PyMem_Malloc(col_num * row_num * sizeof(float)));
3805 if (mat_alloc == nullptr) [[unlikely]] {
3806 PyErr_SetString(PyExc_MemoryError,
3807 "Matrix(): "
3808 "problem allocating data");
3809 return nullptr;
3810 }
3811
3812 self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
3813 if (self) {
3814 self->matrix = mat_alloc;
3815 self->col_num = col_num;
3816 self->row_num = row_num;
3817
3818 /* init callbacks as nullptr */
3819 self->cb_user = nullptr;
3820 self->cb_type = self->cb_subtype = 0;
3821
3822 if (mat) { /* If a float array passed. */
3823 memcpy(self->matrix, mat, col_num * row_num * sizeof(float));
3824 }
3825 else if (col_num == row_num) {
3826 /* or if no arguments are passed return identity matrix for square matrices */
3828 }
3829 else {
3830 /* otherwise zero everything */
3831 memset(self->matrix, 0, col_num * row_num * sizeof(float));
3832 }
3833 self->flag = BASE_MATH_FLAG_DEFAULT;
3834 }
3835 else {
3836 PyMem_Free(mat_alloc);
3837 }
3838
3839 return reinterpret_cast<PyObject *>(self);
3840}
3841
3842PyObject *Matrix_CreatePyObject_wrap(float *mat,
3843 const ushort col_num,
3844 const ushort row_num,
3845 PyTypeObject *base_type)
3846{
3847 MatrixObject *self;
3848
3849 /* matrix objects can be any 2-4row x 2-4col matrix */
3850 if (col_num < 2 || col_num > 4 || row_num < 2 || row_num > 4) {
3851 PyErr_SetString(PyExc_RuntimeError,
3852 "Matrix(): "
3853 "row and column sizes must be between 2 and 4");
3854 return nullptr;
3855 }
3856
3857 self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
3858 if (self) {
3859 self->col_num = col_num;
3860 self->row_num = row_num;
3861
3862 /* init callbacks as nullptr */
3863 self->cb_user = nullptr;
3864 self->cb_type = self->cb_subtype = 0;
3865
3866 self->matrix = mat;
3868 }
3869 return reinterpret_cast<PyObject *>(self);
3870}
3871
3873 PyObject *cb_user, const ushort col_num, const ushort row_num, uchar cb_type, uchar cb_subtype)
3874{
3875 MatrixObject *self = reinterpret_cast<MatrixObject *>(
3876 Matrix_CreatePyObject(nullptr, col_num, row_num, nullptr));
3877 if (self) {
3878 Py_INCREF(cb_user);
3879 self->cb_user = cb_user;
3880 self->cb_type = cb_type;
3881 self->cb_subtype = cb_subtype;
3882 BLI_assert(!PyObject_GC_IsTracked((PyObject *)self));
3883 PyObject_GC_Track(self);
3884 }
3885 return reinterpret_cast<PyObject *>(self);
3886}
3887
3888PyObject *Matrix_CreatePyObject_alloc(float *mat,
3889 const ushort col_num,
3890 const ushort row_num,
3891 PyTypeObject *base_type)
3892{
3893 MatrixObject *self;
3894 self = reinterpret_cast<MatrixObject *>(
3895 Matrix_CreatePyObject_wrap(mat, col_num, row_num, base_type));
3896 if (self) {
3897 self->flag &= ~BASE_MATH_FLAG_IS_WRAP;
3898 }
3899
3900 return reinterpret_cast<PyObject *>(self);
3901}
3902
3904
3905/* -------------------------------------------------------------------- */
3908
3913{
3914 if (!MatrixObject_Check(pymat)) {
3915 PyErr_Format(
3916 PyExc_TypeError, "expected a mathutils.Matrix, not a %.200s", Py_TYPE(pymat)->tp_name);
3917 return false;
3918 }
3919 /* sets error */
3920 if (BaseMath_ReadCallback(pymat) == -1) {
3921 return false;
3922 }
3923 return true;
3924}
3925
3926int Matrix_ParseAny(PyObject *o, void *p)
3927{
3928 MatrixObject **pymat_p = static_cast<MatrixObject **>(p);
3929 MatrixObject *pymat = reinterpret_cast<MatrixObject *>(o);
3930
3931 if (!Matrix_ParseCheck(pymat)) {
3932 return 0;
3933 }
3934 *pymat_p = pymat;
3935 return 1;
3936}
3937
3938int Matrix_Parse2x2(PyObject *o, void *p)
3939{
3940 MatrixObject **pymat_p = static_cast<MatrixObject **>(p);
3941 MatrixObject *pymat = reinterpret_cast<MatrixObject *>(o);
3942
3943 if (!Matrix_ParseCheck(pymat)) {
3944 return 0;
3945 }
3946 if ((pymat->col_num != 2) || (pymat->row_num != 2)) {
3947 PyErr_SetString(PyExc_ValueError, "matrix must be 2x2");
3948 return 0;
3949 }
3950
3951 *pymat_p = pymat;
3952 return 1;
3953}
3954
3955int Matrix_Parse3x3(PyObject *o, void *p)
3956{
3957 MatrixObject **pymat_p = static_cast<MatrixObject **>(p);
3958 MatrixObject *pymat = reinterpret_cast<MatrixObject *>(o);
3959
3960 if (!Matrix_ParseCheck(pymat)) {
3961 return 0;
3962 }
3963 if ((pymat->col_num != 3) || (pymat->row_num != 3)) {
3964 PyErr_SetString(PyExc_ValueError, "matrix must be 3x3");
3965 return 0;
3966 }
3967
3968 *pymat_p = pymat;
3969 return 1;
3970}
3971
3972int Matrix_Parse4x4(PyObject *o, void *p)
3973{
3974 MatrixObject **pymat_p = static_cast<MatrixObject **>(p);
3975 MatrixObject *pymat = reinterpret_cast<MatrixObject *>(o);
3976
3977 if (!Matrix_ParseCheck(pymat)) {
3978 return 0;
3979 }
3980 if ((pymat->col_num != 4) || (pymat->row_num != 4)) {
3981 PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
3982 return 0;
3983 }
3984
3985 *pymat_p = pymat;
3986 return 1;
3987}
3988
3990
3991/* -------------------------------------------------------------------- */
3994
3996 PyObject_HEAD /* Required Python macro. */
3999};
4000
4001static int MatrixAccess_traverse(MatrixAccessObject *self, visitproc visit, void *arg)
4002{
4003 Py_VISIT(self->matrix_user);
4004 return 0;
4005}
4006
4008{
4009 Py_CLEAR(self->matrix_user);
4010 return 0;
4011}
4012
4014{
4015 if (self->matrix_user) {
4016 PyObject_GC_UnTrack(self);
4017 MatrixAccess_clear(self);
4018 }
4019
4020 Py_TYPE(self)->tp_free(self);
4021}
4022
4024
4025/* -------------------------------------------------------------------- */
4028
4029static Py_ssize_t MatrixAccess_len(MatrixAccessObject *self)
4030{
4031 return (self->type == MAT_ACCESS_ROW) ? self->matrix_user->row_num : self->matrix_user->col_num;
4032}
4033
4039 Py_ssize_t start,
4040 Py_ssize_t step,
4041 Py_ssize_t slice_length)
4042{
4043 MatrixObject *matrix_user = self->matrix_user;
4044 int matrix_access_len;
4045 PyObject *(*Matrix_item_new)(MatrixObject *, Py_ssize_t);
4046
4047 if (self->type == MAT_ACCESS_ROW) {
4048 matrix_access_len = matrix_user->row_num;
4049 Matrix_item_new = Matrix_item_row;
4050 }
4051 else { /* MAT_ACCESS_COL */
4052 matrix_access_len = matrix_user->col_num;
4053 Matrix_item_new = Matrix_item_col;
4054 }
4055
4056 PyObject *tuple = PyTuple_New(slice_length);
4057 Py_ssize_t index = start;
4058 for (Py_ssize_t i = 0; i < slice_length; i++, index += step) {
4059 BLI_assert(index >= 0 && index < matrix_access_len);
4060 UNUSED_VARS_NDEBUG(matrix_access_len);
4061 PyTuple_SET_ITEM(tuple, i, Matrix_item_new(matrix_user, index));
4062 }
4063 return tuple;
4064}
4065
4072 Py_ssize_t start,
4073 Py_ssize_t step,
4074 Py_ssize_t slice_length,
4075 PyObject *value)
4076{
4077 MatrixObject *matrix_user = self->matrix_user;
4078 int matrix_access_len;
4079 int axis_size;
4080
4081 if (self->type == MAT_ACCESS_ROW) {
4082 matrix_access_len = matrix_user->row_num;
4083 axis_size = matrix_user->col_num;
4084 }
4085 else { /* MAT_ACCESS_COL */
4086 matrix_access_len = matrix_user->col_num;
4087 axis_size = matrix_user->row_num;
4088 }
4089
4090 /* Subset writes merge into existing values, so sync the source first. */
4091 if (mathutils_slice_is_subset(start, step, slice_length, matrix_access_len)) {
4092 if (BaseMath_ReadCallback_ForWrite(matrix_user) == -1) {
4093 return -1;
4094 }
4095 }
4096 else {
4097 if (BaseMath_Prepare_ForWrite(matrix_user) == -1) {
4098 return -1;
4099 }
4100 }
4101
4102 PyObject *value_fast = PySequence_Fast(value, "matrix.row/col[slice] = value");
4103 if (value_fast == nullptr) {
4104 return -1;
4105 }
4106
4107 const Py_ssize_t value_num = PySequence_Fast_GET_SIZE(value_fast);
4108 if (value_num != slice_length) {
4109 Py_DECREF(value_fast);
4110 PyErr_Format(PyExc_ValueError,
4111 "matrix.%s[slice] = value: sequence size is %zd, expected %zd",
4112 (self->type == MAT_ACCESS_ROW) ? "row" : "col",
4113 value_num,
4114 slice_length);
4115 return -1;
4116 }
4117
4118 /* Stage parsed rows/cols so a mid-sequence parse failure cannot leave the
4119 * matrix half-written: only commit after every item has parsed successfully. */
4120 BLI_assert(slice_length <= MATRIX_MAX_DIM);
4121 BLI_assert(axis_size <= MATRIX_MAX_DIM);
4122 float staging[MATRIX_MAX_DIM][MATRIX_MAX_DIM];
4123 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
4124
4125 for (Py_ssize_t i = 0; i < slice_length; i++) {
4126 if (mathutils_array_parse(staging[i],
4127 axis_size,
4128 axis_size,
4129 value_fast_items[i],
4130 "matrix.row/col[slice] = value") == -1)
4131 {
4132 Py_DECREF(value_fast);
4133 return -1;
4134 }
4135 }
4136
4137 Py_DECREF(value_fast);
4138
4139 /* Commit. */
4140 Py_ssize_t index = start;
4141 if (self->type == MAT_ACCESS_ROW) {
4142 for (Py_ssize_t i = 0; i < slice_length; i++, index += step) {
4143 BLI_assert(index >= 0 && index < matrix_access_len);
4144 for (int col = 0; col < axis_size; col++) {
4145 MATRIX_ITEM(matrix_user, index, col) = staging[i][col];
4146 }
4147 }
4148 }
4149 else { /* MAT_ACCESS_COL */
4150 for (Py_ssize_t i = 0; i < slice_length; i++, index += step) {
4151 BLI_assert(index >= 0 && index < matrix_access_len);
4152 for (int row = 0; row < axis_size; row++) {
4153 MATRIX_ITEM(matrix_user, row, index) = staging[i][row];
4154 }
4155 }
4156 }
4157
4158 (void)BaseMath_WriteCallback(matrix_user);
4159 return 0;
4160}
4161
4162static PyObject *MatrixAccess_subscript(MatrixAccessObject *self, PyObject *item)
4163{
4164 MatrixObject *matrix_user = self->matrix_user;
4165
4166 if (PyIndex_Check(item)) {
4167 Py_ssize_t i;
4168 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
4169 if (i == -1 && PyErr_Occurred()) {
4170 return nullptr;
4171 }
4172 if (self->type == MAT_ACCESS_ROW) {
4173 if (i < 0) {
4174 i += matrix_user->row_num;
4175 }
4176 return Matrix_item_row(matrix_user, i);
4177 }
4178 /* MAT_ACCESS_COL */
4179 if (i < 0) {
4180 i += matrix_user->col_num;
4181 }
4182 return Matrix_item_col(matrix_user, i);
4183 }
4184 if (PySlice_Check(item)) {
4185 Py_ssize_t start, stop, step, slice_length;
4186
4187 if (PySlice_GetIndicesEx(item, MatrixAccess_len(self), &start, &stop, &step, &slice_length) <
4188 0)
4189 {
4190 return nullptr;
4191 }
4192
4193 return MatrixAccess_slice(self, start, step, slice_length);
4194 }
4195
4196 PyErr_Format(
4197 PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
4198 return nullptr;
4199}
4200
4201static int MatrixAccess_ass_subscript(MatrixAccessObject *self, PyObject *item, PyObject *value)
4202{
4203 MatrixObject *matrix_user = self->matrix_user;
4204
4205 if (PyIndex_Check(item)) {
4206 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
4207 if (i == -1 && PyErr_Occurred()) {
4208 return -1;
4209 }
4210
4211 if (self->type == MAT_ACCESS_ROW) {
4212 if (i < 0) {
4213 i += matrix_user->row_num;
4214 }
4215 return Matrix_ass_item_row(matrix_user, i, value);
4216 }
4217 /* MAT_ACCESS_COL */
4218 if (i < 0) {
4219 i += matrix_user->col_num;
4220 }
4221 return Matrix_ass_item_col(matrix_user, i, value);
4222 }
4223 if (PySlice_Check(item)) {
4224 Py_ssize_t start, stop, step, slice_length;
4225
4226 if (PySlice_GetIndicesEx(item, MatrixAccess_len(self), &start, &stop, &step, &slice_length) <
4227 0)
4228 {
4229 return -1;
4230 }
4231
4232 return MatrixAccess_ass_slice(self, start, step, slice_length, value);
4233 }
4234
4235 PyErr_Format(
4236 PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
4237 return -1;
4238}
4239
4241{
4242 /* Try get values from a collection. */
4243 PyObject *ret;
4244 PyObject *iter = nullptr;
4245 ret = MatrixAccess_slice(self, 0, 1, MatrixAccess_len(self));
4246
4247 /* We know this is a tuple so no need to #PyIter_Check
4248 * otherwise it could be nullptr (unlikely) if conversion failed. */
4249 if (ret) {
4250 iter = PyObject_GetIter(ret);
4251 Py_DECREF(ret);
4252 }
4253
4254 return iter;
4255}
4256
4257static PyMappingMethods MatrixAccess_AsMapping = {
4258 /*mp_length*/ reinterpret_cast<lenfunc>(MatrixAccess_len),
4259 /*mp_subscript*/ reinterpret_cast<binaryfunc>(MatrixAccess_subscript),
4260 /*mp_ass_subscript*/ reinterpret_cast<objobjargproc>(MatrixAccess_ass_subscript),
4261};
4262
4264
4265/* -------------------------------------------------------------------- */
4268
4270 /* Wrap. */
4271 matrix_access_doc,
4272 "An indexable type for accessing matrix rows or columns as :class:`Vector` types.\n");
4273
4274PyTypeObject matrix_access_Type = {
4275 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
4276 /*tp_name*/ "MatrixAccess",
4277 /*tp_basicsize*/ sizeof(MatrixAccessObject),
4278 /*tp_itemsize*/ 0,
4279 /*tp_dealloc*/ reinterpret_cast<destructor>(MatrixAccess_dealloc),
4280 /*tp_vectorcall_offset*/ 0,
4281 /*tp_getattr*/ nullptr,
4282 /*tp_setattr*/ nullptr,
4283 /*tp_as_async*/ nullptr,
4284 /*tp_repr*/ nullptr,
4285 /*tp_as_number*/ nullptr,
4286 /*tp_as_sequence*/ nullptr /* &MatrixAccess_SeqMethods */ /* TODO. */,
4287 /*tp_as_mapping*/ &MatrixAccess_AsMapping,
4288 /*tp_hash*/ nullptr,
4289 /*tp_call*/ nullptr,
4290 /*tp_str*/ nullptr,
4291 /*tp_getattro*/ nullptr,
4292 /*tp_setattro*/ nullptr,
4293 /*tp_as_buffer*/ nullptr,
4294 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4295 /*tp_doc*/ matrix_access_doc,
4296 /*tp_traverse*/ reinterpret_cast<traverseproc>(MatrixAccess_traverse),
4297 /*tp_clear*/ reinterpret_cast<inquiry>(MatrixAccess_clear),
4298 /*tp_richcompare*/ nullptr /* MatrixAccess_richcmpr */ /* TODO. */,
4299 /*tp_weaklistoffset*/ 0,
4300 /*tp_iter*/ reinterpret_cast<getiterfunc>(MatrixAccess_iter),
4301 /*tp_iternext*/ nullptr,
4302 /*tp_methods*/ nullptr,
4303 /*tp_members*/ nullptr,
4304 /*tp_getset*/ nullptr,
4305 /*tp_base*/ nullptr,
4306 /*tp_dict*/ nullptr,
4307 /*tp_descr_get*/ nullptr,
4308 /*tp_descr_set*/ nullptr,
4309 /*tp_dictoffset*/ 0,
4310 /*tp_init*/ nullptr,
4311 /*tp_alloc*/ nullptr,
4312 /*tp_new*/ nullptr,
4313 /*tp_free*/ nullptr,
4314 /*tp_is_gc*/ nullptr,
4315 /*tp_bases*/ nullptr,
4316 /*tp_mro*/ nullptr,
4317 /*tp_cache*/ nullptr,
4318 /*tp_subclasses*/ nullptr,
4319 /*tp_weaklist*/ nullptr,
4320 /*tp_del*/ nullptr,
4321 /*tp_version_tag*/ 0,
4322 /*tp_finalize*/ nullptr,
4323 /*tp_vectorcall*/ nullptr,
4324};
4325
4327
4328/* -------------------------------------------------------------------- */
4331
4332static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type)
4333{
4334 MatrixAccessObject *matrix_access = reinterpret_cast<MatrixAccessObject *> PyObject_GC_New(
4336
4337 matrix_access->matrix_user = matrix;
4338 Py_INCREF(matrix);
4339
4340 matrix_access->type = type;
4341
4342 return reinterpret_cast<PyObject *>(matrix_access);
4343}
4344
4346
4347} // namespace blender
#define ATTR_FALLTHROUGH
A dynamically sized string ADT.
#define PSEUDOINVERSE_EPSILON
#define SNPRINTF_UTF8_RLEN(dst, format,...)
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define UNLIKELY(x)
#define ELEM(...)
#define STREQ(a, b)
SIMD_FORCE_INLINE btScalar norm() const
Return the norm (length) of the vector.
Definition btVector3.h:263
SIMD_FORCE_INLINE btScalar angle(const btVector3 &v) const
Return the angle between this and another vector.
Definition btVector3.h:356
#define rot(x, k)
float dot(VecOp< float, D >, VecOp< float, D >) RET
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
float3x3 scale(float3x3 mat, float2 scale)
#define BaseMathObject_Prepare_ForResize(_self, error_prefix)
Definition mathutils.hh:180
#define BaseMath_ReadCallback_ForWrite(_self)
Definition mathutils.hh:157
#define BaseMath_Prepare_ForBufferAccess(_self, _view, _flags)
Definition mathutils.hh:189
#define BaseMath_WriteCallback(_self)
Definition mathutils.hh:149
#define BASE_MATH_NEW(struct_name, root_type, base_type)
Definition mathutils.hh:29
#define BaseMathObject_Prepare_ForHash(_self)
Definition mathutils.hh:172
#define BASE_MATH_FLAG_DEFAULT
Definition mathutils.hh:54
#define BaseMath_Prepare_ForWrite(_self)
Definition mathutils.hh:167
#define BaseMath_ReadCallback(_self)
Definition mathutils.hh:147
#define EulerObject_Check(v)
#define MATRIX_COL_PTR(_mat, _col)
#define MATRIX_MAX_DIM
#define MatrixObject_Check(v)
#define MATRIX_ITEM_INDEX_NUMROW(_totrow, _row, _col)
#define MATRIX_ITEM(_mat, _row, _col)
#define QuaternionObject_Check(v)
#define VectorObject_Check(v)
BMesh Iterators.
char BaseMathObject_owner_doc[]
Definition mathutils.cc:686
static void MatrixAccess_dealloc(MatrixAccessObject *self)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void mul_vn_fl(float *array_tar, int size, float f)
char BaseMathObject_freeze_doc[]
Definition mathutils.cc:716
static PyObject * C_Matrix_Translation(PyObject *cls, PyObject *value)
static int Matrix_ass_subscript(MatrixObject *self, PyObject *item, PyObject *value)
static PyMethodDef Matrix_methods[]
int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int floatSteps)
Definition mathutils.cc:511
static PyObject * Matrix_zero(MatrixObject *self)
static PyObject * Matrix_to_NxN(MatrixObject *self, const int col_num, const int row_num)
static int mathutils_matrix_row_check(BaseMathObject *bmo)
void BLI_dynstr_appendf(DynStr *__restrict ds, const char *__restrict format,...) ATTR_PRINTF_FORMAT(2
static void adjoint_matrix_n(float *mat_dst, const float *mat_src, const ushort dim)
static bool matrix_invert_args_check(const MatrixObject *self, PyObject *args, bool check_type)
static PyObject * Matrix_imul(PyObject *m1, PyObject *m2)
void mat4_to_loc_rot_size(float loc[3], float rot[3][3], float size[3], const float wmat[4][4])
static Py_ssize_t MatrixAccess_len(MatrixAccessObject *self)
static PyObject * Matrix_matmul(PyObject *m1, PyObject *m2)
bool mathutils_slice_is_subset(Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length, Py_ssize_t array_num)
Definition mathutils.hh:241
static PyObject * Matrix_normalized(MatrixObject *self)
static int mathutils_matrix_translation_set(BaseMathObject *bmo, int col)
static PyObject * Matrix_str(MatrixObject *self)
void BaseMathObject_dealloc(BaseMathObject *self)
Definition mathutils.cc:766
static PyObject * C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void mat4_to_quat(float q[4], const float mat[4][4])
static PyObject * C_Matrix_Rotation(PyObject *cls, PyObject *args)
int PyC_CheckArgs_DeepCopy(PyObject *args)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
static PyObject * Matrix_transpose(MatrixObject *self)
void sub_vn_vnvn(float *array_tar, const float *array_src_a, const float *array_src_b, int size)
void copy_m3_m4(float m1[3][3], const float m2[4][4])
Py_hash_t mathutils_array_hash(const float *array, size_t array_len)
Definition mathutils.cc:69
void copy_m3_m3(float m1[3][3], const float m2[3][3])
PyObject * mathutils_dynstr_to_py(DynStr *ds)
Definition mathutils.cc:523
static int matrix_row_vector_check(MatrixObject *mat, VectorObject *vec, int row)
static PyObject * Matrix_to_3x3(MatrixObject *self)
void mul_vn_vn_fl(float *array_tar, const float *array_src, int size, float f)
void copy_m4_m3(float m1[4][4], const float m2[3][3])
static PyObject * Matrix_mul(PyObject *m1, PyObject *m2)
static PyObject * Matrix_transposed(MatrixObject *self)
static PyObject * Matrix_rotate(MatrixObject *self, PyObject *value)
static void matrix_transpose_internal(float mat_dst_fl[], const MatrixObject *mat_src)
uchar mathutils_matrix_col_cb_index
uchar mathutils_matrix_row_cb_index
void normalize_m3(float R[3][3]) ATTR_NONNULL()
static Py_hash_t Matrix_hash(MatrixObject *self)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
PyObject * BaseMathObject_owner_get(BaseMathObject *self, void *)
Definition mathutils.cc:690
static PyObject * Matrix_repr(MatrixObject *self)
unsigned short ushort
Definition BKE_text.h:56
int Matrix_Parse2x2(PyObject *o, void *p)
PyObject * Euler_CreatePyObject(const float eul[3], const short order, PyTypeObject *base_type)
static int mathutils_matrix_row_get_index(BaseMathObject *bmo, int row, int col)
void interp_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4], float t)
static PyObject * Matrix_richcmpr(PyObject *a, PyObject *b, int op)
PyTypeObject euler_Type
float determinant_m2(float a, float b, float c, float d)
void axis_angle_to_mat3(float R[3][3], const float axis[3], float angle)
void blend_m4_m4m4(float out[4][4], const float dst[4][4], const float src[4][4], float srcweight)
static void Matrix_releasebuffer(PyObject *, Py_buffer *view)
PyTypeObject matrix_access_Type
bool is_negative_m4(const float mat[4][4])
static PyObject * Matrix_to_scale(MatrixObject *self)
static PyObject * matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *), MatrixObject *self)
int BaseMathObject_clear(BaseMathObject *self)
Definition mathutils.cc:748
MINLINE int max_ii(int a, int b)
PyObject * BaseMathObject_freeze(BaseMathObject *self)
Definition mathutils.cc:725
void unit_m2(float m[2][2])
int Matrix_ParseAny(PyObject *o, void *p)
void mat3_normalized_to_compatible_eulO(float eul[3], const float oldrot[3], short order, const float mat[3][3])
static int mathutils_matrix_translation_get(BaseMathObject *bmo, int col)
static PyObject * Matrix_to_translation(MatrixObject *self)
static int mathutils_matrix_col_get(BaseMathObject *bmo, int col)
void mat3_normalized_to_eul(float eul[3], const float mat[3][3])
float determinant_m3_array(const float m[3][3])
static int Matrix_ass_item_col(MatrixObject *self, int col, PyObject *value)
static void matrix_invert_raise_degenerate()
PyObject * Matrix_CreatePyObject_cb(PyObject *cb_user, const ushort col_num, const ushort row_num, uchar cb_type, uchar cb_subtype)
static PyObject * Matrix_to_2x2(MatrixObject *self)
Mathutils_Callback mathutils_matrix_col_cb
void mat3_to_rot_size(float rot[3][3], float size[3], const float mat3[3][3])
int BaseMathObject_is_gc(BaseMathObject *self)
Definition mathutils.cc:788
void normalize_m4(float R[4][4]) ATTR_NONNULL()
static bool matrix_invert_is_compat(const MatrixObject *self)
static void matrix_identity_internal(MatrixObject *self)
static int MatrixAccess_clear(MatrixAccessObject *self)
static PyObject * Matrix_lerp(MatrixObject *self, PyObject *args)
static PyObject * MatrixAccess_iter(MatrixAccessObject *self)
static PyObject * Matrix_is_orthogonal_get(MatrixObject *self, void *)
PyObject * BaseMathObject_is_frozen_get(BaseMathObject *self, void *)
Definition mathutils.cc:705
static PyObject * Matrix_is_negative_get(MatrixObject *self, void *)
bool is_orthogonal_m3(const float m[3][3])
static PyObject * Matrix_inverted(MatrixObject *self, PyObject *args)
void BLI_dynstr_append(DynStr *__restrict ds, const char *cstr) ATTR_NONNULL()
Definition BLI_dynstr.cc:58
PyObject * Vector_CreatePyObject(const float *vec, const int vec_num, PyTypeObject *base_type)
PyObject * BaseMathObject_is_valid_get(BaseMathObject *self, void *)
Definition mathutils.cc:711
void matrix_as_3x3(float mat[3][3], MatrixObject *self)
static int MatrixAccess_traverse(MatrixAccessObject *self, visitproc visit, void *arg)
void adjoint_m3_m3(float R[3][3], const float M[3][3])
unsigned char uchar
Definition BKE_text.h:58
PyObject * Matrix_CreatePyObject(const float *mat, const ushort col_num, const ushort row_num, PyTypeObject *base_type)
void transpose_m3(float R[3][3])
void mat3_normalized_to_quat_fast(float q[4], const float mat[3][3])
static PyObject * Matrix_translation_get(MatrixObject *self, void *)
static int mathutils_matrix_col_set_index(BaseMathObject *bmo, int col, int row)
static PyObject * Matrix_to_euler(MatrixObject *self, PyObject *args)
PyObject * Quaternion_CreatePyObject(const float quat[4], PyTypeObject *base_type)
Mathutils_Callback mathutils_matrix_row_cb
int Matrix_Parse3x3(PyObject *o, void *p)
static PyObject * Matrix_add(PyObject *m1, PyObject *m2)
static PyObject * MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type)
static PyObject * Matrix_deepcopy(MatrixObject *self, PyObject *args)
static int mathutils_matrix_col_get_index(BaseMathObject *bmo, int col, int row)
static void matrix_3x3_as_4x4(float mat[16])
static int Matrix_ass_item_row(MatrixObject *self, Py_ssize_t row, PyObject *value)
bool is_orthonormal_m3(const float m[3][3])
static PyObject * C_Matrix_Scale(PyObject *cls, PyObject *args)
void adjoint_m2_m2(float R[2][2], const float M[2][2])
static PyObject * Matrix_slice(MatrixObject *self, Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length)
PyObject * Vector_CreatePyObject_cb(PyObject *cb_user, int vec_num, uchar cb_type, uchar cb_subtype)
static bool Matrix_ParseCheck(MatrixObject *pymat)
static PyNumberMethods Matrix_NumMethods
static int Matrix_getbuffer(PyObject *obj, Py_buffer *view, int flags)
static int MatrixAccess_ass_slice(MatrixAccessObject *self, Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length, PyObject *value)
static bool matrix_invert_internal(const MatrixObject *self, float *r_mat)
@ BASE_MATH_FLAG_IS_WRAP
Definition mathutils.hh:39
@ BASE_MATH_FLAG_HAS_BUFFER_VIEW
Definition mathutils.hh:52
PyObject * Matrix_CreatePyObject_wrap(float *mat, const ushort col_num, const ushort row_num, PyTypeObject *base_type)
void blend_m3_m3m3(float out[3][3], const float dst[3][3], const float src[3][3], float srcweight)
static PyObject * Matrix_to_quaternion(MatrixObject *self)
int mathutils_array_parse(float *array, int array_num_min, int array_num_max, PyObject *value, const char *error_prefix)
Definition mathutils.cc:97
static PyObject * MatrixAccess_subscript(MatrixAccessObject *self, PyObject *item)
static PyObject * Matrix_adjugate(MatrixObject *self)
int column_vector_multiplication(float r_vec[4], VectorObject *vec, MatrixObject *mat)
static PyObject * Matrix_item_row(MatrixObject *self, Py_ssize_t row)
static Py_ssize_t Matrix_len(MatrixObject *self)
static PyObject * Matrix_normalize(MatrixObject *self)
void unit_m4(float m[4][4])
void mul_vn_vn(float *array_tar, const float *array_src, int size)
static PyBufferProcs Matrix_as_buffer
static int MatrixAccess_ass_subscript(MatrixAccessObject *self, PyObject *item, PyObject *value)
static PyObject * Matrix_is_orthogonal_axis_vectors_get(MatrixObject *self, void *)
static int matrix_col_vector_check(MatrixObject *mat, VectorObject *vec, int col)
static int mathutils_matrix_translation_check(BaseMathObject *bmo)
static PyObject * Matrix_inverted_noargs(MatrixObject *self)
void angle_to_mat2(float R[2][2], float angle)
MINLINE void zero_v3(float r[3])
short euler_order_from_string(const char *str, const char *error_prefix)
void mat3_normalized_to_compatible_eul(float eul[3], const float oldrot[3], float mat[3][3])
static PyObject * Matrix_sub(PyObject *m1, PyObject *m2)
static PyObject * Matrix_determinant(MatrixObject *self)
void add_vn_vnvn(float *array_tar, const float *array_src_a, const float *array_src_b, int size)
static PyObject * C_Matrix_Identity(PyObject *cls, PyObject *args)
static PyObject * Matrix_imatmul(PyObject *m1, PyObject *m2)
static int mathutils_matrix_row_set(BaseMathObject *bmo, int row)
static PyMappingMethods Matrix_AsMapping
static PyObject * Matrix_median_scale_get(MatrixObject *self, void *)
static PyObject * Matrix_row_get(MatrixObject *self, void *)
PyTypeObject matrix_Type
static PyMappingMethods MatrixAccess_AsMapping
PyObject * BaseMathObject_is_wrapped_get(BaseMathObject *self, void *)
Definition mathutils.cc:698
char BaseMathObject_is_valid_doc[]
Definition mathutils.cc:710
void transpose_m4(float R[4][4])
static PyObject * Matrix_to_4x4(MatrixObject *self)
void interp_m3_m3m3(float R[3][3], const float A[3][3], const float B[3][3], float t)
void unit_m3(float m[3][3])
Mathutils_Callback mathutils_matrix_translation_cb
bool is_orthonormal_m4(const float m[4][4])
static PyObject * Matrix_col_get(MatrixObject *self, void *)
int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
Definition mathutils.cc:742
static PyObject * Matrix_resize_4x4(MatrixObject *self)
int Matrix_Parse4x4(PyObject *o, void *p)
static bool matrix_is_identity(MatrixObject *self)
static PyObject * C_Matrix_LocRotScale(PyObject *cls, PyObject *args)
int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
Definition mathutils.cc:426
static PyObject * Matrix_is_identity_get(MatrixObject *self, void *)
void eulO_to_mat4(float mat[4][4], const float e[3], short order)
uchar mathutils_matrix_translation_cb_index
static int Matrix_ass_slice(MatrixObject *self, Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length, PyObject *value)
bool is_orthogonal_m4(const float m[4][4])
void rescale_m4(float mat[4][4], const float scale[3])
static PyObject * C_Matrix_Shear(PyObject *cls, PyObject *args)
static PyGetSetDef Matrix_getseters[]
static PyObject * matrix_mul_float(MatrixObject *mat, const float scalar)
static int mathutils_matrix_translation_set_index(BaseMathObject *bmo, int col, int row)
char BaseMathObject_is_frozen_doc[]
Definition mathutils.cc:703
static PyObject * MatrixAccess_slice(MatrixAccessObject *self, Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length)
static int Matrix_translation_set(MatrixObject *self, PyObject *value, void *)
static PyObject * Matrix_invert_safe(MatrixObject *self)
static PyObject * Matrix_invert(MatrixObject *self, PyObject *args)
void mul_vn_vnvn(float *array_tar, const float *array_src_a, const float *array_src_b, int size)
void mul_m3_m3m3(float R[3][3], const float A[3][3], const float B[3][3])
void copy_m4_m4(float m1[4][4], const float m2[4][4])
static void matrix_unit_internal(MatrixObject *self)
static PyObject * C_Matrix_Diagonal(PyObject *cls, PyObject *value)
static PyObject * Matrix_copy_notest(MatrixObject *self, const float *matrix)
static PyObject * Matrix_copy(MatrixObject *self)
bool is_negative_m3(const float mat[3][3])
static float matrix_determinant_internal(const MatrixObject *self)
static int mathutils_matrix_row_get(BaseMathObject *bmo, int row)
MINLINE int min_ii(int a, int b)
DynStr * BLI_dynstr_new() ATTR_MALLOC ATTR_WARN_UNUSED_RESULT
Definition BLI_dynstr.cc:39
int PyC_ParseTypeOrNone(PyObject *o, void *p)
static PyObject * Matrix_vectorcall(PyObject *type, PyObject *const *args, const size_t nargsf, PyObject *kwnames)
static PyObject * Matrix_subscript(MatrixObject *self, PyObject *item)
PyObject * Matrix_CreatePyObject_alloc(float *mat, const ushort col_num, const ushort row_num, PyTypeObject *base_type)
static void matrix_invert_safe_internal(const MatrixObject *self, float *r_mat)
float determinant_m3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3)
float mat3_to_scale(const float mat[3][3])
void mat3_to_quat(float q[4], const float mat[3][3])
static void matrix_invert_with_det_n_internal(float *mat_dst, const float *mat_src, const float det, const ushort dim)
static int mathutils_matrix_col_set(BaseMathObject *bmo, int col)
static PyObject * Matrix_item_col(MatrixObject *self, Py_ssize_t col)
static int mathutils_matrix_col_check(BaseMathObject *bmo)
static void matrix_copy(MatrixObject *mat_dst, const MatrixObject *mat_src)
void mat3_normalized_to_eulO(float eul[3], short order, const float m[3][3])
void axis_angle_to_mat3_single(float R[3][3], char axis, float angle)
void quat_to_mat4(float m[4][4], const float q[4])
static PyObject * Matrix_inverted_safe(MatrixObject *self)
static int mathutils_matrix_translation_get_index(BaseMathObject *bmo, int col, int row)
static PyObject * Matrix_identity(MatrixObject *self)
static int mathutils_matrix_row_set_index(BaseMathObject *bmo, int row, int col)
void adjoint_m4_m4(float R[4][4], const float M[4][4])
static PyObject * Matrix_adjugated(MatrixObject *self)
static PyObject * Matrix_decompose(MatrixObject *self)
static PyObject * Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
char BaseMathObject_is_wrapped_doc[]
Definition mathutils.cc:696
float determinant_m4(const float m[4][4])
static PySequenceMethods Matrix_SeqMethods
float angle_wrap_rad(float angle)
const btScalar eps
Definition poly34.cpp:11
#define PyC_TYPE_OR_NONE_INIT(py_type, value_p)
header-only utilities
#define PyTuple_SET_ITEMS(op_arg,...)
#define sqrtf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
PyObject_HEAD MatrixObject * matrix_user