Example #1
0
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;

            GlobalCloud = pointCloud;


            //Initialize KDTree with three Dimentions.
            //KDTree = new KDTree<int>(3);
            /// Get Total Count Fraction to calculate Operation Percentage.
            double totc = (double)1 / GlobalCloud.Count;


            //Loop over individual RangePartitions per processor.
            for (int i = 0; i < GlobalCloud.Count; i++)
            {
                //Operation Percentage Report
                ///Safe Counter Increment.
                Interlocked.Increment(ref PointCounter);
                ///Calculate and Report Percentage.
                if (LastPercentReported < ((PointCounter * totc) * 100))
                {
                    LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                    this.ReportPercent  = LastPercentReported;
                }
                //Add Points to KDTree.
                insV_KDTree.AddPoint(new double[] { GlobalCloud[i].Location.X, GlobalCloud[i].Location.Y, GlobalCloud[i].Location.Z }, i);
            }



            //Set OutputCloud
            PointCloud newcloud = (PointCloud)pointCloud.Duplicate();


            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            pointCloud = newcloud;



            //Return True on Finish
            return(true);
        }
Example #2
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // PointCloud to meassure Distance From.
            PointCloud cloudFrom = null;
            // PointCloud/KDTree to meassure Distance From.
            Type_KDTree treeT = null;
            // Amount
            int amount = 1;
            //UserData Key String.
            string key = "CloCloD";

            if (!DA.GetData(0, ref cloudFrom))
            {
                return;
            }
            if (!DA.GetData(1, ref treeT))
            {
                return;
            }
            if (!DA.GetData(2, ref amount))
            {
                return;
            }
            if (!DA.GetData(3, ref key))
            {
                return;
            }

            Tuple <KDTree <int>, GH_Cloud> KDTreeCloud = treeT.Value;

            //Make Duplicate to make sure I dont change UserData in input Cloud.
            cloudFrom = (PointCloud)cloudFrom.Duplicate();

            //Calculate closestPoint distances between the two Clouds.
            double[] dist = KDTreeLib.CloudCloudDist(cloudFrom, KDTreeCloud, amount);

            //Add Distances to UserDictionary
            cloudFrom.UserDictionary.Set(key, dist);

            //Output
            DA.SetData(0, cloudFrom);
        }
