public static List <GeometryBase> AllVisableGeometryInGHDocmument() { var canvas = Instances.ActiveCanvas; if (canvas == null) { throw new Exception("No Document Server exist!"); } if (!canvas.IsDocument) { throw new Exception("No Document Server exist!"); } GH_Document doc = canvas.Document; if (doc == null) { throw new Exception("Tasker 未找到GH_Document"); } var list = new List <GeometryBase>(); foreach (IGH_DocumentObject obj in doc.Objects) { if (!(obj is IGH_PreviewObject prev) || prev.Hidden || !(obj is IGH_Component comp)) { continue; } comp.Params.Output.ForEach((IGH_Param output) => { IGH_Structure data = output.VolatileData; if (!data.IsEmpty) { foreach (var dat in data.AllData(true)) { GeometryBase geometry = GH_Convert.ToGeometryBase(dat); if (geometry == null) { continue; } list.Add(geometry); } } }); } return(list); }
public static void AddVolatileDataTree <T1, T2>(this IGH_Param param, IGH_Structure structure, Converter <T1, T2> converter) where T1 : IGH_Goo where T2 : IGH_Goo { for (int p = 0; p < structure.PathCount; ++p) { var path = structure.get_Path(p); var srcBranch = structure.get_Branch(path); var data = srcBranch.As <T1>().Select(x => x == null ? default : converter(x)); param.AddVolatileDataList(path, data); } }
protected override void BeforeSolveInstance() { ClearOutput(); curve = false; line = false; polyline = false; arc = false; circle = false; ellipse = false; IGH_Structure dd = Params.Input[0].VolatileData; double tolerance = 0; foreach (IGH_Goo number in Params.Input[1].VolatileData.AllData(true)) { GH_Number num = (GH_Number)number; tolerance = num.Value; } foreach (IGH_Goo geo in dd.AllData(true)) { GH_Curve crv = (GH_Curve)geo; if (crv.Value.IsLinear(tolerance)) { line = true; } else if (crv.Value.IsPolyline()) { polyline = true; } else if (crv.Value.IsCircle(tolerance)) { circle = true; } else if (crv.Value.IsArc(tolerance)) { arc = true; } else if (crv.Value.IsEllipse(tolerance)) { ellipse = true; } else { curve = true; } } AddOutput(); }
// // Compare two structures for equality. // internal bool isStructureTheSame(IGH_Structure struct1, IGH_Structure struct2) { // m_owner.attr.Panel.Message(m_owner.NickName + ": Compare:"); if (struct1 == null ^ struct2 == null) { //m_owner.attr.Panel.Message(" One of the structures is null"); return(false); } if (struct1.IsEmpty ^ struct2.IsEmpty) { //m_owner.attr.Panel.Message(" One of the structures is empty"); return(false); } if (struct1 != null && struct2 != null) { int pc = Math.Min(struct1.Paths.Count, struct2.Paths.Count); for (int i = 0; i < pc; i++) { IList b1 = struct1.get_Branch(struct1.Paths[i]); IList b2 = struct2.get_Branch(struct2.Paths[i]); int bc = Math.Min(b1.Count, b2.Count); for (int j = 0; j < bc; j++) { if (b1[j] is GH_Integer && b2[j] is GH_Integer) { GH_Integer n1 = (GH_Integer)b1[j]; GH_Integer n2 = (GH_Integer)b2[j]; if (n1.Value != n2.Value) { return(false); } } else if (b1[j] is GH_Number && b2[j] is GH_Number) { GH_Number n1 = (GH_Number)b1[j]; GH_Number n2 = (GH_Number)b2[j]; if (Math.Round(n1.Value, 8) != Math.Round(n2.Value, 8)) { return(false); } } } } } return(true); }
// // Check if a structure is null. // internal bool isNull(IGH_Structure s) { if (!s.IsEmpty) { foreach (GH_Path p in s.Paths) { foreach (IGH_Goo item in s.get_Branch(p)) { if (item != null) { return(false); } } } } return(true); }
internal bool isInLoop(IGH_Structure s) { foreach (GH_Path p in s.Paths) { foreach (IGH_Goo item in s.get_Branch(p)) { if (item is GH_Boolean && !((GH_Boolean)item).Value) { return(false); } else if (item is GH_Number && m_owner.CStep >= ((GH_Number)item).Value) { return(false); } } } return(true); }
protected override void BeforeSolveInstance() { ClearOutput(); point = false; curve = false; surface = false; brep = false; mesh = false; IGH_Structure dd = Params.Input[0].VolatileData; foreach (IGH_Goo geo in dd.AllData(true)) { if (geo is GH_Point) { point = true; } else if (geo is GH_Curve)////curve { curve = true; } else if (geo is GH_Brep) { GH_Brep bp = (GH_Brep)geo; if (bp.Value.IsSurface)///surface { surface = true; } else//////brep { brep = true; } } else if (geo is GH_Mesh) { mesh = true; GH_Mesh me = (GH_Mesh)geo; } } AddOutput(); }
// // Duplicate a structure. // internal GH_Structure <IGH_Goo> duplicateStructure(IGH_Structure source) { GH_Structure <IGH_Goo> copy = new GH_Structure <IGH_Goo>(); foreach (GH_Path p in source.Paths) { List <IGH_Goo> l = new List <IGH_Goo>(); foreach (IGH_Goo item in source.get_Branch(p)) { if (item == null) { l.Add(null); } else { l.Add(item.Duplicate()); } } copy.AppendRange(l, p); } return(copy); }
public static GH_Structure <T> DuplicateAs <T>(this IGH_Structure structure, bool shallowCopy) where T : IGH_Goo { // GH_Structure<T> constructor is a bit faster if shallowCopy is true because // it doesn't need to cast on each item. if (structure is GH_Structure <T> structureT) { return(new GH_Structure <T>(structureT, shallowCopy)); } var result = new GH_Structure <T>(); for (int p = 0; p < structure.PathCount; ++p) { var path = structure.get_Path(p); var srcBranch = structure.get_Branch(path); var destBranch = result.EnsurePath(path); destBranch.Capacity = srcBranch.Count; var data = srcBranch.As <T>(); if (!shallowCopy) { data = data.Select(x => x?.Duplicate() is T t ? t : default);
internal static IEnumerable <Types.IGH_ElementId> ToElementIds(IGH_Structure data) => data.AllData(true). OfType <Types.IGH_ElementId>(). Where(x => x.IsValid);
protected override void SolveInstance(IGH_DataAccess DA) { UpdateMessage(); PythonScript script = PythonScript.Create(); string outDir = ""; try { script.ExecuteScript("import scriptcontext as sc\nV=sc.sticky['NOAH_PROJECT']\nT=sc.sticky['TASK_TICKET']\nG=sc.sticky['NOAH_GENERATOR']\nID=sc.sticky['UUID']"); NOAH_PROJECT = (string)script.GetVariable("V"); TASK_TICKET = (string)script.GetVariable("T"); NOAH_GENERATOR = (string)script.GetVariable("G"); UUID = (string)script.GetVariable("ID"); if (File.Exists(NOAH_PROJECT)) { outDir = Path.Combine(Path.GetDirectoryName(NOAH_PROJECT), ".noah", "tasks", UUID, TASK_TICKET, "out"); ProjectInfo = JObject.Parse(File.ReadAllText(NOAH_PROJECT)); JArray generators = JArray.Parse(ProjectInfo["generators"].ToString()); FindJobjectFromJArray(generators, NOAH_GENERATOR, out Generator, out GeneratorIndex); } } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); } int outIndex = 0; DA.GetData(1, ref outIndex); JArray output = JArray.Parse(Generator["output"].ToString()); if (outIndex >= output.Count) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "定义时未指定此输出端口"); } switch (m_mode) { case ExportMode.None: Message = null; break; case ExportMode.Rhino: string fileName = Convert.ToString(outIndex) + ".3dm"; string filePath = Path.Combine(outDir, fileName); File3dmWriter writer = new File3dmWriter(filePath); List <int> ll = new List <int>(); List <ObjectLayerInfo> layeredObj = new List <ObjectLayerInfo>(); DA.GetDataList(0, layeredObj); layeredObj.ForEach(x => { writer.ChildLayerSolution(x.Name); ll.Add(writer.CreateLayer(x.Name, x.Color)); }); if (layeredObj.Count > 0) { writer.Write(layeredObj, ll); if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } } break; case ExportMode.Text: if (!exported) { string outputData = ""; DA.GetData(0, ref outputData); ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = outputData; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; case ExportMode.Data: fileName = Convert.ToString(outIndex) + ".noahdata"; filePath = Path.Combine(outDir, fileName); if (string.IsNullOrWhiteSpace(filePath)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "未指定文件."); return; } GH_LooseChunk val = new GH_LooseChunk("Grasshopper Data"); val.SetGuid("OriginId", base.InstanceGuid); val.SetInt32("Count", base.Params.Input.Count); IGH_Param iGH_Param = base.Params.Input[0]; IGH_Structure volatileData = iGH_Param.VolatileData; GH_IWriter val2 = val.CreateChunk("Block", 0); val2.SetString("Name", iGH_Param.NickName); val2.SetBoolean("Empty", volatileData.IsEmpty); if (!volatileData.IsEmpty) { GH_Structure <IGH_Goo> tree = null; DA.GetDataTree(0, out tree); if (!tree.Write(val2.CreateChunk("Data"))) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"There was a problem writing the {iGH_Param.NickName} data."); } } byte[] bytes = val.Serialize_Binary(); try { File.WriteAllBytes(filePath, bytes); } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, ex.Message); } if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; case ExportMode.CSV: fileName = Convert.ToString(outIndex) + ".csv"; filePath = Path.Combine(outDir, fileName); List <object> oList = new List <object>(); List <string> sList = new List <string>(); DA.GetDataList(0, oList); oList.ForEach(el => { string tmp = ""; GH_Convert.ToString(el, out tmp, GH_Conversion.Both); sList.Add(tmp); }); File.WriteAllText(filePath, string.Join(Environment.NewLine, sList)); if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; } }
internal static IEnumerable <ElementId> ToElementIds(IGH_Structure data) => data.AllData(true). OfType <Types.IGH_ElementId>(). Where(x => x is object). Select(x => x.Id);
//test if all branches have exactly the same length. Assumes A and B have the same number of branches bool sameBranchLengths(IGH_Structure A, IGH_Structure B) { bool results = true; for (int i = 0; i < A.PathCount; i++) { if (A.get_Branch(i).Count != B.get_Branch(i).Count) results = false; } return results; }
//test if all branches have 1 item bool oneItemPerBranch(IGH_Structure g) { bool results = true; for (int i = 0; i < g.PathCount;i++ ) { if (g.get_Branch(i).Count != 1) results = false; } return results; }
protected override void Render(GH_Canvas canvas, Graphics graphics, GH_CanvasChannel channel) { if (channel == GH_CanvasChannel.Wires) { RenderIncomingWires(canvas.Painter, Owner.Sources, Owner.WireDisplay); } if (channel == GH_CanvasChannel.Objects) { base.Render(canvas, graphics, channel); GH_Palette palette = GH_Palette.Normal; switch (Owner.RuntimeMessageLevel) { case GH_RuntimeMessageLevel.Warning: palette = GH_Palette.Warning; break; case GH_RuntimeMessageLevel.Error: palette = GH_Palette.Error; break; } GH_Capsule capsule = GH_Capsule.CreateCapsule(Bounds, palette); capsule.AddInputGrip(InputGrip.Y); capsule.Render(graphics, Selected, Owner.Locked, true); capsule.Dispose(); StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; format.Trimming = StringTrimming.EllipsisCharacter; RectangleF textRectangle = Bounds; textRectangle.Height = 20; graphics.DrawString(Owner.NickName, GH_FontServer.Standard, Brushes.Black, textRectangle, format); int displayWidth = (int)(Bounds.Width - padding * 2); int displayHeight = (int)(Bounds.Height - padding * 4); System.Drawing.Point position = new System.Drawing.Point((int)(Bounds.X + padding), (int)(Bounds.Y + padding * 3)); Rectangle PatternRectangle = new Rectangle(position.X, position.Y, displayWidth, displayHeight); graphics.DrawRectangle(new Pen(Color.White), PatternRectangle); IGH_Structure data = Owner.VolatileData; if (data.PathCount != 0) { GH_Path path = data.get_Path(0); List <GH_Number> branch = data.get_Branch(path) as List <GH_Number>; int patternSize = branch.Count; float width = (float)Math.Ceiling(Math.Sqrt((double)patternSize)); if (displayWidth > displayHeight) { displaySize = displayHeight; } else { displaySize = displayWidth; } float rectSize = (float)(displaySize / width); RectangleF[] rectangles = new RectangleF[patternSize]; for (int i = 0; i < patternSize; i++) { PointF pos = new PointF((float)(Bounds.X + padding), (float)(Bounds.Y + padding * 3)); pos = new PointF(pos.X + rectSize * (float)Math.Floor(i % width), pos.Y + rectSize * (float)Math.Floor(i / width)); RectangleF content = new RectangleF(pos.X, pos.Y, rectSize, rectSize); rectangles[i] = content; SolidBrush brush; if ((int)branch[i].Value == 0) { brush = new SolidBrush(Color.White); } else if ((int)branch[i].Value == 1) { brush = new SolidBrush(Color.Black); } else { brush = new SolidBrush(Color.Orange); } graphics.FillRectangle(brush, rectangles[i]); } } format.Dispose(); } }