public static Result PickPoint(RhinoDoc doc) { // this creates a point where the mouse is clicked. var gp = new GetPoint(); gp.SetCommandPrompt("Click for new point"); gp.Get(); if (gp.CommandResult() != Result.Success) return gp.CommandResult(); var point3d = gp.Point(); doc.Objects.AddPoint(point3d); doc.Views.Redraw(); // selects a point that already exists ObjRef obj_ref; var rc = RhinoGet.GetOneObject("Select point", false, ObjectType.Point, out obj_ref); if (rc != Result.Success) return rc; var point = obj_ref.Point(); RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); doc.Objects.UnselectAll(); // selects multiple points that already exist ObjRef[] obj_refs; rc = RhinoGet.GetMultipleObjects("Select point", false, ObjectType.Point, out obj_refs); if (rc != Result.Success) return rc; foreach (var o_ref in obj_refs) { point = o_ref.Point(); RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); } doc.Objects.UnselectAll(); // also selects a point that already exists. // Used when RhinoGet doesn't provide enough control var go = new GetObject(); go.SetCommandPrompt("Select point"); go.GeometryFilter = ObjectType.Point; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) return go.CommandResult(); foreach (var o_ref in go.Objects()) { point = o_ref.Point(); if (point != null) RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); } doc.Views.Redraw(); return Result.Success; }
public static Result ProjectPointsToBreps(RhinoDoc doc) { var gs = new GetObject(); gs.SetCommandPrompt("select surface"); gs.GeometryFilter = ObjectType.Surface | ObjectType.PolysrfFilter; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); var brep = gs.Object(0).Brep(); if (brep == null) return Result.Failure; var points = Intersection.ProjectPointsToBreps( new List<Brep> {brep}, // brep on which to project new List<Point3d> {new Point3d(0, 0, 0), new Point3d(3,0,3), new Point3d(-2,0,-2)}, // some random points to project new Vector3d(0, 1, 0), // project on Y axis doc.ModelAbsoluteTolerance); if (points != null && points.Length > 0) { foreach (var point in points) { doc.Objects.AddPoint(point); } } doc.Views.Redraw(); return Result.Success; }
public static Result DrawMesh(RhinoDoc doc) { var gs = new GetObject(); gs.SetCommandPrompt("select sphere"); gs.GeometryFilter = ObjectType.Surface; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); Sphere sphere; gs.Object(0).Surface().TryGetSphere(out sphere); if (sphere.IsValid) { var mesh = Mesh.CreateFromSphere(sphere, 10, 10); if (mesh == null) return Result.Failure; var conduit = new DrawBlueMeshConduit(mesh) {Enabled = true}; doc.Views.Redraw(); var in_str = ""; Rhino.Input.RhinoGet.GetString("press <Enter> to continue", true, ref in_str); conduit.Enabled = false; doc.Views.Redraw(); return Result.Success; } else return Result.Failure; }
public static Result MeshVolume(RhinoDoc doc) { var gm = new GetObject(); gm.SetCommandPrompt("Select solid meshes for volume calculation"); gm.GeometryFilter = ObjectType.Mesh; gm.GeometryAttributeFilter = GeometryAttributeFilter.ClosedMesh; gm.SubObjectSelect = false; gm.GroupSelect = true; gm.GetMultiple(1, 0); if (gm.CommandResult() != Result.Success) return gm.CommandResult(); double volume = 0.0; double volume_error = 0.0; foreach (var obj_ref in gm.Objects()) { if (obj_ref.Mesh() != null) { var mass_properties = VolumeMassProperties.Compute(obj_ref.Mesh()); if (mass_properties != null) { volume += mass_properties.Volume; volume_error += mass_properties.VolumeError; } } } RhinoApp.WriteLine("Total volume = {0:f} (+/- {1:f})", volume, volume_error); return Result.Success; }
public static Result FilletCurves(RhinoDoc doc) { var gc1 = new GetObject(); gc1.DisablePreSelect(); gc1.SetCommandPrompt("Select first curve to fillet (close to the end you want to fillet)"); gc1.GeometryFilter = ObjectType.Curve; gc1.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; gc1.Get(); if (gc1.CommandResult() != Result.Success) return gc1.CommandResult(); var curve1_obj_ref = gc1.Object(0); var curve1 = curve1_obj_ref.Curve(); if (curve1 == null) return Result.Failure; var curve1_point_near_end = curve1_obj_ref.SelectionPoint(); if (curve1_point_near_end == Point3d.Unset) return Result.Failure; var gc2 = new GetObject(); gc2.DisablePreSelect(); gc2.SetCommandPrompt("Select second curve to fillet (close to the end you want to fillet)"); gc2.GeometryFilter = ObjectType.Curve; gc2.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; gc2.Get(); if (gc2.CommandResult() != Result.Success) return gc2.CommandResult(); var curve2_obj_ref = gc2.Object(0); var curve2 = curve2_obj_ref.Curve(); if (curve2 == null) return Result.Failure; var curve2_point_near_end = curve2_obj_ref.SelectionPoint(); if (curve2_point_near_end == Point3d.Unset) return Result.Failure; double radius = 0; var rc = RhinoGet.GetNumber("fillet radius", false, ref radius); if (rc != Result.Success) return rc; var join = false; var trim = true; var arc_extension = true; var fillet_curves = Curve.CreateFilletCurves(curve1, curve1_point_near_end, curve2, curve2_point_near_end, radius, join, trim, arc_extension, doc.ModelAbsoluteTolerance, doc.ModelAngleToleranceDegrees); if (fillet_curves == null /*|| fillet_curves.Length != 3*/) return Result.Failure; foreach(var fillet_curve in fillet_curves) doc.Objects.AddCurve(fillet_curve); doc.Views.Redraw(); return rc; }
public static Result CustomGeometryFilter(RhinoDoc doc) { m_tolerance = doc.ModelAbsoluteTolerance; // only use a custom geometry filter if no simpler filter does the job // only curves var gc = new GetObject(); gc.SetCommandPrompt("select curve"); gc.GeometryFilter = ObjectType.Curve; gc.DisablePreSelect(); gc.SubObjectSelect = false; gc.Get(); if (gc.CommandResult() != Result.Success) return gc.CommandResult(); if (null == gc.Object(0).Curve()) return Result.Failure; Rhino.RhinoApp.WriteLine("curve was selected"); // only closed curves var gcc = new GetObject(); gcc.SetCommandPrompt("select closed curve"); gcc.GeometryFilter = ObjectType.Curve; gcc.GeometryAttributeFilter = GeometryAttributeFilter.ClosedCurve; gcc.DisablePreSelect(); gcc.SubObjectSelect = false; gcc.Get(); if (gcc.CommandResult() != Result.Success) return gcc.CommandResult(); if (null == gcc.Object(0).Curve()) return Result.Failure; Rhino.RhinoApp.WriteLine("closed curve was selected"); // only circles with a radius of 10 var gcc10 = new GetObject(); gcc10.SetCommandPrompt("select circle with radius of 10"); gc.GeometryFilter = ObjectType.Curve; gcc10.SetCustomGeometryFilter(CircleWithRadiusOf10GeometryFilter); // custom geometry filter gcc10.DisablePreSelect(); gcc10.SubObjectSelect = false; gcc10.Get(); if (gcc10.CommandResult() != Result.Success) return gcc10.CommandResult(); if (null == gcc10.Object(0).Curve()) return Result.Failure; RhinoApp.WriteLine("circle with radius of 10 was selected"); return Result.Success; }
public static Result CurveSurfaceIntersect(RhinoDoc doc) { var gs = new GetObject(); gs.SetCommandPrompt("select brep"); gs.GeometryFilter = ObjectType.Brep; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); var brep = gs.Object(0).Brep(); var gc = new GetObject(); gc.SetCommandPrompt("select curve"); gc.GeometryFilter = ObjectType.Curve; gc.DisablePreSelect(); gc.SubObjectSelect = false; gc.Get(); if (gc.CommandResult() != Result.Success) return gc.CommandResult(); var curve = gc.Object(0).Curve(); if (brep == null || curve == null) return Result.Failure; var tolerance = doc.ModelAbsoluteTolerance; Point3d[] intersection_points; Curve[] overlap_curves; if (!Intersection.CurveBrep(curve, brep, tolerance, out overlap_curves, out intersection_points)) { RhinoApp.WriteLine("curve brep intersection failed"); return Result.Nothing; } foreach (var overlap_curve in overlap_curves) doc.Objects.AddCurve(overlap_curve); foreach (var intersection_point in intersection_points) doc.Objects.AddPoint(intersection_point); RhinoApp.WriteLine("{0} overlap curves, and {1} intersection points", overlap_curves.Length, intersection_points.Length); doc.Views.Redraw(); return Result.Success; }
public static Result FurthestZOnSurfaceGivenXY(RhinoDoc doc) { #region user input // select a surface var gs = new GetObject(); gs.SetCommandPrompt("select surface"); gs.GeometryFilter = ObjectType.Surface; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); // get the brep var brep = gs.Object(0).Brep(); if (brep == null) return Result.Failure; // get X and Y double x = 0.0, y = 0.0; var rc = RhinoGet.GetNumber("value of X coordinate", true, ref x); if (rc != Result.Success) return rc; rc = RhinoGet.GetNumber("value of Y coordinate", true, ref y); if (rc != Result.Success) return rc; #endregion // an earlier version of this sample used a curve-brep intersection to find Z //var maxZ = maxZIntersectionMethod(brep, x, y, doc.ModelAbsoluteTolerance); // projecting points is another way to find Z var max_z = MaxZProjectionMethod(brep, x, y, doc.ModelAbsoluteTolerance); if (max_z != null) { RhinoApp.WriteLine("Maximum surface Z coordinate at X={0}, Y={1} is {2}", x, y, max_z); doc.Objects.AddPoint(new Point3d(x, y, max_z.Value)); doc.Views.Redraw(); } else RhinoApp.WriteLine("no maximum surface Z coordinate at X={0}, Y={1} found.", x, y); return Result.Success; }
public static Result ExtendCurve(RhinoDoc doc) { ObjRef[] boundary_obj_refs; var rc = RhinoGet.GetMultipleObjects("Select boundary objects", false, ObjectType.AnyObject, out boundary_obj_refs); if (rc != Result.Success) return rc; if (boundary_obj_refs == null || boundary_obj_refs.Length == 0) return Result.Nothing; var gc = new GetObject(); gc.SetCommandPrompt("Select curve to extend"); gc.GeometryFilter = ObjectType.Curve; gc.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; gc.DisablePreSelect (); gc.Get(); if (gc.CommandResult() != Result.Success) return gc.CommandResult(); var curve_obj_ref = gc.Object(0); var curve = curve_obj_ref.Curve(); if (curve == null) return Result.Failure; double t; if (!curve.ClosestPoint(curve_obj_ref.SelectionPoint(), out t)) return Result.Failure; var curve_end = t <= curve.Domain.Mid ? CurveEnd.Start : CurveEnd.End; var geometry = boundary_obj_refs.Select(obj=> obj.Geometry()); var extended_curve = curve.Extend(curve_end, CurveExtensionStyle.Line, geometry); if (extended_curve != null && extended_curve.IsValid) { if (!doc.Objects.Replace(curve_obj_ref.ObjectId, extended_curve)) return Result.Failure; doc.Views.Redraw(); } else { RhinoApp.WriteLine("No boundary object was intersected so curve not extended"); return Result.Nothing; } return Result.Success; }
public static Result Loft(RhinoDoc doc) { // select curves to loft var gs = new GetObject(); gs.SetCommandPrompt("select curves to loft"); gs.GeometryFilter = ObjectType.Curve; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.GetMultiple(2, 0); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); var curves = gs.Objects().Select(obj => obj.Curve()).ToList(); var breps = Brep.CreateFromLoft(curves, Point3d.Unset, Point3d.Unset, LoftType.Tight, false); foreach (var brep in breps) doc.Objects.AddBrep(brep); doc.Views.Redraw(); return Result.Success; }
public static Result DetermineNormalDirectionOfBrepFace(RhinoDoc doc) { // select a surface var gs = new GetObject(); gs.SetCommandPrompt("select surface"); gs.GeometryFilter = ObjectType.Surface; gs.DisablePreSelect(); gs.SubObjectSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) return gs.CommandResult(); // get the selected face var face = gs.Object(0).Face(); if (face == null) return Result.Failure; // pick a point on the surface. Constain // picking to the face. var gp = new GetPoint(); gp.SetCommandPrompt("select point on surface"); gp.Constrain(face, false); gp.Get(); if (gp.CommandResult() != Result.Success) return gp.CommandResult(); // get the parameters of the point on the // surface that is clesest to gp.Point() double u, v; if (face.ClosestPoint(gp.Point(), out u, out v)) { var direction = face.NormalAt(u, v); if (face.OrientationIsReversed) direction.Reverse(); RhinoApp.WriteLine( string.Format( "Surface normal at uv({0:f},{1:f}) = ({2:f},{3:f},{4:f})", u, v, direction.X, direction.Y, direction.Z)); } return Result.Success; }
public static Result EdgeSrf(RhinoDoc doc) { var go = new GetObject(); go.SetCommandPrompt("Select 2, 3, or 4 open curves"); go.GeometryFilter = ObjectType.Curve; go.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; go.GetMultiple(2, 4); if (go.CommandResult() != Result.Success) return go.CommandResult(); var curves = go.Objects().Select(o => o.Curve()); var brep = Brep.CreateEdgeSurface(curves); if (brep != null) { doc.Objects.AddBrep(brep); doc.Views.Redraw(); } return Result.Success; }
public static Result ReadDimensionText(RhinoDoc doc) { var go = new GetObject(); go.SetCommandPrompt("Select annotation"); go.GeometryFilter = ObjectType.Annotation; go.Get(); if (go.CommandResult() != Result.Success) return Result.Failure; var annotation = go.Object(0).Object() as AnnotationObjectBase; if (annotation == null) return Result.Failure; RhinoApp.WriteLine("Annotation text = {0}", annotation.DisplayText); return Result.Success; }
public static Result CustomGeometryFilter(RhinoDoc doc) { m_tolerance = doc.ModelAbsoluteTolerance; // only use a custom geometry filter if no simpler filter does the job // only curves var gc = new GetObject(); gc.SetCommandPrompt("select curve"); gc.GeometryFilter = ObjectType.Curve; gc.DisablePreSelect(); gc.SubObjectSelect = false; gc.Get(); if (gc.CommandResult() != Result.Success) { return(gc.CommandResult()); } if (null == gc.Object(0).Curve()) { return(Result.Failure); } Rhino.RhinoApp.WriteLine("curve was selected"); // only closed curves var gcc = new GetObject(); gcc.SetCommandPrompt("select closed curve"); gcc.GeometryFilter = ObjectType.Curve; gcc.GeometryAttributeFilter = GeometryAttributeFilter.ClosedCurve; gcc.DisablePreSelect(); gcc.SubObjectSelect = false; gcc.Get(); if (gcc.CommandResult() != Result.Success) { return(gcc.CommandResult()); } if (null == gcc.Object(0).Curve()) { return(Result.Failure); } Rhino.RhinoApp.WriteLine("closed curve was selected"); // only circles with a radius of 10 var gcc10 = new GetObject(); gcc10.SetCommandPrompt("select circle with radius of 10"); gc.GeometryFilter = ObjectType.Curve; gcc10.SetCustomGeometryFilter(CircleWithRadiusOf10GeometryFilter); // custom geometry filter gcc10.DisablePreSelect(); gcc10.SubObjectSelect = false; gcc10.Get(); if (gcc10.CommandResult() != Result.Success) { return(gcc10.CommandResult()); } if (null == gcc10.Object(0).Curve()) { return(Result.Failure); } RhinoApp.WriteLine("circle with radius of 10 was selected"); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Check the selected dot GetObject go = new GetObject(); // Create a new dictionary of strings, with string keys. // Dictionary <int, int> sizeAngle = new Dictionary <int, int>(); List <int> holeSizeList = new List <int>(); //Setting up for hole selection go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve; go.SetCommandPrompt("Select all the circles:"); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); List <RhinoObject> rhinoObjectList = new List <RhinoObject>(); List <ArcCurve> arcCurveList = new List <ArcCurve>(); // Loop through all the objects to find Curve for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (rhinoObject.ObjectType == ObjectType.Curve) { ArcCurve curve = rhinoObject.Geometry as ArcCurve; if (curve != null) { if (curve.IsCircle() == true) { if (!holeSizeList.Exists(element => element == curve.Radius)) { holeSizeList.Add(Convert.ToInt32(curve.Radius)); //add unique hole sizes } arcCurveList.Add(curve); } } } } holeSizeList.Sort(); int maxHole = Convert.ToInt32(holeSizeList.Max()); //get the maximum hole size in the list int minHole = Convert.ToInt32(holeSizeList.Min()); //get the minimum hole size in the list double maximumRotation = (360 - (360 / holeSizeList.Count)); //equation to calculate the maximum rotation int indexCOunt = 0; foreach (int size in holeSizeList) //for each hole size in the list, calculate the angle of rotation { int angle; if ((maxHole - minHole) != 0) { angle = Convert.ToInt32(indexCOunt * (360 / holeSizeList.Count)); indexCOunt++; } else { angle = 0; } sizeAngle.Add(size, angle); //assign the angle for each hole size } // Create a new layer string layerName = "CaveTool"; // Does a layer with the same name already exist? int layerIndex = doc.Layers.Find(layerName, true); // If layer does not exist if (layerIndex == -1) { // Add a new layer to the document layerIndex = doc.Layers.Add(layerName, System.Drawing.Color.Black); } doc.Layers.SetCurrentLayerIndex(layerIndex, true); String location = getCaveToolLocation(); //get the location of the cave tool (request from user) if (location != null) { //for each hole found (selected by user) //start drawing the cave tool foreach (ArcCurve ac in arcCurveList) { int angle = 0; //pass the hole size and get the angle specific to the hole size sizeAngle.TryGetValue(Convert.ToInt32(ac.Radius), out angle); //draw the cave tool drawCaveImageTool(ac.Arc.Center.X, ac.Arc.Center.Y, angle, layerIndex, location); } } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance; if (p.if_painted_object_set_ == false) { RhinoApp.WriteLine("No mesh"); return(Result.Failure); } Mesh my_mesh = p.painted_object_; GetObject gbrep = new GetObject(); gbrep.SetCommandPrompt("get the brep"); gbrep.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep.SubObjectSelect = false; gbrep.Get(); if (gbrep.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep.CommandResult()); } ObjRef my_objref = gbrep.Object(0); RhinoObject my_obj = my_objref.Object(); if (my_obj == null) { return(Rhino.Commands.Result.Failure); } Brep brep = my_objref.Brep(); if (brep == null) { return(Result.Failure); } my_obj.Select(false); int brep_number = 0; for (int i = 0; i < p.my_objects_list.Count; i++) { Brep an_object = p.my_objects_list[i]; if (My_object_functions.GetComponentID(brep) == My_object_functions.GetComponentID(an_object)) { brep_number = i; break; } } GetComponentPosition gp = new GetComponentPosition(brep, my_mesh); gp.SetCommandPrompt("Get the object position on mesh: "); gp.Constrain(my_mesh, false); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } Point3d n_p = gp.Point(); List <Sphere> pin_ball_list; Brep new_brep = GetComponentPosition.MoveBrep(brep, my_mesh, n_p, out pin_ball_list); /* * Point3d position = My_object_functions.GetPosition(new_brep); * Vector3d d_x = My_object_functions.GetX(new_brep); * Vector3d d_y = My_object_functions.GetY(new_brep); * Vector3d d_z = My_object_functions.GetZ(new_brep); * Line l_x = new Line(position, 10 * d_x); * Line l_y = new Line(position, 10 * d_y); * Line l_z = new Line(position, 10 * d_z); */ ObjectAttributes path_attributes = new ObjectAttributes(); path_attributes.ObjectColor = Color.Yellow; path_attributes.ColorSource = ObjectColorSource.ColorFromObject; path_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject; path_attributes.PlotWeight = 2.0; ObjectAttributes my_attributes = new ObjectAttributes(); my_attributes.ObjectColor = My_object_functions.GetColor(new_brep); my_attributes.ColorSource = ObjectColorSource.ColorFromObject; int new_pin_number = My_object_functions.GetPinQuantity(new_brep); List <NurbsCurve> new_path_list = new List <NurbsCurve>(); for (int i = 0; i < new_pin_number; i++) { Guid pin_id = My_object_functions.GetPinGuid(new_brep, i); Point3d pin_position = My_object_functions.GetPinPosition(new_brep, i); MeshPoint pin_on_mesh = my_mesh.ClosestMeshPoint(pin_position, 0); new_path_list = p.graph.DijkstraPath_Change(pin_id, pin_on_mesh); } IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve); foreach (RhinoObject path in path_objref) { doc.Objects.Delete(path, true); } for (int i = 0; i < new_path_list.Count; i++) { Guid path_id = new_path_list[i].UserDictionary.GetGuid("PathID"); path_attributes.ObjectId = path_id; doc.Objects.AddCurve(new_path_list[i], path_attributes); } doc.Objects.Delete(my_objref, true); /* * IEnumerable<RhinoObject> rhino_objects = doc.Objects.GetObjectList(ObjectType.Brep); * foreach (RhinoObject r_o in rhino_objects) { doc.Objects.Delete(r_o, true); } * * IEnumerable<RhinoObject> lines = doc.Objects.GetObjectList(ObjectType.Curve); * foreach (RhinoObject r_o in lines) { doc.Objects.Delete(r_o, true); } */ doc.Objects.AddBrep(new_brep, my_attributes); p.my_objects_list[brep_number] = new_brep; /* * foreach (Sphere s in pin_ball_list) * { doc.Objects.AddSphere(s); } * doc.Objects.AddLine(l_x, path_attributes); * doc.Objects.AddLine(l_y, path_attributes); * doc.Objects.AddLine(l_z, path_attributes); */ doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { GetObject go = new GetObject(); go.SetCommandPrompt("Select mesh faces to delete"); go.GeometryFilter = ObjectType.MeshFace; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } List <FaceInfo> face_list = new List <FaceInfo>(go.ObjectCount); for (int i = 0; i < go.ObjectCount; i++) { ObjRef obj_ref = go.Object(i); MeshObject obj = obj_ref.Object() as Rhino.DocObjects.MeshObject; if (null == obj) { return(Result.Failure); } FaceInfo fi = new FaceInfo(); fi.m_obj = obj; fi.m_idx = obj_ref.GeometryComponentIndex.Index; face_list.Add(fi); } face_list.Sort(CompareFaceInfo); List <int> face_indices = new List <int>(); int idx = 1; Mesh new_mesh = null; MeshObject next_obj = null; MeshObject curr_obj = face_list[0].m_obj; face_indices.Add(face_list[0].m_idx); while (idx < face_list.Count) { next_obj = face_list[idx].m_obj; if (curr_obj.RuntimeSerialNumber == next_obj.RuntimeSerialNumber) { face_indices.Add(face_list[idx].m_idx); curr_obj = next_obj; idx++; continue; } new_mesh = curr_obj.MeshGeometry.DuplicateMesh(); face_indices.Sort(); new_mesh.Faces.DeleteFaces(face_indices); new_mesh.Compact(); doc.Objects.Replace(curr_obj.Id, new_mesh); face_indices.Clear(); face_indices.Add(face_list[idx].m_idx); curr_obj = next_obj; idx++; } new_mesh = curr_obj.MeshGeometry.DuplicateMesh(); face_indices.Sort(); new_mesh.Faces.DeleteFaces(face_indices); new_mesh.Compact(); doc.Objects.Replace(curr_obj.Id, new_mesh); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Select surface that look like a cylinder var go = new GetObject(); go.SetCommandPrompt("Select surface that look like a cylinder"); go.GeometryFilter = ObjectType.Surface; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var obj = go.Object(0).Object(); var surface = go.Object(0).Surface(); if (null == obj || null == surface) { return(Result.Failure); } // Verify the surface looks like a cylinder Cylinder cylinder; if (!surface.TryGetCylinder(out cylinder, doc.ModelAbsoluteTolerance)) { RhinoApp.WriteLine("Surface is not a cylinder"); return(Result.Success); } var circle = cylinder.CircleAt(0.0); var plane = circle.Plane; var origin = plane.Origin; // Calculate a plane-aligned bounding box. // Calculating the bounding box from the runtime object, instead // of a copy of the geometry, will produce a more accurate result. var world_to_plane = Transform.ChangeBasis(Plane.WorldXY, plane); var bbox = obj.Geometry.GetBoundingBox(world_to_plane); // Move the cylinder's plane to the base of the bounding box. // Create a plane through the base of the bounding box. var bbox_plane = new Plane( bbox.Corner(true, true, true), bbox.Corner(false, true, true), bbox.Corner(true, false, true) ); // Transform the plane to the world xy-plane var plane_to_world = Transform.ChangeBasis(plane, Plane.WorldXY); bbox_plane.Transform(plane_to_world); // Project the cylinder plane's origin onto the bounding box plane plane.Origin = bbox_plane.ClosestPoint(origin); // Cylinder height is bounding box height var pt0 = bbox.Corner(true, true, true); var pt1 = bbox.Corner(true, true, false); var height = pt0.DistanceTo(pt1); // Create a new cylinder var new_circle = new Circle(plane, circle.Radius); var new_cylinder = new Cylinder(new_circle, height); var rev_surface = new_cylinder.ToRevSurface(); doc.Objects.AddSurface(rev_surface); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { //look at this for a summary of all the GET commands. // https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_Input_Custom_GetBaseClass.htm. /*System.Object * Rhino.Input.Custom.GetBaseClass * Rhino.Input.Custom.GetInteger * Rhino.Input.Custom.GetNumber * Rhino.Input.Custom.GetObject * Rhino.Input.Custom.GetOption * Rhino.Input.Custom.GetPoint * Rhino.Input.Custom.GetString * * */ var gc = new GetObject(); gc.SetCommandPrompt("Select objects"); gc.GeometryFilter = ObjectType.AnyObject; OptionInteger intOption = new OptionInteger(1, 1, 99); OptionDouble dblOption = new OptionDouble(2.2, 0, 99); OptionToggle boolOption = new OptionToggle(true, "off", "on"); gc.AddOptionInteger("Integer", ref intOption); gc.AddOptionDouble("Double", ref dblOption); gc.AddOptionToggle("Boolean", ref boolOption); int listIndex = 0; string[] listValues = new string[] { "Bran", "Bob", "Arya", "Sansa", "Rickon" }; int optList = gc.AddOptionList("List", listValues, listIndex); while (true) { GetResult res = gc.GetMultiple(1, 0); //we can check if the user selected something if (gc.CommandResult() != Result.Success) { return(gc.CommandResult()); } if (res == Rhino.Input.GetResult.Object) { RhinoApp.WriteLine("Command line option values are"); RhinoApp.WriteLine("Integer = {0}", intOption.CurrentValue); RhinoApp.WriteLine("Double = {0}", dblOption.CurrentValue); RhinoApp.WriteLine("Boolean = {0}", boolOption.CurrentValue); RhinoApp.WriteLine("List = {0}", listValues[listIndex]); } else if (res == Rhino.Input.GetResult.Option) { if (gc.OptionIndex() == optList) { listIndex = gc.Option().CurrentListOptionIndex; //this updates the list option to whatever index the user has picked } continue; } break; } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { const ObjectType geometryFilter = ObjectType.Mesh; OptionDouble minEdgeLengthOption = new OptionDouble(minEdgeLength, 0.001, 200); OptionDouble maxEdgeLengthOption = new OptionDouble(maxEdgeLength, 0.001, 200); OptionDouble constriantAngleOption = new OptionDouble(constriantAngle, 0.001, 360); OptionInteger smoothStepsOptions = new OptionInteger(smoothSteps, 0, 1000); OptionDouble smoothSpeedOption = new OptionDouble(smoothSpeed, 0.01, 1.0); OptionDouble projectAmountOption = new OptionDouble(projectedAmount, 0.01, 1.0); OptionDouble projectedDistanceOption = new OptionDouble(projectedDistance, 0.01, 100000.0); GetObject go = new GetObject(); go.SetCommandPrompt("Select mesh to remesh"); go.GeometryFilter = geometryFilter; go.AddOptionDouble("ConstraintAngle", ref constriantAngleOption); go.AddOptionDouble("MinEdge", ref minEdgeLengthOption); go.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption); go.AddOptionInteger("SmoothSteps", ref smoothStepsOptions); go.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption); go.AddOptionDouble("ProjectAmount", ref projectAmountOption); go.AddOptionDouble("ProjectDistance", ref projectedDistanceOption); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; bool bHavePreselectedObjects = false; for (;;) { GetResult res = go.Get(); if (res == GetResult.Option) { go.EnablePreSelect(false, true); continue; } else if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } if (go.ObjectsWerePreselected) { bHavePreselectedObjects = true; go.EnablePreSelect(false, true); continue; } break; } GetObject goProjected = new GetObject(); goProjected.EnablePreSelect(false, true); goProjected.SetCommandPrompt("Select mesh to project to"); goProjected.GeometryFilter = geometryFilter; goProjected.AddOptionDouble("ConstraintAngle", ref constriantAngleOption); goProjected.AddOptionDouble("MinEdge", ref minEdgeLengthOption); goProjected.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption); goProjected.AddOptionInteger("SmoothSteps", ref smoothStepsOptions); goProjected.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption); goProjected.AddOptionDouble("ProjectAmount", ref projectAmountOption); goProjected.AddOptionDouble("ProjectDistance", ref projectedDistanceOption); goProjected.GroupSelect = true; goProjected.SubObjectSelect = false; goProjected.EnableClearObjectsOnEntry(false); goProjected.EnableUnselectObjectsOnExit(false); for (;;) { GetResult res = goProjected.Get(); if (res == GetResult.Option) { continue; } else if (goProjected.CommandResult() != Result.Success) { return(goProjected.CommandResult()); } break; } minEdgeLength = minEdgeLengthOption.CurrentValue; maxEdgeLength = maxEdgeLengthOption.CurrentValue; constriantAngle = constriantAngleOption.CurrentValue; smoothSteps = smoothStepsOptions.CurrentValue; smoothSpeed = smoothSpeedOption.CurrentValue; projectedAmount = projectAmountOption.CurrentValue; projectedDistance = projectedDistanceOption.CurrentValue; if (bHavePreselectedObjects) { // Normally, pre-selected objects will remain selected, when a // command finishes, and post-selected objects will be unselected. // This this way of picking, it is possible to have a combination // of pre-selected and post-selected. So, to make sure everything // "looks the same", lets unselect everything before finishing // the command. for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (null != rhinoObject) { rhinoObject.Select(false); } } doc.Views.Redraw(); } bool result = false; if (goProjected.ObjectCount < 1) { return(Result.Failure); } foreach (var obj in go.Objects()) { var rhinoMesh = obj.Mesh(); if (rhinoMesh == null || !rhinoMesh.IsValid) { continue; } var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh()); var rhinoMeshProject = goProjected.Object(0).Mesh(); if (rhinoMeshProject == null || !rhinoMeshProject.IsValid) { continue; } var meshProjected = GopherUtil.ConvertToD3Mesh(rhinoMeshProject); var mesh2 = new DMesh3(mesh); var mesh3 = new DMesh3(mesh); var res3 = GopherUtil.RemeshMesh(mesh3, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance); var watch = System.Diagnostics.Stopwatch.StartNew(); // the code that you want to measure comes here var res = GopherUtil.RemeshMesh(mesh, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance); watch.Stop(); var watch2 = System.Diagnostics.Stopwatch.StartNew(); var res2 = GopherUtil.RemeshMeshNew(mesh2, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance); watch2.Stop(); Rhino.RhinoApp.WriteLine("Time 1: {0} Time 2: {1}", watch.ElapsedMilliseconds, watch2.ElapsedMilliseconds); var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(res); var newRhinoMesh2 = GopherUtil.ConvertToRhinoMesh(mesh2); newRhinoMesh2.Translate(new Rhino.Geometry.Vector3d(newRhinoMesh2.GetBoundingBox(true).Diagonal.X, 0, 0)); doc.Objects.Add(newRhinoMesh2); if (newRhinoMesh != null && newRhinoMesh.IsValid) { doc.Objects.Replace(obj, newRhinoMesh); } if (newRhinoMesh != null && newRhinoMesh.IsValid) { result |= doc.Objects.Replace(obj, newRhinoMesh); } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Check the selected dot GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = Rhino.DocObjects.ObjectType.Annotation; go.SetCommandPrompt("Select Text to append Metrix M01:"); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); List <TextEntity> textEntityList = new List <TextEntity>(); List <RhinoObject> rhinoObjectList = new List <RhinoObject>(); // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (rhinoObject.ObjectType == ObjectType.Annotation) { TextEntity textEntity = rhinoObject.Geometry as TextEntity; if (textEntity != null) { rhinoObjectList.Add(rhinoObject); textEntityList.Add(textEntity); } } } // Sort the text Entity list IEnumerable <TextEntity> query = textEntityList.OrderByDescending(t => t.Plane.OriginY); //.ThenBy(t => t.Plane.OriginX); IEnumerable <TextEntity> xSortedList = textEntityList.OrderBy(t => t.Plane.OriginX); //.ThenBy(t => t.Plane.OriginY); IEnumerable <TextEntity> newList = null; List <TextEntity> toSort = new List <TextEntity>(); List <TextEntity> toRemove = new List <TextEntity>(); double y; Point3d previous = new Point3d(0, 0, 0); int maxDigit = (int)Math.Floor(Math.Log10(textEntityList.Count) + 1); int j = 1; Boolean found = false; foreach (TextEntity yText in query) { found = false; if (toRemove.Count > 0) { foreach (TextEntity deletedElement in toRemove) { if (deletedElement.Equals(yText)) { found = true; break; } } } if (found == false) { y = yText.Plane.OriginY; toSort = new List <TextEntity>(); newList = null; // p = textE; foreach (TextEntity t in xSortedList) { if (t.Plane.OriginY == y || t.Plane.OriginY >= y && t.Plane.OriginY <= (y + 200) || t.Plane.OriginY <= y && t.Plane.OriginY >= (y - 1000)) //Check if y is same { toSort.Add(t); } } if (toSort.Count > 0) //If the list is more than 0, sort it by X { //toSort.Add(yText); newList = toSort.OrderBy(t => t.Plane.OriginX); toRemove.AddRange(newList); } foreach (TextEntity textE in newList) { // Test if there is a M_- in front of the text, if yes, remove it if (textE.Text.Count() > 2) { if (textE.Text[0] == 'M') { if (Char.IsNumber(textE.Text[1])) { if (textE.Text.IndexOf('-') != -1) { // This means M0 exist textE.Text = textE.Text.Substring(textE.Text.IndexOf('-') + 1); } } } } textE.Text = "M" + j.ToString().PadLeft(maxDigit, '0') + "-" + textE.Text; j++; } // toRemove.AddRange(newList); } else { continue; } } // Commit the changes for all updated labels for (int k = 0; k < rhinoObjectList.Count; k++) { rhinoObjectList[k].CommitChanges(); } doc.Views.Redraw(); return(Result.Success); }
/// <summary> /// Creates the layout. /// </summary> /// <param name="doc">The document.</param> /// <param name="panel">The panel.</param> /// <param name="panelParas">The panel paras.</param> /// <returns></returns> public Result createLayout(RhinoDoc doc, PerforationPanel panel, PanelParameters panelParas) { if (panelParas == null) { panelParas = new PanelParameters(); } if (panel == null) { panel = new PerforationPanel(); } // Get all selected Objects GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.EnablePressEnterWhenDonePrompt(false); go.SetCommandPrompt("Select items for the new layout:"); // Disable the scaling RhinoApp.RunScript("_-DocumentProperties AnnotationStyles ModelSpaceScaling=Disabled LayoutSpaceScaling=Disabled _Enter _Enter", true); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Total Objects Selected: {0}", go.ObjectCount); string labelName = panel.PartName; string area = string.Format("{0:0.00}", panel.Area); Point2d minPoint = new Point2d(0, 0); Point2d maxPoint = new Point2d(0, 0); // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { BoundingBox bBox = go.Object(i).Object().Geometry.GetBoundingBox(true); if (bBox.Min.X < minPoint.X) { minPoint.X = bBox.Min.X; } if (bBox.Min.Y < minPoint.Y) { minPoint.Y = bBox.Min.Y; } if (bBox.Max.X > maxPoint.X) { maxPoint.X = bBox.Max.X; } if (bBox.Max.Y > maxPoint.Y) { maxPoint.Y = bBox.Max.Y; } } // If the selected items has no label, return failure if (labelName == null) { return(Rhino.Commands.Result.Failure); } // Hide all the non selected objects foreach (var obj in doc.Objects) { if (obj.IsSelected(true) == 0) { doc.Objects.Hide(obj, false); } } // Add layout doc.PageUnitSystem = Rhino.UnitSystem.Millimeters; RhinoView currentView = doc.Views.ActiveView; var pageview = doc.Views.AddPageView(string.Format("{0}", labelName), 210, 297); Point2d bottomLeft = new Point2d(10, 70); Point2d topRight = new Point2d(200, 287); if (pageview != null) { pageview.SetPageAsActive(); var detail = pageview.AddDetailView("Panel", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); // Show all objects RhinoApp.RunScript("_-Show _Enter", true); if (detail != null) { pageview.SetActiveDetail(detail.Id); doc.Views.ActiveView = pageview; // doc.Views.Redraw(); // Select all the objects //for (int i = 0; i < go.ObjectCount; i++) //{ // RhinoObject rhinoObject = go.Object(i).Object(); // rhinoObject.Select(true); //} //// Hide all the non selected objects //var filter = new ObjectEnumeratorSettings //{ // NormalObjects = true, // LockedObjects = false, // HiddenObjects = false, // ActiveObjects = true, // ReferenceObjects = true //}; //var rh_objects = doc.Objects.FindByFilter(filter); //// pageview.SetPageAsActive(); //doc.Views.Redraw(); //foreach (var rh_obj in rh_objects) //{ // var select = 0 == rh_obj.IsSelected(false) && rh_obj.IsSelectable(); // rh_obj.Select(select); //} //RhinoApp.RunScript("_-HideInDetail Enter", true); detail.IsActive = false; } bottomLeft = new Point2d(10, 40); topRight = new Point2d(135, 70); detail = pageview.AddDetailView("Sample", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); // doc.Views.Redraw(); pageview.SetActiveDetail(detail.Id); detail.Viewport.SetCameraLocation(new Point3d(50, 160, 0), true); detail.CommitViewportChanges(); //doc.Views.Redraw(); detail.DetailGeometry.IsProjectionLocked = true; detail.DetailGeometry.SetScale(4.5, doc.ModelUnitSystem, 1, doc.PageUnitSystem); detail.CommitChanges(); //doc.Views.Redraw(); detail.IsActive = true; pageview.SetActiveDetail(detail.Id); RhinoApp.WriteLine("Name = {0}: Width = {1}, Height = {2}", detail.Viewport.Name, detail.Viewport.Size.Width, detail.Viewport.Size.Height); detail.CommitViewportChanges(); // doc.Views.Redraw(); detail.IsActive = false; bottomLeft = new Point2d(5, 5); topRight = new Point2d(205, 35); detail = pageview.AddDetailView("Block", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); //doc.Views.Redraw(); detail.IsActive = true; pageview.SetActiveDetail(detail.Id); detail.Viewport.SetCameraLocation(new Point3d(105, 520, 0), true); detail.CommitViewportChanges(); // doc.Views.Redraw(); detail.DetailGeometry.IsProjectionLocked = true; detail.DetailGeometry.SetScale(1, doc.ModelUnitSystem, 1, doc.PageUnitSystem); detail.CommitChanges(); detail.IsActive = false; //doc.Views.Redraw(); drawBlock(doc, labelName, area, panel.PanelNumber, panelParas); // doc.Views.Redraw(); } // Show all objects RhinoApp.RunScript("_-Show _Enter", true); doc.Views.DefaultViewLayout(); doc.Views.ActiveView = currentView; 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); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { GetObject go = new GetObject(); go.SetCommandPrompt("Select surfaces, polysurfaces, or meshes"); go.GeometryFilter = ObjectType.Surface | ObjectType.PolysrfFilter | ObjectType.Mesh; go.GroupSelect = true; go.SubObjectSelect = false; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } List <Mesh> InMeshes = new List <Mesh>(go.ObjectCount); List <RhinoObject> InMeshObjects = new List <RhinoObject>(go.ObjectCount); List <RhinoObject> InObjects = new List <RhinoObject>(go.ObjectCount); for (int i = 0; i < go.ObjectCount; i++) { ObjRef objRef = go.Object(i); Mesh mesh = objRef.Mesh(); if (null == mesh) { InObjects.Add(objRef.Object()); } else { InMeshes.Add(mesh); InMeshObjects.Add(objRef.Object()); } } ObjRef[] meshRefs = null; if (InObjects.Count > 0) { meshRefs = RhinoObject.GetRenderMeshes(InObjects, true, false); if (null != meshRefs) { for (int i = 0; i < meshRefs.Length; i++) { Mesh mesh = meshRefs[i].Mesh(); if (null != mesh) { InMeshes.Add(mesh); } } } } RhinoViewport vp = doc.Views.ActiveView.ActiveViewport; for (int i = 0; i < InMeshes.Count; i++) { Polyline[] plines = InMeshes[i].GetOutlines(vp); if (null != plines) { for (int j = 0; j < plines.Length; j++) { Rhino.Geometry.PolylineCurve plineCrv = new PolylineCurve(plines[j]); plineCrv.RemoveShortSegments(RhinoMath.SqrtEpsilon); if (plineCrv.IsValid) { Guid objId = doc.Objects.AddCurve(plineCrv); RhinoObject obj = doc.Objects.Find(objId); if (null != obj) { obj.Select(true); } } } } } for (int i = 0; i < InObjects.Count; i++) { InObjects[i].Select(false); } for (int i = 0; i < InMeshObjects.Count; i++) { InMeshObjects[i].Select(false); } doc.Views.Redraw(); return(Result.Success); }
///<summary>The only instance of this command.</summary> ///<param name="doc" RhinoDoc></param> ///<param name="mode" Run mode></param> ///<returns>returns sucess if doc is successfully created </returns> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { #region set all the file parameters pdfOptionForm = new PDFOptionForm(); Application.Run(pdfOptionForm); getSelectedOption = PDFOptionForm.optionsSelected; myUniqueFileName = string.Format(@"{0}" + ext, Guid.NewGuid()); string logFilePath = Rhino.ApplicationSettings.FileSettings.WorkingFolder + "\\Log-" + DateTime.Now.GetHashCode().ToString() + ".txt"; string curveType = "C"; try { string[] checkFileName = Rhino.ApplicationSettings.FileSettings.RecentlyOpenedFiles()[0].ToString().Split('\\'); int checklength = checkFileName.Length; rhinoFile = Rhino.ApplicationSettings.FileSettings.RecentlyOpenedFiles()[0].ToString().Split('\\')[--checklength]; } catch (FileNotFoundException fnf) { logFile(fnf.Message); } catch (IndexOutOfRangeException ioor) { logFile(ioor.Message); } string rhinoFileName = rhinoFile.Split('.')[0]; string filename = Rhino.ApplicationSettings.FileSettings.WorkingFolder + '\\' + rhinoFileName + "-" + myUniqueFileName; #endregion Rhino.RhinoApp.RunScript("-_Save Enter", false); logFile("Process started for ---> " + rhinoFileName + "-" + myUniqueFileName); PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.Bold); #region Check the selected curve GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = ObjectType.AnyObject; GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("{0} objects are selected.", go.ObjectCount); #endregion // Process the list of objects logFile("Processing List of Object"); #region set the paramenters for Xgraph to process shapes List <GeometryBase> geoList = new List <GeometryBase>(); double minX, minY, maxX, maxY; minX = double.MaxValue; minY = double.MaxValue; maxX = double.MinValue; maxY = double.MinValue; List <Curve> curveList = new List <Curve>(); List <TextEntity> textEntityList = new List <TextEntity>(); List <Circle> circleList = new List <Circle>(); List <Polyline> polyList = new List <Polyline>(); Circle circleCurve; Polyline polygon; #endregion for (int i = 0; i < go.ObjectCount; i++) { // Check the type of the Object and process differently Curve curve = go.Object(i).Curve(); if (go.Object(i).Curve().TryGetCircle(out circleCurve)) { circleList.Add(circleCurve); } if (go.Object(i).Curve().TryGetPolyline(out polygon)) { polyList.Add(polygon); } if (curve != null) { curveList.Add(curve); } TextEntity te = go.Object(i).TextEntity(); if (te != null) { textEntityList.Add(te); } GeometryBase geo = go.Object(i).Geometry(); BoundingBox bbox = geo.GetBoundingBox(Rhino.Geometry.Plane.WorldXY); if (bbox.Min.X < minX) { minX = bbox.Min.X; } if (bbox.Min.Y < minY) { minY = bbox.Min.Y; } if (bbox.Max.X > maxX) { maxX = bbox.Max.X; } if (bbox.Max.Y > maxY) { maxY = bbox.Max.Y; } geoList.Add(geo); } page.Height = maxY - minY; page.Width = maxX - minX; foreach (GeometryBase g in geoList) { if (g.GetType().Equals(typeof(PolyCurve))) { //System.Windows.Forms.MessageBox.Show("PolyCurve changed"); PolyCurve polyCurve = (PolyCurve)g; curveType = "NC"; break; } else if (g.GetType().Equals(typeof(Curve))) { System.Windows.Forms.MessageBox.Show("Curve"); Curve curve = (Curve)g; } else if (g.GetType().Equals(typeof(TextEntity))) { System.Windows.Forms.MessageBox.Show("TextEntity"); TextEntity textEntity = (TextEntity)g; curveType = "T"; } } logFile("Checking the pattern"); if (curveType.Equals("C") || curveType.Equals("T")) { logFile("Objects processed sucessfully"); double x1, y1, width, height; logFile("Creating Circles on the PDF"); //Loop to draw the circles foreach (Circle c in circleList) { XPen pen = new XPen(XColors.Black, 0.5); x1 = c.BoundingBox.Min.X - minX; y1 = maxY - c.BoundingBox.Max.Y; width = c.BoundingBox.Max.X - c.BoundingBox.Min.X; height = c.BoundingBox.Max.Y - c.BoundingBox.Min.Y; gfx.DrawEllipse(XBrushes.Black, x1, y1, width, height); } //Loop used to draw rectangles foreach (Polyline p in polyList) { XPen pen = new XPen(XColors.Black, 0.5); x1 = p.BoundingBox.Min.X - minX; y1 = maxY - p.BoundingBox.Max.Y; width = p.BoundingBox.Max.X - p.BoundingBox.Min.X; height = p.BoundingBox.Max.Y - p.BoundingBox.Min.Y; XPoint p1 = new XPoint(x1, y1); XPoint p2 = new XPoint(x1 + width, y1); XPoint p3 = new XPoint(x1, y1 + height); XPoint p4 = new XPoint(x1 + width, y1 + height); XRect rect = new XRect(x1, y1, width, height); XPoint[] xPoint = new XPoint[] { p1, p2, p4, p3 }; //XPoint mid = new XPoint( (x1 + x1)/2); XGraphicsState gs = gfx.Save(); gfx.RotateAtTransform(-45, p1); gfx.DrawPolygon(pen, XBrushes.Black, xPoint, XFillMode.Alternate); gfx.Restore(gs); } #region Print the PDF as per the option selected if (getSelectedOption.Equals('N')) { logFile("Normal PDF feature was selected"); document.Save(filename); logFile("Document saved successfully - " + Rhino.ApplicationSettings.FileSettings.WorkingFolder); } if (getSelectedOption.Equals('C')) { logFile("Compressed PDF feature was selected"); CompressMyPdf(document); string compressedFileName = Rhino.ApplicationSettings.FileSettings.WorkingFolder + '\\' + "C-" + rhinoFileName + "-" + myUniqueFileName; document.Save(compressedFileName); } if (getSelectedOption.Equals('E')) { logFile("Encrypted PDF feature was selected"); EncryptMyPdf(document); string encryptPdf = Rhino.ApplicationSettings.FileSettings.WorkingFolder + '\\' + "E-" + rhinoFileName + "-" + myUniqueFileName; document.Save(encryptPdf); } if (getSelectedOption.Equals('P')) { logFile("Password Protection PDF feature was selected"); PasswordProtectMyPdf(document); string passwordProtectPdf = Rhino.ApplicationSettings.FileSettings.WorkingFolder + '\\' + "PP-" + rhinoFileName + "-" + myUniqueFileName; document.Save(passwordProtectPdf); } #endregion logFile("Document saved successfully - " + Rhino.ApplicationSettings.FileSettings.WorkingFolder); logFile("Panel perforated successfully. Check File --> " + rhinoFileName + "-" + myUniqueFileName); System.Windows.Forms.MessageBox.Show(" <----SUCCESS----> " + Environment.NewLine + Environment.NewLine + " Pannels perforated Successfully. "); } else { System.Windows.Forms.MessageBox.Show(" ERROR! " + Environment.NewLine + Environment.NewLine + "The curve you have selected contains some invalid shape." + Environment.NewLine + " Please select the appropriate patterns. "); logFile("Please select the appropriate pattern"); } logFile("----------------- WAITING FOR THE NEXT PANEL PERFORATION ---------------------"); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Select curves to project var gc = new GetObject(); gc.SetCommandPrompt("Select curves to project"); gc.GeometryFilter = ObjectType.Curve; gc.GetMultiple(1, 0); if (gc.CommandResult() != Result.Success) { return(gc.CommandResult()); } // Select planar surface to project onto var gs = new GetObject(); gs.SetCommandPrompt("Select planar surface to project onto"); gs.GeometryFilter = ObjectType.Surface; gs.EnablePreSelect(false, true); gs.DeselectAllBeforePostSelect = false; gs.Get(); if (gs.CommandResult() != Result.Success) { return(gs.CommandResult()); } // Get the Brep face var brep_face = gs.Object(0).Face(); if (null == brep_face) { return(Result.Failure); } // Verify the Brep face is planar var tolerance = doc.ModelAbsoluteTolerance; if (!brep_face.IsPlanar(tolerance)) { RhinoApp.WriteLine("Surface is not planar."); return(Result.Nothing); } // Get normal direction of Brep face var u = brep_face.Domain(0).Min; var v = brep_face.Domain(1).Min; var normal = brep_face.NormalAt(u, v); // If the Brep face's orientation is opposite of natural surface orientation, // then reverse the normal vector. if (brep_face.OrientationIsReversed) { normal.Reverse(); } // Invert norma; direction of the vector for projection normal.Reverse(); // Create a array of Breps to project onto var breps = new Brep[1]; breps[0] = brep_face.DuplicateFace(true); // Create a single Brep, including trims // Create a collection of curves to project var curves = new List <Curve>(gc.ObjectCount); for (var i = 0; i < gc.ObjectCount; i++) { var curve = gc.Object(i).Curve(); if (null != curve) { curves.Add(curve); } } // Do the projection var projected_curves = Curve.ProjectToBrep(curves, breps, normal, tolerance); // Add the results to the document foreach (var crv in projected_curves) { doc.Objects.AddCurve(crv); } doc.Views.Redraw(); return(Result.Success); }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var rc = RockfishClientPlugIn.VerifyServerHostName(); if (rc != Result.Success) { return(rc); } var go = new GetObject(); go.SetCommandPrompt("Select points for polyline creation"); go.GeometryFilter = ObjectType.Point; go.SubObjectSelect = false; go.GetMultiple(2, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var in_points = new List <RockfishPoint>(go.ObjectCount); foreach (var obj_ref in go.Objects()) { var point = obj_ref.Point(); if (null != point) { in_points.Add(new RockfishPoint(point.Location)); } } if (in_points.Count < 2) { return(Result.Cancel); } RockfishGeometry out_curve; try { RockfishClientPlugIn.ServerHostName(); using (var channel = new RockfishClientChannel()) { channel.Create(); out_curve = channel.PolylineFromPoints(in_points.ToArray(), doc.ModelAbsoluteTolerance); } } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); return(Result.Failure); } if (null != out_curve?.Curve) { doc.Objects.AddCurve(out_curve.Curve); doc.Views.Redraw(); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { const ObjectType geometryFilter = ObjectType.Mesh; OptionDouble minEdgeLengthOption = new OptionDouble(minEdgeLength, 0.001, 200); OptionDouble maxEdgeLengthOption = new OptionDouble(maxEdgeLength, 0.001, 200); OptionDouble constriantAngleOption = new OptionDouble(constriantAngle, 0.001, 360); OptionInteger smoothStepsOptions = new OptionInteger(smoothSteps, 0, 10000); OptionDouble smoothSpeedOption = new OptionDouble(smoothSpeed, 0.01, 1.0); GetObject go = new GetObject(); go.SetCommandPrompt("Select meshes to remesh"); go.GeometryFilter = geometryFilter; go.AddOptionDouble("ConstraintAngle", ref constriantAngleOption); go.AddOptionDouble("MinEdge", ref minEdgeLengthOption); go.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption); go.AddOptionInteger("SmoothSteps", ref smoothStepsOptions); go.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; bool bHavePreselectedObjects = false; for (;;) { GetResult res = go.GetMultiple(1, 0); if (res == GetResult.Option) { go.EnablePreSelect(false, true); continue; } else if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } if (go.ObjectsWerePreselected) { bHavePreselectedObjects = true; go.EnablePreSelect(false, true); continue; } break; } minEdgeLength = minEdgeLengthOption.CurrentValue; maxEdgeLength = maxEdgeLengthOption.CurrentValue; constriantAngle = constriantAngleOption.CurrentValue; smoothSteps = smoothStepsOptions.CurrentValue; smoothSpeed = smoothSpeedOption.CurrentValue; if (bHavePreselectedObjects) { // Normally, pre-selected objects will remain selected, when a // command finishes, and post-selected objects will be unselected. // This this way of picking, it is possible to have a combination // of pre-selected and post-selected. So, to make sure everything // "looks the same", lets unselect everything before finishing // the command. for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (null != rhinoObject) { rhinoObject.Select(false); } } doc.Views.Redraw(); } bool result = false; foreach (var obj in go.Objects()) { var rhinoMesh = obj.Mesh(); if (rhinoMesh == null || !rhinoMesh.IsValid) { continue; } var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh()); var res = GopherUtil.RemeshMesh(mesh, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps); var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(mesh); if (newRhinoMesh != null && newRhinoMesh.IsValid) { doc.Objects.Replace(obj, newRhinoMesh); } if (newRhinoMesh != null && newRhinoMesh.IsValid) { result |= doc.Objects.Replace(obj, newRhinoMesh); } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curves"); go.GeometryFilter = ObjectType.Curve; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var curve = go.Object(0).Curve(); if (null == curve) { return(Result.Failure); } var continuity = Continuity.G1_continuous; var gd = new GetOption(); gd.SetCommandPrompt("Discontinuity to search"); gd.AddOptionEnumList("Discontinuity", continuity); gd.AcceptNothing(true); var res = gd.Get(); if (res == GetResult.Option) { var option = gd.Option(); if (null == option) { return(Result.Failure); } var list = Enum.GetValues(typeof(Continuity)).Cast <Continuity>().ToList(); continuity = list[option.CurrentListOptionIndex]; } else if (res != GetResult.Nothing) { return(Result.Cancel); } var t0 = curve.Domain.Min; var t1 = curve.Domain.Max; var parameters = new List <double>(); parameters.Add(t0); for (; ;) { double t; var rc = curve.GetNextDiscontinuity(continuity, t0, t1, out t); if (rc) { parameters.Add(t); t0 = t; } else { break; } } parameters.Add(t1); if (parameters.Count > 2) { for (var i = 0; i < parameters.Count - 1; i++) { t0 = parameters[i]; t1 = parameters[i + 1]; var dom = new Interval(t0, t1); var new_curve = curve.Trim(dom); if (null != new_curve) { doc.Objects.AddCurve(new_curve); } } doc.Objects.Delete(go.Object(0), false); } return(Result.Success); }
/// <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); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curve to intersect"); go.GeometryFilter = ObjectType.Curve; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var curve = go.Object(0).Curve(); if (null == curve) { return(Result.Failure); } var gp = new GetPoint(); gp.SetCommandPrompt("First point of infinite intersecting line"); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var from = gp.Point(); gp.SetCommandPrompt("Second point of infinite intersecting line"); gp.SetBasePoint(from, true); gp.DrawLineFromPoint(from, true); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var line = new Rhino.Geometry.Line(from, gp.Point()); if (!line.IsValid || line.Length < Rhino.RhinoMath.SqrtEpsilon) { return(Result.Nothing); } var ccx = IntersectCurveLine(curve, line, doc.ModelAbsoluteTolerance, doc.ModelAbsoluteTolerance); if (null != ccx) { foreach (var x in ccx) { if (x.IsPoint) { doc.Objects.AddPoint(x.PointA); } } doc.Views.Redraw(); } return(Result.Success); }
public static Result PickPoint(RhinoDoc doc) { // this creates a point where the mouse is clicked. var gp = new GetPoint(); gp.SetCommandPrompt("Click for new point"); gp.Get(); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var point3d = gp.Point(); doc.Objects.AddPoint(point3d); doc.Views.Redraw(); // selects a point that already exists ObjRef obj_ref; var rc = RhinoGet.GetOneObject("Select point", false, ObjectType.Point, out obj_ref); if (rc != Result.Success) { return(rc); } var point = obj_ref.Point(); RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); doc.Objects.UnselectAll(); // selects multiple points that already exist ObjRef[] obj_refs; rc = RhinoGet.GetMultipleObjects("Select point", false, ObjectType.Point, out obj_refs); if (rc != Result.Success) { return(rc); } foreach (var o_ref in obj_refs) { point = o_ref.Point(); RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); } doc.Objects.UnselectAll(); // also selects a point that already exists. // Used when RhinoGet doesn't provide enough control var go = new GetObject(); go.SetCommandPrompt("Select point"); go.GeometryFilter = ObjectType.Point; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } foreach (var o_ref in go.Objects()) { point = o_ref.Point(); if (point != null) { RhinoApp.WriteLine("Point: x:{0}, y:{1}, z:{2}", point.Location.X, point.Location.Y, point.Location.Z); } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var gp = new GetObject(); gp.SetCommandPrompt("Select points to project"); gp.GeometryFilter = ObjectType.Point; gp.GetMultiple(1, 0); if (gp.CommandResult() != Result.Success) { return(gp.CommandResult()); } var gm = new GetObject(); gm.SetCommandPrompt("Select mesh to project onto"); gm.GeometryFilter = ObjectType.Mesh; gm.SubObjectSelect = false; gm.EnablePreSelect(false, true); gm.DeselectAllBeforePostSelect = false; gm.Get(); if (gm.CommandResult() != Result.Success) { return(gm.CommandResult()); } var mesh = gm.Object(0).Mesh(); if (null == mesh) { return(Result.Failure); } var meshes = new List <Mesh>(1) { mesh }; var points = new List <Point3d>(gp.ObjectCount); for (var i = 0; i < gp.ObjectCount; i++) { var point = gp.Object(i).Point(); if (null != point) { points.Add(point.Location); } } var dir = -Vector3d.ZAxis; var tol = doc.ModelAbsoluteTolerance; int[] indices; var project_points = Intersection.ProjectPointsToMeshesEx(meshes, points, dir, tol, out indices); if (null != project_points) { for (int i = 0; i < project_points.Length; i++) { doc.Objects.AddPoint(project_points[i]); doc.Objects.AddLine(project_points[i], points[indices[i]]); } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Check the selected dot GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = Rhino.DocObjects.ObjectType.Annotation; go.SetCommandPrompt("Select Text to append Metrix M01:"); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); List <TextEntity> textEntityList = new List <TextEntity>(); List <RhinoObject> rhinoObjectList = new List <RhinoObject>(); // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (rhinoObject.ObjectType == ObjectType.Annotation) { TextEntity textEntity = rhinoObject.Geometry as TextEntity; if (textEntity != null) { rhinoObjectList.Add(rhinoObject); textEntityList.Add(textEntity); } } } // Sort the text Entity list IEnumerable <TextEntity> query = textEntityList.OrderByDescending(t => t.Plane.OriginY).ThenBy(t => t.Plane.OriginX); int maxDigit = (int)Math.Floor(Math.Log10(textEntityList.Count) + 1); int j = 1; foreach (TextEntity textE in query) { textE.Text = textE.Text + "-Q1"; j++; } // Commit the changes for all updated labels for (int k = 0; k < rhinoObjectList.Count; k++) { rhinoObjectList[k].CommitChanges(); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Select a mesh var go = new GetObject(); go.SetCommandPrompt("Select mesh face to extrude"); go.GeometryFilter = ObjectType.MeshFace; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } // Get the selected object reference var objref = go.Object(0); var rh_obj = objref.Object(); if (null == rh_obj) { return(Result.Failure); } // Get the base mesh var mesh = objref.Mesh(); if (null == mesh) { return(Result.Failure); } // Get the selected component var ci = objref.GeometryComponentIndex; if (ComponentIndexType.MeshFace != ci.ComponentIndexType) { return(Result.Failure); } // Copy the mesh geometry var mesh_copy = mesh.DuplicateMesh(); // Make sure the mesh has normals if (mesh_copy.FaceNormals.Count != mesh_copy.Faces.Count) { mesh_copy.FaceNormals.ComputeFaceNormals(); } if (mesh_copy.Normals.Count != mesh_copy.Vertices.Count) { mesh_copy.Normals.ComputeNormals(); } // Get the mesh face var face = mesh_copy.Faces[ci.Index]; // Get the mesh face vertices var base_vertices = new Point3d[4]; for (var i = 0; i < 4; i++) { base_vertices[i] = mesh_copy.Vertices[face[i]]; } // Get the face normal and scale it by 5.0 var offset = mesh_copy.FaceNormals[ci.Index] * (float)5.0; // Calculate the offset vertices var offset_vertices = new Point3d[4]; for (var i = 0; i < 4; i++) { offset_vertices[i] = base_vertices[i] + offset; } // Delete the mesh face var faces_indices = new int[] { ci.Index }; mesh_copy.Faces.DeleteFaces(faces_indices); // Add the base mesh face vertices var base_indices = new int[4]; for (var i = 0; i < 4; i++) { base_indices[i] = mesh_copy.Vertices.Add(base_vertices[i]); } // Add the offset mesh face vertices var offset_indices = new int[4]; for (var i = 0; i < 4; i++) { offset_indices[i] = mesh_copy.Vertices.Add(offset_vertices[i]); } // Add the new mesh faces mesh_copy.Faces.AddFace(base_indices[3], base_indices[0], offset_indices[0], offset_indices[3]); mesh_copy.Faces.AddFace(base_indices[0], base_indices[1], offset_indices[1], offset_indices[0]); mesh_copy.Faces.AddFace(base_indices[1], base_indices[2], offset_indices[2], offset_indices[1]); mesh_copy.Faces.AddFace(base_indices[2], base_indices[3], offset_indices[3], offset_indices[2]); mesh_copy.Faces.AddFace(offset_indices[0], offset_indices[1], offset_indices[2], offset_indices[3]); // Clean up mesh_copy.FaceNormals.ComputeFaceNormals(); mesh_copy.Normals.ComputeNormals(); mesh_copy.TextureCoordinates.Clear(); mesh_copy.Compact(); string log; if (!mesh_copy.IsValidWithLog(out log)) { RhinoApp.WriteLine(log); return(Result.Failure); } doc.Objects.Replace(rh_obj.Id, mesh_copy); //doc.Objects.AddMesh(mesh_copy); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var rails = new Guid[2]; var go = new GetObject(); go.SetCommandPrompt("Select first rail"); go.GeometryFilter = ObjectType.Curve; go.GeometryAttributeFilter = GeometryAttributeFilter.ClosedCurve; go.DisablePreSelect(); go.SubObjectSelect = false; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var obj = go.Object(0).Object(); if (null == obj) { return(Result.Failure); } rails[0] = obj.Id; go.SetCommandPrompt("Select second rail"); go.DeselectAllBeforePostSelect = false; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } obj = go.Object(0).Object(); if (null == obj) { return(Result.Failure); } rails[1] = obj.Id; var gc = new GetObject(); gc.SetCommandPrompt("Select cross section curves"); gc.GeometryFilter = ObjectType.Curve; gc.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; gc.DisablePreSelect(); gc.DeselectAllBeforePostSelect = false; gc.SubObjectSelect = false; gc.GetMultiple(1, 0); if (gc.CommandResult() != Result.Success) { return(gc.CommandResult()); } var curves = new Guid[gc.ObjectCount]; for (var i = 0; i < gc.ObjectCount; i++) { obj = gc.Object(i).Object(); if (null == obj) { return(Result.Failure); } curves[i] = obj.Id; } var object_ids = ScriptedSweep2(doc, rails[0], rails[1], curves); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { const ObjectType geometryFilter = ObjectType.Curve; GetObject get_rail = new GetObject(); get_rail.SetCommandPrompt("Select rail curve"); get_rail.GeometryFilter = geometryFilter; //get_rail.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; get_rail.SubObjectSelect = false; get_rail.Get(); if (get_rail.CommandResult() != Result.Success) { return(get_rail.CommandResult()); } ObjRef rail_objref = get_rail.Object(0); Curve rail_curve = rail_objref.Curve(); if (null == rail_curve) { return(Result.Failure); } GetObject get_shape = new GetObject(); get_shape.SetCommandPrompt("Select cross section curve"); get_shape.GeometryFilter = geometryFilter; //get_shape.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve; get_shape.SubObjectSelect = false; get_shape.EnablePreSelect(false, false); get_shape.DeselectAllBeforePostSelect = false; get_shape.Get(); if (get_shape.CommandResult() != Result.Success) { return(get_shape.CommandResult()); } ObjRef shape_objref = get_shape.Object(0); Curve shape_curve = shape_objref.Curve(); if (null == shape_curve) { return(Result.Failure); } double tolerance = doc.ModelAbsoluteTolerance; Brep[] brep = Brep.CreateFromSweep(rail_curve, shape_curve, false, tolerance); if (null == brep || 0 == brep.Length) { return(Result.Failure); } // Create a history record HistoryRecord history = new HistoryRecord(this, HISTORY_VERSION); WriteHistory(history, rail_objref, shape_objref, tolerance); for (int i = 0; i < brep.Length; i++) { doc.Objects.AddBrep(brep[i], null, history, false); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { string pipeIdentifier; using (GetString getter = new GetString()) { getter.SetCommandPrompt("Enter the name/url for the pipe"); if (_prevPipeName != null) { getter.SetDefaultString(_prevPipeName); } if (getter.Get() != GetResult.String) { RhinoApp.WriteLine("Invalid Input"); return(getter.CommandResult()); } pipeIdentifier = getter.StringResult(); _prevPipeName = pipeIdentifier; } if (_pipe != null) { _pipe.ClosePipe(); _pipe = null; } if (PipeDataUtil.IsValidUrl(pipeIdentifier)) { _pipe = new MyWebPipe(pipeIdentifier); } else { _pipe = new LocalNamedPipe(pipeIdentifier); } _pipe.SetCollector(this); _objectsToSend = new List <RhinoObject>(); using (GetObject getter = new GetObject()) { getter.EnablePreSelect(true, false); getter.SetCommandPrompt("Select all the objects to be pushed through the pipe"); getter.GroupSelect = true; getter.GetMultiple(1, 0); if (getter.CommandResult() != Result.Success) { return(getter.CommandResult()); } for (int i = 0; i < getter.ObjectCount; i++) { _objectsToSend.Add(getter.Object(i).Object()); } } try { _pipe.Update(); } catch (Exception e) { Rhino.UI.Dialogs.ShowMessageBox(e.Message, "Error"); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curves"); go.GeometryFilter = ObjectType.Curve; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var curve = go.Object(0).Curve(); if (null == curve) { return(Result.Failure); } var continuity = Continuity.G1_continuous; var gd = new GetOption(); gd.SetCommandPrompt("Discontinuity to search"); gd.AddOptionEnumList("Discontinuity", continuity); gd.AcceptNothing(true); var res = gd.Get(); if (res == GetResult.Option) { var option = gd.Option(); if (null == option) { return(Result.Failure); } var list = Enum.GetValues(typeof(Continuity)).Cast <Continuity>().ToList(); continuity = list[option.CurrentListOptionIndex]; } else if (res != GetResult.Nothing) { return(Result.Cancel); } var t0 = curve.Domain.Min; var t1 = curve.Domain.Max; for (; ;) { double t; var rc = curve.GetNextDiscontinuity(continuity, t0, t1, out t); if (rc) { doc.Objects.AddPoint(curve.PointAt(t)); t0 = t; } else { break; } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: complete command. MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance; if (p.if_painted_object_set_ == false) { RhinoApp.WriteLine("No mesh"); return(Result.Failure); } Mesh my_mesh = p.painted_object_; DijkstraGraph my_graph = p.graph; GetObject gbrep1 = new GetObject(); gbrep1.SetCommandPrompt("get the brep"); gbrep1.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep1.SubObjectSelect = false; gbrep1.Get(); if (gbrep1.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep1.CommandResult()); } Rhino.DocObjects.ObjRef my_objref1 = gbrep1.Object(0); Rhino.DocObjects.RhinoObject my_obj1 = my_objref1.Object(); if (my_obj1 == null) { return(Rhino.Commands.Result.Failure); } Brep brep1 = my_objref1.Brep(); if (brep1 == null) { return(Result.Failure); } my_obj1.Select(false); GetObject gbrep2 = new GetObject(); gbrep2.SetCommandPrompt("get the brep"); gbrep2.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep2.SubObjectSelect = false; gbrep2.Get(); if (gbrep2.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep2.CommandResult()); } Rhino.DocObjects.ObjRef my_objref2 = gbrep2.Object(0); Rhino.DocObjects.RhinoObject my_obj2 = my_objref2.Object(); if (my_obj2 == null) { return(Rhino.Commands.Result.Failure); } Brep brep2 = my_objref2.Brep(); if (brep2 == null) { return(Result.Failure); } my_obj2.Select(false); Point3d pin_1_position = brep1.UserDictionary.GetPoint3d("CurrentPosition"); Point3d pin_2_position = brep2.UserDictionary.GetPoint3d("CurrentPosition"); Guid pin_1_id = brep1.UserDictionary.GetGuid("PinID"); Guid pin_2_id = brep2.UserDictionary.GetGuid("PinID"); MeshPoint pin_1_meshpoint = my_mesh.ClosestMeshPoint(pin_1_position, 0); MeshPoint pin_2_meshpoint = my_mesh.ClosestMeshPoint(pin_2_position, 0); Stopwatch watch = new Stopwatch(); watch.Start(); NurbsCurve d_path = my_graph.DijkstraPath_Add(pin_1_meshpoint, pin_1_id, pin_2_meshpoint, pin_2_id); watch.Stop(); if (d_path == null) { return(Result.Success); } RhinoApp.WriteLine("link time: {0}", watch.Elapsed); ObjectAttributes my_attributes = new ObjectAttributes(); my_attributes.ObjectColor = Color.Yellow; my_attributes.ColorSource = ObjectColorSource.ColorFromObject; my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject; my_attributes.PlotWeight = 2.0; doc.Objects.AddCurve(d_path, my_attributes); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: complete command. MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance; if (p.if_painted_object_set_ == false) { RhinoApp.WriteLine("No mesh"); return(Result.Failure); } Mesh my_mesh = p.painted_object_; DijkstraGraph my_graph = p.graph; GetObject gbrep1 = new GetObject(); gbrep1.SetCommandPrompt("get the brep"); gbrep1.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep1.SubObjectSelect = false; gbrep1.Get(); if (gbrep1.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep1.CommandResult()); } Rhino.DocObjects.ObjRef my_objref1 = gbrep1.Object(0); Rhino.DocObjects.RhinoObject my_obj1 = my_objref1.Object(); if (my_obj1 == null) { return(Rhino.Commands.Result.Failure); } Brep brep1 = my_objref1.Brep(); if (brep1 == null) { return(Result.Failure); } my_obj1.Select(false); for (int i = 0; i < p.my_objects_list.Count; i++) { Guid brep1_id = My_object_functions.GetComponentID(brep1); Guid my_object_id = My_object_functions.GetComponentID(p.my_objects_list[i]); if (brep1_id == my_object_id) { p.my_objects_list.RemoveAt(i); } } IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve); foreach (RhinoObject path in path_objref) { doc.Objects.Delete(path, true); } List <NurbsCurve> new_path_list = new List <NurbsCurve>(); int pin_number = My_object_functions.GetPinQuantity(brep1); for (int i = 0; i < pin_number; i++) { Guid pin_id = My_object_functions.GetPinGuid(brep1, i); new_path_list = p.graph.DijkstraPath_DeletePin(pin_id); } ObjectAttributes my_attributes = new ObjectAttributes(); my_attributes.ObjectColor = Color.Yellow; my_attributes.ColorSource = ObjectColorSource.ColorFromObject; my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject; my_attributes.PlotWeight = 2.0; doc.Objects.Delete(my_objref1, true); for (int i = 0; i < new_path_list.Count; i++) { Guid path_id = new_path_list[i].UserDictionary.GetGuid("PathID"); my_attributes.ObjectId = path_id; doc.Objects.Add(new_path_list[i], my_attributes); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curves to fair"); go.GeometryFilter = ObjectType.Curve; go.GroupSelect = true; go.ReferenceObjectSelect = false; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } foreach (var objref in go.Objects()) { var curve = objref.Curve(); var nurb = curve?.ToNurbsCurve(); if (nurb == null) { return(Result.Failure); } if (1 == nurb.Degree) { RhinoApp.WriteLine("Cannot fair degree 1 curves."); var obj = objref.Object(); if (null != obj) { obj.Select(false); obj.Highlight(false); doc.Views.Redraw(); } return(Result.Cancel); } } var rc = GetTolerance(ref m_dist_tol); if (rc != Result.Success) { return(rc); } // Divide tolerance by 4 as part of getting Fair to stay within stated tolerance var dist_tol = m_dist_tol * 0.25; var faired_count = 0; var degree3_count = 0; foreach (var objref in go.Objects()) { var curve = objref.Curve(); var nurb = curve?.ToNurbsCurve(); if (nurb == null) { return(Result.Failure); } var curve_degree = nurb.Degree; Curve fair = null; if (nurb.IsPeriodic) { nurb.Knots.ClampEnd(CurveEnd.Start); nurb.Knots.ClampEnd(CurveEnd.End); var new_curve = nurb.Fair(dist_tol, m_ang_tol, (int)FairClamp.Tangency, (int)FairClamp.Tangency, m_iterations); if (null != new_curve) { fair = Curve.CreatePeriodicCurve(new_curve, true); } } else { fair = nurb.Fair(dist_tol, m_ang_tol, (int)FairClamp.None, (int)FairClamp.None, m_iterations); } if (null != fair && fair.IsValid) { if (curve_degree != fair.Degree) { degree3_count++; } if (doc.Objects.Replace(objref, fair)) { faired_count++; } } } if (0 == faired_count) { RhinoApp.WriteLine("No curves were faired."); } else if (1 == faired_count) { RhinoApp.WriteLine("1 curve was faired."); } else { RhinoApp.WriteLine("{0} curves were faired.", faired_count); } if (degree3_count > 0) { if (1 == degree3_count) { RhinoApp.WriteLine("1 curve was changed to degree 3 during fairing."); } else { RhinoApp.WriteLine("{0} curves were changed to degree 3 during fairing.", degree3_count); } } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { string fontName = "Dot-Matrix"; float fontSize = 12; using (System.Drawing.Font fontTester = new System.Drawing.Font(fontName, fontSize)) { if (fontTester.Name == fontName) { // Font exists do nothing } else { RhinoApp.WriteLine("Dot Matrix Font does not exist, press install to install the font. Restart Rhino after installation."); string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Process.Start(assemblyFolder + @"\Fonts\dotmat_0.ttf"); return(Rhino.Commands.Result.Failure); } } // Check the selected dot GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = Rhino.DocObjects.ObjectType.Point | Rhino.DocObjects.ObjectType.Annotation; go.SetCommandPrompt("Select Label and a point:"); GetResult result = go.GetMultiple(2, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); Point pt = null; TextEntity textEntity = null; int pointCounter = 0; int textCounter = 0; // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (rhinoObject.ObjectType == ObjectType.Annotation) { textEntity = rhinoObject.Geometry as TextEntity; if (textEntity != null && textCounter == 0) { textCounter++; } } else if (rhinoObject.ObjectType == ObjectType.Point) { pt = rhinoObject.Geometry as Point; if (pt != null && pointCounter == 0) { pointCounter++; } } } //if (go.Object(0).Point() != null && go.Object(1).TextEntity() != null) //{ // pt = go.Object(0).Point(); // textEntity = go.Object(1).TextEntity(); //} //else if (go.Object(1).Point() != null && go.Object(0).TextEntity() != null) //{ // pt = go.Object(1).Point(); // textEntity = go.Object(0).TextEntity(); //} //else //{ // RhinoApp.WriteLine("Two of the same objects are selected."); // return Result.Failure; //} if (textCounter > 1) { RhinoApp.WriteLine("More than one text has been selected."); } if (pointCounter > 1) { RhinoApp.WriteLine("More than one point has been selected."); } // Record the current layer int currentLayer = doc.Layers.CurrentLayerIndex; // Set the layer to perforation RhinoUtilities.SetActiveLayer(Properties.Settings.Default.DotFontLayerName, System.Drawing.Color.Black); if (pt != null && textEntity != null) { drawDotMatrix(pt.Location, textEntity.Text, Properties.Settings.Default.DotMatrixHeight, 80); } doc.Layers.SetCurrentLayerIndex(currentLayer, true); doc.Views.Redraw(); return(Result.Success); }