Example #3
0
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;
            NewCloud            = new PointCloud();
            CloudPieces         = null;
            CloudPieces         = new PointCloud[ProcCount];
            DictPieces          = new object[ProcCount];
            GlobalCloud         = pointCloud;

            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));

            Dict_Utils.CastDictionary_ToArrayDouble(ref GlobalCloud);

            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();
                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;

                /// Initialize Partial Dictionary Lists
                List <double>[] MyDict = new List <double> [GlobalCloud.UserDictionary.Count];
                //Get Dictionary Values from PointCloud
                List <double[]> GlobalDict = new List <double[]>();
                GlobalDict.Clear();

                if (GlobalCloud.UserDictionary.Count > 0)
                {
                    Dict_Utils.Initialize_Dictionary(ref GlobalDict, ref MyDict, GlobalCloud);
                    //Loop over individual RangePartitions per processor.
                    for (int i = rng.Item1; i < rng.Item2; i++)
                    {
                        //Operation Percentage Report
                        ///Safe Counter Increment.
                        Interlocked.Increment(ref PointCounter);
                        ///Calculate and Report Percentage.
                        if (LastPercentReported < ((PointCounter * totc) * 100))
                        {
                            LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                            this.ReportPercent  = LastPercentReported;
                        }

                        //
                        if (insV_InsideBool)
                        {
                            for (int j = 0; j <= insV_Box.Count - 1; j += 1)
                            {
                                PointCloudItem GlobalCloudItem = GlobalCloud[i];
                                if (Math_Utils.IsInBox(GlobalCloudItem.Location, insV_Box[j]))
                                {
                                    Cloud_Utils.AddItem_FromOtherCloud(ref MyCloud, GlobalCloud, i);
                                    Dict_Utils.AddItem_FromGlobalDict(ref MyDict, GlobalDict, i);
                                    break; // TODO: might not be correct. Was : Exit For
                                }
                            }
                        }
                        else
                        {
                            List <Boolean> CropBools       = new List <Boolean>();
                            PointCloudItem GlobalCloudItem = GlobalCloud[i];
                            for (int j = 0; j <= insV_Box.Count - 1; j += 1)
                            {
                                CropBools.Add(Math_Utils.IsInBox(GlobalCloudItem.Location, insV_Box[j]));
                            }
                            bool Crop = !CropBools.Any(x => x == true);

                            if (Crop)
                            {
                                Cloud_Utils.AddItem_FromOtherCloud(ref MyCloud, GlobalCloud, i);
                                Dict_Utils.AddItem_FromGlobalDict(ref MyDict, GlobalDict, i);
                            }
                        }
                    }
                }
                else
                {
                    //Loop over individual RangePartitions per processor.
                    for (int i = rng.Item1; i < rng.Item2; i++)
                    {
                        //Operation Percentage Report
                        ///Safe Counter Increment.
                        Interlocked.Increment(ref PointCounter);
                        ///Calculate and Report Percentage.
                        if (LastPercentReported < ((PointCounter * totc) * 100))
                        {
                            LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                            this.ReportPercent  = LastPercentReported;
                        }

                        //
                        if (insV_InsideBool)
                        {
                            for (int j = 0; j <= insV_Box.Count - 1; j += 1)
                            {
                                PointCloudItem GlobalCloudItem = GlobalCloud[i];
                                if (Math_Utils.IsInBox(GlobalCloudItem.Location, insV_Box[j]))
                                {
                                    Cloud_Utils.AddItem_FromOtherCloud(ref MyCloud, GlobalCloud, i);
                                    break; // TODO: might not be correct. Was : Exit For
                                }
                            }
                        }
                        else
                        {
                            List <Boolean> CropBools       = new List <Boolean>();
                            PointCloudItem GlobalCloudItem = GlobalCloud[i];
                            for (int j = 0; j <= insV_Box.Count - 1; j += 1)
                            {
                                CropBools.Add(Math_Utils.IsInBox(GlobalCloudItem.Location, insV_Box[j]));
                            }
                            bool Crop = !CropBools.Any(x => x == true);

                            if (Crop)
                            {
                                Cloud_Utils.AddItem_FromOtherCloud(ref MyCloud, GlobalCloud, i);
                            }
                        }
                    }
                }
                //Set DictPieces.
                if (GlobalCloud.UserDictionary.Count > 0)
                {
                    DictPieces[(int)MyIndex] = MyDict;
                }

                //Add MyCloud to CloudPieces at ProcesserIndex.
                CloudPieces[(int)MyIndex] = MyCloud;

                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );



            //Merge PointCloud Pieces into One PointCloud.
            Cloud_Utils.MergeClouds(ref NewCloud, CloudPieces);

            if (GlobalCloud.UserDictionary.Count > 0)
            {
                List <double>[] NewDict = new List <double> [GlobalCloud.UserDictionary.Count];
                Dict_Utils.Merge_DictPieces(ref NewDict, DictPieces);
                Dict_Utils.SetUserDict_FromDictLists(ref NewCloud, NewDict, GlobalCloud.UserDictionary.Keys);
            }

            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            //Set OutputCloud
            pointCloud = (PointCloud)NewCloud.Duplicate();

            //Dispose of PointCloud Pieces and NewCloud.
            CloudPieces = null;
            DictPieces  = null;
            NewCloud.Dispose();


            //Return True on Finish
            return(true);
        }
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;

            if (insV_KDTree == null)
            {
                tree = KDTreeLib.ConstructKDTree(pointCloud);
            }
            else
            {
                tree = insV_KDTree;
            }

            Dict_Utils.CastDictionary_ToArrayDouble(ref pointCloud);
            GlobalCloud = pointCloud;

            NewCloud    = new PointCloud();
            CloudPieces = null;
            CloudPieces = new PointCloud[ProcCount];
            DictPieces  = new object[ProcCount];

            pts = pointCloud.GetPoints().ToList();

            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));

            Dict_Utils.CastDictionary_ToArrayDouble(ref GlobalCloud);

            //Search for NearestNeighbors per point in PointCloud. Gets the indices in the Cloud for the neighbors to each Point.
            List <double> NRange = new List <double> {
                double.MaxValue
            };

            List <int>[] idc = KDTreeLib.NearestNeighborSearch(tree, pts, NRange, insV_NumN);

            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();



                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;
                int count   = 0;
                if (GlobalCloud.UserDictionary.Count > 0)
                {
                    /// Initialize Partial Dictionary Lists
                    List <double>[] MyDict = new List <double> [GlobalCloud.UserDictionary.Count];

                    //Get Dictionary Values from PointCloud
                    List <double[]> GlobalDict = new List <double[]>();
                    GlobalDict.Clear();

                    Dict_Utils.Initialize_Dictionary(ref GlobalDict, ref MyDict, GlobalCloud);

                    //Loop over individual RangePartitions per processor.
                    for (int i = rng.Item1; i < rng.Item2; i++)
                    {
                        //Operation Percentage Report
                        ///Safe Counter Increment.
                        Interlocked.Increment(ref PointCounter);
                        ///Calculate and Report Percentage.
                        if (LastPercentReported < ((PointCounter * totc) * 100))
                        {
                            LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                            this.ReportPercent  = LastPercentReported;
                        }

                        calcNormal(idc, ref MyCloud, ref count, i);
                        Dict_Utils.AddItem_FromGlobalDict(ref MyDict, GlobalDict, i);
                    }

                    //Add MyCloud to CloudPieces at ProcesserIndex.
                    CloudPieces[(int)MyIndex] = MyCloud;
                    //Set DictPieces.
                    DictPieces[(int)MyIndex] = MyDict;
                }
                else
                {
                    //Loop over individual RangePartitions per processor.
                    for (int i = rng.Item1; i < rng.Item2; i++)
                    {
                        //Operation Percentage Report
                        ///Safe Counter Increment.
                        Interlocked.Increment(ref PointCounter);
                        ///Calculate and Report Percentage.
                        if (LastPercentReported < ((PointCounter * totc) * 100))
                        {
                            LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                            this.ReportPercent  = LastPercentReported;
                        }

                        calcNormal(idc, ref MyCloud, ref count, i);
                    }
                    //Add MyCloud to CloudPieces at ProcesserIndex.
                    CloudPieces[(int)MyIndex] = MyCloud;
                }
                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );



            //Merge PointCloud Pieces into One PointCloud.
            Cloud_Utils.MergeClouds(ref NewCloud, CloudPieces);
            if (GlobalCloud.UserDictionary.Count > 0)
            {
                List <double>[] NewDict = new List <double> [GlobalCloud.UserDictionary.Count];
                Dict_Utils.Merge_DictPieces(ref NewDict, DictPieces);
                Dict_Utils.SetUserDict_FromDictLists(ref NewCloud, NewDict, GlobalCloud.UserDictionary.Keys);
            }


            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            /*
             * //Colorize
             * if (insV_Colorize)
             * {
             *  List<double> colorValues = Color_Utils.ColorValues_Std_pos(NewCloud, insV_Key);
             *  List<Color> Colors = Color_Utils.ColorGradient_Std_GtoR();
             *
             *  Instruction.Instr_Dict_Color col = new Instruction.Instr_Dict_Color(insV_Key, colorValues, Colors, -1, 0.00);
             *  Boolean ColResult = col.Execute(ref NewCloud);
             *
             *  //Set ColorGradient UserData
             *  Color_Utils.Set_ColorGradient_Dict(ref NewCloud, Colors, colorValues);
             * }
             */

            pointCloud = (PointCloud)NewCloud.Duplicate();

            //Dispose of PointCloud Pieces and NewCloud.
            GlobalCloud.Dispose();
            NewCloud.Dispose();

            //Return True on Finish
            return(true);
        }
