コード例 #1
0
ファイル: NGon.cs プロジェクト: petrasvestartas/NGon
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            System.Drawing.Color f  = System.Drawing.Color.White;
            System.Drawing.Color b  = System.Drawing.Color.Red;
            System.Drawing.Color lc = System.Drawing.Color.Black;
            int w = 1;

            DA.GetData(1, ref f);
            DA.GetData(2, ref b);
            //DA.GetData(3, ref w);
            DA.GetData(3, ref lc);


            Grasshopper.Kernel.Data.GH_Structure <GH_Mesh> tree = new Grasshopper.Kernel.Data.GH_Structure <GH_Mesh>();
            DA.GetDataTree(0, out tree);

            Mesh mesh = new Mesh();

            foreach (GH_Mesh m in tree)
            {
                mesh.Append(m.Value);
            }

            this.PreparePreview(mesh, DA.Iteration, null, true, null, null, b.R, b.G, b.B, null, f.R, f.G, f.B, w, true, lc.R, lc.G, lc.B);

            // DA.SetDataTree(0, tree);
        }
コード例 #2
0
 static void CollectDataHelper2 <T, GHT>(IGH_DataAccess DA,
                                         string inputName,
                                         GH_ParamAccess access,
                                         ref int inputCount,
                                         DataTree <ResthopperObject> dataTree) where GHT : GH_Goo <T>
 {
     if (access == GH_ParamAccess.tree)
     {
         var tree = new Grasshopper.Kernel.Data.GH_Structure <GHT>();
         if (DA.GetDataTree(inputName, out tree))
         {
             foreach (var path in tree.Paths)
             {
                 string pathString = path.ToString();
                 var    items      = tree[path];
                 foreach (var item in items)
                 {
                     dataTree.Append(new ResthopperObject(item.Value), pathString);
                 }
             }
         }
     }
     else
     {
         CollectDataHelper <T>(DA, inputName, access, ref inputCount, dataTree);
     }
 }
コード例 #3
0
ファイル: Utility.cs プロジェクト: marioguttman/hummingbird
 public bool GetInput(int dataAccessIndex, out Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> dataTree, bool checkNull, bool checkEmpty, bool silent)
 {
     if (!this.dataAccess.GetDataTree <Grasshopper.Kernel.Types.GH_String>(dataAccessIndex, out dataTree))
     {
         if (!silent)
         {
             Print("DataAccess.GetData() failed at index: " + dataAccessIndex.ToString() + ".");
         }
         return(false);
     }
     if (checkNull)
     {
         if (dataTree == null)
         {
             if (!silent)
             {
                 Print("DataAccess.GetData(" + dataAccessIndex.ToString() + ", dataTree) returned null.");
             }
             return(false);
         }
     }
     if (checkEmpty)
     {
         if (dataTree.Branches.Count == 0)
         {
             if (!silent)
             {
                 Print("DataAccess.GetData() returned data tree with no branches at index: " + dataAccessIndex.ToString() + ".");
             }
             return(false);
         }
     }
     return(true);
 }
コード例 #4
0
ファイル: KoalaComponent.cs プロジェクト: dbt-ethz/Koala
        private List <Line> GetLines(List <Plane> planes, Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer> indices)
        {
            List <Line>          lines      = new List <Line>();
            List <List <Plane> > new_planes = new List <List <Plane> >();

            foreach (Grasshopper.Kernel.Data.GH_Path path in indices.Paths)
            {
                List <Plane> branch_planes = new List <Plane>();
                foreach (Grasshopper.Kernel.Types.GH_Integer wrapper in indices[path])
                {
                    int index = wrapper.Value;
                    branch_planes.Add(planes[index]);
                }
                new_planes.Add(branch_planes);
            }
            for (int i = 0; i < new_planes.Count; i++)
            {
                for (int j = 1; j < new_planes[i].Count; j++)
                {
                    //get an intersection line between planes[i][0] and planes[i][j]
                    bool line_exists = Rhino.Geometry.Intersect.Intersection.PlanePlane(new_planes[i][0], new_planes[i][j], out Line line);
                    if (line_exists)
                    {
                        lines.Add(line);
                    }
                }
            }

            return(lines);
        }
コード例 #5
0
 public static List <T> InfinitBranchAt <T>(this Grasshopper.Kernel.Data.GH_Structure <T> source, int index) where T : IGH_Goo
 {
     if (source == null)
     {
         return(null);
     }
     if (source.Count() == 0)
     {
         return(null);
     }
     return((source.Branches.Count() > index) ? source.Branches[index] : source.Branches[source.Count() - 1]);
 }
コード例 #6
0
        public void SetComponentOutputs(Schema schema, IGH_DataAccess DA, List <IGH_Param> outputParams, GH_ActiveObject component)
        {
            foreach (var datatree in schema.Values)
            {
                string outputParamName = datatree.ParamName;
                if (outputParamName.StartsWith("RH_OUT:"))
                {
                    var chunks = outputParamName.Split(new char[] { ':' });
                    outputParamName = chunks[chunks.Length - 1];
                }
                int paramIndex = 0;
                for (int i = 0; i < outputParams.Count; i++)
                {
                    if (outputParams[i].Name.Equals(outputParamName))
                    {
                        paramIndex = i;
                        break;
                    }
                }

                var structure = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.IGH_Goo>();
                foreach (var kv in datatree.InnerTree)
                {
                    var        tokens   = kv.Key.Trim(new char[] { '{', '}' }).Split(';');
                    List <int> elements = new List <int>();
                    foreach (var token in tokens)
                    {
                        if (!string.IsNullOrWhiteSpace(token))
                        {
                            elements.Add(int.Parse(token));
                        }
                    }
                    var path = new Grasshopper.Kernel.Data.GH_Path(elements.ToArray());
                    for (int gooIndex = 0; gooIndex < kv.Value.Count; gooIndex++)
                    {
                        var goo = GooFromReshopperObject(kv.Value[gooIndex]);
                        structure.Insert(goo, path, gooIndex);
                    }
                }
                DA.SetDataTree(paramIndex, structure);
            }

            foreach (var error in schema.Errors)
            {
                component.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error);
            }
            foreach (var warning in schema.Warnings)
            {
                component.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, warning);
            }
        }
コード例 #7
0
ファイル: KoalaComponent.cs プロジェクト: dbt-ethz/Koala
        private Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Point> FromListToTree(List <List <Point3d> > points)
        {
            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Point> new_points = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Point>();

            for (int i = 0; i < points.Count; i++)
            {
                for (int j = 0; j < points[i].Count; j++)
                {
                    Grasshopper.Kernel.Types.GH_Point pt = new Grasshopper.Kernel.Types.GH_Point();
                    pt.Value = points[i][j];
                    new_points.Append(pt, new Grasshopper.Kernel.Data.GH_Path(i));
                }
            }
            return(new_points);
        }
コード例 #8
0
 public bool BlitData <TQ>(int paramIndex, Grasshopper.Kernel.Data.GH_Structure <TQ> tree, bool overwrite) where TQ : Grasshopper.Kernel.Types.IGH_Goo
 {
     throw new NotImplementedException();
 }
コード例 #9
0
ファイル: AntsEngine.cs プロジェクト: ksteinfe/ants
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            List<double> v_list = new List<double>();
            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            if (!DA.GetData(1, ref pyString)) return;
            if (!DA.GetDataList(2, v_list)) return;
            if (!DA.GetData(3, ref nGen)) return;

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            double[] val_list = new double[gph.nodes.Count];
            int v_i = 0;
            for (int i = 0; i < gph.nodes.Count; i++)
            {
                if (v_i == v_list.Count) v_i = 0;
                val_list[i] = v_list[v_i];
                v_i++;
            }

            AWorld wrld = new AWorld(gph, val_list);

            _py = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_py = _py.Compile(pyString);

            // console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            // Main evaluation cycle
            // Should move code into the Antsworld Class
            for (int g = 0; g < nGen; g++)
            {
                // console out
                this.m_py_output.Reset();

                double[] new_vals = new double[wrld.NodeCount];
                for (int i = 0; i < wrld.NodeCount; i++)
                {
                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
                    //double d = g + i + 0.0;

                    new_vals[i] = d;
                }
                wrld.AddGen(new_vals);

                // console out
                Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
                List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
                foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
                consoleOut.AppendRange(gh_strs, key_path);

            }

            DA.SetDataTree(0, consoleOut);
            DA.SetData(1, wrld);
        }
コード例 #10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<int> hrs = new List<int>();
            List<string> keys = new List<string>();
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Number> valtree = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Number>();
            if ((DA.GetDataList(1, keys)) && (DA.GetDataTree(2, out valtree)) && (DA.GetDataList(0, hrs)))
            {

                bool has_color = false;
                List<Color> colors = new List<Color>();
                has_color = DA.GetDataList(4, colors);

                bool has_pt = false;
                List<Point3d> points = new List<Point3d>();
                has_pt = DA.GetDataList(4, points);

                if (hrs.Count != valtree.Branches.Count) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "List matching error.  Hours and Vals must match.  If you pass in more than one hour number, then you must pass in a tree of values with one branch per hour number, and vice-versa.");
                else foreach (List<GH_Number> branch in valtree.Branches) if (keys.Count != branch.Count) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "List matching error.  Keys and Vals must offer lists of the same length.  If you pass in a tree of values, each branch must contain a list of the same length as the list of keys.");
                        else
                        {
                            if (((has_color) && (colors.Count != hrs.Count)) || ((has_pt) && (points.Count != hrs.Count)))
                            {
                                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "List matching error.");
                                return;
                            }
                            List<DHr> hours = new List<DHr>();
                            for (int n = 0; n < valtree.Branches.Count; n++)
                            {
                                DHr hr = new DHr(hrs[n]);
                                for (int m = 0; m < keys.Count; m++) hr.put(keys[m], (float)valtree.Branches[n][m].Value);
                                if (has_color) hr.color = colors[n];
                                if (has_pt) hr.pos = points[n];
                                hours.Add(hr);
                            }
                            DA.SetDataList(0, hours);
                        }
            }
        }
