protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetOption(); go.SetCommandPrompt("Choose an option"); go.AddOption("Add"); go.AddOption("Delete"); go.AddOption("List"); go.AcceptNothing(true); var res = go.Get(); Result rc; switch (res) { case GetResult.Option: rc = CommandOption(go.Option()); break; case GetResult.Nothing: rc = Result.Success; break; default: rc = Result.Cancel; break; } return(rc); }
/// <summary> /// Call to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var panel_id = SchemaBuilderPanelControl.PanelId; var visible = Panels.IsPanelVisible(panel_id); string prompt = (visible) ? "Chromium panel is visible. New value" : "Chromium Manager panel is hidden. New value"; var go = new GetOption(); go.SetCommandPrompt(prompt); var hide_index = go.AddOption("Hide"); var show_index = go.AddOption("Show"); var toggle_index = go.AddOption("Toggle"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var option = go.Option(); if (null == option) { return(Result.Failure); } var index = option.Index; if (index == hide_index) { if (visible) { Panels.ClosePanel(panel_id); } } else if (index == show_index) { if (!visible) { Panels.OpenPanel(panel_id); } } else if (index == toggle_index) { if (visible) { Panels.ClosePanel(panel_id); } else { Panels.OpenPanel(panel_id); } } return(Result.Success); }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { GetOption go = new GetOption(); go.SetCommandPrompt("Select command option"); int add_index = go.AddOption("Add"); int delete_index = go.AddOption("Delete"); int list_index = go.AddOption("List"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } CommandLineOption option = go.Option(); if (null == option) { return(Result.Failure); } int index = option.Index; if (index == add_index) { string str = string.Empty; Result rc = RhinoGet.GetString("String to add", false, ref str); if (rc == Result.Success) { SampleCsStringTableHelpers.Add(str); } } else if (index == delete_index) { string str = string.Empty; Result rc = RhinoGet.GetString("String to delete", false, ref str); if (rc == Result.Success) { SampleCsStringTableHelpers.Remove(str); } } else if (index == list_index) { int count = SampleCsStringTableHelpers.Count(); if (0 == count) { RhinoApp.WriteLine("0 string items to list."); } else { for (int i = 0; i < count; i++) { RhinoApp.WriteLine(SampleCsStringTableHelpers.GetAt(i)); } } } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var panel_id = typeof(SampleCsWpfPanelHost).GUID; var panel_visible = Panels.IsPanelVisible(panel_id); var prompt = (panel_visible) ? "Sample panel is visible. New value" : "Sample Manager panel is hidden. New value"; var go = new GetOption(); go.SetCommandPrompt(prompt); var hide_index = go.AddOption("Hide"); var show_index = go.AddOption("Show"); var toggle_index = go.AddOption("Toggle"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var option = go.Option(); if (null == option) { return(Result.Failure); } var index = option.Index; if (index == hide_index) { if (panel_visible) { Panels.ClosePanel(panel_id); } } else if (index == show_index) { if (!panel_visible) { Panels.OpenPanel(panel_id); } } else if (index == toggle_index) { if (panel_visible) { Panels.ClosePanel(panel_id); } else { Panels.OpenPanel(panel_id); } } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var panel_id = SpeckleRhinoUserControl.PanelId; var visible = Panels.IsPanelVisible(panel_id); var prompt = visible ? "Speckle panel is visible." : "Speckle panel is hidden."; var go = new GetOption(); go.SetCommandPrompt(prompt); var hide_index = go.AddOption("Hide"); var show_index = go.AddOption("Show"); var toggle_index = go.AddOption("Toggle"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var option = go.Option(); if (null == option) { return(Result.Failure); } var index = option.Index; if (index == hide_index) { if (visible) { Panels.ClosePanel(panel_id); } } else if (index == show_index) { if (!visible) { Panels.OpenPanel(panel_id); } } else if (index == toggle_index) { if (visible) { Panels.ClosePanel(panel_id); } else { Panels.OpenPanel(panel_id); } } return(Result.Success); }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { System.Guid panel_id = SampleCsMainPanel.PanelId; bool visible = Panels.IsPanelVisible(panel_id); string prompt = (visible) ? "Main panel is visible. New value" : "Main Manager panel is hidden. New value"; GetOption go = new GetOption(); int hide_index = go.AddOption("Hide"); int show_index = go.AddOption("Show"); int toggle_index = go.AddOption("Toggle"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } CommandLineOption option = go.Option(); if (null == option) { return(Result.Failure); } int index = option.Index; if (index == hide_index) { if (visible) { Panels.ClosePanel(panel_id); } } else if (index == show_index) { if (!visible) { Panels.OpenPanel(panel_id); } } else if (index == toggle_index) { if (visible) { Panels.ClosePanel(panel_id); } else { Panels.OpenPanel(panel_id); } } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var enabled = SampleCsEventHandlers.Instance.IsEnabled; var prompt = enabled ? "Event watcher is enabled. New value" : "Event watcher is disabled. New value"; var go = new GetOption(); go.SetCommandPrompt(prompt); go.AcceptNothing(true); var d_option = go.AddOption("Disable"); var e_option = go.AddOption("Enable"); var t_option = go.AddOption("Toggle"); var res = go.Get(); if (res == GetResult.Nothing) { return(Result.Success); } if (res != GetResult.Option) { return(Result.Cancel); } var option = go.Option(); if (null == option) { return(Result.Failure); } if (d_option == option.Index) { if (enabled) { SampleCsEventHandlers.Instance.Enable(false); } } else if (e_option == option.Index) { if (!enabled) { SampleCsEventHandlers.Instance.Enable(true); } } else if (t_option == option.Index) { SampleCsEventHandlers.Instance.Enable(!enabled); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { int index = SampleCsCommandsPlugIn.Instance.IsolateIndex - 1; if (index < 0) { RhinoApp.WriteLine("No isolated objects to unisolate."); SampleCsCommandsPlugIn.Instance.IsolateIndex = 0; return(Result.Nothing); } var go = new GetOption(); go.SetCommandPrompt("Choose unisolate option"); int a_opt = go.AddOption("All"); int p_opt = go.AddOption("Previous"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var opt = go.Option(); if (null == opt) { return(Result.Failure); } string script = null; if (opt.Index == a_opt) { script = "_-Show _Enter"; SampleCsCommandsPlugIn.Instance.IsolateIndex = 0; } else if (opt.Index == p_opt) { script = string.Format("_-Show {0}", index); SampleCsCommandsPlugIn.Instance.IsolateIndex--; } else { return(Result.Failure); } RhinoApp.RunScript(script, false); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetOption(); go.SetCommandPrompt("Optimize B"); go.AddOption("Run"); while (true) { go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } if (go.Option().EnglishName == "Run") { RhinoApp.WriteLine("Running optimization..."); break; } } var optimize = new OptimizerB(50, 10); var conduit = new ConduitB(); conduit.Enabled = true; conduit.Path = optimize.Path; conduit.Info = optimize.Info; Task redrawTask = null; optimize.UpdateCandidate = () => { conduit.Path = optimize.Path; conduit.Info = optimize.Info; if (redrawTask?.IsCompleted != false) { redrawTask = Task.Run(doc.Views.Redraw); } }; optimize.Finished = () => { RhinoApp.WriteLine(optimize.Info); doc.Objects.AddPolyline(optimize.Path); doc.Views.Redraw(); conduit.Enabled = false; }; Task.Run(optimize.SimulatedAnnealing); return(Result.Success); }
public override Direction EnterDirection(string prompt = "Enter direction", bool xyzOnly = false) { GetOption gO = new GetOption(); gO.SetCommandPrompt(prompt); gO.AddOption("X"); gO.AddOption("Y"); gO.AddOption("Z"); if (!xyzOnly) { gO.AddOption("XX"); gO.AddOption("YY"); gO.AddOption("ZZ"); } // TODO throw new NotImplementedException(); }
/// <summary> /// Called by Rhino when the user runs the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select object"); go.SubObjectSelect = false; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var obj_ref = go.Object(0); var obj = obj_ref.Object(); if (null == obj) { return(Result.Failure); } var pre_selected = go.ObjectsWerePreselected; obj.Select(true); var gt = new GetOption(); gt.SetCommandPrompt("Choose mobile plane option"); gt.AcceptNothing(true); var attach_index = gt.AddOption("Attach"); var detach_index = gt.AddOption("Detach"); var enable_index = gt.AddOption("Enable"); var refresh_index = gt.AddOption("Refresh"); var show_index = gt.AddOption("Show"); for (;;) { var res = gt.Get(); if (res != GetResult.Option) { break; } var rc = Result.Cancel; var index = gt.OptionIndex(); if (index == attach_index) { rc = AttachOption(doc, obj); } else if (index == detach_index) { rc = DetachOption(doc, obj); } else if (index == enable_index) { rc = EnableOption(doc, obj); } else if (index == refresh_index) { rc = RefreshOption(doc, obj); } else if (index == show_index) { rc = ShowOption(doc, obj); } if (rc != Result.Success) { break; } } if (!pre_selected) { doc.Objects.UnselectAll(); } doc.Views.Redraw(); return(Result.Success); }
/// <summary> /// Command.RunCommand override /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { Potrace.Clear(); // Prompt the user for the name of the image file to vectorize. string path = GetImageFileName(mode); if (string.IsNullOrEmpty(path)) { return(Result.Cancel); } // Creates a bitmap from the specified file. var bitmap = Image.FromFile(path) as Bitmap; if (null == bitmap) { RhinoApp.WriteLine("The specified file cannot be identifed as a supported type."); return(Result.Failure); } // Verify bitmap size if (0 == bitmap.Width || 0 == bitmap.Height) { RhinoApp.WriteLine("Error reading the specified file."); return(Result.Failure); } // Calculate scale factor so curves of a reasonable size are added to Rhino var unit_scale = (doc.ModelUnitSystem != UnitSystem.Inches) ? RhinoMath.UnitScale(UnitSystem.Inches, doc.ModelUnitSystem) : 1.0; var scale = (double)(1.0 / bitmap.HorizontalResolution * unit_scale); // I'm not convinced this is useful... if (true) { var format = $"F{doc.DistanceDisplayPrecision}"; // Print image size in pixels RhinoApp.WriteLine("Image size in pixels: {0} x {1}", bitmap.Width, bitmap.Height ); // Print image size in inches var width = (double)(bitmap.Width / bitmap.HorizontalResolution); var height = (double)(bitmap.Height / bitmap.VerticalResolution); RhinoApp.WriteLine("Image size in inches: {0} x {1}", width.ToString(format, CultureInfo.InvariantCulture), height.ToString(format, CultureInfo.InvariantCulture) ); // Image size in in model units, if needed if (doc.ModelUnitSystem != UnitSystem.Inches) { width = (double)(bitmap.Width / bitmap.HorizontalResolution * unit_scale); height = (double)(bitmap.Height / bitmap.VerticalResolution * unit_scale); RhinoApp.WriteLine("Image size in {0}: {1} x {2}", doc.ModelUnitSystem.ToString().ToLower(), width.ToString(format, CultureInfo.InvariantCulture), height.ToString(format, CultureInfo.InvariantCulture) ); } } // Convert the bitmap to an Eto bitmap var eto_bitmap = ConvertBitmapToEto(bitmap); if (null == eto_bitmap) { RhinoApp.WriteLine("Unable to convert image to Eto bitmap."); return(Result.Failure); } // 12-Jan-2021 Dale Fugier // This should prevent Eto.Drawing.BitmapData.GetPixels() from throwing an exception if (!IsCompatibleBitmap(eto_bitmap)) { RhinoApp.WriteLine("The image has an incompatible pixel format. Please select an image with 24 or 32 bits per pixel, or 8 bit indexed."); return(Result.Failure); } // This bitmap is not needed anymore, so dispose of it bitmap.Dispose(); // Gets the Potrace settings from the plug-in settings file GetPotraceSettings(); // Create the conduit, which does most of the work var conduit = new VectorizeConduit( eto_bitmap, scale, doc.ModelAbsoluteTolerance, m_select_output ? Rhino.ApplicationSettings.AppearanceSettings.SelectedObjectColor : doc.Layers.CurrentLayer.Color ) { Enabled = true }; if (mode == RunMode.Interactive) { // Show the interactive dialog box var dialog = new VectorizeDialog(doc, conduit); dialog.RestorePosition(); var result = dialog.ShowSemiModal(doc, RhinoEtoApp.MainWindow); dialog.SavePosition(); if (result != Result.Success) { conduit.Enabled = false; Potrace.Clear(); doc.Views.Redraw(); return(Result.Cancel); } } else { // Show the command line options var go = new GetOption(); go.SetCommandPrompt("Vectorization options. Press Enter when done"); go.AcceptNothing(true); while (true) { conduit.TraceBitmap(); doc.Views.Redraw(); go.ClearCommandOptions(); // IgnoreArea var turdsize_opt = new OptionInteger(Potrace.turdsize, 2, 100); var turdsize_idx = go.AddOptionInteger("FilterSize", ref turdsize_opt, "Filter speckles of up to this size in pixels"); // TurnPolicy var turnpolicy_idx = go.AddOptionEnumList("TurnPolicy", Potrace.turnpolicy); // Optimizing var curveoptimizing_opt = new OptionToggle(Potrace.curveoptimizing, "No", "Yes"); var curveoptimizing_idx = go.AddOptionToggle("Optimizing", ref curveoptimizing_opt); // Tolerance var opttolerance_opt = new OptionDouble(Potrace.opttolerance, 0.0, 1.0); var opttolerance_idx = go.AddOptionDouble("Tolerance", ref opttolerance_opt, "Optimizing tolerance"); // CornerThreshold var alphamax_opt = new OptionDouble(Potrace.alphamax, 0.0, 100.0); var alphamax_idx = go.AddOptionDouble("CornerRounding", ref alphamax_opt, "Corner rounding threshold"); // Threshold var threshold_opt = new OptionDouble(Potrace.Treshold, 0.0, 100.0); var threshold_idx = go.AddOptionDouble("Threshold", ref threshold_opt, "Threshold"); // RestoreDefaults var defaults_idx = go.AddOption("RestoreDefaults"); var res = go.Get(); if (res == GetResult.Option) { var option = go.Option(); if (null != option) { if (turdsize_idx == option.Index) { Potrace.turdsize = turdsize_opt.CurrentValue; } if (turnpolicy_idx == option.Index) { var list = Enum.GetValues(typeof(TurnPolicy)).Cast <TurnPolicy>().ToList(); Potrace.turnpolicy = list[option.CurrentListOptionIndex]; } if (curveoptimizing_idx == option.Index) { Potrace.curveoptimizing = curveoptimizing_opt.CurrentValue; } if (opttolerance_idx == option.Index) { Potrace.opttolerance = opttolerance_opt.CurrentValue; } if (alphamax_idx == option.Index) { Potrace.alphamax = alphamax_opt.CurrentValue; } if (threshold_idx == option.Index) { Potrace.Treshold = threshold_opt.CurrentValue; } if (defaults_idx == option.Index) { Potrace.RestoreDefaults(); } } continue; } if (res != GetResult.Nothing) { conduit.Enabled = false; doc.Views.Redraw(); Potrace.Clear(); return(Result.Cancel); } break; } } // Group curves var attributes = doc.CreateDefaultAttributes(); attributes.AddToGroup(doc.Groups.Add()); for (var i = 0; i < conduit.OutlineCurves.Count; i++) { var rhobj_id = doc.Objects.AddCurve(conduit.OutlineCurves[i], attributes); if (m_select_output) { var rhobj = doc.Objects.Find(rhobj_id); if (null != rhobj) { rhobj.Select(true); } } } conduit.Enabled = false; Potrace.Clear(); doc.Views.Redraw(); // Set the Potrace settings to the plug -in settings file. SetPotraceSettings(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var cities = new OptionInteger(50, 3, 1000); var time = new OptionInteger(10, 5, 120); var algorithmIndex = 0; var get = new GetOption(); get.SetCommandPrompt("Optimize TSP"); get.AddOptionInteger("Cities", ref cities); get.AddOptionInteger("Time", ref time); get.AddOptionList("Algorithm", new[] { "RandomSearch", "HillClimbing", "SimulatedAnnealing" }, 0); get.AddOption("Run"); while (true) { get.Get(); if (get.CommandResult() != Result.Success) { return(get.CommandResult()); } if (get.Option().EnglishName == "Algorithm") { algorithmIndex = get.Option().CurrentListOptionIndex; } if (get.Option().EnglishName == "Run") { RhinoApp.WriteLine("Optimization started..."); break; } } var optimizer = new Optimizer(cities.CurrentValue, time.CurrentValue); var conduit = new OptimizeConduit(optimizer.Path) { Enabled = true }; Task updateTask = null; optimizer.UpdatedCandidate += (o, e) => { conduit.Path = optimizer.Path; conduit.Info = optimizer.Info; //doc.Views.Redraw(); if (updateTask?.IsCompleted != false) { updateTask = Task.Run(() => doc.Views.Redraw()); } }; optimizer.Finished += (o, e) => { conduit.Enabled = false; doc.Objects.AddPolyline(optimizer.Path); doc.Views.Redraw(); RhinoApp.WriteLine($"Optimization finished ({optimizer.Info})."); }; var algorithms = new Action[] { optimizer.RandomSearch, optimizer.HillClimbing, optimizer.SimulatedAnnealing }; Task.Run(algorithms[algorithmIndex]); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { if (!(RhinoApp.GetPlugInObject("Grasshopper") is GH_RhinoScriptInterface Grasshopper)) { return(Result.Cancel); } GetOption go = null; while (true) { var port = new OptionInteger(Port, 1024, 65535); var toggle = new OptionToggle(ShowEditor, "Hide", "Show"); var debugger = new OptionToggle(Debug, "Off", "On"); go = new GetOption(); go.SetCommandPrompt("Noah Server"); go.AddOption("Connect"); go.AddOption("Stop"); go.AddOption("Observer"); go.AddOptionInteger("Port", ref port); go.AddOptionToggle("Editor", ref toggle); go.AddOptionToggle("Debug", ref debugger); go.AddOption("Workspace"); GetResult result = go.Get(); if (result != GetResult.Option) { break; } ShowEditor = toggle.CurrentValue; Debug = debugger.CurrentValue; string whereToGo = go.Option().EnglishName; if (whereToGo == "Connect") { if (Port == 0) { RhinoApp.WriteLine("Please set Port you want to connect!"); continue; } if (WorkDir == null) { RhinoApp.WriteLine("Noah can not work without workspace!"); continue; } if (Client == null) { try { Grasshopper.DisableBanner(); if (!Grasshopper.IsEditorLoaded()) { Grasshopper.LoadEditor(); } Client = new NoahClient(Port, WorkDir); Client.InfoEvent += Client_MessageEvent; Client.ErrorEvent += Client_ErrorEvent; Client.WarningEvent += Client_WarningEvent; Client.DebugEvent += Client_DebugEvent; } catch (Exception ex) { RhinoApp.WriteLine("Error: " + ex.Message); } Client.Connect(); } else { Client.Reconnect(); } if (Debug) { try { if (Logger == null) { Panels.OpenPanel(LoggerPanel.PanelId); } Logger = Panels.GetPanel <LoggerPanel>(doc); } catch (Exception ex) { RhinoApp.WriteLine("Error: " + ex.Message); } } if (ShowEditor) { Grasshopper.ShowEditor(); } break; } if (whereToGo == "Stop") { if (Port == 0) { continue; } if (Client != null) { Client.Close(); } break; } if (whereToGo == "Workspace") { RhinoGet.GetString("Noah Workspace", false, ref WorkDir); } if (whereToGo == "Observer") { if (Port == 0) { RhinoApp.WriteLine("Server connecting need a port!"); continue; } Process.Start("http://localhost:" + Port + "/data/center"); break; } if (whereToGo == "Port") { Port = port.CurrentValue; RhinoApp.WriteLine("Port is set to " + Port.ToString()); continue; } } return(Result.Nothing); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var pack_algorithm = PackingAlgorithm.Fast; Point3d base_point = new Point3d(); var option_count = new OptionInteger(100, true, 2); var option_min_radius = new OptionDouble(0.1, true, 0.001); var option_max_radius = new OptionDouble(1.0, true, 0.001); var option_iterations = new OptionInteger(10000, false, 100); bool done_looping = false; while (!done_looping) { var gp = new GetPoint(); gp.SetCommandPrompt("Center of fitting solution"); gp.AddOptionInteger("Count", ref option_count); gp.AddOptionDouble("MinRadius", ref option_min_radius); gp.AddOptionDouble("MaxRadius", ref option_max_radius); gp.AddOptionInteger("IterationLimit", ref option_iterations); int index_option_packing = gp.AddOption("Packing", pack_algorithm.ToString()); gp.AcceptNumber(true, true); switch (gp.Get()) { case GetResult.Point: base_point = gp.Point(); done_looping = true; break; case GetResult.Option: if (index_option_packing == gp.OptionIndex()) { var get_algorithm = new GetOption(); get_algorithm.SetCommandPrompt("Packing"); get_algorithm.SetDefaultString(pack_algorithm.ToString()); var opts = new string[] { "Fast", "Double", "Random", "Simple" }; int current_index = 0; switch (pack_algorithm) { case PackingAlgorithm.Fast: current_index = 0; break; case PackingAlgorithm.Double: current_index = 1; break; case PackingAlgorithm.Random: current_index = 2; break; case PackingAlgorithm.Simple: current_index = 3; break; } int index_list = get_algorithm.AddOptionList("algorithm", opts, current_index); get_algorithm.AddOption("Help"); while (get_algorithm.Get() == GetResult.Option) { if (index_list == get_algorithm.OptionIndex()) { int index = get_algorithm.Option().CurrentListOptionIndex; if (0 == index) { pack_algorithm = PackingAlgorithm.Fast; } if (1 == index) { pack_algorithm = PackingAlgorithm.Double; } if (2 == index) { pack_algorithm = PackingAlgorithm.Simple; } if (3 == index) { pack_algorithm = PackingAlgorithm.Random; } break; } // if we get here, the user selected help const string help = @"Fast: fast packing prevents collisions by moving one circle away from all its intersectors. After every collision iteration, all circles are moved towards the centre of the packing to reduce the amount of wasted space. Collision detection proceeds from the center outwards. Double: similar to Fast, except that both circles are moved in case of a collision. Random: similar to Fast, except that collision detection is randomized rather than sorted. Simple: similar to Fast, but without a contraction pass after every collision iteration."; Rhino.UI.Dialogs.ShowMessageBox(help, "Packing algorithm description", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } } break; default: return(Result.Cancel); } } int count = option_count.CurrentValue; double min_radius = option_min_radius.CurrentValue; double max_radius = option_max_radius.CurrentValue; int iterations = option_iterations.CurrentValue; // TODO: try setting up a background worker thread and // communicate with the GetString through messages //GetString gs = new GetString(); //gs.SetCommandPrompt("Press escape to cancel"); using (var all_circles = new PackCircles(base_point, count, min_radius, max_radius)) { double damping = 0.1; for (int i = 1; i <= iterations; i++) { RhinoApp.SetCommandPrompt(string.Format("Performing circle packing iteration {0}... (Press Shift+Ctrl to abort)", i)); if (System.Windows.Forms.Control.ModifierKeys == (System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)) { RhinoApp.WriteLine("Circle fitting process aborted at iteration {0}...", i); break; } if (!all_circles.Pack(pack_algorithm, damping, doc.ModelAbsoluteTolerance)) { RhinoApp.WriteLine("Circle fitting process completed at iteration {0}...", i); break; } damping *= 0.98; doc.Views.Redraw(); RhinoApp.Wait(); } all_circles.Add(doc); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetOption(); go.SetCommandPrompt("Command tracking options"); go.AcceptNothing(true); for (;;) { go.ClearCommandOptions(); var clear_index = go.AddOption("Clear"); var enabled = CommandTrackerPlugIn.Instance.CommandTrackingEnabled; var opt_enable = new OptionToggle(enabled, "Off", "On"); var enable_index = go.AddOptionToggle("Enable", ref opt_enable); var report_index = go.AddOption("Report"); var res = go.Get(); if (res == GetResult.Nothing) { return(Result.Nothing); } if (res != GetResult.Option) { break; } var option = go.Option(); if (null == option) { return(Result.Failure); } var index = option.Index; if (index == clear_index) { var count = CommandTrackerPlugIn.Instance.ClearCommandDictionary(); switch (CommandTrackerPlugIn.Instance.ClearCommandDictionary()) { case 0: RhinoApp.WriteLine("No command tracking records to clear."); break; case 1: RhinoApp.WriteLine("1 command tracking record cleared."); break; default: RhinoApp.WriteLine("{0} command tracking records cleared.", count); break; } } else if (index == enable_index) { CommandTrackerPlugIn.Instance.CommandTrackingEnabled = opt_enable.CurrentValue; } else if (index == report_index) { var message = string.Empty; var rc = CommandTrackerPlugIn.Instance.CommandTrackingReport(ref message); if (rc) { Rhino.UI.Dialogs.ShowTextDialog(message, EnglishName); } else { RhinoApp.WriteLine("No command tracking records to report."); } } } return(Result.Nothing); }
/// <summary> /// RunCommand override /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { string rhinoScriptFile = string.Empty; // Prompt for a filename if (mode == RunMode.Interactive) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "RhinoScript Files (*.rvb)|*.rvb"; openFileDialog.Title = "Select RhinoScript File"; if (openFileDialog.ShowDialog() != DialogResult.OK) { return(Result.Cancel); } rhinoScriptFile = openFileDialog.FileName; } else { Result rc = GetOpenFileName("RhinoScript file to encrypt", ref rhinoScriptFile); if (rc != Result.Success) { return(rc); } } // Verify the filename rhinoScriptFile = rhinoScriptFile.Trim(); if (string.IsNullOrEmpty(rhinoScriptFile)) { return(Result.Nothing); } // Verify the file exists if (!File.Exists(rhinoScriptFile)) { string error = string.Format("RhinoScript file not found - {0}\n", rhinoScriptFile); if (mode == RunMode.Interactive) { MessageBox.Show(error, EnglishName, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { RhinoApp.WriteLine(error); } return(Result.Failure); } // Generate an encryption password string encryptPassword = Guid.NewGuid().ToString(); // Do the file encryption string encryptedFileName = string.Empty; try { // Read the script string clearString = File.ReadAllText(rhinoScriptFile); // Encrypt the script string encryptedString = Encrypt(clearString, encryptPassword); // Write the encrypted script encryptedFileName = Path.ChangeExtension(rhinoScriptFile, ".rvbx"); File.WriteAllText(encryptedFileName, encryptedString); } catch (Exception ex) { string error = string.Format("Error encrypting RhinoScript file - {0}\n{1}\n", rhinoScriptFile, ex.Message); if (mode == RunMode.Interactive) { MessageBox.Show(error, EnglishName, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { RhinoApp.WriteLine(error); } return(Result.Failure); } // Report the results string outputString = "RhinoScript file encryption successful!\n"; outputString += string.Format(" Input filename: {0}\n", rhinoScriptFile); outputString += string.Format(" Output filename: {0}\n", encryptedFileName); outputString += string.Format(" Decrypt password: {0}\n", encryptPassword); if (mode == RunMode.Interactive) { Rhino.UI.Dialogs.ShowTextDialog(outputString, EnglishName); } else { string[] values = new string[] { "HistoryWindow", "File", "Clipboard", "Dialog" }; GetOption go = new GetOption(); go.SetCommandPrompt(string.Format("Text destination <{0}>", values[_optionIndex])); go.AcceptNothing(true); go.AddOption(new Rhino.UI.LocalizeStringPair(values[0], values[0])); // 1 go.AddOption(new Rhino.UI.LocalizeStringPair(values[1], values[1])); // 2 go.AddOption(new Rhino.UI.LocalizeStringPair(values[2], values[2])); // 3 go.AddOption(new Rhino.UI.LocalizeStringPair(values[3], values[3])); // 4 GetResult res = go.Get(); if (res == GetResult.Option) { _optionIndex = go.OptionIndex() - 1; } else if (res != GetResult.Nothing) { return(Result.Cancel); } switch (_optionIndex) { case 0: // HistoryWindow RhinoApp.WriteLine(outputString); break; case 1: // File { string outputFileName = string.Empty; Result cmd_rc = GetSaveFileName("Save file name", ref outputFileName); if (cmd_rc != Result.Success) { return(Result.Cancel); } outputFileName = outputFileName.Trim(); if (string.IsNullOrEmpty(outputFileName)) { return(Result.Nothing); } try { outputString = outputString.Replace("\n", "\r\n"); using (StreamWriter stream = new StreamWriter(outputFileName)) stream.Write(outputString); } catch { RhinoApp.WriteLine("Unable to write to file.\n"); return(Result.Failure); } } break; case 2: // Clipboard outputString = outputString.Replace("\n", "\r\n"); Clipboard.SetText(outputString); break; case 3: // Dialog Rhino.UI.Dialogs.ShowTextDialog(outputString, EnglishName); break; } } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { if (m_draw_conduit != null) { RhinoApp.WriteLine("Turn off existing arrowhead conduit"); m_draw_conduit.Enabled = false; m_draw_conduit = null; } else { // get arrow head size var go = new GetOption(); go.SetCommandPrompt("ArrowHead length in screen size (pixels) or world size (percentage of arrow length)?"); go.AddOption("screen"); go.AddOption("world"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } int screen_size = 0; double world_size = 0.0; if (go.Option().EnglishName == "screen") { var gi = new GetInteger(); gi.SetLowerLimit(0, true); gi.SetCommandPrompt("Length of arrow head in pixels"); gi.Get(); if (gi.CommandResult() != Result.Success) { return(gi.CommandResult()); } screen_size = gi.Number(); } else { var gi = new GetInteger(); gi.SetLowerLimit(0, true); gi.SetUpperLimit(100, false); gi.SetCommandPrompt("Length of arrow head in percentage of total arrow length"); gi.Get(); if (gi.CommandResult() != Result.Success) { return(gi.CommandResult()); } world_size = gi.Number() / 100.0; } // get arrow start and end points var gp = new GetPoint(); gp.SetCommandPrompt("Start of line"); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var start_point = gp.Point(); gp.SetCommandPrompt("End of line"); gp.SetBasePoint(start_point, false); gp.DrawLineFromPoint(start_point, true); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var end_point = gp.Point(); var v = end_point - start_point; if (v.IsTiny(Rhino.RhinoMath.ZeroTolerance)) { return(Result.Nothing); } var line = new Line(start_point, end_point); m_draw_conduit = new DrawArrowHeadsConduit(line, screen_size, world_size); // toggle conduit on/off m_draw_conduit.Enabled = true; RhinoApp.WriteLine("Draw arrowheads conduit enabled."); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var view = doc.Views.ActiveView; if (null == view) { return(Result.Failure); } var gz = new GetOption(); gz.SetCommandPrompt("Zoom option"); var b_opt = gz.AddOption("BoundingBox"); var e_opt = gz.AddOption("Extents"); var s_opt = gz.AddOption("Selected"); gz.Get(); if (gz.CommandResult() != Result.Success) { return(gz.CommandResult()); } var option = gz.Option(); if (null == option) { return(Result.Failure); } if (option.Index == b_opt) { var go = new GetObject(); go.SetCommandPrompt("Select objects"); go.SubObjectSelect = false; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var bbox = new BoundingBox(); for (var i = 0; i < go.ObjectCount; i++) { var geom = go.Object(i).Geometry(); if (null != geom) { var b = geom.GetBoundingBox(true); if (b.IsValid) { if (0 == i) { bbox = b; } else { bbox.Union(b); } } } } if (bbox.IsValid) { view.ActiveViewport.ZoomBoundingBox(bbox); view.Redraw(); } } else if (option.Index == e_opt) { view.ActiveViewport.ZoomExtents(); view.Redraw(); } else if (option.Index == s_opt) { view.ActiveViewport.ZoomExtentsSelected(); view.Redraw(); } return(Result.Success); }
private void Socket_OnMessage(object sender, MessageEventArgs e) { try { ClientEventArgs eve = JsonConvert.DeserializeObject <ClientEventArgs>(e.Data); switch (eve.route) { case ClientEventType.task: { NoahTask task = JsonConvert.DeserializeObject <NoahTask>(eve.data); task.SetWorkspace(WorkDir); TaskRunner(task); break; } case ClientEventType.message: { InfoEvent(this, eve.data); break; } case ClientEventType.data: { TaskData taskData = JsonConvert.DeserializeObject <TaskData>(eve.data); NoahTask noahTask = TaskList.Find(task => Equals(task.ID, taskData.ID)); if (noahTask == null) { DebugEvent("This task is not running!"); break; } GH_Canvas activeCanvas = Instances.ActiveCanvas; if (activeCanvas == null || !activeCanvas.IsDocument) { ErrorEvent(this, "No Active Canvas exist!"); return; } if (activeCanvas.Document.Properties.ProjectFileName != taskData.ID.ToString()) { DebugEvent("这个任务没有置于前台!"); return; } DebugEvent(taskData.type); noahTask.dataList.Add(taskData); noahTask.dataTable = taskData.table; TaskRunner(noahTask); break; } case ClientEventType.pick: { RhinoApp.InvokeOnUiThread(new Action(() => { GetOption go = null; var structrue = new GH_Structure <IGH_Goo>(); while (true) { go = new GetOption(); go.SetCommandPrompt("需要选择什么呢?"); go.AddOption(new LocalizeStringPair("Point", "点")); go.AddOption(new LocalizeStringPair("Curve", "线")); go.AddOption(new LocalizeStringPair("Surface", "面")); go.AddOption(new LocalizeStringPair("Guid", "ID")); GetResult result = go.Get(); if (result != GetResult.Option) { break; } string whereToGo = go.Option().EnglishName; if (whereToGo == "Curve") { var res = Picker.PickCurves(); if (res == null) { return; } res.ForEach(crv => structrue.Append(crv)); break; } else if (whereToGo == "Point") { var res = Picker.PickPoint(); if (res == null) { return; } res.ForEach(pt => structrue.Append(pt)); break; } else if (whereToGo == "Surface") { var res = Picker.PickFace(); if (res == null) { return; } res.ForEach(face => structrue.Append(face)); break; } else if (whereToGo == "Guid") { var res = Picker.PickGuid(); if (res == null) { return; } res.ForEach(text => structrue.Append(text)); break; } else { break; } } Client.Send(JsonConvert.SerializeObject(new JObject { ["route"] = "store-picker-data", ["guid"] = eve.data, ["bytes"] = IO.SerializeGrasshopperData(structrue) })); })); break; } default: break; } } catch (Exception ex) { ErrorEvent(this, ex.Message); } }