/// <summary> /// 尺寸标注双根直线元素间距 -详图线、模型线,要求:方向相同,起点共线方向与轴网方向垂直 /// </summary> public static Dimension DimensionBetweenCurveElements(this Document doc, CurveElement curveElement01, CurveElement curveElement02) { Dimension dimension = null; if (!(((curveElement01 is DetailLine) || (curveElement01 is ModelLine)) && ((curveElement02 is DetailLine) || (curveElement02 is ModelLine)))) { return(dimension); } ReferenceArray referenceArray = new ReferenceArray(); referenceArray.Append(curveElement01.GeometryCurve.Reference); referenceArray.Append(curveElement02.GeometryCurve.Reference); Curve curve01 = curveElement01.GeometryCurve; Curve curve02 = curveElement02.GeometryCurve; Line line = Line.CreateBound(curve01.GetEndPoint(1), curve02.GetEndPoint(1)); // 【】移动标注线的位置 //double distanceMove = 2000.0.MilliMeterToFeet(); //distanceMove = distanceMove.MilliMeterToFeet(); //line = line.CreateOffset(distanceMove, (curve01 as Line).Direction) as Line; using (Transaction trans = new Transaction(doc, "轴网端头尺寸标注")) { trans.Start(); dimension = doc.Create.NewDimension(doc.ActiveView, line, referenceArray); trans.Commit(); } return(dimension); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var app = uiapp.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; var acview = uidoc.ActiveView; var pipe = uidoc.Selection.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is Pipe)) .GetElement(doc) as Pipe; var location = pipe.Location as LocationCurve; var ref1 = location.Curve.GetEndPointReference(0); var ref2 = location.Curve.GetEndPointReference(1); var referencearray = new ReferenceArray(); referencearray.Append(ref1); referencearray.Append(ref2); var line = pipe.LocationLine(); doc.Invoke(m => { doc.Create.NewDimension(acview, line, referencearray); }, "dim"); return(Result.Succeeded); }
private Form CreateExtrusionForm(Autodesk.Revit.DB.Document massFamilyDocument) { Form extrusionForm = null; // Create one profile ReferenceArray ref_ar = new ReferenceArray(); XYZ ptA = new XYZ(10, 10, 0); XYZ ptB = new XYZ(90, 10, 0); ModelCurve modelcurve = MakeLine(massFamilyDocument, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new XYZ(90, 10, 0); ptB = new XYZ(10, 90, 0); modelcurve = MakeLine(massFamilyDocument, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new XYZ(10, 90, 0); ptB = new XYZ(10, 10, 0); modelcurve = MakeLine(massFamilyDocument, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); // The extrusion form direction XYZ direction = new XYZ(0, 0, 50); extrusionForm = massFamilyDocument.FamilyCreate.NewExtrusionForm(true, ref_ar, direction); int profileCount = extrusionForm.ProfileCount; return(extrusionForm); }
/// <summary> /// 尺寸标注双根直线元素间距--轴网,要求:轴网方向相同,起点共线方向与轴网方向垂直 /// </summary> public static Dimension DimensionBetweenGrids(this Document doc, Grid grid01, Grid grid02) { Dimension dimension = null; ReferenceArray referenceArray = new ReferenceArray(); Reference reference01 = new Reference(grid01); Reference reference02 = new Reference(grid02); referenceArray.Append(reference01); referenceArray.Append(reference02); Curve curve01 = grid01.Curve; Curve curve02 = grid02.Curve; Line line = Line.CreateBound(curve01.GetEndPoint(1), curve02.GetEndPoint(1)); // 【】移动标注线的位置 double distanceMove = 2000.0.MilliMeterToFeet(); line = line.CreateOffset(distanceMove, (curve01 as Line).Direction) as Line; using (Transaction trans = new Transaction(doc, "轴网端头尺寸标注")) { trans.Start(); dimension = doc.Create.NewDimension(doc.ActiveView, line, referenceArray); trans.Commit(); } return(dimension); }
//--建立尺寸 public void CreateNewDimensionAlongLine(Document doc, Solid solid, Transform instanceTransform) { try { foreach (Face f in solid.Faces) { bool result = f.ComputeNormal(new UV(0.5, 0.5)).IsAlmostEqualTo(XYZ.BasisZ.Negate()); if (result) //get bottom face { //Transform instanceTransform = Transform.Identity; foreach (EdgeArray edgeArr in f.EdgeLoops) { for (int i = 0; i < 2; i++) { Edge edge = edgeArr.get_Item(i); ReferenceArray refArray = new ReferenceArray(); refArray.Append(edge.GetEndPointReference(0)); refArray.Append(edge.GetEndPointReference(1)); XYZ offsetVec = instanceTransform.OfVector(edge.Evaluate(0.5)).Normalize(); // 取得邊的法向量(normal vector) XYZ p1 = instanceTransform.OfPoint(edge.Evaluate(0)) + (-250) * offsetVec; // 將點座標依照轉換為全域坐標系(Local transform to global transform) XYZ p2 = instanceTransform.OfPoint(edge.Evaluate(1)) + (-250) * offsetVec; // 將點座標依照轉換為全域坐標系(Local transform to global transform) Line line = Line.CreateBound(p1, p2); doc.Create.NewDimension(doc.ActiveView, line, refArray); } } } } } catch { MessageBox.Show("錯誤"); } }
/// <summary> /// Create a new dimension element using the given /// references and dimension line end points. /// This method opens and commits its own transaction, /// assuming that no transaction is open yet and manual /// transaction mode is being used. /// Note that this has only been tested so far using /// references to surfaces on planar walls in a plan /// view. /// </summary> public static void CreateDimensionElement( View view, XYZ p1, Reference r1, XYZ p2, Reference r2) { Document doc = view.Document; ReferenceArray ra = new ReferenceArray(); ra.Append(r1); ra.Append(r2); Line line = Line.CreateBound(p1, p2); using (Transaction t = new Transaction(doc)) { t.Start("Create New Dimension"); Dimension dim = doc.Create.NewDimension( view, line, ra); t.Commit(); } }
public Dimension CreateLinearDimension( Document doc) { Application app = doc.Application; // first create two lines XYZ pt1 = new XYZ(5, 5, 0); XYZ pt2 = new XYZ(5, 10, 0); Line line = Line.CreateBound(pt1, pt2); //Plane plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016 Plane plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); // 2017 //SketchPlane skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013 SketchPlane skplane = SketchPlane.Create(doc, plane); // 2014 ModelCurve modelcurve1 = doc.FamilyCreate .NewModelCurve(line, skplane); pt1 = new XYZ(10, 5, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateBound(pt1, pt2); //plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016 plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); // 2017 //skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013 skplane = SketchPlane.Create(doc, plane); // 2014 ModelCurve modelcurve2 = doc.FamilyCreate .NewModelCurve(line, skplane); // now create a linear dimension between them ReferenceArray ra = new ReferenceArray(); ra.Append(modelcurve1.GeometryCurve.Reference); ra.Append(modelcurve2.GeometryCurve.Reference); pt1 = new XYZ(5, 10, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateBound(pt1, pt2); Dimension dim = doc.FamilyCreate .NewLinearDimension(doc.ActiveView, line, ra); // create a label for the dimension called "width" FamilyParameter param = doc.FamilyManager .AddParameter("width", BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Length, false); //dim.Label = param; // 2013 dim.FamilyLabel = param; // 2014 return(dim); }
public Dimension CreateLinearDimension(Document doc) { Autodesk.Revit.ApplicationServices.Application app = doc.Application; XYZ pt1 = new XYZ(5, 5, 0); XYZ pt2 = new XYZ(5, 10, 0); Line line = Line.CreateUnbound(pt1, pt2); Plane plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); SketchPlane skPlane = SketchPlane.Create(doc, plane); ModelCurve modelCurveA = doc.FamilyCreate.NewModelCurve(line, skPlane); pt1 = new XYZ(10, 5, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateUnbound(pt1, pt2); plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); skPlane = SketchPlane.Create(doc, plane); ModelCurve modelCurveB = doc.FamilyCreate.NewModelCurve(line, skPlane); ReferenceArray refArr = new ReferenceArray(); refArr.Append(modelCurveA.GeometryCurve.Reference); refArr.Append(modelCurveB.GeometryCurve.Reference); pt1 = new XYZ(5, 10, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateUnbound(pt1, pt2); Dimension dim = doc.FamilyCreate.NewLinearDimension(doc.ActiveView, line, refArr); FamilyParameter param = doc.FamilyManager.AddParameter("width", BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Length, false); dim.FamilyLabel = param; return(dim); }
private static void AddReferencesToArray(ReferenceArray refArr, FSharpList <Value> lst) { dynRevitSettings.Doc.RefreshActiveView(); foreach (Value vInner in lst) { var mc = (vInner as Value.Container).Item as ModelCurve; var f = (vInner as Value.Container).Item as Face; var p = (vInner as Value.Container).Item as Point; var c = (vInner as Value.Container).Item as Curve; var rp = (vInner as Value.Container).Item as ReferencePlane; if (mc != null) { refArr.Append(mc.GeometryCurve.Reference); } else if (f != null) { refArr.Append(f.Reference); } else if (p != null) { refArr.Append(p.Reference); } else if (c != null) { refArr.Append(c.Reference); } else if (c != null) { refArr.Append(rp.Reference); } } }
public static void CreateDimensionElement( Document doc, Autodesk.Revit.ApplicationServices.Application app, Autodesk.Revit.DB.View view, XYZ p1, Reference r1, XYZ p2, Reference r2) { Autodesk.Revit.Creation.Application creApp = app.Create; Autodesk.Revit.Creation.Document creDoc = doc.Create; ReferenceArray refArr = new ReferenceArray(); refArr.Append(r1); refArr.Append(r2); Line line = Line.CreateBound(p1, p2); Transaction t = new Transaction(doc, "Dimension Two Walls"); t.Start(); Dimension dim = creDoc.NewDimension(doc.ActiveView, line, refArr); t.Commit(); }
/// <summary> /// Converts a ReferenceArray to array with a bunch of lines /// </summary> /// <param name="doc"></param> /// <param name="dimList"></param> /// <param name="gridList"></param> /// <param name="opt"></param> /// <returns></returns> private static ReferenceArray PopulateReferenceArray(Document doc, List <Dimenser> dimList, List <Grid> gridList, Options opt) { var tempArray = new ReferenceArray(); if (doc.ActiveView.ViewType == ViewType.Section) { dimList.OrderBy(wall => wall.Height).ToList(); } foreach (Dimenser dimenser in dimList) { tempArray.Append(dimenser.Face[0].Reference); tempArray.Append(dimenser.Face[1].Reference); } opt.IncludeNonVisibleObjects = true; opt.View = doc.ActiveView; foreach (Grid grid in gridList) { foreach (GeometryObject obj in grid.get_Geometry(opt)) { if (obj is Line line) { tempArray.Append(((Curve)line).Reference); } } } return(tempArray); }
/// <summary> /// 基于reference创建尺寸标注 /// </summary> /// <returns></returns> internal Dimension GetDimension(Face face01, Face face02, Document doc) { ReferenceArray referenceArray = new ReferenceArray(); referenceArray.Append((face01 as PlanarFace).Reference); referenceArray.Append((face02 as PlanarFace).Reference); Element element01 = doc.GetElement(face01.Reference.ElementId); Element element02 = doc.GetElement(face02.Reference.ElementId); XYZ locationPoint01 = (element01.Location as LocationPoint).Point; XYZ locationPoint02 = (element02.Location as LocationPoint).Point; Line dimensionLine = Line.CreateBound(locationPoint01, locationPoint02); Dimension dimension = null; using (Transaction trans = new Transaction(doc, "添加塔楼间距标注")) { trans.Start(); if (this.dimensionType == null) { dimension = doc.Create.NewDimension(doc.ActiveView, dimensionLine, referenceArray); } else { dimension = doc.Create.NewDimension(doc.ActiveView, dimensionLine, referenceArray, this.dimensionType); } trans.Commit(); } return(dimension); }
/// <summary> /// The method is used to create dimension between referenceplane and face /// </summary> /// <param name="view">the view in which the dimension is created</param> /// <param name="refPlane">the reference plane</param> /// <param name="face">the face</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, ReferencePlane refPlane, Face face) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; ReferenceArray refArray = new ReferenceArray(); ref1 = refPlane.Reference; PlanarFace pFace = face as PlanarFace; ref2 = pFace.Reference; if (null != ref1 && null != ref2) { refArray.Append(ref1); refArray.Append(ref2); } startPoint = refPlane.FreeEnd; endPoint = new Autodesk.Revit.DB.XYZ(startPoint.X, pFace.Origin.Y, startPoint.Z); SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); line = m_application.Create.NewLineBound(startPoint, endPoint); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
public static void DrawDimension(Document doc, ReferencePlane refP, FamilyInstance fi1, double offset) { IList <Reference> fir1 = fi1.GetReferences(FamilyInstanceReferenceType.WeakReference); XYZ refPlanePoint = refP.FreeEnd;//end point of reference plane LocationPoint lp = fi1.Location as LocationPoint; XYZ direction = refP.Normal;//perpendicular direction to reference plane Plane p = Plane.CreateByNormalAndOrigin(direction, refP.FreeEnd); XYZ startPoint = ProjectOnto(p, lp.Point) + offset * refP.Direction; double distance = 1; //direction = direction / direction.GetLength(); XYZ endPoint = startPoint + distance * direction; Line dimensionLine = Line.CreateBound(startPoint, endPoint); ReferenceArray references = new ReferenceArray(); references.Append(fir1.First()); references.Append(refP.GetReference()); // lockedAlign = doc.Create.NewAlignment(view, r1, r2) Dimension d = doc.Create.NewDimension(doc.ActiveView, dimensionLine, references); d.IsLocked = true; }
/// <summary> /// Create vertical dimensioning, cf. /// http://forums.autodesk.com/t5/revit-api-forum/how-can-i-create-dimension-line-that-is-not-parallel-to-detail/m-p/6801271 /// </summary> void CreateVerticalDimensioning(ViewSection viewSection) { Document doc = viewSection.Document; XYZ point3 = new XYZ(417.8, 80.228, 46.8); XYZ point4 = new XYZ(417.8, 80.811, 46.3); Line geomLine3 = Line.CreateBound(point3, point4); Line dummyLine = Line.CreateBound(XYZ.Zero, XYZ.BasisY); using (Transaction tx = new Transaction(doc)) { tx.Start("tx"); DetailLine line3 = doc.Create.NewDetailCurve( viewSection, geomLine3) as DetailLine; DetailLine dummy = doc.Create.NewDetailCurve( viewSection, dummyLine) as DetailLine; ReferenceArray refArray = new ReferenceArray(); refArray.Append(dummy.GeometryCurve.Reference); refArray.Append(line3.GeometryCurve.GetEndPointReference(0)); refArray.Append(line3.GeometryCurve.GetEndPointReference(1)); XYZ dimPoint1 = new XYZ(417.8, 80.118, 46.8); XYZ dimPoint2 = new XYZ(417.8, 80.118, 46.3); Line dimLine3 = Line.CreateBound(dimPoint1, dimPoint2); Dimension dim = doc.Create.NewDimension( viewSection, dimLine3, refArray); doc.Delete(dummy.Id); tx.Commit(); } }
/// <summary> /// This method is used to create dimension among three reference planes /// </summary> /// <param name="view">the view</param> /// <param name="refPlane1">the first reference plane</param> /// <param name="refPlane2">the second reference plane</param> /// <param name="refPlane">the middle reference plane</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, ReferencePlane refPlane1, ReferencePlane refPlane2, ReferencePlane refPlane) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; Reference ref3; ReferenceArray refArray = new ReferenceArray(); ref1 = refPlane1.Reference; ref2 = refPlane2.Reference; ref3 = refPlane.Reference; startPoint = refPlane1.FreeEnd; endPoint = refPlane2.FreeEnd; line = m_application.Create.NewLineBound(startPoint, endPoint); if (null != ref1 && null != ref2 && null != ref3) { refArray.Append(ref1); refArray.Append(ref3); refArray.Append(ref2); } SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
/// <summary> /// Удаление нулей из размерной цепочки. В случае, если нулей не найдено, возвращает False. Иначе - True и /// массив <see cref="Reference"/> для пересоздания размерной цепочки без нулей /// </summary> /// <param name="dimension">Проверяемая размерная цепочка</param> /// <param name="referenceArray">Массив <see cref="Reference"/> для пересоздания размерной цепочки</param> /// <returns>True - размерная цепочка имела нули и требуется пересоздать её. Иначе false</returns> public static bool TryRemoveZeroes(Dimension dimension, out ReferenceArray referenceArray) { referenceArray = new ReferenceArray(); if (dimension.Segments.IsEmpty) { return(false); } var doc = dimension.Document; var reCreate = false; for (var i = 0; i < dimension.NumberOfSegments; i++) { var segment = dimension.Segments.get_Item(i); var value = segment.Value; if (value.HasValue && Math.Abs(value.Value) < 0.0001) { reCreate = true; } else { if (i == 0) { referenceArray.Append(dimension.References.get_Item(i).FixReference(doc)); } referenceArray.Append(dimension.References.get_Item(i + 1).FixReference(doc)); } } return(reCreate); }
/// <summary> /// Create a new dimension element using the given /// references and dimension line end points. /// This method opens and commits its own transaction, /// assuming that no transaction is open yet and manual /// transaction mode is being used. /// Note that this has only been tested so far using /// references to surfaces on planar walls in a plan /// view. /// </summary> public static void CreateDimensionElement( View view, XYZ p1, Reference r1, XYZ p2, Reference r2) { Document doc = view.Document; ReferenceArray ra = new ReferenceArray(); ra.Append( r1 ); ra.Append( r2 ); Line line = Line.CreateBound( p1, p2 ); using( Transaction t = new Transaction( doc ) ) { t.Start( "Create New Dimension" ); Dimension dim = doc.Create.NewDimension( view, line, ra ); t.Commit(); } }
private Form CreateExtrusionForm(Document familyDoc) { try { ReferenceArray ra = new ReferenceArray(); ModelCurve mc; int i = 0; while (i < 3) { mc = MakeLine(familyDoc, _Vertices[i], _Vertices[i + 1]); ra.Append(mc.GeometryCurve.Reference); ++i; } mc = MakeLine(familyDoc, _Vertices[i], _Vertices[i - i]); ra.Append(mc.GeometryCurve.Reference); XYZ dir = new XYZ(0, 0, _Height); Form extrusion = familyDoc.FamilyCreate.NewExtrusionForm(true, ra, dir); AssignSubCategory(familyDoc, extrusion); return(extrusion); } catch (Exception ex) { TaskDialog.Show("Extrusion Error", ex.Message); return(null); } }
public Dimension AddDimension(Document doc, Autodesk.Revit.DB.View view, Face face1, Face face2) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; ReferenceArray refArray = new ReferenceArray(); PlanarFace pFace1 = face1 as PlanarFace; ref1 = pFace1.Reference; PlanarFace pFace2 = face2 as PlanarFace; ref2 = pFace2.Reference; if (null != ref1 && null != ref2) { refArray.Append(ref1); refArray.Append(ref2); } startPoint = pFace1.Origin; endPoint = new Autodesk.Revit.DB.XYZ(startPoint.X, startPoint.Y, pFace2.Origin.Z); SubTransaction subTransaction = new SubTransaction(doc); subTransaction.Start(); line = Line.CreateBound(startPoint, endPoint); dim = doc.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
public void createALinearDimensionFamilyEditor() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; using (Transaction trans = new Transaction(doc, "Create linear Dimension")) { trans.Start(); XYZ pt1 = new XYZ(5, 5, 0); XYZ pt2 = new XYZ(5, 10, 0); Line line = Line.CreateBound(pt1, pt2); Plane plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); SketchPlane skPlane = SketchPlane.Create(doc, plane); ModelCurve modelCurve1 = doc.FamilyCreate.NewModelCurve(line, skPlane); pt1 = new XYZ(10, 5, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateBound(pt1, pt2); plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); skPlane = SketchPlane.Create(doc, plane); ModelCurve modelCurve2 = doc.FamilyCreate.NewModelCurve(line, skPlane); // Create a linear dimension between them ReferenceArray ra = new ReferenceArray(); ra.Append(modelCurve1.GeometryCurve.Reference); ra.Append(modelCurve2.GeometryCurve.Reference); pt1 = new XYZ(5, 10, 0); pt2 = new XYZ(10, 10, 0); line = Line.CreateBound(pt1, pt2); Dimension dim = doc.FamilyCreate.NewLinearDimension(doc.ActiveView, line, ra); // Create a lable for the dimension called "width" FamilyParameter param = doc.FamilyManager.AddParameter("width", BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Length, false); dim.FamilyLabel = param; trans.Commit(); } }
/// <summary>Создание размеров для крайних осей</summary> /// <param name="doc">Document</param> /// <param name="chainDimensionLine">Chain dimension line</param> /// <param name="extremeWallVariant">Extreme wall variant</param> private Dimension CreateDimensionByExtremeGrids(Document doc, Line chainDimensionLine, ExtremeWallVariant extremeWallVariant) { if (!_advancedGrids.Any()) { return(null); } Dimension returnedDimension = null; var referenceArray = new ReferenceArray(); // Нужно получить референсы крайних осей в зависимости от направления if (extremeWallVariant == ExtremeWallVariant.Left || extremeWallVariant == ExtremeWallVariant.Right) { // Беру горизонтальные оси var verticalGrids = _advancedGrids.Where(g => g.Orientation == ElementOrientation.Horizontal).ToList(); if (verticalGrids.Any()) { // Сортирую по Y verticalGrids.Sort((g1, g2) => g1.StartPoint.Y.CompareTo(g2.StartPoint.Y)); var grids = new List <AdvancedGrid> { verticalGrids.First(), verticalGrids.Last() }; foreach (var grid in grids) { referenceArray.Append(grid.Reference); } } } else //// Иначе верх/низ { var horizontalGrids = _advancedGrids.Where(g => g.Orientation == ElementOrientation.Vertical).ToList(); if (horizontalGrids.Any()) { horizontalGrids.Sort((g1, g2) => g1.StartPoint.X.CompareTo(g2.StartPoint.X)); var grids = new List <AdvancedGrid> { horizontalGrids.First(), horizontalGrids.Last() }; foreach (var grid in grids) { referenceArray.Append(grid.Reference); } } } if (!referenceArray.IsEmpty && referenceArray.Size > 1) { using (var transaction = new Transaction(doc, _transactionName)) { transaction.Start(); returnedDimension = doc.Create.NewDimension(doc.ActiveView, chainDimensionLine, referenceArray); transaction.Commit(); } } return(returnedDimension); }
public XYZ GetReferenceDirection(Reference ref1, Document doc) // returns the direction perpendicular to reference // returns XYZ.Zero on error; { XYZ res = XYZ.Zero; XYZ workPlaneNormal = doc.ActiveView.SketchPlane.GetPlane().Normal; if (ref1.ElementId == ElementId.InvalidElementId) { return(res); } Element elem = doc.GetElement(ref1.ElementId); if (elem == null) { return(res); } if (ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE || ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_LINEAR) { // make a dimension to a point for direction XYZ bEnd = new XYZ(10, 10, 10); ReferenceArray refArr = new ReferenceArray(); refArr.Append(ref1); Dimension dim = null; using (Transaction t = new Transaction(doc, "test")) { FailureHandlingOptions failureHandlingOptions = t.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); failureHandlingOptions.SetClearAfterRollback(true); t.SetFailureHandlingOptions(failureHandlingOptions); t.Start(); using (SubTransaction st = new SubTransaction(doc)) { st.Start(); ReferencePlane refPlane = doc.Create.NewReferencePlane(XYZ.Zero, bEnd, bEnd.CrossProduct(XYZ.BasisZ).Normalize(), doc.ActiveView); ModelCurve mc = doc.Create.NewModelCurve(Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 10)), SketchPlane.Create(doc, refPlane.Id)); refArr.Append(mc.GeometryCurve.GetEndPointReference(0)); dim = doc.Create.NewDimension(doc.ActiveView, Line.CreateBound(XYZ.Zero, new XYZ(10, 0, 0)), refArr); ElementTransformUtils.MoveElement(doc, dim.Id, new XYZ(0, 0.1, 0)); st.Commit(); } if (dim != null) { Curve cv = dim.Curve; cv.MakeBound(0, 1); XYZ pt1 = cv.GetEndPoint(0); XYZ pt2 = cv.GetEndPoint(1); res = pt2.Subtract(pt1).Normalize(); } t.RollBack(); } } return(res); }
public void Dimelement(Document doc, DimensionType dimensionType, View view) { Dictionary <string, List <Grid> > dic = GridCollection(doc, view); foreach (var item in dic.Keys) { ReferenceArray referenceArray = new ReferenceArray(); ReferenceArray referenceArray2 = new ReferenceArray(); foreach (var item2 in dic[item]) { referenceArray.Append(GetGridReference(doc.ActiveView, item2)); } referenceArray2.Append(GetGridReference(doc.ActiveView, dic[item].First())); referenceArray2.Append(GetGridReference(doc.ActiveView, dic[item].Last())); var p1 = GetGridDirection(doc.ActiveView, dic[item].First()); var p2 = GetGridDirection(doc.ActiveView, dic[item].Last()); var r1 = p1.CrossProduct(doc.ActiveView.ViewDirection); var curve = dic[item].First().Curve; var curve2 = dic[item].Last().Curve; Line line1 = curve as Line; if (line1.Direction.Equalpoint(doc.ActiveView.RightDirection)) { XYZ point = Findpointdimension(curve.GetEndPoint(0), p1, 450, view); XYZ point2 = Findpointdimension(curve2.GetEndPoint(0), p2, 450, view); XYZ point3 = Findpointdimension(curve.GetEndPoint(0), p1, 200, view); XYZ point4 = Findpointdimension(curve2.GetEndPoint(0), p2, 200, view); Line line = Line.CreateBound(point, point2); Line line2 = Line.CreateBound(point3, point4); using (Transaction tran = new Transaction(doc, "Create dimesion")) { tran.Start(); doc.Create.NewDimension(doc.ActiveView, line, referenceArray, dimensionType); doc.Create.NewDimension(doc.ActiveView, line2, referenceArray2, dimensionType); tran.Commit(); } } if (line1.Direction.Equalpoint(doc.ActiveView.UpDirection)) { XYZ point = Findpointdimension(curve.GetEndPoint(0), p1, 450, view); XYZ point2 = Findpointdimension(curve2.GetEndPoint(0), p2, 450, view); XYZ point3 = Findpointdimension(curve.GetEndPoint(0), p1, 200, view); XYZ point4 = Findpointdimension(curve2.GetEndPoint(0), p2, 200, view); Line line = Line.CreateBound(point, point2); Line line2 = Line.CreateBound(point3, point4); using (Transaction tran = new Transaction(doc, "Create dimesion")) { tran.Start(); doc.Create.NewDimension(doc.ActiveView, line, referenceArray, dimensionType); doc.Create.NewDimension(doc.ActiveView, line2, referenceArray2, dimensionType); tran.Commit(); } } } }
/// <summary> /// Auto dimsection view /// /// </summary> public void autoDimSection() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; Reference selectedBeamRef = uiDoc.Selection.PickObject(ObjectType.Element, "pick a beam..."); FamilyInstance selectedBeam = doc.GetElement(selectedBeamRef) as FamilyInstance; if (selectedBeam == null) { return; } var beamFaces = getSolids(selectedBeam).SelectMany(x => x.Faces.OfType <PlanarFace>()).ToList(); View view = doc.ActiveView; PlanarFace leftFace = beamFaces.FirstOrDefault(x => x.ComputeNormal(UV.Zero). IsAlmostEqualTo(-1 * view.RightDirection)); PlanarFace rightFace = beamFaces.FirstOrDefault(x => x.ComputeNormal(UV.Zero). IsAlmostEqualTo(view.RightDirection)); if (leftFace == null || rightFace == null) { TaskDialog.Show("abc", "Can't create dimension"); return; } double shift = UnitUtils.ConvertToInternalUnits(500, DisplayUnitType.DUT_MILLIMETERS); XYZ dimensionOrigin = selectedBeam.GetTotalTransform().Origin + shift * view.UpDirection; Line dimensionLine = Line.CreateBound(dimensionOrigin, view.RightDirection); ReferenceArray dimensionReferences = new ReferenceArray(); dimensionReferences.Append(leftFace.Reference); dimensionReferences.Append(rightFace.Reference); using (Transaction trans = new Transaction(doc, "Create dimension...")) { trans.Start(); Dimension myDim = doc.Create.NewDimension(view, dimensionLine, dimensionReferences); trans.Commit(); } }
public Dimension CreateLinearDimension1(Document doc, XYZ pt1, XYZ pt2, SketchPlane sketch, Application app) { // first create line Line line = Line.CreateBound(pt1, pt2); ModelCurve modelcurve = doc.Create .NewModelCurve(line, sketch); ReferenceArray ra = new ReferenceArray(); ra.Append(modelcurve.GeometryCurve.GetEndPointReference(0)); ra.Append(modelcurve.GeometryCurve.GetEndPointReference(1)); return(doc.Create.NewDimension(doc.ActiveView, line, ra)); }
public void DimGrids(Document doc, View view, double kctoidaugrid, double kc2dim) { Dictionary <string, List <Grid> > dic = GridCollection(doc, view); foreach (var item in dic.Keys) { ReferenceArray referenceArray = new ReferenceArray(); ReferenceArray referenceArray2 = new ReferenceArray(); foreach (var item2 in dic[item]) { referenceArray.Append(GetGridReference(doc.ActiveView, item2)); } referenceArray2.Append(GetGridReference(doc.ActiveView, dic[item].First())); referenceArray2.Append(GetGridReference(doc.ActiveView, dic[item].Last())); var p1 = Directorline(dic[item].First()); var p2 = Directorline(dic[item].Last()); var curve = dic[item].First().Curve; var curve2 = dic[item].Last().Curve; XYZ starpoint1 = null; XYZ enpoint1 = null; XYZ startpoint2 = null; XYZ endpoint2 = null; Get2pointofgridingview(view, dic[item].First(), ref starpoint1, ref enpoint1); Get2pointofgridingview(view, dic[item].Last(), ref startpoint2, ref endpoint2); Line line1 = curve as Line; XYZ point = Findpointdimension(starpoint1, p1, UnitUtils.Convert(kctoidaugrid + kc2dim, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point2 = Findpointdimension(startpoint2, p2, UnitUtils.Convert(kctoidaugrid + kc2dim, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point3 = Findpointdimension(starpoint1, p1, UnitUtils.Convert(kctoidaugrid, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point4 = Findpointdimension(startpoint2, p2, UnitUtils.Convert(kctoidaugrid, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point5 = Findpointdimension(enpoint1, -p1, UnitUtils.Convert(kctoidaugrid + kc2dim, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point6 = Findpointdimension(endpoint2, -p2, UnitUtils.Convert(kctoidaugrid + kc2dim, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point7 = Findpointdimension(enpoint1, -p1, UnitUtils.Convert(kctoidaugrid, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); XYZ point8 = Findpointdimension(endpoint2, -p2, UnitUtils.Convert(kctoidaugrid, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET), view); Line line = Line.CreateBound(point, point2); Line line2 = Line.CreateBound(point3, point4); Line line3 = Line.CreateBound(point5, point6); Line line4 = Line.CreateBound(point7, point8); using (Transaction tran = new Transaction(doc, "Create dimesion")) { tran.Start(); //doc.Create.NewDimension(doc.ActiveView, line, referenceArray); //doc.Create.NewDimension(doc.ActiveView, line2, referenceArray2); doc.Create.NewDimension(doc.ActiveView, line3, referenceArray); doc.Create.NewDimension(doc.ActiveView, line4, referenceArray2); tran.Commit(); } } }
private static Form ByLoftCrossSectionsInternal(object[] curves, bool isSolid = true) { if (curves == null) { throw new ArgumentNullException("curves"); } // if the arguments are polycurves, explode them if (curves.Any(x => x is PolyCurve)) { var ca = curves.Select(x => x is PolyCurve ? ((PolyCurve)x).Curves() : new[] { x }).ToArray(); return(ByLoftMultiPartCrossSectionsInternal(ca, isSolid)); } var refArrArr = new ReferenceArrayArray(); foreach (var l in curves) { if (l == null) { throw new ArgumentNullException("curves"); } var refArr = new ReferenceArray(); refArr.Append(ElementCurveReference.TryGetCurveReference(l, "Form").InternalReference); refArrArr.Append(refArr); } return(new Form(isSolid, refArrArr)); }
/// <summary> /// Create a rectangle profile with provided length, width and height /// </summary> /// <param name="length">Length of the rectangle</param> /// <param name="width">Width of the rectangle</param> /// <param name="height">Height of the profile</param> /// <returns>The created profile</returns> private ReferenceArray CreateProfile(double length, double width, double height) { ReferenceArray profile = new ReferenceArray(); // Prepare points to create lines List <XYZ> points = new List <XYZ>(); points.Add(new Autodesk.Revit.DB.XYZ(-1 * length / 2, -1 * width / 2, height)); points.Add(new Autodesk.Revit.DB.XYZ(length / 2, -1 * width / 2, height)); points.Add(new Autodesk.Revit.DB.XYZ(length / 2, width / 2, height)); points.Add(new Autodesk.Revit.DB.XYZ(-1 * length / 2, width / 2, height)); // Prepare sketch plane to create model line Autodesk.Revit.DB.XYZ normal = new Autodesk.Revit.DB.XYZ(0, 0, 1); Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ(0, 0, height); Plane geometryPlane = m_revitApp.Create.NewPlane(normal, origin); SketchPlane sketchPlane = SketchPlane.Create(m_revitDoc, geometryPlane); // Create model lines and get their references as the profile for (int i = 0; i < 4; i++) { Autodesk.Revit.DB.XYZ startPoint = points[i]; Autodesk.Revit.DB.XYZ endPoint = (i == 3 ? points[0] : points[i + 1]); Line line = Line.CreateBound(startPoint, endPoint); ModelCurve modelLine = m_revitDoc.FamilyCreate.NewModelCurve(line, sketchPlane); profile.Append(modelLine.GeometryCurve.Reference); } return(profile); }
/// <summary> /// Create a hosted-sweep according to the CreationData parameter. /// </summary> /// <param name="creationData">CreationData parameter</param> /// <returns>ModificationData which contains the created hosted-sweep</returns> public ModificationData Create(CreationData creationData) { ReferenceArray refArr = new ReferenceArray(); foreach (Edge edge in creationData.EdgesForHostedSweep) { refArr.Append(edge.Reference); } ModificationData modificationData = null; Transaction transaction = new Transaction(m_rvtDoc, "CreateHostedSweep"); try { transaction.Start(); HostedSweep createdHostedSweep = CreateHostedSweep(creationData.Symbol, refArr); if (transaction.Commit() == TransactionStatus.Committed) { m_rvtUIDoc.ShowElements(createdHostedSweep); // just only end transaction return true, we will create the hosted sweep. modificationData = new ModificationData(createdHostedSweep, creationData); m_createdHostedSweeps.Add(modificationData); } } catch { transaction.RollBack(); } return(modificationData); }
private Value GetCurvesFromFamily(Autodesk.Revit.DB.FamilyInstance fi, int count, Autodesk.Revit.DB.Options options) { FamilySymbol fs = fi.Symbol; //Autodesk.Revit.DB.GeometryElement geomElem = fs.get_Geometry(options); Autodesk.Revit.DB.GeometryElement geomElem = fi.get_Geometry(options); // our particular case of a loaded mass family with no joins has no geom in the instance //fi.GetOriginalGeometry(options); //fi.GetTransform() Autodesk.Revit.DB.CurveArray curves = new CurveArray(); Autodesk.Revit.DB.ReferenceArray curveRefs = new ReferenceArray(); //Find all curves and insert them into curve array AddCurves(fi, geomElem, count, ref curves); //curves.Append(GetCurve(fi, options)); //test //extract references for downstream use foreach (Curve c in curves) { curveRefs.Append(c.Reference); } //convert curvearray into list using Stephens MakeEnumerable Value result = Value.NewList(Utils.SequenceToFSharpList( dynUtils.MakeEnumerable(curves).Select(Value.NewContainer) )); return(result); }
public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Application revit = commandData.Application; Document curDoc = revit.ActiveDocument; SelElementSet selSet = curDoc.Selection.Elements; if (selSet.Size != 1) { message = "Please select a wall!"; return IExternalCommand.Result.Cancelled; } Wall wall = null; ElementSetIterator it = selSet.ForwardIterator(); if (it.MoveNext()) { wall = it.Current as Wall; } if (wall == null) { message = "Please select a wall!"; return IExternalCommand.Result.Cancelled; } LocationCurve cur = wall.Location as LocationCurve; if (cur == null) return IExternalCommand.Result.Failed; Line line = cur.Curve as Line; Options options = revit.Create.NewGeometryOptions(); options.ComputeReferences = true; options.View = curDoc.ActiveView; Autodesk.Revit.Geometry.Element element = wall.get_Geometry(options); ReferenceArray referenceArray = new ReferenceArray(); GeometryObjectArray geoObjectArray = element.Objects; //enum the geometry element for (int j = 0; j < geoObjectArray.Size; j++) { GeometryObject geoObject = geoObjectArray.get_Item(j); Line l0 = geoObject as Line; if (null != l0) { //检查该线是否与线line正交 double d = (l0.get_EndPoint(1).X - l0.get_EndPoint(0).X) * (line.get_EndPoint(1).X - line.get_EndPoint(0).X); d += (l0.get_EndPoint(1).Y - l0.get_EndPoint(0).Y) * (line.get_EndPoint(1).Y - line.get_EndPoint(0).Y); d += (l0.get_EndPoint(1).Z - l0.get_EndPoint(0).Z) * (line.get_EndPoint(1).Z - line.get_EndPoint(0).Z); if (d < 0.0000001 && d > -0.0000001) referenceArray.Append(l0.Reference); if (2 == referenceArray.Size) { break; } } } Dimension createdDimension = curDoc.Create.NewDimension(curDoc.ActiveView, line, referenceArray); if (null == createdDimension) { message = "Create the Dimension failed."; return IExternalCommand.Result.Failed; } return IExternalCommand.Result.Succeeded; }
public static Form ByLoftingCurveReferences(object[] curveReferences, bool isSolid = true) { var refArrArr = new ReferenceArrayArray(); foreach (var l in curveReferences) { if (l == null) throw new ArgumentNullException("curveReferences"); var refArr = new ReferenceArray(); refArr.Append(ElementCurveReference.TryGetCurveReference(l, "Form").InternalReference); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
public Dimension CreateLinearDimension( Document doc) { Application app = doc.Application; // first create two lines XYZ pt1 = new XYZ( 5, 5, 0 ); XYZ pt2 = new XYZ( 5, 10, 0 ); Line line = Line.CreateBound( pt1, pt2 ); //Plane plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016 Plane plane = Plane.CreateByNormalAndOrigin( pt1.CrossProduct( pt2 ), pt2 ); // 2017 //SketchPlane skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013 SketchPlane skplane = SketchPlane.Create( doc, plane ); // 2014 ModelCurve modelcurve1 = doc.FamilyCreate .NewModelCurve( line, skplane ); pt1 = new XYZ( 10, 5, 0 ); pt2 = new XYZ( 10, 10, 0 ); line = Line.CreateBound( pt1, pt2 ); //plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016 plane = Plane.CreateByNormalAndOrigin( pt1.CrossProduct( pt2 ), pt2 ); // 2017 //skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013 skplane = SketchPlane.Create( doc, plane ); // 2014 ModelCurve modelcurve2 = doc.FamilyCreate .NewModelCurve( line, skplane ); // now create a linear dimension between them ReferenceArray ra = new ReferenceArray(); ra.Append( modelcurve1.GeometryCurve.Reference ); ra.Append( modelcurve2.GeometryCurve.Reference ); pt1 = new XYZ( 5, 10, 0 ); pt2 = new XYZ( 10, 10, 0 ); line = Line.CreateBound( pt1, pt2 ); Dimension dim = doc.FamilyCreate .NewLinearDimension( doc.ActiveView, line, ra ); // create a label for the dimension called "width" FamilyParameter param = doc.FamilyManager .AddParameter( "width", BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Length, false ); //dim.Label = param; // 2013 dim.FamilyLabel = param; // 2014 return dim; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Application app = commandData.Application.Application; string filename = Path.Combine( _folder, _template ); Document familyDoc = app.NewFamilyDocument( filename ); Family family = familyDoc.OwnerFamily; Autodesk.Revit.Creation.FamilyItemFactory factory = familyDoc.FamilyCreate; Extrusion extrusion = null; using( Transaction trans = new Transaction( familyDoc ) ) { trans.Start( "Create Extrusion" ); XYZ arcCenter = new XYZ( 0.0, 3.0, -2.0 ); // Get the "left" view View view = GetView( ViewType.Elevation, XYZ.BasisY.Negate(), XYZ.BasisZ, familyDoc ); // 2D offsets from view 'left' XYZ xOffset = new XYZ( 0.0, 10.0, 0.0 ); XYZ yOffset = new XYZ( 0.0, 0.0, -10.0 ); //################## Reference planes ################################ // Origin's reference planes ReferencePlane referencePlaneOriginX = factory.NewReferencePlane( XYZ.BasisX, XYZ.Zero, XYZ.BasisY, view ); referencePlaneOriginX.Name = "ReferencePlane_OriginX"; referencePlaneOriginX.Pinned = true; ReferencePlane referencePlaneOriginY = factory.NewReferencePlane( XYZ.BasisZ, XYZ.Zero, -XYZ.BasisX, view ); referencePlaneOriginY.Name = "ReferencePlane_OriginY"; referencePlaneOriginY.Pinned = true; // Reference planes the extruded arc should stick to ReferencePlane referencePlaneX = factory.NewReferencePlane( XYZ.BasisX + yOffset, XYZ.Zero + yOffset, XYZ.BasisY, view ); referencePlaneX.Name = "ReferencePlane_X"; ReferencePlane referencePlaneY = factory.NewReferencePlane( XYZ.BasisZ + xOffset, XYZ.Zero + xOffset, -XYZ.BasisX, view ); referencePlaneY.Name = "ReferencePlane_Y"; familyDoc.Regenerate(); //################## Create dimensions ############################### // Dimension x ReferenceArray refArrayX = new ReferenceArray(); refArrayX.Append( referencePlaneX.GetReference() ); refArrayX.Append( referencePlaneOriginX.GetReference() ); Line lineX = Line.CreateUnbound( arcCenter, XYZ.BasisZ ); Dimension dimensionX = factory.NewDimension( view, lineX, refArrayX ); // Dimension y ReferenceArray refArrayY = new ReferenceArray(); refArrayY.Append( referencePlaneY.GetReference() ); refArrayY.Append( referencePlaneOriginY.GetReference() ); Line lineY = Line.CreateUnbound( arcCenter, XYZ.BasisY ); Dimension dimensionY = factory.NewDimension( view, lineY, refArrayY ); familyDoc.Regenerate(); //################## Create arc ###################################### double arcRadius = 1.0; Arc arc = Arc.Create( XYZ.Zero + xOffset + yOffset, arcRadius, 0.0, 2 * Math.PI, XYZ.BasisZ, XYZ.BasisY.Negate() ); CurveArray curves = new CurveArray(); curves.Append( arc ); CurveArrArray profile = new CurveArrArray(); profile.Append( curves ); Plane plane = new Plane( XYZ.BasisX.Negate(), arcCenter ); SketchPlane sketchPlane = SketchPlane.Create( familyDoc, plane ); Debug.WriteLine( "Origin: " + sketchPlane.GetPlane().Origin ); Debug.WriteLine( "Normal: " + sketchPlane.GetPlane().Normal ); Debug.WriteLine( "XVec: " + sketchPlane.GetPlane().XVec ); Debug.WriteLine( "YVec: " + sketchPlane.GetPlane().YVec ); extrusion = factory.NewExtrusion( true, profile, sketchPlane, 10 ); familyDoc.Regenerate(); //################## Add family parameters ########################### FamilyManager fmgr = familyDoc.FamilyManager; FamilyParameter paramX = fmgr.AddParameter( "X", BuiltInParameterGroup.PG_GEOMETRY, ParameterType.Length, true ); dimensionX.FamilyLabel = paramX; FamilyParameter paramY = fmgr.AddParameter( "Y", BuiltInParameterGroup.PG_GEOMETRY, ParameterType.Length, true ); dimensionY.FamilyLabel = paramY; // Set their values FamilyType familyType = fmgr.NewType( "Standard" ); fmgr.Set( paramX, 10 ); fmgr.Set( paramY, 10 ); trans.Commit(); } // Save it to inspect SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; filename = Path.Combine( Path.GetTempPath(), "test.rfa" ); familyDoc.SaveAs( filename, opt ); return Result.Succeeded; }
/// <summary> /// Creates 2 hardwired lines and a dimension to measure /// the distance between them /// </summary> public void DimensionHardWired() { XYZ location1 = GeomUtils.kOrigin; XYZ location2 = new XYZ( 20.0, 0.0, 0.0 ); XYZ location3 = new XYZ( 0.0, 20.0, 0.0 ); XYZ location4 = new XYZ( 20.0, 20.0, 0.0 ); Curve curve1 = Line.CreateBound( location1, location2 ); Curve curve2 = Line.CreateBound( location3, location4 ); DetailCurve dCurve1 = null; DetailCurve dCurve2 = null; using( Transaction trans = new Transaction( m_revitApp.ActiveUIDocument.Document, "DimensionHardWired" ) ) { trans.Start(); if( !m_revitApp.ActiveUIDocument.Document.IsFamilyDocument ) { dCurve1 = m_revitApp.ActiveUIDocument.Document.Create.NewDetailCurve( m_revitApp.ActiveUIDocument.Document.ActiveView, curve1 ); dCurve2 = m_revitApp.ActiveUIDocument.Document.Create.NewDetailCurve( m_revitApp.ActiveUIDocument.Document.ActiveView, curve2 ); } else { if( null != m_revitApp.ActiveUIDocument.Document.OwnerFamily && null != m_revitApp.ActiveUIDocument.Document.OwnerFamily.FamilyCategory ) { if( !m_revitApp.ActiveUIDocument.Document.OwnerFamily.FamilyCategory.Name.Contains( "Detail" ) ) { MessageBox.Show( "Please make sure you open a detail based family template.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } } dCurve1 = m_revitApp.ActiveUIDocument.Document.FamilyCreate.NewDetailCurve( m_revitApp.ActiveUIDocument.Document.ActiveView, curve1 ); dCurve2 = m_revitApp.ActiveUIDocument.Document.FamilyCreate.NewDetailCurve( m_revitApp.ActiveUIDocument.Document.ActiveView, curve2 ); } Line line = Line.CreateBound( location2, location4 ); ReferenceArray refArray = new ReferenceArray(); /// TBD: all curves return a null Reference, what am I missing? /// 01/12/07 refArray.Append( dCurve1.GeometryCurve.Reference ); refArray.Append( dCurve2.GeometryCurve.Reference ); if( !m_revitApp.ActiveUIDocument.Document.IsFamilyDocument ) { m_revitApp.ActiveUIDocument.Document.Create.NewDimension( m_revitApp.ActiveUIDocument.Document.ActiveView, line, refArray ); } else { m_revitApp.ActiveUIDocument.Document.FamilyCreate.NewDimension( m_revitApp.ActiveUIDocument.Document.ActiveView, line, refArray ); } trans.Commit(); } }
public static Form ByLoftingCurveReferences(object[][] curveReferences, bool isSolid = true) { var refArrArr = new ReferenceArrayArray(); foreach (var curveArr in curveReferences) { var refArr = new ReferenceArray(); curveArr.ForEach(x => refArr.Append(ElementCurveReference.TryGetCurveReference(x, "Form").InternalReference)); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
public static Form ByLoftingCurveElements( CurveElement[] curves, bool isSolid) { var refArrArr = new ReferenceArrayArray(); foreach (var l in curves) { var refArr = new ReferenceArray(); refArr.Append(l.InternalCurveElement.GeometryCurve.Reference); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
private static Form ByLoftMultiPartCrossSectionsInternal(object[][] curves, bool isSolid = true) { if (curves == null || curves.SelectMany(x => x).Any(x => x == null)) { throw new ArgumentNullException("Some of the input curves are null."); } var refArrArr = new ReferenceArrayArray(); foreach (var curveArr in curves) { var refArr = new ReferenceArray(); curveArr.ForEach(x => refArr.Append(ElementCurveReference.TryGetCurveReference(x, "Form").InternalReference)); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
private static Form ByLoftCrossSectionsInternal(object[] curves, bool isSolid = true) { if (curves == null) throw new ArgumentNullException("curves"); // if the arguments are polycurves, explode them if (curves.Any(x => x is PolyCurve)) { var ca = curves.Select(x => x is PolyCurve ? ((PolyCurve)x).Curves() : new[] { x }).ToArray(); return ByLoftMultiPartCrossSectionsInternal(ca, isSolid); } var refArrArr = new ReferenceArrayArray(); foreach (var l in curves) { if (l == null) throw new ArgumentNullException("curves"); var refArr = new ReferenceArray(); refArr.Append(ElementCurveReference.TryGetCurveReference(l, "Form").InternalReference); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; // Select two walls and the dimension line point: Selection sel = uidoc.Selection; ReferenceArray refs = new ReferenceArray(); try { ISelectionFilter f = new JtElementsOfClassSelectionFilter<Wall>(); refs.Append( sel.PickObject( ObjectType.Element, f, "Please select first wall" ) ); refs.Append( sel.PickObject( ObjectType.Element, f, "Please pick dimension line " + "point on second wall" ) ); //rFace = sel.PickObject( ObjectType.Face, // "Please select face on second wall at dimension line point" ); // //rPoint = sel.PickObject( ObjectType.PointOnElement, // "Please select point on first wall" ); } catch( Autodesk.Revit.Exceptions.OperationCanceledException ) { message = "No two walls selected"; return Result.Failed; } // Ensure the two selected walls are straight and // parallel; determine their mutual normal vector // and a point on each wall for distance // calculations: Wall[] walls = new Wall[2]; List<int> ids = new List<int>( 2 ); XYZ[] pts = new XYZ[2]; Line[] lines = new Line[2]; IntersectionResult ir; XYZ normal = null; int i = 0; foreach( Reference r in refs ) { // 'Autodesk.Revit.DB.Reference.Element' is // obsolete: Property will be removed. Use // Document.GetElement(Reference) instead. //Wall wall = r.Element as Wall; // 2011 Wall wall = doc.GetElement( r ) as Wall; // 2012 walls[i] = wall; ids.Add( wall.Id.IntegerValue ); // Obtain location curve and // check that it is straight: LocationCurve lc = wall.Location as LocationCurve; Curve curve = lc.Curve; lines[i] = curve as Line; if( null == lines[i] ) { message = _prompt; return Result.Failed; } // Obtain normal vectors // and ensure that they are equal, // i.e. walls are parallel: if( null == normal ) { normal = Util.Normal( lines[i] ); } else { if( !Util.IsParallel( normal, Util.Normal( lines[i] ) ) ) { message = _prompt; return Result.Failed; } } // Obtain pick points and project // onto wall location lines: XYZ p = r.GlobalPoint; ir = lines[i].Project( p ); if( null == ir ) { message = string.Format( "Unable to project pick point {0} " + "onto wall location line.", i ); return Result.Failed; } pts[i] = ir.XYZPoint; Debug.Print( "Wall {0} id {1} at {2}, {3} --> point {4}", i, wall.Id.IntegerValue, Util.PointString( lines[i].GetEndPoint( 0 ) ), Util.PointString( lines[i].GetEndPoint( 1 ) ), Util.PointString( pts[i] ) ); if( 0 < i ) { // Project dimension point selected on second wall // back onto first wall, and ensure that normal // points from second wall to first: ir = lines[0].Project( pts[1] ); if( null == ir ) { message = string.Format( "Unable to project selected dimension " + "line point {0} on second wall onto " + "first wall's location line.", Util.PointString( pts[1] ) ); return Result.Failed; } pts[0] = ir.XYZPoint; } ++i; } XYZ v = pts[0] - pts[1]; if( 0 > v.DotProduct( normal ) ) { normal = -normal; } // Shoot a ray back from the second // picked wall towards first: Debug.Print( "Shooting ray from {0} in direction {1}", Util.PointString( pts[1] ), Util.PointString( normal ) ); View3D view = Get3DView( doc ); if( null == view ) { message = "No 3D view named '{3D}' found; " + "run the View > 3D View command once " + "to generate it."; return Result.Failed; } //refs = doc.FindReferencesByDirection( // pts[1], normal, view ); // 2011 //IList<ReferenceWithContext> refs2 // = doc.FindReferencesWithContextByDirection( // pts[1], normal, view ); // 2012 // In the Revit 2014 API, the call to // FindReferencesWithContextByDirection causes a // warning saying: // "FindReferencesWithContextByDirection is obsolete: // This method is deprecated in Revit 2014. // Use the ReferenceIntersector class instead." ReferenceIntersector ri = new ReferenceIntersector( walls[0].Id, FindReferenceTarget.Element, view ); ReferenceWithContext ref2 = ri.FindNearest( pts[1], normal ); if( null == ref2 ) { message = "ReferenceIntersector.FindNearest" + " returned null!"; return Result.Failed; } #region Obsolete code to determine the closest reference #if NEED_TO_DETERMINE_CLOSEST_REFERENCE // Store the references to the wall surfaces: Reference[] surfrefs = new Reference[2] { null, null }; // Find the two closest intersection // points on each of the two walls: double[] minDistance = new double[2] { double.MaxValue, double.MaxValue }; //foreach( Reference r in refs ) foreach( ReferenceWithContext rc in refs2 ) { // 'Autodesk.Revit.DB.Reference.Element' is // obsolete: Property will be removed. Use // Document.GetElement(Reference) instead. //Element e = r.Element; // 2011 Reference r = rc.GetReference(); Element e = doc.GetElement( r ); // 2012 if( e is Wall ) { i = ids.IndexOf( e.Id.IntegerValue ); if( -1 < i && ElementReferenceType.REFERENCE_TYPE_SURFACE == r.ElementReferenceType ) { //GeometryObject g = r.GeometryObject; // 2011 GeometryObject g = e.GetGeometryObjectFromReference( r ); // 2012 if( g is PlanarFace ) { PlanarFace face = g as PlanarFace; Line line = ( e.Location as LocationCurve ) .Curve as Line; Debug.Print( "Wall {0} at {1}, {2} surface {3} " + "normal {4} proximity {5}", e.Id.IntegerValue, Util.PointString( line.GetEndPoint( 0 ) ), Util.PointString( line.GetEndPoint( 1 ) ), Util.PointString( face.Origin ), Util.PointString( face.Normal ), rc.Proximity ); // First reference: assert it is a face on this wall // and the distance is half the wall thickness. // Second reference: the first reference on the other // wall; assert the distance between the two references // equals the distance between the wall location lines // minus half of the sum of the two wall thicknesses. if( rc.Proximity < minDistance[i] ) { surfrefs[i] = r; minDistance[i] = rc.Proximity; } } } } } if( null == surfrefs[0] ) { message = "No suitable face intersection " + "points found on first wall."; return Result.Failed; } if( null == surfrefs[1] ) { message = "No suitable face intersection " + "points found on second wall."; return Result.Failed; } CmdDimensionWallsIterateFaces .CreateDimensionElement( doc.ActiveView, pts[0], surfrefs[0], pts[1], surfrefs[1] ); #endif // NEED_TO_DETERMINE_CLOSEST_REFERENCE #endregion // Obsolete code to determine the closest reference CmdDimensionWallsIterateFaces .CreateDimensionElement( doc.ActiveView, pts[0], ref2.GetReference(), pts[1], refs.get_Item( 1 ) ); return Result.Succeeded; }
ArrayList m_walls = new ArrayList(); //store the wall of selected #endregion Fields #region Methods /// <summary> /// find out every wall in the selection and add a dimension from the start of the wall to its end /// </summary> /// <returns>if add successfully, true will be retured, else false will be returned</returns> public bool AddDimension() { if (!initialize()) { return false; } Transaction transaction = new Transaction(m_revit.Application.ActiveUIDocument.Document, "Add Dimensions"); transaction.Start(); //get out all the walls in this array, and create a dimension from its start to its end for (int i = 0; i < m_walls.Count; i++) { Wall wallTemp = m_walls[i] as Wall; if (null == wallTemp) { continue; } //get location curve Location location = wallTemp.Location; LocationCurve locationline = location as LocationCurve; if (null == locationline) { continue; } //New Line Autodesk.Revit.DB.XYZ locationEndPoint = locationline.Curve.get_EndPoint(1); Autodesk.Revit.DB.XYZ locationStartPoint = locationline.Curve.get_EndPoint(0); Line newLine = m_revit.Application.Application.Create.NewLine(locationStartPoint, locationEndPoint, true); //get reference ReferenceArray referenceArray = new ReferenceArray(); Options options = m_revit.Application.Application.Create.NewGeometryOptions(); options.ComputeReferences = true; options.View = m_revit.Application.ActiveUIDocument.Document.ActiveView; Autodesk.Revit.DB.GeometryElement element = wallTemp.get_Geometry(options); GeometryObjectArray geoObjectArray = element.Objects; //enum the geometry element for (int j = 0; j < geoObjectArray.Size; j++) { GeometryObject geoObject = geoObjectArray.get_Item(j); Curve curve = geoObject as Curve; if (null != curve) { //find the two upright lines beside the line if (Validata(newLine, curve as Line)) { referenceArray.Append(curve.Reference); } if (2 == referenceArray.Size) { break; } } } try { //try to new a dimension Autodesk.Revit.UI.UIApplication app = m_revit.Application; Document doc = app.ActiveUIDocument.Document; Autodesk.Revit.DB.XYZ p1 = new XYZ( newLine.get_EndPoint(0).X + 5, newLine.get_EndPoint(0).Y + 5, newLine.get_EndPoint(0).Z); Autodesk.Revit.DB.XYZ p2 = new XYZ( newLine.get_EndPoint(1).X + 5, newLine.get_EndPoint(1).Y + 5, newLine.get_EndPoint(1).Z); Line newLine2 = app.Application.Create.NewLine(p1, p2, true); Dimension newDimension = doc.Create.NewDimension( doc.ActiveView, newLine2, referenceArray); } // catch the exceptions catch (Exception ex) { m_errorMessage += ex.ToString(); return false; } } m_revit.Application.ActiveUIDocument.Document.Regenerate(); transaction.Commit(); return true; }
private Value GetCurvesFromFamily(Autodesk.Revit.DB.FamilyInstance fi, int count, Autodesk.Revit.DB.Options options) { FamilySymbol fs = fi.Symbol; //Autodesk.Revit.DB.GeometryElement geomElem = fs.get_Geometry(options); Autodesk.Revit.DB.GeometryElement geomElem = fi.get_Geometry(options); // our particular case of a loaded mass family with no joins has no geom in the instance //fi.GetOriginalGeometry(options); //fi.GetTransform() Autodesk.Revit.DB.CurveArray curves = new CurveArray(); Autodesk.Revit.DB.ReferenceArray curveRefs = new ReferenceArray(); //Find all curves and insert them into curve array AddCurves(fi, geomElem, count, ref curves); //curves.Append(GetCurve(fi, options)); //test //extract references for downstream use foreach (Curve c in curves) { curveRefs.Append(c.Reference); } //convert curvearray into list using Stephens MakeEnumerable Value result = Value.NewList(Utils.SequenceToFSharpList( dynUtils.MakeEnumerable(curves).Select(Value.NewContainer) )); return result; }
private static void AddReferencesToArray(ReferenceArray refArr, FSharpList<Value> lst) { dynRevitSettings.Doc.RefreshActiveView(); foreach (Value vInner in lst) { var mc = (vInner as Value.Container).Item as ModelCurve; var f = (vInner as Value.Container).Item as Face; var p = (vInner as Value.Container).Item as Point; var c = (vInner as Value.Container).Item as Curve; var rp = (vInner as Value.Container).Item as ReferencePlane; if (mc != null) refArr.Append(mc.GeometryCurve.Reference); else if (f != null) refArr.Append(f.Reference); else if (p != null) refArr.Append(p.Reference); else if (c != null) refArr.Append(c.Reference); else if (c != null) refArr.Append(rp.Reference); } }
/// <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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "MakeRevolveForm"); transaction.Start(); // Create one profile ReferenceArray ref_ar = new ReferenceArray(); Autodesk.Revit.DB.XYZ norm = Autodesk.Revit.DB.XYZ.BasisZ; Autodesk.Revit.DB.XYZ ptA = new Autodesk.Revit.DB.XYZ (0, 0, 10); Autodesk.Revit.DB.XYZ ptB = new Autodesk.Revit.DB.XYZ(100, 0, 10); ModelCurve modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB, norm); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (100, 0, 10); ptB = new Autodesk.Revit.DB.XYZ (100, 100, 10); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB, norm); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (100, 100, 10); ptB = new Autodesk.Revit.DB.XYZ (0, 0, 10); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB, norm); ref_ar.Append(modelcurve.GeometryCurve.Reference); // Create axis for revolve form ptA = new Autodesk.Revit.DB.XYZ (-5, 0, 10); ptB = new Autodesk.Revit.DB.XYZ (-5, 10, 10); ModelCurve axis = FormUtils.MakeLine(commandData.Application, ptA, ptB, norm); axis.ChangeToReferenceLine(); Autodesk.Revit.DB.FormArray form = doc.FamilyCreate.NewRevolveForms(true, ref_ar, axis.GeometryCurve.Reference, 0, Math.PI / 4); transaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
/// <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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "MakeExtrusionForm"); transaction.Start(); // Create one profile ReferenceArray ref_ar = new ReferenceArray(); Autodesk.Revit.DB.XYZ ptA = new Autodesk.Revit.DB.XYZ (10, 10, 0); Autodesk.Revit.DB.XYZ ptB = new Autodesk.Revit.DB.XYZ (90, 10, 0); ModelCurve modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (90, 10, 0); ptB = new Autodesk.Revit.DB.XYZ (10, 90, 0); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (10, 90, 0); ptB = new Autodesk.Revit.DB.XYZ (10, 10, 0); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); // The extrusion form direction Autodesk.Revit.DB.XYZ direction = new Autodesk.Revit.DB.XYZ (0, 0, 50); Autodesk.Revit.DB.Form form = doc.FamilyCreate.NewExtrusionForm(true, ref_ar, direction); transaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
public override FScheme.Value Evaluate(FSharpList<FScheme.Value> args) { //Solid argument bool isSolid = ((FScheme.Value.Number)args[0]).Item == 1; //Surface argument bool isSurface = ((FScheme.Value.Number)args[2]).Item == 1; //Build up our list of list of references for the form by... var curvesListList = (FScheme.Value.List)args[1]; //Now we add all of those references into ReferenceArrays ReferenceArrayArray refArrArr = new ReferenceArrayArray(); FSharpList<FScheme.Value> vals = ((FScheme.Value.List)curvesListList).Item; if (vals.Any() && (vals[0] is FScheme.Value.Container) && ((FScheme.Value.Container)vals[0]).Item is ModelCurveArray) { //Build a sequence that unwraps the input list from it's Value form. IEnumerable<ModelCurveArray> modelCurveArrays = ((FScheme.Value.List)args[1]).Item.Select( x => (ModelCurveArray)((FScheme.Value.Container)x).Item ); foreach (var modelCurveArray in modelCurveArrays) { var refArr = new ReferenceArray(); foreach (Autodesk.Revit.DB.ModelCurve modelCurve in modelCurveArray) { refArr.Append(modelCurve.GeometryCurve.Reference); } refArrArr.Append(refArr); } } else { IEnumerable<IEnumerable<Reference>> refArrays = (curvesListList).Item.Select( //...first selecting everything in the topmost list... delegate(FScheme.Value x) { //If the element in the topmost list is a sub-list... if (x.IsList) { //...then we return a new IEnumerable of References by converting the sub list. return (x as FScheme.Value.List).Item.Select( delegate(FScheme.Value y) { //Since we're in a sub-list, we can assume it's a container. var item = ((FScheme.Value.Container)y).Item; if (item is CurveElement) return (item as CurveElement).GeometryCurve.Reference; else return (Reference)item; } ); } //If the element is not a sub-list, then just assume it's a container. else { var obj = ((FScheme.Value.Container)x).Item; Reference r; if (obj is CurveElement) { r = (obj as CurveElement).GeometryCurve.Reference; } else { r = (Reference)obj; } //We return a list here since it's expecting an IEnumerable<Reference>. In reality, //just passing the element by itself instead of a sub-list is a shortcut for having //a list with one element, so this is just performing that for the user. return new List<Reference>() { r }; } } ); //Now we add all of those references into ReferenceArrays foreach (IEnumerable<Reference> refs in refArrays.Where(x => x.Any())) { var refArr = new ReferenceArray(); foreach (Reference r in refs) refArr.Append(r); refArrArr.Append(refArr); } } //If we already have a form stored... if (this.Elements.Any()) { Form oldF; //is this same element? if (dynUtils.TryGetElement(this.Elements[0], out oldF)) { if (oldF.IsSolid == isSolid && _preferSurfaceForOneLoop == isSurface && matchOrAddFormCurveToReferenceCurveMap(oldF, refArrArr, true)) { return FScheme.Value.NewContainer(oldF); } } //Dissolve it, we will re-make it later. if (FormUtils.CanBeDissolved(this.UIDocument.Document, this.Elements.Take(1).ToList())) FormUtils.DissolveForms(this.UIDocument.Document, this.Elements.Take(1).ToList()); //And register the form for deletion. Since we've already deleted it here manually, we can //pass "true" as the second argument. this.DeleteElement(this.Elements[0], true); } else if (this._formId != ElementId.InvalidElementId) { Form oldF; if (dynUtils.TryGetElement(this._formId, out oldF)) { if (oldF.IsSolid == isSolid && _preferSurfaceForOneLoop == isSurface && matchOrAddFormCurveToReferenceCurveMap(oldF, refArrArr, true)) { return FScheme.Value.NewContainer(oldF); } } } _preferSurfaceForOneLoop = isSurface; //We use the ReferenceArrayArray to make the form, and we store it for later runs. Form f; //if we only have a single refArr, we can make a capping surface or an extrusion if (refArrArr.Size == 1) { ReferenceArray refArr = refArrArr.get_Item(0); if (isSurface) // make a capping surface { f = this.UIDocument.Document.FamilyCreate.NewFormByCap(true, refArr); } else // make an extruded surface { // The extrusion form direction XYZ direction = new XYZ(0, 0, 50); f = this.UIDocument.Document.FamilyCreate.NewExtrusionForm(true, refArr, direction); } } else // make a lofted surface { f = this.UIDocument.Document.FamilyCreate.NewLoftForm(isSolid, refArrArr); } matchOrAddFormCurveToReferenceCurveMap(f, refArrArr, false); this.Elements.Add(f.Id); return FScheme.Value.NewContainer(f); }
public static Form ByLoftingCurveReferences( CurveReference[][] curves, bool isSolid ) { var refArrArr = new ReferenceArrayArray(); foreach (var curveArr in curves) { var refArr = new ReferenceArray(); curveArr.ForEach(x => refArr.Append(x.InternalReference)); refArrArr.Append(refArr); } return new Form(isSolid, refArrArr); }
/// <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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "MakeLoftForm"); transaction.Start(); // Create profiles array ReferenceArrayArray ref_ar_ar = new ReferenceArrayArray(); // Create first profile ReferenceArray ref_ar = new ReferenceArray(); int y = 100; int x = 50; Autodesk.Revit.DB.XYZ ptA = new Autodesk.Revit.DB.XYZ (-x, y, 0); Autodesk.Revit.DB.XYZ ptB = new Autodesk.Revit.DB.XYZ (x, y, 0); Autodesk.Revit.DB.XYZ ptC = new Autodesk.Revit.DB.XYZ (0, y + 10, 10); ModelCurve modelcurve = FormUtils.MakeArc(commandData.Application, ptA, ptB, ptC); ref_ar.Append(modelcurve.GeometryCurve.Reference); ref_ar_ar.Append(ref_ar); // Create second profile ref_ar = new ReferenceArray(); y = 40; ptA = new Autodesk.Revit.DB.XYZ (-x, y, 5); ptB = new Autodesk.Revit.DB.XYZ (x, y, 5); ptC = new Autodesk.Revit.DB.XYZ (0, y, 25); modelcurve = FormUtils.MakeArc(commandData.Application, ptA, ptB, ptC); ref_ar.Append(modelcurve.GeometryCurve.Reference); ref_ar_ar.Append(ref_ar); // Create third profile ref_ar = new ReferenceArray(); y = -20; ptA = new Autodesk.Revit.DB.XYZ (-x, y, 0); ptB = new Autodesk.Revit.DB.XYZ (x, y, 0); ptC = new Autodesk.Revit.DB.XYZ (0, y, 15); modelcurve = FormUtils.MakeArc(commandData.Application, ptA, ptB, ptC); ref_ar.Append(modelcurve.GeometryCurve.Reference); ref_ar_ar.Append(ref_ar); // Create fourth profile ref_ar = new ReferenceArray(); y = -60; ptA = new Autodesk.Revit.DB.XYZ (-x, y, 0); ptB = new Autodesk.Revit.DB.XYZ (x, y, 0); ptC = new Autodesk.Revit.DB.XYZ (0, y + 10, 20); modelcurve = FormUtils.MakeArc(commandData.Application, ptA, ptB, ptC); ref_ar.Append(modelcurve.GeometryCurve.Reference); ref_ar_ar.Append(ref_ar); ref_ar = new ReferenceArray(); ref_ar_ar.Append(ref_ar); Autodesk.Revit.DB.Form form = doc.FamilyCreate.NewLoftForm(true, ref_ar_ar); transaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
/// <summary> /// Create Extrusion /// </summary> /// <param name="extrusion"></param> /// <returns></returns> public static Element Create(this Grevit.Types.SimpleExtrusion extrusion) { // Get the Massing template file string templateFile = GrevitBuildModel.RevitTemplateFolder + @"\Conceptual Mass\Metric Mass.rft"; // If the file doesnt exist ask the user for a new template if (!File.Exists(templateFile)) { System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); ofd.Multiselect = false; ofd.Title = templateFile + " not found."; System.Windows.Forms.DialogResult dr = ofd.ShowDialog(); if (dr != System.Windows.Forms.DialogResult.OK) return null; templateFile = ofd.FileName; } // Create a new family Document Document familyDocument = GrevitBuildModel.document.Application.NewFamilyDocument(templateFile); // Create a new family transaction Transaction familyTransaction = new Transaction(familyDocument, "Transaction in Family"); familyTransaction.Start(); // get family categories Categories categories = familyDocument.Settings.Categories; // Get the mass category Category catMassing = categories.get_Item("Mass"); // Create a new subcategory in Mass Category subcategory = familyDocument.Settings.Categories.NewSubcategory(catMassing, "GrevitExtrusion"); // Create a reference Array for the Profile ReferenceArray referenceArrayProfile = new ReferenceArray(); // Translate all Points to the reference Array for (int i = 0; i < extrusion.polyline.points.Count - 1; i++) { Grevit.Types.Point pkt1 = extrusion.polyline.points[i]; Grevit.Types.Point pkt2 = extrusion.polyline.points[i + 1]; referenceArrayProfile.Append(Utilities.CurveFromXYZ(familyDocument, pkt1.ToXYZ(), pkt2.ToXYZ())); } // Create a new Extrusion Form extrudedMass = familyDocument.FamilyCreate.NewExtrusionForm(true, referenceArrayProfile, new XYZ(extrusion.vector.x, extrusion.vector.y, extrusion.vector.z)); // Apply the subcategory extrudedMass.Subcategory = subcategory; // Commit the Family Transaction familyTransaction.Commit(); // Assemble a filename to save the family to string filename = Path.Combine(Path.GetTempPath(), "GrevitMass-" + extrusion.GID + ".rfa"); // Save Family to Temp path and close it SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; familyDocument.SaveAs(filename, opt); familyDocument.Close(false); // Load the created family to the document Family family = null; GrevitBuildModel.document.LoadFamily(filename, out family); // Get the first family symbol FamilySymbol symbol = null; foreach (ElementId s in family.GetFamilySymbolIds()) { symbol = (FamilySymbol)GrevitBuildModel.document.GetElement(s); break; } if (!symbol.IsActive) symbol.Activate(); // Create a new Family Instance origin based FamilyInstance familyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); // Activate Mass visibility GrevitBuildModel.document.SetMassVisibilityOn(); return familyInstance; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; if( !doc.IsFamilyDocument || !doc.OwnerFamily.FamilyCategory.Name.Equals( "Mass" ) ) { message = "Please run this comand in a conceptual massing family document."; return Result.Failed; } using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Create Loft Form" ); FamilyItemFactory creator = doc.FamilyCreate; // Create profiles array ReferenceArrayArray ref_ar_ar = new ReferenceArrayArray(); // Create first profile ReferenceArray ref_ar = new ReferenceArray(); int y = 100; int x = 50; XYZ pa = new XYZ( -x, y, 0 ); XYZ pb = new XYZ( x, y, 0 ); XYZ pc = new XYZ( 0, y + 10, 10 ); CurveByPoints curve = FormUtils.MakeCurve( creator, pa, pb, pc ); ref_ar.Append( curve.GeometryCurve.Reference ); ref_ar_ar.Append( ref_ar ); // Create second profile ref_ar = new ReferenceArray(); y = 40; pa = new XYZ( -x, y, 5 ); pb = new XYZ( x, y, 5 ); pc = new XYZ( 0, y, 25 ); curve = FormUtils.MakeCurve( creator, pa, pb, pc ); ref_ar.Append( curve.GeometryCurve.Reference ); ref_ar_ar.Append( ref_ar ); // Create third profile ref_ar = new ReferenceArray(); y = -20; pa = new XYZ( -x, y, 0 ); pb = new XYZ( x, y, 0 ); pc = new XYZ( 0, y, 15 ); curve = FormUtils.MakeCurve( creator, pa, pb, pc ); ref_ar.Append( curve.GeometryCurve.Reference ); ref_ar_ar.Append( ref_ar ); // Create fourth profile ref_ar = new ReferenceArray(); y = -60; pa = new XYZ( -x, y, 0 ); pb = new XYZ( x, y, 0 ); pc = new XYZ( 0, y + 10, 20 ); curve = FormUtils.MakeCurve( creator, pa, pb, pc ); ref_ar.Append( curve.GeometryCurve.Reference ); ref_ar_ar.Append( ref_ar ); Form form = creator.NewLoftForm( true, ref_ar_ar ); tx.Commit(); } return Result.Succeeded; }
/// <summary> /// Create a new dimension element using the given /// references and dimension line end points. /// /// This method creates its own transaction. /// It assumes that no transaction is open yet /// and manual transaction mode is being used! /// /// This has only been tested using references to /// surfaces on planar walls in a plan view! /// /// Create a new dimension element using the given /// references and dimension line end points. /// /// This method opens and commits its own transaction, /// assuming that no transaction is open yet and manual /// transaction mode is being used. /// /// Note that this has only been tested so far using /// references to surfaces on planar walls in a plan /// view. /// </summary> public static void CreateDimensionElement( View view, XYZ p1, Reference r1, XYZ p2, Reference r2) { Document doc = view.Document; Application app = doc.Application; // creation objects, or factories, for database // and non-database resident instances: Autodesk.Revit.Creation.Application creApp = app.Create; Autodesk.Revit.Creation.Document creDoc = doc.Create; ReferenceArray ra = new ReferenceArray(); ra.Append( r1 ); ra.Append( r2 ); Line line = Line.CreateBound( p1, p2 ); Transaction t = new Transaction( doc, "Dimension Two Walls" ); t.Start(); Dimension dim = creDoc.NewDimension( doc.ActiveView, line, ra ); t.Commit(); }
private void WriteElementGeometry( int elementId ) { FilteredElementCollector viewCollector = new FilteredElementCollector( m_doc ); viewCollector.OfClass( typeof( ViewPlan ) ); Func<ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast<ViewPlan>().First<ViewPlan>( isLevel1FloorPlan ); Transaction createCurve = new Transaction( m_doc, "Create reference curves" ); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound( new XYZ( xReferenceLocation, 0, 0 ), new XYZ( xReferenceLocation, 20, 0 ) ); m_vLine = m_doc.Create.NewDetailCurve( m_targetView, vLine ); const double yReferenceLocation = -10; Line hLine = Line.CreateBound( new XYZ( 0, yReferenceLocation, 0 ), new XYZ( 20, yReferenceLocation, 0 ) ); m_hLine = m_doc.Create.NewDetailCurve( m_targetView, hLine ); createCurve.Commit(); Element e = m_doc.GetElement( new ElementId( elementId ) ); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry( options ); foreach( GeometryObject geomObj in geomElem ) { if( geomObj is Solid ) { WriteSolid( (Solid) geomObj ); } else if( geomObj is GeometryInstance ) { TraverseGeometryInstance( (GeometryInstance) geomObj ); } else { m_writer.WriteLine( "Something else - " + geomObj.GetType().Name ); } } foreach( Curve curve in m_referencePlaneReferences ) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference( curveReference ); if( geomObj != null ) { m_writer.WriteLine( "Curve reference leads to: " + geomObj.GetType().Name ); } } // Dimension to reference curves foreach( Curve curve in m_referencePlaneReferences ) { DetailCurve targetLine = m_vLine; Line line = (Line) curve; XYZ lineStartPoint = line.GetEndPoint( 0 ); XYZ lineEndPoint = line.GetEndPoint( 1 ); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if( Math.Abs( direction.Y ) < 0.0001 ) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X + 5, lineStartPoint.Y, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X, dimensionLineStart.Y + 10, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X, lineStartPoint.Y + 5, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X + 10, dimensionLineStart.Y, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } ReferenceArray references = new ReferenceArray(); references.Append( curve.Reference ); references.Append( targetLine.GeometryCurve.Reference ); Transaction t = new Transaction( m_doc, "Create dimension" ); t.Start(); m_doc.Create.NewDimension( m_targetView, dimensionLine, references ); t.Commit(); } }
public void SelectReferenceASTGeneration() { Form extrude; using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "Create an extrusion Form")) { trans.Start(); FailureHandlingOptions fails = trans.GetFailureHandlingOptions(); fails.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(fails); var p = new Plane(new XYZ(0, 0, 1), new XYZ()); var arc = Arc.Create(p, 2, 0, System.Math.PI); var sp = SketchPlane.Create(DocumentManager.Instance.CurrentDBDocument, p); var mc = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewModelCurve(arc, sp); var profiles = new ReferenceArray(); profiles.Append(mc.GeometryCurve.Reference); extrude = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewExtrusionForm(false, profiles, new XYZ(0,0,1)); trans.Commit(); } var geom = extrude.get_Geometry(new Options() { ComputeReferences = true, DetailLevel = ViewDetailLevel.Medium, IncludeNonVisibleObjects = true }); var solid = geom.FirstOrDefault(x => x is Solid) as Solid; var face = solid.Faces.get_Item(0); Assert.Greater(solid.Faces.Size, 0); var sel = new DSFaceSelection() { SelectedElement = face.Reference }; var buildOutput = sel.BuildOutputAst(new List<AssociativeNode>()); var funCall = (FunctionCallNode)((IdentifierListNode)((BinaryExpressionNode)buildOutput.First()).RightNode).RightNode; Assert.IsInstanceOf<IdentifierNode>(funCall.Function); Assert.AreEqual(1, funCall.FormalArguments.Count); Assert.IsInstanceOf<StringNode>(funCall.FormalArguments[0]); var stableRef = face.Reference.ConvertToStableRepresentation(DocumentManager.Instance.CurrentDBDocument); Assert.AreEqual(stableRef, ((StringNode)funCall.FormalArguments[0]).value); }
public override Expression Evaluate(FSharpList<Expression> args) { //If we already have a form stored... if (this.Elements.Any()) { //Dissolve it, we will re-make it later. FormUtils.DissolveForms(this.UIDocument.Document, this.Elements.Take(1).ToList()); //And register the form for deletion. Since we've already deleted it here manually, we can //pass "true" as the second argument. this.DeleteElement(this.Elements[0], true); } //Solid argument bool isSolid = ((Expression.Number)args[0]).Item == 1; //Surface argument bool isSurface = ((Expression.Number)args[2]).Item == 1; //Build up our list of list of references for the form by... IEnumerable<IEnumerable<Reference>> refArrays = ((Expression.List)args[1]).Item.Select( //...first selecting everything in the topmost list... delegate(Expression x) { //If the element in the topmost list is a sub-list... if (x.IsList) { //...then we return a new IEnumerable of References by converting the sub list. return (x as Expression.List).Item.Select( delegate(Expression y) { //Since we're in a sub-list, we can assume it's a container. var item = ((Expression.Container)y).Item; if (item is CurveElement) return (item as CurveElement).GeometryCurve.Reference; else return (Reference)item; } ); } //If the element is not a sub-list, then just assume it's a container. else { var obj = ((Expression.Container)x).Item; Reference r; if (obj is CurveElement) { r = (obj as CurveElement).GeometryCurve.Reference; } else { r = (Reference)obj; } //We return a list here since it's expecting an IEnumerable<Reference>. In reality, //just passing the element by itself instead of a sub-list is a shortcut for having //a list with one element, so this is just performing that for the user. return new List<Reference>() { r }; } } ); //Now we add all of those references into ReferenceArrays ReferenceArrayArray refArrArr = new ReferenceArrayArray(); foreach (IEnumerable<Reference> refs in refArrays.Where(x => x.Any())) { var refArr = new ReferenceArray(); foreach (Reference r in refs) refArr.Append(r); refArrArr.Append(refArr); } //We use the ReferenceArrayArray to make the form, and we store it for later runs. Form f; //if we only have a single refArr, we can make a capping surface or an extrusion if (refArrArr.Size == 1) { ReferenceArray refArr = refArrArr.get_Item(0); if (isSurface) // make a capping surface { f = this.UIDocument.Document.FamilyCreate.NewFormByCap(true, refArr); } else // make an extruded surface { // The extrusion form direction XYZ direction = new XYZ(0, 0, 50); f = this.UIDocument.Document.FamilyCreate.NewExtrusionForm(true, refArr, direction); } } else // make a lofted surface { f = this.UIDocument.Document.FamilyCreate.NewLoftForm(isSolid, refArrArr); } this.Elements.Add(f.Id); return Expression.NewContainer(f); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; if( !doc.IsFamilyDocument ) { message = "Please run this command in afamily document."; return Result.Failed; } Autodesk.Revit.Creation.Application creApp = app.Application.Create; Autodesk.Revit.Creation.Document creDoc = doc.Create; SketchPlane skplane = findSketchPlane( doc, XYZ.BasisZ ); if( null == skplane ) { Plane geometryPlane = creApp.NewPlane( XYZ.BasisZ, XYZ.Zero ); //skplane = doc.FamilyCreate.NewSketchPlane( geometryPlane ); // 2013 skplane = SketchPlane.Create( doc, geometryPlane ); // 2014 } double length = 1.23; XYZ start = XYZ.Zero; XYZ end = creApp.NewXYZ( 0, length, 0 ); //Line line = creApp.NewLine( start, end, true ); // 2013 Line line = Line.CreateBound( start, end ); // 2014 ModelCurve modelCurve = doc.FamilyCreate.NewModelCurve( line, skplane ); ReferenceArray ra = new ReferenceArray(); ra.Append( modelCurve.GeometryCurve.Reference ); start = creApp.NewXYZ( length, 0, 0 ); end = creApp.NewXYZ( length, length, 0 ); line = Line.CreateBound( start, end ); modelCurve = doc.FamilyCreate.NewModelCurve( line, skplane ); ra.Append( modelCurve.GeometryCurve.Reference ); start = creApp.NewXYZ( 0, 0.2 * length, 0 ); end = creApp.NewXYZ( length, 0.2 * length, 0 ); line = Line.CreateBound( start, end ); Dimension dim = doc.FamilyCreate.NewLinearDimension( doc.ActiveView, line, ra ); FamilyParameter familyParam = doc.FamilyManager.AddParameter( "length", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Length, false ); //dim.Label = familyParam; // 2013 dim.FamilyLabel = familyParam; // 2014 return Result.Succeeded; }
public static void SlopedWallTest( ExternalCommandData revit) { Document massDoc = revit.Application.Application.NewFamilyDocument( @"C:\ProgramData\Autodesk\RAC 2012\Family Templates\English_I\Conceptual Mass\Mass.rft" ); Transaction transaction = new Transaction( massDoc ); transaction.SetName( "TEST" ); transaction.Start(); ExternalCommandData cdata = revit; Autodesk.Revit.ApplicationServices.Application app = revit.Application.Application; app = revit.Application.Application; // Create one profile ReferenceArray ref_ar = new ReferenceArray(); Autodesk.Revit.DB.XYZ ptA = new XYZ( 0, 0, 0 ); XYZ ptB = new XYZ( 0, 30, 0 ); ModelCurve modelcurve = MakeLine( revit.Application, ptA, ptB, massDoc ); ref_ar.Append( modelcurve.GeometryCurve.Reference ); ptA = new XYZ( 0, 30, 0 ); ptB = new XYZ( 2, 30, 0 ); modelcurve = MakeLine( revit.Application, ptA, ptB, massDoc ); ref_ar.Append( modelcurve.GeometryCurve.Reference ); ptA = new XYZ( 2, 30, 0 ); ptB = new XYZ( 2, 0, 0 ); modelcurve = MakeLine( revit.Application, ptA, ptB, massDoc ); ref_ar.Append( modelcurve.GeometryCurve.Reference ); ptA = new XYZ( 2, 0, 0 ); ptB = new XYZ( 0, 0, 0 ); modelcurve = MakeLine( revit.Application, ptA, ptB, massDoc ); ref_ar.Append( modelcurve.GeometryCurve.Reference ); // The extrusion form direction XYZ direction = new XYZ( -6, 0, 50 ); Form form = massDoc.FamilyCreate.NewExtrusionForm( true, ref_ar, direction ); transaction.Commit(); if( File.Exists( @"C:\TestFamily.rfa" ) ) File.Delete( @"C:\TestFamily.rfa" ); massDoc.SaveAs( @"C:\TestFamily.rfa" ); if( !revit.Application.ActiveUIDocument.Document.LoadFamily( @"C:\TestFamily.rfa" ) ) throw new Exception( "DID NOT LOAD FAMILY" ); Family family = null; foreach( Element el in new FilteredElementCollector( revit.Application.ActiveUIDocument.Document ).WhereElementIsNotElementType().ToElements() ) { if( el is Family ) { if( ( (Family) el ).Name.ToUpper().Trim().StartsWith( "TEST" ) ) family = (Family) el; } } FamilySymbol fs = null; foreach( FamilySymbol sym in family.Symbols ) fs = sym; // Create a family instance. revit.Application.ActiveUIDocument.Document.Create.NewFamilyInstance( new XYZ( 0, 0, 0 ), fs, revit.Application.ActiveUIDocument.Document.ActiveView.Level, StructuralType.NonStructural ); WallType wallType = null; foreach( WallType wt in revit.Application.ActiveUIDocument.Document.WallTypes ) { if( FaceWall.IsWallTypeValidForFaceWall( revit.Application.ActiveUIDocument.Document, wt.Id ) ) { wallType = wt; break; } } foreach( Element el in new FilteredElementCollector( revit.Application.ActiveUIDocument.Document ).WhereElementIsNotElementType().ToElements() ) { if( el is FamilyInstance ) { if( ( (FamilyInstance) el ).Symbol.Family.Name.ToUpper().StartsWith( "TEST" ) ) { Options options = revit.Application.Application.Create.NewGeometryOptions(); options.ComputeReferences = true; options.View = revit.Application.ActiveUIDocument.Document.ActiveView; GeometryElement geoel = el.get_Geometry( options ); // Attempt to create a slopped wall from the geometry. for( int i = 0; i < geoel.Objects.Size; i++ ) { if( geoel.Objects.get_Item( i ) is Solid ) { Solid solid = (Solid) geoel.Objects.get_Item( i ); for( int j = 0; j < solid.Faces.Size; j++ ) { try { if( solid.Faces.get_Item( i ).Reference != null ) { FaceWall.Create( revit.Application.ActiveUIDocument.Document, wallType.Id, WallLocationLine.CoreCenterline, solid.Faces.get_Item( i ).Reference ); } } catch( System.Exception e ) { System.Windows.Forms.MessageBox.Show( e.Message ); } } } } } } } }
/// <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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "MakeSweptBlendForm"); transaction.Start(); // Create first profile ReferenceArray ref_ar = new ReferenceArray(); Autodesk.Revit.DB.XYZ ptA = new Autodesk.Revit.DB.XYZ (10, 10, 0); Autodesk.Revit.DB.XYZ ptB = new Autodesk.Revit.DB.XYZ (50, 10, 0); ModelCurve modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (50, 10, 0); ptB = new Autodesk.Revit.DB.XYZ (10, 50, 0); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (10, 50, 0); ptB = new Autodesk.Revit.DB.XYZ (10, 10, 0); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar.Append(modelcurve.GeometryCurve.Reference); // Create second profile ReferenceArray ref_ar2 = new ReferenceArray(); ptA = new Autodesk.Revit.DB.XYZ (10, 10, 90); ptB = new Autodesk.Revit.DB.XYZ (80, 10, 90); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar2.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (80, 10, 90); ptB = new Autodesk.Revit.DB.XYZ (10, 50, 90); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar2.Append(modelcurve.GeometryCurve.Reference); ptA = new Autodesk.Revit.DB.XYZ (10, 50, 90); ptB = new Autodesk.Revit.DB.XYZ (10, 10, 90); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); ref_ar2.Append(modelcurve.GeometryCurve.Reference); // Add profiles ReferenceArrayArray profiles = new ReferenceArrayArray(); profiles.Append(ref_ar); profiles.Append(ref_ar2); // Create path for swept blend form ReferenceArray path = new ReferenceArray(); ptA = new Autodesk.Revit.DB.XYZ (10, 10, 0); ptB = new Autodesk.Revit.DB.XYZ (10, 10, 90); modelcurve = FormUtils.MakeLine(commandData.Application, ptA, ptB); path.Append(modelcurve.GeometryCurve.Reference); Autodesk.Revit.DB.Form form = doc.FamilyCreate.NewSweptBlendForm(true, path, profiles); transaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
// ====================================== // (3.2) add dimensions // ====================================== void addDimensions() { // find the plan view // View pViewPlan = findElement(typeof(ViewPlan), "Lower Ref. Level") as View; // find reference planes // ReferencePlane refLeft = findElement(typeof(ReferencePlane), "Left") as ReferencePlane; ReferencePlane refFront = findElement(typeof(ReferencePlane), "Front") as ReferencePlane; ReferencePlane refOffsetV = findElement(typeof(ReferencePlane), "OffsetV") as ReferencePlane; // OffsetV is added for L-shape ReferencePlane refOffsetH = findElement(typeof(ReferencePlane), "OffsetH") as ReferencePlane; // OffsetH is added for L-shape // // (1) add dimension between the reference planes 'Left' and 'OffsetV', and label it as 'Tw' // // define a dimension line // XYZ p0 = refLeft.FreeEnd; XYZ p1 = refOffsetV.FreeEnd; // Line pLine = _app.Create.NewLineBound(p0, p1); // Revit 2013 Line pLine = Line.CreateBound(p0, p1); // Revit 2014 // define references // ReferenceArray pRefArray = new ReferenceArray(); pRefArray.Append(refLeft.GetReference()); pRefArray.Append(refOffsetV.GetReference()); // create a dimension // Dimension pDimTw = _doc.FamilyCreate.NewDimension(pViewPlan, pLine, pRefArray); // add label to the dimension // FamilyParameter paramTw = _doc.FamilyManager.get_Parameter("Tw"); // pDimTw.Label = paramTw; //Revit 2013 pDimTw.FamilyLabel = paramTw; // Revit 2014 // // (2) do the same for dimension between 'Front' and 'OffsetH', and lable it as 'Td' // // define a dimension line // p0 = refFront.FreeEnd; p1 = refOffsetH.FreeEnd; //pLine = _app.Create.NewLineBound(p0, p1); // Revit 2013 pLine = Line.CreateBound(p0, p1); // Revit 2014 // define references // pRefArray = new ReferenceArray(); pRefArray.Append(refFront.GetReference()); pRefArray.Append(refOffsetH.GetReference()); // create a dimension // Dimension pDimTd = _doc.FamilyCreate.NewDimension(pViewPlan, pLine, pRefArray); // add label to the dimension // FamilyParameter paramTd = _doc.FamilyManager.get_Parameter("Td"); // pDimTd.Label = paramTd; // Revit 2013 pDimTd.FamilyLabel = paramTd; // Revit 2014 }
/// <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 Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; XYZ xyz = new XYZ(); ReferenceArrayArray refArAr = new ReferenceArrayArray(); int x = 0; double z = 0; while (x < 800) { ReferencePointArray rpAr = new ReferencePointArray(); int y = 0; while (y < 800) { z = 50 * (Math.Cos((Math.PI / 180) * x) + Math.Cos((Math.PI / 180) * y)); xyz = app.Create.NewXYZ(x, y, z); ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(xyz); rpAr.Append(rp); y = y + 40; } CurveByPoints curve = doc.FamilyCreate.NewCurveByPoints(rpAr); ReferenceArray refAr = new ReferenceArray(); refAr.Append(curve.GeometryCurve.Reference); refArAr.Append(refAr); x = x + 40; } Form form = doc.FamilyCreate.NewLoftForm(true, refArAr); return Result.Succeeded; }