コード例 #11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
            String key = "";
            if (DA.GetDataTree(0, out hourTreeIn) && DA.GetData(1, ref key)) {

                Interval ival_y = new Interval();
                float[] garbage = new float[0];
                if (!(DA.GetData(2, ref ival_y))) DHr.get_domain(key, hourTreeIn.ToArray(), ref garbage, ref ival_y); // vals are no good here, we would need a tree of values

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(3, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(4, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 12.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 1.0;
                }

                double barWidth = 1.0;
                DA.GetData(5, ref barWidth);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> rects = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();

                double ival2d_u_delta = ival2d.U.Length / hourTreeIn.Branches.Count;

                for (int b = 0; b < hourTreeIn.Branches.Count; b++) {
                    List<DHr> hours = hourTreeIn.Branches[b];
                    Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(b);
                    hourTreeOut.EnsurePath(path);
                    points.EnsurePath(path);
                    rects.EnsurePath(path);

                    Grasshopper.Kernel.Types.UVInterval ival2d_sub = new Grasshopper.Kernel.Types.UVInterval(new Interval(b * ival2d_u_delta, (b + 1) * ival2d_u_delta), ival2d.V);
                    double t0_sub = ival2d_sub.U.Mid - (ival2d_sub.U.Mid - ival2d_sub.U.T0) * barWidth;
                    double t1_sub = ival2d_sub.U.Mid + (ival2d_sub.U.T1 - ival2d_sub.U.Mid) * barWidth;
                    ival2d_sub.U = new Interval(t0_sub, t1_sub);

                    for (int h = 0; h < hours.Count; h++) {
                        Point3d gpt = GraphPoint(hours[h].hr % 24, hours[h].val(key), plane, ival_y, ival2d_sub); // returns a point in graph coordinates
                        hours[h].pos = gpt; // the hour records the point in graph coordinates
                        hourTreeOut.Append(hours[h], path);

                        Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                        points.Append(new Grasshopper.Kernel.Types.GH_Point(wpt), path);  // adds this point in world coordinates

                        double delta_x2 = (Math.Abs(ival2d_sub.U.Length) / 24.0 / 2.0);
                        Interval ival_gx = new Interval(gpt.X - delta_x2, gpt.X + delta_x2); // interval of horz space occupied by this hour in graphic units
                        Interval ival_gy = new Interval(ival2d_sub.V0, gpt.Y); // interval of vertical space occupied by this hour in graphic units

                        Rectangle3d rect = new Rectangle3d(plane, ival_gx, ival_gy);
                        rects.Append(new Grasshopper.Kernel.Types.GH_Rectangle(rect), path);

                    }
                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, points);
                DA.SetDataTree(2, rects);

            }
        }
コード例 #12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            List<String> keys = new List<string>();
            if (DA.GetDataList(0, hours) && DA.GetDataList(1, keys)) {
                if ((hours[0].is_surrogate) && ((hours.Count != 1) && (hours.Count != 12) && (hours.Count != 52) && (hours.Count != 365))) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component can only plot unmasked surrogate hours for yearly, monthly, weekly, and daily statistics"); }

                Interval ival_y = new Interval();
                bool calc_ival_y = false;
                if (!(DA.GetData(2, ref ival_y))) {
                    ival_y.T0 = hours[0].val(keys[0]);
                    ival_y.T1 = hours[0].val(keys[0]);
                    calc_ival_y = true;
                }
                Dictionary<string, float[]> val_dict = new Dictionary<string, float[]>();
                List<Interval> val_ranges = new List<Interval>();
                foreach (string key in keys) {
                    Interval ival = new Interval();
                    float[] vals = new float[0];
                    DHr.get_domain(key, hours.ToArray(), ref vals, ref ival);
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) vals[h] = hours[h].val(key);
                    val_dict.Add(key, vals);
                    val_ranges.Add(ival);
                }

                bool force_start_at_zero = true;

                int stack_dir = StackDirection(val_ranges[0]);
                if (stack_dir==0) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The first key returned nothing but zero values.  I can't deal!");
                foreach (Interval ival in val_ranges) {
                    if (StackDirection(ival) != stack_dir) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "A stacked graph can only handle all negative or all positive numbers.");
                    if (calc_ival_y) {
                        if (stack_dir < 1) {
                            if (ival.T1 > ival_y.T0) ival_y.T0 = ival.T1;
                            if (ival.T0 < ival_y.T1) ival_y.T1 = ival.T0;
                        } else {
                            if (ival.T0 < ival_y.T0) ival_y.T0 = ival.T0;
                            if (ival.T1 > ival_y.T1) ival_y.T1 = ival.T1;
                        }
                    }
                }

                if (force_start_at_zero && calc_ival_y) ival_y.T0 = 0;

                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval> intervalTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval>();
                intervalTreeOut.Append(new Grasshopper.Kernel.Types.GH_Interval(ival_y),new Grasshopper.Kernel.Data.GH_Path(0));
                foreach (Interval ival in val_ranges) intervalTreeOut.Append(new Grasshopper.Kernel.Types.GH_Interval(ival), new Grasshopper.Kernel.Data.GH_Path(1));

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(3, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(4, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 12.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 1.0;
                }

                double barWidth = 1.0;
                DA.GetData(5, ref barWidth);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> pointTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> rectTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();
                List<Point3d> basepoints = new List<Point3d>();
                for (int h = 0; h < hours.Count; h++) {
                    Point3d gpt = GraphPoint(hours[h].hr, 0.0f, plane, ival_y, ival2d);
                    Point3d wpt = plane.PointAt(gpt.X, 0.0);
                    basepoints.Add(wpt);
                }

                for (int k = 0; k < keys.Count; k++) {
                    Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(k);
                    List<Point3d> points = new List<Point3d>();
                    List<Rectangle3d> rects = new List<Rectangle3d>();

                    for (int h = 0; h < hours.Count; h++) {
                        float val = val_dict[keys[k]][h];
                        for (int kk = 0; kk < k; kk++) val += val_dict[keys[kk]][h]; // add in all previous values
                        Point3d gpt = GraphPoint(hours[h].hr, val, plane, ival_y, ival2d); // returns a point in graph coordinates

                        hours[h].pos = gpt; // the hour records the point in graph coordinates
                        hourTreeOut.Append(new DHr(hours[h]), key_path);

                        Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                        points.Add(wpt); // adds this point in world coordinates

                        Interval ival_gx; // interval of horz space occupied by this hour in graphic units
                        Interval ival_gy = new Interval(ival2d.V0, gpt.Y); // interval of vertical space occupied by this hour in graphic units
                        if (!hours[h].is_surrogate) {
                            double delta_x2 = (Math.Abs(ival2d.U.Length) / 8760 / 2.0);
                            ival_gx = new Interval(gpt.X - delta_x2, gpt.X + delta_x2); // interval of horz space occupied by this hour in graphic units
                        } else {

                            // if we've been passed surrogate hours, the spacing between bars may not be consistant
                            // we assume we've been given an hour at the start of the range represented
                            double ival_gx_0 = gpt.X;
                            double ival_gx_1;
                            if (h < hours.Count - 1) {
                                Point3d pt_next = GraphPoint(hours[h + 1].hr, val_dict[keys[k]][h + 1], plane, ival_y, ival2d);
                                ival_gx_1 = gpt.X + (pt_next.X - gpt.X) * barWidth;
                            } else { ival_gx_1 = gpt.X + (ival2d.U1 - gpt.X) * barWidth; }
                            ival_gx = new Interval(ival_gx_0, ival_gx_1);
                            if (hours.Count == 1) ival_gx = ival2d.U;

                        }
                        Rectangle3d rect = new Rectangle3d(plane, ival_gx, ival_gy);
                        rects.Add(rect);
                    }

                    List<Grasshopper.Kernel.Types.GH_Point> gh_points = new List<Grasshopper.Kernel.Types.GH_Point>();
                    foreach (Point3d pt in points) gh_points.Add(new Grasshopper.Kernel.Types.GH_Point(pt));
                    pointTreeOut.AppendRange(gh_points, key_path);

                    List<Grasshopper.Kernel.Types.GH_Rectangle> gh_rects = new List<Grasshopper.Kernel.Types.GH_Rectangle>();
                    foreach (Rectangle3d rec in rects) gh_rects.Add(new Grasshopper.Kernel.Types.GH_Rectangle(rec));
                    rectTreeOut.AppendRange(gh_rects, key_path);

                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, intervalTreeOut);
                DA.SetDataTree(2, pointTreeOut);
                DA.SetDataList(3, basepoints);
                DA.SetDataTree(4, rectTreeOut);

            }
        }
コード例 #13
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)
        {
            bool test_bool = false;
            List <GH_ObjectWrapper> vals   = new List <GH_ObjectWrapper>();
            List <GH_ObjectWrapper> output = new List <GH_ObjectWrapper>();
            GH_ObjectWrapper        f      = new GH_ObjectWrapper();
            StringList m_py_output         = new StringList(); // python output stream is piped to m_py_output


            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String>();


            GH_ObjectWrapper key_str = new GH_ObjectWrapper();

            //if (!DA.GetData(0, ref key_str)) return;
            if (!DA.GetDataList(0, vals))
            {
                return;
            }
            if (!DA.GetData(1, ref f))
            {
                return;
            }

            var  ret = key_str;
            Type t   = ret.GetType();

            ScriptEngine pyEngine = Python.CreateEngine();

            //var outputStream = m_py_output.Write;
            var outputStream       = new System.IO.MemoryStream();
            var outputStreamWriter = new System.IO.StreamReader(outputStream);
            //pyEngine.Runtime.IO.SetOutput(outputStream, outputStreamWriter);
            //pyEngine.Runtime.IO.SetOutput(m_py_output.Write);
            //pyEngine. = m_py_output.Write;
            PythonScript _py = PythonScript.Create();

            //_py.Output = m_py_output.Write;

            Rhino.RhinoApp.WriteLine("Testing, testong");

            //var textWriter = new System.IO.TextWriter;
            //pyEngine.Runtime.IO.RedirectToConsole();
            //Console.SetOut(TextWriter.Synchronized(textWriter));

            //System.IO.Stream out_string = pyEngine.Runtime.IO.OutputStream;
            //pyEngine.Runtime.IO.RedirectToConsole();
            //pyEngine.Runtime.IO.SetOutput
            //System.IO.TextWriter test = Console.Out;

            //Console.SetOut(test);
            //pyEngine. = this.m_py_output.Write;
            //_py = PythonScript.Create();

            //pyEngine.Operations.Output = this.m_py_output.Write;

            for (int i = 0; i < vals.Count; i++)
            {
                //ret = vals[i];
                Type the_type = vals[i].Value.GetType();

                dynamic result = pyEngine.Operations.Invoke(f.Value, vals[i].Value);

                object return_object = (object)result;

                GH_ObjectWrapper temp = new GH_ObjectWrapper(return_object);

                var temp2 = temp.Value;

                output.Add(new GH_ObjectWrapper(return_object));
            }



            //string out_str = return_object.GetType().ToString();

            SpatialGraph gph = new SpatialGraph();

            DA.SetData(0, test_bool);
            DA.SetDataList(1, output);
            //DA.SetData(2, return_object);
            //DA.SetData(3, out_str);
        }
