protected override void SolveInstance(IGH_DataAccess DA) { bool S = false; DA.GetData(0, ref S); PythonScript script = PythonScript.Create(); script.SetVariable("bakeornot", S ? 1 : 0); script.ExecuteScript("import scriptcontext as sc\nsc.sticky['NOAH_BAKE_INFO'] = bakeornot"); foreach (IGH_DocumentObject obj in ghDoc.Objects) { if (obj is GH_Cluster) { GH_Cluster objCluster = (GH_Cluster)obj; GH_Document clusterDoc = objCluster.Document(""); foreach (IGH_DocumentObject clusterObj in clusterDoc.Objects) { if (clusterObj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9")) { clusterObj.ExpireSolution(true); } } obj.ExpireSolution(true); } else { if (obj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9")) { obj.ExpireSolution(true); } } } }
protected override void SolveInstance(IGH_DataAccess DA) { string str = ""; object obj = null; DA.GetData <string>(0, ref str); DA.GetData <object>(1, ref obj); PythonScript val = PythonScript.Create(); val.SetVariable("V", obj); val.ExecuteScript("import scriptcontext as sc\nsc.sticky['" + str + "'] = V"); }
public void ExecuteScript() { try { var script = new PythonScript(GetCodeToExecute()); script.ExecuteScript(); var pi = PythonInterpreter.Instance; Trace.Write(pi.GetOutput()); } catch (Exception exc) { Trace.TraceWarning(exc.Message); return; } }
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; } }
// the main listener function protected void TcpServerWorkerListening(object sender, DoWorkEventArgs e) { //---listen at the specified IP and port no.--- const int portNo = 614; IPAddress serverIp = IPAddress.Parse("127.0.0.1"); if (_server == null) { _server = new TcpListener(serverIp, portNo); } try { _server.Start(); RhinoApp.WriteLine("VS Code Listener Started..."); } catch (Exception err) { RhinoApp.WriteLine(err.ToString()); } while (true) { // incoming client connected TcpClient client; try { client = _server.AcceptTcpClient(); } catch (Exception serverException) { return; } // get the incoming data through a network stream NetworkStream nwStream = client.GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; // read incoming stream int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); // convert the data received into a string StringBuilder msg = new StringBuilder(); // parse the buffer into msg foreach (var b in buffer) { if (b.Equals(00)) { break; } msg.Append(Convert.ToChar(b).ToString()); } // parse the received message into C# Object string msgString = msg.ToString(); msgString = Regex.Split(msgString, "}")[0] + "}"; MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(msgString)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(msgObject)); msgObject msgObj; try { msgObj = ser.ReadObject(ms) as msgObject; } catch (Exception ex) { RhinoApp.WriteLine("Received invalid data, please try again."); return; } ms.Close(); // invoke the main task in the main thread Application.Current.Dispatcher.Invoke(() => { // create python script runner PythonScript myScript = PythonScript.Create(); // redirect output to _output field myScript.Output = PrintToVSCode; FeedbackSender feedbackSender = new FeedbackSender(nwStream); GotCodeFeekBack += feedbackSender.OnGotCodeFeedBack; // if flagged reset, then reset the script engine. if (msgObj.reset) { ResetScriptEngine.ResetEngine(); } // if it is not a temp folder, add the folder to python library path if (!msgObj.temp) { string pythonFilePath = Path.GetDirectoryName(msgObj.filename); string code = string.Format("import sys\nimport os\nif \"{0}\" not in sys.path: sys.path.append(\"{0}\")", pythonFilePath); try { myScript.ExecuteScript(code); } catch (Exception exception) { PrintToVSCode(exception.Message); } } // determines if run actual script if (msgObj.run) { uint sn = _idoc.BeginUndoRecord("VS Code execution"); var sn_start = RhinoObject.NextRuntimeSerialNumber; try { if (msgObj.minimize) { Utils.MinimizeVSCodeWindow(); } myScript.ExecuteFile(msgObj.filename); } catch (Exception ex) { // get the exception message var error = myScript.GetStackTraceFromException(ex); string message = ex.Message + "\n" + error; // send exception msg back to VS Code PrintToVSCode(message); } finally { CloseConnection(nwStream); _idoc.EndUndoRecord(sn); if (msgObj.minimize) { Utils.RestoreVSCodeWindow(); } // fix the rs.Prompt bug RhinoApp.SetCommandPrompt("Command"); // select created objects var sn_end = RhinoObject.NextRuntimeSerialNumber; if (sn_end > sn_start) { for (var i = sn_start; i < sn_end; i++) { var obj = _idoc.Objects.Find(i); if (null != obj) { obj.Select(true); } } } // enable the view _idoc.Views.RedrawEnabled = true; } } else { CloseConnection(nwStream); } }); } }
protected override void SolveInstance(IGH_DataAccess DA) { GeometryBase G = null; string L = "预设值"; List <Curve> H = new List <Curve>(); Color C = Color.Black; DA.GetData(0, ref G); DA.GetData(1, ref L); DA.GetDataList(2, H); DA.GetData(3, ref C); int NOAH_BAKE_INFO = 0; try { PythonScript script = PythonScript.Create(); script.ExecuteScript("import scriptcontext as sc\nV=sc.sticky['NOAH_BAKE_INFO']"); NOAH_BAKE_INFO = (int)script.GetVariable("V"); } catch { NOAH_BAKE_INFO = 0; } if (NOAH_BAKE_INFO == 1) { if (G != null && H.Count == 0) { //写入物件 ObjectAttributes att = getObjAttr(L, rhinoDoc, C); switch (G.ObjectType) { case ObjectType.Brep: rhinoDoc.Objects.AddBrep(G as Brep, att); break; case ObjectType.Curve: rhinoDoc.Objects.AddCurve(G as Curve, att); break; case ObjectType.Point: rhinoDoc.Objects.AddPoint((G as Rhino.Geometry.Point).Location, att); break; case ObjectType.Surface: rhinoDoc.Objects.AddSurface(G as Surface, att); break; case ObjectType.Mesh: rhinoDoc.Objects.AddMesh(G as Mesh, att); break; case ObjectType.PointSet: rhinoDoc.Objects.AddPointCloud(G as Rhino.Geometry.PointCloud, att); //This is a speculative entry break; default: AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "不能识别的物体: " + G.GetType().FullName); break; } } else if (G == null && H.Count > 0) { ObjectAttributes att = getObjAttr(L, rhinoDoc, C); Hatch[] hatches = Hatch.Create(H, 0, 0, 1, 0); foreach (Hatch hatch in hatches) { rhinoDoc.Objects.AddHatch(hatch, att); } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "G和H只能输入一个"); } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "等待写入"); } }