public override void PopulateItems() //(IEnumerable set, bool readOnly) { //only update the collection on evaluate //if the item coming in is different if (element == null || element.Id.Equals(this.storedId)) { return; } else { this.storedId = element.Id; this.Items.Clear(); } FamilySymbol fs = element as FamilySymbol; FamilyInstance fi = element as FamilyInstance; if (null != fs) { AddFamilySymbolParameters(fs); } if (null != fi) { AddFamilyInstanceParameters(fi); } Items = Items.OrderBy(x => x.Name).ToObservableCollection <DynamoDropDownItem>(); }
/// <summary> /// find Column which will be used to placed to Wall /// </summary> /// <param name="rvtDoc">Revit document</param> /// <param name="familyName">Family name of Column</param> /// <param name="symbolName">Symbol of Column</param> /// <returns></returns> private FamilySymbol FindFamilySymbol(Document rvtDoc, string familyName, string symbolName) { FilteredElementCollector collector = new FilteredElementCollector(rvtDoc); FilteredElementIterator itr = collector.OfClass(typeof(Family)).GetElementIterator(); itr.Reset(); while (itr.MoveNext()) { Autodesk.Revit.DB.Element elem = (Autodesk.Revit.DB.Element)itr.Current; if (elem.GetType() == typeof(Autodesk.Revit.DB.Family)) { if (elem.Name == familyName) { Autodesk.Revit.DB.Family family = (Autodesk.Revit.DB.Family)elem; foreach (Autodesk.Revit.DB.ElementId symbolId in family.GetFamilySymbolIds()) { Autodesk.Revit.DB.FamilySymbol symbol = (Autodesk.Revit.DB.FamilySymbol)rvtDoc.GetElement(symbolId); if (symbol.Name == symbolName) { return(symbol); } } } } } return(null); }
/// <summary> /// Get names of Panel families and populate drop-down lists in the UI /// </summary> private void BuildPanelTypeList(ExternalCommandData commandData) { List <FamilyInstance> list = GetElements <FamilyInstance>(); if (list.Count == 0) { TaskDialog.Show("Revit", "There are no panel families loaded in your project"); btnCompute.Enabled = false; Close(); return; } FamilySymbol fs = commandData.Application.ActiveUIDocument.Document.GetElement(list[0].GetTypeId()) as FamilySymbol; string famDelimiter = ":"; foreach (Autodesk.Revit.DB.ElementId famSymbolId in fs.Family.GetFamilySymbolIds()) { Autodesk.Revit.DB.FamilySymbol famSymbol = (FamilySymbol)commandData.Application.ActiveUIDocument.Document.GetElement(famSymbolId); cboxMax.Items.Add(fs.Family.Name + famDelimiter + famSymbol.Name); cboxMin.Items.Add(fs.Family.Name + famDelimiter + famSymbol.Name); cboxMid.Items.Add(fs.Family.Name + famDelimiter + famSymbol.Name); } cboxMax.SelectedIndex = 0; cboxMin.SelectedIndex = 0; cboxMid.SelectedIndex = 0; }
void ReconstructAdaptiveComponentByPoints ( DB.Document doc, ref DB.Element element, IList <Rhino.Geometry.Point3d> points, DB.FamilySymbol type ) { var adaptivePoints = points.ConvertAll(GeometryEncoder.ToXYZ); if (!type.IsActive) { type.Activate(); } // Type ChangeElementTypeId(ref element, type.Id); if (element is DB.FamilyInstance instance && DB.AdaptiveComponentInstanceUtils.IsAdaptiveComponentInstance(instance)) { var adaptivePointIds = DB.AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(instance); if (adaptivePointIds.Count == adaptivePoints.Length) { int index = 0; foreach (var vertex in adaptivePointIds.Select(id => doc.GetElement(id)).Cast <DB.ReferencePoint>()) { vertex.Position = adaptivePoints[index++]; } return; } } { var creationData = new List <Autodesk.Revit.Creation.FamilyInstanceCreationData> { Revit.ActiveUIApplication.Application.Create.NewFamilyInstanceCreationData(type, adaptivePoints) }; var newElementIds = doc.IsFamilyDocument ? doc.FamilyCreate.NewFamilyInstances2(creationData) : doc.Create.NewFamilyInstances2(creationData); if (newElementIds.Count != 1) { doc.Delete(newElementIds); throw new InvalidOperationException(); } var parametersMask = new DB.BuiltInParameter[] { DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, DB.BuiltInParameter.ELEM_FAMILY_PARAM, DB.BuiltInParameter.ELEM_TYPE_PARAM }; ReplaceElement(ref element, doc.GetElement(newElementIds.First()), parametersMask); } }
/// <summary> /// Obtain a FamilyType by selection. /// </summary> /// <param name="familyType"></param> /// <param name="isRevitOwned"></param> /// <returns></returns> internal static FamilyType FromExisting(Autodesk.Revit.DB.FamilySymbol familyType, bool isRevitOwned) { return(new FamilyType(familyType) { IsRevitOwned = isRevitOwned }); }
/// <summary> /// Initialize a Sheet element with a name, number and specific titleblock. /// </summary> /// <param name="sheetName">name of the sheet.</param> /// <param name="sheetNumber">sheet number.</param> /// <param name="titleBlockFamilySymbol">sheet titleblock.</param> private void InitSheet(string sheetName, string sheetNumber, Autodesk.Revit.DB.FamilySymbol titleBlockFamilySymbol) { //Phase 1 - Check to see if the object exists var oldEle = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.ViewSheet>(Document); // Rebind to Element if (oldEle != null) { InternalSetViewSheet(oldEle); InternalSetSheetName(sheetName); InternalSetSheetNumber(sheetNumber); InternalSetTitleBlock(titleBlockFamilySymbol.Id); return; } //Phase 2 - There was no existing Element, create new one TransactionManager.Instance.EnsureInTransaction(Document); // create sheet with title block ID var sheet = Autodesk.Revit.DB.ViewSheet.Create(Document, titleBlockFamilySymbol.Id); InternalSetViewSheet(sheet); InternalSetSheetName(sheetName); InternalSetSheetNumber(sheetNumber); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(this.InternalElement); }
/// <summary> /// Dump properties specific to a decking layer /// </summary> /// <param name="deck"></param> private void DumbDeck(CompoundStructureLayer deck) { m_displayForm.WriteLine("Dumping Deck"); if (deck.MaterialId != ElementId.InvalidElementId) { // get the deck material object. In this sample all we need to display is the // name, but other properties are readily available from the material object. Autodesk.Revit.DB.Material deckMaterial = m_document.GetElement(deck.MaterialId) as Material; m_displayForm.WriteLine("Deck Material = " + deckMaterial.Name); } if (deck.DeckProfileId != ElementId.InvalidElementId) { // the deck profile is actually a family symbol from a family of profiles Autodesk.Revit.DB.FamilySymbol deckProfile = m_document.GetElement(deck.DeckProfileId) as FamilySymbol; // firstly display the full name as the user would see it in the user interface // this is done in the format Family.Name and then Symbol.Name m_displayForm.WriteLine("Deck Profile = " + deckProfile.Family.Name + " : " + deckProfile.Name); // the symbol object also contains parameters that describe how the deck is // specified. From these parameters an external application can generate // identical decking for analysis purposes DumpParameters(deckProfile); } }
void CommitInstance ( Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Curve curve, Autodesk.Revit.DB.FamilySymbol familySymbol, Autodesk.Revit.DB.Level level ) { var element = PreviousElement(doc, Iteration); if (!element?.Pinned ?? false) { ReplaceElement(doc, DA, Iteration, element); } else { try { var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { curve?.Scale(scaleFactor); } if ( curve == null || curve.IsShort(Revit.ShortCurveTolerance) || curve.IsClosed || !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance) || curve.GetNextDiscontinuity(Rhino.Geometry.Continuity.C1_continuous, curve.Domain.Min, curve.Domain.Max, out double discontinuity) ) { throw new Exception(string.Format("Parameter '{0}' must be a C1 continuous planar non closed curve.", Params.Input[0].Name)); } var axisList = curve.ToHost().ToList(); Debug.Assert(axisList.Count == 1); if (element is FamilyInstance && familySymbol.Id != element.GetTypeId()) { var newElmentId = element.ChangeTypeId(familySymbol.Id); if (newElmentId != ElementId.InvalidElementId) { element = doc.GetElement(newElmentId); } } if (element is FamilyInstance familyInstance && element.Location is LocationCurve locationCurve) { locationCurve.Curve = axisList[0]; } else { element = CopyParametersFrom(doc.Create.NewFamilyInstance(axisList[0], familySymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Beam), element); } ReplaceElement(doc, DA, Iteration, element); }
protected void InternalSetFamilySymbol(Autodesk.Revit.DB.FamilySymbol fs) { TransactionManager.Instance.EnsureInTransaction(Document); InternalFamilyInstance.Symbol = fs; TransactionManager.Instance.TransactionTaskDone(); }
internal static List <revitViewport> _renumberViewsOnSheet(FamilyType familyType, string xGridName, string yGridName, revitSheet rSheet, revitDoc document) { string transactionName = "Renumber views on sheet"; // Initialize variables revitFamilySymbol rFamilySymbol = (revitFamilySymbol)familyType.InternalElement; // Get all viewport ID's on the sheet. List <revitElemId> viewportIds = (List <revitElemId>)rSheet.GetAllViewports(); List <revitViewport> viewports = null; // Get the family Instances in view revitElemId symbolId = familyType.InternalElement.Id; revitCollector collector = new revitCollector(document, rSheet.Id); revitElementFilter filterInstance = new revitDB.FamilyInstanceFilter(document, symbolId); collector.OfClass(typeof(revitDB.FamilyInstance)).WherePasses(filterInstance); revitDB.FamilyInstance originFamily = (revitDB.FamilyInstance)collector.FirstElement(); // If family instance is found in the view // Then renumber views. if (originFamily != null) { revitDB.LocationPoint location = (revitDB.LocationPoint)originFamily.Location; revitXYZ originPoint = location.Point; double gridX = rFamilySymbol.LookupParameter(xGridName).AsDouble(); double gridY = rFamilySymbol.LookupParameter(yGridName).AsDouble(); // If the document is modifieable, // then a transaction is already open // and function uses the Dynamo Transaction Manager. // Else, open a new transaction. if (document.IsModifiable) { TransactionManager.Instance.EnsureInTransaction(document); viewports = View._tempRenumberViewports(viewportIds, document); viewports = View._renumberViewports(viewports, gridX, gridY, originPoint.X, originPoint.Y); TransactionManager.Instance.TransactionTaskDone(); } else { using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document)) { trans.Start(transactionName); viewports = View._tempRenumberViewports(viewportIds, document); viewports = View._renumberViewports(viewports, gridX, gridY, originPoint.X, originPoint.Y); trans.Commit(); } } } return(viewports); }
/// <summary> /// add one FamilySymbol object to the lists /// </summary> /// <param name="framingSymbol"></param> /// <returns></returns> public bool AddSymbol(Autodesk.Revit.DB.FamilySymbol framingSymbol) { if (ContainsSymbolName(framingSymbol.Name)) { return(false); } m_symbolMaps.Add(framingSymbol.Name, framingSymbol); m_symbols.Add(framingSymbol); return(true); }
public ApplicationPlaceholderObject AdaptiveComponentToNative(AdaptiveComponent speckleAc) { var docObj = GetExistingElementByApplicationId(speckleAc.applicationId); string familyName = speckleAc["family"] as string != null ? speckleAc["family"] as string : ""; DB.FamilySymbol familySymbol = GetElementType <DB.FamilySymbol>(speckleAc); DB.FamilyInstance revitAc = null; //try update existing if (docObj != null) { try { var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType; // if family changed, tough luck. delete and let us create a new one. if (familyName != revitType.FamilyName) { Doc.Delete(docObj.Id); } else { revitAc = (DB.FamilyInstance)docObj; // check for a type change if (speckleAc.type != null && speckleAc.type != revitType.Name) { revitAc.ChangeTypeId(familySymbol.Id); } } } catch { //something went wrong, re-create it } } //create family instance if (revitAc == null) { revitAc = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Doc, familySymbol); } SetAdaptivePoints(revitAc, speckleAc.basePoints); AdaptiveComponentInstanceUtils.SetInstanceFlipped(revitAc, speckleAc.flipped); SetInstanceParameters(revitAc, speckleAc); return(new ApplicationPlaceholderObject { applicationId = speckleAc.applicationId, ApplicationGeneratedId = revitAc.UniqueId, NativeObject = revitAc }); }
private void AddFamilySymbolParameters(FamilySymbol fs) { foreach (Parameter p in fs.Parameters) { if (p.IsReadOnly || p.StorageType == StorageType.None) { continue; } Items.Add( new DynamoDropDownItem( string.Format("{0}(Type)({1})", p.Definition.Name, getStorageTypeString(p.StorageType)), p.Definition.Name)); } }
/// <summary> /// Frame a Wall /// </summary> /// <param name="rvtApp">Revit application></param> /// <param name="wall">Wall as host to place column objects</param> /// <param name="spacing">spacing between two columns</param> /// <param name="columnType">column type</param> private void FrameWall(Autodesk.Revit.ApplicationServices.Application rvtApp, Autodesk.Revit.DB.Wall wall, double spacing, Autodesk.Revit.DB.FamilySymbol columnType) { Autodesk.Revit.DB.Document rvtDoc = wall.Document; // get wall location Autodesk.Revit.DB.LocationCurve loc = (Autodesk.Revit.DB.LocationCurve)wall.Location; Autodesk.Revit.DB.XYZ startPt = loc.Curve.GetEndPoint(0); Autodesk.Revit.DB.XYZ endPt = loc.Curve.GetEndPoint(1); // get wall's vector Autodesk.Revit.DB.UV wallVec = new Autodesk.Revit.DB.UV( endPt.X - startPt.X, endPt.Y - startPt.Y); // get the axis vector Autodesk.Revit.DB.UV axis = new Autodesk.Revit.DB.UV(1.0, 0.0); Autodesk.Revit.DB.ElementId baseLevelId = wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId(); Autodesk.Revit.DB.ElementId topLevelId = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId(); // get wall length and vector double wallLength = wallVec.GetLength(); wallVec = wallVec.Normalize(); // get # of column int nmax = (int)(wallLength / spacing); TaskDialog.Show("Revit", "wallLength = " + wallLength + "\r\nspacing = " + spacing.ToString() + "\r\nnmax = " + nmax.ToString()); // get angle of wall and axis double angle = wallVec.AngleTo(axis); // place all column Autodesk.Revit.DB.XYZ loc2 = startPt; double dx = wallVec.U * spacing; double dy = wallVec.V * spacing; for (int i = 0; i < nmax; i++) { PlaceColumn(rvtApp, rvtDoc, loc2, angle, columnType, baseLevelId, topLevelId); loc2 = new XYZ(loc2.X + dx, loc2.Y + dy, loc2.Z); } // place column at end point of wall PlaceColumn(rvtApp, rvtDoc, endPt, angle, columnType, baseLevelId, topLevelId); }
protected void InternalSetFamilySymbol(Autodesk.Revit.DB.FamilySymbol fs) { TransactionManager.Instance.EnsureInTransaction(Document); // Don't attempt to set the symbol if it is the same. // Doing so will raise a document modification event which // will, in turn, be responded to by this node causing an infinite loop. if (InternalFamilyInstance.Symbol.UniqueId != fs.UniqueId) { InternalFamilyInstance.Symbol = fs; } TransactionManager.Instance.TransactionTaskDone(); }
void CommitInstance ( Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Line line, Autodesk.Revit.DB.FamilySymbol familySymbol, Autodesk.Revit.DB.Level level ) { var element = PreviousElement(doc, Iteration); try { if (element?.Pinned ?? true) { var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { line = line.Scale(scaleFactor); } if (line.Length < Revit.ShortCurveTolerance) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is too short.", Params.Input[0].Name)); } else if (level == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is mandatory.", Params.Input[2].Name)); } else { if (element is FamilyInstance && familySymbol.Id != element.GetTypeId()) { var newElmentId = element.ChangeTypeId(familySymbol.Id); if (newElmentId != ElementId.InvalidElementId) { element = doc.GetElement(newElmentId); } } if (element is FamilyInstance familyInstance && element.Location is LocationCurve locationCurve) { locationCurve.Curve = line.ToHost(); } else { element = doc.Create.NewFamilyInstance(line.ToHost(), familySymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Column); } } }
void CommitInstance ( Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Curve curve, Autodesk.Revit.DB.FamilySymbol familySymbol, Autodesk.Revit.DB.Level level ) { var element = PreviousElement(doc, Iteration); try { if (element?.Pinned ?? true) { var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { curve?.Scale(scaleFactor); } if ( curve == null || curve.IsShort(Revit.ShortCurveTolerance) || curve.IsClosed || !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance) || curve.GetNextDiscontinuity(Rhino.Geometry.Continuity.C1_continuous, curve.Domain.Min, curve.Domain.Max, out double discontinuity) ) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' must be a C1 continuous planar non closed curve.", Params.Input[0].Name)); } else { var axisList = curve.ToHost().ToList(); Debug.Assert(axisList.Count == 1); if (axisPlane.Normal.IsParallelTo(Rhino.Geometry.Vector3d.ZAxis) != 0) { element = doc.Create.NewFamilyInstance(axisList[0], familySymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Beam); } else { element = doc.Create.NewFamilyInstance(axisList[0], familySymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Brace); } } } }
public Autodesk.Revit.DB.FamilySymbol GetFamilySymbol(Autodesk.Revit.DB.Document doc) { Autodesk.Revit.DB.FamilySymbol familySymbol = null; Autodesk.Revit.DB.FilteredElementCollector col = new Autodesk.Revit.DB.FilteredElementCollector(doc) .WherePasses(new Autodesk.Revit.DB.ElementClassFilter(typeof(Autodesk.Revit.DB.FamilySymbol))) .WherePasses(new Autodesk.Revit.DB.ElementCategoryFilter(BuiltInCategory.OST_Site)); foreach (var fs in col) { if (typeName == fs.Name) { familySymbol = fs as Autodesk.Revit.DB.FamilySymbol; } } return(familySymbol); }
/// <summary> /// /// </summary> /// <param name="sheetName"></param> /// <param name="sheetNumber"></param> /// <param name="titleBlockFamilySymbol"></param> /// <param name="views"></param> /// <param name="locations"></param> private void InitSheet(string sheetName, string sheetNumber, Autodesk.Revit.DB.FamilySymbol titleBlockFamilySymbol, IEnumerable <Autodesk.Revit.DB.View> views, IEnumerable <XYZ> locations) { //Phase 1 - Check to see if the object exists var oldEles = ElementBinder.GetElementsFromTrace <Autodesk.Revit.DB.ViewSheet>(Document); List <Autodesk.Revit.DB.Element> TraceElements = new List <Autodesk.Revit.DB.Element>(); List <Autodesk.Revit.DB.Viewport> BindingViewports = new List <Autodesk.Revit.DB.Viewport>(); if (ElementBinder.GetElementsFromTrace <Autodesk.Revit.DB.Viewport>(Document) != null) { BindingViewports.AddRange(ElementBinder.GetElementsFromTrace <Autodesk.Revit.DB.Viewport>(Document).ToList()); } // Rebind to Element if (oldEles != null && oldEles.Any()) { var oldEle = oldEles.First(); InternalSetViewSheet(oldEle); InternalSetSheetName(sheetName); InternalSetSheetNumber(sheetNumber); InternalSetTitleBlock(titleBlockFamilySymbol.Id); TraceElements.Add(oldEle); TraceElements.AddRange(InternalSetViewsToSheetView(views, locations, BindingViewports)); ElementBinder.SetElementsForTrace(TraceElements); return; } //Phase 2 - There was no existing Element, create new one TransactionManager.Instance.EnsureInTransaction(Document); // create sheet with title block ID var sheet = Autodesk.Revit.DB.ViewSheet.Create(Document, titleBlockFamilySymbol.Id); InternalSetViewSheet(sheet); InternalSetSheetName(sheetName); InternalSetSheetNumber(sheetNumber); TraceElements.Add(this.InternalElement); TraceElements.AddRange(InternalSetViewsToSheetView(views, locations, BindingViewports)); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementsForTrace(TraceElements); }
/// <summary> /// Initialize a FamilyInstance element /// </summary> private void InitFamilyInstance(Autodesk.Revit.DB.FamilySymbol fs, XYZ pos, Autodesk.Revit.DB.Level level) { //Phase 1 - Check to see if the object exists and should be rebound var oldFam = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document); //There was a point, rebind to that, and adjust its position if (oldFam != null) { InternalSetFamilyInstance(oldFam); InternalSetLevel(level); InternalSetFamilySymbol(fs); InternalSetPosition(pos); return; } //Phase 2- There was no existing point, create one TransactionManager.Instance.EnsureInTransaction(Document); //If the symbol is not active, then activate it if (!fs.IsActive) { fs.Activate(); } Autodesk.Revit.DB.FamilyInstance fi; if (Document.IsFamilyDocument) { fi = Document.FamilyCreate.NewFamilyInstance(pos, fs, level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); } else { fi = Document.Create.NewFamilyInstance( pos, fs, level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); } InternalSetFamilyInstance(fi); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(InternalElement); }
public Autodesk.Revit.DB.FamilyInstance CreateFromDTO(Document doc, JObject source) { Common.Models.FamilyInstance famI = source.ToObject <Common.Models.FamilyInstance>(); Autodesk.Revit.DB.XYZ newOrigin = new Autodesk.Revit.DB.XYZ(famI.Transform.Origin.X, famI.Transform.Origin.Y, famI.Transform.Origin.Z); Autodesk.Revit.DB.FamilySymbol fam = doc.GetElement(new ElementId(Int32.Parse(famI.FamilyId))) as Autodesk.Revit.DB.FamilySymbol; if (fam == null) { throw new Exception($"Failed to find family with id {famI.FamilyId}"); } Autodesk.Revit.DB.FamilyInstance newFamily; if (famI.HostId != null) { ElementId hostId = new ElementId(Int32.Parse(famI.HostId)); newFamily = doc.Create.NewFamilyInstance( newOrigin, fam, doc.GetElement(hostId), StructuralType.NonStructural ); } else { newFamily = doc.Create.NewFamilyInstance( newOrigin, fam, StructuralType.NonStructural ); } Autodesk.Revit.DB.Transform trans = newFamily.GetTransform(); double rotation = Math.Atan2(famI.Transform.BasisX.Y, famI.Transform.BasisX.X); Autodesk.Revit.DB.XYZ a1 = newOrigin; Autodesk.Revit.DB.XYZ a2 = new Autodesk.Revit.DB.XYZ(a1.X, a1.Y, a1.Z + 10); Line axis = Line.CreateBound(a1, a2); newFamily.Location.Rotate(axis, rotation); return(newFamily); }
void CommitInstance ( Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Line line, Autodesk.Revit.DB.FamilySymbol familySymbol, Autodesk.Revit.DB.Level level ) { var element = PreviousElement(doc, Iteration); try { if (element?.Pinned ?? true) { var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { line = line.Scale(scaleFactor); } if (line.Length < Revit.ShortCurveTolerance) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is too short.", Params.Input[0].Name)); } else if (level == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is mandatory.", Params.Input[2].Name)); } else { element = doc.Create.NewFamilyInstance(line.ToHost(), familySymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Column); } } } catch (Exception e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); } finally { ReplaceElement(doc, DA, Iteration, element); } }
protected override void TrySolveInstance(IGH_DataAccess DA) { // get input // panel types can be DB.FamilySymbol or DB.PanelType DB.FamilySymbol famInst = default; if (!DA.GetData("Curtain Grid Panel Type", ref famInst)) { return; } var inputType = famInst.GetType(); // make sure other derivatives of DB.FamilySymbol do not pass this filter // we are only interested in panel types if (inputType == typeof(DB.FamilySymbol) || inputType == typeof(DB.PanelType)) { // TODO: find a way to determine whether panel type is an Empty type or not // maybe the Id/Unique is fixed? Compare across multiple example models of various languages DA.SetData("Panel System Family", new Types.CurtainPanelSystemFamily(External.DB.CurtainPanelSystemFamily.Unknown)); switch (famInst) { case DB.PanelType panelType: PipeHostParameter(DA, panelType, DB.BuiltInParameter.CURTAIN_WALL_SYSPANEL_OFFSET, "Offset"); PipeHostParameter(DA, panelType, DB.BuiltInParameter.CURTAIN_WALL_SYSPANEL_THICKNESS, "Thickness"); break; case DB.FamilySymbol finst: // make sure family symbol belongs to a Panel Family // finst.Family.IsCurtainPanelFamily returns FALSE !!! var isCurtainPanelFamily = finst.Family.FamilyCategory.Id.IntegerValue == (int)DB.BuiltInCategory.OST_CurtainWallPanels; // can not extract Offset and Thickness since they are not builtin for curtain panel custom families // TODO: maybe extract other info for Panel Families?! break; } } }
public static Dictionary <string, object> InstanceByPointAndHost(Point point, FamilyType familyType, Element host) { AD.Document currentDBDocument = DocumentManager.Instance.CurrentDBDocument; AD.XYZ xYZ = GeometryPrimitiveConverter.ToXyz(point, true); AD.FamilySymbol familySymbol = (AD.FamilySymbol)(familyType.InternalElement); if (!familySymbol.IsActive) { familySymbol.Activate(); } AD.Element element = host.InternalElement; AD.Level level = element.Document.GetElement(element.LevelId) as AD.Level; TransactionManager.Instance.EnsureInTransaction(currentDBDocument); AD.FamilyInstance element2 = currentDBDocument.Create.NewFamilyInstance(xYZ, familySymbol, element, level, 0); var ele = element2.ToDSType(false); TransactionManager.Instance.TransactionTaskDone(); return(new Dictionary <string, object> { { "FamilyInstance", ele } }); }
FamilyInstanceCreationData CreateDefault(DB.Document doc, Plane location, DB.FamilySymbol type, Optional <DB.Level> level, DB.Element host) { if (host is null) { SolveOptionalLevel(doc, location.Origin, ref level, out var _); return(new FamilyInstanceCreationData ( location.Origin.ToXYZ(), type, level.Value, DB.Structure.StructuralType.NonStructural )); } else if (level.HasValue) { return(new FamilyInstanceCreationData ( location.Origin.ToXYZ(), type, host, level.Value, DB.Structure.StructuralType.NonStructural )); } else { return(new FamilyInstanceCreationData ( location.Origin.ToXYZ(), type, host, DB.Structure.StructuralType.NonStructural )); } }
//TODO: might need to clean this up and split the ConversionLog.Addic by beam, FI, etc... public List <ApplicationPlaceholderObject> FamilyInstanceToNative(BuiltElements.Revit.FamilyInstance speckleFi) { DB.FamilySymbol familySymbol = GetElementType <FamilySymbol>(speckleFi); XYZ basePoint = PointToNative(speckleFi.basePoint); DB.Level level = LevelToNative(speckleFi.level); DB.FamilyInstance familyInstance = null; var isUpdate = false; //try update existing var docObj = GetExistingElementByApplicationId(speckleFi.applicationId); if (docObj != null) { try { var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType; // if family changed, tough luck. delete and let us create a new one. if (familySymbol.FamilyName != revitType.FamilyName) { Doc.Delete(docObj.Id); } else { familyInstance = (DB.FamilyInstance)docObj; //NOTE: updating an element location is quite buggy in Revit! //Let's say the first time an element is created its base point/curve is @ 10m and the Level is @ 0m //the element will be created @ 0m //but when this element is updated (let's say with no changes), it will jump @ 10m (unless there is a level change)! //to avoid this behavior we're always setting the previous location Z coordinate when updating an element //this means the Z coord of an element will only be set by its Level //and by additional parameters as sill height, base offset etc (familyInstance.Location as LocationPoint).Point = new XYZ(basePoint.X, basePoint.Y, (familyInstance.Location as LocationPoint).Point.Z); // check for a type change if (speckleFi.type != null && speckleFi.type != revitType.Name) { familyInstance.ChangeTypeId(familySymbol.Id); } TrySetParam(familyInstance, BuiltInParameter.FAMILY_LEVEL_PARAM, level); TrySetParam(familyInstance, BuiltInParameter.FAMILY_BASE_LEVEL_PARAM, level); } isUpdate = true; } catch { //something went wrong, re-create it } } //create family instance if (familyInstance == null) { //If the current host element is not null, it means we're coming from inside a nested conversion. if (CurrentHostElement != null) { familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, CurrentHostElement, level, StructuralType.NonStructural); } //Otherwise, proceed as normal. else { familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, level, StructuralType.NonStructural); } } //required for face flipping to work! Doc.Regenerate(); if (familyInstance.CanFlipHand && speckleFi.handFlipped != familyInstance.HandFlipped) { familyInstance.flipHand(); } if (familyInstance.CanFlipFacing && speckleFi.facingFlipped != familyInstance.FacingFlipped) { familyInstance.flipFacing(); } // NOTE: do not check for the CanRotate prop as it doesn't work (at least on some families I tried)! // some point based families don't have a rotation, so keep this in a try catch try { if (speckleFi.rotation != (familyInstance.Location as LocationPoint).Rotation) { var axis = DB.Line.CreateBound(new XYZ(basePoint.X, basePoint.Y, 0), new XYZ(basePoint.X, basePoint.Y, 1000)); (familyInstance.Location as LocationPoint).Rotate(axis, speckleFi.rotation - (familyInstance.Location as LocationPoint).Rotation); } } catch { } SetInstanceParameters(familyInstance, speckleFi); var placeholders = new List <ApplicationPlaceholderObject>() { new ApplicationPlaceholderObject { applicationId = speckleFi.applicationId, ApplicationGeneratedId = familyInstance.UniqueId, NativeObject = familyInstance } }; Report.Log($"{(isUpdate ? "Updated" : "Created")} FamilyInstance ({familyInstance.Category.Name}) {familyInstance.Id}"); return(placeholders); }
private FamilyInstanceCreationData GetCreationData(Autodesk.Revit.DB.Curve curve, Autodesk.Revit.DB.XYZ upVector, Autodesk.Revit.DB.Level level, Autodesk.Revit.DB.Structure.StructuralType structuralType, Autodesk.Revit.DB.FamilySymbol symbol) { //calculate the desired rotation //we do this by finding the angle between the z axis //and vector between the start of the beam and the target point //both projected onto the start plane of the beam. var zAxis = new XYZ(0, 0, 1); var yAxis = new XYZ(0, 1, 0); //flatten the beam line onto the XZ plane //using the start's z coordinate var start = curve.GetEndPoint(0); var end = curve.GetEndPoint(1); var newEnd = new XYZ(end.X, end.Y, start.Z); //drop end point to plane //catch the case where the end is directly above //the start, creating a normal with zero length //in that case, use the Z axis XYZ planeNormal = newEnd.IsAlmostEqualTo(start) ? zAxis : (newEnd - start).Normalize(); double gamma = upVector.AngleOnPlaneTo(zAxis.IsAlmostEqualTo(planeNormal) ? yAxis : zAxis, planeNormal); return(new FamilyInstanceCreationData(curve, symbol, level, structuralType) { RotateAngle = gamma }); }
/// <summary> /// Internal constructor - creates a single StructuralFraming instance /// </summary> internal StructuralFraming(Autodesk.Revit.DB.Curve curve, Autodesk.Revit.DB.XYZ upVector, Autodesk.Revit.DB.Level level, Autodesk.Revit.DB.Structure.StructuralType structuralType, Autodesk.Revit.DB.FamilySymbol symbol) { //Phase 1 - Check to see if the object exists and should be rebound var oldFam = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document); //There was a point, rebind to that, and adjust its position if (oldFam != null) { InternalSetFamilyInstance(oldFam); InternalSetFamilySymbol(symbol); InternalSetCurve(curve); return; } //Phase 2- There was no existing point, create one TransactionManager.Instance.EnsureInTransaction(Document); var creationData = GetCreationData(curve, upVector, level, structuralType, symbol); Autodesk.Revit.DB.FamilyInstance fi; if (Document.IsFamilyDocument) { var elementIds = Document.FamilyCreate.NewFamilyInstances2(new List <FamilyInstanceCreationData>() { creationData }); if (elementIds.Count == 0) { throw new Exception("Could not create the FamilyInstance"); } fi = (Autodesk.Revit.DB.FamilyInstance)Document.GetElement(elementIds.First()); } else { var elementIds = Document.Create.NewFamilyInstances2(new List <FamilyInstanceCreationData>() { creationData }); if (elementIds.Count == 0) { throw new Exception("Could not create the FamilyInstance"); } fi = (Autodesk.Revit.DB.FamilyInstance)Document.GetElement(elementIds.First()); } InternalSetFamilyInstance(fi); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(this.InternalElement); }
void ReconstructFamilyInstanceByLocation ( DB.Document doc, ref DB.FamilyInstance element, [Description("Location where to place the element. Point or plane is accepted.")] Rhino.Geometry.Plane location, DB.FamilySymbol type, Optional <DB.Level> level, [Optional] DB.Element host ) { var scaleFactor = 1.0 / Revit.ModelUnits; location = location.ChangeUnits(scaleFactor); if (!location.IsValid) { ThrowArgumentException(nameof(location), "Should be a valid point or plane."); } SolveOptionalLevel(doc, location.Origin, ref level, out var bbox); if (host == null && type.Family.FamilyPlacementType == DB.FamilyPlacementType.OneLevelBasedHosted) { ThrowArgumentException(nameof(host), $"This family requires a host."); } if (!type.IsActive) { type.Activate(); } ChangeElementTypeId(ref element, type.Id); bool hasSameHost = false; if (element is DB.FamilyInstance) { hasSameHost = (element.Host?.Id ?? DB.ElementId.InvalidElementId) == (host?.Id ?? DB.ElementId.InvalidElementId); if (element.Host == null) { if (element?.get_Parameter(DB.BuiltInParameter.INSTANCE_FREE_HOST_PARAM) is DB.Parameter freeHostParam) { var freeHostName = freeHostParam.AsString(); hasSameHost = freeHostName.EndsWith(host?.Name ?? level.Value.Name); } } } if ( hasSameHost && element is DB.FamilyInstance && element.Location is DB.LocationPoint locationPoint ) { using (var levelParam = element.get_Parameter(DB.BuiltInParameter.FAMILY_LEVEL_PARAM)) { if (levelParam.AsElementId() != level.Value.Id) { levelParam.Set(level.Value.Id); doc.Regenerate(); } } if (host is object) { var newOrigin = location.Origin.ToHost(); if (!newOrigin.IsAlmostEqualTo(locationPoint.Point)) { element.Pinned = false; locationPoint.Point = newOrigin; element.Pinned = true; } } } else { var creationData = new List <Autodesk.Revit.Creation.FamilyInstanceCreationData>() { new Autodesk.Revit.Creation.FamilyInstanceCreationData(location.Origin.ToHost(), type, host, level.Value, DB.Structure.StructuralType.NonStructural) }; var newElementIds = doc.IsFamilyDocument ? doc.FamilyCreate.NewFamilyInstances2(creationData) : doc.Create.NewFamilyInstances2(creationData); if (newElementIds.Count != 1) { doc.Delete(newElementIds); throw new InvalidOperationException(); } var parametersMask = new DB.BuiltInParameter[] { DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, DB.BuiltInParameter.ELEM_FAMILY_PARAM, DB.BuiltInParameter.ELEM_TYPE_PARAM, DB.BuiltInParameter.FAMILY_LEVEL_PARAM }; ReplaceElement(ref element, doc.GetElement(newElementIds.First()) as DB.FamilyInstance, parametersMask); doc.Regenerate(); } if (element is object && element.Host is null) { element.Pinned = false; element.SetTransform(location.Origin.ToHost(), location.XAxis.ToHost(), location.YAxis.ToHost()); element.Pinned = true; } }
void ReconstructFamilyInstanceByPointAtHost ( Document doc, ref Autodesk.Revit.DB.Element element, Rhino.Geometry.Plane location, Autodesk.Revit.DB.FamilySymbol type, Optional <Autodesk.Revit.DB.Level> level, [Optional] Autodesk.Revit.DB.Element host ) { var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { location = location.Scale(scaleFactor); } if (!location.IsValid) { ThrowArgumentException(nameof(location), "Should be a valid point or plane."); } SolveOptionalLevel(ref level, doc, location.Origin.Z, nameof(level)); if (host == null && type.Family.FamilyPlacementType == FamilyPlacementType.OneLevelBasedHosted) { ThrowArgumentNullException(nameof(host), $"This family requires a host."); } if (!type.IsActive) { type.Activate(); } ChangeElementTypeId(ref element, type.Id); bool hasSameHost = false; if (element is FamilyInstance familyInstance) { hasSameHost = (familyInstance.Host?.Id ?? ElementId.InvalidElementId) == (host?.Id ?? ElementId.InvalidElementId); if (familyInstance.Host == null) { if (element?.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_PARAM) is Parameter freeHostParam) { var freeHostName = freeHostParam.AsString(); hasSameHost = freeHostName.EndsWith(host?.Name ?? level.Value.Name); } } } if ( hasSameHost && element is FamilyInstance && element.Location is LocationPoint locationPoint ) { using (var levelParam = element.get_Parameter(BuiltInParameter.FAMILY_LEVEL_PARAM)) { if (levelParam.AsElementId() != level.Value.Id) { levelParam.Set(level.Value.Id); doc.Regenerate(); } } var newOrigin = location.Origin.ToHost(); if (!newOrigin.IsAlmostEqualTo(locationPoint.Point)) { element.Pinned = false; locationPoint.Point = newOrigin; element.Pinned = true; } } else { var creationDataList = new List <Autodesk.Revit.Creation.FamilyInstanceCreationData>() { new Autodesk.Revit.Creation.FamilyInstanceCreationData(location.Origin.ToHost(), type, host, level.Value, Autodesk.Revit.DB.Structure.StructuralType.NonStructural) }; ICollection <ElementId> newElementIds = null; if (doc.IsFamilyDocument) { newElementIds = doc.FamilyCreate.NewFamilyInstances2(creationDataList); } else { newElementIds = doc.Create.NewFamilyInstances2(creationDataList); } if (newElementIds.Count != 1) { doc.Delete(newElementIds); throw new InvalidOperationException(); } var parametersMask = new BuiltInParameter[] { BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.ELEM_TYPE_PARAM, BuiltInParameter.FAMILY_LEVEL_PARAM }; ReplaceElement(ref element, doc.GetElement(newElementIds.First()), parametersMask); } if (element is FamilyInstance instance && instance.Host == null) { element.Pinned = false; SetTransform(instance, location.Origin.ToHost(), location.XAxis.ToHost(), location.YAxis.ToHost()); element.Pinned = true; } }