Fix missing check if isect_plane_plane_v3 fails to find an intersection.
[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_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         int no_flip = false;
580
581         if (!PyArg_ParseTuple(args, "O!O!O!O!|i:intersect_line_plane",
582                               &vector_Type, &line_a,
583                               &vector_Type, &line_b,
584                               &vector_Type, &plane_co,
585                               &vector_Type, &plane_no,
586                               &no_flip))
587         {
588                 return NULL;
589         }
590
591         if (BaseMath_ReadCallback(line_a) == -1 ||
592             BaseMath_ReadCallback(line_b) == -1 ||
593             BaseMath_ReadCallback(plane_co) == -1 ||
594             BaseMath_ReadCallback(plane_no) == -1)
595         {
596                 return NULL;
597         }
598
599         if (ELEM4(2, line_a->size, line_b->size, plane_co->size, plane_no->size)) {
600                 PyErr_SetString(PyExc_ValueError,
601                                 "geometry.intersect_line_plane(...): "
602                                 " can't use 2D Vectors");
603                 return NULL;
604         }
605
606         /* TODO: implements no_flip */
607         if (isect_line_plane_v3(isect, line_a->vec, line_b->vec, plane_co->vec, plane_no->vec) == 1) {
608                 return Vector_CreatePyObject(isect, 3, Py_NEW, NULL);
609         }
610         else {
611                 Py_RETURN_NONE;
612         }
613 }
614
615 PyDoc_STRVAR(M_Geometry_intersect_plane_plane_doc,
616 ".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
617 "\n"
618 "   Return the intersection between two planes\n"
619 "\n"
620 "   :arg plane_a_co: Point on the first plane\n"
621 "   :type plane_a_co: :class:`mathutils.Vector`\n"
622 "   :arg plane_a_no: Normal of the first plane\n"
623 "   :type plane_a_no: :class:`mathutils.Vector`\n"
624 "   :arg plane_b_co: Point on the second plane\n"
625 "   :type plane_b_co: :class:`mathutils.Vector`\n"
626 "   :arg plane_b_no: Normal of the second plane\n"
627 "   :type plane_b_no: :class:`mathutils.Vector`\n"
628 "   :return: The line of the intersection represented as a point and a vector\n"
629 "   :rtype: tuple pair of :class:`mathutils.Vector` or None if the intersection can't be calculated\n"
630 );
631 static PyObject *M_Geometry_intersect_plane_plane(PyObject *UNUSED(self), PyObject *args)
632 {
633         PyObject *ret, *ret_co, *ret_no;
634         VectorObject *plane_a_co, *plane_a_no, *plane_b_co, *plane_b_no;
635
636         float isect_co[3];
637         float isect_no[3];
638
639         if (!PyArg_ParseTuple(args, "O!O!O!O!:intersect_plane_plane",
640                               &vector_Type, &plane_a_co,
641                               &vector_Type, &plane_a_no,
642                               &vector_Type, &plane_b_co,
643                               &vector_Type, &plane_b_no))
644         {
645                 return NULL;
646         }
647
648         if (BaseMath_ReadCallback(plane_a_co) == -1 ||
649             BaseMath_ReadCallback(plane_a_no) == -1 ||
650             BaseMath_ReadCallback(plane_b_co) == -1 ||
651             BaseMath_ReadCallback(plane_b_no) == -1)
652         {
653                 return NULL;
654         }
655
656         if (ELEM4(2, plane_a_co->size, plane_a_no->size, plane_b_co->size, plane_b_no->size)) {
657                 PyErr_SetString(PyExc_ValueError,
658                                 "geometry.intersect_plane_plane(...): "
659                                 " can't use 2D Vectors");
660                 return NULL;
661         }
662
663         if (isect_plane_plane_v3(isect_co, isect_no,
664                                  plane_a_co->vec, plane_a_no->vec,
665                                  plane_b_co->vec, plane_b_no->vec))
666         {
667                 normalize_v3(isect_no);
668
669                 ret_co = Vector_CreatePyObject(isect_co, 3, Py_NEW, NULL);
670                 ret_no = Vector_CreatePyObject(isect_no, 3, Py_NEW, NULL);
671         }
672         else {
673                 ret_co = Py_None;
674                 ret_no = Py_None;
675
676                 Py_INCREF(ret_co);
677                 Py_INCREF(ret_no);
678         }
679
680         ret = PyTuple_New(2);
681         PyTuple_SET_ITEM(ret, 0, ret_co);
682         PyTuple_SET_ITEM(ret, 1, ret_no);
683         return ret;
684 }
685
686 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_doc,
687 ".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
688 "\n"
689 "   Takes a lines (as 2 vectors), a sphere as a point and a radius and\n"
690 "   returns the intersection\n"
691 "\n"
692 "   :arg line_a: First point of the first line\n"
693 "   :type line_a: :class:`mathutils.Vector`\n"
694 "   :arg line_b: Second point of the first line\n"
695 "   :type line_b: :class:`mathutils.Vector`\n"
696 "   :arg sphere_co: The center of the sphere\n"
697 "   :type sphere_co: :class:`mathutils.Vector`\n"
698 "   :arg sphere_radius: Radius of the sphere\n"
699 "   :type sphere_radius: sphere_radius\n"
700 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
701 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
702 );
703 static PyObject *M_Geometry_intersect_line_sphere(PyObject *UNUSED(self), PyObject *args)
704 {
705         VectorObject *line_a, *line_b, *sphere_co;
706         float sphere_radius;
707         int clip = true;
708
709         float isect_a[3];
710         float isect_b[3];
711
712         if (!PyArg_ParseTuple(args, "O!O!O!f|i:intersect_line_sphere",
713                               &vector_Type, &line_a,
714                               &vector_Type, &line_b,
715                               &vector_Type, &sphere_co,
716                               &sphere_radius, &clip))
717         {
718                 return NULL;
719         }
720
721         if (BaseMath_ReadCallback(line_a) == -1 ||
722             BaseMath_ReadCallback(line_b) == -1 ||
723             BaseMath_ReadCallback(sphere_co) == -1)
724         {
725                 return NULL;
726         }
727
728         if (ELEM3(2, line_a->size, line_b->size, sphere_co->size)) {
729                 PyErr_SetString(PyExc_ValueError,
730                                 "geometry.intersect_line_sphere(...): "
731                                 " can't use 2D Vectors");
732                 return NULL;
733         }
734         else {
735                 bool use_a = true;
736                 bool use_b = true;
737                 float lambda;
738
739                 PyObject *ret = PyTuple_New(2);
740
741                 switch (isect_line_sphere_v3(line_a->vec, line_b->vec, sphere_co->vec, sphere_radius, isect_a, isect_b)) {
742                         case 1:
743                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
744                                 use_b = false;
745                                 break;
746                         case 2:
747                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
748                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
749                                 break;
750                         default:
751                                 use_a = false;
752                                 use_b = false;
753                                 break;
754                 }
755
756                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 3, Py_NEW, NULL)); }
757                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
758
759                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 3, Py_NEW, NULL)); }
760                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
761
762                 return ret;
763         }
764 }
765
766 /* keep in sync with M_Geometry_intersect_line_sphere */
767 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_2d_doc,
768 ".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
769 "\n"
770 "   Takes a lines (as 2 vectors), a sphere as a point and a radius and\n"
771 "   returns the intersection\n"
772 "\n"
773 "   :arg line_a: First point of the first line\n"
774 "   :type line_a: :class:`mathutils.Vector`\n"
775 "   :arg line_b: Second point of the first line\n"
776 "   :type line_b: :class:`mathutils.Vector`\n"
777 "   :arg sphere_co: The center of the sphere\n"
778 "   :type sphere_co: :class:`mathutils.Vector`\n"
779 "   :arg sphere_radius: Radius of the sphere\n"
780 "   :type sphere_radius: sphere_radius\n"
781 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
782 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
783 );
784 static PyObject *M_Geometry_intersect_line_sphere_2d(PyObject *UNUSED(self), PyObject *args)
785 {
786         VectorObject *line_a, *line_b, *sphere_co;
787         float sphere_radius;
788         int clip = true;
789
790         float isect_a[2];
791         float isect_b[2];
792
793         if (!PyArg_ParseTuple(args, "O!O!O!f|i:intersect_line_sphere_2d",
794                               &vector_Type, &line_a,
795                               &vector_Type, &line_b,
796                               &vector_Type, &sphere_co,
797                               &sphere_radius, &clip))
798         {
799                 return NULL;
800         }
801
802         if (BaseMath_ReadCallback(line_a) == -1 ||
803             BaseMath_ReadCallback(line_b) == -1 ||
804             BaseMath_ReadCallback(sphere_co) == -1)
805         {
806                 return NULL;
807         }
808         else {
809                 bool use_a = true;
810                 bool use_b = true;
811                 float lambda;
812
813                 PyObject *ret = PyTuple_New(2);
814
815                 switch (isect_line_sphere_v2(line_a->vec, line_b->vec, sphere_co->vec, sphere_radius, isect_a, isect_b)) {
816                         case 1:
817                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
818                                 use_b = false;
819                                 break;
820                         case 2:
821                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
822                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
823                                 break;
824                         default:
825                                 use_a = false;
826                                 use_b = false;
827                                 break;
828                 }
829
830                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 2, Py_NEW, NULL)); }
831                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
832
833                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 2, Py_NEW, NULL)); }
834                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
835
836                 return ret;
837         }
838 }
839
840 PyDoc_STRVAR(M_Geometry_intersect_point_line_doc,
841 ".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
842 "\n"
843 "   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"
844 "\n"
845 "   :arg pt: Point\n"
846 "   :type pt: :class:`mathutils.Vector`\n"
847 "   :arg line_p1: First point of the line\n"
848 "   :type line_p1: :class:`mathutils.Vector`\n"
849 "   :arg line_p1: Second point of the line\n"
850 "   :type line_p1: :class:`mathutils.Vector`\n"
851 "   :rtype: (:class:`mathutils.Vector`, float)\n"
852 );
853 static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObject *args)
854 {
855         VectorObject *pt, *line_1, *line_2;
856         float pt_in[3], pt_out[3], l1[3], l2[3];
857         float lambda;
858         PyObject *ret;
859         int size = 2;
860         
861         if (!PyArg_ParseTuple(args, "O!O!O!:intersect_point_line",
862                               &vector_Type, &pt,
863                               &vector_Type, &line_1,
864                               &vector_Type, &line_2))
865         {
866                 return NULL;
867         }
868
869         if (BaseMath_ReadCallback(pt) == -1 ||
870             BaseMath_ReadCallback(line_1) == -1 ||
871             BaseMath_ReadCallback(line_2) == -1)
872         {
873                 return NULL;
874         }
875
876         /* accept 2d verts */
877         if (pt->size >= 3)     { copy_v3_v3(pt_in, pt->vec); size = 3; }
878         else                   { copy_v2_v2(pt_in, pt->vec); pt_in[2] = 0.0f; }
879         
880         if (line_1->size >= 3) { copy_v3_v3(l1, line_1->vec); size = 3; }
881         else                   { copy_v2_v2(l1, line_1->vec); l1[2] = 0.0f; }
882         
883         if (line_2->size >= 3) { copy_v3_v3(l2, line_2->vec); size = 3; }
884         else                   { copy_v2_v2(l2, line_2->vec); l2[2] = 0.0f; }
885         
886         /* do the calculation */
887         lambda = closest_to_line_v3(pt_out, pt_in, l1, l2);
888         
889         ret = PyTuple_New(2);
890         PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(pt_out, size, Py_NEW, NULL));
891         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(lambda));
892         return ret;
893 }
894
895 PyDoc_STRVAR(M_Geometry_intersect_point_tri_2d_doc,
896 ".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
897 "\n"
898 "   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"
899 "\n"
900 "   :arg pt: Point\n"
901 "   :type v1: :class:`mathutils.Vector`\n"
902 "   :arg tri_p1: First point of the triangle\n"
903 "   :type tri_p1: :class:`mathutils.Vector`\n"
904 "   :arg tri_p2: Second point of the triangle\n"
905 "   :type tri_p2: :class:`mathutils.Vector`\n"
906 "   :arg tri_p3: Third point of the triangle\n"
907 "   :type tri_p3: :class:`mathutils.Vector`\n"
908 "   :rtype: int\n"
909 );
910 static PyObject *M_Geometry_intersect_point_tri_2d(PyObject *UNUSED(self), PyObject *args)
911 {
912         VectorObject *pt_vec, *tri_p1, *tri_p2, *tri_p3;
913         
914         if (!PyArg_ParseTuple(args, "O!O!O!O!:intersect_point_tri_2d",
915                               &vector_Type, &pt_vec,
916                               &vector_Type, &tri_p1,
917                               &vector_Type, &tri_p2,
918                               &vector_Type, &tri_p3))
919         {
920                 return NULL;
921         }
922         
923         if (BaseMath_ReadCallback(pt_vec) == -1 ||
924             BaseMath_ReadCallback(tri_p1) == -1 ||
925             BaseMath_ReadCallback(tri_p2) == -1 ||
926             BaseMath_ReadCallback(tri_p3) == -1)
927         {
928                 return NULL;
929         }
930
931         return PyLong_FromLong(isect_point_tri_v2(pt_vec->vec, tri_p1->vec, tri_p2->vec, tri_p3->vec));
932 }
933
934 PyDoc_STRVAR(M_Geometry_intersect_point_quad_2d_doc,
935 ".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
936 "\n"
937 "   Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad, \n"
938 "   only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0.\n"
939 "   Works only with convex quads without singular edges."
940 "\n"
941 "   :arg pt: Point\n"
942 "   :type pt: :class:`mathutils.Vector`\n"
943 "   :arg quad_p1: First point of the quad\n"
944 "   :type quad_p1: :class:`mathutils.Vector`\n"
945 "   :arg quad_p2: Second point of the quad\n"
946 "   :type quad_p2: :class:`mathutils.Vector`\n"
947 "   :arg quad_p3: Third point of the quad\n"
948 "   :type quad_p3: :class:`mathutils.Vector`\n"
949 "   :arg quad_p4: Forth point of the quad\n"
950 "   :type quad_p4: :class:`mathutils.Vector`\n"
951 "   :rtype: int\n"
952 );
953 static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyObject *args)
954 {
955         VectorObject *pt_vec, *quad_p1, *quad_p2, *quad_p3, *quad_p4;
956         
957         if (!PyArg_ParseTuple(args, "O!O!O!O!O!:intersect_point_quad_2d",
958                               &vector_Type, &pt_vec,
959                               &vector_Type, &quad_p1,
960                               &vector_Type, &quad_p2,
961                               &vector_Type, &quad_p3,
962                               &vector_Type, &quad_p4))
963         {
964                 return NULL;
965         }
966
967         if (BaseMath_ReadCallback(pt_vec)  == -1 ||
968             BaseMath_ReadCallback(quad_p1) == -1 ||
969             BaseMath_ReadCallback(quad_p2) == -1 ||
970             BaseMath_ReadCallback(quad_p3) == -1 ||
971             BaseMath_ReadCallback(quad_p4) == -1)
972         {
973                 return NULL;
974         }
975
976         return PyLong_FromLong(isect_point_quad_v2(pt_vec->vec, quad_p1->vec, quad_p2->vec, quad_p3->vec, quad_p4->vec));
977 }
978
979 PyDoc_STRVAR(M_Geometry_distance_point_to_plane_doc,
980 ".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
981 "\n"
982 "   Returns the signed distance between a point and a plane "
983 "   (negative when below the normal).\n"
984 "\n"
985 "   :arg pt: Point\n"
986 "   :type pt: :class:`mathutils.Vector`\n"
987 "   :arg plane_co: A point on the plane\n"
988 "   :type plane_co: :class:`mathutils.Vector`\n"
989 "   :arg plane_no: The direction the plane is facing\n"
990 "   :type plane_no: :class:`mathutils.Vector`\n"
991 "   :rtype: float\n"
992 );
993 static PyObject *M_Geometry_distance_point_to_plane(PyObject *UNUSED(self), PyObject *args)
994 {
995         VectorObject *pt, *plane_co, *plane_no;
996         float plane[4];
997
998         if (!PyArg_ParseTuple(args, "O!O!O!:distance_point_to_plane",
999                               &vector_Type, &pt,
1000                               &vector_Type, &plane_co,
1001                               &vector_Type, &plane_no))
1002         {
1003                 return NULL;
1004         }
1005
1006         if (pt->size != 3 ||
1007             plane_co->size != 3 ||
1008             plane_no->size != 3)
1009         {
1010                 PyErr_SetString(PyExc_ValueError,
1011                                 "One of more of the vector arguments wasn't a 3D vector");
1012                 return NULL;
1013         }
1014
1015         if (BaseMath_ReadCallback(pt) == -1 ||
1016             BaseMath_ReadCallback(plane_co) == -1 ||
1017             BaseMath_ReadCallback(plane_no) == -1)
1018         {
1019                 return NULL;
1020         }
1021
1022         plane_from_point_normal_v3(plane, plane_co->vec, plane_no->vec);
1023         return PyFloat_FromDouble(dist_to_plane_v3(pt->vec, plane));
1024 }
1025
1026 PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
1027 ".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
1028 "\n"
1029 "   Return a transformed point, the transformation is defined by 2 triangles.\n"
1030 "\n"
1031 "   :arg point: The point to transform.\n"
1032 "   :type point: :class:`mathutils.Vector`\n"
1033 "   :arg tri_a1: source triangle vertex.\n"
1034 "   :type tri_a1: :class:`mathutils.Vector`\n"
1035 "   :arg tri_a2: source triangle vertex.\n"
1036 "   :type tri_a2: :class:`mathutils.Vector`\n"
1037 "   :arg tri_a3: source triangle vertex.\n"
1038 "   :type tri_a3: :class:`mathutils.Vector`\n"
1039 "   :arg tri_a1: target triangle vertex.\n"
1040 "   :type tri_a1: :class:`mathutils.Vector`\n"
1041 "   :arg tri_a2: target triangle vertex.\n"
1042 "   :type tri_a2: :class:`mathutils.Vector`\n"
1043 "   :arg tri_a3: target triangle vertex.\n"
1044 "   :type tri_a3: :class:`mathutils.Vector`\n"
1045 "   :return: The transformed point\n"
1046 "   :rtype: :class:`mathutils.Vector`'s\n"
1047 );
1048 static PyObject *M_Geometry_barycentric_transform(PyObject *UNUSED(self), PyObject *args)
1049 {
1050         VectorObject *vec_pt;
1051         VectorObject *vec_t1_tar, *vec_t2_tar, *vec_t3_tar;
1052         VectorObject *vec_t1_src, *vec_t2_src, *vec_t3_src;
1053         float vec[3];
1054
1055         if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!O!:barycentric_transform",
1056                               &vector_Type, &vec_pt,
1057                               &vector_Type, &vec_t1_src,
1058                               &vector_Type, &vec_t2_src,
1059                               &vector_Type, &vec_t3_src,
1060                               &vector_Type, &vec_t1_tar,
1061                               &vector_Type, &vec_t2_tar,
1062                               &vector_Type, &vec_t3_tar))
1063         {
1064                 return NULL;
1065         }
1066
1067         if (vec_pt->size != 3 ||
1068             vec_t1_src->size != 3 ||
1069             vec_t2_src->size != 3 ||
1070             vec_t3_src->size != 3 ||
1071             vec_t1_tar->size != 3 ||
1072             vec_t2_tar->size != 3 ||
1073             vec_t3_tar->size != 3)
1074         {
1075                 PyErr_SetString(PyExc_ValueError,
1076                                 "One of more of the vector arguments wasn't a 3D vector");
1077                 return NULL;
1078         }
1079
1080         if (BaseMath_ReadCallback(vec_pt) == -1 ||
1081             BaseMath_ReadCallback(vec_t1_src) == -1 ||
1082             BaseMath_ReadCallback(vec_t2_src) == -1 ||
1083             BaseMath_ReadCallback(vec_t3_src) == -1 ||
1084             BaseMath_ReadCallback(vec_t1_tar) == -1 ||
1085             BaseMath_ReadCallback(vec_t2_tar) == -1 ||
1086             BaseMath_ReadCallback(vec_t3_tar) == -1)
1087         {
1088                 return NULL;
1089         }
1090
1091         barycentric_transform(vec, vec_pt->vec,
1092                               vec_t1_tar->vec, vec_t2_tar->vec, vec_t3_tar->vec,
1093                               vec_t1_src->vec, vec_t2_src->vec, vec_t3_src->vec);
1094
1095         return Vector_CreatePyObject(vec, 3, Py_NEW, NULL);
1096 }
1097
1098 PyDoc_STRVAR(M_Geometry_points_in_planes_doc,
1099 ".. function:: points_in_planes(planes)\n"
1100 "\n"
1101 "   Returns a list of points inside all planes given and a list of index values for the planes used.\n"
1102 "\n"
1103 "   :arg planes: List of planes (4D vectors).\n"
1104 "   :type planes: list of :class:`mathutils.Vector`\n"
1105 "   :return: two lists, once containing the vertices inside the planes, another containing the plane indicies used\n"
1106 "   :rtype: pair of lists\n"
1107 );
1108 /* note: this function could be optimized by some spatial structure */
1109 static PyObject *M_Geometry_points_in_planes(PyObject *UNUSED(self), PyObject *args)
1110 {
1111         PyObject *py_planes;
1112         float (*planes)[4];
1113         unsigned int planes_len;
1114
1115         if (!PyArg_ParseTuple(args, "O:points_in_planes",
1116                               &py_planes))
1117         {
1118                 return NULL;
1119         }
1120
1121         if ((planes_len = mathutils_array_parse_alloc_v((float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
1122                 return NULL;
1123         }
1124         else {
1125                 /* note, this could be refactored into plain C easy - py bits are noted */
1126                 const float eps = 0.0001f;
1127                 const unsigned int len = (unsigned int)planes_len;
1128                 unsigned int i, j, k, l;
1129
1130                 float n1n2[3], n2n3[3], n3n1[3];
1131                 float potentialVertex[3];
1132                 char *planes_used = PyMem_Malloc(sizeof(char) * len);
1133
1134                 /* python */
1135                 PyObject *py_verts = PyList_New(0);
1136                 PyObject *py_plane_index = PyList_New(0);
1137
1138                 memset(planes_used, 0, sizeof(char) * len);
1139
1140                 for (i = 0; i < len; i++) {
1141                         const float *N1 = planes[i];
1142                         for (j = i + 1; j < len; j++) {
1143                                 const float *N2 = planes[j];
1144                                 cross_v3_v3v3(n1n2, N1, N2);
1145                                 if (len_squared_v3(n1n2) > eps) {
1146                                         for (k = j + 1; k < len; k++) {
1147                                                 const float *N3 = planes[k];
1148                                                 cross_v3_v3v3(n2n3, N2, N3);
1149                                                 if (len_squared_v3(n2n3) > eps) {
1150                                                         cross_v3_v3v3(n3n1, N3, N1);
1151                                                         if (len_squared_v3(n3n1) > eps) {
1152                                                                 const float quotient = dot_v3v3(N1, n2n3);
1153                                                                 if (fabsf(quotient) > eps) {
1154                                                                         /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
1155                                                                         const float quotient_ninv = -1.0f / quotient;
1156                                                                         potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) + (n1n2[0] * N3[3])) * quotient_ninv;
1157                                                                         potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) + (n1n2[1] * N3[3])) * quotient_ninv;
1158                                                                         potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) + (n1n2[2] * N3[3])) * quotient_ninv;
1159                                                                         for (l = 0; l < len; l++) {
1160                                                                                 const float *NP = planes[l];
1161                                                                                 if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
1162                                                                                         break;
1163                                                                                 }
1164                                                                         }
1165
1166                                                                         if (l == len) { /* ok */
1167                                                                                 /* python */
1168                                                                                 PyObject *item = Vector_CreatePyObject(potentialVertex, 3, Py_NEW, NULL);
1169                                                                                 PyList_Append(py_verts, item);
1170                                                                                 Py_DECREF(item);
1171
1172                                                                                 planes_used[i] = planes_used[j] = planes_used[k] = true;
1173                                                                         }
1174                                                                 }
1175                                                         }
1176                                                 }
1177                                         }
1178                                 }
1179                         }
1180                 }
1181
1182                 PyMem_Free(planes);
1183
1184                 /* now make a list of used planes */
1185                 for (i = 0; i < len; i++) {
1186                         if (planes_used[i]) {
1187                                 PyObject *item = PyLong_FromLong(i);
1188                                 PyList_Append(py_plane_index, item);
1189                                 Py_DECREF(item);
1190                         }
1191                 }
1192                 PyMem_Free(planes_used);
1193
1194                 {
1195                         PyObject *ret = PyTuple_New(2);
1196                         PyTuple_SET_ITEM(ret, 0, py_verts);
1197                         PyTuple_SET_ITEM(ret, 1, py_plane_index);
1198                         return ret;
1199                 }
1200         }
1201 }
1202
1203 #ifndef MATH_STANDALONE
1204
1205 PyDoc_STRVAR(M_Geometry_interpolate_bezier_doc,
1206 ".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
1207 "\n"
1208 "   Interpolate a bezier spline segment.\n"
1209 "\n"
1210 "   :arg knot1: First bezier spline point.\n"
1211 "   :type knot1: :class:`mathutils.Vector`\n"
1212 "   :arg handle1: First bezier spline handle.\n"
1213 "   :type handle1: :class:`mathutils.Vector`\n"
1214 "   :arg handle2: Second bezier spline handle.\n"
1215 "   :type handle2: :class:`mathutils.Vector`\n"
1216 "   :arg knot2: Second bezier spline point.\n"
1217 "   :type knot2: :class:`mathutils.Vector`\n"
1218 "   :arg resolution: Number of points to return.\n"
1219 "   :type resolution: int\n"
1220 "   :return: The interpolated points\n"
1221 "   :rtype: list of :class:`mathutils.Vector`'s\n"
1222 );
1223 static PyObject *M_Geometry_interpolate_bezier(PyObject *UNUSED(self), PyObject *args)
1224 {
1225         VectorObject *vec_k1, *vec_h1, *vec_k2, *vec_h2;
1226         int resolu;
1227         int dims;
1228         int i;
1229         float *coord_array, *fp;
1230         PyObject *list;
1231
1232         float k1[4] = {0.0, 0.0, 0.0, 0.0};
1233         float h1[4] = {0.0, 0.0, 0.0, 0.0};
1234         float k2[4] = {0.0, 0.0, 0.0, 0.0};
1235         float h2[4] = {0.0, 0.0, 0.0, 0.0};
1236
1237
1238         if (!PyArg_ParseTuple(args, "O!O!O!O!i:interpolate_bezier",
1239                               &vector_Type, &vec_k1,
1240                               &vector_Type, &vec_h1,
1241                               &vector_Type, &vec_h2,
1242                               &vector_Type, &vec_k2, &resolu))
1243         {
1244                 return NULL;
1245         }
1246
1247         if (resolu <= 1) {
1248                 PyErr_SetString(PyExc_ValueError,
1249                                 "resolution must be 2 or over");
1250                 return NULL;
1251         }
1252
1253         if (BaseMath_ReadCallback(vec_k1) == -1 ||
1254             BaseMath_ReadCallback(vec_h1) == -1 ||
1255             BaseMath_ReadCallback(vec_k2) == -1 ||
1256             BaseMath_ReadCallback(vec_h2) == -1)
1257         {
1258                 return NULL;
1259         }
1260
1261         dims = max_iiii(vec_k1->size, vec_h1->size, vec_h2->size, vec_k2->size);
1262
1263         for (i = 0; i < vec_k1->size; i++) k1[i] = vec_k1->vec[i];
1264         for (i = 0; i < vec_h1->size; i++) h1[i] = vec_h1->vec[i];
1265         for (i = 0; i < vec_k2->size; i++) k2[i] = vec_k2->vec[i];
1266         for (i = 0; i < vec_h2->size; i++) h2[i] = vec_h2->vec[i];
1267
1268         coord_array = MEM_callocN(dims * (resolu) * sizeof(float), "interpolate_bezier");
1269         for (i = 0; i < dims; i++) {
1270                 BKE_curve_forward_diff_bezier(k1[i], h1[i], h2[i], k2[i], coord_array + i, resolu - 1, sizeof(float) * dims);
1271         }
1272
1273         list = PyList_New(resolu);
1274         fp = coord_array;
1275         for (i = 0; i < resolu; i++, fp = fp + dims) {
1276                 PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, Py_NEW, NULL));
1277         }
1278         MEM_freeN(coord_array);
1279         return list;
1280 }
1281
1282
1283 PyDoc_STRVAR(M_Geometry_tessellate_polygon_doc,
1284 ".. function:: tessellate_polygon(veclist_list)\n"
1285 "\n"
1286 "   Takes a list of polylines (each point a vector) and returns the point indices for a polyline filled with triangles.\n"
1287 "\n"
1288 "   :arg veclist_list: list of polylines\n"
1289 "   :rtype: list\n"
1290 );
1291 /* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
1292 static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject *polyLineSeq)
1293 {
1294         PyObject *tri_list; /*return this list of tri's */
1295         PyObject *polyLine, *polyVec;
1296         int i, len_polylines, len_polypoints, ls_error = 0;
1297
1298         /* display listbase */
1299         ListBase dispbase = {NULL, NULL};
1300         DispList *dl;
1301         float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
1302         int index, *dl_face, totpoints = 0;
1303
1304         if (!PySequence_Check(polyLineSeq)) {
1305                 PyErr_SetString(PyExc_TypeError,
1306                                 "expected a sequence of poly lines");
1307                 return NULL;
1308         }
1309
1310         len_polylines = PySequence_Size(polyLineSeq);
1311
1312         for (i = 0; i < len_polylines; i++) {
1313                 polyLine = PySequence_GetItem(polyLineSeq, i);
1314                 if (!PySequence_Check(polyLine)) {
1315                         BKE_displist_free(&dispbase);
1316                         Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
1317                         PyErr_SetString(PyExc_TypeError,
1318                                         "One or more of the polylines is not a sequence of mathutils.Vector's");
1319                         return NULL;
1320                 }
1321
1322                 len_polypoints = PySequence_Size(polyLine);
1323                 if (len_polypoints > 0) { /* don't bother adding edges as polylines */
1324 #if 0
1325                         if (EXPP_check_sequence_consistency(polyLine, &vector_Type) != 1) {
1326                                 freedisplist(&dispbase);
1327                                 Py_DECREF(polyLine);
1328                                 PyErr_SetString(PyExc_TypeError,
1329                                                 "A point in one of the polylines is not a mathutils.Vector type");
1330                                 return NULL;
1331                         }
1332 #endif
1333                         dl = MEM_callocN(sizeof(DispList), "poly disp");
1334                         BLI_addtail(&dispbase, dl);
1335                         dl->type = DL_INDEX3;
1336                         dl->nr = len_polypoints;
1337                         dl->type = DL_POLY;
1338                         dl->parts = 1; /* no faces, 1 edge loop */
1339                         dl->col = 0; /* no material */
1340                         dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
1341                         dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
1342
1343                         for (index = 0; index < len_polypoints; index++, fp += 3) {
1344                                 polyVec = PySequence_GetItem(polyLine, index);
1345                                 if (VectorObject_Check(polyVec)) {
1346
1347                                         if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1)
1348                                                 ls_error = 1;
1349
1350                                         fp[0] = ((VectorObject *)polyVec)->vec[0];
1351                                         fp[1] = ((VectorObject *)polyVec)->vec[1];
1352                                         if (((VectorObject *)polyVec)->size > 2)
1353                                                 fp[2] = ((VectorObject *)polyVec)->vec[2];
1354                                         else
1355                                                 fp[2] = 0.0f;  /* if its a 2d vector then set the z to be zero */
1356                                 }
1357                                 else {
1358                                         ls_error = 1;
1359                                 }
1360
1361                                 totpoints++;
1362                                 Py_DECREF(polyVec);
1363                         }
1364                 }
1365                 Py_DECREF(polyLine);
1366         }
1367
1368         if (ls_error) {
1369                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1370                 PyErr_SetString(PyExc_TypeError,
1371                                 "A point in one of the polylines "
1372                                 "is not a mathutils.Vector type");
1373                 return NULL;
1374         }
1375         else if (totpoints) {
1376                 /* now make the list to return */
1377                 /* TODO, add normal arg */
1378                 BKE_displist_fill(&dispbase, &dispbase, NULL, false);
1379
1380                 /* The faces are stored in a new DisplayList
1381                  * thats added to the head of the listbase */
1382                 dl = dispbase.first;
1383
1384                 tri_list = PyList_New(dl->parts);
1385                 if (!tri_list) {
1386                         BKE_displist_free(&dispbase);
1387                         PyErr_SetString(PyExc_RuntimeError,
1388                                         "failed to make a new list");
1389                         return NULL;
1390                 }
1391
1392                 index = 0;
1393                 dl_face = dl->index;
1394                 while (index < dl->parts) {
1395                         PyList_SET_ITEM(tri_list, index, Py_BuildValue("iii", dl_face[0], dl_face[1], dl_face[2]));
1396                         dl_face += 3;
1397                         index++;
1398                 }
1399                 BKE_displist_free(&dispbase);
1400         }
1401         else {
1402                 /* no points, do this so scripts don't barf */
1403                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1404                 tri_list = PyList_New(0);
1405         }
1406
1407         return tri_list;
1408 }
1409
1410
1411 static int boxPack_FromPyObject(PyObject *value, BoxPack **boxarray)
1412 {
1413         Py_ssize_t len, i;
1414         PyObject *list_item, *item_1, *item_2;
1415         BoxPack *box;
1416
1417
1418         /* Error checking must already be done */
1419         if (!PyList_Check(value)) {
1420                 PyErr_SetString(PyExc_TypeError,
1421                                 "can only back a list of [x, y, w, h]");
1422                 return -1;
1423         }
1424
1425         len = PyList_GET_SIZE(value);
1426
1427         *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
1428
1429
1430         for (i = 0; i < len; i++) {
1431                 list_item = PyList_GET_ITEM(value, i);
1432                 if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
1433                         MEM_freeN(*boxarray);
1434                         PyErr_SetString(PyExc_TypeError,
1435                                         "can only pack a list of [x, y, w, h]");
1436                         return -1;
1437                 }
1438
1439                 box = (*boxarray) + i;
1440
1441                 item_1 = PyList_GET_ITEM(list_item, 2);
1442                 item_2 = PyList_GET_ITEM(list_item, 3);
1443
1444                 box->w =  (float)PyFloat_AsDouble(item_1);
1445                 box->h =  (float)PyFloat_AsDouble(item_2);
1446                 box->index = i;
1447
1448                 /* accounts for error case too and overwrites with own error */
1449                 if (box->w < 0.0f || box->h < 0.0f) {
1450                         MEM_freeN(*boxarray);
1451                         PyErr_SetString(PyExc_TypeError,
1452                                         "error parsing width and height values from list: "
1453                                         "[x, y, w, h], not numbers or below zero");
1454                         return -1;
1455                 }
1456
1457                 /* verts will be added later */
1458         }
1459         return 0;
1460 }
1461
1462 static void boxPack_ToPyObject(PyObject *value, BoxPack **boxarray)
1463 {
1464         Py_ssize_t len, i;
1465         PyObject *list_item;
1466         BoxPack *box;
1467
1468         len = PyList_GET_SIZE(value);
1469
1470         for (i = 0; i < len; i++) {
1471                 box = (*boxarray) + i;
1472                 list_item = PyList_GET_ITEM(value, box->index);
1473                 PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
1474                 PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
1475         }
1476         MEM_freeN(*boxarray);
1477 }
1478
1479 PyDoc_STRVAR(M_Geometry_box_pack_2d_doc,
1480 ".. function:: box_pack_2d(boxes)\n"
1481 "\n"
1482 "   Returns the normal of the 3D tri or quad.\n"
1483 "\n"
1484 "   :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"
1485 "   :type boxes: list\n"
1486 "   :return: the width and height of the packed bounding box\n"
1487 "   :rtype: tuple, pair of floats\n"
1488 );
1489 static PyObject *M_Geometry_box_pack_2d(PyObject *UNUSED(self), PyObject *boxlist)
1490 {
1491         float tot_width = 0.0f, tot_height = 0.0f;
1492         Py_ssize_t len;
1493
1494         PyObject *ret;
1495
1496         if (!PyList_Check(boxlist)) {
1497                 PyErr_SetString(PyExc_TypeError,
1498                                 "expected a list of boxes [[x, y, w, h], ... ]");
1499                 return NULL;
1500         }
1501
1502         len = PyList_GET_SIZE(boxlist);
1503         if (len) {
1504                 BoxPack *boxarray = NULL;
1505                 if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
1506                         return NULL; /* exception set */
1507                 }
1508
1509                 /* Non Python function */
1510                 BLI_box_pack_2d(boxarray, len, &tot_width, &tot_height);
1511
1512                 boxPack_ToPyObject(boxlist, &boxarray);
1513         }
1514
1515         ret = PyTuple_New(2);
1516         PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(tot_width));
1517         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(tot_width));
1518         return ret;
1519 }
1520
1521 PyDoc_STRVAR(M_Geometry_box_fit_2d_doc,
1522 ".. function:: box_fit_2d(points)\n"
1523 "\n"
1524 "   Returns an angle that best fits the points to an axis aligned rectangle\n"
1525 "\n"
1526 "   :arg points: list of 2d points.\n"
1527 "   :type points: list\n"
1528 "   :return: angle\n"
1529 "   :rtype: float\n"
1530 );
1531 static PyObject *M_Geometry_box_fit_2d(PyObject *UNUSED(self), PyObject *pointlist)
1532 {
1533         float (*points)[2];
1534         Py_ssize_t len;
1535
1536         float angle = 0.0f;
1537
1538         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "box_fit_2d");
1539         if (len == -1) {
1540                 return NULL;
1541         }
1542
1543         if (len) {
1544                 /* Non Python function */
1545                 angle = BLI_convexhull_aabb_fit_points_2d((const float (*)[2])points, len);
1546
1547                 PyMem_Free(points);
1548         }
1549
1550
1551         return PyFloat_FromDouble(angle);
1552 }
1553
1554 PyDoc_STRVAR(M_Geometry_convex_hull_2d_doc,
1555 ".. function:: convex_hull_2d(points)\n"
1556 "\n"
1557 "   Returns a list of indices into the list given\n"
1558 "\n"
1559 "   :arg points: list of 2d points.\n"
1560 "   :type points: list\n"
1561 "   :return: a list of indices\n"
1562 "   :rtype: list of ints\n"
1563 );
1564 static PyObject *M_Geometry_convex_hull_2d(PyObject *UNUSED(self), PyObject *pointlist)
1565 {
1566         float (*points)[2];
1567         Py_ssize_t len;
1568
1569         PyObject *ret;
1570
1571         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "convex_hull_2d");
1572         if (len == -1) {
1573                 return NULL;
1574         }
1575
1576         if (len) {
1577                 int *index_map;
1578                 Py_ssize_t len_ret, i;
1579
1580                 index_map  = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
1581
1582                 /* Non Python function */
1583                 len_ret = BLI_convexhull_2d((const float (*)[2])points, len, index_map);
1584
1585                 ret = PyList_New(len_ret);
1586                 for (i = 0; i < len_ret; i++) {
1587                         PyList_SET_ITEM(ret, i, PyLong_FromLong(index_map[i]));
1588                 }
1589
1590                 MEM_freeN(index_map);
1591
1592                 PyMem_Free(points);
1593         }
1594         else {
1595                 ret = PyList_New(0);
1596         }
1597
1598
1599         return ret;
1600 }
1601
1602 #endif /* MATH_STANDALONE */
1603
1604
1605 static PyMethodDef M_Geometry_methods[] = {
1606         {"intersect_ray_tri", (PyCFunction) M_Geometry_intersect_ray_tri, METH_VARARGS, M_Geometry_intersect_ray_tri_doc},
1607         {"intersect_point_line", (PyCFunction) M_Geometry_intersect_point_line, METH_VARARGS, M_Geometry_intersect_point_line_doc},
1608         {"intersect_point_tri_2d", (PyCFunction) M_Geometry_intersect_point_tri_2d, METH_VARARGS, M_Geometry_intersect_point_tri_2d_doc},
1609         {"intersect_point_quad_2d", (PyCFunction) M_Geometry_intersect_point_quad_2d, METH_VARARGS, M_Geometry_intersect_point_quad_2d_doc},
1610         {"intersect_line_line", (PyCFunction) M_Geometry_intersect_line_line, METH_VARARGS, M_Geometry_intersect_line_line_doc},
1611         {"intersect_line_line_2d", (PyCFunction) M_Geometry_intersect_line_line_2d, METH_VARARGS, M_Geometry_intersect_line_line_2d_doc},
1612         {"intersect_line_plane", (PyCFunction) M_Geometry_intersect_line_plane, METH_VARARGS, M_Geometry_intersect_line_plane_doc},
1613         {"intersect_plane_plane", (PyCFunction) M_Geometry_intersect_plane_plane, METH_VARARGS, M_Geometry_intersect_plane_plane_doc},
1614         {"intersect_line_sphere", (PyCFunction) M_Geometry_intersect_line_sphere, METH_VARARGS, M_Geometry_intersect_line_sphere_doc},
1615         {"intersect_line_sphere_2d", (PyCFunction) M_Geometry_intersect_line_sphere_2d, METH_VARARGS, M_Geometry_intersect_line_sphere_2d_doc},
1616         {"distance_point_to_plane", (PyCFunction) M_Geometry_distance_point_to_plane, METH_VARARGS, M_Geometry_distance_point_to_plane_doc},
1617         {"intersect_sphere_sphere_2d", (PyCFunction) M_Geometry_intersect_sphere_sphere_2d, METH_VARARGS, M_Geometry_intersect_sphere_sphere_2d_doc},
1618         {"area_tri", (PyCFunction) M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
1619         {"volume_tetrahedron", (PyCFunction) M_Geometry_volume_tetrahedron, METH_VARARGS, M_Geometry_volume_tetrahedron_doc},
1620         {"normal", (PyCFunction) M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
1621         {"barycentric_transform", (PyCFunction) M_Geometry_barycentric_transform, METH_VARARGS, M_Geometry_barycentric_transform_doc},
1622         {"points_in_planes", (PyCFunction) M_Geometry_points_in_planes, METH_VARARGS, M_Geometry_points_in_planes_doc},
1623 #ifndef MATH_STANDALONE
1624         {"interpolate_bezier", (PyCFunction) M_Geometry_interpolate_bezier, METH_VARARGS, M_Geometry_interpolate_bezier_doc},
1625         {"tessellate_polygon", (PyCFunction) M_Geometry_tessellate_polygon, METH_O, M_Geometry_tessellate_polygon_doc},
1626         {"convex_hull_2d", (PyCFunction) M_Geometry_convex_hull_2d, METH_O, M_Geometry_convex_hull_2d_doc},
1627         {"box_fit_2d", (PyCFunction) M_Geometry_box_fit_2d, METH_O, M_Geometry_box_fit_2d_doc},
1628         {"box_pack_2d", (PyCFunction) M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
1629 #endif
1630         {NULL, NULL, 0, NULL}
1631 };
1632
1633 static struct PyModuleDef M_Geometry_module_def = {
1634         PyModuleDef_HEAD_INIT,
1635         "mathutils.geometry",  /* m_name */
1636         M_Geometry_doc,  /* m_doc */
1637         0,  /* m_size */
1638         M_Geometry_methods,  /* m_methods */
1639         NULL,  /* m_reload */
1640         NULL,  /* m_traverse */
1641         NULL,  /* m_clear */
1642         NULL,  /* m_free */
1643 };
1644
1645 /*----------------------------MODULE INIT-------------------------*/
1646 PyMODINIT_FUNC PyInit_mathutils_geometry(void)
1647 {
1648         PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
1649         return submodule;
1650 }