Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mathutils_kdtree.c « mathutils « python « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 519778aea7dd6a907b174c78d10ed3dc855863c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contributor(s): Dan Eicher, Campbell Barton
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/python/mathutils/mathutils_kdtree.c
 *  \ingroup mathutils
 *
 * This file defines the 'mathutils.kdtree' module, a general purpose module to access
 * blenders kdtree for 3d spatial lookups.
 */

#include <Python.h>

#include "MEM_guardedalloc.h"

#include "BLI_utildefines.h"
#include "BLI_kdtree.h"

#include "../generic/py_capi_utils.h"

#include "mathutils.h"
#include "mathutils_kdtree.h"  /* own include */

#include "BLI_strict_flags.h"

typedef struct {
	PyObject_HEAD
	KDTree *obj;
	unsigned int maxsize;
	unsigned int count;
	unsigned int count_balance;  /* size when we last balanced */
} PyKDTree;


/* -------------------------------------------------------------------- */
/* Utility helper functions */

static void kdtree_nearest_to_py_tuple(const KDTreeNearest *nearest, PyObject *py_retval)
{
	BLI_assert(nearest->index >= 0);
	BLI_assert(PyTuple_GET_SIZE(py_retval) == 3);

	PyTuple_SET_ITEM(py_retval, 0, Vector_CreatePyObject((float *)nearest->co, 3, Py_NEW, NULL));
	PyTuple_SET_ITEM(py_retval, 1, PyLong_FromLong(nearest->index));
	PyTuple_SET_ITEM(py_retval, 2, PyFloat_FromDouble(nearest->dist));
}

static PyObject *kdtree_nearest_to_py(const KDTreeNearest *nearest)
{
	PyObject *py_retval;

	py_retval = PyTuple_New(3);

	kdtree_nearest_to_py_tuple(nearest, py_retval);

	return py_retval;
}

static PyObject *kdtree_nearest_to_py_and_check(const KDTreeNearest *nearest)
{
	PyObject *py_retval;

	py_retval = PyTuple_New(3);

	if (nearest->index != -1) {
		kdtree_nearest_to_py_tuple(nearest, py_retval);
	}
	else {
		PyC_Tuple_Fill(py_retval, Py_None);
	}

	return py_retval;
}


/* -------------------------------------------------------------------- */
/* KDTree */

/* annoying since arg parsing won't check overflow */
#define UINT_IS_NEG(n) ((n) > INT_MAX)

static int PyKDTree__tp_init(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
	unsigned int maxsize;
	const char *keywords[] = {"size", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "I:KDTree", (char **)keywords, &maxsize)) {
		return -1;
	}

	if (UINT_IS_NEG(maxsize)) {
		PyErr_SetString(PyExc_ValueError, "negative 'size' given");
		return -1;
	}

	self->obj = BLI_kdtree_new(maxsize);
	self->maxsize = maxsize;
	self->count = 0;
	self->count_balance = 0;

	return 0;
}

static void PyKDTree__tp_dealloc(PyKDTree *self)
{
	BLI_kdtree_free(self->obj);
	Py_TYPE(self)->tp_free((PyObject *)self);
}

PyDoc_STRVAR(py_kdtree_insert_doc,
".. method:: insert(index, co)\n"
"\n"
"   Insert a point into the KDTree.\n"
"\n"
"   :arg co: Point 3d position.\n"
"   :type co: float triplet\n"
"   :arg index: The index of the point.\n"
"   :type index: int\n"
);
static PyObject *py_kdtree_insert(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
	PyObject *py_co;
	float co[3];
	int index;
	const char *keywords[] = {"co", "index", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "Oi:insert", (char **)keywords,
	                                 &py_co, &index))
	{
		return NULL;
	}

	if (mathutils_array_parse(co, 3, 3, py_co, "insert: invalid 'co' arg") == -1)
		return NULL;

	if (index < 0) {
		PyErr_SetString(PyExc_ValueError, "negative index given");
		return NULL;
	}

	if (self->count >= self->maxsize) {
		PyErr_SetString(PyExc_RuntimeError, "Trying to insert more items than KDTree has room for");
		return NULL;
	}

	BLI_kdtree_insert(self->obj, index, co);
	self->count++;

	Py_RETURN_NONE;
}

