mathutils.bvhtree.BVHTree has FromBMesh and FromObject for fast BVH tree construction, but not mathutils.kdtree.KDTree.

Inserting a large number of vertices using “insert” will take a lot of processing time.

Is it possible to implement FormBmesh and FromObject in kdtree as well?

To construct BVH Tree it requires polygons and vertices. Constructing KD Tree only requires vertices. may be that’s why it doesn’t have those functions.

You can create those functions like this:

```
import bpy
import bmesh
import mathutils
def KDTree_FromBMesh(bm):
size = len(bm.verts)
kdTree = mathutils.kdtree.KDTree(size)
for v in bm.verts:
kdTree.insert(v.co, v.index)
kdTree.balance()
return kdTree
def KDTree_FromObject(object):
mesh = object.data
size = len(mesh.vertices)
kdTree = mathutils.kdtree.KDTree(size)
for v in mesh.vertices:
kdTree.insert(v.co, v.index)
kdTree.balance()
return kdTree
```

1 Like

Thanks for the answer.

However, for models with a large number of vertices, iterating in Python can be very costly.

FromBMesh and FromObject are needed to solve this problem.