コード例 #14
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            String key = "";
            if (DA.GetDataList(0, hours) && DA.GetData(1, ref key)) {
                if (hours.Count == 0) {
                    //TODO: we may want to return null values here instead.
                    return;
                }
                Interval ival_r = new Interval();
                float[] vals = new float[0];

                if (!(DA.GetData(2, ref ival_r))) DHr.get_domain(key, hours.ToArray(), ref vals, ref ival_r);
                else
                {
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) vals[h] = hours[h].val(key);
                    /* FROM HEAD:
                    ival_r = new Interval(hours[0].val(key), hours[0].val(key));
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) {
                        vals[h] = hours[h].val(key);
                        if (vals[h] < ival_r.T0) ival_r.T0 = vals[h];
                        if (vals[h] > ival_r.T1) ival_r.T1 = vals[h];
                    }
                     */
                }

                String period_string = "none";
                cycle_type = CType.Invalid;
                DA.GetData(3, ref period_string);

                if (period_string.Contains("year")) { this.cycle_type = CType.Year; }
                else if (period_string.Contains("day") || period_string.Contains("daily")) { this.cycle_type = CType.Day; }
                else if (period_string.Contains("none")) { this.cycle_type = CType.None; }
                if (cycle_type == CType.Invalid)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "I don't understand the time period you're looking for.\nPlease choose 'year', 'day', or 'none'.");
                    return;
                }

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(4, ref plane);

                Interval ival_gr = new Interval();
                Interval ival_ga = new Interval(Math.PI * 2, 0); // reversed interval to ensure clockwise direction
                DA.GetData(5, ref ival_gr);

                switch (this.cycle_type) {

                    case CType.None: {
                            List<Point3d> points = new List<Point3d>();
                            Rhino.Geometry.Mesh mesh = new Mesh();
                            for (int h = 0; h < hours.Count; h++) {
                                double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals[h]));
                                double theta = ival_ga.ParameterAt(h / (double)hours.Count);
                                Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                                hours[h].pos = gpt; // the hour records the point in graph coordinates

                                Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                                points.Add(wpt);  // adds this point in world coordinates

                                mesh.Vertices.Add(wpt);
                                mesh.VertexColors.Add(hours[h].color);
                                Point3d wbpt = PointByCylCoords(ival_gr.ParameterAt(-0.01), theta);
                                mesh.Vertices.Add(plane.PointAt(wbpt.X, wbpt.Y));
                                mesh.VertexColors.Add(hours[h].color);
                                if (h > 0) mesh.Faces.AddFace(h * 2, h * 2 + 1, h * 2 - 1);
                                if (h > 0) mesh.Faces.AddFace(h * 2 - 1, h * 2 - 2, h * 2);
                            }
                            mesh.Normals.ComputeNormals();
                            mesh.Compact();

                            DA.SetDataList(0, hours);
                            DA.SetDataList(1, points);
                            //DA.SetDataTree(2, regions);
                            DA.SetData(2, mesh);
                        }
                        break;

                    case CType.Day: {
                            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                            List<Mesh> meshes = new List<Mesh>();
                            Rhino.Geometry.Mesh mesh = new Mesh();
                            int hour_of_day = 0;
                            int cycle_count = 0;
                            for (int i = 0; i < hours.Count; i++) {
                                if (hours[i].hr % 24 != hour_of_day) {
                                    cycle_count++;
                                    hour_of_day = hours[i].hr % 24;
                                    mesh.Normals.ComputeNormals();
                                    mesh.Compact();
                                    meshes.Add(mesh);
                                    mesh = new Mesh();
                                }
                                double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals[i]));
                                double theta = ival_ga.ParameterAt(hour_of_day / 24.0);
                                Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                                hours[i].pos = gpt; // the hour records the point in graph coordinates

                                Point3d wpt = plane.PointAt(gpt.X, gpt.Y);

                                points.Append(new Grasshopper.Kernel.Types.GH_Point(wpt),new Grasshopper.Kernel.Data.GH_Path(cycle_count)); // adds this point in world coordinates
                                hourTreeOut.Append(hours[i], new Grasshopper.Kernel.Data.GH_Path(cycle_count));

                                mesh.Vertices.Add(wpt);
                                mesh.VertexColors.Add(hours[i].color);
                                Point3d wbpt = PointByCylCoords(ival_gr.ParameterAt(-0.01), theta);
                                mesh.Vertices.Add(plane.PointAt(wbpt.X, wbpt.Y));
                                mesh.VertexColors.Add(hours[i].color);
                                if (hour_of_day > 0) mesh.Faces.AddFace(hour_of_day * 2, hour_of_day * 2 + 1, hour_of_day * 2 - 1);
                                if (hour_of_day > 0) mesh.Faces.AddFace(hour_of_day * 2 - 1, hour_of_day * 2 - 2, hour_of_day * 2);

                                hour_of_day++;
                            }

                            DA.SetDataTree(0, hourTreeOut);
                            DA.SetDataTree(1, points);
                            //DA.SetDataTree(2, regions);
                            DA.SetDataList(2, meshes);
                        }
                        break;
                }

            }
        }
コード例 #15
0
ファイル: Components Filter.cs プロジェクト: ksteinfe/dyear
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
            string key = "";
            int subdivs = 0;
            if ((DA.GetDataTree(0, out hourTreeIn)) && (DA.GetData(1, ref key)) && (DA.GetData(3, ref subdivs)))
            {
                Interval ival_overall = new Interval();
                if (!DA.GetData(2, ref ival_overall)) {
                    // go thru the given hours and find the max and min value for the given key
                    ival_overall.T0 = MDHr.INVALID_VAL;
                    ival_overall.T1 = MDHr.INVALID_VAL;
                    foreach (DHr dhr in hourTreeIn.AllData(true)) {
                        float val = dhr.val(key);
                        if ((ival_overall.T0 == MDHr.INVALID_VAL) || (val < ival_overall.T0)) ival_overall.T0 = val;
                        if ((ival_overall.T1 == MDHr.INVALID_VAL) || (val > ival_overall.T1)) ival_overall.T1 = val;
                    }
                }

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer> freqTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval> ivalTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval>();

                List<Interval> ivalList = new List<Interval>();
                if (ival_overall.IsDecreasing) ival_overall.Swap();
                double delta = ival_overall.Length / subdivs;
                for (int n = 0; n < subdivs; n++) {  ivalList.Add(new Interval(ival_overall.T0 + n * delta, ival_overall.T0 + ((n + 1) * delta)));  }

                for (int b = 0; b < hourTreeIn.Branches.Count; b++)
                {
                    Grasshopper.Kernel.Data.GH_Structure<DHr> hourBranch = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                    for (int n = 0; n < subdivs; n++) { hourBranch.EnsurePath(n); }
                    List<int> freqOut = new List<int>();

                    List<DHr> hrsIn = hourTreeIn.Branches[b];
                    foreach (DHr dhr in hrsIn)
                    {
                        if (dhr.val(key) < ivalList[0].T0)
                        {
                            hourBranch.Append(dhr, new Grasshopper.Kernel.Data.GH_Path(0));
                            continue;
                        }
                        if (dhr.val(key) > ivalList[ivalList.Count - 1].T1)
                        {
                            hourBranch.Append(dhr, new Grasshopper.Kernel.Data.GH_Path(ivalList.Count - 1));
                            continue;
                        }
                        for (int n = 0; n < subdivs; n++)
                        {
                            if (ivalList[n].IncludesParameter(dhr.val(key)))
                            {
                                hourBranch.Append(dhr,new Grasshopper.Kernel.Data.GH_Path(n));
                                break;
                            }
                        }
                    }

                    for (int bb = 0; bb < hourBranch.Branches.Count; bb++)
                    {
                        Grasshopper.Kernel.Data.GH_Path branch_path = hourTreeIn.Paths[b].AppendElement(bb);
                        hourTreeOut.AppendRange(hourBranch.Branches[bb], branch_path);
                        Grasshopper.Kernel.Types.GH_Integer freq = new Grasshopper.Kernel.Types.GH_Integer(hourBranch.Branches[bb].Count);
                        freqTreeOut.Append(freq, branch_path);
                        Grasshopper.Kernel.Types.GH_Interval ival = new Grasshopper.Kernel.Types.GH_Interval(ivalList[bb]);
                        ivalTreeOut.Append(ival, branch_path);
                    }

                }

                hourTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);
                freqTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);
                ivalTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);

                DA.SetDataTree(0, freqTreeOut);
                DA.SetDataTree(1, ivalTreeOut);
                DA.SetDataTree(2, hourTreeOut);
            }
        }
