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