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