Example #5
0
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;

            Dict_Utils.CastDictionary_ToArrayDouble(ref pointCloud);
            GlobalCloud = pointCloud;
            NewCloud    = (PointCloud)pointCloud.Duplicate();


            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));



            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();
                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;


                //Loop over individual RangePartitions per processor.
                for (int i = rng.Item1; i < rng.Item2; i++)
                {
                    //Operation Percentage Report
                    ///Safe Counter Increment.
                    Interlocked.Increment(ref PointCounter);
                    ///Calculate and Report Percentage.
                    if (LastPercentReported < ((PointCounter * totc) * 100))
                    {
                        LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                        this.ReportPercent  = LastPercentReported;
                    }

                    //
                    Color color  = NewCloud[i].Color;
                    Color newCol = Color_Utils.Blend(color, insV_Color, insV_Pct);

                    NewCloud[i].Color = newCol;
                    //
                }



                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );



            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            //Set OutputCloud

            pointCloud = (PointCloud)NewCloud.Duplicate();

            //Dispose of PointCloud Pieces and NewCloud.
            GlobalCloud.Dispose();
            NewCloud.Dispose();

            //Return True on Finish
            return(true);
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="PointCloud"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            #region - Initialize Execution
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;
            NewCloud            = new PointCloud();
            CloudPieces         = null;
            CloudPieces         = new PointCloud[ProcCount];
            GlobalCloud         = pointCloud;


            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));

            Dict_Utils.CastDictionary_ToArrayDouble(ref GlobalCloud);


            ////
            //Initialize ColorGradient
            Interval  Itv  = new Interval();
            Bitmap    bmp  = new Bitmap(1000, 1);
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Drawing2D.ColorBlend cb = new System.Drawing.Drawing2D.ColorBlend();
            float[] pos = new float[insV_Colors.Count];

            for (int i = 0; i <= pos.Length - 1; i += 1)
            {
                pos[i] = (float)insV_Values[i];
            }

            Color[] colors = insV_Colors.ToArray();
            Array.Sort(pos, colors);
            Array.Sort(pos, pos);
            float[] normpos = new float[insV_Colors.Count];
            Itv = new Interval(pos[0], pos[pos.Length - 1]);

            for (int i = 0; i <= normpos.Length - 1; i += 1)
            {
                normpos[i] = (float)Itv.NormalizedParameterAt(pos[i]);
            }

            cb.Positions = normpos;
            cb.Colors    = colors;


            System.Drawing.Drawing2D.LinearGradientBrush lin = new System.Drawing.Drawing2D.LinearGradientBrush(rect, Color.Black, Color.Black, 0, false);
            lin.LinearColors        = colors;
            lin.InterpolationColors = cb;


            ColVal = null;
            ColVal = new Color[bmp.Width];

            int counter = 0;

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.FillRectangle(lin, rect);
                for (int i = 0; i <= bmp.Width - 1; i += 1)
                {
                    Color col = bmp.GetPixel(i, 0);
                    ColVal[counter] = col;
                    counter        += 1;
                }
            }

            ////

            //Get Dictionary Values from PointCloud
            List <double> DictVal = new List <double>();
            DictVal.AddRange((double[])GlobalCloud.UserDictionary[insV_Key]);
            //Get idx to multiply with for normalized values.
            int idx = ColVal.Length - 1;

            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();

                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;

                //Loop over individual RangePartitions per processor.
                for (int i = rng.Item1; i < rng.Item2; i++)
                {
                    //Operation Percentage Report
                    ///Safe Counter Increment.
                    Interlocked.Increment(ref PointCounter);
                    ///Calculate and Report Percentage.
                    if (LastPercentReported < ((PointCounter * totc) * 100))
                    {
                        LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                        this.ReportPercent  = LastPercentReported;
                    }
                    #endregion - End of Initialize Execution

                    #region - Code to Process on PointCloud.


                    double thisnorm = new double();
                    if (insV_Step <= 0.0)
                    {
                        thisnorm = Itv.NormalizedParameterAt(DictVal[i]);
                    }
                    else
                    {
                        thisnorm = Itv.NormalizedParameterAt((Math.Floor((DictVal[i] - Itv[0]) / insV_Step) * insV_Step) + Itv[0]);
                    }

                    Color col = new Color();
                    if (thisnorm < (0.0000000))
                    {
                        col = ColVal.First();
                    }
                    else if (thisnorm > (1.0000000)) //+ Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)
                    {
                        col = ColVal.Last();
                    }
                    else
                    {
                        col = ColVal[(int)(thisnorm * idx)];
                    }

                    if (insV_ColPct >= 0.0)
                    {
                        col = Color_Utils.Blend(GlobalCloud[i].Color, col, insV_ColPct);
                    }

                    MyCloud.Add(GlobalCloud[i].Location, col);


                    #endregion - End of Code to Process on PointCloud.
                    #region - Finalize Execution
                }



                //Add MyCloud to CloudPieces at ProcesserIndex.
                CloudPieces[(int)MyIndex] = MyCloud;

                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );


            //Merge PointCloud Pieces into One PointCloud.
            Cloud_Utils.MergeClouds(ref NewCloud, CloudPieces);

            //Set UserDictionary from DictionaryLists.
            Dict_Utils.SetUserDict_FromOtherCloud(ref NewCloud, GlobalCloud);
            //Set ColorGradient UserData
            List <double> gradVals = new List <double>();
            List <Color>  gradCols = new List <Color>();
            if (insV_Step > 0.00)
            {
                for (int i = 0; i < pos.Length; i++)
                {
                    double gradVal = (Math.Floor((pos[i] - Itv[0]) / insV_Step) * insV_Step) + Itv[0];
                    if (!gradVals.Contains(gradVal))
                    {
                        Color gradCol = ColVal[(int)(Itv.NormalizedParameterAt(gradVal) * idx)];
                        gradVals.Add(gradVal);
                        gradCols.Add(gradCol);
                    }
                }
                double lastVal = (Math.Ceiling((pos[pos.Length - 1] - Itv[0]) / insV_Step) * insV_Step) + Itv[0];
                if (!gradVals.Contains(lastVal))
                {
                    Color gradCol = ColVal[(int)(Itv.NormalizedParameterAt(pos[pos.Length - 1]) * idx)];
                    gradVals.Add(lastVal);
                    gradCols.Add(gradCol);
                }
            }
            else
            {
                gradVals = insV_Values;
                gradCols = insV_Colors;
            }

            Color_Utils.Set_ColorGradient_Dict(ref NewCloud, gradCols, gradVals);

            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            //Set OutputCloud
            pointCloud = (PointCloud)NewCloud.Duplicate();


            //Dispose of PointCloud Pieces and NewCloud.
            CloudPieces = null;
            NewCloud.Dispose();
            #endregion - End of Finalize Execution

            //Return True on Finish
            return(true);
        }
