/// <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 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; }
void EnsureGodRaysCreated() { if (ImageSpaces == null) { GodRays = new ReferenceArray(); } GodRays.SetLength(8); }
void EnsureImageSpaceCreated() { if (ImageSpaces == null) { ImageSpaces = new ReferenceArray(); } ImageSpaces.SetLength(8); }
private static ReferenceArray ConvertFSharpListListToReferenceArray(FSharpList <Value> lstlst) { ReferenceArray refArr = new ReferenceArray(); AddReferencesToArray(refArr, lstlst); return(refArr); }
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); //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); //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); }
/// <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); }
/// <summary> /// Family symbol parameter. /// </summary> /// <param name="tplFileName"></param> /// <param name="profile"></param> /// <param name="profilePath"></param> /// <param name="location"></param> /// <param name="index"></param> public FamilySymbolParameter(string tplFileName, CurveArrArray profile, ReferenceArray profilePath, ProfilePlaneLocation location = ProfilePlaneLocation.Start, int index = 0) { TemplateFileName = tplFileName ?? throw new ArgumentNullException(nameof(tplFileName)); Profile = profile ?? throw new ArgumentNullException(nameof(profile)); SweepPath = profilePath ?? throw new ArgumentNullException(nameof(profilePath)); Location = location; Index = index; }
public void getSubElement() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; View myView = doc.ActiveView; Reference myRef = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a rebar..."); Rebar myRebar = doc.GetElement(myRef) as Rebar; TaskDialog.Show("abc", "Has: " + myRebar.NumberOfBarPositions.ToString()); ReferenceArray myRefAr = new ReferenceArray(); int myNumberRebar = (int)myRebar.NumberOfBarPositions; if (myNumberRebar > 1) { for (int i = 0; i < myNumberRebar; i++) { List <Curve> centerLines = myRebar.GetCenterlineCurves(false, false, false, MultiplanarOption.IncludeOnlyPlanarCurves, 0) as List <Curve>; foreach (Curve myCurBar in centerLines) { if (myCurBar is Line) { Line myLine = myCurBar as Line; Reference myRefLine = myLine.Reference; myRefAr.Append(myRefLine); break; } } } } TaskDialog.Show("abc", myRefAr.Size.ToString()); setCurrentViewAsWorkPlan(); XYZ myDimPoint_1 = uiDoc.Selection.PickPoint("Pick Point To Place Dimension...."); XYZ myDimPoint_2 = new XYZ(myDimPoint_1.X + 5, myDimPoint_1.Y, myDimPoint_1.Z); Line dimLine = Line.CreateBound(myDimPoint_1, myDimPoint_2); using (Transaction trans = new Transaction(doc, "Create linear Dimension")) { trans.Start(); Dimension myDim = doc.Create.NewDimension(doc.ActiveView, dimLine, myRefAr); trans.Commit(); } }
private void ConstructParam(Document familyDoc, ReferenceArray ra, Line line, string label) { Autodesk.Revit.DB.Dimension dim = familyDoc.FamilyCreate.NewDimension(familyDoc.ActiveView, line, ra); FamilyParameter param = familyDoc.FamilyManager.AddParameter(label, BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Length, true); //if (label == "Height") _param = param; //if (label == "Height") familyDoc.FamilyManager.SetFormula(param, "Width"); dim.Label = param; }
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); }
/// <summary> /// Create an extrusion form in the given /// conceptual mass family document. /// </summary> static void CreateMassExtrusion( Document doc) { using (Transaction tx = new Transaction(doc)) { tx.Start("Create Mass"); // Create profile ReferenceArray refar = new ReferenceArray(); XYZ[] pts = new XYZ[] { new XYZ(-10, -10, 0), new XYZ(+10, -10, 0), new XYZ(+10, +10, 0), new XYZ(-10, +10, 0) }; int j, n = pts.Length; for (int i = 0; i < n; ++i) { j = i + 1; if (j >= n) { j = 0; } // The Creator.CreateModelLine method creates // pretty arbitrary sketch planes, which causes // the NewExtrusionForm method to fail, saying // "Cannot create extrude form." //ModelCurve c = Creator.CreateModelLine( doc, pts[i], pts[j] ); ModelCurve c = MakeLine(doc, pts[i], pts[j]); refar.Append(c.GeometryCurve.Reference); } //doc.Regenerate(); // The extrusion form direction and length. // The direction must be perpendicular to the // plane determined by profile. The length // must be non-zero. XYZ direction = new XYZ(/*-6*/ 0, 0, 20); Form form = doc.FamilyCreate.NewExtrusionForm( // Cannot create extrude form. true, refar, direction); tx.Commit(); } }
private void CreateDimensions( FilledRegion filledRegion, XYZ dimensionDirection, string typeName) { var document = filledRegion.Document; var view = (View)document.GetElement( filledRegion.OwnerViewId); var edgesDirection = dimensionDirection.CrossProduct( view.ViewDirection); var edges = FindRegionEdges(filledRegion) .Where(x => IsEdgeDirectionSatisfied(x, edgesDirection)) .ToList(); if (edges.Count < 2) { return; } // Se hace este ajuste para que la distancia no // depende de la escala. <<<<<< evaluar para // información de acotado y etiquetado!!! //var shift = UnitUtils.ConvertToInternalUnits( // 5 * view.Scale, DisplayUnitType.DUT_MILLIMETERS ) // 2020 // * edgesDirection; var shift = UnitUtils.ConvertToInternalUnits( 5 * view.Scale, UnitTypeId.Millimeters) // 2021 * edgesDirection; var dimensionLine = Line.CreateUnbound( filledRegion.get_BoundingBox(view).Min + shift, dimensionDirection); var references = new ReferenceArray(); foreach (var edge in edges) { references.Append(edge.Reference); } Dimension dim = document.Create.NewDimension( view, dimensionLine, references); ElementId dr_id = DimensionTypeId( document, typeName); if (dr_id != null) { dim.ChangeTypeId(dr_id); } }
//根据参照点和法向量创建放样截面,针对中间截面对象 private ReferenceArray CreatePlaneByPoint(ReferencePoint refPt, XYZ normal) { Plane plane = new Plane(normal, refPt.Position); Arc circle = Arc.Create(plane, mmToFeet(300), 0, 2 * Math.PI); ModelCurve modelcurve = m_familyCreator.NewModelCurve(circle, SketchPlane.Create(massdoc, plane)); ReferenceArray ra = new ReferenceArray(); ra.Append(modelcurve.GeometryCurve.Reference); return(ra); }
/// <summary> /// Adds the new family symbol. /// </summary> /// <param name="uiapp"></param> /// <param name="rfa"></param> /// <param name="profile"></param> /// <param name="path"></param> /// <param name="index"></param> /// <returns></returns> public static FamilySymbol AddFamilySymbol(this UIApplication uiapp, string rfa, SweepProfile profile, ReferenceArray path, int index) { var doc = uiapp.ActiveUIDocument.Document; var fdoc = uiapp.Application.NewFamilyDocument(rfa); fdoc.AddSweep(profile, path, index); return(doc.GetElement(fdoc.LoadFamily(doc).GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol); }
/// <summary> /// Converts the reference set to the reference array. /// </summary> /// <param name="refers"></param> /// <returns></returns> public static ReferenceArray ToReferArray(this List <Reference> refers) { var results = new ReferenceArray(); foreach (var refer in refers) { results.Append(refer); } return(results); }
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> /// 尺寸标注单根直线元素-墙体 /// </summary> public static Dimension DimensionSingeleWall(this Document doc, Wall wall) { Dimension dimension = null; // 【】求出尺寸线所在位置 Line line = (wall.Location as LocationCurve).Curve as Line; XYZ wallDirection = line.Direction; ReferenceArray referenceArray = new ReferenceArray(); // 【】求出dimension可参照几何体 Options options = new Options(); options.View = doc.ActiveView; options.ComputeReferences = true; GeometryElement geometryElement = wall.get_Geometry(options); Solid solid = geometryElement.First() as Solid; // 【方法一】求出墙体两侧边的Edge-reference //List<Edge> edges = solid.Edges.ToIEnumerable().ToList(); //edges = edges.OrderBy(p => p.ApproximateLength).ToList();// 边长排序 //edges = edges.GetRange(0, 4); //edges = edges.OrderBy(p => p.AsCurve().GetEndPoint(0).Z).ToList();// y轴排序 //edges = edges.GetRange(0, 2); //foreach (Edge edge in edges) // referenceArray.Append(edge.Reference); // 【方法二】求出墙体两侧边的Face List <Face> faces = solid.Faces.ToIEnumerable().ToList(); foreach (Face face in faces) { XYZ normalXyz = face.ComputeNormal(new UV()); if (Math.Abs(normalXyz.DotProduct(wallDirection)).EqualPrecision(1)) { referenceArray.Append(face.Reference); } } // 【】移动标注线的位置 //double distanceMove = 2000.0.MilliMeterToFeet(); //distanceMove = distanceMove.MilliMeterToFeet(); //XYZ xyzDirection = line.Direction.CrossProduct(new XYZ(0, 0, 1)).Normalize(); //line = line.CreateOffset(distanceMove, xyzDirection) as Line; using (Transaction trans = new Transaction(doc, "轴网端头尺寸标注")) { trans.Start(); dimension = doc.Create.NewDimension(doc.ActiveView, line, referenceArray); trans.Commit(); } return(dimension); }
/// <summary> /// Create a SlabEdge. /// </summary> /// <param name="symbol">SlabEdge type</param> /// <param name="refArr">SlabEdge reference array</param> /// <returns>Created SlabEdge</returns> protected override HostedSweep CreateHostedSweep(ElementType symbol, ReferenceArray refArr) { SlabEdge slabEdge = m_rvtDoc.Create.NewSlabEdge(symbol as SlabEdgeType, refArr); if (slabEdge != null) { // Avoid the Revit warning, flip the direction in horizontal direction. slabEdge.HorizontalFlip(); } return(slabEdge); }
public void CreateWallDimensions_Vertical() { Document doc = this.ActiveUIDocument.Document; UIDocument uidoc = this.ActiveUIDocument; Options opt = doc.Application.Create.NewGeometryOptions(); opt.ComputeReferences = true; ReferenceArray referenceArray = new ReferenceArray(); ISelectionFilter verwallfilter = new VerWallSelectionFilter(); foreach (Wall wall in uidoc.Selection.PickElementsByRectangle(verwallfilter)) { GeometryElement geo = wall.get_Geometry(opt); foreach (GeometryObject objects in geo) { Solid solid = objects as Solid; foreach (Face face in solid.Faces) { if (face.ComputeNormal(new UV(0, 0)).X == 1 || face.ComputeNormal(new UV(0, 0)).X == -1) { referenceArray.Append(face.Reference); } } } } XYZ pnt = uidoc.Selection.PickPoint(ObjectSnapTypes.None); try { XYZ p1 = pnt + new XYZ(1, 0, 0); XYZ p2 = pnt + new XYZ(-1, 0, 0); Line newLine2 = Line.CreateBound(p1, p2); using (Transaction t = new Transaction(doc, "dim")) { t.Start(); Dimension newDimension = doc.Create.NewDimension(doc.ActiveView, newLine2, referenceArray); t.Commit(); } } // catch the exceptions catch { TaskDialog.Show("11", "script error ask Hongseok"); } }
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 Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // 【获取句柄】 UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; // 【获取墙】 Wall wall = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element)) as Wall; if (wall != null) { // 【获取定位线】 Line wallLine = (wall.Location as LocationCurve).Curve as Line; // 【获取方向,用来寻找参照】 XYZ wallDir = wallLine.Direction; // 【获取墙定位线的参照】 ReferenceArray refArry = new ReferenceArray(); // 【定义几何选项】 Options opt = new Options(); opt.ComputeReferences = true; opt.DetailLevel = ViewDetailLevel.Fine; //【获取墙的几何】 GeometryElement gelem = wall.get_Geometry(opt); foreach (GeometryObject gobj in gelem) { if (gobj is Solid) { Solid solid = gobj as Solid; if (solid.Volume > 0) { foreach (Face face in solid.Faces) { if (face is PlanarFace) { XYZ faceDir = face.ComputeNormal(new UV()); //判断是否平行 if (faceDir.IsAlmostEqualTo(wallDir) || faceDir.IsAlmostEqualTo(-wallDir)) { refArry.Append(face.Reference); TaskDialog.Show("1", "1"); } } } } } } Transaction trans = new Transaction(doc, "开始标注"); trans.Start(); Dimension dimension = doc.Create.NewDimension(doc.ActiveView, wallLine, refArry); trans.Commit(); } return(Result.Succeeded); }
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)); }
/// <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)); }
private void WriteDimensionReferences(int dimId) { Dimension dim = m_doc.GetElement( new ElementId(dimId)) as Dimension; ReferenceArray references = dim.References; foreach (Reference reference in references) { m_writer.WriteLine("Dim reference - " + reference.ConvertToStableRepresentation( m_doc)); } }
public void DuplicateDimension(Document doc, Dimension dimension) { Line line = dimension.Curve as Line; if (null != line) { Autodesk.Revit.DB.View view = dimension.View; ReferenceArray references = dimension.References; Dimension newDimension = doc.Create.NewDimension( view, line, references); } }
/// <summary> /// Construct a Revit Dimension from at least two elements /// </summary> /// <param name="view">View to place dimension in</param> /// <param name="referenceElements">Elements to dimension</param> /// <param name="line">location of the dimension</param> /// <param name="suffix">Suffix</param> /// <param name="prefix">Prefix</param> /// <returns>Dimension</returns> public static Dimension ByElements(Revit.Elements.Views.View view, IEnumerable <Revit.Elements.Element> referenceElements, [DefaultArgument("null")] Autodesk.DesignScript.Geometry.Line line, string suffix = "", string prefix = "") { var elements = referenceElements.ToList(); if (elements.Count < 2) { throw new Exception(Properties.Resources.NotEnoughDataError); } Autodesk.Revit.DB.View revitView = (Autodesk.Revit.DB.View)view.InternalElement; Line revitLine = null; // if there is no location line supplied, draw a line between the midpoints // of the supplied elements. if (line == null) { BoundingBoxXYZ boundingBoxFirstElement = elements[0].InternalElement.get_BoundingBox(revitView); if ((boundingBoxFirstElement) == null) { throw new Exception(Properties.Resources.ElementCannotBeAnnotatedError); } BoundingBoxXYZ boundingBoxLastElement = elements[elements.Count - 1].InternalElement.get_BoundingBox(revitView); if ((boundingBoxLastElement) == null) { throw new Exception(Properties.Resources.ElementCannotBeAnnotatedError); } revitLine = Line.CreateBound(GetMidpoint(boundingBoxFirstElement), GetMidpoint(boundingBoxLastElement)); } else { revitLine = (Line)line.ToRevitType(true); } if (!view.IsAnnotationView()) { throw new Exception(Properties.Resources.ViewDoesNotSupportAnnotations); } ReferenceArray array = new ReferenceArray(); foreach (Revit.Elements.Element element in elements) { array.Append(new Reference(element.InternalElement)); } return(new Dimension(revitView, revitLine, array, suffix, prefix)); }
private void Member(Document doc, Dimension dimension, ref string hh, ref string type) { ReferenceArray referenceArray = dimension.References; List <string> list = new List <string>(); for (int i = 1; i < referenceArray.Size - 1; i++) { Reference reference = referenceArray.get_Item(i); Element element = doc.GetElement(reference); if (element.Category.Id.IntegerValue != (int)BuiltInCategory.OST_StructuralFraming) { ElementId elementId = element.GetTypeId(); Element eletype = doc.GetElement(elementId); Parameter sorting_order = eletype.LookupParameter("SORTING_ORDER"); string val = string.Empty; if (sorting_order != null) { if (sorting_order.AsInteger() == 405) { type = "REBAR"; val = element.LookupParameter("CONTROL_MARK").AsString(); } else { type = "EMBED"; val = eletype.LookupParameter("CONTROL_MARK").AsString(); } } else { type = "EMBED"; val = element.LookupParameter("CONTROL_MARK").AsString(); } list.Add(val); } } Removeduplicatestring(list); for (int i = 0; i < list.Count; i++) { if (i == 0) { hh = list[i]; } else { hh = hh + "," + list[i]; } } }
/// <summary> /// Create Curtain System from face references /// </summary> /// <param name="face"></param> /// <param name="curtainSystemType"></param> /// <returns></returns> public static CurtainSystem ByFace(Autodesk.DesignScript.Geometry.Surface face, CurtainSystemType curtainSystemType) { ReferenceArray ca = new ReferenceArray(); var reference = face.Tags.LookupTag("RevitFaceReference"); if (reference == null) { throw new Exception(Properties.Resources.FaceReferenceFailure); } ca.Append((Autodesk.Revit.DB.Reference)reference); return(new CurtainSystem(ca, curtainSystemType.InternalCurtainSystemType)); }
/// <summary> /// Init by Elements /// </summary> /// <param name="view"></param> /// <param name="line"></param> /// <param name="references"></param> /// <param name="suffix"></param> /// <param name="prefix"></param> private void Init(Autodesk.Revit.DB.View view, Autodesk.Revit.DB.Line line, ReferenceArray references, string suffix, string prefix) { Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument; TransactionManager.Instance.EnsureInTransaction(document); // get element from trace var element = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.Dimension>(document); if (element == null) { element = document.Create.NewDimension(view, line, references); } else { LocationCurve location = element.Location as LocationCurve; location.Curve = line; } InternalSetElement(element); // apply suffix if (this.InternalRevitElement.NumberOfSegments == 0) { this.InternalRevitElement.Suffix = suffix; } else if (this.InternalRevitElement.NumberOfSegments > 1) { foreach (DimensionSegment segment in this.InternalRevitElement.Segments) { segment.Suffix = suffix; } } // apply prefix if (this.InternalRevitElement.NumberOfSegments == 0) { this.InternalRevitElement.Prefix = prefix; } else if (this.InternalRevitElement.NumberOfSegments > 1) { foreach (DimensionSegment segment in this.InternalRevitElement.Segments) { segment.Prefix = prefix; } } TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(this.InternalElement); }
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(); } } }
/// <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; }
private static ReferenceArray ConvertFSharpListListToReferenceArray(FSharpList<Value> lstlst) { ReferenceArray refArr = new ReferenceArray(); AddReferencesToArray(refArr, lstlst); return refArr; }
private static ReferenceArrayArray ConvertFSharpListListToReferenceArrayArray(FSharpList<Value> lstlst) { ReferenceArrayArray refArrArr = new ReferenceArrayArray(); foreach (Value v in lstlst) { ReferenceArray refArr = new ReferenceArray(); FSharpList<Value> lst = (v as Value.List).Item; AddReferencesToArray(refArr, lst); refArrArr.Append(refArr); } return refArrArr; }
/// <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(); } }
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; }
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 SlabEdge. /// </summary> /// <param name="symbol">SlabEdge type</param> /// <param name="refArr">SlabEdge reference array</param> /// <returns>Created SlabEdge</returns> protected override HostedSweep CreateHostedSweep(ElementType symbol, ReferenceArray refArr) { SlabEdge slabEdge = m_rvtDoc.Create.NewSlabEdge(symbol as SlabEdgeType, refArr); if (slabEdge != null) // Avoid the Revit warning, flip the direction in horizontal direction. slabEdge.HorizontalFlip(); return slabEdge; }
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 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); }
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> /// 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; }
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; }
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; }
/// <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 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> /// 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 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); }
/// <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(); }
/// <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; }
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 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); }
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); } }
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); }
/// <summary> /// Create a Gutter. /// </summary> /// <param name="symbol">Gutter type</param> /// <param name="refArr">Gutter Reference array</param> /// <returns>Created Gutter</returns> protected override HostedSweep CreateHostedSweep(ElementType symbol, ReferenceArray refArr) { Gutter gutter = m_rvtDoc.Create.NewGutter(symbol as GutterType, refArr); return gutter; }
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); }
/// <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 }
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); }