PyDoc_STRVAR(py_kdtree_balance_doc,
".. method:: balance()\n"
"\n"
"   Balance the tree.\n"
);
static PyObject *py_kdtree_balance(PyKDTree *self)
{
	BLI_kdtree_balance(self->obj);
	self->count_balance = self->count;
	Py_RETURN_NONE;
}

PyDoc_STRVAR(py_kdtree_find_doc,
".. method:: find(co)\n"
"\n"
"   Find nearest point to ``co``.\n"
"\n"
"   :arg co: 3d coordinates.\n"
"   :type co: float triplet\n"
"   :return: Returns (:class:`Vector`, index, distance).\n"
"   :rtype: :class:`tuple`\n"
);
static PyObject *py_kdtree_find(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
	PyObject *py_co;
	float co[3];
	KDTreeNearest nearest;
	const char *keywords[] = {"co", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "O:find", (char **)keywords,
	                                 &py_co))
	{
		return NULL;
	}

	if (mathutils_array_parse(co, 3, 3, py_co, "find: invalid 'co' arg") == -1)
		return NULL;

	if (self->count != self->count_balance) {
		PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find()");
		return NULL;
	}


	nearest.index = -1;

	BLI_kdtree_find_nearest(self->obj, co, &nearest);

	return kdtree_nearest_to_py_and_check(&nearest);
}

PyDoc_STRVAR(py_kdtree_find_n_doc,
".. method:: find_n(co, n)\n"
"\n"
"   Find nearest ``n`` points to ``co``.\n"
"\n"
"   :arg co: 3d coordinates.\n"
"   :type co: float triplet\n"
"   :arg n: Number of points to find.\n"
"   :type n: int\n"
"   :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
"   :rtype: :class:`list`\n"
);
static PyObject *py_kdtree_find_n(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
	PyObject *py_list;
	PyObject *py_co;
	float co[3];
	KDTreeNearest *nearest;
	unsigned int n;
	int i, found;
	const char *keywords[] = {"co", "n", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "OI:find_n", (char **)keywords,
	                                 &py_co, &n))
	{
		return NULL;
	}

	if (mathutils_array_parse(co, 3, 3, py_co, "find_n: invalid 'co' arg") == -1)
		return NULL;

	if (UINT_IS_NEG(n)) {
		PyErr_SetString(PyExc_RuntimeError, "negative 'n' given");
		return NULL;
	}

	if (self->count != self->count_balance) {
		PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_n()");
		return NULL;
	}

	nearest = MEM_mallocN(sizeof(KDTreeNearest) * n, __func__);

	found = BLI_kdtree_find_nearest_n(self->obj, co, nearest, n);

	py_list = PyList_New(found);

	for (i = 0; i < found; i++) {
		PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
	}

	MEM_freeN(nearest);

	return py_list;
}

PyDoc_STRVAR(py_kdtree_find_range_doc,
".. method:: find_range(co, radius)\n"
"\n"
"   Find all points within ``radius`` of ``co``.\n"
"\n"
"   :arg co: 3d coordinates.\n"
"   :type co: float triplet\n"
"   :arg radius: Distance to search for points.\n"
"   :type radius: float\n"
"   :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
"   :rtype: :class:`list`\n"
);
static PyObject *py_kdtree_find_range(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
	PyObject *py_list;
	PyObject *py_co;
	float co[3];
	KDTreeNearest *nearest = NULL;
	float radius;
	int i, found;

	const char *keywords[] = {"co", "radius", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "Of:find_range", (char **)keywords,
	                                 &py_co, &radius))
	{
		return NULL;
	}

	if (mathutils_array_parse(co, 3, 3, py_co, "find_range: invalid 'co' arg") == -1)
		return NULL;

	if (radius < 0.0f) {
		PyErr_SetString(PyExc_RuntimeError, "negative radius given");
		return NULL;
	}

	if (self->count != self->count_balance) {
		PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_range()");
		return NULL;
	}

	found = BLI_kdtree_range_search(self->obj, co, &nearest, radius);

	py_list = PyList_New(found);

	for (i = 0; i < found; i++) {
		PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
	}

	if (nearest) {
		MEM_freeN(nearest);
	}

	return py_list;
}


