public void Transform() { var ctx = Context.Current; var plane = DatumPlane.Create(); ctx.Document.Add(plane); ctx.ViewportController.ZoomFitAll(); Assert.Multiple(() => { ctx.ClickAt(300, 300); Assert.That(ctx.WorkspaceController.Selection.SelectedEntities.SequenceEqual(new[] { plane })); Assert.That(WorkspaceCommands.Transform.CanExecute()); WorkspaceCommands.Transform.Execute(); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Transform01")); ctx.MoveTo(219, 267); ctx.ViewportController.MouseDown(); ctx.MoveTo(151, 313); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Transform02")); // AIS local transformation working ctx.ViewportController.MouseUp(false); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Transform03")); // Updating transformation working }); }
private void CreateSketchInLayer(int layerNr) { double _z = layerNr * layerHeight; // create an empty sketch Point3d nxOrigin = new Point3d(0.0, 0.0, 0.0); Point3d curaOrigin = new Point3d(-111.5, -111.5, 0); Matrix3x3 wcsMatrix = workPart.WCS.CoordinateSystem.Orientation.Element; DatumPlane myDatumPlane = workPart.Datums.CreateFixedDatumPlane(nxOrigin, wcsMatrix); DisplayableObject[] objects = { myDatumPlane }; theSession.DisplayManager.BlankObjects(objects); // hide datum plane SketchInPlaceBuilder sketchBuilder = workPart.Sketches.CreateSketchInPlaceBuilder2((Sketch)null); sketchBuilder.PlaneOrFace.Value = myDatumPlane; sketchBuilder.SketchOrigin = workPart.Points.CreatePoint(curaOrigin); sketchBuilder.PlaneOption = Sketch.PlaneOption.Inferred; mySketch = (Sketch)sketchBuilder.Commit(); sketchBuilder.Destroy(); objects[0] = mySketch; theSession.DisplayManager.BlankObjects(objects); mySketch.SetName("Sketch_Layer_" + layerNr.ToString()); mySketch.Activate(Sketch.ViewReorient.False); workPart.ModelingViews.WorkView.FitAfterShowOrHide(View.ShowOrHideType.HideOnly); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { ReferenceArray GridsRefRow = new ReferenceArray(); ReferenceArray GridsRefCol = new ReferenceArray(); XYZ TopPoint = null; XYZ LeftPoint = null; foreach (ElementId elemId in uidoc.Selection.GetElementIds()) { Element SelectedElem = doc.GetElement(elemId); if (SelectedElem is DatumPlane) { DatumPlane xGrid = SelectedElem as DatumPlane; IList <Curve> CurvesInGrid = xGrid.GetCurvesInView(DatumExtentType.ViewSpecific, uidoc.ActiveView); Curve cv = CurvesInGrid.First(); // only one segment grids allowed XYZ cvStart = cv.GetEndPoint(0); XYZ cvEnd = cv.GetEndPoint(1); if (Convert.ToInt32(cvStart.Y) == Convert.ToInt32(cvEnd.Y)) // then its a horizontal line, need to round the double bc the comparison will never work { GridsRefRow.Append(new Reference(xGrid)); if (LeftPoint is null && cvStart.X < cvEnd.X) // drawn left to right, keep start X---------> { LeftPoint = cvStart; } else if (LeftPoint is null && cvStart.X > cvEnd.X) // drawn right to left, keep end <---------X { LeftPoint = cvEnd; } } else if (Convert.ToInt32(cvStart.X) == Convert.ToInt32(cvEnd.X)) // then its a vertical { GridsRefCol.Append(new Reference(xGrid)); if (TopPoint is null && cvStart.Y < cvEnd.Y) // drawn bottom to top, keep end { TopPoint = cvEnd; } else if (TopPoint is null && cvStart.Y > cvEnd.Y) // drawn top to bottom, keep start { TopPoint = cvStart; } } } }
private void GetXYPlane(Part component, out DatumPlane XYPlane) { DatumCollection datums = component.Datums; object[] datums1 = component.Datums.ToArray(); List <DatumPlane> datumPlanes = new List <DatumPlane>(); XYPlane = null; foreach (object obj in datums1) { DatumPlane plane = obj as DatumPlane; if (plane != null) { datumPlanes.Add(plane); } } foreach (DatumPlane plane in datumPlanes) { if (plane.Normal.Z == 1) { XYPlane = plane; } } }
public void ColorFromLayer() { var ctx = Context.Current; ctx.Layers.ActiveLayer.Color = new Color(1, 0, 0); var plane = DatumPlane.Create(); Assert.AreEqual("DatumPlane_1", plane.Name); ctx.Document.Add(plane); ctx.ViewportController.ZoomFitAll(); Assert.Multiple(() => { AssertHelper.IsSameViewport(Path.Combine(_BasePath, "ColorFromLayer01")); ctx.Layers.ActiveLayer.Color = new Color(0, 1, 0); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "ColorFromLayer02")); var layer = new Layer() { Color = new Color(0, 0, 1) }; ctx.Layers.Add(layer); plane.Layer = layer; AssertHelper.IsSameViewport(Path.Combine(_BasePath, "ColorFromLayer03")); }); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document document = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.DB.View view = commandData.Application.ActiveUIDocument.ActiveView; datumDic.Clear(); ICollection <ElementId> datums = commandData.Application.ActiveUIDocument.Selection.GetElementIds(); if (datums == null || datums.Count == 0) { return(Result.Cancelled); } foreach (ElementId datumRef in datums) { DatumPlane datum = document.GetElement(datumRef) as DatumPlane; if (!datumDic.Keys.Contains(datum.Name)) { datumDic.Add(datum.Name, datum); } } //// Show UI using (AlignmentSetting settingForm = new AlignmentSetting()) { if (settingForm.ShowDialog() == DialogResult.OK) { DatumPlane selectedDatum = datumDic[settingForm.datumList.SelectedItem.ToString()]; Curve baseCurve = selectedDatum.GetCurvesInView(DatumExtentType.ViewSpecific, view).ElementAt(0); Line baseLine = baseCurve as Line; XYZ baseDirect = baseLine.Direction; using (Transaction tran = new Transaction(document, "DatumAlignment")) { tran.Start(); foreach (DatumPlane datum in datumDic.Values) { Curve curve = datum.GetCurvesInView(datum.GetDatumExtentTypeInView(DatumEnds.End0, view), view).ElementAt(0); XYZ direct = (curve as Line).Direction; Curve newCurve = CalculateCurve(curve, baseLine, baseDirect); datum.SetCurveInView(datum.GetDatumExtentTypeInView(DatumEnds.End0, view), view, newCurve); } tran.Commit(); } } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
//-------------------------------------------------------------------------------------------------- public override void Initialize(BaseObject instance) { DatumPlane = instance as DatumPlane; Debug.Assert(DatumPlane != null); if (Application.Current != null) { InitializeComponent(); } }
private static string FormatDatumOffsetString(DatumPlane datum, double offset, Units docUnits) { if (datum == null) { return(UnitFormatUtils.Format(docUnits, 0, offset, false, false)); } double num = Math.Abs(offset); bool flag = offset < 0.0; return("(" + datum.get_Name() + ")" + (flag ? " - " : " + ") + UnitFormatUtils.Format(docUnits, 0, num, false, false)); }
public void CreateWithImage() { var ctx = Context.Current; var imagePlane = DatumPlane.Create(); imagePlane.ImageFilePath = _SourceImagePath; ctx.Document.Add(imagePlane); ctx.ViewportController.ZoomFitAll(); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "CreateWithImage01")); }
public void Create() { var ctx = Context.Current; var plane = DatumPlane.Create(); Assert.AreEqual("DatumPlane_1", plane.Name); ctx.Document.Add(plane); ctx.ViewportController.ZoomFitAll(); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Create01")); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document document = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.DB.View view = commandData.Application.ActiveUIDocument.ActiveView; viewDic.Clear(); ElementId datumRef = commandData.Application.ActiveUIDocument.Selection.GetElementIds().First(); if (datumRef == null) { return(Result.Cancelled); } DatumPlane datum = document.GetElement(datumRef) as DatumPlane; ISet <ElementId> viewList = datum.GetPropagationViews(view); foreach (ElementId id in viewList) { Autodesk.Revit.DB.View pView = document.GetElement(id) as Autodesk.Revit.DB.View; if (!viewDic.Keys.Contains(pView.ViewType + " : " + pView.Name)) { viewDic.Add(pView.ViewType + " : " + pView.Name, id); } } //// Show UI using (PropogateSetting settingForm = new PropogateSetting()) { if (settingForm.ShowDialog() == DialogResult.OK) { ISet <ElementId> pViewList = new List <ElementId>() as ISet <ElementId>; foreach (var item in settingForm.propagationViewList.CheckedItems) { ElementId selectedView = viewDic[item.ToString()]; pViewList.Add(selectedView); } using (Transaction tran = new Transaction(document, "propagation")) { tran.Start(); datum.PropagateToViews(view, pViewList); tran.Commit(); } } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
public bool CopyGridExtent(Document doc, View sourceView, Reference selectedGrid) { DatumPlane selectedDatum = doc.GetElement(selectedGrid) as DatumPlane; Curve baseCurve = selectedDatum.GetCurvesInView(DatumExtentType.ViewSpecific, sourceView).ElementAt(0); XYZ basePoint0 = baseCurve.GetEndPoint(0); XYZ basePoint1 = baseCurve.GetEndPoint(1); Line baseLine = baseCurve as Line; Curve newCurve = selectedDatum.GetCurvesInView(DatumExtentType.ViewSpecific, doc.ActiveView).ElementAt(0); XYZ newCurvePt = newCurve.GetEndPoint(0); Line newLine = newCurve as Line; //sb.AppendLine("Source view end0 " + baseLine.GetEndPoint(0).X.ToString() + " - " + baseLine.GetEndPoint(0).Y.ToString() + " - " + baseLine.GetEndPoint(0).Z.ToString()); //sb.AppendLine("Active view end0 " + newLine.GetEndPoint(0).X.ToString() + " - " + newLine.GetEndPoint(0).Y.ToString() + " - " + newLine.GetEndPoint(0).Z.ToString()); //sb.AppendLine("Source view end1 " + baseLine.GetEndPoint(1).X.ToString() + " - " + baseLine.GetEndPoint(1).Y.ToString() + " - " + baseLine.GetEndPoint(1).Z.ToString()); //sb.AppendLine("Active view end1 " + newLine.GetEndPoint(1).X.ToString() + " - " + newLine.GetEndPoint(1).Y.ToString() + " - " + newLine.GetEndPoint(1).Z.ToString()); ISet <ElementId> par = new List <ElementId>() as ISet <ElementId>; View destination = doc.ActiveView; ViewPlan vp = destination as ViewPlan; PlanViewRange pvr = vp.GetViewRange(); Level l = vp.GenLevel; double zLevel = pvr.GetOffset(PlanViewPlane.CutPlane) + l.Elevation; //Z point for Datum curve //Curve projectedCurve = Line.CreateBound(new XYZ(basePoint0.X, basePoint0.Y, newCurvePt.Z), new XYZ(basePoint1.X, basePoint1.Y, newCurvePt.Z)); Curve projectedCurve = Line.CreateBound(new XYZ(basePoint0.X, basePoint0.Y, zLevel), new XYZ(basePoint1.X, basePoint1.Y, zLevel)); //par.Add(destination); //TaskDialog.Show("r", par.Count.ToString()); Grid g = doc.GetElement(selectedGrid) as Grid; //g.SetDatumExtentType(DatumEnds.End1, destination, DatumExtentType.ViewSpecific); g.SetCurveInView(g.GetDatumExtentTypeInView(DatumEnds.End1, sourceView), destination, projectedCurve); //TaskDialog.Show("r", sb.ToString()); //g.PropagateToViews(source, par); return(true); }
public static void AnnotateFace(Part targetPart, DesignFace face, string comment, double textHeight, Direction?direction) { string annotationPlanePartName = "Annotation Planes"; Part part = null; foreach (Part testPart in targetPart.Document.Parts) { if (testPart.Name == annotationPlanePartName) { part = testPart; } } if (part == null) { part = Part.Create(targetPart.Document, annotationPlanePartName); Component component = Component.Create(targetPart, part); } Plane plane = GetPlaneCenteredOnFace(face); if (direction != null) { Direction dirX = Direction.DirX; if (direction.Value != Direction.DirZ) { dirX = direction.Value.ArbitraryPerpendicular; } plane = Plane.Create(Frame.Create(plane.Frame.Origin, dirX, Direction.Cross(direction.Value, dirX))); } Layer planeLayer = CreateOrGetLayer(targetPart.Document, Resources.AnnotationPlaneLayerNameText, System.Drawing.Color.Black); planeLayer.SetVisible(null, false); Layer noteLayer = CreateOrGetLayer(targetPart.Document, Resources.AnnotationLayerNameText, System.Drawing.Color.DarkRed); DatumPlane datum = DatumPlane.Create(part, Resources.AnnotationPlaneNameText, plane); datum.Layer = planeLayer; PointUV location = PointUV.Origin; Note note = Note.Create(datum, location, TextPoint.Center, textHeight, comment); note.SetFontName(DraftingFont.Asme); note.Layer = noteLayer; note.SetColor(null, null); }
public void Clone() { var ctx = Context.Current; ctx.Workspace.GridEnabled = true; ctx.Workspace.GridStep = 15.0; var datumPlane = DatumPlane.Create(); datumPlane.Position = new Pnt(5, 10, 10); ctx.Document.Add(datumPlane); ctx.WorkspaceController.Selection.SelectEntity(datumPlane); Assert.IsTrue(WorkspaceCommands.DuplicateEntity.CanExecute()); WorkspaceCommands.DuplicateEntity.Execute(); Assert.AreEqual(2, ctx.Document.Cast <DatumPlane>().Count()); }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { //isDetectingCollisions = Booleans[Resources.DetectCollisionsText].Value; //isCreatingDashes = Booleans[Resources.CreateDashesText].Value; Part part = Window.ActiveWindow.Scene as Part; if (part == null) { return; } Layer curveLayer = NoteHelper.CreateOrGetLayer(Window.ActiveWindow.Document, Resources.FlatMediumEngravingLayerName, System.Drawing.Color.Green); Layer planeLayer = NoteHelper.CreateOrGetLayer(part.Document, Resources.AnnotationPlanesLayerName, Color.Gray); planeLayer.SetVisible(null, false); foreach (Component component in part.Components) { Body body = component.Content.Bodies.First().Master.Shape.Copy(); body.Transform(component.Content.TransformToMaster.Inverse); Face startFace = body.Faces.First(); string name = component.Content.Master.Name; FlatPattern flatPattern = new FlatPattern(body, startFace, isDetectingCollisions, false, 0, 0, name); flatPattern.Render(); DatumPlane datumPlane = DatumPlane.Create(flatPattern.FlatPart, Resources.AnnotationPlaneName, flatPattern.PaperPlane); datumPlane.Layer = planeLayer; PointUV center = flatPattern.PaperPlane.ProjectPoint(flatPattern.GetBoundingBox(Matrix.Identity).Center).Param; Note note = Note.Create(datumPlane, center, TextPoint.Center, 0.01, name); note.Layer = NoteHelper.CreateOrGetLayer(part.Document, Resources.AnnotationLayerName, System.Drawing.Color.DarkViolet); foreach (FlatBody flatBody in flatPattern.FlatBodies) { foreach (FlatFace flatFace in flatBody.FlatFaces) { foreach (ITrimmedCurve iTrimmedCurve in part.Curves.Select(c => c.Shape).Where(c => c.AreEndPointsOnFace(flatFace.SourceFace))) { var designCurve = DesignCurve.Create(flatBody.FlatPart, iTrimmedCurve); designCurve.Transform(flatFace.Transform); designCurve.Layer = curveLayer; } } } } }
public void CreateOnDatumPlane() { var ctx = Context.Current; ctx.Workspace.GridEnabled = true; ctx.Workspace.GridStep = 15.0; var datumPlane = DatumPlane.Create(); datumPlane.Position = new Pnt(5, 10, 10); ctx.Document.Add(datumPlane); ctx.ViewportController.ZoomFitAll(); ctx.WorkspaceController.StartTool(new CreateSketchTool(CreateSketchTool.CreateMode.Interactive)); ctx.ClickAt(300, 300); var sketchEditTool = ctx.WorkspaceController.CurrentTool as SketchEditorTool; Assert.NotNull(sketchEditTool); Assert.AreEqual(sketchEditTool.Sketch.Body.Position, datumPlane.Position); }
public void SelectAsWorkingPlane() { var ctx = Context.Current; ctx.Workspace.GridEnabled = true; ctx.Workspace.GridStep = 15.0; var datumPlane = DatumPlane.Create(); datumPlane.Position = new Pnt(5, 10, 10); ctx.Document.Add(datumPlane); ctx.ViewportController.ZoomFitAll(); Assert.Multiple(() => { WorkspaceCommands.AlignWorkingPlane.Execute(); ctx.ClickAt(300, 300); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "SelectAsWorkingPlane01")); }); }
public void Select() { var ctx = Context.Current; var datumPlane = DatumPlane.Create(); ctx.Document.Add(datumPlane); Assert.Multiple(() => { ctx.ViewportController.ZoomFitAll(); ctx.MoveTo(300, 300); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Select01")); ctx.ClickAt(300, 300); Assert.That(ctx.WorkspaceController.Selection.SelectedEntities.SequenceEqual(new[] { datumPlane })); ctx.MoveTo(1, 1); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "Select02")); }); }
public void SelectInSelectionContext() { var ctx = Context.Current; var datumPlane = DatumPlane.Create(); ctx.Document.Add(datumPlane); ctx.ViewportController.ZoomFitAll(); Assert.Multiple(() => { var selCtx = ctx.WorkspaceController.Selection.OpenContext(SelectionContext.Options.IncludeAll); ctx.ClickAt(300, 300); Assert.That(ctx.WorkspaceController.Selection.SelectedEntities.SequenceEqual(new[] { datumPlane })); ctx.WorkspaceController.Selection.CloseContext(selCtx); ctx.WorkspaceController.Selection.SelectEntity(null); ctx.ClickAt(300, 300); Assert.That(ctx.WorkspaceController.Selection.SelectedEntities.SequenceEqual(new[] { datumPlane })); }); }
public void HideWithLayer() { var ctx = Context.Current; var datumPlane = DatumPlane.Create(); ctx.Document.Add(datumPlane); ctx.ViewportController.ZoomFitAll(); Assert.Multiple(() => { ctx.Document.Layers.ActiveLayer.IsVisible = false; AssertHelper.IsSameViewport(Path.Combine(_BasePath, "HideWithLayer01")); ctx.ClickAt(300, 300); Assert.AreEqual(0, ctx.WorkspaceController.Selection.SelectedEntities.Count); ctx.Document.Layers.ActiveLayer.IsVisible = true; AssertHelper.IsSameViewport(Path.Combine(_BasePath, "HideWithLayer02")); ctx.ClickAt(300, 300); Assert.AreEqual(1, ctx.WorkspaceController.Selection.SelectedEntities.Count); }); }
public void IsolateSelection() { var ctx = Context.Current; var datumPlane = DatumPlane.Create(); ctx.Document.Add(datumPlane); ctx.ViewportController.ZoomFitAll(); var body1 = TestData.GetBodyFromBRep(@"SourceData\BRep\ImprintRingFace.brep"); Assert.Multiple(() => { ctx.WorkspaceController.Selection.SelectEntity(body1); WorkspaceCommands.ToggleIsolateSelection.Execute(); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "IsolateSelection01")); WorkspaceCommands.ToggleIsolateSelection.Execute(); ctx.WorkspaceController.Selection.SelectEntity(datumPlane); WorkspaceCommands.ToggleIsolateSelection.Execute(); AssertHelper.IsSameViewport(Path.Combine(_BasePath, "IsolateSelection02")); }); }
//-------------------------------------------------------------------------------------------------- public override void Cleanup() { DatumPlane = null; }
//-------------------------------------------------------------------------------------------------- public VisualPlane(WorkspaceController workspaceController, DatumPlane entity) : base(workspaceController, entity) { _DatumPlane = entity; Update(); }
public static void Print(this Plane plane, Part part = null) { DatumPlane.Create(part ?? MainPart, GetDebugString(plane), plane); }
public void ToolSketch(Part workPart, Session theSession) { string com; try { //CordSystemAndGeometry Class object CordSystemAndGeometry geomObj = new CordSystemAndGeometry(); //ReadFile Class object ReadFile data = new ReadFile(); data.ReadData(); // Definition of cradle center point //Point ptCradleCenter = geomObj.Point3DCreation(workPart, 0, 0, 0); Point3d ptCradleCenter = new Point3d(0, 0, 0); //Definition of cradle Csys // Point ptX = geomObj.Point3DCreation(workPart, 10, 0, 0); // Point ptY = geomObj.Point3DCreation(workPart, 0, 10, 0); Point3d ptX = new Point3d(10, 0, 0); Point3d ptY = new Point3d(0, 10, 0); NXOpen.Features.DatumCsys csysCradle = geomObj.CsysCreation(workPart, ptCradleCenter, ptX, ptY); //Definition of Cradle Angle sign // Hand of spiral // -- LEFT: -Q // -- RIGHT: +Q if (data.kierunekLinii == 0) { data.q = -data.q; } else if (data.kierunekLinii != 1 && data.kierunekLinii != 0) { throw new Exception("Niepoprawne dane dotyczace Pochylenia Linii Zeba"); } if (data.q == 0) { throw new Exception("Niepoprawne dane dotyczace Ustawienia Katowego Glowicy"); } // Taken Q to calculations: com = "Q przyjete do obliczen: " + data.q.ToString(); data.PrintComToLog(theSession, com); //Changing polar to cartesian cordinates double H = data.u * Math.Cos(data.q * (Math.PI / 180)); double V = data.u * Math.Sin(data.q * (Math.PI / 180)); //------ Cutter sketch creation ------ //Total tooth depth double mat = data.hae + data.hfe; //Starting points and line Point3d pGlo1 = new Point3d(ptCradleCenter.X - data.wys, ptCradleCenter.Y + H, ptCradleCenter.Z + V); Point3d pGlo2 = geomObj.Point3DPolar(workPart, pGlo1, -mat, 0); Line lGlo1 = geomObj.UnAssLines(workPart, pGlo1, pGlo2); //cutter outline Point3d pGlo8 = geomObj.Point3DPolar(workPart, pGlo2, data.d0 / 2, -90); Point3d pGlo10 = geomObj.Point3DPolar(workPart, pGlo8, data.wys + mat, 0); Point3d pGlo9 = geomObj.Point3DPolar(workPart, pGlo10, data.w2 / 2, -90); Point3d pGlo5 = pGlo9; Point3d pGlo4 = geomObj.Point3DPolar(workPart, pGlo5, data.wys / Math.Cos(data.alf2wk * Math.PI / 180), 180 + data.alf2wk); Point3d pGlo3 = geomObj.Point3DPolar(workPart, pGlo4, mat, 180); Point3d pGlo6 = geomObj.Point3DPolar(workPart, pGlo9, data.w2 / 2, 90); Point3d pGlo7 = geomObj.Point3DPolar(workPart, pGlo6, data.wys / Math.Cos(data.alf2wp * Math.PI / 180), 180 - data.alf2wp); Line lGlo2 = geomObj.UnAssLines(workPart, pGlo2, pGlo3); Line lGlo3 = geomObj.UnAssLines(workPart, pGlo4, pGlo3); Line lGlo4 = geomObj.UnAssLines(workPart, pGlo5, pGlo4); Line lGlo5 = geomObj.UnAssLines(workPart, pGlo5, pGlo6); Line lGlo6 = geomObj.UnAssLines(workPart, pGlo6, pGlo7); Line lGlo7 = geomObj.UnAssLines(workPart, pGlo7, pGlo1); Point3d pointt = new Point3d(0, 0, 0); //Point pointInput = workPart.Points.CreatePoint(pointt); Point3d pointt2 = new Point3d(0, 20, 0); //Point pointInput2 = workPart.Points.CreatePoint(pointt2); Curve linia1 = workPart.Curves.CreateLine(pointt, pointt2); linia1.SetVisibility(SmartObject.VisibilityOption.Visible); //Sketch def //Axis normal do sketch plane Point3d helpPointN = new Point3d(0, 0, 1); DatumAxis axisNor = geomObj.DatumAxisCreation(workPart, ptCradleCenter, helpPointN); DatumPlane plane = geomObj.DatumPlaneCreation(workPart, pGlo2, axisNor); //Axis perpendicular to the sketch plane Point3d helpPointP = new Point3d(1, 0, 0); DatumAxis axisPer = geomObj.DatumAxisCreation(workPart, ptCradleCenter, helpPointP); Sketch sketchTool = geomObj.SketchCreation(workPart, theSession, pGlo2, axisPer, plane, csysCradle); //Attach geometry to the sketch sketchTool.AddGeometry(lGlo2); sketchTool.AddGeometry(lGlo3); sketchTool.AddGeometry(lGlo4); sketchTool.AddGeometry(lGlo5); sketchTool.AddGeometry(lGlo6); sketchTool.AddGeometry(lGlo7); sketchTool.Update(); //Cutter radius creation //Concave side Point3d helpPoint1 = geomObj.Point3dOnCurve(workPart, "0.5", lGlo5); Point3d helpPoint2 = geomObj.Point3dOnCurve(workPart, "0.5", lGlo4); Arc r02wk = geomObj.FilletOnSketch(theSession, lGlo5, lGlo4, helpPoint1, helpPoint2, data.r02wk); //Convex side helpPoint1 = geomObj.Point3dOnCurve(workPart, "0.5", lGlo5); helpPoint2 = geomObj.Point3dOnCurve(workPart, "0.5", lGlo6); Arc r02wp = geomObj.FilletOnSketch(theSession, lGlo5, lGlo6, helpPoint1, helpPoint2, data.r02wp); sketchTool.Update(); //Creation a solid cutter //Axis def Vector3d vectorCutterAxis = new Vector3d(1, 0, 0); Axis axisCutter = geomObj.AxisCreation(workPart, pGlo1, vectorCutterAxis); Body cutter = geomObj.Revolve(workPart, axisCutter, sketchTool, lGlo6, pGlo1, 0, 360); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { base.OnExecute(command, context, buttonRect); List <ITrimmedCurve> trimmedCurves = new List <ITrimmedCurve>(); foreach (ITrimmedCurve trimmedCurve in activeWindow.GetAllSelectedITrimmedCurves()) { trimmedCurves.Add(trimmedCurve); } TrimmedCurveChain curveChain = new TrimmedCurveChain(trimmedCurves); double length = curveChain.Length; int count = (int)Math.Floor(length / dashMinSize / 2) * 2; if (curveChain.StartPoint != curveChain.EndPoint) // odd number when not closed curve { count++; } List <DesignCurve> dashes = new List <DesignCurve>(); double lastParam = curveChain.Bounds.Start; Point lastPoint; Debug.Assert(curveChain.TryGetPointAlongCurve(lastParam, out lastPoint)); for (int i = 0; i < count; i++) { Point point; if (curveChain.TryGetPointAlongCurve(lastParam -= length / count, out point)) { if (i % 2 == 1) { DesignCurve dash = DesignCurve.Create(part, CurveSegment.Create(lastPoint, point)); dash.Layer = dashLayer; dashes.Add(dash); } #if false // tori ShapeHelper.CreateTorus( new Point[] { point, lastPoint }.Average(), (point - lastPoint).Direction, 0.188 * inches, 0.75 * inches, part ); #endif lastPoint = point; } } #if false // cylinders for (int i = 1; i < count; i++) { CurveEvaluation eval = dashes[i].Shape.Geometry.Evaluate(dashes[i].Shape.Bounds.Start); Direction dir1 = eval.Tangent; eval = dashes[i - 1].Shape.Geometry.Evaluate(dashes[i - 1].Shape.Bounds.End); Direction dir2 = eval.Tangent; if (dir1 == dir2) { DatumPlane.Create(part, "miter parallel", Plane.Create(Frame.Create(eval.Point, eval.Tangent.ArbitraryPerpendicular, Direction.Cross(eval.Tangent.ArbitraryPerpendicular, eval.Tangent)))); continue; } Direction averageDir = (dir1.UnitVector + dir2.UnitVector).Direction; Direction xDir = Direction.Cross(averageDir, dir1); // DatumPlane.Create(part, "miter", Plane.Create(Frame.Create(eval.Point, xDir, Direction.Cross(xDir, averageDir)))); double offset = 0.0001 / 2; ShapeHelper.CreateCylinder(eval.Point + averageDir * offset, eval.Point - averageDir * offset, 7 * inches, part); } #endif }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { using (Transaction t = new Transaction(doc, "Correct grid bubbles")) { t.Start(); foreach (ElementId elemId in uidoc.Selection.GetElementIds()) { Element SelectedElem = doc.GetElement(elemId); if (SelectedElem is DatumPlane) { DatumPlane xGrid = SelectedElem as DatumPlane; IList <Curve> CurvesInGrid = xGrid.GetCurvesInView(DatumExtentType.ViewSpecific, uidoc.ActiveView); Curve cv = CurvesInGrid.First(); // only one segment grids allowed XYZ cvStart = cv.GetEndPoint(0); XYZ cvEnd = cv.GetEndPoint(1); XYZ cvTop = null; XYZ cvLeft = null; #region FIND TOP AND LEFT if (Convert.ToInt32(cvStart.Y) == Convert.ToInt32(cvEnd.Y)) // then its a horizontal line { if (cvStart.X < cvEnd.X) // drawn left to right, keep start X---------> { cvLeft = cvStart; } else if (cvStart.X > cvEnd.X) // drawn right to left, keep end <---------X { cvLeft = cvEnd; } } else if (Convert.ToInt32(cvStart.X) == Convert.ToInt32(cvEnd.X)) // then its a vertical { if (cvStart.Y < cvEnd.Y) // drawn bottom to top, keep end { cvTop = cvEnd; } else if (cvStart.Y > cvEnd.Y) // drawn top to bottom, keep start { cvTop = cvStart; } } #endregion // Use top and left, and start and end to find which endpoint to turn on if ((cvLeft != null && cvLeft.IsAlmostEqualTo(cvStart)) || (cvTop != null && cvTop.IsAlmostEqualTo(cvStart))) // the grid was drawn correctly { xGrid.ShowBubbleInView(DatumEnds.End0, uidoc.ActiveView); xGrid.HideBubbleInView(DatumEnds.End1, uidoc.ActiveView); } else if ((cvLeft != null && cvLeft.IsAlmostEqualTo(cvEnd)) || cvTop != null && cvTop.IsAlmostEqualTo(cvEnd)) // the grid was drawn the other way around { xGrid.ShowBubbleInView(DatumEnds.End1, uidoc.ActiveView); xGrid.HideBubbleInView(DatumEnds.End0, uidoc.ActiveView); } } } t.Commit(); } return(Result.Succeeded); } catch (Exception ex) { Utils.CatchDialog(ex); return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document document = commandData.Application.ActiveUIDocument.Document; ICollection <ElementId> datums = commandData.Application.ActiveUIDocument.Selection.GetElementIds(); Autodesk.Revit.DB.View view = commandData.Application.ActiveUIDocument.ActiveView; if (datums == null || datums.Count == 0) { return(Result.Cancelled); } //// Show UI using (DatumStyleSetting settingForm = new DatumStyleSetting()) { if (settingForm.ShowDialog() == DialogResult.OK) { using (Transaction tran = new Transaction(document, "StyleModification")) { tran.Start(); foreach (ElementId datumRef in datums) { DatumPlane datum = document.GetElement(datumRef) as DatumPlane; if (showLeftBubble) { datum.ShowBubbleInView(DatumEnds.End0, view); } else { datum.HideBubbleInView(DatumEnds.End0, view); } if (showRightBubble) { datum.ShowBubbleInView(DatumEnds.End1, view); } else { datum.HideBubbleInView(DatumEnds.End1, view); } if (changeLeftEnd2D) { datum.SetDatumExtentType(DatumEnds.End0, view, DatumExtentType.ViewSpecific); } else { datum.SetDatumExtentType(DatumEnds.End0, view, DatumExtentType.Model); } if (changeRightEnd2D) { datum.SetDatumExtentType(DatumEnds.End1, view, DatumExtentType.ViewSpecific); } else { datum.SetDatumExtentType(DatumEnds.End1, view, DatumExtentType.Model); } if (addLeftElbow && datum.GetLeader(DatumEnds.End0, view) == null) { datum.AddLeader(DatumEnds.End0, view); } else if (datum.GetLeader(DatumEnds.End0, view) != null) { Leader leader = datum.GetLeader(DatumEnds.End0, view); leader = CalculateLeader(leader, addLeftElbow); datum.SetLeader(DatumEnds.End0, view, leader); } if (addRightElbow && datum.GetLeader(DatumEnds.End1, view) == null) { datum.AddLeader(DatumEnds.End1, view); } else if (datum.GetLeader(DatumEnds.End1, view) != null) { Leader leader = datum.GetLeader(DatumEnds.End1, view); leader = CalculateLeader(leader, addRightElbow); datum.SetLeader(DatumEnds.End1, view, leader); } } tran.Commit(); } } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
private static void c_Executing(object sender, CommandExecutingEventArgs e) { Window aw = Window.ActiveWindow; // section plane. It is not null only if sketch or section mode is on. Plane sP = aw.ActiveContext.SectionPlane; if (sP != null) { int sw = aw.Size.Width; int sh = aw.Size.Height; // get screen center, right-mid and upper mid System.Drawing.Point sm = new System.Drawing.Point((int)Math.Round(sw * 0.5), (int)Math.Round(sh * 0.5)); System.Drawing.Point sr = new System.Drawing.Point(sw, sm.Y); System.Drawing.Point su = new System.Drawing.Point(sm.X, 1); // screen center projection onto section plane in model coordinates Point mm; if (sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(sm), out mm)) { // get projections of right mid and upper mid and use these projections // to define bas vectors. Point mr, mu; sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(sr), out mr); sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(su), out mu); Vector bx = mr - mm; Vector bz = Vector.Cross(bx, mu - mm); // normal to section plane looking to us Vector by = Vector.Cross(bz, bx); double ext = bx.Magnitude; // rotate view to look perpendicular to section plane double fe = ext * Math.Min(sw, sh) / Math.Max(sw, sh) * 2; aw.SetProjection(Frame.Create(mm, bx.Direction, by.Direction), fe); // generate string for clipboard string f3 = " {0:G5} {1:G5} {2:G5} "; string f1 = " {0:G5} "; string pc = ""; // or command pc = "or"; pc += string.Format(f3, nullify(mm.X * cc), nullify(mm.Y * cc), nullify(mm.Z * cc)); // bas command bx = bx.Direction.UnitVector; by = by.Direction.UnitVector; pc += "bas"; pc += string.Format(f3, nullify(bx.X), nullify(bx.Y), nullify(bx.Z)); pc += string.Format(f3, nullify(by.X), nullify(by.Y), nullify(by.Z)); // ext command pc += "ext"; pc += string.Format(f1, ext * cc); // tune formatting pc = pc.Replace(",", "."); pc = pc.Replace("E+000", " "); pc = pc.Replace("E-000", " "); pc = pc.Replace("E+00", "E+"); pc = pc.Replace("E-00", "E-"); pc = pc.Replace("E+0", "E+"); pc = pc.Replace("E-0", "E-"); // put to clipboard ClipBoard.SetText(pc); } else { SpaceClaim.Api.V16.Application.ReportStatus("Section plane exists but cannot intersect with cursor ray", StatusMessageType.Information, null); } } else { // try to read plot commands from clipboard Frame fr; double ext; if (TryParseClipboard(out fr, out ext)) { // If clipboard parsed, add a new plane to the model DatumPlane.Create(aw.Document.MainPart, "MCNP plot plane", Plane.Create(fr)); } else { SpaceClaim.Api.V16.Application.ReportStatus("Clipboard does not contain MCNP plot commands.", StatusMessageType.Warning, null); } } }
//------------------------------------------------------------------------------ // NX Startup // This entry point activates the application at NX startup //Will work when complete path of the dll is provided to Environment Variable //USER_STARTUP or USER_DEFAULT //------------------------------------------------------------------------------ public static int Startup() { int retValue = 0; try { theProgram = new Program(); //string partPath = @"F:\TEST.prt"; //string partPath = @"F:\CASE\ASM.prt"; string partPath = @"F:\CASE1\Case_1-1_stp.prt"; PartLoadStatus PLD; Part workPart = theSession.Parts.OpenBaseDisplay(partPath, out PLD) as Part; if (workPart != null) { ComponentAssembly assembly = workPart.ComponentAssembly; Component rootComponent = assembly.RootComponent; //try {object flange1 = assembly.FindObject("FLANGE(10K_150A_G)_K3029930#1");} //catch(Exception ex) { theUI.NXMessageBox.Show("Null", NXMessageBox.DialogType.Error, ex.Message); } theProgram.Traverse(rootComponent); Component comp1_1 = rootComponent.FindObject("COMPONENT OIL_PIPE_TYPE1_ASSY-01 2") as Component; Component comp1 = comp1_1.FindObject("COMPONENT FLANGE(10K_150A_G)_K3029930#1 1") as Component; Component comp2_1 = rootComponent.FindObject("COMPONENT OIL_PIPE_TYPE1_ASSY-01 3") as Component; Component comp2 = comp2_1.FindObject("COMPONENT FLANGE(10K_150A_N)_K3034074#1 1") as Component; Part one = comp1.Prototype as Part; Part two = comp2.Prototype as Part; DatumPlane oneXY = null; DatumPlane twoXY = null; //foreach(Component leaf in theProgram.leafList) //{ // if(leaf.DisplayName == "FLANGE(10K_150A_G)_K3029930#1") // { // //comp1 = leaf; // one = leaf.Prototype as Part; // } // if (leaf.DisplayName == "FLANGE(10K_150A_N)_K3034074#1") // { // //comp2 = leaf; // two = leaf.Prototype as Part; // } //} if (one != null && two != null) { theProgram.GetXYPlane(one, out oneXY); theProgram.GetXYPlane(two, out twoXY); oneXY = comp1.FindOccurrence(oneXY) as DatumPlane; twoXY = comp2.FindOccurrence(twoXY) as DatumPlane; } //Tag tag1 = theUfSession.Assem.AskPartOccurrence(oneXY.Tag); try { ComponentPositioner positioner1 = assembly.Positioner; positioner1.BeginAssemblyConstraints(); Constraint constraint1 = positioner1.CreateConstraint(true); ComponentConstraint componentConstraint1 = constraint1 as ComponentConstraint; componentConstraint1.ConstraintAlignment = Constraint.Alignment.ContraAlign; componentConstraint1.ConstraintType = Constraint.Type.Touch; ConstraintReference ref1 = componentConstraint1.CreateConstraintReference(comp1, oneXY, false, false, false); ConstraintReference ref2 = componentConstraint1.CreateConstraintReference(comp2, twoXY, false, false, false); //componentConstraint1.FlipAlignment(); //componentConstraint1.SetAlignmentHint(NXOpen.Positioning.Constraint.Alignment.ContraAlign); } catch (Exception E) { theUI.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, E.Message); } } PartSaveStatus ps; bool partSaved; theSession.Parts.SaveAll(out partSaved, out ps); theUfSession.Part.CloseAll(); } catch (NXOpen.NXException ex) { // ---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("UI Styler", NXMessageBox.DialogType.Error, ex.Message); } return(retValue); }