I make efforts to study kdTree but get the wrong result. I return indexes that I did not expect.
Please tell me what my mistake is.
Video example - http://take.ms/UX1nm
import bpy
import bmesh
import bgl
import blf
from bpy.types import Operator
from bpy_extras import view3d_utils
from mathutils import Vector, Matrix, kdtree
def GetCoordMouse(self, context, event):
'''Get Coordinate Mouse in 3d view'''
#scene = context.scene
region = context.region
rv3d = context.region_data
coord = event.mouse_region_x, event.mouse_region_y
#rv3d.view_rotation * Vector((0.0, 0.0, 0.0))
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
loc = view3d_utils.region_2d_to_location_3d(region, rv3d, coord, view_vector)
act_obj = context.active_object
matrix_obj = act_obj.matrix_world
loc = matrix_obj.inverted() * loc
return loc
class TetsKD(Operator):
bl_idname = "view3d.test_kd"
bl_label = "Test KD"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls,context):
#return context.mode == "EDIT_MESH" and context.object is not None and context.object.type == "MESH"
return context.space_data.type == "VIEW_3D"
# ______________________________INVOKE________________________________#
>
def invoke(self,context, event):
if context.space_data.type == 'VIEW_3D':
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "Active space must be a View3d")
return {'CANCELLED'}
#______________________________MODAL________________________________#
def modal(self, context, event):
if event.type == 'MOUSEMOVE':
#self.me = context.active_object.data
self.me = context.object.data
#self.bm = bmesh.new()
self.bm = bmesh.from_edit_mesh(self.me)
#self.bm.from_mesh(self.me)
self.size = len(self.bm.verts)
self.kd = kdtree.KDTree(self.size)
for i, vtx in enumerate(self.bm.verts):
self.kd.insert(vtx.co, i)
self.kd.balance()
self.loc = GetCoordMouse(self, context, event)
dist = self.kd.find_range(self.loc, 2.0)
print("index = ", dist[1])
return {'RUNNING_MODAL'}
elif event.type in {'RIGHTMOUSE', 'ESC'}:
return {'FINISHED'}
self.report({'WARNING'}, "Active space must be a View3d")
return {'RUNNING_MODAL'}
def register():
bpy.utils.register_module(__name__)
def unregister():
bpy.utils.unregister_module(__name__)
if __name__ == "__main__":
register()