your naive algorithm checks all verts of one mesh against all verts of another which is slow and inefficient
to make it faster you’ll have to use some accelerating structure
little interactive example:
struct Lookup2DGrid
(
_minx = 1e6,
_miny = 1e6,
_maxx = -1e6,
_maxy = -1e6,
_min = [0,0,0],
_max = [0,0,0],
width,
height,
step,
size = [0,0],
points,
lookup2D,
fn init pts gridsize =
(
for p in pts where p != undefined do
(
if p.x < _minx then _minx = p.x else (if p.x > _maxx do _maxx = p.x)
if p.y < _miny then _miny = p.y else (if p.y > _maxy do _maxy = p.y)
)
_min = [ _minx, _miny, 0 ]
_max = [ _maxx, _maxy, 0 ]
points = pts
width = _maxx - _minx
height = _maxy - _miny
step = gridsize
size = [ceil (width / step) , ceil (height / step)]
lookup2D = for i=1 to size.x collect (for j=1 to size.y collect #())
for i=1 to pts.count where pts[i] != undefined do
(
index_x = 1 + int((pts[i].x - _minx)/step)
index_y = 1 + int((pts[i].y - _miny)/step)
append lookup2D[ index_x ][ index_y ] i
)
),
fn getNearestNeighbors pt offset:1 =
(
index_x = 1 + (floor((pt.x - _minx)/step))
index_y = 1 + (floor((pt.y - _miny)/step))
indexes = #()
for x = amax 1 (index_x-offset) to amin (index_x + offset) size.x do
(
for y = amax 1 (index_y-offset) to amin (index_y + offset) size.y do join indexes lookup2D[ x ][ y ]
)
indexes
),
fn getNearestIndex pt =
(
mind = 1e6
index = -1
for i in getNearestNeighbors pt where (d = distance pt points[i]) < mind do (mind = d; index = i)
index
),
fn getMinDistance pt =
(
mind = 1e6
indexes = getNearestNeighbors pt
if indexes.count == 0 do return -1
for i in indexes where (d = distance pt points[i]) < mind do mind = d
mind
)
)
delete objects
gc light:true
actionMan.executeAction 0 "551"
p = plane widthsegments:12 lengthsegments:12 wirecolor:black
convertToPoly p
rotate p (EulerAngles 0 0 23.5)
lg = Lookup2DGrid()
lg.init (for i=1 to polyop.getNumVerts p collect polyop.getVert p i) 2.0
move_me = point centermarker:on cross:off wirecolor:yellow isSelected:true
h2 = point wirecolor:red
deleteAllChangeHandlers id:#xxx
when transform move_me change id:#xxx val do
(
nearest_index = lg.getNearestIndex val.pos
if nearest_index > 0 do
(
h2.pos = lg.points[ nearest_index ]
)
)
btw. What’s the best way to find closest grid cell to arbitrary point in space?