public static List <global::Revit.Elements.Room> CenterRoom(List <global::Revit.Elements.Room> room) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; foreach (var r in room) { Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)r.InternalElement; Autodesk.Revit.DB.Options geoOpts = new Autodesk.Revit.DB.Options(); var geo = internalRoom.get_Geometry(geoOpts); Autodesk.DesignScript.Geometry.Point centroid = geo.GetBoundingBox().ToProtoType(true).ToCuboid().Centroid(); Autodesk.DesignScript.Geometry.Point roomLocation = (Autodesk.DesignScript.Geometry.Point)r.GetLocation(); var newPoint = Autodesk.DesignScript.Geometry.Point.ByCoordinates(centroid.X, centroid.Y, roomLocation.Z); if (r.IsInsideRoom(newPoint)) { TransactionManager.Instance.EnsureInTransaction(doc); r.SetLocation(newPoint); TransactionManager.Instance.TransactionTaskDone(); } else { TransactionManager.Instance.EnsureInTransaction(doc); r.SetLocation(r.Location); TransactionManager.Instance.TransactionTaskDone(); } //dispose of the temp points centroid.Dispose(); roomLocation.Dispose(); newPoint.Dispose(); } return(room); }
public static List <Revit.Elements.Element> GetElementsByCategory(Revit.Elements.Element Room, Revit.Elements.Category category) { DB.Document doc = DocumentManager.Instance.CurrentDBDocument; ElementId categoryId = new ElementId(category.Id); DB.Category internalRevitCat = Autodesk.Revit.DB.Category.GetCategory(doc, categoryId); FilteredElementCollector collector = new FilteredElementCollector(doc); List <DB.Element> AllElementOfCategory = collector.OfCategoryId(internalRevitCat.Id).WhereElementIsNotElementType().ToElements().ToList(); DB.Element _room = (DB.Element)Room.InternalElement; DB.Architecture.Room room = _room as DB.Architecture.Room; List <Revit.Elements.Element> elems = new List <Revit.Elements.Element>(); List <Revit.Elements.Element> _elems = new List <Revit.Elements.Element>(); foreach (DB.Element element in AllElementOfCategory) { DB.FamilyInstance familyInstance = (DB.FamilyInstance)element; LocationPoint familyInstanceLocationPoint = familyInstance.Location as LocationPoint; XYZ point = familyInstanceLocationPoint.Point; if (room.IsPointInRoom(point)) { _elems.Add(element.ToDSType(true)); } } return(_elems); }
/// <summary> /// Create a space from an existing reference /// </summary> /// <param name="room"></param> /// <param name="isRevitOwned"></param> /// <returns></returns> internal static CustomRoom FromExisting(DB.Architecture.Room room, bool isRevitOwned) { return(new CustomRoom(room) { //IsRevitOwned = isRevitOwned }); }
/// <summary> /// Batch creation of Rooms /// </summary> /// <returns>If batch creation succeeds, return true; otherwise, return false</returns> private bool CreateRooms() { try { if (null == m_level) { return(false); } //Try to get Phase used to create Rooms Phase phase = (from elem in new FilteredElementCollector(m_doc).OfClass(typeof(Phase)).ToElements() select elem).First() as Phase; if (null == phase) { return(false); } for (int i = 1; i < 6; i++) { Autodesk.Revit.DB.UV point = new Autodesk.Revit.DB.UV(i * 10, 0); Autodesk.Revit.DB.UV tagPoint = new Autodesk.Revit.DB.UV(i * 10, 0); Autodesk.Revit.DB.Architecture.Room room = m_doc.Create.NewRoom(m_level, point); } } catch (Exception) { return(false); } return(true); }
private void updateGeometry(RoomObject ro, IList <RoomObject> allRooms, Phase roomPhase, Level refLevel) { // add all of the geometry info... Autodesk.Revit.DB.Architecture.Room r = ro.Document.GetElement(ro.Id) as Autodesk.Revit.DB.Architecture.Room; SpatialElementBoundaryOptions opts = new SpatialElementBoundaryOptions() { SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Center }; var segmentList = r.GetBoundarySegments(opts); foreach (BoundarySegment roomSeg in segmentList[0]) // outermost segment only! { Segment seg = new Segment() { Parent = ro, Element = roomSeg.ElementId }; fetchSegmentElemInfo(ro, roomSeg, refLevel, seg); ro.Boundaries.Add(seg); } calculateOppositeRooms(ro, allRooms, refLevel, roomPhase); }
internal static Room FromExisting(Autodesk.Revit.DB.Architecture.Room instance, bool isRevitOwned) { return(new Room(instance) { IsRevitOwned = isRevitOwned }); }
//Ist anders als in den vorherigen Versionen!! private static void update(ClassRoom _clr) { if (_clr != null) { try { bool worked; if (_clr.Id != null) { RevitRoom room = (RevitRoom)_doc.GetElement(_clr.Id); using (Transaction trans = new Transaction(_doc)) { if (trans.Start("Change Room Parameters") == TransactionStatus.Started) { room.Name = _clr.Bez; worked = room.GetParameters(typeofuse).First().Set(idenfifyTyp(_clr)); trans.Commit(); } } } } catch (Exception e) { TaskDialog.Show("RoomInfoUpdater", e.Message); } } else { TaskDialog.Show("RoomInfoUpdater", "Please select a Room!"); } }
public static global::Revit.Elements.Room CenterRoom2(global::Revit.Elements.Room room) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement; IEnumerable <IEnumerable <Autodesk.DesignScript.Geometry.Curve> > coreBoundary = room.CoreBoundary; List <Autodesk.DesignScript.Geometry.Point> pointList = new List <Autodesk.DesignScript.Geometry.Point>(); Polygon poly = null; foreach (IEnumerable <Autodesk.DesignScript.Geometry.Curve> curve in coreBoundary) { foreach (Autodesk.DesignScript.Geometry.Curve c in curve) { pointList.Add(c.StartPoint); } poly = Polygon.ByPoints(pointList); } if (room.IsInsideRoom(poly.Center())) { TransactionManager.Instance.EnsureInTransaction(doc); room.SetLocation(poly.Center()); TransactionManager.Instance.TransactionTaskDone(); } else { TransactionManager.Instance.EnsureInTransaction(doc); room.SetLocation(room.Location); TransactionManager.Instance.TransactionTaskDone(); } return(room); }
public RoomWithTransitLines(Autodesk.Revit.DB.Architecture.Room room) { RoomId = room.Id; LevelId = room.LevelId; Name = room.Number + ": " + room.Name; Lines = new List <TransitLine>(); }
/// <summary> /// Set the internal Element, ElementId, and UniqueId /// </summary> /// <param name="room"></param> private void InternalSetRoom(DB.Architecture.Room room) { InternalRoom = room; InternalElementId = room.Id; InternalUniqueId = room.UniqueId; InternalBoundarySegments = GetBoundarySegment(); InternalTransform = GetTransform(); }
public RoomInfo(Autodesk.Revit.DB.Architecture.Room room) { Name = room.Name; Coeff = 1; IsLive = true; roomIds = new List <Autodesk.Revit.DB.ElementId> { room.Id }; }
public ClassRoom parseRoom(RevitRoom room) { ClassRoom raum = new ClassRoom(); raum.RoomArea = squarefeetToMeter(room.Area); raum.RoomType = room.GetParameters("Nutzungsgruppe DIN 277-2")[0].AsString(); return(raum); }
private XYZ GetAptCentroid() { double x = 0, y = 0, z = 0; foreach (int id in m_iRoomId) { Room rm = m_doc.GetElement(new ElementId(id)) as Room; XYZ roomCntPnt = ((Autodesk.Revit.DB.LocationPoint)rm.Location).Point; x += roomCntPnt.X; y += roomCntPnt.Y; z = roomCntPnt.Z; } return(new XYZ(x / m_iRoomId.Count, y / m_iRoomId.Count, z)); }
internal void AddRoom(Room room) { if (!m_iRoomId.Contains(room.Id.IntegerValue)) { m_iRoomId.Add(room.Id.IntegerValue); } m_totalArea += room.Area; m_roomAreas.Add(room.Area); if (room.Number != "3") { m_totalAreaSansWetAreas += room.Area; } }
public static Room ToSpeckle(this Autodesk.Revit.DB.Architecture.Room myRoom) { var speckleRoom = new Room(); speckleRoom.roomName = myRoom.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.ROOM_NAME).AsString(); speckleRoom.roomNumber = myRoom.Number; var locPt = ((Autodesk.Revit.DB.LocationPoint)myRoom.Location).Point; speckleRoom.roomLocation = new SpecklePoint(locPt.X / Scale, locPt.Y / Scale, locPt.Z / Scale); (speckleRoom.Faces, speckleRoom.Vertices) = GetFaceVertexArrayFromElement(myRoom); // TODO: Get and set the boundary curve var seg = myRoom.GetBoundarySegments(new Autodesk.Revit.DB.SpatialElementBoundaryOptions()); var myPolyCurve = new SpecklePolycurve() { Segments = new List <SpeckleCore.SpeckleObject>() }; foreach (BoundarySegment segment in seg[0]) { var crv = segment.GetCurve(); var converted = SpeckleCore.Converter.Serialise(crv); myPolyCurve.Segments.Add(converted as SpeckleObject); } speckleRoom.baseCurve = myPolyCurve; speckleRoom.parameters = GetElementParams(myRoom); if (myRoom.IsValidType(myRoom.GetTypeId())) { speckleRoom.typeParameters = GetElementTypeParams(myRoom); } speckleRoom.ApplicationId = myRoom.UniqueId; speckleRoom.elementId = myRoom.Id.ToString(); speckleRoom.GenerateHash(); return(speckleRoom); }
public bool CanConvertToSpeckle(object @object) { return(@object switch { DB.DetailCurve _ => true, DB.DirectShape _ => true, DB.FamilyInstance _ => true, DB.Floor _ => true, DB.Level _ => true, DB.View _ => true, DB.ModelCurve _ => true, DB.Opening _ => true, DB.RoofBase _ => true, DB.Area _ => true, DB.Architecture.Room _ => true, DB.Architecture.TopographySurface _ => true, DB.Wall _ => true, DB.Mechanical.Duct _ => true, DB.Mechanical.Space _ => true, DB.Plumbing.Pipe _ => true, DB.Electrical.Wire _ => true, DB.CurtainGridLine _ => true, //these should be handled by curtain walls DB.Architecture.BuildingPad _ => true, DB.Architecture.Stairs _ => true, DB.Architecture.StairsRun _ => true, DB.Architecture.StairsLanding _ => true, DB.Architecture.Railing _ => true, DB.Architecture.TopRail _ => true, DB.Ceiling _ => true, DB.PointCloudInstance _ => true, DB.Group _ => true, DB.ProjectInfo _ => true, DB.ElementType _ => true, DB.Grid _ => true, DB.ReferencePoint _ => true, DB.Structure.AnalyticalModelStick _ => true, DB.Structure.AnalyticalModelSurface _ => true, DB.Structure.BoundaryConditions _ => true, _ => (@object as Element).IsElementSupported() });
internal int GetRoomIdContainingCentroid() { XYZ centroid = GetAptCentroid(); double distToClosestPnt = 100; Room outRoom = null; foreach (int id in m_iRoomId) { Room rm = m_doc.GetElement(new ElementId(id)) as Room; Autodesk.Revit.DB.LocationPoint currRoomCnt = rm.Location as Autodesk.Revit.DB.LocationPoint; if (centroid.DistanceTo(currRoomCnt.Point) < distToClosestPnt) { distToClosestPnt = centroid.DistanceTo(currRoomCnt.Point); outRoom = rm; } } return(outRoom.Id.IntegerValue); }
public static RevitElements.Element GetRoom(Revit.Elements.Element Element) { List <RevitElements.Element> result = new List <RevitElements.Element>(); DB.Document doc = DocumentManager.Instance.CurrentDBDocument; FilteredElementCollector collector = new FilteredElementCollector(doc); List <DB.Element> _rooms = collector.OfClass(typeof(DB.SpatialElement)).WhereElementIsNotElementType().Where(x => x.GetType() == typeof(DB.Architecture.Room)).ToList(); List <DB.Architecture.Room> rooms = _rooms.Select(r => r as DB.Architecture.Room).ToList(); DB.Element _element = (DB.Element)Element.InternalElement; DB.FamilyInstance familyInstance = (DB.FamilyInstance)Element.InternalElement; LocationPoint familyInstanceLocationPoint = familyInstance.Location as LocationPoint; XYZ point = familyInstanceLocationPoint.Point; DB.Architecture.Room room = rooms.Where(x => x.IsPointInRoom(point)).FirstOrDefault(); return(room.ToDSType(true)); }
public static List <Curve> IntersectWithCurve(global::Revit.Elements.Room room, Curve curve) { List <Curve> curveList = null; Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement; Autodesk.Revit.DB.GeometryElement roomGeometryElement = internalRoom.ClosedShell; foreach (GeometryObject geoObj in roomGeometryElement) { if (geoObj is Autodesk.Revit.DB.Solid) { Autodesk.Revit.DB.Solid geoSolid = geoObj as Autodesk.Revit.DB.Solid; Autodesk.Revit.DB.SolidCurveIntersection intersectingCurve = geoSolid.IntersectWithCurve(curve.ToRevitType(), new SolidCurveIntersectionOptions()); curveList = intersectingCurve.Select(c => c.ToProtoType()).ToList(); } } return(curveList); }
private RoomObject buildRoom(Autodesk.Revit.DB.Architecture.Room r) { RoomObject ro = new RoomObject() { Id = r.Id, Name = r.Name, Number = r.Number, Location = (r.Location as LocationPoint).Point }; ro.Document = r.Document; Parameter p = r.GetParameters(TypeParam).FirstOrDefault(); if (p != null) { ro.RoomType = p.AsString(); ro.LevelId = r.LevelId; //if (String.IsNullOrEmpty(ro.RoomType)) ro.RoomType = "<MISSING>"; if (ro.RoomType == null) { ro.RoomType = ""; } // lookup the score. RoomTypeConfig rtc = Configuration.RoomTypes.FirstOrDefault(c => c.TypeName.ToUpper().Trim() == ro.RoomType.ToUpper().Trim()); if (rtc != null) { ro.Score = rtc.Score; } else { ro.Score = 999; } } else { ro.RoomType = "<missing>"; } return(ro); }
public static Dictionary <string, List <Revit.Elements.Element> > GetToFromRoom(List <Revit.Elements.Element> FamilyInstance, Revit.Elements.Element Phase) { List <Revit.Elements.Element> toRooms = new List <Revit.Elements.Element>(); List <Revit.Elements.Element> fromRooms = new List <Revit.Elements.Element>(); ElementId phaseId = Spring.Elements.UnwrapElement(Phase); try { Autodesk.Revit.DB.Phase phase = DocumentManager.Instance.CurrentDBDocument.GetElement(phaseId) as Autodesk.Revit.DB.Phase; try { foreach (Revit.Elements.Element v in FamilyInstance) { ElementId elemId = Spring.Elements.UnwrapElement(v); Autodesk.Revit.DB.FamilyInstance elements = DocumentManager.Instance.CurrentDBDocument.GetElement(elemId) as Autodesk.Revit.DB.FamilyInstance; Autodesk.Revit.DB.Architecture.Room fromRoom = elements.get_FromRoom(phase); Autodesk.Revit.DB.Architecture.Room toRoom = elements.get_ToRoom(phase); toRooms.Add(toRoom.ToDSType(true)); fromRooms.Add(fromRoom.ToDSType(true)); } ; } catch (Exception ex) { toRooms.Add(null); fromRooms.Add(null); } } catch (Exception ex) { throw ex; } return(new Dictionary <string, List <Revit.Elements.Element> > { { "From Room", fromRooms }, { "To Room", toRooms } }); }
public static Room Wrap(Autodesk.Revit.DB.Architecture.Room ele, bool isRevitOwned) { return(Room.FromExisting(ele, isRevitOwned)); }
/// <summary> /// Set internal element /// </summary> private void InitElement(Autodesk.Revit.DB.Architecture.Room element) { InternalSetElement(element); }
/// <summary> /// Create from existing element /// </summary> /// <param name="Room"></param> internal Room(Autodesk.Revit.DB.Architecture.Room Room) { SafeInit(() => InitElement(Room)); }
/// <summary> /// Set the internal Element, ElementId, and UniqueId /// </summary> private void InternalSetElement(Autodesk.Revit.DB.Architecture.Room element) { InternalRevitElement = element; InternalElementId = element.Id; InternalUniqueId = element.UniqueId; }
private void calculateOppositeRooms(RoomObject ro, IList <RoomObject> allRooms, Level refLevel, Phase targetPhase) { foreach (var seg in ro.Boundaries) { Transform t = seg.Curve.ComputeDerivatives(0.5, true); XYZ alongDir = t.BasisX.Normalize(); XYZ normalDir = XYZ.BasisZ.CrossProduct(alongDir).Normalize(); seg.OutsideRoomVector = normalDir; // what room is outside? XYZ testPoint1 = t.Origin.Add(normalDir.Multiply(_outsideRoomTestDist)); XYZ testPoint2 = t.Origin.Add(normalDir.Negate().Multiply(_outsideRoomTestDist)); XYZ origin = t.Origin; if (ro.LevelId != refLevel.Id) { origin = new XYZ(t.Origin.X, t.Origin.Y, t.Origin.Z); } testPoint1 = new XYZ(testPoint1.X, testPoint1.Y, refLevel.ProjectElevation + 1.0); // one foot off the floor, just for safety... testPoint2 = new XYZ(testPoint2.X, testPoint2.Y, refLevel.ProjectElevation + 1.0); List <Document> all = new List <Document>(RoomDocs); all.Remove(ro.Document); all.Insert(0, ro.Document); // find the opposite room... Autodesk.Revit.DB.Architecture.Room opposite = null; foreach (Document testDoc in all) { var revitRoom1 = testDoc.GetRoomAtPoint(testPoint1, targetPhase); var revitRoom2 = testDoc.GetRoomAtPoint(testPoint2, targetPhase); if ((revitRoom1 != null) && (revitRoom2 != null)) { if ((revitRoom1.Id != ro.Id)) { opposite = revitRoom1; } if ((revitRoom2.Id != ro.Id)) { opposite = revitRoom2; seg.OutsideRoomVector = normalDir.Negate(); testPoint1 = testPoint2; // reset } } else { if (revitRoom1 != null) { seg.OutsideRoomVector = normalDir.Negate(); testPoint1 = testPoint2; } if (revitRoom2 != null) { // do nothing. } } if (opposite != null) { break; } } // Turn on for debugging line sides from rooms. //GeometryHelper.DrawLine(origin, testPoint1); if (opposite != null) { // see if we can find it in the room list. var match = allRooms.FirstOrDefault(r => r.Id == opposite.Id); if (match == null) { log("NOTE: Found a matching room for a segment in " + ro.Number + " that points to Room Num: " + opposite.Number + "(" + opposite.Id + ") but we don't have that in our list!?!"); } else { seg.OppositeRoom = match; } } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Add an EventLogTraceListener object System.Diagnostics.Trace.Listeners.Add( new System.Diagnostics.EventLogTraceListener("Application")); // Lay the hands on the active document UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; // Set up a timer Timing myTimer = new Timing(); myTimer.StartTime(); try { var flatsGroupedByFlatNo = new FilteredElementCollector(doc, doc.ActiveView.Id) .WherePasses(new Autodesk.Revit.DB.Architecture.RoomFilter()) .WhereElementIsNotElementType() .ToElements() .Cast <Room>() .GroupBy(rm => rm.LookupParameter(FLAT_NO_PARAM).AsString()); IList <Apartment> aptsOnFloor = new List <Apartment>(); StringBuilder strBld = new StringBuilder(); foreach (var grp in flatsGroupedByFlatNo) { string number = grp.Key; Apartment apt = new Apartment(doc, number); foreach (Room rm in grp) { apt.AddRoom(rm); } aptsOnFloor.Add(apt); strBld.AppendLine(apt.ToString()); } System.Diagnostics.Trace.Write(strBld.ToString()); using (Transaction t = new Transaction(doc, "Set Area Parameters")) { t.Start(); foreach (Apartment apt in aptsOnFloor) { foreach (int id in apt.GetIds()) { Room rm = doc.GetElement(new ElementId(id)) as Room; rm.LookupParameter(TOTAL_AREA_SAW) .Set(apt.AreaNoWetAreas); rm.LookupParameter(TOTAL_AREA_PARAM) .Set(apt.TotalArea); } } t.Commit(); } TaskDialog.Show("Success", "The task has been completed successfully."); return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { TaskDialog.Show("Exception", string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); System.Diagnostics.Trace.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } finally { myTimer.StopTime(); System.Diagnostics.Trace .Write(string.Format("Time elapsed: {0}s", myTimer.Duration.TotalSeconds)); } }
public static Dictionary <string, object> ByRoom(string familyTemplatePath, global::Revit.Elements.Room room, string materialName, global::Revit.Elements.Category category, string subcategory = "") { //variables global::Revit.Elements.Element famInstance = null; Autodesk.Revit.DB.FamilyInstance internalFam = null; bool fileFound = false; //the current document Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; UIApplication uiapp = new UIApplication(doc.Application); //convert the room to an Autodesk.Revit.DB representation Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement; string name = internalRoom.Name; //we close all of the families because we need to swap documents foreach (Document d in uiapp.Application.Documents) { if (d.IsFamilyDocument) { d.Close(false); } } //create the new family document in the background and store it in memory Document familyDocument = uiapp.Application.NewFamilyDocument(familyTemplatePath); //instantiate a material element id and try to get the material that was specified ElementId material = null; FilteredElementCollector materialCollector = new FilteredElementCollector(familyDocument).OfClass(typeof(Autodesk.Revit.DB.Material)); foreach (var m in materialCollector) { if (m.Name.ToLower().Replace(" ", "") == materialName.ToLower().Replace(" ", "")) { material = m.Id; } } //close Dynamo's open transaction, we need to do this because we open a new Revit API transaction in the family document (This is document switching) TransactionManager.Instance.ForceCloseTransaction(); //start creating the families. Transaction trans = new Transaction(familyDocument, "Generate Families Ya'll"); trans.Start(); //set the family category Autodesk.Revit.DB.Category familyCategory = familyDocument.Settings.Categories.get_Item(category.Name); familyDocument.OwnerFamily.FamilyCategory = familyCategory; //get the subcategory for the solids Autodesk.Revit.DB.Category subCategory = null; foreach (Autodesk.Revit.DB.Category c in familyCategory.SubCategories) { if (c.Name.ToLower() == subcategory.ToLower()) { subCategory = c; } } //get the height of the thing double height = room.Height; //get the curves IList <IList <BoundarySegment> > boundary = internalRoom.GetBoundarySegments(new SpatialElementBoundaryOptions()); //generate a plane Autodesk.Revit.DB.Plane revitPlane = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(Vector.ZAxis().ToXyz(), new XYZ(0, 0, 0)); Autodesk.Revit.DB.SketchPlane sketchPlane = SketchPlane.Create(familyDocument, revitPlane); //the curve arrays to generate solids and voids in family CurveArray curveArray = new CurveArray(); CurveArrArray curveArrArray = new CurveArrArray(); CurveArray curveArrayVoid = new CurveArray(); CurveArrArray curveArrArrayVoid = new CurveArrArray(); //to perform the cut action on the solid with the voids CombinableElementArray ceArray = new CombinableElementArray(); //transform bizness Point roomCentroid = room.BoundingBox.ToCuboid().Centroid(); Point locationPoint = Point.ByCoordinates(roomCentroid.X, roomCentroid.Y, 0); CoordinateSystem oldCS = CoordinateSystem.ByOrigin(locationPoint); CoordinateSystem newCS = CoordinateSystem.ByOrigin(0, 0, 0); //flag to step through the boundaries. int flag = 0; while (flag < boundary.Count) { //the first set of curves is the solid's boundary if (flag == 0) { //generate the solid form which is the first item in the boundary segments. foreach (BoundarySegment b in boundary[flag]) { Autodesk.DesignScript.Geometry.Curve c = b.GetCurve().ToProtoType(); Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve; curveArray.Append(movedCurve.ToRevitType()); } curveArrArray.Append(curveArray); Extrusion solidExtrusion = familyDocument.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height); if (material != null) { //Set the material Autodesk.Revit.DB.Parameter matParam = solidExtrusion.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM); matParam.Set(material); } //try to set the subcategory if (subCategory != null) { solidExtrusion.Subcategory = subCategory; } } //subsequent lists of curves are representative of the voids else { //clear the curves from the collection for all items after the second one. (index 2+) if (!curveArrayVoid.IsEmpty) { curveArrayVoid.Clear(); curveArrArrayVoid.Clear(); ceArray.Clear(); } //generate the void form foreach (BoundarySegment b in boundary[flag]) { Autodesk.DesignScript.Geometry.Curve c = b.GetCurve().ToProtoType(); Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve; curveArrayVoid.Append(movedCurve.ToRevitType()); } curveArrArrayVoid.Append(curveArrayVoid); Extrusion voidExtrusion = familyDocument.FamilyCreate.NewExtrusion(false, curveArrArrayVoid, sketchPlane, height); //try to combine things foreach (Extrusion genericForm in new FilteredElementCollector(familyDocument).OfClass(typeof(Extrusion)) .Cast <Extrusion>()) { ceArray.Append(genericForm); } //to add the void to the solid familyDocument.CombineElements(ceArray); } flag++; } familyDocument.Regenerate(); trans.Commit(); Autodesk.Revit.DB.Family fam = null; //build the temporary path string familyFilePath = Path.GetTempPath() + name + ".rfa"; SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; familyDocument.SaveAs(familyFilePath, opt); familyDocument.Close(false); TransactionManager.Instance.ForceCloseTransaction(); Transaction trans2 = new Transaction(doc, "Attempting to place or update Room family instances."); trans2.Start(); IFamilyLoadOptions loadOptions = new FamilyImportOptions(); bool variable = true; loadOptions.OnFamilyFound(true, out variable); doc.LoadFamily(familyFilePath, loadOptions, out fam); FamilySymbol familySymbol = (FamilySymbol)doc.GetElement(fam.GetFamilySymbolIds().First()); //try to find if it is placed already FilteredElementCollector col = new FilteredElementCollector(doc); //get built in category from user viewable category BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString()); foreach (Autodesk.Revit.DB.Element e in col.WhereElementIsNotElementType().OfCategory(myCatEnum).ToElements()) { Autodesk.Revit.DB.FamilySymbol type = (FamilySymbol)doc.GetElement(e.GetTypeId()); if (type.FamilyName.Equals(name)) { fileFound = true; internalFam = e as Autodesk.Revit.DB.FamilyInstance; } } //place families that are not placed if (fileFound == false) { if (!familySymbol.IsActive) { familySymbol.Activate(); } internalFam = doc.Create.NewFamilyInstance(new XYZ(roomCentroid.X, roomCentroid.Y, 0), familySymbol, internalRoom.Level, StructuralType.NonStructural); } trans2.Commit(); //delete the temp file File.Delete(familyFilePath); //cast to Dynamo type for output and location updating (if necessary) famInstance = internalFam.ToDSType(true); if (fileFound) { famInstance.SetLocation(locationPoint); } //returns the outputs var outInfo = new Dictionary <string, object> { { "familyInstance", famInstance } }; return(outInfo); }
public string getRoomName(Autodesk.Revit.DB.Architecture.Room room) { return(room.Name); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Add an EventLogTraceListener Trace.Listeners.Add(new EventLogTraceListener("Application")); // Gain access to the document UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new RoomSelectionFilter()); RvtRoom pickedRoom = doc.GetElement(r) as RvtRoom; RoomProperties window = new RoomProperties(); window.ShowDialog(); IDictionary <string, string> values = window.Values; if (values == null) { return(Result.Cancelled); } using (Transaction t = new Transaction(doc, "Name room")) { if (t.Start() == TransactionStatus.Started) { foreach (string key in values.Keys) { if (pickedRoom.LookupParameter(key) != null) { pickedRoom.LookupParameter(key).Set(values[key]); } } if (t.Commit() == TransactionStatus.Committed) { } else { t.RollBack(); TaskDialog.Show("Transaction Failed", "Name room transaction fell through."); } } else { TaskDialog.Show("Transaction Failed", "Name room transaction failed to start."); } } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { TaskDialog.Show("Command Exception", string.Format("{0}\n{1]", ex.Message, ex.StackTrace)); return(Result.Failed); } finally { } }