VEX: nested loops doesn't work as espected

   3294   2   1
User Avatar
Member
4 posts
Joined: June 2016
Offline
Hi!
I have a VEX program to connect those yellow points (grouped as “loosepts”) to its closest point in the mesh.
And it cannot be connected to another yellow point “loosepts”, nor to any of those points outside the red circle (“outerpts” point
group).


So, to prevent those situations, I added a simple if() statement inside the for() loop that searches for the closest point.

int pts = npoints(0);
int closestpt = -1;
float mindist = 0.0;

for(int i = 0; i< pts; i++){//run over all pts
    
    int isouterpts = inpointgroup(0,"outerpts",i);
    int isloosepts = inpointgroup(0,"loosepts",i);

    //filter some points
    if(i == @ptnum || isouterpts==1 || isloosepts==1){
        continue;
    }
        //vars
        vector cP = point(0,"P",i);
        float curdist = distance(@P,cP);
        
        if(i == 0){//assign mindist
            mindist = curdist;
            closestpt = i;
        }
        else if(curdist < mindist){
            mindist = curdist;
            closestpt = i;
        }
    
}

printf("mindist: %f\nclosestpt: %d\n\n", mindist,closestpt);

if(closestpt != -1){
    //connect current point to closestpt
    int newprim = addprim(0,"polyline");
    addvertex(0,newprim, @ptnum);
    addvertex(0,newprim, closestpt);
}

The problem is that this code never finds a closest point, and never changes the “closestpt” variable, so it never runs the connection algorythm.
What have I done wrong?

The question is also if VEX nested loops and if() statements run in a particular way I'm not aware of
I'm having problem with this kind of code since weeks ago and can't find help

Attachments:
debugging-nested-loops.jpg (216.9 KB)


Best regards,
Antônio Souza
User Avatar
Member
8772 posts
Joined: July 2007
Offline
if pt 0 is in any of your excluded points then your mindist is never initialised and your closestpt stays -1

so change
if(i == 0){//assign mindist
    mindist = curdist;
    closestpt = i;
}
to
if(closestpt == -1){//assign mindist
    mindist = curdist;
    closestpt = i;
}

also I wouldn't loop through all the points
you can use nearpoint() to get closest point within specified group, so in your case group that doesn't contain loosepts outerpts or current point
so all you need is to run this in PointWrangle that runs on loosepts group
string group = "!loosepts ^outerpts ^" + itoa(@ptnum);
int closestpt = nearpoint(0, group, @P);

if(closestpt != -1){
    int newprim = addprim(0,"polyline");
    addvertex(0,newprim, @ptnum);
    addvertex(0,newprim, closestpt);
}
Edited by tamte - April 12, 2018 11:23:13
Tomas Slancik
FX Supervisor
Method Studios, NY
User Avatar
Member
4 posts
Joined: June 2016
Offline
Man, this is a superb solution! haha
I learned three things I wish never forget!
I badly forgot nearpoint()! :O
Thanks, Tomas!

Best regards,
Antônio Souza
  • Quick Links