PyAPI: allow non-vector args for geometry module
[blender-staging.git] / source / blender / python / mathutils / mathutils_geometry.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Joseph Gilbert, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/mathutils/mathutils_geometry.c
24  *  \ingroup pymathutils
25  */
26
27
28 #include <Python.h>
29
30 #include "mathutils.h"
31 #include "mathutils_geometry.h"
32
33 /* Used for PolyFill */
34 #ifndef MATH_STANDALONE /* define when building outside blender */
35 #  include "MEM_guardedalloc.h"
36 #  include "BLI_blenlib.h"
37 #  include "BLI_boxpack2d.h"
38 #  include "BLI_convexhull2d.h"
39 #  include "BKE_displist.h"
40 #  include "BKE_curve.h"
41 #endif
42
43 #include "BLI_math.h"
44 #include "BLI_utildefines.h"
45
46 /*-------------------------DOC STRINGS ---------------------------*/
47 PyDoc_STRVAR(M_Geometry_doc,
48 "The Blender geometry module"
49 );
50
51 /* ---------------------------------INTERSECTION FUNCTIONS-------------------- */
52
53 PyDoc_STRVAR(M_Geometry_intersect_ray_tri_doc,
54 ".. function:: intersect_ray_tri(v1, v2, v3, ray, orig, clip=True)\n"
55 "\n"
56 "   Returns the intersection between a ray and a triangle, if possible, returns None otherwise.\n"
57 "\n"
58 "   :arg v1: Point1\n"
59 "   :type v1: :class:`mathutils.Vector`\n"
60 "   :arg v2: Point2\n"
61 "   :type v2: :class:`mathutils.Vector`\n"
62 "   :arg v3: Point3\n"
63 "   :type v3: :class:`mathutils.Vector`\n"
64 "   :arg ray: Direction of the projection\n"
65 "   :type ray: :class:`mathutils.Vector`\n"
66 "   :arg orig: Origin\n"
67 "   :type orig: :class:`mathutils.Vector`\n"
68 "   :arg clip: When False, don't restrict the intersection to the area of the triangle, use the infinite plane defined by the triangle.\n"
69 "   :type clip: boolean\n"
70 "   :return: The point of intersection or None if no intersection is found\n"
71 "   :rtype: :class:`mathutils.Vector` or None\n"
72 );
73 static PyObject *M_Geometry_intersect_ray_tri(PyObject *UNUSED(self), PyObject *args)
74 {
75         const char *error_prefix = "intersect_ray_tri";
76         PyObject *py_ray, *py_ray_off, *py_tri[3];
77         float dir[3], orig[3], tri[3][3], e1[3], e2[3], pvec[3], tvec[3], qvec[3];
78         float det, inv_det, u, v, t;
79         int clip = 1;
80         int i;
81
82         if (!PyArg_ParseTuple(
83                 args, "OOOOO|i:intersect_ray_tri",
84                 UNPACK3_EX(&, py_tri, ), &py_ray, &py_ray_off, &clip))
85         {
86                 return NULL;
87         }
88
89         if (((mathutils_array_parse(dir, 3, 3, py_ray, error_prefix) != -1) &&
90              (mathutils_array_parse(orig, 3, 3, py_ray_off, error_prefix) != -1)) == 0)
91         {
92                 return NULL;
93         }
94
95         for (i = 0; i < ARRAY_SIZE(tri); i++) {
96                 if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
97                         return NULL;
98                 }
99         }
100
101         normalize_v3(dir);
102
103         /* find vectors for two edges sharing v1 */
104         sub_v3_v3v3(e1, tri[1], tri[0]);
105         sub_v3_v3v3(e2, tri[2], tri[0]);
106
107         /* begin calculating determinant - also used to calculated U parameter */
108         cross_v3_v3v3(pvec, dir, e2);
109
110         /* if determinant is near zero, ray lies in plane of triangle */
111         det = dot_v3v3(e1, pvec);
112
113         if (det > -0.000001f && det < 0.000001f) {
114                 Py_RETURN_NONE;
115         }
116
117         inv_det = 1.0f / det;
118
119         /* calculate distance from v1 to ray origin */
120         sub_v3_v3v3(tvec, orig, tri[0]);
121
122         /* calculate U parameter and test bounds */
123         u = dot_v3v3(tvec, pvec) * inv_det;
124         if (clip && (u < 0.0f || u > 1.0f)) {
125                 Py_RETURN_NONE;
126         }
127
128         /* prepare to test the V parameter */
129         cross_v3_v3v3(qvec, tvec, e1);
130
131         /* calculate V parameter and test bounds */
132         v = dot_v3v3(dir, qvec) * inv_det;
133
134         if (clip && (v < 0.0f || u + v > 1.0f)) {
135                 Py_RETURN_NONE;
136         }
137
138         /* calculate t, ray intersects triangle */
139         t = dot_v3v3(e2, qvec) * inv_det;
140
141         /* ray hit behind */
142         if (t < 0.0f) {
143                 Py_RETURN_NONE;
144         }
145
146         mul_v3_fl(dir, t);
147         add_v3_v3v3(pvec, orig, dir);
148
149         return Vector_CreatePyObject(pvec, 3, Py_NEW, NULL);
150 }
151
152 /* Line-Line intersection using algorithm from mathworld.wolfram.com */
153
154 PyDoc_STRVAR(M_Geometry_intersect_line_line_doc,
155 ".. function:: intersect_line_line(v1, v2, v3, v4)\n"
156 "\n"
157 "   Returns a tuple with the points on each line respectively closest to the other.\n"
158 "\n"
159 "   :arg v1: First point of the first line\n"
160 "   :type v1: :class:`mathutils.Vector`\n"
161 "   :arg v2: Second point of the first line\n"
162 "   :type v2: :class:`mathutils.Vector`\n"
163 "   :arg v3: First point of the second line\n"
164 "   :type v3: :class:`mathutils.Vector`\n"
165 "   :arg v4: Second point of the second line\n"
166 "   :type v4: :class:`mathutils.Vector`\n"
167 "   :rtype: tuple of :class:`mathutils.Vector`'s\n"
168 );
169 static PyObject *M_Geometry_intersect_line_line(PyObject *UNUSED(self), PyObject *args)
170 {
171         const char *error_prefix = "intersect_line_line";
172         PyObject *tuple;
173         PyObject *py_lines[4];
174         float lines[4][3], i1[3], i2[3];
175         int len;
176         int result;
177
178         if (!PyArg_ParseTuple(
179                 args, "OOOO:intersect_line_line",
180                 UNPACK4_EX(&, py_lines, )))
181         {
182                 return NULL;
183         }
184
185         if ((((len = mathutils_array_parse(lines[0], 2, 3, py_lines[0], error_prefix)) != -1) &&
186              (mathutils_array_parse(lines[1], len, len, py_lines[1], error_prefix) != -1) &&
187              (mathutils_array_parse(lines[2], len, len, py_lines[2], error_prefix) != -1) &&
188              (mathutils_array_parse(lines[3], len, len, py_lines[3], error_prefix) != -1)) == 0)
189         {
190                 return NULL;
191         }
192
193         if (len == 2) {
194                 lines[0][2] = lines[1][2] = lines[2][2] = lines[3][2] = 0.0f;
195         }
196
197         result = isect_line_line_v3(UNPACK4(lines), i1, i2);
198         /* The return-code isnt exposed,
199          * this way we can check know how close the lines are. */
200         if (result == 1) {
201                 closest_to_line_v3(i2, i1, lines[2], lines[3]);
202         }
203
204         if (result == 0) {
205                 /* colinear */
206                 Py_RETURN_NONE;
207         }
208         else {
209                 tuple = PyTuple_New(2);
210                 PyTuple_SET_ITEM(tuple, 0, Vector_CreatePyObject(i1, len, Py_NEW, NULL));
211                 PyTuple_SET_ITEM(tuple, 1, Vector_CreatePyObject(i2, len, Py_NEW, NULL));
212                 return tuple;
213         }
214 }
215
216 /* Line-Line intersection using algorithm from mathworld.wolfram.com */
217
218 PyDoc_STRVAR(M_Geometry_intersect_sphere_sphere_2d_doc,
219 ".. function:: intersect_sphere_sphere_2d(p_a, radius_a, p_b, radius_b)\n"
220 "\n"
221 "   Returns 2 points on between intersecting circles.\n"
222 "\n"
223 "   :arg p_a: Center of the first circle\n"
224 "   :type p_a: :class:`mathutils.Vector`\n"
225 "   :arg radius_a: Radius of the first circle\n"
226 "   :type radius_a: float\n"
227 "   :arg p_b: Center of the second circle\n"
228 "   :type p_b: :class:`mathutils.Vector`\n"
229 "   :arg radius_b: Radius of the second circle\n"
230 "   :type radius_b: float\n"
231 "   :rtype: tuple of :class:`mathutils.Vector`'s or None when there is no intersection\n"
232 );
233 static PyObject *M_Geometry_intersect_sphere_sphere_2d(PyObject *UNUSED(self), PyObject *args)
234 {
235         const char *error_prefix = "intersect_sphere_sphere_2d";
236         PyObject *ret;
237         PyObject *py_v_a, *py_v_b;
238         float v_a[2], v_b[2];
239         float rad_a, rad_b;
240         float v_ab[2];
241         float dist;
242
243         if (!PyArg_ParseTuple(
244                 args, "OfOf:intersect_sphere_sphere_2d",
245                 &py_v_a, &rad_a,
246                 &py_v_b, &rad_b))
247         {
248                 return NULL;
249         }
250
251         if (((mathutils_array_parse(v_a, 2, 2, py_v_a, error_prefix) != -1) &&
252              (mathutils_array_parse(v_b, 2, 2, py_v_b, error_prefix) != -1)) == 0)
253         {
254                 return NULL;
255         }
256
257         ret = PyTuple_New(2);
258
259         sub_v2_v2v2(v_ab, v_b, v_a);
260         dist = len_v2(v_ab);
261
262         if (/* out of range */
263             (dist > rad_a + rad_b) ||
264             /* fully-contained in the other */
265             (dist < fabsf(rad_a - rad_b)) ||
266             /* co-incident */
267             (dist < FLT_EPSILON))
268         {
269                 /* out of range */
270                 PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None);
271                 PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None);
272         }
273         else {
274                 const float dist_delta = ((rad_a * rad_a) - (rad_b * rad_b) + (dist * dist)) / (2.0f * dist);
275                 const float h = powf(fabsf((rad_a * rad_a) - (dist_delta * dist_delta)), 0.5f);
276                 float i_cent[2];
277                 float i1[2], i2[2];
278
279                 i_cent[0] = v_a[0] + ((v_ab[0] * dist_delta) / dist);
280                 i_cent[1] = v_a[1] + ((v_ab[1] * dist_delta) / dist);
281
282                 i1[0] = i_cent[0] + h * v_ab[1] / dist;
283                 i1[1] = i_cent[1] - h * v_ab[0] / dist;
284
285                 i2[0] = i_cent[0] - h * v_ab[1] / dist;
286                 i2[1] = i_cent[1] + h * v_ab[0] / dist;
287
288                 PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(i1, 2, Py_NEW, NULL));
289                 PyTuple_SET_ITEM(ret, 1, Vector_CreatePyObject(i2, 2, Py_NEW, NULL));
290         }
291
292         return ret;
293 }
294
295 PyDoc_STRVAR(M_Geometry_normal_doc,
296 ".. function:: normal(v1, v2, v3, v4=None)\n"
297 "\n"
298 "   Returns the normal of the 3D tri or quad.\n"
299 "\n"
300 "   :arg v1: Point1\n"
301 "   :type v1: :class:`mathutils.Vector`\n"
302 "   :arg v2: Point2\n"
303 "   :type v2: :class:`mathutils.Vector`\n"
304 "   :arg v3: Point3\n"
305 "   :type v3: :class:`mathutils.Vector`\n"
306 "   :arg v4: Point4 (optional)\n"
307 "   :type v4: :class:`mathutils.Vector`\n"
308 "   :rtype: :class:`mathutils.Vector`\n"
309 );
310 static PyObject *M_Geometry_normal(PyObject *UNUSED(self), PyObject *args)
311 {
312         VectorObject *vec1, *vec2, *vec3, *vec4;
313         float n[3];
314
315         if (PyTuple_GET_SIZE(args) == 3) {
316                 if (!PyArg_ParseTuple(args, "O!O!O!:normal",
317                                       &vector_Type, &vec1,
318                                       &vector_Type, &vec2,
319                                       &vector_Type, &vec3))
320                 {
321                         return NULL;
322                 }
323
324                 if (vec1->size != vec2->size || vec1->size != vec3->size) {
325                         PyErr_SetString(PyExc_ValueError,
326                                         "vectors must be of the same size");
327                         return NULL;
328                 }
329                 if (vec1->size < 3) {
330                         PyErr_SetString(PyExc_ValueError,
331                                         "2D vectors unsupported");
332                         return NULL;
333                 }
334
335                 if (BaseMath_ReadCallback(vec1) == -1 ||
336                     BaseMath_ReadCallback(vec2) == -1 ||
337                     BaseMath_ReadCallback(vec3) == -1)
338                 {
339                         return NULL;
340                 }
341
342                 normal_tri_v3(n, vec1->vec, vec2->vec, vec3->vec);
343         }
344         else {
345                 if (!PyArg_ParseTuple(args, "O!O!O!O!:normal",
346                                       &vector_Type, &vec1,
347                                       &vector_Type, &vec2,
348                                       &vector_Type, &vec3,
349                                       &vector_Type, &vec4))
350                 {
351                         return NULL;
352                 }
353                 if (vec1->size != vec2->size || vec1->size != vec3->size || vec1->size != vec4->size) {
354                         PyErr_SetString(PyExc_ValueError,
355                                         "vectors must be of the same size");
356                         return NULL;
357                 }
358                 if (vec1->size < 3) {
359                         PyErr_SetString(PyExc_ValueError,
360                                         "2D vectors unsupported");
361                         return NULL;
362                 }
363
364                 if (BaseMath_ReadCallback(vec1) == -1 ||
365                     BaseMath_ReadCallback(vec2) == -1 ||
366                     BaseMath_ReadCallback(vec3) == -1 ||
367                     BaseMath_ReadCallback(vec4) == -1)
368                 {
369                         return NULL;
370                 }
371
372                 normal_quad_v3(n, vec1->vec, vec2->vec, vec3->vec, vec4->vec);
373         }
374
375         return Vector_CreatePyObject(n, 3, Py_NEW, NULL);
376 }
377
378 /* --------------------------------- AREA FUNCTIONS-------------------- */
379
380 PyDoc_STRVAR(M_Geometry_area_tri_doc,
381 ".. function:: area_tri(v1, v2, v3)\n"
382 "\n"
383 "   Returns the area size of the 2D or 3D triangle defined.\n"
384 "\n"
385 "   :arg v1: Point1\n"
386 "   :type v1: :class:`mathutils.Vector`\n"
387 "   :arg v2: Point2\n"
388 "   :type v2: :class:`mathutils.Vector`\n"
389 "   :arg v3: Point3\n"
390 "   :type v3: :class:`mathutils.Vector`\n"
391 "   :rtype: float\n"
392 );
393 static PyObject *M_Geometry_area_tri(PyObject *UNUSED(self), PyObject *args)
394 {
395         const char *error_prefix = "area_tri";
396         PyObject *py_tri[3];
397         float tri[3][3];
398         int len;
399
400         if (!PyArg_ParseTuple(
401                 args, "OOO:area_tri",
402                 UNPACK3_EX(&, py_tri, )))
403         {
404                 return NULL;
405         }
406
407         if ((((len = mathutils_array_parse(tri[0], 2, 3, py_tri[0], error_prefix)) != -1) &&
408              (mathutils_array_parse(tri[1], len, len, py_tri[1], error_prefix) != -1) &&
409              (mathutils_array_parse(tri[2], len, len, py_tri[2], error_prefix) != -1)) == 0)
410         {
411                 return NULL;
412         }
413
414         return PyFloat_FromDouble((len == 3 ? area_tri_v3 : area_tri_v2)(UNPACK3(tri)));
415 }
416
417 PyDoc_STRVAR(M_Geometry_volume_tetrahedron_doc,
418 ".. function:: volume_tetrahedron(v1, v2, v3, v4)\n"
419 "\n"
420 "   Return the volume formed by a tetrahedron (points can be in any order).\n"
421 "\n"
422 "   :arg v1: Point1\n"
423 "   :type v1: :class:`mathutils.Vector`\n"
424 "   :arg v2: Point2\n"
425 "   :type v2: :class:`mathutils.Vector`\n"
426 "   :arg v3: Point3\n"
427 "   :type v3: :class:`mathutils.Vector`\n"
428 "   :arg v4: Point4\n"
429 "   :type v4: :class:`mathutils.Vector`\n"
430 "   :rtype: float\n"
431 );
432 static PyObject *M_Geometry_volume_tetrahedron(PyObject *UNUSED(self), PyObject *args)
433 {
434         const char *error_prefix = "volume_tetrahedron";
435         PyObject *py_tet[4];
436         float tet[4][3];
437         int i;
438
439         if (!PyArg_ParseTuple(
440                 args, "OOOO:volume_tetrahedron",
441                 UNPACK4_EX(&, py_tet, )))
442         {
443                 return NULL;
444         }
445
446         for (i = 0; i < ARRAY_SIZE(tet); i++) {
447                 if (mathutils_array_parse(tet[i], 3, 3 | MU_ARRAY_SPILL, py_tet[i], error_prefix) == -1) {
448                         return NULL;
449                 }
450         }
451
452         return PyFloat_FromDouble(volume_tetrahedron_v3(UNPACK4(tet)));
453 }
454
455 PyDoc_STRVAR(M_Geometry_intersect_line_line_2d_doc,
456 ".. function:: intersect_line_line_2d(lineA_p1, lineA_p2, lineB_p1, lineB_p2)\n"
457 "\n"
458 "   Takes 2 lines (as 4 vectors) and returns a vector for their point of intersection or None.\n"
459 "\n"
460 "   :arg lineA_p1: First point of the first line\n"
461 "   :type lineA_p1: :class:`mathutils.Vector`\n"
462 "   :arg lineA_p2: Second point of the first line\n"
463 "   :type lineA_p2: :class:`mathutils.Vector`\n"
464 "   :arg lineB_p1: First point of the second line\n"
465 "   :type lineB_p1: :class:`mathutils.Vector`\n"
466 "   :arg lineB_p2: Second point of the second line\n"
467 "   :type lineB_p2: :class:`mathutils.Vector`\n"
468 "   :return: The point of intersection or None when not found\n"
469 "   :rtype: :class:`mathutils.Vector` or None\n"
470 );
471 static PyObject *M_Geometry_intersect_line_line_2d(PyObject *UNUSED(self), PyObject *args)
472 {
473         const char *error_prefix = "intersect_line_line_2d";
474         PyObject *py_lines[4];
475         float lines[4][2];
476         float vi[2];
477         int i;
478
479         if (!PyArg_ParseTuple(
480                 args, "OOOO:intersect_line_line_2d",
481                 UNPACK4_EX(&, py_lines, )))
482         {
483                 return NULL;
484         }
485
486         for (i = 0; i < ARRAY_SIZE(lines); i++) {
487                 if (mathutils_array_parse(lines[i], 2, 2 | MU_ARRAY_SPILL, py_lines[i], error_prefix) == -1) {
488                         return NULL;
489                 }
490         }
491
492         if (isect_seg_seg_v2_point(UNPACK4(lines), vi) == 1) {
493                 return Vector_CreatePyObject(vi, 2, Py_NEW, NULL);
494         }
495         else {
496                 Py_RETURN_NONE;
497         }
498 }
499
500
501 PyDoc_STRVAR(M_Geometry_intersect_line_plane_doc,
502 ".. function:: intersect_line_plane(line_a, line_b, plane_co, plane_no, no_flip=False)\n"
503 "\n"
504 "   Calculate the intersection between a line (as 2 vectors) and a plane.\n"
505 "   Returns a vector for the intersection or None.\n"
506 "\n"
507 "   :arg line_a: First point of the first line\n"
508 "   :type line_a: :class:`mathutils.Vector`\n"
509 "   :arg line_b: Second point of the first line\n"
510 "   :type line_b: :class:`mathutils.Vector`\n"
511 "   :arg plane_co: A point on the plane\n"
512 "   :type plane_co: :class:`mathutils.Vector`\n"
513 "   :arg plane_no: The direction the plane is facing\n"
514 "   :type plane_no: :class:`mathutils.Vector`\n"
515 "   :return: The point of intersection or None when not found\n"
516 "   :rtype: :class:`mathutils.Vector` or None\n"
517 );
518 static PyObject *M_Geometry_intersect_line_plane(PyObject *UNUSED(self), PyObject *args)
519 {
520         const char *error_prefix = "intersect_line_plane";
521         PyObject *py_line_a, *py_line_b, *py_plane_co, *py_plane_no;
522         float line_a[3], line_b[3], plane_co[3], plane_no[3];
523         float isect[3];
524         int no_flip = false;
525
526         if (!PyArg_ParseTuple(
527                 args, "OOOO|i:intersect_line_plane",
528                 &py_line_a, &py_line_b, &py_plane_co, &py_plane_no,
529                 &no_flip))
530         {
531                 return NULL;
532         }
533
534         if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
535              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
536              (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
537              (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
538         {
539                 return NULL;
540         }
541
542         /* TODO: implements no_flip */
543         if (isect_line_plane_v3(isect, line_a, line_b, plane_co, plane_no) == 1) {
544                 return Vector_CreatePyObject(isect, 3, Py_NEW, NULL);
545         }
546         else {
547                 Py_RETURN_NONE;
548         }
549 }
550
551 PyDoc_STRVAR(M_Geometry_intersect_plane_plane_doc,
552 ".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
553 "\n"
554 "   Return the intersection between two planes\n"
555 "\n"
556 "   :arg plane_a_co: Point on the first plane\n"
557 "   :type plane_a_co: :class:`mathutils.Vector`\n"
558 "   :arg plane_a_no: Normal of the first plane\n"
559 "   :type plane_a_no: :class:`mathutils.Vector`\n"
560 "   :arg plane_b_co: Point on the second plane\n"
561 "   :type plane_b_co: :class:`mathutils.Vector`\n"
562 "   :arg plane_b_no: Normal of the second plane\n"
563 "   :type plane_b_no: :class:`mathutils.Vector`\n"
564 "   :return: The line of the intersection represented as a point and a vector\n"
565 "   :rtype: tuple pair of :class:`mathutils.Vector` or None if the intersection can't be calculated\n"
566 );
567 static PyObject *M_Geometry_intersect_plane_plane(PyObject *UNUSED(self), PyObject *args)
568 {
569         const char *error_prefix = "intersect_plane_plane";
570         PyObject *ret, *ret_co, *ret_no;
571         PyObject *py_plane_a_co, *py_plane_a_no, *py_plane_b_co, *py_plane_b_no;
572         float plane_a_co[3], plane_a_no[3], plane_b_co[3], plane_b_no[3];
573
574         float isect_co[3];
575         float isect_no[3];
576
577         if (!PyArg_ParseTuple(
578                 args, "OOOO:intersect_plane_plane",
579                 &plane_a_co, &plane_a_no, &plane_b_co, &plane_b_no))
580         {
581                 return NULL;
582         }
583
584         if (((mathutils_array_parse(plane_a_co, 3, 3 | MU_ARRAY_SPILL, py_plane_a_co, error_prefix) != -1) &&
585              (mathutils_array_parse(plane_a_no, 3, 3 | MU_ARRAY_SPILL, py_plane_a_no, error_prefix) != -1) &&
586              (mathutils_array_parse(plane_b_co, 3, 3 | MU_ARRAY_SPILL, py_plane_b_co, error_prefix) != -1) &&
587              (mathutils_array_parse(plane_b_no, 3, 3 | MU_ARRAY_SPILL, py_plane_b_no, error_prefix) != -1)) == 0)
588         {
589                 return NULL;
590         }
591
592         if (isect_plane_plane_v3(isect_co, isect_no,
593                                  plane_a_co, plane_a_no,
594                                  plane_b_co, plane_b_no))
595         {
596                 normalize_v3(isect_no);
597
598                 ret_co = Vector_CreatePyObject(isect_co, 3, Py_NEW, NULL);
599                 ret_no = Vector_CreatePyObject(isect_no, 3, Py_NEW, NULL);
600         }
601         else {
602                 ret_co = Py_None;
603                 ret_no = Py_None;
604
605                 Py_INCREF(ret_co);
606                 Py_INCREF(ret_no);
607         }
608
609         ret = PyTuple_New(2);
610         PyTuple_SET_ITEM(ret, 0, ret_co);
611         PyTuple_SET_ITEM(ret, 1, ret_no);
612         return ret;
613 }
614
615 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_doc,
616 ".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
617 "\n"
618 "   Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
619 "   returns the intersection\n"
620 "\n"
621 "   :arg line_a: First point of the line\n"
622 "   :type line_a: :class:`mathutils.Vector`\n"
623 "   :arg line_b: Second point of the line\n"
624 "   :type line_b: :class:`mathutils.Vector`\n"
625 "   :arg sphere_co: The center of the sphere\n"
626 "   :type sphere_co: :class:`mathutils.Vector`\n"
627 "   :arg sphere_radius: Radius of the sphere\n"
628 "   :type sphere_radius: sphere_radius\n"
629 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
630 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
631 );
632 static PyObject *M_Geometry_intersect_line_sphere(PyObject *UNUSED(self), PyObject *args)
633 {
634         const char *error_prefix = "intersect_line_sphere";
635         PyObject *py_line_a, *py_line_b, *py_sphere_co;
636         float line_a[3], line_b[3], sphere_co[3];
637         float sphere_radius;
638         int clip = true;
639
640         float isect_a[3];
641         float isect_b[3];
642
643         if (!PyArg_ParseTuple(
644                 args, "OOOf|i:intersect_line_sphere",
645                 &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius, &clip))
646         {
647                 return NULL;
648         }
649
650         if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
651              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
652              (mathutils_array_parse(sphere_co, 3, 3 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
653         {
654                 return NULL;
655         }
656         else {
657                 bool use_a = true;
658                 bool use_b = true;
659                 float lambda;
660
661                 PyObject *ret = PyTuple_New(2);
662
663                 switch (isect_line_sphere_v3(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
664                         case 1:
665                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
666                                 use_b = false;
667                                 break;
668                         case 2:
669                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
670                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
671                                 break;
672                         default:
673                                 use_a = false;
674                                 use_b = false;
675                                 break;
676                 }
677
678                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 3, Py_NEW, NULL)); }
679                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
680
681                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 3, Py_NEW, NULL)); }
682                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
683
684                 return ret;
685         }
686 }
687
688 /* keep in sync with M_Geometry_intersect_line_sphere */
689 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_2d_doc,
690 ".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
691 "\n"
692 "   Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
693 "   returns the intersection\n"
694 "\n"
695 "   :arg line_a: First point of the line\n"
696 "   :type line_a: :class:`mathutils.Vector`\n"
697 "   :arg line_b: Second point of the line\n"
698 "   :type line_b: :class:`mathutils.Vector`\n"
699 "   :arg sphere_co: The center of the sphere\n"
700 "   :type sphere_co: :class:`mathutils.Vector`\n"
701 "   :arg sphere_radius: Radius of the sphere\n"
702 "   :type sphere_radius: sphere_radius\n"
703 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
704 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
705 );
706 static PyObject *M_Geometry_intersect_line_sphere_2d(PyObject *UNUSED(self), PyObject *args)
707 {
708         const char *error_prefix = "intersect_line_sphere_2d";
709         PyObject *py_line_a, *py_line_b, *py_sphere_co;
710         float line_a[2], line_b[2], sphere_co[2];
711         float sphere_radius;
712         int clip = true;
713
714         float isect_a[2];
715         float isect_b[2];
716
717         if (!PyArg_ParseTuple(
718                 args, "OOOf|i:intersect_line_sphere_2d",
719                 &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius, &clip))
720         {
721                 return NULL;
722         }
723
724         if (((mathutils_array_parse(line_a, 2, 2 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
725              (mathutils_array_parse(line_b, 2, 2 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
726              (mathutils_array_parse(sphere_co, 2, 2 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
727         {
728                 return NULL;
729         }
730         else {
731                 bool use_a = true;
732                 bool use_b = true;
733                 float lambda;
734
735                 PyObject *ret = PyTuple_New(2);
736
737                 switch (isect_line_sphere_v2(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
738                         case 1:
739                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
740                                 use_b = false;
741                                 break;
742                         case 2:
743                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
744                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
745                                 break;
746                         default:
747                                 use_a = false;
748                                 use_b = false;
749                                 break;
750                 }
751
752                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 2, Py_NEW, NULL)); }
753                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
754
755                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 2, Py_NEW, NULL)); }
756                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
757
758                 return ret;
759         }
760 }
761
762 PyDoc_STRVAR(M_Geometry_intersect_point_line_doc,
763 ".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
764 "\n"
765 "   Takes a point and a line and returns a tuple with the closest point on the line and its distance from the first point of the line as a percentage of the length of the line.\n"
766 "\n"
767 "   :arg pt: Point\n"
768 "   :type pt: :class:`mathutils.Vector`\n"
769 "   :arg line_p1: First point of the line\n"
770 "   :type line_p1: :class:`mathutils.Vector`\n"
771 "   :arg line_p1: Second point of the line\n"
772 "   :type line_p1: :class:`mathutils.Vector`\n"
773 "   :rtype: (:class:`mathutils.Vector`, float)\n"
774 );
775 static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObject *args)
776 {
777         const char *error_prefix = "intersect_point_line";
778         PyObject *py_pt, *py_line_a, *py_line_b;
779         float pt[3], pt_out[3], line_a[3], line_b[3];
780         float lambda;
781         PyObject *ret;
782         int size = 2;
783         
784         if (!PyArg_ParseTuple(
785                 args, "OOO:intersect_point_line",
786                 &py_pt, &py_line_a, &py_line_b))
787         {
788                 return NULL;
789         }
790
791         /* accept 2d verts */
792         if (((mathutils_array_parse(pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix) != -1) &&
793              (mathutils_array_parse(line_a, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_a, error_prefix) != -1) &&
794              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_b, error_prefix) != -1)) == 0)
795         {
796                 return NULL;
797         }
798
799         /* do the calculation */
800         lambda = closest_to_line_v3(pt_out, pt, line_a, line_b);
801         
802         ret = PyTuple_New(2);
803         PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(pt_out, size, Py_NEW, NULL));
804         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(lambda));
805         return ret;
806 }
807
808 PyDoc_STRVAR(M_Geometry_intersect_point_tri_doc,
809 ".. function:: intersect_point_tri(pt, tri_p1, tri_p2, tri_p3)\n"
810 "\n"
811 "   Takes 4 vectors: one is the point and the next 3 define the triangle.\n"
812 "\n"
813 "   :arg pt: Point\n"
814 "   :type pt: :class:`mathutils.Vector`\n"
815 "   :arg tri_p1: First point of the triangle\n"
816 "   :type tri_p1: :class:`mathutils.Vector`\n"
817 "   :arg tri_p2: Second point of the triangle\n"
818 "   :type tri_p2: :class:`mathutils.Vector`\n"
819 "   :arg tri_p3: Third point of the triangle\n"
820 "   :type tri_p3: :class:`mathutils.Vector`\n"
821 "   :return: Point on the triangles plane or None if its outside the triangle\n"
822 "   :rtype: :class:`mathutils.Vector` or None\n"
823 );
824 static PyObject *M_Geometry_intersect_point_tri(PyObject *UNUSED(self), PyObject *args)
825 {
826         const char *error_prefix = "intersect_point_tri";
827         PyObject *py_pt, *py_tri[3];
828         float pt[3], tri[3][3];
829         float vi[3];
830         int i;
831
832         if (!PyArg_ParseTuple(
833                 args, "OOOO:intersect_point_tri",
834                 &py_pt, UNPACK3_EX(&, py_tri,)))
835         {
836                 return NULL;
837         }
838
839         if (mathutils_array_parse(pt, 3, 3 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
840                 return NULL;
841         }
842         for (i = 0; i < ARRAY_SIZE(tri); i++) {
843                 if (mathutils_array_parse(tri[i], 3, 3 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
844                         return NULL;
845                 }
846         }
847
848         if (isect_point_tri_v3(pt, UNPACK3(tri), vi)) {
849                 return Vector_CreatePyObject(vi, 3, Py_NEW, NULL);
850         }
851         else {
852                 Py_RETURN_NONE;
853         }
854 }
855
856 PyDoc_STRVAR(M_Geometry_intersect_point_tri_2d_doc,
857 ".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
858 "\n"
859 "   Takes 4 vectors (using only the x and y coordinates): one is the point and the next 3 define the triangle. Returns 1 if the point is within the triangle, otherwise 0.\n"
860 "\n"
861 "   :arg pt: Point\n"
862 "   :type pt: :class:`mathutils.Vector`\n"
863 "   :arg tri_p1: First point of the triangle\n"
864 "   :type tri_p1: :class:`mathutils.Vector`\n"
865 "   :arg tri_p2: Second point of the triangle\n"
866 "   :type tri_p2: :class:`mathutils.Vector`\n"
867 "   :arg tri_p3: Third point of the triangle\n"
868 "   :type tri_p3: :class:`mathutils.Vector`\n"
869 "   :rtype: int\n"
870 );
871 static PyObject *M_Geometry_intersect_point_tri_2d(PyObject *UNUSED(self), PyObject *args)
872 {
873         const char *error_prefix = "intersect_point_tri_2d";
874         PyObject *py_pt, *py_tri[3];
875         float pt[2], tri[3][2];
876         int i;
877
878         if (!PyArg_ParseTuple(
879                 args, "OOOO:intersect_point_tri_2d",
880                 &py_pt, UNPACK3_EX(&, py_tri,)))
881         {
882                 return NULL;
883         }
884
885         if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
886                 return NULL;
887         }
888         for (i = 0; i < ARRAY_SIZE(tri); i++) {
889                 if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
890                         return NULL;
891                 }
892         }
893
894         return PyLong_FromLong(isect_point_tri_v2(pt, UNPACK3(tri)));
895 }
896
897 PyDoc_STRVAR(M_Geometry_intersect_point_quad_2d_doc,
898 ".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
899 "\n"
900 "   Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad, \n"
901 "   only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0.\n"
902 "   Works only with convex quads without singular edges."
903 "\n"
904 "   :arg pt: Point\n"
905 "   :type pt: :class:`mathutils.Vector`\n"
906 "   :arg quad_p1: First point of the quad\n"
907 "   :type quad_p1: :class:`mathutils.Vector`\n"
908 "   :arg quad_p2: Second point of the quad\n"
909 "   :type quad_p2: :class:`mathutils.Vector`\n"
910 "   :arg quad_p3: Third point of the quad\n"
911 "   :type quad_p3: :class:`mathutils.Vector`\n"
912 "   :arg quad_p4: Forth point of the quad\n"
913 "   :type quad_p4: :class:`mathutils.Vector`\n"
914 "   :rtype: int\n"
915 );
916 static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyObject *args)
917 {
918         const char *error_prefix = "intersect_point_quad_2d";
919         PyObject *py_pt, *py_quad[4];
920         float pt[2], quad[4][2];
921         int i;
922         
923         if (!PyArg_ParseTuple(
924                 args, "OOOOO:intersect_point_quad_2d",
925                 &py_pt, UNPACK4_EX(&, py_quad,)))
926         {
927                 return NULL;
928         }
929
930         if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
931                 return NULL;
932         }
933         for (i = 0; i < ARRAY_SIZE(quad); i++) {
934                 if (mathutils_array_parse(quad[i], 2, 2 | MU_ARRAY_SPILL, py_quad[i], error_prefix) == -1) {
935                         return NULL;
936                 }
937         }
938
939         return PyLong_FromLong(isect_point_quad_v2(pt, UNPACK4(quad)));
940 }
941
942 PyDoc_STRVAR(M_Geometry_distance_point_to_plane_doc,
943 ".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
944 "\n"
945 "   Returns the signed distance between a point and a plane "
946 "   (negative when below the normal).\n"
947 "\n"
948 "   :arg pt: Point\n"
949 "   :type pt: :class:`mathutils.Vector`\n"
950 "   :arg plane_co: A point on the plane\n"
951 "   :type plane_co: :class:`mathutils.Vector`\n"
952 "   :arg plane_no: The direction the plane is facing\n"
953 "   :type plane_no: :class:`mathutils.Vector`\n"
954 "   :rtype: float\n"
955 );
956 static PyObject *M_Geometry_distance_point_to_plane(PyObject *UNUSED(self), PyObject *args)
957 {
958         const char *error_prefix = "distance_point_to_plane";
959         PyObject *py_pt, *py_plane_co, *py_plane_no;
960         float pt[3], plane_co[3], plane_no[3];
961         float plane[4];
962
963         if (!PyArg_ParseTuple(
964                 args, "OOO:distance_point_to_plane",
965                 &py_pt, &py_plane_co, &py_plane_no))
966         {
967                 return NULL;
968         }
969
970         if (((mathutils_array_parse(pt,       3, 3 | MU_ARRAY_SPILL, py_pt,       error_prefix) != -1) &&
971              (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
972              (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
973         {
974                 return NULL;
975         }
976
977         plane_from_point_normal_v3(plane, plane_co, plane_no);
978         return PyFloat_FromDouble(dist_signed_to_plane_v3(pt, plane));
979 }
980
981 PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
982 ".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
983 "\n"
984 "   Return a transformed point, the transformation is defined by 2 triangles.\n"
985 "\n"
986 "   :arg point: The point to transform.\n"
987 "   :type point: :class:`mathutils.Vector`\n"
988 "   :arg tri_a1: source triangle vertex.\n"
989 "   :type tri_a1: :class:`mathutils.Vector`\n"
990 "   :arg tri_a2: source triangle vertex.\n"
991 "   :type tri_a2: :class:`mathutils.Vector`\n"
992 "   :arg tri_a3: source triangle vertex.\n"
993 "   :type tri_a3: :class:`mathutils.Vector`\n"
994 "   :arg tri_a1: target triangle vertex.\n"
995 "   :type tri_a1: :class:`mathutils.Vector`\n"
996 "   :arg tri_a2: target triangle vertex.\n"
997 "   :type tri_a2: :class:`mathutils.Vector`\n"
998 "   :arg tri_a3: target triangle vertex.\n"
999 "   :type tri_a3: :class:`mathutils.Vector`\n"
1000 "   :return: The transformed point\n"
1001 "   :rtype: :class:`mathutils.Vector`'s\n"
1002 );
1003 static PyObject *M_Geometry_barycentric_transform(PyObject *UNUSED(self), PyObject *args)
1004 {
1005         const char *error_prefix = "barycentric_transform";
1006         PyObject *py_pt_src, *py_tri_src[3], *py_tri_dst[3];
1007         float pt_src[3], pt_dst[3], tri_src[3][3], tri_dst[3][3];
1008         int i;
1009
1010         if (!PyArg_ParseTuple(
1011                 args, "OOOOOOO:barycentric_transform",
1012                 &py_pt_src,
1013                 UNPACK3_EX(&, py_tri_src, ),
1014                 UNPACK3_EX(&, py_tri_dst, )))
1015         {
1016                 return NULL;
1017         }
1018
1019         if (mathutils_array_parse(pt_src, 2, 2 | MU_ARRAY_SPILL, py_pt_src, error_prefix) == -1) {
1020                 return NULL;
1021         }
1022         for (i = 0; i < ARRAY_SIZE(tri_src); i++) {
1023                 if (((mathutils_array_parse(tri_src[i], 3, 3 | MU_ARRAY_SPILL, py_tri_src[i], error_prefix) != -1) &&
1024                      (mathutils_array_parse(tri_dst[i], 3, 3 | MU_ARRAY_SPILL, py_tri_dst[i], error_prefix) != -1)) == 0)
1025                 {
1026                         return NULL;
1027                 }
1028         }
1029
1030         transform_point_by_tri_v3(
1031                 pt_dst, pt_src,
1032                 UNPACK3(tri_dst),
1033                 UNPACK3(tri_src));
1034
1035         return Vector_CreatePyObject(pt_dst, 3, Py_NEW, NULL);
1036 }
1037
1038 PyDoc_STRVAR(M_Geometry_points_in_planes_doc,
1039 ".. function:: points_in_planes(planes)\n"
1040 "\n"
1041 "   Returns a list of points inside all planes given and a list of index values for the planes used.\n"
1042 "\n"
1043 "   :arg planes: List of planes (4D vectors).\n"
1044 "   :type planes: list of :class:`mathutils.Vector`\n"
1045 "   :return: two lists, once containing the vertices inside the planes, another containing the plane indices used\n"
1046 "   :rtype: pair of lists\n"
1047 );
1048 /* note: this function could be optimized by some spatial structure */
1049 static PyObject *M_Geometry_points_in_planes(PyObject *UNUSED(self), PyObject *args)
1050 {
1051         PyObject *py_planes;
1052         float (*planes)[4];
1053         unsigned int planes_len;
1054
1055         if (!PyArg_ParseTuple(
1056                 args, "O:points_in_planes",
1057                 &py_planes))
1058         {
1059                 return NULL;
1060         }
1061
1062         if ((planes_len = mathutils_array_parse_alloc_v((float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
1063                 return NULL;
1064         }
1065         else {
1066                 /* note, this could be refactored into plain C easy - py bits are noted */
1067                 const float eps = 0.0001f;
1068                 const unsigned int len = (unsigned int)planes_len;
1069                 unsigned int i, j, k, l;
1070
1071                 float n1n2[3], n2n3[3], n3n1[3];
1072                 float potentialVertex[3];
1073                 char *planes_used = PyMem_Malloc(sizeof(char) * len);
1074
1075                 /* python */
1076                 PyObject *py_verts = PyList_New(0);
1077                 PyObject *py_plane_index = PyList_New(0);
1078
1079                 memset(planes_used, 0, sizeof(char) * len);
1080
1081                 for (i = 0; i < len; i++) {
1082                         const float *N1 = planes[i];
1083                         for (j = i + 1; j < len; j++) {
1084                                 const float *N2 = planes[j];
1085                                 cross_v3_v3v3(n1n2, N1, N2);
1086                                 if (len_squared_v3(n1n2) > eps) {
1087                                         for (k = j + 1; k < len; k++) {
1088                                                 const float *N3 = planes[k];
1089                                                 cross_v3_v3v3(n2n3, N2, N3);
1090                                                 if (len_squared_v3(n2n3) > eps) {
1091                                                         cross_v3_v3v3(n3n1, N3, N1);
1092                                                         if (len_squared_v3(n3n1) > eps) {
1093                                                                 const float quotient = dot_v3v3(N1, n2n3);
1094                                                                 if (fabsf(quotient) > eps) {
1095                                                                         /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
1096                                                                         const float quotient_ninv = -1.0f / quotient;
1097                                                                         potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) + (n1n2[0] * N3[3])) * quotient_ninv;
1098                                                                         potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) + (n1n2[1] * N3[3])) * quotient_ninv;
1099                                                                         potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) + (n1n2[2] * N3[3])) * quotient_ninv;
1100                                                                         for (l = 0; l < len; l++) {
1101                                                                                 const float *NP = planes[l];
1102                                                                                 if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
1103                                                                                         break;
1104                                                                                 }
1105                                                                         }
1106
1107                                                                         if (l == len) { /* ok */
1108                                                                                 /* python */
1109                                                                                 PyObject *item = Vector_CreatePyObject(potentialVertex, 3, Py_NEW, NULL);
1110                                                                                 PyList_Append(py_verts, item);
1111                                                                                 Py_DECREF(item);
1112
1113                                                                                 planes_used[i] = planes_used[j] = planes_used[k] = true;
1114                                                                         }
1115                                                                 }
1116                                                         }
1117                                                 }
1118                                         }
1119                                 }
1120                         }
1121                 }
1122
1123                 PyMem_Free(planes);
1124
1125                 /* now make a list of used planes */
1126                 for (i = 0; i < len; i++) {
1127                         if (planes_used[i]) {
1128                                 PyObject *item = PyLong_FromLong(i);
1129                                 PyList_Append(py_plane_index, item);
1130                                 Py_DECREF(item);
1131                         }
1132                 }
1133                 PyMem_Free(planes_used);
1134
1135                 {
1136                         PyObject *ret = PyTuple_New(2);
1137                         PyTuple_SET_ITEM(ret, 0, py_verts);
1138                         PyTuple_SET_ITEM(ret, 1, py_plane_index);
1139                         return ret;
1140                 }
1141         }
1142 }
1143
1144 #ifndef MATH_STANDALONE
1145
1146 PyDoc_STRVAR(M_Geometry_interpolate_bezier_doc,
1147 ".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
1148 "\n"
1149 "   Interpolate a bezier spline segment.\n"
1150 "\n"
1151 "   :arg knot1: First bezier spline point.\n"
1152 "   :type knot1: :class:`mathutils.Vector`\n"
1153 "   :arg handle1: First bezier spline handle.\n"
1154 "   :type handle1: :class:`mathutils.Vector`\n"
1155 "   :arg handle2: Second bezier spline handle.\n"
1156 "   :type handle2: :class:`mathutils.Vector`\n"
1157 "   :arg knot2: Second bezier spline point.\n"
1158 "   :type knot2: :class:`mathutils.Vector`\n"
1159 "   :arg resolution: Number of points to return.\n"
1160 "   :type resolution: int\n"
1161 "   :return: The interpolated points\n"
1162 "   :rtype: list of :class:`mathutils.Vector`'s\n"
1163 );
1164 static PyObject *M_Geometry_interpolate_bezier(PyObject *UNUSED(self), PyObject *args)
1165 {
1166         const char *error_prefix = "interpolate_bezier";
1167         PyObject *py_data[4];
1168         float data[4][4] = {{0.0f}};
1169         int resolu;
1170         int dims = 0;
1171         int i;
1172         float *coord_array, *fp;
1173         PyObject *list;
1174
1175         if (!PyArg_ParseTuple(
1176                 args, "OOOOi:interpolate_bezier",
1177                 UNPACK4_EX(&, py_data, ), &resolu))
1178         {
1179                 return NULL;
1180         }
1181
1182         for (i = 0; i < 4; i++) {
1183                 int dims_tmp;
1184                 if ((((dims_tmp = mathutils_array_parse(data[i], 2, 2 | MU_ARRAY_SPILL, py_data[i], error_prefix)) == -1))) {
1185                         return NULL;
1186                 }
1187                 dims = max_ii(dims, dims_tmp);
1188         }
1189
1190         if (resolu <= 1) {
1191                 PyErr_SetString(PyExc_ValueError,
1192                                 "resolution must be 2 or over");
1193                 return NULL;
1194         }
1195
1196         coord_array = MEM_callocN(dims * (resolu) * sizeof(float), error_prefix);
1197         for (i = 0; i < dims; i++) {
1198                 BKE_curve_forward_diff_bezier(UNPACK4_EX(, data, [i]), coord_array + i, resolu - 1, sizeof(float) * dims);
1199         }
1200
1201         list = PyList_New(resolu);
1202         fp = coord_array;
1203         for (i = 0; i < resolu; i++, fp = fp + dims) {
1204                 PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, Py_NEW, NULL));
1205         }
1206         MEM_freeN(coord_array);
1207         return list;
1208 }
1209
1210
1211 PyDoc_STRVAR(M_Geometry_tessellate_polygon_doc,
1212 ".. function:: tessellate_polygon(veclist_list)\n"
1213 "\n"
1214 "   Takes a list of polylines (each point a vector) and returns the point indices for a polyline filled with triangles.\n"
1215 "\n"
1216 "   :arg veclist_list: list of polylines\n"
1217 "   :rtype: list\n"
1218 );
1219 /* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
1220 static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject *polyLineSeq)
1221 {
1222         PyObject *tri_list; /*return this list of tri's */
1223         PyObject *polyLine, *polyVec;
1224         int i, len_polylines, len_polypoints, ls_error = 0;
1225
1226         /* display listbase */
1227         ListBase dispbase = {NULL, NULL};
1228         DispList *dl;
1229         float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
1230         int index, *dl_face, totpoints = 0;
1231
1232         if (!PySequence_Check(polyLineSeq)) {
1233                 PyErr_SetString(PyExc_TypeError,
1234                                 "expected a sequence of poly lines");
1235                 return NULL;
1236         }
1237
1238         len_polylines = PySequence_Size(polyLineSeq);
1239
1240         for (i = 0; i < len_polylines; i++) {
1241                 polyLine = PySequence_GetItem(polyLineSeq, i);
1242                 if (!PySequence_Check(polyLine)) {
1243                         BKE_displist_free(&dispbase);
1244                         Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
1245                         PyErr_SetString(PyExc_TypeError,
1246                                         "One or more of the polylines is not a sequence of mathutils.Vector's");
1247                         return NULL;
1248                 }
1249
1250                 len_polypoints = PySequence_Size(polyLine);
1251                 if (len_polypoints > 0) { /* don't bother adding edges as polylines */
1252 #if 0
1253                         if (EXPP_check_sequence_consistency(polyLine, &vector_Type) != 1) {
1254                                 freedisplist(&dispbase);
1255                                 Py_DECREF(polyLine);
1256                                 PyErr_SetString(PyExc_TypeError,
1257                                                 "A point in one of the polylines is not a mathutils.Vector type");
1258                                 return NULL;
1259                         }
1260 #endif
1261                         dl = MEM_callocN(sizeof(DispList), "poly disp");
1262                         BLI_addtail(&dispbase, dl);
1263                         dl->type = DL_INDEX3;
1264                         dl->nr = len_polypoints;
1265                         dl->type = DL_POLY;
1266                         dl->parts = 1; /* no faces, 1 edge loop */
1267                         dl->col = 0; /* no material */
1268                         dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
1269                         dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
1270
1271                         for (index = 0; index < len_polypoints; index++, fp += 3) {
1272                                 polyVec = PySequence_GetItem(polyLine, index);
1273                                 if (VectorObject_Check(polyVec)) {
1274
1275                                         if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1)
1276                                                 ls_error = 1;
1277
1278                                         fp[0] = ((VectorObject *)polyVec)->vec[0];
1279                                         fp[1] = ((VectorObject *)polyVec)->vec[1];
1280                                         if (((VectorObject *)polyVec)->size > 2)
1281                                                 fp[2] = ((VectorObject *)polyVec)->vec[2];
1282                                         else
1283                                                 fp[2] = 0.0f;  /* if its a 2d vector then set the z to be zero */
1284                                 }
1285                                 else {
1286                                         ls_error = 1;
1287                                 }
1288
1289                                 totpoints++;
1290                                 Py_DECREF(polyVec);
1291                         }
1292                 }
1293                 Py_DECREF(polyLine);
1294         }
1295
1296         if (ls_error) {
1297                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1298                 PyErr_SetString(PyExc_TypeError,
1299                                 "A point in one of the polylines "
1300                                 "is not a mathutils.Vector type");
1301                 return NULL;
1302         }
1303         else if (totpoints) {
1304                 /* now make the list to return */
1305                 /* TODO, add normal arg */
1306                 BKE_displist_fill(&dispbase, &dispbase, NULL, false);
1307
1308                 /* The faces are stored in a new DisplayList
1309                  * thats added to the head of the listbase */
1310                 dl = dispbase.first;
1311
1312                 tri_list = PyList_New(dl->parts);
1313                 if (!tri_list) {
1314                         BKE_displist_free(&dispbase);
1315                         PyErr_SetString(PyExc_RuntimeError,
1316                                         "failed to make a new list");
1317                         return NULL;
1318                 }
1319
1320                 index = 0;
1321                 dl_face = dl->index;
1322                 while (index < dl->parts) {
1323                         PyList_SET_ITEM(tri_list, index, Py_BuildValue("iii", dl_face[0], dl_face[1], dl_face[2]));
1324                         dl_face += 3;
1325                         index++;
1326                 }
1327                 BKE_displist_free(&dispbase);
1328         }
1329         else {
1330                 /* no points, do this so scripts don't barf */
1331                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1332                 tri_list = PyList_New(0);
1333         }
1334
1335         return tri_list;
1336 }
1337
1338
1339 static int boxPack_FromPyObject(PyObject *value, BoxPack **boxarray)
1340 {
1341         Py_ssize_t len, i;
1342         PyObject *list_item, *item_1, *item_2;
1343         BoxPack *box;
1344
1345
1346         /* Error checking must already be done */
1347         if (!PyList_Check(value)) {
1348                 PyErr_SetString(PyExc_TypeError,
1349                                 "can only back a list of [x, y, w, h]");
1350                 return -1;
1351         }
1352
1353         len = PyList_GET_SIZE(value);
1354
1355         *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
1356
1357
1358         for (i = 0; i < len; i++) {
1359                 list_item = PyList_GET_ITEM(value, i);
1360                 if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
1361                         MEM_freeN(*boxarray);
1362                         PyErr_SetString(PyExc_TypeError,
1363                                         "can only pack a list of [x, y, w, h]");
1364                         return -1;
1365                 }
1366
1367                 box = (*boxarray) + i;
1368
1369                 item_1 = PyList_GET_ITEM(list_item, 2);
1370                 item_2 = PyList_GET_ITEM(list_item, 3);
1371
1372                 box->w =  (float)PyFloat_AsDouble(item_1);
1373                 box->h =  (float)PyFloat_AsDouble(item_2);
1374                 box->index = i;
1375
1376                 /* accounts for error case too and overwrites with own error */
1377                 if (box->w < 0.0f || box->h < 0.0f) {
1378                         MEM_freeN(*boxarray);
1379                         PyErr_SetString(PyExc_TypeError,
1380                                         "error parsing width and height values from list: "
1381                                         "[x, y, w, h], not numbers or below zero");
1382                         return -1;
1383                 }
1384
1385                 /* verts will be added later */
1386         }
1387         return 0;
1388 }
1389
1390 static void boxPack_ToPyObject(PyObject *value, BoxPack **boxarray)
1391 {
1392         Py_ssize_t len, i;
1393         PyObject *list_item;
1394         BoxPack *box;
1395
1396         len = PyList_GET_SIZE(value);
1397
1398         for (i = 0; i < len; i++) {
1399                 box = (*boxarray) + i;
1400                 list_item = PyList_GET_ITEM(value, box->index);
1401                 PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
1402                 PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
1403         }
1404         MEM_freeN(*boxarray);
1405 }
1406
1407 PyDoc_STRVAR(M_Geometry_box_pack_2d_doc,
1408 ".. function:: box_pack_2d(boxes)\n"
1409 "\n"
1410 "   Returns the normal of the 3D tri or quad.\n"
1411 "\n"
1412 "   :arg boxes: list of boxes, each box is a list where the first 4 items are [x, y, width, height, ...] other items are ignored.\n"
1413 "   :type boxes: list\n"
1414 "   :return: the width and height of the packed bounding box\n"
1415 "   :rtype: tuple, pair of floats\n"
1416 );
1417 static PyObject *M_Geometry_box_pack_2d(PyObject *UNUSED(self), PyObject *boxlist)
1418 {
1419         float tot_width = 0.0f, tot_height = 0.0f;
1420         Py_ssize_t len;
1421
1422         PyObject *ret;
1423
1424         if (!PyList_Check(boxlist)) {
1425                 PyErr_SetString(PyExc_TypeError,
1426                                 "expected a list of boxes [[x, y, w, h], ... ]");
1427                 return NULL;
1428         }
1429
1430         len = PyList_GET_SIZE(boxlist);
1431         if (len) {
1432                 BoxPack *boxarray = NULL;
1433                 if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
1434                         return NULL; /* exception set */
1435                 }
1436
1437                 /* Non Python function */
1438                 BLI_box_pack_2d(boxarray, len, &tot_width, &tot_height);
1439
1440                 boxPack_ToPyObject(boxlist, &boxarray);
1441         }
1442
1443         ret = PyTuple_New(2);
1444         PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(tot_width));
1445         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(tot_height));
1446         return ret;
1447 }
1448
1449 PyDoc_STRVAR(M_Geometry_box_fit_2d_doc,
1450 ".. function:: box_fit_2d(points)\n"
1451 "\n"
1452 "   Returns an angle that best fits the points to an axis aligned rectangle\n"
1453 "\n"
1454 "   :arg points: list of 2d points.\n"
1455 "   :type points: list\n"
1456 "   :return: angle\n"
1457 "   :rtype: float\n"
1458 );
1459 static PyObject *M_Geometry_box_fit_2d(PyObject *UNUSED(self), PyObject *pointlist)
1460 {
1461         float (*points)[2];
1462         Py_ssize_t len;
1463
1464         float angle = 0.0f;
1465
1466         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "box_fit_2d");
1467         if (len == -1) {
1468                 return NULL;
1469         }
1470
1471         if (len) {
1472                 /* Non Python function */
1473                 angle = BLI_convexhull_aabb_fit_points_2d((const float (*)[2])points, len);
1474
1475                 PyMem_Free(points);
1476         }
1477
1478
1479         return PyFloat_FromDouble(angle);
1480 }
1481
1482 PyDoc_STRVAR(M_Geometry_convex_hull_2d_doc,
1483 ".. function:: convex_hull_2d(points)\n"
1484 "\n"
1485 "   Returns a list of indices into the list given\n"
1486 "\n"
1487 "   :arg points: list of 2d points.\n"
1488 "   :type points: list\n"
1489 "   :return: a list of indices\n"
1490 "   :rtype: list of ints\n"
1491 );
1492 static PyObject *M_Geometry_convex_hull_2d(PyObject *UNUSED(self), PyObject *pointlist)
1493 {
1494         float (*points)[2];
1495         Py_ssize_t len;
1496
1497         PyObject *ret;
1498
1499         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "convex_hull_2d");
1500         if (len == -1) {
1501                 return NULL;
1502         }
1503
1504         if (len) {
1505                 int *index_map;
1506                 Py_ssize_t len_ret, i;
1507
1508                 index_map  = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
1509
1510                 /* Non Python function */
1511                 len_ret = BLI_convexhull_2d((const float (*)[2])points, len, index_map);
1512
1513                 ret = PyList_New(len_ret);
1514                 for (i = 0; i < len_ret; i++) {
1515                         PyList_SET_ITEM(ret, i, PyLong_FromLong(index_map[i]));
1516                 }
1517
1518                 MEM_freeN(index_map);
1519
1520                 PyMem_Free(points);
1521         }
1522         else {
1523                 ret = PyList_New(0);
1524         }
1525
1526
1527         return ret;
1528 }
1529
1530 #endif /* MATH_STANDALONE */
1531
1532
1533 static PyMethodDef M_Geometry_methods[] = {
1534         {"intersect_ray_tri", (PyCFunction) M_Geometry_intersect_ray_tri, METH_VARARGS, M_Geometry_intersect_ray_tri_doc},
1535         {"intersect_point_line", (PyCFunction) M_Geometry_intersect_point_line, METH_VARARGS, M_Geometry_intersect_point_line_doc},
1536         {"intersect_point_tri", (PyCFunction) M_Geometry_intersect_point_tri, METH_VARARGS, M_Geometry_intersect_point_tri_doc},
1537         {"intersect_point_tri_2d", (PyCFunction) M_Geometry_intersect_point_tri_2d, METH_VARARGS, M_Geometry_intersect_point_tri_2d_doc},
1538         {"intersect_point_quad_2d", (PyCFunction) M_Geometry_intersect_point_quad_2d, METH_VARARGS, M_Geometry_intersect_point_quad_2d_doc},
1539         {"intersect_line_line", (PyCFunction) M_Geometry_intersect_line_line, METH_VARARGS, M_Geometry_intersect_line_line_doc},
1540         {"intersect_line_line_2d", (PyCFunction) M_Geometry_intersect_line_line_2d, METH_VARARGS, M_Geometry_intersect_line_line_2d_doc},
1541         {"intersect_line_plane", (PyCFunction) M_Geometry_intersect_line_plane, METH_VARARGS, M_Geometry_intersect_line_plane_doc},
1542         {"intersect_plane_plane", (PyCFunction) M_Geometry_intersect_plane_plane, METH_VARARGS, M_Geometry_intersect_plane_plane_doc},
1543         {"intersect_line_sphere", (PyCFunction) M_Geometry_intersect_line_sphere, METH_VARARGS, M_Geometry_intersect_line_sphere_doc},
1544         {"intersect_line_sphere_2d", (PyCFunction) M_Geometry_intersect_line_sphere_2d, METH_VARARGS, M_Geometry_intersect_line_sphere_2d_doc},
1545         {"distance_point_to_plane", (PyCFunction) M_Geometry_distance_point_to_plane, METH_VARARGS, M_Geometry_distance_point_to_plane_doc},
1546         {"intersect_sphere_sphere_2d", (PyCFunction) M_Geometry_intersect_sphere_sphere_2d, METH_VARARGS, M_Geometry_intersect_sphere_sphere_2d_doc},
1547         {"area_tri", (PyCFunction) M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
1548         {"volume_tetrahedron", (PyCFunction) M_Geometry_volume_tetrahedron, METH_VARARGS, M_Geometry_volume_tetrahedron_doc},
1549         {"normal", (PyCFunction) M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
1550         {"barycentric_transform", (PyCFunction) M_Geometry_barycentric_transform, METH_VARARGS, M_Geometry_barycentric_transform_doc},
1551         {"points_in_planes", (PyCFunction) M_Geometry_points_in_planes, METH_VARARGS, M_Geometry_points_in_planes_doc},
1552 #ifndef MATH_STANDALONE
1553         {"interpolate_bezier", (PyCFunction) M_Geometry_interpolate_bezier, METH_VARARGS, M_Geometry_interpolate_bezier_doc},
1554         {"tessellate_polygon", (PyCFunction) M_Geometry_tessellate_polygon, METH_O, M_Geometry_tessellate_polygon_doc},
1555         {"convex_hull_2d", (PyCFunction) M_Geometry_convex_hull_2d, METH_O, M_Geometry_convex_hull_2d_doc},
1556         {"box_fit_2d", (PyCFunction) M_Geometry_box_fit_2d, METH_O, M_Geometry_box_fit_2d_doc},
1557         {"box_pack_2d", (PyCFunction) M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
1558 #endif
1559         {NULL, NULL, 0, NULL}
1560 };
1561
1562 static struct PyModuleDef M_Geometry_module_def = {
1563         PyModuleDef_HEAD_INIT,
1564         "mathutils.geometry",  /* m_name */
1565         M_Geometry_doc,  /* m_doc */
1566         0,  /* m_size */
1567         M_Geometry_methods,  /* m_methods */
1568         NULL,  /* m_reload */
1569         NULL,  /* m_traverse */
1570         NULL,  /* m_clear */
1571         NULL,  /* m_free */
1572 };
1573
1574 /*----------------------------MODULE INIT-------------------------*/
1575 PyMODINIT_FUNC PyInit_mathutils_geometry(void)
1576 {
1577         PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
1578         return submodule;
1579 }