コード例 #16
0
ファイル: Components Filter.cs プロジェクト: ksteinfe/dyear
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string period_string = "";
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref period_string))) {
                if (period_string == "") { return; }
                period_string = period_string.ToLowerInvariant().Trim();
                this.cycle_type = CType.Invalid;
                if (period_string.Contains("year")) { this.cycle_type = CType.Yearly; } else if (period_string.Contains("monthly diurnal")) { this.cycle_type = CType.MonthlyDiurnal; } else if (period_string.Contains("month")) { this.cycle_type = CType.Monthly; } else if (period_string.Contains("day") || period_string.Contains("daily")) { this.cycle_type = CType.Daily; } else if (period_string.Contains("weekly diurnal")) { this.cycle_type = CType.WeeklyDiurnal; } else if (period_string.Contains("weekly")) { this.cycle_type = CType.Weekly; } else {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "I don't understand the time period you're looking for.\nPlease choose 'yearly', 'monthly', 'monthly diurnal', 'weekly', 'weekly diurnal', or 'daily'.");
                }

                string[] commonKeys = DHr.commonkeys(dhrs.ToArray());
                Dictionary<string, List<DHr>> stat_hours = new Dictionary<string, List<DHr>>();
                InitStatHours(ref stat_hours);

                HourMask mask = new HourMask();

                switch (this.cycle_type) {

                    case CType.MonthlyDiurnal:
                    case CType.WeeklyDiurnal:
                        Grasshopper.Kernel.Data.GH_Structure<DHr> meanTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> modeTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> highTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> uqTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> medianTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> lqTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> lowTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> sumTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();

                        switch (this.cycle_type) {
                            case CType.MonthlyDiurnal:
                                for (int mth = 0; mth < 12; mth++) {
                                    InitStatHours(ref stat_hours);
                                    for (int hour = 0; hour < 24; hour++) {
                                        mask.maskByMonthAndHour(mth, hour);
                                        int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(mth).AddHours(hour)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                                    }
                                    meanTree.AppendRange(stat_hours["meanHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    modeTree.AppendRange(stat_hours["modeHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    highTree.AppendRange(stat_hours["highHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    uqTree.AppendRange(stat_hours["uqHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    medianTree.AppendRange(stat_hours["medianHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    lqTree.AppendRange(stat_hours["lqHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    lowTree.AppendRange(stat_hours["lowHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    sumTree.AppendRange(stat_hours["sumHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                }
                                break;
                            case CType.WeeklyDiurnal:
                                for (int wk = 0; wk < 52; wk++) {
                                    InitStatHours(ref stat_hours);
                                    for (int hour = 0; hour < 24; hour++) {
                                        mask.maskByWeekAndHour(wk, hour);
                                        int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(wk * 7).AddHours(hour)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                                    }
                                    meanTree.AppendRange(stat_hours["meanHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    modeTree.AppendRange(stat_hours["modeHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    highTree.AppendRange(stat_hours["highHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    uqTree.AppendRange(stat_hours["uqHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    medianTree.AppendRange(stat_hours["medianHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    lqTree.AppendRange(stat_hours["lqHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    lowTree.AppendRange(stat_hours["lowHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    sumTree.AppendRange(stat_hours["sumHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                }
                                break;
                        }
                        DA.SetDataTree(0, meanTree);
                        DA.SetDataTree(1, modeTree);
                        DA.SetDataTree(2, highTree);
                        DA.SetDataTree(3, uqTree);
                        DA.SetDataTree(4, medianTree);
                        DA.SetDataTree(5, lqTree);
                        DA.SetDataTree(6, lowTree);
                        DA.SetDataTree(7, sumTree);
                        break;

                    case CType.Daily:
                        for (int day = 0; day < 365; day++) {
                            mask.maskByDayOfYear(day, day); // passing in same day twice masks to this single day
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(day).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Weekly:
                        for (int wk = 0; wk < 52; wk++) {
                            mask.maskByWeek(wk);
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(wk * 7).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Monthly:
                        for (int mth = 0; mth < 12; mth++) {
                            mask.maskByMonthOfYear(mth);
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(mth).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Yearly:
                        mask.fillMask(true); // all hours may pass
                        int hhh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(6).AddDays(15).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hhh, true);
                        SetOutputData(DA, stat_hours);
                        break;
                    default:
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Time period option not yet implimented.  Cannot produce statistics.");
                        break;
                }

            }
        }
コード例 #17
0
ファイル: AntPicnic.cs プロジェクト: nreifenstein/Picnic
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld                       refwrld = new AWorld();
            List <object>                v_list  = new List <object>();
            GH_ObjectWrapper             gh_dict = new GH_ObjectWrapper();
            IDictionary <string, string> dict    = new Dictionary <string, string>();
            string                       k       = "";

            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();

            if (!DA.GetData(0, ref gph))
            {
                return;
            }

            int    nGen     = 0;
            string pyString = "";

            if (!DA.GetData(1, ref pyString))
            {
                return;
            }
            if (!DA.GetDataList(2, v_list))
            {
                return;
            }
            if (!DA.GetData(3, ref nGen))
            {
                return;
            }
            if (!DA.GetData(4, ref gh_dict))
            {
                return;
            }
            if (!DA.GetData(5, ref k))
            {
                return;
            }

            //dict = (IDictionary<string, string>)gh_dict.Value;

            //object d = gh_dict.Value;
            var         t      = Type.GetType("IronPython.Runtime.PythonDictionary,IronPython");
            IDictionary i_dict = Activator.CreateInstance(t) as IDictionary;
            //IronPython.Runtime.PythonDictionary d = gh_dict.Value;
            //string v = d.get(k);
            string v = "oops";

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            //object[] val_list = new object[gph.nodes.Count];
            //int v_i = 0;
            //for (int i = 0; i < gph.nodes.Count; i++)
            //{
            //    if (v_i == v_list.Count) v_i = 0;
            //    val_list[i] = v_list[v_i];
            //    v_i++;
            //}

            //AWorld wrld = new AWorld(gph, val_list);

            //_py = PythonScript.Create();
            //_py.Output = this.m_py_output.Write;
            //_compiled_py = _py.Compile(pyString);

            //// console out
            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String>();

            //// Main evaluation cycle
            //// Should move code into the Antsworld Class
            //for (int g = 0; g < nGen; g++)
            //{
            //    // console out
            //    this.m_py_output.Reset();

            //    double[] new_vals = new double[wrld.NodeCount];
            //    for (int i = 0; i < wrld.NodeCount; i++)
            //    {
            //        int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

            //        // build list of neighboring values
            //        List<double> neighboring_vals = new List<double>();
            //        for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);


            //        double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
            //        //double d = g + i + 0.0;

            //        new_vals[i] = d;
            //    }
            //    wrld.AddGen(new_vals);

            //    // console out
            //    Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
            //    List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
            //    foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
            //    consoleOut.AppendRange(gh_strs, key_path);


            //}

            DA.SetDataTree(0, consoleOut);
            //DA.SetData(1, wrld);
            DA.SetData(2, v);
        }
コード例 #18
0
ファイル: Components Filter.cs プロジェクト: ksteinfe/dyear
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string key_u = "";
            string key_v = "";
            Interval subdivs = new Interval();
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref key_u)) && (DA.GetData(2, ref key_v)) && (DA.GetData(4, ref subdivs)))
            {
                int subdivs_u = (int) Math.Floor(subdivs.T0);
                int subdivs_v = (int) Math.Floor(subdivs.T1);

                Grasshopper.Kernel.Types.UVInterval ival_overall = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(3, ref ival_overall)) {
                    // go thru the given hours and find the max and min value for the given key
                    Interval ival_temp_u = new Interval(MDHr.INVALID_VAL, MDHr.INVALID_VAL);
                    Interval ival_temp_v = new Interval(MDHr.INVALID_VAL, MDHr.INVALID_VAL);
                    foreach (DHr dhr in dhrs) {
                        float val_u = dhr.val(key_u);
                        float val_v = dhr.val(key_v);
                        if ((ival_temp_u.T0 == MDHr.INVALID_VAL) || (val_u < ival_temp_u.T0)) ival_temp_u.T0 = val_u;
                        if ((ival_temp_u.T1 == MDHr.INVALID_VAL) || (val_u > ival_temp_u.T1)) ival_temp_u.T1 = val_u;
                        if ((ival_temp_v.T0 == MDHr.INVALID_VAL) || (val_v < ival_temp_v.T0)) ival_temp_v.T0 = val_v;
                        if ((ival_temp_v.T1 == MDHr.INVALID_VAL) || (val_v > ival_temp_v.T1)) ival_temp_v.T1 = val_v;
                    }
                }

                bool cull_outliers = false;
                DA.GetData(5, ref cull_outliers);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hrsOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer> freqOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval2D> ivalsOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval2D>();

                if (ival_overall.U.IsDecreasing) ival_overall.U.Swap();
                if (ival_overall.V.IsDecreasing) ival_overall.V.Swap();
                double delta_u = ival_overall.U.Length / subdivs_u;
                double delta_v = ival_overall.V.Length / subdivs_v;
                for (int u = 0; u < subdivs_u; u++) {
                    for (int v = 0; v < subdivs_v; v++) {
                        Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(new int[] { u, v });
                        ivalsOut.EnsurePath(path);
                        hrsOut.EnsurePath(path);

                        Interval sub_u = new Interval(ival_overall.U.T0 + u * delta_u, ival_overall.U.T0 + ((u + 1) * delta_u));
                        Interval sub_v = new Interval(ival_overall.V.T0 + v * delta_v, ival_overall.V.T0 + ((v + 1) * delta_v));
                        Grasshopper.Kernel.Types.UVInterval sub_uv = new Grasshopper.Kernel.Types.UVInterval(sub_u, sub_v);
                        Grasshopper.Kernel.Types.GH_Interval2D i2d = new Grasshopper.Kernel.Types.GH_Interval2D();
                        i2d.Value = sub_uv;
                        ivalsOut.Append(i2d, path);
                    }
                }

                foreach (DHr dhr in dhrs) {
                    int[] address = new int[] { -1 , -1};
                    for (int u = 0; u < subdivs_u; u++)
                    {
                        Grasshopper.Kernel.Data.GH_Path path_u = new Grasshopper.Kernel.Data.GH_Path(new int[] { u, 0 });
                        Interval sub_u = ivalsOut.get_DataItem(path_u, 0).Value.U;
                        double val = dhr.val(key_u);
                        if ((sub_u.IncludesParameter(val)) || ((!cull_outliers) && (u == 0) && (val <= sub_u.Min)) || ((!cull_outliers) && (u == subdivs_u - 1) && (val >= sub_u.Max)))
                        {
                            address[0] = u;
                            break;
                        }
                    }

                    for (int v = 0; v < subdivs_v; v++)
                    {
                        Grasshopper.Kernel.Data.GH_Path path_v = new Grasshopper.Kernel.Data.GH_Path(new int[] { 0, v });
                        Interval sub_v = ivalsOut.get_DataItem(path_v, 0).Value.V;
                        double val = dhr.val(key_v);
                        if ((sub_v.IncludesParameter(val)) || ((!cull_outliers) && (v == 0) && (val <= sub_v.Min)) || ((!cull_outliers) && (v == subdivs_v - 1) && (val >= sub_v.Max)))
                        {
                            address[1] = v;
                            break;
                        }
                    }
                    if ((address[0] < 0) || (address[1] < 0))
                    {
                        if (!cull_outliers) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Crud. Could not place an outlier into any intervals.  What gives?!");
                    }
                    else
                    {
                        Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(address);
                        hrsOut.Append(dhr, path);
                    }
                }

                foreach (Grasshopper.Kernel.Data.GH_Path path in hrsOut.Paths)
                {
                    int n = hrsOut.get_Branch(path).Count;
                    freqOut.Append(new Grasshopper.Kernel.Types.GH_Integer(n), path);
                }

                DA.SetDataTree(0, freqOut);
                DA.SetDataTree(1, ivalsOut);
                DA.SetDataTree(2, hrsOut);
            }
        }
コード例 #19
0
        protected override void BeforeSolveInstance()
        {
            Grasshopper.Kernel.Parameters.Param_Integer myMaterialParam = Params.Input[0] as Grasshopper.Kernel.Parameters.Param_Integer;
            myMaterialParam.ClearNamedValues();

            //////////  Code for automatically loading Materials from XML when intance of class is initiated.
            IBIS_XML.Load("D:\\Dropbox\\_F13\\6338\\GH Plugin\\Ibis\\Ibis\\IBIS_XML.xml");
            List <String> myMaterialNameList = new List <string>();
            XmlNodeList   myList             = IBIS_XML.GetElementsByTagName("Material");

            foreach (XmlNode mx in myList)
            {
                XmlElement x             = mx as XmlElement;
                string     myXMLMaterial = x.GetAttribute("type");
                myMaterialNameList.Add(myXMLMaterial);
            }

            for (int i = 0; i < myMaterialNameList.Count; i++)
            {
                myMaterialParam.AddNamedValue(myMaterialNameList[i], i + 1);
            }

            Grasshopper.Kernel.Parameters.Param_Integer myGrainParam = Params.Input[2] as Grasshopper.Kernel.Parameters.Param_Integer;
            myGrainParam.ClearNamedValues();


            Grasshopper.Kernel.Parameters.Param_Integer myThicknessParam = Params.Input[3] as Grasshopper.Kernel.Parameters.Param_Integer;
            myThicknessParam.ClearNamedValues();


            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer> myMaterialValue = myMaterialParam.VolatileData as Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer>;
            //GH_Structure<GH_Integer> data = param0.VolatileData as GH_Structure<GH_Integer>;

            if (myMaterialValue.IsEmpty)
            {
                return;
            }

            //Code to load the thickness list depending on user Material input:-
            List <String> myThicknessList = new List <string>();
            List <String> myBendList      = new List <string>();

            IBIS_XML.Load("D:\\Dropbox\\_F13\\6338\\GH Plugin\\Ibis\\Ibis\\IBIS_XML.xml");
            foreach (Grasshopper.Kernel.Types.GH_Integer myThis in myMaterialValue.AllData(true))
            {
                switch (myThis.Value)
                {
                case 1:
                    //////////for thickness:
                    XmlNodeList myNodeList1 = IBIS_XML.SelectNodes("IBIS/DryBending/Material[@id=1]/BendDirection/Thickness");
                    foreach (XmlNode myNode in myNodeList1)
                    {
                        XmlElement myElement      = myNode as XmlElement;
                        String     myXMLThickness = myElement.GetAttribute("type");
                        myThicknessList.Add(myXMLThickness);
                    }


                    for (int i = 0; i < 6; i++)     //This needs to be changed!!
                    {
                        myThicknessParam.AddNamedValue(myThicknessList[i], i + 1001);
                    }
                    //////////for benddirection
                    XmlNodeList myNodeList1b = IBIS_XML.SelectNodes("IBIS/DryBending/Material[@id=1]/BendDirection");
                    foreach (XmlNode myNode in myNodeList1b)
                    {
                        XmlElement myElement = myNode as XmlElement;
                        String     myXMLBend = myElement.GetAttribute("type");
                        myBendList.Add(myXMLBend);
                    }


                    for (int i = 0; i < myBendList.Count; i++)
                    {
                        myGrainParam.AddNamedValue(myBendList[i], i + 101);
                    }
                    break;

                case 2:
                    //////////for thickness:
                    XmlNodeList myNodeList2 = IBIS_XML.SelectNodes("IBIS/DryBending/Material[@id=2]/BendDirection/Thickness");
                    foreach (XmlNode myNode in myNodeList2)
                    {
                        XmlElement myElement      = myNode as XmlElement;
                        String     myXMLThickness = myElement.GetAttribute("type");
                        myThicknessList.Add(myXMLThickness);
                    }


                    for (int i = 0; i < myThicknessList.Count; i++)
                    {
                        myThicknessParam.AddNamedValue(myThicknessList[i], i + 1001);
                    }
                    //////////for benddirection
                    XmlNodeList myNodeList2b = IBIS_XML.SelectNodes("IBIS/DryBending/Material[@id=2]/BendDirection");
                    foreach (XmlNode myNode in myNodeList2b)
                    {
                        XmlElement myElement = myNode as XmlElement;
                        String     myXMLBend = myElement.GetAttribute("type");
                        myBendList.Add(myXMLBend);
                    }


                    for (int i = 0; i < myBendList.Count; i++)
                    {
                        myGrainParam.AddNamedValue(myBendList[i], i + 101);
                    }
                    break;

                case 3:
                    XmlNodeList myNodeList3 = IBIS_XML.SelectNodes("IBIS/DryBending/Material[@id=3]/BendDirection/Thickness");
                    foreach (XmlNode myNode in myNodeList3)
                    {
                        XmlElement myElement      = myNode as XmlElement;
                        String     myXMLThickness = myElement.GetAttribute("type");
                        myThicknessList.Add(myXMLThickness);
                    }


                    for (int i = 0; i < myThicknessList.Count; i++)
                    {
                        myThicknessParam.AddNamedValue(myThicknessList[i], i + 1001);
                    }
                    break;
                }
                return;
            }
        }
コード例 #20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Number> xValuesTree = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Number>();
            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Number> yValuesTree = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Number>();
            List <string>   valuesNames = new List <string>();
            List <DataType> dataTypes   = new List <DataType>();

            DA.GetDataTree("X Values", out xValuesTree);
            DA.GetDataTree("Y Values", out yValuesTree);
            DA.GetDataList(2, valuesNames);
            DA.GetDataList(3, dataTypes);

            List <List <double> > xValues = new List <List <double> >();
            List <List <double> > yValues = new List <List <double> >();

            for (int i = 0; i < xValuesTree.PathCount; i++)
            {
                List <double> currentBranchXValues = new List <double>();
                for (int j = 0; j < xValuesTree.get_Branch(i).Count; j++)
                {
                    currentBranchXValues.Add(Convert.ToDouble(xValuesTree.get_Branch(i)[j].ToString()));
                }
                xValues.Add(currentBranchXValues);

                List <double> currentBranchYValues = new List <double>();
                for (int j = 0; j < yValuesTree.get_Branch(i).Count; j++)
                {
                    currentBranchYValues.Add(Convert.ToDouble(yValuesTree.get_Branch(i)[j].ToString()));
                }
                yValues.Add(currentBranchYValues);
            }

            GraphData graphData = new GraphData(xValues, yValues, valuesNames, dataTypes);

            DA.SetData(0, graphData);
        }
コード例 #21
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)
        {
            bool test_bool = false;
            List<GH_ObjectWrapper> vals = new List<GH_ObjectWrapper>();
            List<GH_ObjectWrapper> output = new List<GH_ObjectWrapper>();
            GH_ObjectWrapper f = new GH_ObjectWrapper();
            StringList m_py_output = new StringList(); // python output stream is piped to m_py_output

            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            GH_ObjectWrapper key_str = new GH_ObjectWrapper();

            //if (!DA.GetData(0, ref key_str)) return;
            if (!DA.GetDataList(0, vals)) return;
            if (!DA.GetData(1, ref f)) return;

            var ret = key_str;
            Type t =ret.GetType();

            ScriptEngine pyEngine = Python.CreateEngine();

            //var outputStream = m_py_output.Write;
            var outputStream = new System.IO.MemoryStream();
            var outputStreamWriter = new System.IO.StreamReader(outputStream);
            //pyEngine.Runtime.IO.SetOutput(outputStream, outputStreamWriter);
            //pyEngine.Runtime.IO.SetOutput(m_py_output.Write);
            //pyEngine. = m_py_output.Write;
            PythonScript _py = PythonScript.Create();
            //_py.Output = m_py_output.Write;

            Rhino.RhinoApp.WriteLine("Testing, testong");

            //var textWriter = new System.IO.TextWriter;
            //pyEngine.Runtime.IO.RedirectToConsole();
            //Console.SetOut(TextWriter.Synchronized(textWriter));

            //System.IO.Stream out_string = pyEngine.Runtime.IO.OutputStream;
            //pyEngine.Runtime.IO.RedirectToConsole();
            //pyEngine.Runtime.IO.SetOutput
            //System.IO.TextWriter test = Console.Out;

            //Console.SetOut(test);
            //pyEngine. = this.m_py_output.Write;
            //_py = PythonScript.Create();

            //pyEngine.Operations.Output = this.m_py_output.Write;

            for (int i = 0; i < vals.Count; i++)
            {
                //ret = vals[i];
                Type the_type = vals[i].Value.GetType();

                dynamic result = pyEngine.Operations.Invoke(f.Value, vals[i].Value);

                object return_object = (object)result;

                GH_ObjectWrapper temp = new GH_ObjectWrapper(return_object);

                var temp2 = temp.Value;

                output.Add(new GH_ObjectWrapper(return_object));

            }

            //string out_str = return_object.GetType().ToString();

            SpatialGraph gph = new SpatialGraph();

            DA.SetData(0, test_bool);
            DA.SetDataList(1, output);
            //DA.SetData(2, return_object);
            //DA.SetData(3, out_str);
        }
コード例 #22
0
 public bool GetDataTree <T>(int index, out Grasshopper.Kernel.Data.GH_Structure <T> tree) where T : Grasshopper.Kernel.Types.IGH_Goo
 {
     throw new NotImplementedException();
 }
コード例 #23
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure <IGH_Goo> elementsToAdd = new Grasshopper.Kernel.Data.GH_Structure <IGH_Goo>();
            double        width          = 0;
            double        height         = 0;
            List <string> rowDefinitions = new List <string>();
            List <string> colDefinitions = new List <string>();

            if (!DA.GetDataTree <IGH_Goo>(0, out elementsToAdd))
            {
                return;
            }
            bool hasWidth  = DA.GetData <double>("Width", ref width);
            bool hasHeight = DA.GetData <double>("Height", ref height);

            bool hasRowDefs = DA.GetDataList <string>("Row Definitions", rowDefinitions);
            bool hasColDefs = DA.GetDataList <string>("Column Definitions", colDefinitions);


            //initialize the grid
            Grid grid = new Grid();

            grid.HorizontalAlignment = HorizontalAlignment.Left;
            grid.VerticalAlignment   = VerticalAlignment.Top;
            grid.Name = "GH_Grid";
            if (hasWidth)
            {
                grid.Width = width;
            }
            else
            {
                grid.HorizontalAlignment = HorizontalAlignment.Stretch;
            }
            if (hasHeight)
            {
                grid.Height = height;
            }
            else
            {
                grid.VerticalAlignment = VerticalAlignment.Stretch;
            }


            //set up a "GridLengthConverter" to handle parsing our strings.
            GridLengthConverter gridLengthConverter = new GridLengthConverter();

            //set up rows and columns if present
            if (hasColDefs)
            {
                for (int i = 0; i < elementsToAdd.PathCount; i++)
                {
                    ColumnDefinition cd = new ColumnDefinition();
                    cd.Width = (GridLength)gridLengthConverter.ConvertFromString(colDefinitions[i % colDefinitions.Count]);  // use repeating pattern of supplied list
                    grid.ColumnDefinitions.Add(cd);
                }
            }

            if (hasRowDefs)
            {
                int maxCount = 0;

                // Find the count of the longest list
                for (int i = 0; i < elementsToAdd.PathCount; i++)
                {
                    if (elementsToAdd.Branches[i].Count > maxCount)
                    {
                        maxCount = elementsToAdd.Branches[i].Count;
                    }
                }

                // Build up the row heights based on a repeating pattern
                for (int i = 0; i < maxCount; i++)
                {
                    RowDefinition rd = new RowDefinition();
                    rd.Height = (GridLength)gridLengthConverter.ConvertFromString(rowDefinitions[i % rowDefinitions.Count]);  // use repeating pattern of supplied list
                    grid.RowDefinitions.Add(rd);
                }
            }
            else
            {
            }


            for (int i = 0; i < elementsToAdd.PathCount; i++)
            {
                List <IGH_Goo> branch = elementsToAdd.Branches[i];
                //for all the elements in each branch
                for (int j = 0; j < branch.Count; j++)
                {
                    UIElement_Goo u = branch[j] as UIElement_Goo;
                    //make sure it doesn't already have a parent
                    HUI_Util.removeParent(u.element);
                    FrameworkElement fe = u.element as FrameworkElement;
                    if (fe != null)
                    {
                        //set its alignment to be relative to upper left - this makes margin-based positioning easy
                        fe.HorizontalAlignment = HorizontalAlignment.Left;
                        fe.VerticalAlignment   = VerticalAlignment.Top;

                        //set up row and column positioning
                        Grid.SetColumn(fe, i);
                        Grid.SetRow(fe, j);
                    }
                    //add it to the grid
                    grid.Children.Add(u.element);
                }
            }


            //pass the grid out
            DA.SetData("Simple Grid", new UIElement_Goo(grid, "Simple Grid", InstanceGuid, DA.Iteration));
        }
コード例 #24
0
ファイル: Utility.cs プロジェクト: marioguttman/hummingbird
 public bool GetInput(int dataAccessIndex, out Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> dataTree)
 {
     return(GetInput(dataAccessIndex, out dataTree, true, true, false));
 }
コード例 #25
0
ファイル: KoalaComponent.cs プロジェクト: dbt-ethz/Koala
        private void TransformPlanes(Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer> indices, out List <Line> output_lines, out double output_fitness, out List <Line> output_segments, out List <List <Point3d> > list_points)
        {
            ////record current performance and planes
            List <Line> lines = GetLines(current_planes, indices);

            lines = ModifyLines(lines, boundary);
            CalculateFitness(lines, out List <Line> old_lines, out double old_fitness, out List <Line> segs, out List <List <Point3d> > ps);
            //List<Line> lines = new List<Line>();
            //randomly select one plane and transform
            Random rnd       = new Random();
            int    index     = rnd.Next(current_planes.Count);
            Plane  plane     = current_planes[index].Clone();
            Plane  old_plane = current_planes[index].Clone();


            //calculate performance after the transformation
            //Transform transformation_matrix = Transform.Identity;
            //transformation_matrix.M03 = Convert.ToDouble(rnd.Next(-max_translation, max_translation));
            //transformation_matrix.M13 = Convert.ToDouble(rnd.Next(-max_translation, max_translation));
            //transformation_matrix.M23 = Convert.ToDouble(rnd.Next(-max_translation, max_translation));
            //transformation_matrix.M00 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M01 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M02 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M10 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M11 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M12 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M30 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M31 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //transformation_matrix.M32 = Convert.ToDouble(rnd.Next(-max_rotation, max_rotation) * 0.001);
            //plane.Transform(transformation_matrix);
            Vector3d translation = new Vector3d(Convert.ToDouble(rnd.Next(-max_translation, max_translation)), Convert.ToDouble(rnd.Next(-max_translation, max_translation)), Convert.ToDouble(rnd.Next(-max_translation, max_translation)));

            plane.Translate(translation);
            plane.Rotate(Convert.ToDouble(rnd.Next(-max_rotation, max_rotation)), Vector3d.XAxis);
            plane.Rotate(Convert.ToDouble(rnd.Next(-max_rotation, max_rotation)), Vector3d.YAxis);
            plane.Rotate(Convert.ToDouble(rnd.Next(-max_rotation, max_rotation)), Vector3d.ZAxis);
            current_planes[index] = plane;
            lines = GetLines(current_planes, indices);
            lines = ModifyLines(lines, boundary);
            CalculateFitness(lines, out List <Line> long_lines, out double new_fitness, out List <Line> segs2, out List <List <Point3d> > ps2);

            //compare performance between new and old
            if (new_fitness < best_fitness)
            {
                //if old one is better, restore the transformed plane
                current_planes[index] = old_plane;
                output_lines          = old_lines;
                output_fitness        = old_fitness;
                output_segments       = segs;
                list_points           = ps;
            }
            else
            {
                best_fitness    = new_fitness;
                output_lines    = long_lines;
                output_fitness  = new_fitness;
                output_segments = segs2;
                list_points     = ps2;
                best_lines      = new List <Line>(long_lines);
            }
        }
コード例 #26
0
ファイル: DataListener.cs プロジェクト: ksteinfe/lemmings
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            this.JSONIsPopulated = false;
            this.JSONString = "";
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.IGH_Goo> tree = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.IGH_Goo>();
            if (!DA.GetDataTree(0, out tree)) { return; }

            String JSONOpen = "";
            String JSONClose = "";
            JSONOpen = @"""" + this.ComponentName + @""":{";
            JSONClose = "}";

            DataStructure dim;
            if (tree.PathCount == 1) {
                if (tree.DataCount == 1) dim = DataStructure.Singleton; // a singleton
                else dim = DataStructure.List; // a list
            } else dim = DataStructure.Tree; // a tree
            JSONOpen += @"""DataStructure"":""" + dim.ToString() + @""",";

            String UniformType = "";
            bool IsUniform = JSONConverter.UniformDataType(tree, ref UniformType);
            if (IsUniform) JSONOpen += @"""Type"":""" + UniformType + @""",";

            if (dim == DataStructure.Singleton) {
                // SINGLETONS
                //
                String ObjString = "";
                IGH_Goo obj = tree.get_FirstItem(false);
                if ((obj != null)&&(JSONConverter.ObjectToJSON(obj, ref ObjString,false))){
                    this.JSONString = JSONOpen + @"""Value"":"+ObjString + JSONClose;
                    DA.SetData(0, "{" + this.JSONString + "}");
                    this.JSONIsPopulated = true;
                    return;
                } else {
                    // TODO: return failed item
                    this.JSONIsPopulated = false;
                    return;
                }
            } else if (dim == DataStructure.List) {
                // LISTS
                //

                JSONOpen += @"""Items"":{";
                JSONClose += "}";

                List<IGH_Goo> failures = new List<IGH_Goo>();
                List<String> ObjStrings = JSONConverter.ObjectsToJSON(tree.get_Branch(tree.Paths[0]), ref failures, !IsUniform);
                if (failures.Count > 0) AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some items failed to be converted to JSON.");
                if (ObjStrings.Count == 0) {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Nothing was successfully converted to JSON.");
                    this.JSONIsPopulated = false;
                    return;
                }

                this.JSONString = JSONOpen + String.Join(",", ObjStrings.ToArray()) + JSONClose;
                DA.SetData(0, "{"+this.JSONString+"}");
                this.JSONIsPopulated = true;
                // TODO: return failed items
                return;
            } else {
                // TREES
                //
                JSONOpen += @"""BranchCount"":" + tree.Branches.Count + @",""DataCount"":" + tree.DataCount + @", ""Paths"":{";
                JSONClose += "}";

                List<IGH_Goo> failures = new List<IGH_Goo>();
                List<String> BranchStrings = new List<string>();

                foreach (Grasshopper.Kernel.Data.GH_Path path in tree.Paths) {
                    String BRANCHOpen = @"""" + path.ToString() + @""":{";
                    String BRANCHClose = "}";

                    List<String> ObjStrings = JSONConverter.ObjectsToJSON(tree.get_Branch(path), ref failures, !IsUniform);
                    if (ObjStrings.Count >= 0) {
                        BranchStrings.Add(BRANCHOpen + String.Join(",", ObjStrings.ToArray()) + BRANCHClose);
                    } else {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "An entire branch failed to be converted to JSON.");
                    }
                }

                if (failures.Count > 0) AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some items failed to be converted to JSON.");

                this.JSONString = JSONOpen + String.Join(",", BranchStrings.ToArray()) + JSONClose;
                DA.SetData(0, "{" + this.JSONString + "}");
                this.JSONIsPopulated = true;
                // TODO: return failed items
                return;
            }
            //if (JSONConverter.ObjectToJSON(obj, ref JSONString)) DA.SetData(0, JSONString);
            //DA.SetData(0, tree.PathCount.ToString());
        }
コード例 #27
0
ファイル: TableGH.cs プロジェクト: paireks/Pterodactyl
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <string> headings  = new List <string>();
            List <int>    alignment = new List <int>();

            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> dataTree = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String>();

            DA.GetDataList(0, headings);
            DA.GetDataList(1, alignment);
            DA.GetDataTree("Data Tree", out dataTree);

            int columnHeight = dataTree.get_Branch(0).Count;

            for (int i = 1; i < dataTree.Branches.Count; i++) //check if columns have the same size
            {
                if (dataTree.get_Branch(i).Count != columnHeight)
                {
                    throw new ArgumentException("Columns heights must be the same");
                }
            }

            string[,] dataTreeArray = new string[dataTree.Branches.Count, columnHeight];

            for (int i = 0; i < dataTree.Branches.Count; i++) //for each column
            {
                for (int j = 0; j < dataTree.get_Branch(i).Count; j++)
                {
                    dataTreeArray[i, j] = dataTree.get_Branch(i)[j].ToString();
                }
            }

            List <string> report;
            Table         reportObject = new Table(headings, alignment, dataTreeArray);

            report = reportObject.Create();

            DA.SetDataList(0, report);
        }
コード例 #28
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            String key_r = "";
            String key_a = "";
            if (DA.GetDataList(0, hours) && DA.GetData(1, ref key_r) && DA.GetData(2, ref key_a)) {

                Interval ival_r = new Interval();
                Interval ival_a = new Interval();
                float[] vals_r = new float[0];
                float[] vals_a = new float[0];

                if (!(DA.GetData(3, ref ival_r))) DHr.get_domain(key_r, hours.ToArray(), ref vals_r, ref ival_r);
                else {
                    ival_r = new Interval(hours[0].val(key_r), hours[0].val(key_r));

                    vals_r = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) {
                        vals_r[h] = hours[h].val(key_r);
                        if (vals_r[h] < ival_r.T0) ival_r.T0 = vals_r[h];
                        if (vals_r[h] > ival_r.T1) ival_r.T1 = vals_r[h];
                    }
                }

                DHr.get_domain(key_a, hours.ToArray(), ref vals_a, ref ival_a);
                DA.GetData(4, ref ival_a);

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(5, ref plane);

                Interval ival_gr = new Interval();
                Interval ival_ga = new Interval(0, Math.PI * 2);
                DA.GetData(6, ref ival_gr);

                Interval subdivs = new Interval();
                DA.GetData(7, ref subdivs);
                int subdivs_r = (int)Math.Floor(subdivs.T0);
                int subdivs_a = (int)Math.Floor(subdivs.T1);

                List<Point3d> points = new List<Point3d>();
                for (int h = 0; h < hours.Count; h++) {
                    double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals_r[h]));
                    double theta = ival_a.NormalizedParameterAt(vals_a[h]) * Math.PI * 2;
                    Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                    hours[h].pos = gpt; // the hour records the point in graph coordinates

                    Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                    points.Add(wpt);  // adds this point in world coordinates
                }

                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Curve> regions = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Curve>();

                int segments_in_whole_circle = 36;
                //double step_r = ival_r.Length / subdivs_r;
                //double step_a = Math.PI*2 / subdivs_a;

                for (int r = 0; r < subdivs_r; r++)
                    for (int a = 0; a < subdivs_a; a++) {
                        Interval rad = new Interval(ival_gr.ParameterAt(r / (float)subdivs_r), ival_gr.ParameterAt((r + 1) / (float)subdivs_r));
                        Interval ang = new Interval(ival_ga.ParameterAt(a / (float)subdivs_a), ival_ga.ParameterAt((a + 1) / (float)subdivs_a));

                        int cnt = (int)Math.Ceiling(segments_in_whole_circle * ang.Length / Math.PI * 2);
                        Polyline pcrv = new Polyline();
                        pcrv.AddRange(FakeArc(plane, rad.T0, ang.T0, ang.T1, cnt));
                        pcrv.AddRange(FakeArc(plane, rad.T1, ang.T1, ang.T0, cnt));
                        pcrv.Add(pcrv[0]);

                        Grasshopper.Kernel.Types.GH_Curve gh_curve = new Grasshopper.Kernel.Types.GH_Curve();
                        Grasshopper.Kernel.GH_Convert.ToGHCurve(pcrv, GH_Conversion.Both, ref gh_curve);
                        regions.Append(gh_curve, new Grasshopper.Kernel.Data.GH_Path(new int[] { r, a }));
                    }

                DA.SetDataList(0, hours);
                DA.SetDataList(1, points);
                DA.SetDataTree(2, regions);

            }
        }
コード例 #29
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)
        {
            //Grasshopper.DataTree<Point3d> ipts = new Grasshopper.DataTree<Point3d>();
            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Goo <Point3d> > ipts = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Goo <Point3d> >();

            List <Point3d> opts  = new List <Point3d>();
            Mesh           mesh1 = new Mesh();

            for (int i = 0; i < ipts.Branches.Count; i++)
            {
                for (int j = 0; j < ipts.Branches[i].Count; j++)
                {
                    opts.Add(ipts.Branches(i)[i]);
                }
            }
            DA.GetDataTree(0, out ipts);
            DA.SetDataList(1, opts);
        }
コード例 #30
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();

            if (DA.GetDataTree(0, out hourTreeIn)) {
                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(1, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(2, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 1.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 2.0;
                }
                if (ival2d.U.IsDecreasing) ival2d.U.Swap();
                if (ival2d.V.IsDecreasing) ival2d.V.Swap();

                double barWidthScale = 1.0;
                DA.GetData(3, ref barWidthScale);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> srects = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();
                List<Rectangle3d> rects = new List<Rectangle3d>();
                List<Mesh> meshes = new List<Mesh>();

                int i = 0;//keeps track of which branch we're on... note, this assumes we've been passed a list of lists and nothing 'deeper'
                int maxHourCount = hourTreeIn.Branches[0].Count;
                foreach (List<DHr> hourList in hourTreeIn.Branches) if (hourList.Count > maxHourCount) maxHourCount = hourList.Count;
                Rectangle3d brect = new Rectangle3d(plane, new Interval(0, ival2d.U1), new Interval(0, ival2d.V.ParameterAt((double)hourTreeIn.DataCount / maxHourCount)));
                DA.SetData(5, brect);

                double dx = ival2d.U.Length / hourTreeIn.Branches.Count * barWidthScale;
                double dy = ival2d.V.Length / maxHourCount;
                foreach (List<DHr> hourList in hourTreeIn.Branches) {
                    Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(i);
                    hourTreeOut.EnsurePath(path);
                    points.EnsurePath(path);
                    srects.EnsurePath(path);

                    double x = ival2d.U.ParameterAt((i + 0.5) / hourTreeIn.Branches.Count);
                    for (int j = 0; j < hourList.Count; j++) {
                        DHr dhour = hourList[j];

                        double y = ival2d.V.ParameterAt((j + 0.5) / maxHourCount);
                        Point3d pt = plane.PointAt(x, y);
                        dhour.pos = new Point3d(x, y, 0);
                        points.Append(new Grasshopper.Kernel.Types.GH_Point(pt), path);
                        hourTreeOut.Append(dhour, path);

                        Plane pln = new Plane(plane);
                        pln.Origin = plane.PointAt(x - dx / 2, y - dy / 2);
                        Rectangle3d rct = new Rectangle3d(pln, dx, dy);
                        srects.Append(new Grasshopper.Kernel.Types.GH_Rectangle(rct), path);
                    }

                    // make meshes & big rectangles
                    if (hourList.Count > 0) {
                        Mesh mesh = new Mesh();
                        // add bottom pts
                        mesh.Vertices.Add(plane.PointAt(x - dx / 2, 0));
                        mesh.VertexColors.Add(hourList[0].color);
                        mesh.Vertices.Add(plane.PointAt(x + dx / 2, 0));
                        mesh.VertexColors.Add(hourList[0].color);

                        for (int j = 0; j < hourList.Count; j++) {
                            double y = ival2d.V.ParameterAt((j + 0.5) / maxHourCount);
                            mesh.Vertices.Add(plane.PointAt(x - dx / 2, y));
                            mesh.VertexColors.Add(hourList[j].color);
                            mesh.Vertices.Add(plane.PointAt(x + dx / 2, y));
                            mesh.VertexColors.Add(hourList[j].color);
                        }

                        // add top pts
                        double yy = ival2d.V.ParameterAt((float)hourList.Count / maxHourCount);
                        mesh.Vertices.Add(plane.PointAt(x - dx / 2, yy));
                        mesh.VertexColors.Add(hourList[hourList.Count - 1].color);
                        mesh.Vertices.Add(plane.PointAt(x + dx / 2, yy));
                        mesh.VertexColors.Add(hourList[hourList.Count - 1].color);

                        for (int n = 2; n < mesh.Vertices.Count; n = n + 2) mesh.Faces.AddFace(n - 2, n - 1, n + 1, n);
                        meshes.Add(mesh);

                        Plane pln = new Plane(plane);
                        pln.Origin = plane.PointAt(x - dx / 2, 0);
                        Rectangle3d rct = new Rectangle3d(pln, dx, yy);
                        rects.Add(rct);
                    }

                    i++;
                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, points);
                DA.SetDataList(2, srects);
                DA.SetDataList(3, rects);
                DA.SetDataList(4, meshes);

            }
        }
コード例 #31
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <string> headings  = new List <string>();
            List <int>    alignment = new List <int>();

            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> dataTree = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String>();

            DA.GetDataList(0, headings);
            DA.GetDataList(1, alignment);
            DA.GetDataTree("Data Tree", out dataTree);

            int currentColumnHeight = 1;

            for (int i = 0; i < dataTree.Branches.Count; i++) //for each column check for highest
            {
                if (dataTree.get_Branch(i).Count > currentColumnHeight)
                {
                    currentColumnHeight = dataTree.get_Branch(i).Count;
                }
            }

            string[,] dataTreeArray = new string[dataTree.Branches.Count, currentColumnHeight];

            for (int i = 0; i < dataTree.Branches.Count; i++) //for each column
            {
                for (int j = 0; j < dataTree.get_Branch(i).Count; j++)
                {
                    dataTreeArray[i, j] = dataTree.get_Branch(i)[j].ToString();
                }
            }


            List <string> report;
            Table         reportObject = new Table(headings, alignment, dataTreeArray);

            report = reportObject.Create();

            DA.SetDataList(0, report);
        }
コード例 #32
0
ファイル: AntPicnic.cs プロジェクト: nreifenstein/Picnic
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            List<object> v_list = new List<object>();
            GH_ObjectWrapper gh_dict = new GH_ObjectWrapper();
            IDictionary<string, string> dict = new Dictionary<string,string>();
            string k = "";

            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            if (!DA.GetData(1, ref pyString)) return;
            if (!DA.GetDataList(2, v_list)) return;
            if (!DA.GetData(3, ref nGen)) return;
            if (!DA.GetData(4, ref gh_dict)) return;
            if (!DA.GetData(5, ref k)) return;

            //dict = (IDictionary<string, string>)gh_dict.Value;

            //object d = gh_dict.Value;
            var t = Type.GetType("IronPython.Runtime.PythonDictionary,IronPython");
            IDictionary i_dict = Activator.CreateInstance(t) as IDictionary;
            //IronPython.Runtime.PythonDictionary d = gh_dict.Value;
            //string v = d.get(k);
            string v = "oops";

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            //object[] val_list = new object[gph.nodes.Count];
            //int v_i = 0;
            //for (int i = 0; i < gph.nodes.Count; i++)
            //{
            //    if (v_i == v_list.Count) v_i = 0;
            //    val_list[i] = v_list[v_i];
            //    v_i++;
            //}

            //AWorld wrld = new AWorld(gph, val_list);

            //_py = PythonScript.Create();
            //_py.Output = this.m_py_output.Write;
            //_compiled_py = _py.Compile(pyString);

            //// console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            //// Main evaluation cycle
            //// Should move code into the Antsworld Class
            //for (int g = 0; g < nGen; g++)
            //{
            //    // console out
            //    this.m_py_output.Reset();

            //    double[] new_vals = new double[wrld.NodeCount];
            //    for (int i = 0; i < wrld.NodeCount; i++)
            //    {
            //        int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

            //        // build list of neighboring values
            //        List<double> neighboring_vals = new List<double>();
            //        for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

            //        double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
            //        //double d = g + i + 0.0;

            //        new_vals[i] = d;
            //    }
            //    wrld.AddGen(new_vals);

            //    // console out
            //    Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
            //    List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
            //    foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
            //    consoleOut.AppendRange(gh_strs, key_path);

            //}

            DA.SetDataTree(0, consoleOut);
            //DA.SetData(1, wrld);
            DA.SetData(2, v);
        }
