/Nearest Neighbor code
//=====================
//Maya should run thru as many frames as needed to generate the
//appropriate number of particles. Then, run this code. After it
//generates the text file, rewind Maya and run the particle position
//gatherer as needed.
  
global proc float getDistance(int $myID, string $particleShapeName, int $compareID){
  
    string $ptName = $particleShapeName + ".pt[" + $myID + "]";
    float $position1[] = `getParticleAttr -at position -array true $ptName`;
    
    $ptName = $particleShapeName + ".pt[" + $compareID + "]";
    float $position2[] = `getParticleAttr -at position -array true $ptName`;
    
    float $tmpX = $position1[0]-$position2[0];
    float $tmpZ = $position1[2]-$position2[2];
    
    if ($tmpX > 6 || $tmpZ > 6){
        return 1000;
        }
    if ((($tmpX * $tmpX) + ($tmpZ * $tmpZ)) > 36){
        return 1000;
        }
    
    return sqrt(($tmpX * $tmpX) + ($tmpZ * $tmpZ));
}
  
global proc findNearestID(string $particleShapeName){
  
    int $nearestID = -1;
    int $totalNumOfParticle = `getAttr ($particleShapeName +".count")`;
    print ("Checking " + $totalNumOfParticle + " particles.\n");
    $path = "/stuhome/maya/projects/vsfx705/data/particleDistance.txt";
    int $fileid = fopen($path, "w");
  
    for ($j = 0; $j < $totalNumOfParticle; $j++){
        float $nearestDistance = -1;
        for($i = 0; $i < $totalNumOfParticle; $i++){
            if($i != $j){
                float $distance = getDistance($j, $particleShapeName, $i);
                if($nearestDistance == -1 || $nearestDistance > $distance){
                    $nearestDistance = $distance;
                    $nearestID = $i;
                }
            }
        }
        $halfway = ($nearestDistance/2);
        fprint($fileid, $halfway + "\n");
    }
  
    fclose($fileid);
    print "Done with file";
  
}
  
  
  
//ParticlesToStemCurves
//=====================
//Called via the script editor to set the rest in motion
  
global proc string[] particlesToStemCurves(int $startAt, int $endAt)
{
string  $result[2];
string  $particle[] = `ls -tr "particle*"`;
  
$tnode = "\"particle1\"";
  
python("import StemCurveWriter");
python("reload(StemCurveWriter)");
  
$cmd = python("StemCurveWriter.particlesToStemCurves(" + 
                $tnode + "," + 
                $startAt +  "," +
                $endAt + ")"  );
$path = python("StemCurveWriter.writeToFile()");
  
$result[0] = $cmd;
$result[1] = $path;
return $result;
}