Hi all,
I’m displaying random points on a 2D canvas and would like (for each one of them) to get the coordinates of the nearest grid vertices.
To find the nearest vertices I’m using Delaunay triangulation.
-
I put all the points (grid vertices + random points) in an array list (
allpList
) and use the Triangulate library to operate the triangulation. I end-up with a new array list (triangles
) containing all the triangles and their vertices. -
Then, I look for the triangles with at least one vertex placed at the random point locations.
The problem occurs when I try to sort-out the nearest grid points.
- Out of the 3 vertices of each selected triangle, I keep the 2 that are not placed at the location of the random point (in red)
However, for some reason, that sorting part doesn’t work well and my final array list (nearestpList
) is still filled with (some, not all) random points
for t in triangles: #list of triangles
for i, p in enumerate(rdmpList): #list of random points
#if the triangle 1st vertex == a random point location, then select 2nd and 3rd vertex
if t.p1 == p:
nearestpList.append(PVector(t.p2.x, t.p2.y))
nearestpList.append(PVector(t.p3.x, t.p3.y))
#if the triangle 2nd vertex == a random point location, then select 1st and 3rd vertex
if t.p2 == p:
nearestpList.append(PVector(t.p1.x, t.p1.y))
nearestpList.append(PVector(t.p3.x, t.p3.y))
#if the triangle 3rd vertex == a random point location, then select 1st and 2nd vertex
if t.p3 == p:
nearestpList.append(PVector(t.p1.x, t.p1.y))
nearestpList.append(PVector(t.p2.x, t.p2.y))
I suspect the logic of that final sorting step to be flawed (some triangles may have 2 vertices corresponding to random points location, not only one like I stated) but cannot figure out how to fix it.
Would really appreciate your help.
code (in Python)
Summary
add_library('triangulate')
from java.util import ArrayList
allpList, rdmpList, nearestpList = ArrayList(), [], []
step, edge = 20, 60
def setup():
size(1000, 1000, P2D)
background(255)
smooth(8)
#Adding grid points (vertices) to array list
for y in range(edge, width, step):
for x in range(edge, height, step):
allpList.add(PVector(x, y))
#Adding random points to array list
#Also adding them to a seperate list (rdmpList)
for e in range(256):
p = PVector(random(edge, width-edge), random(edge, height-edge))
allpList.add(p)
rdmpList.append(p)
#Triangulating all the points in the array list
triangles = Triangulate.triangulate(allpList)
#Sorting-out nearest grid vertices
for t in triangles:
for i, p in enumerate(rdmpList):
if t.p1 == p:
nearestpList.append(PVector(t.p2.x, t.p2.y))
nearestpList.append(PVector(t.p3.x, t.p3.y))
if t.p2 == p:
nearestpList.append(PVector(t.p1.x, t.p1.y))
nearestpList.append(PVector(t.p3.x, t.p3.y))
if t.p3 == p:
nearestpList.append(PVector(t.p1.x, t.p1.y))
nearestpList.append(PVector(t.p2.x, t.p2.y))
strokeWeight(5)
for p in nearestpList: point(p.x, p.y)