コード例 #33
0
ファイル: AntsEngine.cs プロジェクト: ksteinfe/ants
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            bool SelectType = false;
            List<double> v_list = new List<double>();
            Random rnd = new Random();

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            string spyString = "";
            if (!DA.GetData(1, ref spyString)) return;
            if (!DA.GetData(2, ref SelectType)) return;
            if (!DA.GetData(3, ref pyString)) return;
            if (!DA.GetDataList(4, v_list)) return;
            if (!DA.GetData(5, ref nGen)) return;

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            double[] val_list = new double[gph.nodes.Count];
            int v_i = 0;
            for (int i = 0; i < gph.nodes.Count; i++)
            {
                if (v_i == v_list.Count) v_i = 0;
                val_list[i] = v_list[v_i];
                v_i++;
            }

            AWorld wrld = new AWorld(gph, val_list);

            // evaluation function
            _py = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_py = _py.Compile(pyString);

            // selection function
            _spy = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_spy = _py.Compile(spyString);

            // console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            // Main evaluation cycle
            // Should move code into the Antsworld Class
            for (int g = 0; g < nGen; g++)
            {
                // console out
                this.m_py_output.Reset();
                double[] new_vals = new double[wrld.NodeCount];

                // build list to test
                List<int> nodes_to_test = new List<int>();

                for (int i = 0; i < wrld.NodeCount; i++)
                {
                    // build this now since we will only change a few of them later
                    new_vals[i] = wrld.LatestGen[i];

                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);
                    double[] n_wts = wrld.gph.NeighboringWeightsOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    bool test = SelectCell(i, wrld.LatestGen[i], neighboring_vals, n_wts);

                    if (test) nodes_to_test.Add(i);

                }

                if (SelectType)
                {
                    int trial = rnd.Next(nodes_to_test.Count);
                    int new_index = nodes_to_test[trial];
                    nodes_to_test[0] = new_index;
                    nodes_to_test.RemoveRange(1, nodes_to_test.Count - 1);
                }

                // evaluate list of cells
                for (int j = 0; j < nodes_to_test.Count; j++)
                {
                    int i = nodes_to_test[j];
                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals, wrld.gph.NeighboringWeightsOf(i));
                    //double d = g + i + 0.0;

                    new_vals[i] = d;
                }
                wrld.AddGen(new_vals);

                // console out
                Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
                List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
                foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
                consoleOut.AppendRange(gh_strs, key_path);

            }

            DA.SetDataTree(0, consoleOut);
            DA.SetData(1, wrld);
        }
