Pass EvaluationContext argument everywhere
[blender.git] / source / blender / python / mathutils / mathutils_bvhtree.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): Lukas Toenne, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/mathutils/mathutils_bvhtree.c
24  *  \ingroup mathutils
25  *
26  * This file defines the 'mathutils.bvhtree' module, a general purpose module to access
27  * blenders bvhtree for mesh surface nearest-element search and ray casting.
28  */
29
30 #include <Python.h>
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_utildefines.h"
35 #include "BLI_kdopbvh.h"
36 #include "BLI_polyfill2d.h"
37 #include "BLI_math.h"
38 #include "BLI_ghash.h"
39 #include "BLI_memarena.h"
40
41 #include "BKE_bvhutils.h"
42
43 #include "../generic/py_capi_utils.h"
44 #include "../generic/python_utildefines.h"
45
46 #include "mathutils.h"
47 #include "mathutils_bvhtree.h"  /* own include */
48
49 #ifndef MATH_STANDALONE
50 #include "DNA_object_types.h"
51
52 #include "BKE_customdata.h"
53 #include "BKE_DerivedMesh.h"
54 #include "BKE_editmesh_bvh.h"
55
56 #include "bmesh.h"
57
58 #include "../bmesh/bmesh_py_types.h"
59 #endif  /* MATH_STANDALONE */
60
61
62 #include "BLI_strict_flags.h"
63
64
65 /* -------------------------------------------------------------------- */
66
67 /** \name Docstring (snippets)
68  * \{ */
69
70 #define PYBVH_FIND_GENERIC_DISTANCE_DOC \
71 "   :arg distance: Maximum distance threshold.\n" \
72 "   :type distance: float\n"
73
74 #define PYBVH_FIND_GENERIC_RETURN_DOC \
75 "   :return: Returns a tuple\n" \
76 "      (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
77 "      Values will all be None if no hit is found.\n" \
78 "   :rtype: :class:`tuple`\n"
79
80 #define PYBVH_FIND_GENERIC_RETURN_LIST_DOC \
81 "   :return: Returns a list of tuples\n" \
82 "      (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
83 "   :rtype: :class:`list`\n"
84
85 #define PYBVH_FROM_GENERIC_EPSILON_DOC \
86 "   :arg epsilon: Increase the threshold for detecting overlap and raycast hits.\n" \
87 "   :type epsilon: float\n"
88
89 /** \} */
90
91 /* sqrt(FLT_MAX) */
92 #define PYBVH_MAX_DIST_STR "1.84467e+19"
93 static const float max_dist_default = 1.844674352395373e+19f;
94
95 static const char PY_BVH_TREE_TYPE_DEFAULT = 4;
96 static const char PY_BVH_AXIS_DEFAULT = 6;
97
98 typedef struct {
99         PyObject_HEAD
100         BVHTree *tree;
101         float epsilon;
102
103         float (*coords)[3];
104         unsigned int (*tris)[3];
105         unsigned int coords_len, tris_len;
106
107         /* Optional members */
108         /* aligned with 'tris' */
109         int *orig_index;
110         /* aligned with array that 'orig_index' points to */
111         float (*orig_normal)[3];
112 } PyBVHTree;
113
114
115 /* -------------------------------------------------------------------- */
116
117 /** \name Utility helper functions
118  * \{ */
119
120 static PyObject *bvhtree_CreatePyObject(
121         BVHTree *tree, float epsilon,
122
123         float (*coords)[3], unsigned int coords_len,
124         unsigned int (*tris)[3], unsigned int tris_len,
125
126         /* optional arrays */
127         int *orig_index, float (*orig_normal)[3])
128 {
129         PyBVHTree *result = PyObject_New(PyBVHTree, &PyBVHTree_Type);
130
131         result->tree = tree;
132         result->epsilon = epsilon;
133
134         result->coords = coords;
135         result->tris = tris;
136         result->coords_len = coords_len;
137         result->tris_len = tris_len;
138
139         result->orig_index = orig_index;
140         result->orig_normal = orig_normal;
141
142         return (PyObject *)result;
143 }
144
145 /** \} */
146
147
148 /* -------------------------------------------------------------------- */
149
150 /** \name BVHTreeRayHit to Python utilities
151  * \{ */
152
153 static void py_bvhtree_raycast_to_py_tuple(const BVHTreeRayHit *hit, PyObject *py_retval)
154 {
155         BLI_assert(hit->index >= 0);
156         BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
157
158         PyTuple_SET_ITEMS(py_retval,
159                 Vector_CreatePyObject(hit->co, 3, NULL),
160                 Vector_CreatePyObject(hit->no, 3, NULL),
161                 PyLong_FromLong(hit->index),
162                 PyFloat_FromDouble(hit->dist));
163
164 }
165
166 static PyObject *py_bvhtree_raycast_to_py(const BVHTreeRayHit *hit)
167 {
168         PyObject *py_retval = PyTuple_New(4);
169
170         py_bvhtree_raycast_to_py_tuple(hit, py_retval);
171
172         return py_retval;
173 }
174
175 static PyObject *py_bvhtree_raycast_to_py_none(void)
176 {
177         PyObject *py_retval = PyTuple_New(4);
178
179         PyC_Tuple_Fill(py_retval, Py_None);
180
181         return py_retval;
182 }
183
184 #if 0
185 static PyObject *py_bvhtree_raycast_to_py_and_check(const BVHTreeRayHit *hit)
186 {
187         PyObject *py_retval;
188
189         py_retval = PyTuple_New(4);
190
191         if (hit->index != -1) {
192                 py_bvhtree_raycast_to_py_tuple(hit, py_retval);
193         }
194         else {
195                 PyC_Tuple_Fill(py_retval, Py_None);
196         }
197
198         return py_retval;
199 }
200 #endif
201
202 /** \} */
203
204
205 /* -------------------------------------------------------------------- */
206
207 /** \name BVHTreeNearest to Python utilities
208  * \{ */
209
210 static void py_bvhtree_nearest_to_py_tuple(const BVHTreeNearest *nearest, PyObject *py_retval)
211 {
212         BLI_assert(nearest->index >= 0);
213         BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
214
215         PyTuple_SET_ITEMS(py_retval,
216                 Vector_CreatePyObject(nearest->co, 3, NULL),
217                 Vector_CreatePyObject(nearest->no, 3, NULL),
218                 PyLong_FromLong(nearest->index),
219                 PyFloat_FromDouble(sqrtf(nearest->dist_sq)));
220
221 }
222
223 static PyObject *py_bvhtree_nearest_to_py(const BVHTreeNearest *nearest)
224 {
225         PyObject *py_retval = PyTuple_New(4);
226
227         py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
228
229         return py_retval;
230 }
231
232 static PyObject *py_bvhtree_nearest_to_py_none(void)
233 {
234         PyObject *py_retval = PyTuple_New(4);
235
236         PyC_Tuple_Fill(py_retval, Py_None);
237
238         return py_retval;
239 }
240
241 #if 0
242 static PyObject *py_bvhtree_nearest_to_py_and_check(const BVHTreeNearest *nearest)
243 {
244         PyObject *py_retval;
245
246         py_retval = PyTuple_New(4);
247
248         if (nearest->index != -1) {
249                 py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
250         }
251         else {
252                 PyC_Tuple_Fill(py_retval, Py_None);
253         }
254
255         return py_retval;
256 }
257 #endif
258
259 /** \} */
260
261 static void py_bvhtree__tp_dealloc(PyBVHTree *self)
262 {
263         if (self->tree) {
264                 BLI_bvhtree_free(self->tree);
265         }
266
267         MEM_SAFE_FREE(self->coords);
268         MEM_SAFE_FREE(self->tris);
269
270         MEM_SAFE_FREE(self->orig_index);
271         MEM_SAFE_FREE(self->orig_normal);
272
273         Py_TYPE(self)->tp_free((PyObject *)self);
274 }
275
276
277 /* -------------------------------------------------------------------- */
278
279 /** \name Methods
280  * \{ */
281
282 static void py_bvhtree_raycast_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
283 {
284         const PyBVHTree *self = userdata;
285
286         const float (*coords)[3] = (const float (*)[3])self->coords;
287         const unsigned int *tri = self->tris[index];
288         const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
289         float dist;
290
291         if (self->epsilon == 0.0f) {
292                 dist = bvhtree_ray_tri_intersection(ray, hit->dist, UNPACK3(tri_co));
293         }
294         else {
295                 dist = bvhtree_sphereray_tri_intersection(ray, self->epsilon, hit->dist, UNPACK3(tri_co));
296         }
297
298         if (dist >= 0 && dist < hit->dist) {
299                 hit->index = self->orig_index ? self->orig_index[index] : index;
300                 hit->dist = dist;
301                 madd_v3_v3v3fl(hit->co, ray->origin, ray->direction, dist);
302                 if (self->orig_normal) {
303                         copy_v3_v3(hit->no, self->orig_normal[hit->index]);
304                 }
305                 else {
306                         normal_tri_v3(hit->no, UNPACK3(tri_co));
307                 }
308         }
309 }
310
311 static void py_bvhtree_nearest_point_cb(void *userdata, int index, const float co[3], BVHTreeNearest *nearest)
312 {
313         PyBVHTree *self = userdata;
314
315         const float (*coords)[3] = (const float (*)[3])self->coords;
316         const unsigned int *tri = self->tris[index];
317         const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
318         float nearest_tmp[3], dist_sq;
319
320         closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
321         dist_sq = len_squared_v3v3(co, nearest_tmp);
322
323         if (dist_sq < nearest->dist_sq) {
324                 nearest->index = self->orig_index ? self->orig_index[index] : index;
325                 nearest->dist_sq = dist_sq;
326                 copy_v3_v3(nearest->co, nearest_tmp);
327                 if (self->orig_normal) {
328                         copy_v3_v3(nearest->no, self->orig_normal[nearest->index]);
329                 }
330                 else {
331                         normal_tri_v3(nearest->no, UNPACK3(tri_co));
332                 }
333         }
334 }
335
336 PyDoc_STRVAR(py_bvhtree_ray_cast_doc,
337 ".. method:: ray_cast(origin, direction, distance=sys.float_info.max)\n"
338 "\n"
339 "   Cast a ray onto the mesh.\n"
340 "\n"
341 "   :arg co: Start location of the ray in object space.\n"
342 "   :type co: :class:`Vector`\n"
343 "   :arg direction: Direction of the ray in object space.\n"
344 "   :type direction: :class:`Vector`\n"
345 PYBVH_FIND_GENERIC_DISTANCE_DOC
346 PYBVH_FIND_GENERIC_RETURN_DOC
347 );
348 static PyObject *py_bvhtree_ray_cast(PyBVHTree *self, PyObject *args)
349 {
350         const char *error_prefix = "ray_cast";
351         float co[3], direction[3];
352         float max_dist = FLT_MAX;
353         BVHTreeRayHit hit;
354
355         /* parse args */
356         {
357                 PyObject *py_co, *py_direction;
358
359                 if (!PyArg_ParseTuple(
360                         args, (char *)"OO|f:ray_cast",
361                         &py_co, &py_direction, &max_dist))
362                 {
363                         return NULL;
364                 }
365
366                 if ((mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) ||
367                     (mathutils_array_parse(direction, 2, 3 | MU_ARRAY_ZERO, py_direction, error_prefix) == -1))
368                 {
369                         return NULL;
370                 }
371
372                 normalize_v3(direction);
373         }
374
375         hit.dist = max_dist;
376         hit.index = -1;
377
378         /* may fail if the mesh has no faces, in that case the ray-cast misses */
379         if (self->tree) {
380                 if (BLI_bvhtree_ray_cast(
381                         self->tree, co, direction, 0.0f, &hit,
382                         py_bvhtree_raycast_cb, self) != -1)
383                 {
384                         return py_bvhtree_raycast_to_py(&hit);
385                 }
386         }
387
388         return py_bvhtree_raycast_to_py_none();
389 }
390
391 PyDoc_STRVAR(py_bvhtree_find_nearest_doc,
392 ".. method:: find_nearest(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
393 "\n"
394 "   Find the nearest element to a point.\n"
395 "\n"
396 "   :arg co: Find nearest element to this point.\n"
397 "   :type co: :class:`Vector`\n"
398 PYBVH_FIND_GENERIC_DISTANCE_DOC
399 PYBVH_FIND_GENERIC_RETURN_DOC
400 );
401 static PyObject *py_bvhtree_find_nearest(PyBVHTree *self, PyObject *args)
402 {
403         const char *error_prefix = "find_nearest";
404         float co[3];
405         float max_dist = max_dist_default;
406
407         BVHTreeNearest nearest;
408
409         /* parse args */
410         {
411                 PyObject *py_co;
412
413                 if (!PyArg_ParseTuple(
414                         args, (char *)"O|f:find_nearest",
415                         &py_co, &max_dist))
416                 {
417                         return NULL;
418                 }
419
420                 if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
421                         return NULL;
422                 }
423         }
424
425         nearest.index = -1;
426         nearest.dist_sq = max_dist * max_dist;
427
428         /* may fail if the mesh has no faces, in that case the ray-cast misses */
429         if (self->tree) {
430                 if (BLI_bvhtree_find_nearest(
431                         self->tree, co, &nearest,
432                         py_bvhtree_nearest_point_cb, self) != -1)
433                 {
434                         return py_bvhtree_nearest_to_py(&nearest);
435                 }
436         }
437
438         return py_bvhtree_nearest_to_py_none();
439 }
440
441 struct PyBVH_RangeData {
442         PyBVHTree *self;
443         PyObject *result;
444         float dist_sq;
445 };
446
447 static void py_bvhtree_nearest_point_range_cb(void *userdata, int index, const float co[3], float UNUSED(dist_sq_bvh))
448 {
449         struct PyBVH_RangeData *data = userdata;
450         PyBVHTree *self = data->self;
451
452         const float (*coords)[3] = (const float (*)[3])self->coords;
453         const unsigned int *tri = self->tris[index];
454         const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
455         float nearest_tmp[3], dist_sq;
456
457         closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
458         dist_sq = len_squared_v3v3(co, nearest_tmp);
459
460         if (dist_sq < data->dist_sq) {
461                 BVHTreeNearest nearest;
462                 nearest.index = self->orig_index ? self->orig_index[index] : index;
463                 nearest.dist_sq = dist_sq;
464                 copy_v3_v3(nearest.co, nearest_tmp);
465                 if (self->orig_normal) {
466                         copy_v3_v3(nearest.no, self->orig_normal[nearest.index]);
467                 }
468                 else {
469                         normal_tri_v3(nearest.no, UNPACK3(tri_co));
470                 }
471
472                 PyList_APPEND(data->result, py_bvhtree_nearest_to_py(&nearest));
473         }
474 }
475
476 PyDoc_STRVAR(py_bvhtree_find_nearest_range_doc,
477 ".. method:: find_nearest_range(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
478 "\n"
479 "   Find the nearest elements to a point in the distance range.\n"
480 "\n"
481 "   :arg co: Find nearest elements to this point.\n"
482 "   :type co: :class:`Vector`\n"
483 PYBVH_FIND_GENERIC_DISTANCE_DOC
484 PYBVH_FIND_GENERIC_RETURN_LIST_DOC
485 );
486 static PyObject *py_bvhtree_find_nearest_range(PyBVHTree *self, PyObject *args)
487 {
488         const char *error_prefix = "find_nearest_range";
489         float co[3];
490         float max_dist = max_dist_default;
491
492         /* parse args */
493         {
494                 PyObject *py_co;
495
496                 if (!PyArg_ParseTuple(
497                         args, (char *)"O|f:find_nearest_range",
498                         &py_co, &max_dist))
499                 {
500                         return NULL;
501                 }
502
503                 if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
504                         return NULL;
505                 }
506         }
507
508         PyObject *ret = PyList_New(0);
509
510         if (self->tree) {
511                 struct PyBVH_RangeData data = {
512                         .self = self,
513                         .result = ret,
514                         .dist_sq = SQUARE(max_dist),
515                 };
516
517                 BLI_bvhtree_range_query(
518                         self->tree, co, max_dist,
519                         py_bvhtree_nearest_point_range_cb, &data);
520         }
521
522         return ret;
523 }
524
525
526 BLI_INLINE unsigned int overlap_hash(const void *overlap_v)
527 {
528         const BVHTreeOverlap *overlap = overlap_v;
529         /* same constants as edge-hash */
530         return (((unsigned int)overlap->indexA * 65) ^ ((unsigned int)overlap->indexA * 31));
531 }
532
533 BLI_INLINE bool overlap_cmp(const void *a_v, const void *b_v)
534 {
535         const BVHTreeOverlap *a = a_v;
536         const BVHTreeOverlap *b = b_v;
537         return (memcmp(a, b, sizeof(*a)) != 0);
538 }
539
540 struct PyBVHTree_OverlapData {
541         PyBVHTree *tree_pair[2];
542         float epsilon;
543 };
544
545 static bool py_bvhtree_overlap_cb(void *userdata, int index_a, int index_b, int UNUSED(thread))
546 {
547         struct PyBVHTree_OverlapData *data = userdata;
548         PyBVHTree *tree_a = data->tree_pair[0];
549         PyBVHTree *tree_b = data->tree_pair[1];
550         const unsigned int *tri_a = tree_a->tris[index_a];
551         const unsigned int *tri_b = tree_b->tris[index_b];
552         const float *tri_a_co[3] = {tree_a->coords[tri_a[0]], tree_a->coords[tri_a[1]], tree_a->coords[tri_a[2]]};
553         const float *tri_b_co[3] = {tree_b->coords[tri_b[0]], tree_b->coords[tri_b[1]], tree_b->coords[tri_b[2]]};
554         float ix_pair[2][3];
555         int verts_shared = 0;
556
557         if (tree_a == tree_b) {
558                 if (UNLIKELY(index_a == index_b)) {
559                         return false;
560                 }
561
562                 verts_shared = (
563                         ELEM(tri_a_co[0], UNPACK3(tri_b_co)) +
564                         ELEM(tri_a_co[1], UNPACK3(tri_b_co)) +
565                         ELEM(tri_a_co[2], UNPACK3(tri_b_co)));
566
567                 /* if 2 points are shared, bail out */
568                 if (verts_shared >= 2) {
569                         return false;
570                 }
571         }
572
573         return (isect_tri_tri_epsilon_v3(UNPACK3(tri_a_co), UNPACK3(tri_b_co), ix_pair[0], ix_pair[1], data->epsilon) &&
574                 ((verts_shared == 0) || (len_squared_v3v3(ix_pair[0], ix_pair[1]) > data->epsilon)));
575 }
576
577 PyDoc_STRVAR(py_bvhtree_overlap_doc,
578 ".. method:: overlap(other_tree)\n"
579 "\n"
580 "   Find overlapping indices between 2 trees.\n"
581 "\n"
582 "   :arg other_tree: Other tree to preform overlap test on.\n"
583 "   :type other_tree: :class:`BVHTree`\n"
584 "   :return: Returns a list of unique index pairs,"
585 "      the first index referencing this tree, the second referencing the **other_tree**.\n"
586 "   :rtype: :class:`list`\n"
587 );
588 static PyObject *py_bvhtree_overlap(PyBVHTree *self, PyBVHTree *other)
589 {
590         struct PyBVHTree_OverlapData data;
591         BVHTreeOverlap *overlap;
592         unsigned int overlap_len = 0;
593         PyObject *ret;
594
595         if (!PyBVHTree_CheckExact(other)) {
596                 PyErr_SetString(PyExc_ValueError, "Expected a BVHTree argument");
597                 return NULL;
598         }
599
600         data.tree_pair[0] = self;
601         data.tree_pair[1] = other;
602         data.epsilon = max_ff(self->epsilon, other->epsilon);
603
604         overlap = BLI_bvhtree_overlap(self->tree, other->tree, &overlap_len, py_bvhtree_overlap_cb, &data);
605
606         ret = PyList_New(0);
607
608         if (overlap == NULL) {
609                 /* pass */
610         }
611         else {
612                 bool use_unique = (self->orig_index || other->orig_index);
613                 GSet *pair_test = use_unique ? BLI_gset_new_ex(overlap_hash, overlap_cmp, __func__, overlap_len) : NULL;
614                 /* simple case, no index remapping */
615                 unsigned int i;
616
617                 for (i = 0; i < overlap_len; i++) {
618                         PyObject *item;
619                         if (use_unique) {
620                                 if (self->orig_index) {
621                                         overlap[i].indexA = self->orig_index[overlap[i].indexA];
622                                 }
623                                 if (other->orig_index) {
624                                         overlap[i].indexB = other->orig_index[overlap[i].indexB];
625                                 }
626
627                                 /* skip if its already added */
628                                 if (!BLI_gset_add(pair_test, &overlap[i])) {
629                                         continue;
630                                 }
631                         }
632
633                         item = PyTuple_New(2);
634                         PyTuple_SET_ITEMS(item,
635                                 PyLong_FromLong(overlap[i].indexA),
636                                 PyLong_FromLong(overlap[i].indexB));
637
638                         PyList_Append(ret, item);
639                         Py_DECREF(item);
640                 }
641
642                 if (pair_test) {
643                         BLI_gset_free(pair_test, NULL);
644                 }
645         }
646
647         if (overlap) {
648                 MEM_freeN(overlap);
649         }
650
651         return ret;
652 }
653
654 /** \} */
655
656
657 /* -------------------------------------------------------------------- */
658
659 /** \name Class Methods
660  * \{ */
661
662 PyDoc_STRVAR(C_BVHTree_FromPolygons_doc,
663 ".. classmethod:: FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)\n"
664 "\n"
665 "   BVH tree constructed geometry passed in as arguments.\n"
666 "\n"
667 "   :arg vertices: float triplets each representing ``(x, y, z)``\n"
668 "   :type vertices: float triplet sequence\n"
669 "   :arg polygons: Sequence of polyugons, each containing indices to the vertices argument.\n"
670 "   :type polygons: Sequence of sequences containing ints\n"
671 "   :arg all_triangles: Use when all **polygons** are triangles for more efficient conversion.\n"
672 "   :type all_triangles: bool\n"
673 PYBVH_FROM_GENERIC_EPSILON_DOC
674 );
675 static PyObject *C_BVHTree_FromPolygons(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
676 {
677         const char *error_prefix = "BVHTree.FromPolygons";
678         const char *keywords[] = {"vertices", "polygons", "all_triangles", "epsilon", NULL};
679
680         PyObject *py_coords, *py_tris;
681         PyObject *py_coords_fast = NULL, *py_tris_fast = NULL;
682
683         MemArena *poly_arena = NULL;
684         MemArena *pf_arena = NULL;
685
686         float (*coords)[3] = NULL;
687         unsigned int (*tris)[3] = NULL;
688         unsigned int coords_len, tris_len;
689         float epsilon = 0.0f;
690         bool all_triangles = false;
691
692         /* when all_triangles is False */
693         int *orig_index = NULL;
694         float (*orig_normal)[3] = NULL;
695
696         unsigned int i;
697         bool valid = true;
698
699
700         if (!PyArg_ParseTupleAndKeywords(
701                 args, kwargs, (char *)"OO|$O&f:BVHTree.FromPolygons", (char **)keywords,
702                 &py_coords, &py_tris,
703                 PyC_ParseBool, &all_triangles,
704                 &epsilon))
705         {
706                 return NULL;
707         }
708
709         if (!(py_coords_fast = PySequence_Fast(py_coords, error_prefix)) ||
710             !(py_tris_fast  = PySequence_Fast(py_tris, error_prefix)))
711         {
712                 Py_XDECREF(py_coords_fast);
713                 return NULL;
714         }
715
716         if (valid) {
717                 PyObject **py_coords_fast_items = PySequence_Fast_ITEMS(py_coords_fast);
718                 coords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_coords_fast);
719                 coords = MEM_mallocN((size_t)coords_len * sizeof(*coords), __func__);
720
721                 for (i = 0; i < coords_len; i++) {
722                         PyObject *py_vert = py_coords_fast_items[i];
723
724                         if (mathutils_array_parse(coords[i], 3, 3, py_vert, "BVHTree vertex: ") == -1) {
725                                 valid = false;
726                                 break;
727                         }
728                 }
729         }
730
731         if (valid == false) {
732                 /* pass */
733         }
734         else if (all_triangles) {
735                 /* all triangles, simple case */
736                 PyObject **py_tris_fast_items = PySequence_Fast_ITEMS(py_tris_fast);
737                 tris_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
738                 tris = MEM_mallocN((size_t)tris_len * sizeof(*tris), __func__);
739
740                 for (i = 0; i < tris_len; i++) {
741                         PyObject *py_tricoords = py_tris_fast_items[i];
742                         PyObject *py_tricoords_fast;
743                         PyObject **py_tricoords_fast_items;
744                         unsigned int *tri = tris[i];
745                         int j;
746
747                         if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
748                                 valid = false;
749                                 break;
750                         }
751
752                         if (PySequence_Fast_GET_SIZE(py_tricoords_fast) != 3) {
753                                 Py_DECREF(py_tricoords_fast);
754                                 PyErr_Format(PyExc_ValueError,
755                                              "%s: non triangle found at index %d with length of %d",
756                                              error_prefix, i, PySequence_Fast_GET_SIZE(py_tricoords_fast));
757                                 valid = false;
758                                 break;
759                         }
760
761                         py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
762
763                         for (j = 0; j < 3; j++) {
764                                 tri[j] = (unsigned int)_PyLong_AsInt(py_tricoords_fast_items[j]);
765                                 if (UNLIKELY(tri[j] >= (unsigned int)coords_len)) {
766                                         PyErr_Format(PyExc_ValueError,
767                                                      "%s: index %d must be less than %d",
768                                                      error_prefix, tri[j], coords_len);
769
770                                         /* decref below */
771                                         valid = false;
772                                         break;
773                                 }
774                         }
775
776                         Py_DECREF(py_tricoords_fast);
777                 }
778         }
779         else {
780                 /* ngon support (much more involved) */
781                 const unsigned int polys_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
782                 struct PolyLink {
783                         struct PolyLink *next;
784                         unsigned int len;
785                         unsigned int poly[0];
786                 } *plink_first = NULL, **p_plink_prev = &plink_first, *plink = NULL;
787                 int poly_index;
788
789                 tris_len = 0;
790
791                 poly_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
792
793                 for (i = 0; i < polys_len; i++) {
794                         PyObject *py_tricoords = PySequence_Fast_GET_ITEM(py_tris_fast, i);
795                         PyObject *py_tricoords_fast;
796                         PyObject **py_tricoords_fast_items;
797                         unsigned int py_tricoords_len;
798                         unsigned int j;
799
800                         if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
801                                 valid = false;
802                                 break;
803                         }
804
805                         py_tricoords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tricoords_fast);
806                         py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
807
808                         plink = BLI_memarena_alloc(poly_arena, sizeof(*plink) + (sizeof(int) * (size_t)py_tricoords_len));
809
810                         plink->len = (unsigned int)py_tricoords_len;
811                         *p_plink_prev = plink;
812                         p_plink_prev = &plink->next;
813
814                         for (j = 0; j < py_tricoords_len; j++) {
815                                 plink->poly[j] = (unsigned int)_PyLong_AsInt(py_tricoords_fast_items[j]);
816                                 if (UNLIKELY(plink->poly[j] >= (unsigned int)coords_len)) {
817                                         PyErr_Format(PyExc_ValueError,
818                                                      "%s: index %d must be less than %d",
819                                                      error_prefix, plink->poly[j], coords_len);
820                                         /* decref below */
821                                         valid = false;
822                                         break;
823                                 }
824                         }
825
826                         Py_DECREF(py_tricoords_fast);
827
828                         if (py_tricoords_len >= 3) {
829                                 tris_len += (py_tricoords_len - 2);
830                         }
831                 }
832                 *p_plink_prev = NULL;
833
834                 /* all ngon's are parsed, now tessellate */
835
836                 pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
837                 tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
838
839                 orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
840                 orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)polys_len, __func__);
841
842                 for (plink = plink_first, poly_index = 0, i = 0; plink; plink = plink->next, poly_index++) {
843                         if (plink->len == 3) {
844                                 unsigned int *tri = tris[i];
845                                 memcpy(tri, plink->poly, sizeof(unsigned int[3]));
846                                 orig_index[i] = poly_index;
847                                 normal_tri_v3(orig_normal[poly_index], coords[tri[0]], coords[tri[1]], coords[tri[2]]);
848                                 i++;
849                         }
850                         else if (plink->len > 3) {
851                                 float (*proj_coords)[2] = BLI_memarena_alloc(pf_arena, sizeof(*proj_coords) * plink->len);
852                                 float *normal = orig_normal[poly_index];
853                                 const float *co_prev;
854                                 const float *co_curr;
855                                 float axis_mat[3][3];
856                                 unsigned int (*tris_offset)[3] = &tris[i];
857                                 unsigned int j;
858
859                                 /* calc normal and setup 'proj_coords' */
860                                 zero_v3(normal);
861                                 co_prev = coords[plink->poly[plink->len - 1]];
862                                 for (j = 0; j < plink->len; j++) {
863                                         co_curr = coords[plink->poly[j]];
864                                         add_newell_cross_v3_v3v3(normal, co_prev, co_curr);
865                                         co_prev = co_curr;
866                                 }
867                                 normalize_v3(normal);
868
869                                 axis_dominant_v3_to_m3_negate(axis_mat, normal);
870
871                                 for (j = 0; j < plink->len; j++) {
872                                         mul_v2_m3v3(proj_coords[j], axis_mat, coords[plink->poly[j]]);
873                                 }
874
875                                 BLI_polyfill_calc_arena((const float (*)[2])proj_coords, plink->len, 1, tris_offset, pf_arena);
876
877                                 j = plink->len - 2;
878                                 while (j--) {
879                                         unsigned int *tri = tris_offset[j];
880                                         /* remap to global indices */
881                                         tri[0] = plink->poly[tri[0]];
882                                         tri[1] = plink->poly[tri[1]];
883                                         tri[2] = plink->poly[tri[2]];
884
885                                         orig_index[i] = poly_index;
886                                         i++;
887                                 }
888
889                                 BLI_memarena_clear(pf_arena);
890                         }
891                         else {
892                                 zero_v3(orig_normal[poly_index]);
893                         }
894                 }
895         }
896
897         Py_DECREF(py_coords_fast);
898         Py_DECREF(py_tris_fast);
899
900         if (pf_arena) {
901                 BLI_memarena_free(pf_arena);
902         }
903
904         if (poly_arena) {
905                 BLI_memarena_free(poly_arena);
906         }
907
908         if (valid) {
909                 BVHTree *tree;
910
911                 tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
912                 if (tree) {
913                         for (i = 0; i < tris_len; i++) {
914                                 float co[3][3];
915
916                                 copy_v3_v3(co[0], coords[tris[i][0]]);
917                                 copy_v3_v3(co[1], coords[tris[i][1]]);
918                                 copy_v3_v3(co[2], coords[tris[i][2]]);
919
920                                 BLI_bvhtree_insert(tree, (int)i, co[0], 3);
921                         }
922
923                         BLI_bvhtree_balance(tree);
924                 }
925
926                 return bvhtree_CreatePyObject(
927                         tree, epsilon,
928                         coords, coords_len,
929                         tris, tris_len,
930                         orig_index, orig_normal);
931         }
932         else {
933                 if (coords)
934                         MEM_freeN(coords);
935                 if (tris)
936                         MEM_freeN(tris);
937
938                 return NULL;
939         }
940 }
941
942
943 #ifndef MATH_STANDALONE
944
945 PyDoc_STRVAR(C_BVHTree_FromBMesh_doc,
946 ".. classmethod:: FromBMesh(bmesh, epsilon=0.0)\n"
947 "\n"
948 "   BVH tree based on :class:`BMesh` data.\n"
949 "\n"
950 "   :arg bmesh: BMesh data.\n"
951 "   :type bmesh: :class:`BMesh`\n"
952 PYBVH_FROM_GENERIC_EPSILON_DOC
953 );
954 static PyObject *C_BVHTree_FromBMesh(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
955 {
956         const char *keywords[] = {"bmesh", "epsilon", NULL};
957
958         BPy_BMesh *py_bm;
959
960         float (*coords)[3] = NULL;
961         unsigned int (*tris)[3] = NULL;
962         unsigned int coords_len, tris_len;
963         float epsilon = 0.0f;
964
965         BMesh *bm;
966         BMLoop *(*looptris)[3];
967
968         if (!PyArg_ParseTupleAndKeywords(
969                 args, kwargs, (char *)"O!|$f:BVHTree.FromBMesh", (char **)keywords,
970                 &BPy_BMesh_Type, &py_bm, &epsilon))
971         {
972                 return NULL;
973         }
974
975         bm = py_bm->bm;
976
977         /* Get data for tessellation */
978         {
979                 int tris_len_dummy;
980
981                 coords_len = (unsigned int)bm->totvert;
982                 tris_len = (unsigned int)poly_to_tri_count(bm->totface, bm->totloop);
983
984                 coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
985                 tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
986
987                 looptris = MEM_mallocN(sizeof(*looptris) * (size_t)tris_len, __func__);
988
989                 BM_mesh_calc_tessellation(bm, looptris, &tris_len_dummy);
990                 BLI_assert(tris_len_dummy == (int)tris_len);
991         }
992
993         {
994                 BMIter iter;
995                 BVHTree *tree;
996                 unsigned int i;
997
998                 int *orig_index = NULL;
999                 float (*orig_normal)[3] = NULL;
1000
1001                 tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
1002                 if (tree) {
1003                         BMFace *f;
1004                         BMVert *v;
1005
1006                         orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
1007                         orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)bm->totface, __func__);
1008
1009                         BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
1010                                 copy_v3_v3(coords[i], v->co);
1011                                 BM_elem_index_set(v, (int)i);  /* set_inline */
1012                         }
1013                         BM_ITER_MESH_INDEX (f, &iter, bm, BM_FACES_OF_MESH, i) {
1014                                 copy_v3_v3(orig_normal[i], f->no);
1015                                 BM_elem_index_set(f, (int)i);  /* set_inline */
1016                         }
1017                         bm->elem_index_dirty &= (char)~(BM_VERT | BM_FACE);
1018
1019                         for (i = 0; i < tris_len; i++) {
1020                                 float co[3][3];
1021
1022                                 tris[i][0] = (unsigned int)BM_elem_index_get(looptris[i][0]->v);
1023                                 tris[i][1] = (unsigned int)BM_elem_index_get(looptris[i][1]->v);
1024                                 tris[i][2] = (unsigned int)BM_elem_index_get(looptris[i][2]->v);
1025
1026                                 copy_v3_v3(co[0], coords[tris[i][0]]);
1027                                 copy_v3_v3(co[1], coords[tris[i][1]]);
1028                                 copy_v3_v3(co[2], coords[tris[i][2]]);
1029
1030                                 BLI_bvhtree_insert(tree, (int)i, co[0], 3);
1031                                 orig_index[i] = BM_elem_index_get(looptris[i][0]->f);
1032                         }
1033
1034                         BLI_bvhtree_balance(tree);
1035                 }
1036
1037                 MEM_freeN(looptris);
1038
1039                 return bvhtree_CreatePyObject(
1040                         tree, epsilon,
1041                         coords, coords_len,
1042                         tris, tris_len,
1043                         orig_index, orig_normal);
1044         }
1045 }
1046
1047 /* return various derived meshes based on requested settings */
1048 static DerivedMesh *bvh_get_derived_mesh(
1049         const char *funcname, struct Scene *scene, Object *ob,
1050         bool use_deform, bool use_render, bool use_cage)
1051 {
1052         /* TODO: This doesn't work currently because of eval_ctx. */
1053 #if 0
1054         /* we only need minimum mesh data for topology and vertex locations */
1055         CustomDataMask mask = CD_MASK_BAREMESH;
1056
1057         /* Write the display mesh into the dummy mesh */
1058         if (use_deform) {
1059                 if (use_render) {
1060                         if (use_cage) {
1061                                 PyErr_Format(PyExc_ValueError,
1062                                              "%s(...): cage arg is unsupported when (render=True)", funcname);
1063                                 return NULL;
1064                         }
1065                         else {
1066                                 return mesh_create_derived_render(scene, ob, mask);
1067                         }
1068                 }
1069                 else {
1070                         if (use_cage) {
1071                                 return mesh_get_derived_deform(scene, ob, mask);  /* ob->derivedDeform */
1072                         }
1073                         else {
1074                                 return mesh_get_derived_final(scene, ob, mask);  /* ob->derivedFinal */
1075                         }
1076                 }
1077         }
1078         else {
1079                 /* !use_deform */
1080                 if (use_render) {
1081                         if (use_cage) {
1082                                 PyErr_Format(PyExc_ValueError,
1083                                              "%s(...): cage arg is unsupported when (render=True)", funcname);
1084                                 return NULL;
1085                         }
1086                         else {
1087                                 return mesh_create_derived_no_deform_render(scene, ob, NULL, mask);
1088                         }
1089                 }
1090                 else {
1091                         if (use_cage) {
1092                                 PyErr_Format(PyExc_ValueError,
1093                                              "%s(...): cage arg is unsupported when (deform=False, render=False)", funcname);
1094                                 return NULL;
1095                         }
1096                         else {
1097                                 return mesh_create_derived_no_deform(scene, ob, NULL, mask);
1098                         }
1099                 }
1100         }
1101 #endif
1102
1103         return NULL;
1104 }
1105
1106 PyDoc_STRVAR(C_BVHTree_FromObject_doc,
1107 ".. classmethod:: FromObject(object, scene, deform=True, render=False, cage=False, epsilon=0.0)\n"
1108 "\n"
1109 "   BVH tree based on :class:`Object` data.\n"
1110 "\n"
1111 "   :arg object: Object data.\n"
1112 "   :type object: :class:`Object`\n"
1113 "   :arg scene: Scene data to use for evaluating the mesh.\n"
1114 "   :type scene: :class:`Scene`\n"
1115 "   :arg deform: Use mesh with deformations.\n"
1116 "   :type deform: bool\n"
1117 "   :arg render: Use render settings.\n"
1118 "   :type render: bool\n"
1119 "   :arg cage: Use render settings.\n"
1120 "   :type cage: bool\n"
1121 PYBVH_FROM_GENERIC_EPSILON_DOC
1122 );
1123 static PyObject *C_BVHTree_FromObject(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
1124 {
1125         /* note, options here match 'bpy_bmesh_from_object' */
1126         const char *keywords[] = {"object", "scene",  "deform", "render", "cage", "epsilon", NULL};
1127
1128         PyObject *py_ob, *py_scene;
1129         Object *ob;
1130         struct Scene *scene;
1131         DerivedMesh *dm;
1132         bool use_deform = true;
1133         bool use_render = false;
1134         bool use_cage = false;
1135
1136         const MLoopTri *lt;
1137         const MLoop *mloop;
1138
1139         float (*coords)[3] = NULL;
1140         unsigned int (*tris)[3] = NULL;
1141         unsigned int coords_len, tris_len;
1142         float epsilon = 0.0f;
1143
1144         if (!PyArg_ParseTupleAndKeywords(
1145                 args, kwargs, (char *)"OO|$O&O&O&f:BVHTree.FromObject", (char **)keywords,
1146                 &py_ob, &py_scene,
1147                 PyC_ParseBool, &use_deform,
1148                 PyC_ParseBool, &use_render,
1149                 PyC_ParseBool, &use_cage,
1150                 &epsilon) ||
1151             ((ob = PyC_RNA_AsPointer(py_ob, "Object")) == NULL) ||
1152             ((scene = PyC_RNA_AsPointer(py_scene, "Scene")) == NULL))
1153         {
1154                 return NULL;
1155         }
1156
1157         dm = bvh_get_derived_mesh("BVHTree", scene, ob, use_deform, use_render, use_cage);
1158         if (dm == NULL) {
1159                 return NULL;
1160         }
1161
1162         /* Get data for tessellation */
1163         {
1164                 DM_ensure_looptri(dm);
1165                 lt = dm->getLoopTriArray(dm);
1166
1167                 tris_len = (unsigned int)dm->getNumLoopTri(dm);
1168                 coords_len = (unsigned int)dm->getNumVerts(dm);
1169
1170                 coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
1171                 tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
1172
1173                 dm->getVertCos(dm, coords);
1174
1175                 mloop = dm->getLoopArray(dm);
1176         }
1177
1178         {
1179                 BVHTree *tree;
1180                 unsigned int i;
1181
1182                 int *orig_index = NULL;
1183                 float (*orig_normal)[3] = NULL;
1184
1185                 tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
1186                 if (tree) {
1187                         orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
1188                         orig_normal = dm->getPolyDataArray(dm, CD_NORMAL);  /* can be NULL */
1189                         if (orig_normal) {
1190                                 orig_normal = MEM_dupallocN(orig_normal);
1191                         }
1192
1193                         for (i = 0; i < tris_len; i++, lt++) {
1194                                 float co[3][3];
1195
1196                                 tris[i][0] = mloop[lt->tri[0]].v;
1197                                 tris[i][1] = mloop[lt->tri[1]].v;
1198                                 tris[i][2] = mloop[lt->tri[2]].v;
1199
1200                                 copy_v3_v3(co[0], coords[tris[i][0]]);
1201                                 copy_v3_v3(co[1], coords[tris[i][1]]);
1202                                 copy_v3_v3(co[2], coords[tris[i][2]]);
1203
1204                                 BLI_bvhtree_insert(tree, (int)i, co[0], 3);
1205                                 orig_index[i] = (int)lt->poly;
1206                         }
1207
1208                         BLI_bvhtree_balance(tree);
1209                 }
1210
1211                 dm->release(dm);
1212
1213                 return bvhtree_CreatePyObject(
1214                         tree, epsilon,
1215                         coords, coords_len,
1216                         tris, tris_len,
1217                         orig_index, orig_normal);
1218         }
1219 }
1220 #endif  /* MATH_STANDALONE */
1221
1222 /** \} */
1223
1224
1225 /* -------------------------------------------------------------------- */
1226
1227 /** \name Module & Type definition
1228  * \{ */
1229
1230 static PyMethodDef py_bvhtree_methods[] = {
1231         {"ray_cast", (PyCFunction)py_bvhtree_ray_cast, METH_VARARGS, py_bvhtree_ray_cast_doc},
1232         {"find_nearest", (PyCFunction)py_bvhtree_find_nearest, METH_VARARGS, py_bvhtree_find_nearest_doc},
1233         {"find_nearest_range", (PyCFunction)py_bvhtree_find_nearest_range, METH_VARARGS, py_bvhtree_find_nearest_range_doc},
1234         {"overlap", (PyCFunction)py_bvhtree_overlap, METH_O, py_bvhtree_overlap_doc},
1235
1236         /* class methods */
1237         {"FromPolygons", (PyCFunction) C_BVHTree_FromPolygons, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromPolygons_doc},
1238 #ifndef MATH_STANDALONE
1239         {"FromBMesh", (PyCFunction) C_BVHTree_FromBMesh, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromBMesh_doc},
1240         {"FromObject", (PyCFunction) C_BVHTree_FromObject, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromObject_doc},
1241 #endif
1242         {NULL, NULL, 0, NULL}
1243 };
1244
1245 PyTypeObject PyBVHTree_Type = {
1246         PyVarObject_HEAD_INIT(NULL, 0)
1247         "BVHTree",                                   /* tp_name */
1248         sizeof(PyBVHTree),                           /* tp_basicsize */
1249         0,                                           /* tp_itemsize */
1250         /* methods */
1251         (destructor)py_bvhtree__tp_dealloc,          /* tp_dealloc */
1252         NULL,                                        /* tp_print */
1253         NULL,                                        /* tp_getattr */
1254         NULL,                                        /* tp_setattr */
1255         NULL,                                        /* tp_compare */
1256         NULL,                                        /* tp_repr */
1257         NULL,                                        /* tp_as_number */
1258         NULL,                                        /* tp_as_sequence */
1259         NULL,                                        /* tp_as_mapping */
1260         NULL,                                        /* tp_hash */
1261         NULL,                                        /* tp_call */
1262         NULL,                                        /* tp_str */
1263         NULL,                                        /* tp_getattro */
1264         NULL,                                        /* tp_setattro */
1265         NULL,                                        /* tp_as_buffer */
1266         Py_TPFLAGS_DEFAULT,                          /* tp_flags */
1267         NULL,                                        /* Documentation string */
1268         NULL,                                        /* tp_traverse */
1269         NULL,                                        /* tp_clear */
1270         NULL,                                        /* tp_richcompare */
1271         0,                                           /* tp_weaklistoffset */
1272         NULL,                                        /* tp_iter */
1273         NULL,                                        /* tp_iternext */
1274         py_bvhtree_methods,                          /* tp_methods */
1275         NULL,                                        /* tp_members */
1276         NULL,                                        /* tp_getset */
1277         NULL,                                        /* tp_base */
1278         NULL,                                        /* tp_dict */
1279         NULL,                                        /* tp_descr_get */
1280         NULL,                                        /* tp_descr_set */
1281         0,                                           /* tp_dictoffset */
1282         NULL,                                        /* tp_init */
1283         (allocfunc)PyType_GenericAlloc,              /* tp_alloc */
1284         (newfunc)PyType_GenericNew,                  /* tp_new */
1285         (freefunc)0,                                 /* tp_free */
1286         NULL,                                        /* tp_is_gc */
1287         NULL,                                        /* tp_bases */
1288         NULL,                                        /* tp_mro */
1289         NULL,                                        /* tp_cache */
1290         NULL,                                        /* tp_subclasses */
1291         NULL,                                        /* tp_weaklist */
1292         (destructor) NULL                            /* tp_del */
1293 };
1294
1295 /* -------------------------------------------------------------------- */
1296 /* Module definition */
1297
1298 PyDoc_STRVAR(py_bvhtree_doc,
1299 "BVH tree structures for proximity searches and ray casts on geometry."
1300 );
1301 static struct PyModuleDef bvhtree_moduledef = {
1302         PyModuleDef_HEAD_INIT,
1303         "mathutils.bvhtree",                         /* m_name */
1304         py_bvhtree_doc,                              /* m_doc */
1305         0,                                           /* m_size */
1306         NULL,                                        /* m_methods */
1307         NULL,                                        /* m_reload */
1308         NULL,                                        /* m_traverse */
1309         NULL,                                        /* m_clear */
1310         NULL                                         /* m_free */
1311 };
1312
1313 PyMODINIT_FUNC PyInit_mathutils_bvhtree(void)
1314 {
1315         PyObject *m = PyModule_Create(&bvhtree_moduledef);
1316
1317         if (m == NULL) {
1318                 return NULL;
1319         }
1320
1321         /* Register classes */
1322         if (PyType_Ready(&PyBVHTree_Type) < 0) {
1323                 return NULL;
1324         }
1325
1326         PyModule_AddObject(m, "BVHTree", (PyObject *)&PyBVHTree_Type);
1327
1328         return m;
1329 }
1330
1331 /** \} */