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