static PyMethodDef PyKDTree_methods[] = {
	{"insert", (PyCFunction)py_kdtree_insert, METH_VARARGS | METH_KEYWORDS, py_kdtree_insert_doc},
	{"balance", (PyCFunction)py_kdtree_balance, METH_NOARGS, py_kdtree_balance_doc},
	{"find", (PyCFunction)py_kdtree_find, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_doc},
	{"find_n", (PyCFunction)py_kdtree_find_n, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_n_doc},
	{"find_range", (PyCFunction)py_kdtree_find_range, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_range_doc},
	{NULL, NULL, 0, NULL}
};

PyDoc_STRVAR(py_KDtree_doc,
"KdTree(size) -> new kd-tree initialized to hold ``size`` items.\n"
"\n"
".. note::\n"
"\n"
"   :class:`KDTree.balance` must have been called before using any of the ``find`` methods.\n"
);
PyTypeObject PyKDTree_Type = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"KDTree",                                    /* tp_name */
	sizeof(PyKDTree),                            /* tp_basicsize */
	0,                                           /* tp_itemsize */
	/* methods */
	(destructor)PyKDTree__tp_dealloc,            /* tp_dealloc */
	NULL,                                        /* tp_print */
	NULL,                                        /* tp_getattr */
	NULL,                                        /* tp_setattr */
	NULL,                                        /* tp_compare */
	NULL,                                        /* tp_repr */
	NULL,                                        /* tp_as_number */
	NULL,                                        /* tp_as_sequence */
	NULL,                                        /* tp_as_mapping */
	NULL,                                        /* tp_hash */
	NULL,                                        /* tp_call */
	NULL,                                        /* tp_str */
	NULL,                                        /* tp_getattro */
	NULL,                                        /* tp_setattro */
	NULL,                                        /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,                          /* tp_flags */
	py_KDtree_doc,                               /* Documentation string */
	NULL,                                        /* tp_traverse */
	NULL,                                        /* tp_clear */
	NULL,                                        /* tp_richcompare */
	0,                                           /* tp_weaklistoffset */
	NULL,                                        /* tp_iter */
	NULL,                                        /* tp_iternext */
	(struct PyMethodDef *)PyKDTree_methods,      /* tp_methods */
	NULL,                                        /* tp_members */
	NULL,                                        /* tp_getset */
	NULL,                                        /* tp_base */
	NULL,                                        /* tp_dict */
	NULL,                                        /* tp_descr_get */
	NULL,                                        /* tp_descr_set */
	0,                                           /* tp_dictoffset */
	(initproc)PyKDTree__tp_init,                 /* tp_init */
	(allocfunc)PyType_GenericAlloc,              /* tp_alloc */
	(newfunc)PyType_GenericNew,                  /* tp_new */
	(freefunc)0,                                 /* tp_free */
	NULL,                                        /* tp_is_gc */
	NULL,                                        /* tp_bases */
	NULL,                                        /* tp_mro */
	NULL,                                        /* tp_cache */
	NULL,                                        /* tp_subclasses */
	NULL,                                        /* tp_weaklist */
	(destructor) NULL                            /* tp_del */
};

PyDoc_STRVAR(py_kdtree_doc,
"Generic 3-dimentional kd-tree to perform spatial searches."
);
static struct PyModuleDef kdtree_moduledef = {
	PyModuleDef_HEAD_INIT,
	"mathutils.kdtree",                          /* m_name */
	py_kdtree_doc,                               /* m_doc */
	0,                                           /* m_size */
	NULL,                                        /* m_methods */
	NULL,                                        /* m_reload */
	NULL,                                        /* m_traverse */
	NULL,                                        /* m_clear */
	NULL                                         /* m_free */
};

PyMODINIT_FUNC PyInit_mathutils_kdtree(void)
{
	PyObject *m = PyModule_Create(&kdtree_moduledef);

	if (m == NULL) {
		return NULL;
	}

	/* Register the 'KDTree' class */
	if (PyType_Ready(&PyKDTree_Type)) {
		return NULL;
	}
	PyModule_AddObject(m, "KDTree", (PyObject *) &PyKDTree_Type);

	return m;
}