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