/*
 * SelectPointsFromSamples
 * -----------------------
 * 
 *   Converts UV selection from texture editor
 * into geometry points selection.
 *
 * USAGE:
 *   1) Select some UVs in texture editor
 *   2) Run this script
 *   3) Switch selection mode to "point" to see
 *      the results
 *
 * -by bartek-
 * bartekd@o2.pl
 */

SelectPointsFromSamples();

function SelectPointsFromSamples()
{

  if(Selection.Count==0) {
    logmessage("Selection empty", siError);
    return;
  }
  var sel = Selection(0);
  if(sel.type!="sampleSubComponent") {
    logmessage("Please select only UVs", siError);
    return;
  }
      // ok here's the weird stuff
      // it seems the only way to retrieve *full* object
      // name from "sampleSubComponent" is to parse the
      // string it returns.

  var rxresult = String(sel).match(/(.+)\.sample/);

  var obj = ActiveProject.ActiveScene.Root.FindChild(rxresult[1], "", "", true); 

  var sa = new VBArray(sel.subelements).toArray();
  var uvp = obj.Material.CurrentUV; //uv property
  var spc = uvp.Parent;     //sample cluster

  var nima = new Array();     //node index mask array
  for(var i=0; i<sa.length; i++)
    nima[spc.Elements(sa[i])] = true;

  var geo = obj.ActivePrimitive.Geometry;
  var ep = new Enumerator(geo.Points);
  var res = new Array();
  for(; !ep.atEnd(); ep.moveNext()) {
    var pnt = ep.item();
    var es = new Enumerator(pnt.Samples);
    for(; !es.atEnd(); es.moveNext()) {
      var ps = es.item();
      if(nima[ps.index]) {
        res.push(pnt.Index);
        break;
      }
    }
  }
  SelectGeometryComponents(obj+".pnt["+res+"]");  
}