コード例 #34
0
ファイル: Guage.cs プロジェクト: ahmedhosny/Ibis
        protected override void BeforeSolveInstance()
        {
            Grasshopper.Kernel.Parameters.Param_Integer myMaterialParam = Params.Input[0] as Grasshopper.Kernel.Parameters.Param_Integer;
            myMaterialParam.ClearNamedValues();

            //////////  Code for automatically loading Materials from XML when intance of class is initiated.
            IBIS_XML.Load("D:\\Dropbox\\_F13\\6338\\GH Plugin\\Ibis\\Ibis\\IBIS_XML.xml");
            List <String> myMaterialNameList = new List <string>();
            XmlNodeList   myList             = IBIS_XML.GetElementsByTagName("Material");

            foreach (XmlNode mx in myList)
            {
                XmlElement x             = mx as XmlElement;
                string     myXMLMaterial = x.GetAttribute("type");
                myMaterialNameList.Add(myXMLMaterial);
            }

            for (int i = 0; i < myMaterialNameList.Count; i++)
            {
                myMaterialParam.AddNamedValue(myMaterialNameList[i], i + 1);
            }



            Grasshopper.Kernel.Parameters.Param_Integer myGrainParam = Params.Input[2] as Grasshopper.Kernel.Parameters.Param_Integer;
            myGrainParam.ClearNamedValues();


            Grasshopper.Kernel.Parameters.Param_Integer myThicknessParam = Params.Input[3] as Grasshopper.Kernel.Parameters.Param_Integer;
            myThicknessParam.ClearNamedValues();


            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer> myMaterialValue = myMaterialParam.VolatileData as Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer>;
            //GH_Structure<GH_Integer> data = param0.VolatileData as GH_Structure<GH_Integer>;
        }