Example #7
0
        public override bool Execute(ref PointCloud pointCloud)
        {
            LastPercentReported = 0;
            PointCounter        = 0;
            NewCloud            = new PointCloud();
            CloudPieces         = null;

            CloudPieces = new PointCloud[ProcCount];

            GlobalCloud = pointCloud;

            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));

            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>

            {
                //Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();

                //Initialize Partial Dictionary Lists
                List <double>[] myDict = new List <double> [GlobalCloud.UserDictionary.Count];
                for (int L = 0; L < myDict.Length; L++)
                {
                    myDict[L] = new List <double>();
                }


                double totc = (double)1 / GlobalCloud.Count;
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));

                for (int i = rng.Item1; i < rng.Item2; i++)
                {
                    Interlocked.Increment(ref PointCounter);
                    double tmp = PointCounter * totc * 100;


                    if (LastPercentReported < ((PointCounter * totc) * 100))
                    {
                        LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                        this.ReportPercent  = LastPercentReported;
                    }

                    if (InsideBool)
                    {
                        for (int j = 0; j <= BoxCrop.Count - 1; j += 1)
                        {
                            PointCloudItem GlobalCloudItem = GlobalCloud[i];
                            if (Math_Utils.IsInBox(GlobalCloudItem.Location, BoxCrop[j]))
                            {
                                //AddPointCloudItem(ref MyCloud, GlobalCloudItem);

                                MyCloud.AppendNew();
                                PointCloudItem MyCloudItem = MyCloud[MyCloud.Count - 1];
                                MyCloudItem.Location       = GlobalCloudItem.Location;
                                if (GlobalCloud.ContainsColors)
                                {
                                    MyCloudItem.Color = GlobalCloudItem.Color;
                                }
                                if (GlobalCloud.ContainsNormals)
                                {
                                    MyCloudItem.Normal = GlobalCloudItem.Normal;
                                }
                                if (GlobalCloud.HasUserData)
                                {
                                    for (int k = 0; k < GlobalCloud.UserDictionary.Count; k++)
                                    {
                                        string key   = GlobalCloud.UserDictionary.Keys[k];
                                        double value = ((Double[])GlobalCloud.UserDictionary[key])[i];
                                        myDict[k].Add(value);
                                    }
                                }

                                break; // TODO: might not be correct. Was : Exit For
                            }
                        }
                    }


                    else
                    {
                        List <Boolean> CropBools       = new List <Boolean>();
                        PointCloudItem GlobalCloudItem = GlobalCloud[i];
                        for (int j = 0; j <= BoxCrop.Count - 1; j += 1)
                        {
                            CropBools.Add(Math_Utils.IsInBox(GlobalCloudItem.Location, BoxCrop[j]));
                        }
                        bool Crop = !CropBools.Any(x => x == true);

                        if (Crop)
                        {
                            MyCloud.AppendNew();
                            PointCloudItem MyCloudItem = MyCloud[MyCloud.Count - 1];
                            MyCloudItem.Location       = GlobalCloudItem.Location;
                            if (GlobalCloud.ContainsColors)
                            {
                                MyCloudItem.Color = GlobalCloudItem.Color;
                            }
                            if (GlobalCloud.ContainsNormals)
                            {
                                MyCloudItem.Normal = GlobalCloudItem.Normal;
                            }
                            if (GlobalCloud.HasUserData)
                            {
                                for (int k = 0; k < GlobalCloud.UserDictionary.Count; k++)
                                {
                                    string key   = GlobalCloud.UserDictionary.Keys[k];
                                    double value = ((Double[])GlobalCloud.UserDictionary[key])[i];
                                    myDict[k].Add(value);
                                }
                            }

                            //break; // TODO: might not be correct. Was : Exit For
                        }
                    }
                }

                for (int k = 0; k < myDict.Length; k++)
                {
                    string key         = GlobalCloud.UserDictionary.Keys[k];
                    double[] MyDictArr = myDict[k].ToArray();
                    MyCloud.UserDictionary.Set(key, MyDictArr);
                }


                CloudPieces[(int)MyIndex] = MyCloud;

                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );


            GlobalCloud.Dispose();
            pointCloud.Dispose();
            foreach (PointCloud pc in CloudPieces)
            {
                if (pc != null)
                {
                    NewCloud.Merge(pc);
                }


                if (pc.HasUserData)
                {
                    foreach (string key in pc.UserDictionary.Keys)
                    {
                        double[] newDict = null;

                        if (NewCloud.UserDictionary.ContainsKey(key))
                        {
                            double[]      Dict        = (double[])NewCloud.UserDictionary[key];
                            double[]      MyDict      = (double[])pc.UserDictionary[key];
                            List <Double> listNewDict = new List <double>(Dict);
                            listNewDict.AddRange(MyDict);
                            newDict = listNewDict.ToArray();
                        }
                        else
                        {
                            newDict = (double[])pc.UserDictionary[key];
                        }

                        NewCloud.UserDictionary.Set(key, newDict);

                        newDict = null;
                    }
                }
            }

            pointCloud  = (PointCloud)NewCloud.Duplicate();
            CloudPieces = null;
            NewCloud.Dispose();


            return(true);
        }
Example #8
0
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;

            Dict_Utils.CastDictionary_ToArrayDouble(ref pointCloud);
            GlobalCloud = pointCloud;
            NewCloud    = (PointCloud)pointCloud.Duplicate();

            Array.Resize(ref Distances, pointCloud.Count);
            Array.Resize(ref ApproachAngle, pointCloud.Count);

            double halfpi = Math.PI / 2;

            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));



            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();
                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;


                //Loop over individual RangePartitions per processor.
                for (int i = rng.Item1; i < rng.Item2; i++)
                {
                    //Operation Percentage Report
                    ///Safe Counter Increment.
                    Interlocked.Increment(ref PointCounter);
                    ///Calculate and Report Percentage.
                    if (LastPercentReported < ((PointCounter * totc) * 100))
                    {
                        LastPercentReported = (int)(5 * Math.Ceiling((double)(PointCounter * totc) * 20));
                        this.ReportPercent  = LastPercentReported;
                    }

                    //
                    PointCloudItem GlobalCloudItem = GlobalCloud[i];
                    Point3d p3  = GlobalCloudItem.Location;
                    Point3d pm  = new Point3d();
                    Vector3d pv = new Vector3d();

                    insV_Mesh.ClosestPoint(p3, out pm, out pv, 0);
                    double d = p3.DistanceTo(pm);

                    if (Vector3d.VectorAngle(pv, new Vector3d(pm - p3)) < halfpi)
                    {
                        d = -d;
                    }
                    Distances[i] = d;


                    if (insV_ApproachAngle)
                    {
                        Point3d pos      = (Point3d)insV_PositionPt;
                        Vector3d scanVec = new Vector3d(p3 - pos);
                        double appA      = Math.Abs(halfpi - Vector3d.VectorAngle(pv, scanVec));


                        ApproachAngle[i] = appA;
                    }
                }



                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );



            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            //Set OutputCloud
            NewCloud.UserDictionary.Set(insV_Key, Distances);
            NewCloud.UserDictionary.Set(insV_AngleKey, ApproachAngle);
            //Colorize
            if (insV_Colorize)
            {
                List <double> colorValues = Color_Utils.ColorValues_Std_negpos(NewCloud, insV_Key);
                List <Color>  Colors      = Color_Utils.ColorGradient_Std_BtoR();

                Instruction.Instr_Dict_Color col = new Instruction.Instr_Dict_Color(insV_Key, colorValues, Colors, -1, 0.00);
                Boolean ColResult = col.Execute(ref NewCloud);

                //Set ColorGradient UserData
                Color_Utils.Set_ColorGradient_Dict(ref NewCloud, Colors, colorValues);
            }


            pointCloud = (PointCloud)NewCloud.Duplicate();

            //Dispose of PointCloud Pieces and NewCloud.
            GlobalCloud.Dispose();
            NewCloud.Dispose();

            //Return True on Finish
            return(true);
        }