コード例 #35
0
        //Get list of materials and their corresponding gauge values
        protected override void BeforeSolveInstance()
        {
            Grasshopper.Kernel.Parameters.Param_Integer myMaterialParam = Params.Input[0] as Grasshopper.Kernel.Parameters.Param_Integer;
            myMaterialParam.ClearNamedValues();
            Grasshopper.Kernel.Parameters.Param_Integer myGaugeParam = Params.Input[1] as Grasshopper.Kernel.Parameters.Param_Integer;
            myGaugeParam.ClearNamedValues();

            //////////  Code for automatically loading Materials from XML when intance of class is initiated.
            IBIS_XML.Load("D:\\Dropbox\\_F13\\6338\\GH Plugin\\Ibis\\Ibis\\IBIS_XML.xml");
            List <String> myMaterialNameList = new List <string>();
            XmlNodeList   myList             = IBIS_XML.GetElementsByTagName("ThicknessMaterial");

            foreach (XmlNode mx in myList)
            {
                XmlElement x             = mx as XmlElement;
                string     myXMLMaterial = x.GetAttribute("type");
                myMaterialNameList.Add(myXMLMaterial);
            }

            for (int i = 0; i < myMaterialNameList.Count; i++)
            {
                myMaterialParam.AddNamedValue(myMaterialNameList[i], i + 1);
            }


            Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer> myMaterialValue = myMaterialParam.VolatileData as Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_Integer>;

            if (myMaterialValue.IsEmpty)
            {
                return;
            }

            //Code to load the Gauge list depending on user Material input:-
            List <String> myGaugeList = new List <string>();

            IBIS_XML.Load("D:\\Dropbox\\_F13\\6338\\GH Plugin\\Ibis\\Ibis\\IBIS_XML.xml");
            foreach (Grasshopper.Kernel.Types.GH_Integer myThis in myMaterialValue.AllData(true))
            {
                switch (myThis.Value)
                {
                case 1:     //for standard steel
                    //////////Gauge numbers
                    XmlNodeList myNodeList1 = IBIS_XML.SelectNodes("IBIS/ThicknessGauge/ThicknessMaterial[@id=1]/Gauge");
                    foreach (XmlNode myNode in myNodeList1)
                    {
                        XmlElement myElement  = myNode as XmlElement;
                        String     myXMLGauge = myElement.GetAttribute("type");
                        myGaugeList.Add(myXMLGauge);
                    }

                    for (int i = 0; i < myGaugeList.Count; i++)
                    {
                        myGaugeParam.AddNamedValue(myGaugeList[i], i + 1001);
                    }
                    break;
                }
                return;
            }
        }