Example #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int ProcCount = Environment.ProcessorCount;

            Color[]  ColVal = null;
            Interval Itv    = new Interval();

            List <double> pars = new List <double>();
            List <Color>  cols = new List <Color>();

            string     strdc       = null;
            PointCloud GlobalCloud = null;

            double step = 0.0;

            if (!DA.GetData("Cloud", ref GlobalCloud))
            {
                return;
            }
            if (!DA.GetData(1, ref strdc))
            {
                return;
            }
            if (!DA.GetDataList(2, pars))
            {
                return;
            }
            if (!DA.GetDataList(3, cols))
            {
                return;
            }
            DA.GetData(4, ref step);
            ///Duplicate Point Cloud.
            PointCloud newCloud = (PointCloud)GlobalCloud.Duplicate();


            Bitmap    bmp  = new Bitmap(1000, 1);
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Drawing2D.ColorBlend cb = new System.Drawing.Drawing2D.ColorBlend();
            float[] pos = new float[cols.Count];

            for (int i = 0; i <= pos.Length - 1; i += 1)
            {
                pos[i] = (float)pars[i];
            }

            Color[] colors = cols.ToArray();
            Array.Sort(pos, colors);
            Array.Sort(pos, pos);
            float[] normpos = new float[cols.Count];
            Itv = new Interval(pos[0], pos[pos.Length - 1]);

            for (int i = 0; i <= normpos.Length - 1; i += 1)
            {
                normpos[i] = (float)Itv.NormalizedParameterAt(pos[i]);
            }

            cb.Positions = normpos;
            cb.Colors    = colors;


            System.Drawing.Drawing2D.LinearGradientBrush lin = new System.Drawing.Drawing2D.LinearGradientBrush(rect, Color.Black, Color.Black, 0, false);
            lin.LinearColors        = colors;
            lin.InterpolationColors = cb;


            ColVal = null;
            ColVal = new Color[bmp.Width];

            int counter = 0;

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.FillRectangle(lin, rect);
                for (int i = 0; i <= bmp.Width - 1; i += 1)
                {
                    Color col = bmp.GetPixel(i, 0);
                    ColVal[counter] = col;
                    counter        += 1;
                }
            }



            List <double> DictVal = new List <double>();

            DictVal.AddRange((double[])newCloud.UserDictionary[strdc]);
            int idx = ColVal.Length - 1;

            for (int i = 0; i <= newCloud.Count - 1; i += 1)
            {
                double thisnorm = new double();
                if (step <= 0.0)
                {
                    thisnorm = Itv.NormalizedParameterAt(DictVal[i]);
                }
                else
                {
                    thisnorm = Itv.NormalizedParameterAt(Math.Floor(DictVal[i] / step) * step);
                }


                if (thisnorm < (0.0))                   //- Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance))
                {
                    newCloud[i].Color = ColVal.First(); //Color.Black;
                }
                else if (thisnorm > (1.0))              //+ Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance))
                {
                    newCloud[i].Color = ColVal.Last();  //Color.White;
                }
                else
                {
                    newCloud[i].Color = ColVal[(int)(thisnorm * idx)];
                }
            }



            DA.SetData(0, newCloud);
            GlobalCloud.Dispose();
            //newCloud.Dispose();
            newCloud    = null;
            GlobalCloud = null;
            ColVal      = null;
            bmp.Dispose();
            Itv = new Interval();
        }
        /// <summary>
        /// Parallel Computing Setup for Code to Execute.
        /// </summary>
        /// <param name="pointCloud">ByRef PointCloud to Execute Code on.</param>
        /// <returns></returns>
        public override bool Execute(ref PointCloud pointCloud)
        {
            //Set Global Variables
            LastPercentReported = 0;
            PointCounter        = 0;

            Dict_Utils.CastDictionary_ToArrayDouble(ref pointCloud);
            GlobalCloud = pointCloud;
            NewCloud    = (PointCloud)pointCloud.Duplicate();

            tree    = insV_KDTree.Value.Item1;
            cloudTo = insV_KDTree.Value.Item2.Value;
            pts     = pointCloud.GetPoints();
            Array.Resize(ref Distances, pointCloud.Count);

            // Setup the cancellation mechanism.
            po.CancellationToken = cts.Token;

            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, GlobalCloud.Count, (int)Math.Ceiling((double)GlobalCloud.Count / ProcCount));



            //Run MultiThreaded Loop.
            Parallel.ForEach(rangePartitioner, po, (rng, loopState) =>
            {
                //Initialize Local Variables.
                /// Get Index for Processor to be able to merge clouds in ProcesserIndex order in the end.
                int MyIndex = (int)(rng.Item1 / Math.Ceiling(((double)GlobalCloud.Count / ProcCount)));
                /// Initialize Partial PointCloud
                PointCloud MyCloud = new PointCloud();
                /// Get Total Count Fraction to calculate Operation Percentage.
                double totc = (double)1 / GlobalCloud.Count;


                //Loop over individual RangePartitions per processor.
                for (int i = rng.Item1; i < rng.Item2; i++)
                {
                    //Point to measure From
                    var p = pts[i];
                    //Range
                    var r = Double.MaxValue;
                    //Get one Nearest Neighbor (Part of KDTree.dll)
                    var ns = tree.NearestNeighbors(new double[] { p.X, p.Y, p.Z }, insV_Amount, r);
                    //The index of the Nearest Point in the PointCloud to Measure To.
                    var indList = ns.ToList();

                    double D = 0.0;
                    foreach (int idx in indList)
                    {
                        //Distance between Point measured From to Point meassured To.
                        //Point meassured From.
                        Point3d P2 = cloudTo[idx].Location;
                        //Distance betwen Points
                        //double D = fastDist(p, P2);
                        //Cumulative Distance
                        D = D + p.DistanceTo(P2);
                    }
                    //Average distances
                    double aveD = D / indList.Count;
                    //Add Distances to Array.
                    Distances[i] = aveD;
                }



                //Enable Parrallel Computing Cancellation
                po.CancellationToken.ThrowIfCancellationRequested();
            }
                             );



            //Dispose of Global Clouds.
            GlobalCloud.Dispose();
            pointCloud.Dispose();

            //Set OutputCloud
            NewCloud.UserDictionary.Set(insV_Key, Distances);
            //Colorize
            if (insV_Colorize)
            {
                List <double> colorValues = Color_Utils.ColorValues_Std_pos(NewCloud, insV_Key);
                List <Color>  Colors      = Color_Utils.ColorGradient_Std_GtoR();

                Instruction.Instr_Dict_Color col = new Instruction.Instr_Dict_Color(insV_Key, colorValues, Colors, -1, 0.00);
                Boolean ColResult = col.Execute(ref NewCloud);

                //Set ColorGradient UserData
                Color_Utils.Set_ColorGradient_Dict(ref NewCloud, Colors, colorValues);
            }


            pointCloud = (PointCloud)NewCloud.Duplicate();

            //Dispose of PointCloud Pieces and NewCloud.
            GlobalCloud.Dispose();
            NewCloud.Dispose();

            //Return True on Finish
            return(true);
        }