void f(Document doc) { // Before invoking this sample, select some walls // to add a roof over. Make sure there is a level // named "Roof" in the document. Level level = new FilteredElementCollector(doc) .OfClass(typeof(Level)) .Where <Element>(e => !string.IsNullOrEmpty(e.Name) && e.Name.Equals("Roof")) .FirstOrDefault <Element>() as Level; RoofType roofType = new FilteredElementCollector(doc) .OfClass(typeof(RoofType)) .FirstOrDefault <Element>() as RoofType; // Get the handle of the application Application application = doc.Application; // Define the footprint for the roof based on user selection CurveArray footprint = application.Create .NewCurveArray(); UIDocument uidoc = new UIDocument(doc); ICollection <ElementId> selectedIds = uidoc.Selection.GetElementIds(); if (selectedIds.Count != 0) { foreach (ElementId id in selectedIds) { Element element = doc.GetElement(id); Wall wall = element as Wall; if (wall != null) { LocationCurve wallCurve = wall.Location as LocationCurve; footprint.Append(wallCurve.Curve); continue; } ModelCurve modelCurve = element as ModelCurve; if (modelCurve != null) { footprint.Append(modelCurve.GeometryCurve); } } } else { throw new Exception( "Please select a curve loop, wall loop or " + "combination of walls and curves to " + "create a footprint roof."); } ModelCurveArray footPrintToModelCurveMapping = new ModelCurveArray(); FootPrintRoof footprintRoof = doc.Create.NewFootPrintRoof( footprint, level, roofType, out footPrintToModelCurveMapping); ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator(); iterator.Reset(); while (iterator.MoveNext()) { ModelCurve modelCurve = iterator.Current as ModelCurve; footprintRoof.set_DefinesSlope(modelCurve, true); footprintRoof.set_SlopeAngle(modelCurve, 0.5); } }
/// <summary> /// The construct of the FootPrintRoofLine class. /// </summary> /// <param name="roof">The footprint roof which the foot print data belong to.</param> /// <param name="curve">The model curve data which the foot print data stand for.</param> public FootPrintRoofLine(FootPrintRoof roof, ModelCurve curve) { m_roof = roof; m_curve = curve; m_boundingbox = m_roof.get_BoundingBox(Revit.SDK.Samples.NewRoof.CS.Command.ActiveView); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; try { Element tTypeElement = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(fsy => fsy is TrussType).ToList().FirstOrDefault(); if (tTypeElement == null) { message = "Nenhum tipo de treliça foi encontrada no projeto, por favor, carregue um tipo e rode este comando novamente"; return(Result.Failed); } TrussType tType = tTypeElement as TrussType; ISelectionFilter ridgeSelectionFilter = new RoofClasses.SelectionFilters.StraightLinesAndFacesRidgeSelectionFilter(doc); Reference currentReference = sel.PickObject(ObjectType.Edge, ridgeSelectionFilter); FootPrintRoof currentFootPrintRoof = doc.GetElement(currentReference) as FootPrintRoof; RoofClasses.EdgeInfo currentRidgeInfo = Support.GetMostSimilarEdgeInfo(currentReference, doc); if (currentRidgeInfo == null) { message = "Nenhuma linha inferior pode ser obtida a partir da seleção"; return(Result.Failed); } // #region DEBUG ONLY //#if DEBUG // using (Transaction ta = new Transaction(doc, "Line test")) // { // ta.Start(); // Frame fr = new Frame(currentRidgeInfo.Curve.Evaluate(0.5, true), XYZ.BasisX, XYZ.BasisY, XYZ.BasisZ); // SketchPlane skp = SketchPlane.Create(doc, Plane.Create(fr)); // doc.Create.NewModelCurve(currentRidgeInfo.Curve, skp); // ta.Commit(); // } //#endif // #endregion Line currentRidgeLine = currentRidgeInfo.Curve as Line; if (currentRidgeLine == null) { message = "Ridge must be a straight line"; return(Result.Failed); } ISelectionFilter currentTrussBaseSupportFilter = new RoofClasses.SelectionFilters.SupportsSelectionFilter(currentRidgeLine.Direction.CrossProduct(XYZ.BasisZ)); XYZ baseSupportPoint = null; try { Reference currentTrussBaseRef = sel.PickObject(ObjectType.Element, currentTrussBaseSupportFilter, "Selecione uma base para a treliça ou (ESC) para ignorar"); Element currentTrussBaseElem = doc.GetElement(currentTrussBaseRef.ElementId); //We can safely convert because the selection filter does not select anything that is not a curve locatated Curve currentElementCurve = (currentTrussBaseElem.Location as LocationCurve).Curve; if (currentRidgeLine != null) { if (currentElementCurve is Line) { Line currentSupportLine = currentElementCurve as Line; double height = currentRidgeInfo.GetCurrentRoofHeight(); currentRidgeLine = currentRidgeLine.Flatten(height); currentSupportLine = currentSupportLine.Flatten(height); IntersectionResultArray iResutArr = new IntersectionResultArray(); SetComparisonResult compResult = currentRidgeLine.Intersect(currentSupportLine, out iResutArr); if (iResutArr.Size == 1) { IntersectionResult iResult = iResutArr.get_Item(0); if (iResult != null) { baseSupportPoint = currentRidgeInfo.Curve.Project(iResult.XYZPoint).XYZPoint; } } } } } catch { } if (baseSupportPoint == null) { baseSupportPoint = currentRidgeLine.Project(currentReference.GlobalPoint).XYZPoint; } Managers.TrussRidgeManager currentTrussManager = new Managers.TrussRidgeManager(); Line currentSupport0ElemLine = null; Line currentSupport1ElemLine = null; currentTrussBaseSupportFilter = new RoofClasses.SelectionFilters.SupportsSelectionFilter(currentRidgeLine.Direction); if (currentRidgeInfo.RoofLineType == RoofClasses.RoofLineType.Ridge) { try { Reference currentSupport0Ref = sel.PickObject(ObjectType.Element, currentTrussBaseSupportFilter, "O primeiro suporte para a treliça"); Element currentSupport0Elem = doc.GetElement(currentSupport0Ref.ElementId); Curve currentSupport0ElemCurve = (currentSupport0Elem.Location as LocationCurve).Curve; currentSupport0ElemLine = currentSupport0ElemCurve as Line; Reference currentSupport1Ref = sel.PickObject(ObjectType.Element, currentTrussBaseSupportFilter, "O segundo suporte para a treliça"); Element currentSupport1Elem = doc.GetElement(currentSupport1Ref.ElementId); Curve currentSupport1ElemCurve = (currentSupport1Elem.Location as LocationCurve).Curve; currentSupport1ElemLine = currentSupport1ElemCurve as Line; } catch { currentSupport0ElemLine = null; currentSupport1ElemLine = null; } } else if (currentRidgeInfo.RoofLineType == RoofClasses.RoofLineType.RidgeSinglePanel) { try { Reference currentSupport0Ref = sel.PickObject(ObjectType.Element, currentTrussBaseSupportFilter, "O suporte para a treliça"); Element currentSupport0Elem = doc.GetElement(currentSupport0Ref.ElementId); Curve currentSupport0ElemCurve = (currentSupport0Elem.Location as LocationCurve).Curve; currentSupport0ElemLine = currentSupport0ElemCurve as Line; } catch { currentSupport0ElemLine = null; } } RoofClasses.TrussInfo currentTrussInfo = currentTrussManager.CreateTrussFromRidgeWithSupports(baseSupportPoint, currentRidgeInfo, tType, currentSupport0ElemLine, currentSupport1ElemLine); //#region DEBUG ONLY //if (currentReference != null) // DEBUG.CreateDebugPoint(doc, baseSupportPoint); //#endregion } catch (Exception e) { if (!(e is Autodesk.Revit.Exceptions.OperationCanceledException)) { throw e; } } return(Result.Succeeded); }
/// <summary> /// Aplies the slope in a determined FootPrintRoof. /// </summary> /// <param name="overhang">The overhang value.</param> /// <param name="slope">The slope of the roof</param> /// <param name="slopeDirection">The vector that represents the directions that the slope should be applied.</param> /// <param name="footPrintRoof">The Roof</param> /// <param name="footPrintToModelCurveMapping">The ModelCurveArray generated with the roof instance.</param> private static void ApplySlope(double overhang, double slope, XYZ slopeDirection, FootPrintRoof footPrintRoof, ModelCurveArray footPrintToModelCurveMapping) { ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator(); iterator.Reset(); while (iterator.MoveNext()) { ModelCurve modelCurve = iterator.Current as ModelCurve; Curve curve = modelCurve.GeometryCurve; XYZ curveDirection = VectorManipulator.GetCurveDirection(curve); if (curveDirection.DotProduct(slopeDirection) == 0) { footPrintRoof.set_DefinesSlope(modelCurve, true); footPrintRoof.set_SlopeAngle(modelCurve, slope); } double elevation = -(overhang - UnitUtils.ConvertToInternalUnits(0.1, UnitTypeId.Meters)) / 3; footPrintRoof.set_Offset(modelCurve, elevation); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { try { WaitCursor waitCursor = new WaitCursor(); UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; Autodesk.Revit.Creation.Application createApp = app.Application.Create; Autodesk.Revit.Creation.Document createDoc = doc.Create; using (Transaction t = new Transaction(doc)) { t.Start("Create Little House"); // Determine the four corners of the rectangular house: double width = 7 * LabConstants.MeterToFeet; double depth = 4 * LabConstants.MeterToFeet; List <XYZ> corners = new List <XYZ>(4); corners.Add(XYZ.Zero); corners.Add(new XYZ(width, 0, 0)); corners.Add(new XYZ(width, depth, 0)); corners.Add(new XYZ(0, depth, 0)); #region Test creating two levels #if CREATE_TWO_LEVELS Level levelBottom = null; Level levelMiddle = null; Level levelTop = null; List <Element> levels = new List <Element>(); Filter filterType = createApp.Filter.NewTypeFilter( typeof(Level)); doc.get_Elements(filterType, levels); foreach (Element e in levels) { if (null == levelBottom) { levelBottom = e as Level; } else if (null == levelMiddle) { levelMiddle = e as Level; } else if (null == levelTop) { levelTop = e as Level; } else { break; } } BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE; Line line; Wall wall; Parameter param; ElementId topId = levelMiddle.Id; List <Wall> walls = new List <Wall>(8); for (int i = 0; i < 4; ++i) { line = createApp.NewLineBound( corners[i], corners[3 == i ? 0 : i + 1]); wall = createDoc.NewWall( line, levelBottom, false); param = wall.get_Parameter(topLevelParam); param.Set(ref topId); walls.Add(wall); } topId = levelTop.Id; for (int i = 0; i < 4; ++i) { line = createApp.NewLineBound( corners[i], corners[3 == i ? 0 : i + 1]); wall = createDoc.NewWall( line, levelMiddle, false); param = wall.get_Parameter(topLevelParam); param.Set(ref topId); walls.Add(wall); } List <Element> doorSymbols = LabUtils.GetAllFamilySymbols( app, BuiltInCategory.OST_Doors); Debug.Assert( 0 < doorSymbols.Count, "expected at least one door symbol" + " to be loaded into project"); FamilySymbol door = doorSymbols[0] as FamilySymbol; XYZ midpoint = LabUtils.Midpoint( corners[0], corners[1]); FamilyInstance inst0 = createDoc.NewFamilyInstance( midpoint, door, walls[0], levelBottom, StructuralType.NonStructural); midpoint.Z = levelMiddle.Elevation; FamilyInstance inst1 = createDoc.NewFamilyInstance( midpoint, door, walls[4], levelMiddle, StructuralType.NonStructural); #endif // CREATE_TWO_LEVELS #endregion // Test creating two levels // Determine the levels where the walls will be located: Level levelBottom = null; Level levelTop = null; if (!LabUtils.GetBottomAndTopLevels(doc, ref levelBottom, ref levelTop)) { message = "Unable to determine wall bottom and top levels"; return(Result.Failed); } Debug.Print(string.Format("Drawing walls on '{0}' up to '{1}'", levelBottom.Name, levelTop.Name)); // Create the walls: BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE; ElementId levelBottomId = levelBottom.Id; ElementId topLevelId = levelTop.Id; List <Wall> walls = new List <Wall>(4); for (int i = 0; i < 4; ++i) { Line line = Line.CreateBound(corners[i], corners[3 == i ? 0 : i + 1]); //Wall wall = createDoc.NewWall( line, levelBottom, false ); // 2012 Wall wall = Wall.Create(doc, line, levelBottomId, false); // 2013 Parameter param = wall.get_Parameter(topLevelParam); param.Set(topLevelId); walls.Add(wall); } // Determine wall thickness for tag offset and profile growth: //double wallThickness = walls[0].WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011 //double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012 double wallThickness = walls[0].WallType.Width; // simpler and more direct property available in 2012 // Add door and windows to the first wall; // note that the NewFamilyInstance() api method does not automatically add door // and window tags, like the ui command does. we add tags here by making additional calls // to NewTag(): FamilySymbol door = LabUtils.GetFirstFamilySymbol(doc, BuiltInCategory.OST_Doors); if (null == door) { LabUtils.InfoMsg("No door symbol found."); return(Result.Failed); } FamilySymbol window = LabUtils.GetFirstFamilySymbol( doc, BuiltInCategory.OST_Windows); if (null == window) { LabUtils.InfoMsg("No window symbol found."); return(Result.Failed); } XYZ midpoint = LabUtils.Midpoint(corners[0], corners[1]); XYZ p = LabUtils.Midpoint(corners[0], midpoint); XYZ q = LabUtils.Midpoint(midpoint, corners[1]); double tagOffset = 3 * wallThickness; //double windowHeight = 1 * LabConstants.MeterToFeet; double windowHeight = levelBottom.Elevation + 0.3 * ( levelTop.Elevation - levelBottom.Elevation); p = new XYZ(p.X, p.Y, windowHeight); q = new XYZ(q.X, q.Y, windowHeight); View view = doc.ActiveView; door.Activate(); // 2016 FamilyInstance inst = createDoc.NewFamilyInstance( midpoint, door, walls[0], levelBottom, StructuralType.NonStructural); midpoint += tagOffset * XYZ.BasisY; //IndependentTag tag = createDoc.NewTag( // view, inst, false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.Horizontal, midpoint ); // 2017 IndependentTag tag = IndependentTag.Create( doc, view.Id, new Reference(inst), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midpoint); // 2018 IList <FamilyPointPlacementReference> fpprefs = inst.GetFamilyPointPlacementReferences(); IList <Reference> refs = inst.GetReferences(FamilyInstanceReferenceType.CenterLeftRight); //IndependentTag tag = IndependentTag.Create( doc, // view.Id, refs[0], false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.Horizontal, midpoint ); // 2018 window.Activate(); // 2016 inst = createDoc.NewFamilyInstance(p, window, walls[0], levelBottom, StructuralType.NonStructural); p += tagOffset * XYZ.BasisY; //tag = createDoc.NewTag( view, inst, // false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.Horizontal, p ); // 2017 tag = IndependentTag.Create( doc, view.Id, new Reference(inst), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, p); // 2018 inst = createDoc.NewFamilyInstance(q, window, walls[0], levelBottom, StructuralType.NonStructural); q += tagOffset * XYZ.BasisY; //tag = createDoc.NewTag( view, inst, // false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.TAG_HORIZONTAL, q ); // 2011 //tag = createDoc.NewTag( view, inst, // false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.Horizontal, q ); // 2012 tag = IndependentTag.Create( doc, view.Id, new Reference(inst), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, p); // 2018 // Grow the profile out by half the wall thickness, // so the floor and roof do not stop halfway through the wall: double w = 0.5 * wallThickness; corners[0] -= w * (XYZ.BasisX + XYZ.BasisY); corners[1] += w * (XYZ.BasisX - XYZ.BasisY); corners[2] += w * (XYZ.BasisX + XYZ.BasisY); corners[3] -= w * (XYZ.BasisX - XYZ.BasisY); CurveArray profile = new CurveArray(); for (int i = 0; i < 4; ++i) { //Line line = createApp.NewLineBound( // 2013 Line line = Line.CreateBound( // 2014 corners[i], corners[3 == i ? 0 : i + 1]); profile.Append(line); } // Add a floor, a roof and the roof slope: bool structural = false; Floor floor = createDoc.NewFloor( profile, structural); List <Element> roofTypes = new List <Element>( LabUtils.GetElementsOfType( doc, typeof(RoofType), BuiltInCategory.OST_Roofs)); Debug.Assert(0 < roofTypes.Count, "expected at least one roof type" + " to be loaded into project"); // Ensure that we get a valid roof type. // In Revit 2013, the first one encountered // is sloped glazing with zero entries in // its compound layers; actually, the entire // compound structure is null: //RoofType roofType = null; //foreach( RoofType rt in roofTypes ) //{ // CompoundStructure cs = rt.GetCompoundStructure(); // if( null != cs // && 0 < cs.GetLayers().Count ) // { // roofType = rt; // break; // } //} RoofType roofType = roofTypes .Cast <RoofType>() .FirstOrDefault <RoofType>(typ => null != typ.GetCompoundStructure()); ModelCurveArray modelCurves = new ModelCurveArray(); FootPrintRoof roof = createDoc.NewFootPrintRoof(profile, levelTop, roofType, out modelCurves); // Regenerate the model after roof creation, // otherwise the calls to set_DefinesSlope and // set_SlopeAngle throw the exception "Unable // to access curves from the roof sketch." doc.Regenerate(); // The argument to set_SlopeAngle is NOT an // angle, it is really a slope, i.e. relation // of height to distance, e.g. 0.5 = 6" / 12", // 0.75 = 9" / 12", etc. double slope = 0.3; foreach (ModelCurve curve in modelCurves) { roof.set_DefinesSlope(curve, true); roof.set_SlopeAngle(curve, slope); } // Add a room and a room tag: Room room = createDoc.NewRoom(levelBottom, new UV(0.5 * width, 0.5 * depth)); //RoomTag roomTag = createDoc.NewRoomTag( // room, new UV( 0.5 * width, 0.7 * depth ), // null ); // 2014 RoomTag roomTag = createDoc.NewRoomTag( new LinkElementId(room.Id), new UV(0.5 * width, 0.7 * depth), null); // 2015 //doc.AutoJoinElements(); // todo: remove this, the transaction should perform this automatically //LabUtils.InfoMsg( "Little house was created successfully." ); //#region Test setting BaseOffset and LimitOffset //// 11334196 [Failed to set Room.BaseOffset and Room.LimitOffset properties] //double h = 0.123; //room.BaseOffset = -h; //room.LimitOffset = h + h; //#endregion // Test setting BaseOffset and LimitOffset t.Commit(); return(Result.Succeeded); } } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
private void SetParameters(FootPrintRoof roof, IEnumerable<RevitParameter> parameters, Document doc) { foreach (RevitParameter rp in parameters) { try { Parameter p = roof.LookupParameter(rp.ParameterName); switch (rp.StorageType) { case "Double": if (p.Definition.ParameterType == ParameterType.Area) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT)); else if (p.Definition.ParameterType == ParameterType.Volume) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT)); else if (p.Definition.ParameterType == ParameterType.Length) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT)); else p.Set(Convert.ToDouble(rp.Value)); break; case "Integer": p.Set(Convert.ToInt32(rp.Value)); break; case "String": p.Set(rp.Value); break; case "ElementId": try { int idInt = Convert.ToInt32(rp.Value); ElementId elemId = new ElementId(idInt); Element elem = doc.GetElement(elemId); if (elem != null) { //TaskDialog.Show("Test:", "Param: " + p.Definition.Name + "\nID: " + elemId.IntegerValue.ToString()); p.Set(elemId); } } catch { try { p.Set(p.Definition.ParameterType == ParameterType.Material ? GetMaterial(rp.Value, doc) : new ElementId(Convert.ToInt32(rp.Value))); } catch (Exception ex) { //TaskDialog.Show(p.Definition.Name, ex.Message); } } break; default: p.Set(rp.Value); break; } } catch { try { Parameter p = roof.RoofType.LookupParameter(rp.ParameterName); switch (rp.StorageType) { case "Double": if (p.Definition.ParameterType == ParameterType.Area) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT)); else if (p.Definition.ParameterType == ParameterType.Volume) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT)); else if (p.Definition.ParameterType == ParameterType.Length) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT)); else p.Set(Convert.ToDouble(rp.Value)); break; case "Integer": p.Set(Convert.ToInt32(rp.Value)); break; case "String": p.Set(rp.Value); break; case "ElementId": try { int idInt = Convert.ToInt32(rp.Value); ElementId elemId = new ElementId(idInt); Element elem = doc.GetElement(elemId); if (elem != null) { //TaskDialog.Show("Test:", "Param: " + p.Definition.Name + "\nID: " + elemId.IntegerValue.ToString()); p.Set(elemId); } } catch { try { p.Set(p.Definition.ParameterType == ParameterType.Material ? GetMaterial(rp.Value, doc) : new ElementId(Convert.ToInt32(rp.Value))); } catch (Exception ex) { //TaskDialog.Show(p.Definition.Name, ex.Message); } } break; default: p.Set(rp.Value); break; } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } } } }
public void AddRoof(Document rvtDoc, List <Wall> walls) { // Hardcoding the roof type we will use. // e.g., "Basic Roof: Generic - 400mm" const string roofFamilyName = "Basic Roof"; const string roofTypeName = "Generic - 9\""; const string roofFamilyAndTypeName = roofFamilyName + ": " + roofTypeName; // Find the roof type RoofType roofType = (RoofType)ElementFiltering.FindFamilyType( rvtDoc, typeof(RoofType), roofFamilyName, roofTypeName, null); if (roofType == null) { TaskDialog.Show( "Add roof", "Cannot find (" + roofFamilyAndTypeName + "). Maybe you use a different template? Try with DefaultMetric.rte."); } /* * Wall thickness to adjust the footprint of the walls * to the outer most lines. * Note: This may not be the best way, * but we will live with this excercise. * DIM wallThickness as Double */ double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; double dt = wallThickness / 2.0; List <XYZ> dts = new List <XYZ>(5); dts.Add(new XYZ(-dt, -dt, 0.0)); dts.Add(new XYZ(dt, -dt, 0.0)); dts.Add(new XYZ(dt, dt, 0.0)); dts.Add(new XYZ(-dt, dt, 0.0)); dts.Add(dts[0]); // set the profile from four wals CurveArray footPrint = new CurveArray(); for (int i = 0; i <= 3; i++) { LocationCurve locCurve = (LocationCurve)walls[i].Location; XYZ pt1 = locCurve.Curve.GetEndPoint(0) + dts[i]; XYZ pt2 = locCurve.Curve.GetEndPoint(1) + dts[i + 1]; Line line = Line.CreateBound(pt1, pt2); footPrint.Append(line); } ///////////////////////////////////////////////// ///new mapping ///////////////////////////////////////////////// Curve getCurveOne = footPrint.get_Item(1); Curve getCurveTwo = footPrint.get_Item(3); CurveArray gabledFootprint = new CurveArray(); gabledFootprint.Append(getCurveOne); gabledFootprint.Append(getCurveTwo); // get the lvl2 from wall ElementId idlvl2 = walls[0].get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId(); Level lvl2 = rvtDoc.GetElement(idlvl2) as Level; ModelCurveArray mapping = new ModelCurveArray(); // footprint to model curve mapping FootPrintRoof aRoof = rvtDoc.Create.NewFootPrintRoof(footPrint, lvl2, roofType, out mapping); //double offsetValue = 10; foreach /*set the slope */ (ModelCurve modelCurve in mapping) { aRoof.set_DefinesSlope(modelCurve, true); aRoof.set_SlopeAngle(modelCurve, 0.5); //aRoof.set_Offset(modelCurve, offsetValue); } /* performed automatically by transaction commit. * rvtDoc.Regenerate(); * rvtDoc.AutoJoinElement(); */ }
private void SetParameters(FootPrintRoof roof, IEnumerable<RevitParameter> parameters, Document doc) { foreach (RevitParameter rp in parameters) { try { Parameter p = roof.get_Parameter(rp.ParameterName); switch (rp.StorageType) { case "Double": if (p.Definition.ParameterType == ParameterType.Area) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT)); else if (p.Definition.ParameterType == ParameterType.Volume) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT)); else if (p.Definition.ParameterType == ParameterType.Length) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT)); else p.Set(Convert.ToDouble(rp.Value)); break; case "Integer": p.Set(Convert.ToInt32(rp.Value)); break; case "String": p.Set(rp.Value); break; case "ElementId": if (p.Definition.ParameterType == ParameterType.Material) p.Set(GetMaterial(rp.Value, doc)); else p.Set(new ElementId(Convert.ToInt32(rp.Value))); break; default: p.Set(rp.Value); break; } } catch { try { Parameter p = roof.RoofType.get_Parameter(rp.ParameterName); switch (rp.StorageType) { case "Double": if (p.Definition.ParameterType == ParameterType.Area) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT)); else if (p.Definition.ParameterType == ParameterType.Volume) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT)); else if (p.Definition.ParameterType == ParameterType.Length) p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT)); else p.Set(Convert.ToDouble(rp.Value)); break; case "Integer": p.Set(Convert.ToInt32(rp.Value)); break; case "String": p.Set(rp.Value); break; case "ElementId": if (p.Definition.ParameterType == ParameterType.Material) p.Set(GetMaterial(rp.Value, doc)); else p.Set(new ElementId(Convert.ToInt32(rp.Value))); break; default: p.Set(rp.Value); break; } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } } } }
/// <summary> /// The construct of the FootPrintRoofWrapper class. /// </summary> /// <param name="roof">The footprint roof which will be edited in a PropertyGrid.</param> public FootPrintRoofWrapper(FootPrintRoof roof) { m_roof = roof; m_roofLines = new List<FootPrintRoofLine>(); ModelCurveArrArray curveloops = m_roof.GetProfiles(); foreach(ModelCurveArray curveloop in curveloops) { foreach(ModelCurve curve in curveloop) { m_roofLines.Add(new FootPrintRoofLine(m_roof, curve)); } } FootPrintRoofLineConverter.SetStandardValues(m_roofLines); m_footPrintLine = m_roofLines[0]; m_boundingbox = m_roof.get_BoundingBox(Revit.SDK.Samples.NewRoof.CS.Command.ActiveView); }
protected AGCRoofBase(FootPrintRoof elem) : base(elem) { }
/// <summary> /// Add a roof over the rectangular profile of the walls we created earlier. /// </summary> public static void AddRoof(Document rvtDoc, List <Wall> walls) { // Hard coding the roof type we will use. // e.g., "Basic Roof: Generic - 400mm" const string roofFamilyName = "Basic Roof"; const string roofTypeName = Util.Constant.RoofTypeName; const string roofFamilyAndTypeName = roofFamilyName + ": " + roofTypeName; // Find the roof type RoofType roofType = ElementFiltering.FindFamilyType( rvtDoc, typeof(RoofType), roofFamilyName, roofTypeName, null ) as RoofType; if (roofType == null) { TaskDialog.Show( "Add roof", "Cannot find (" + roofFamilyAndTypeName + "). Maybe you use a different template? Try with DefaultMetric.rte."); } // Wall thickness to adjust the footprint of the walls // to the outer most lines. // Note: this may not be the best way. // but we will live with this for this exercise. //Dim wallThickness As Double = _ //walls(0).WallType.CompoundStructure.Layers.Item(0).Thickness() ' 2011 double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012 double dt = wallThickness / 2.0; List <XYZ> dts = new List <XYZ>(5); dts.Add(new XYZ(-dt, -dt, 0.0)); dts.Add(new XYZ(dt, -dt, 0.0)); dts.Add(new XYZ(dt, dt, 0.0)); dts.Add(new XYZ(-dt, dt, 0.0)); dts.Add(dts[0]); // Set the profile from four walls CurveArray footPrint = new CurveArray(); for (int i = 0; i <= 3; i++) { LocationCurve locCurve = (LocationCurve)walls[i].Location; XYZ pt1 = locCurve.Curve.GetEndPoint(0) + dts[i]; XYZ pt2 = locCurve.Curve.GetEndPoint(1) + dts[i + 1]; Line line = Line.CreateBound(pt1, pt2); footPrint.Append(line); } // Get the level2 from the wall. ElementId idLevel2 = walls[0].get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId(); //Level level2 = (Level)_doc.get_Element(idLevel2); // 2012 Level level2 = rvtDoc.GetElement(idLevel2) as Level; // since 2013 // Footprint to model curve mapping. ModelCurveArray mapping = new ModelCurveArray(); // Create a roof. FootPrintRoof aRoof = rvtDoc.Create.NewFootPrintRoof( footPrint, level2, roofType, out mapping); // Set the slope. ///////////////////////////////////////////////// ///new mapping ///////////////////////////////////////////////// LocationCurve wallCurv1 = (LocationCurve)walls[1].Location; // set the gable roof slope ModelCurveArray mappingNew = new ModelCurveArray(); ModelCurve gableCurve1 = mapping.get_Item(1); ModelCurve gableCurve2 = mapping.get_Item(3); double a = wallCurv1.Curve.Length / 2.00; double b = 4.00; //double angleB = Math.Truncate( Math.Acos((c * c + a * a - b * b)/(2 * c * a)) * 100 ) / 100; // Math.PI * 180; /* The value is a 'slope' measurement. For example, 0.5 is one unit of rise for each 2 units of run. * this creates a slope of 26.57 degrees * (the arctangent of 0.5) * double angleBDegrees = angleBRadians * 180 / Math.PI; * double c = Math.Truncate(Math.Sqrt(a * a + b * b) * 100) / 100; * double c = Math.Sqrt(a * a + b * b); * double a = Math.Truncate(gableCurve1.GeometryCurve.Length /2.00 * 100) / 100; * //double a = gableCurve1.GeometryCurve.Length / 2.00; * //double n = wallCurv2.Curve.Length; * //// * * //double c = Math.Sqrt(a * a + b * b); * //double angleB = Math.Acos(c); * //find double slope A use pythagorum theroum * // set lines a and b, find c * * //double b = 4.00; // height should be 4' from center * ////// <<<hey hey hey hey hey hey herrrreeeeeeeeee <<<<<<<<<< * /////LocationCurve wallCurv2 = (LocationCurve)walls[3].Location; * */ double angleBRadians = Math.Atan(b / a); double angleB = Math.Tan(angleBRadians); TaskDialog.Show("Test Values", "lenght a: " + a + " length b: " + b + " radians: " + angleBRadians + " angle B: " + angleB); aRoof.set_DefinesSlope(gableCurve1, true); aRoof.set_SlopeAngle(gableCurve1, angleB); aRoof.set_DefinesSlope(gableCurve2, true); aRoof.set_SlopeAngle(gableCurve2, angleB); #region note text and abandoned code //foreach (ModelCurve modelCurve in mapping) //{ // aRoof.set_DefinesSlope(modelCurve, true); // aRoof.set_SlopeAngle(modelCurve, 0.5); //} // Performed automatically by transaction commit. //rvtDoc.Regenerate(); //rvtDoc.AutoJoinElements(); #endregion }
public Result setup_roof() { FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(RoofType)); RoofType roofType = collector.FirstElement() as RoofType; Transaction trans = new Transaction(doc); string jsonFilePath = @"C:\Users\John\AppData\Roaming\Autodesk\Revit\Addins\2019\data.json"; List <mylevels> items; List <XYZ[]> coords = new List <XYZ[]>(); using (StreamReader r = new StreamReader(jsonFilePath)) { string json = r.ReadToEnd(); items = JsonConvert.DeserializeObject <List <mylevels> >(json); } List <int> slopes = new List <int>(); int i; foreach (mylevels l in items) { if (l.level == level.Name) { dataset = l.sets; } } foreach (mysets s in dataset) { if (s.type == "roof") { using (trans = new Transaction(doc)) { trans.Start("roof"); CurveArray footprint = new CurveArray(); Level roof_level = level; if (s.base_level != null) { roof_level = new FilteredElementCollector(doc) .OfClass(typeof(Level)) .Cast <Level>().FirstOrDefault(q => q.Name == s.base_level); } walls p = null; foreach (walls w in s.walls) { XYZ a = w.coords[0] is null ? new XYZ(p.coords[1][0] / 12.0, p.coords[1][1] / 12.0, roof_level.Elevation) : new XYZ(w.coords[0][0] / 12.0, w.coords[0][1] / 12.0, roof_level.Elevation); XYZ b = new XYZ(w.coords[1][0] / 12.0, w.coords[1][1] / 12.0, roof_level.Elevation); Line line = Line.CreateBound(a, b); footprint.Append(line); p = w; } ModelCurveArray footPrintToModelCurveMapping = new ModelCurveArray(); FootPrintRoof footprintRoof = doc.Create.NewFootPrintRoof(footprint, roof_level, roofType, out footPrintToModelCurveMapping); ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator(); iterator.Reset(); i = 0; while (iterator.MoveNext()) { ModelCurve modelCurve = iterator.Current as ModelCurve; if (s.walls[i].define_slope) { footprintRoof.set_DefinesSlope(modelCurve, true); // footprintRoof.set_SlopeAngle(modelCurve, 0.5); } if (s.walls[i].roof_offset != 0) { footprintRoof.set_Offset(modelCurve, s.walls[i].roof_offset / 12.0); } i++; } trans.Commit(); } } } return(Result.Succeeded); }
/// <summary> /// Exports a curtain roof to IFC curtain wall. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="hostElement"> /// The host object element to be exported. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void ExportFootPrintRoof(ExporterIFC exporterIFC, FootPrintRoof hostElement, IFCProductWrapper productWrapper) { // Don't export the Curtain Wall itself, which has no useful geometry; instead export all of the GReps of the // mullions and panels. CurtainGridSet grids = hostElement.CurtainGrids; if (grids == null || grids.Size == 0) return; ICollection<ElementId> allSubElements = new HashSet<ElementId>(); foreach (CurtainGrid grid in grids) { foreach (ElementId panelId in grid.GetPanelIds()) allSubElements.Add(panelId); foreach (ElementId subElem in grid.GetMullionIds()) allSubElements.Add(subElem); } ExportBase(exporterIFC, allSubElements, hostElement, productWrapper); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(Misc.LoadFromSameFolder); UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; View active_view = doc.ActiveView; double tolerance = app.ShortCurveTolerance; /////////////////////// // Pick Import Instance ImportInstance import = null; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>()); import = doc.GetElement(r) as ImportInstance; } catch { return(Result.Cancelled); } if (import == null) { System.Windows.MessageBox.Show("CAD not found", "Tips"); return(Result.Cancelled); } // Initiate the progress bar Views.ProgressBar pb = new Views.ProgressBar("Modeling entire building", "Initiation...", 100); if (pb.ProcessCancelled) { return(Result.Cancelled); } ////////////////////////////////// // Check if the families are ready pb.CustomizeStatus("Checking families...", 2); if (pb.ProcessCancelled) { return(Result.Cancelled); } // Consider to add more customized families (in the Setting Panel) if (Properties.Settings.Default.name_door == null || Properties.Settings.Default.name_window == null || Properties.Settings.Default.name_columnRect == null || Properties.Settings.Default.name_columnRound == null) { System.Windows.MessageBox.Show("Please select the column/door/window type in settings", "Tips"); return(Result.Cancelled); } //if (!File.Exists(Properties.Settings.Default.url_door) && File.Exists(Properties.Settings.Default.url_window) // && File.Exists(Properties.Settings.Default.url_column)) //{ // System.Windows.MessageBox.Show("Please check the family path is solid", "Tips"); // return Result.Cancelled; //} //Family fColumn, fDoor, fWindow = null; //using (Transaction tx = new Transaction(doc, "Load necessary families")) //{ // tx.Start(); // if (!doc.LoadFamily(Properties.Settings.Default.url_column, out fColumn)) // { // System.Windows.MessageBox.Show("Please check the column family path is solid", "Tips"); // return Result.Cancelled; // } // if (!doc.LoadFamily(Properties.Settings.Default.url_door, out fDoor) || // !doc.LoadFamily(Properties.Settings.Default.url_window, out fWindow)) // { // System.Windows.MessageBox.Show("Please check the door/window family path is solid", "Tips"); // return Result.Cancelled; // } // tx.Commit(); //} // Prepare a family for ViewPlan creation // It may be a coincidence that the 1st ViewFamilyType is for the FloorPlan // Uplift needed here (doomed if it happends to be a CeilingPlan) ViewFamilyType viewType = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)).First() as ViewFamilyType; RoofType roofType = new FilteredElementCollector(doc) .OfClass(typeof(RoofType)).FirstOrDefault <Element>() as RoofType; FloorType floorType = new FilteredElementCollector(doc) .OfClass(typeof(FloorType)).FirstOrDefault <Element>() as FloorType; //////////////////// // DATA PREPARATIONS pb.CustomizeStatus("Processing geometries...", 3); if (pb.ProcessCancelled) { return(Result.Cancelled); } // Prepare frames and levels // Cluster all geometry elements and texts into datatrees // Two procedures are intertwined List <GeometryObject> dwg_frames = Util.TeighaGeometry.ExtractElement(uidoc, import, Properties.Settings.Default.layerFrame, "PolyLine"); // framework is polyline by default List <GeometryObject> dwg_geos = Util.TeighaGeometry.ExtractElement(uidoc, import); // Terminate if no geometry has been found if (dwg_geos == null) { System.Windows.MessageBox.Show("A drawing frame is mandantory", "Tips"); return(Result.Failed); } List <PolyLine> closedPolys = new List <PolyLine>(); List <PolyLine> parentPolys = new List <PolyLine>(); Debug.Print("Number of geos acting as the framework is " + dwg_frames.Count().ToString()); if (dwg_frames.Count > 0) { foreach (var obj in dwg_frames) { PolyLine poly = obj as PolyLine; // Draw shattered lines in case the object is a PolyLine if (null != poly) { var vertices = poly.GetCoordinates(); if (vertices[0].IsAlmostEqualTo(vertices.Last())) { closedPolys.Add(poly); } } } for (int i = 0; i < closedPolys.Count(); i++) { int judgement = 0; int counter = 0; for (int j = 0; j < closedPolys.Count(); j++) { if (i != j) { if (!RegionDetect.PolyInPoly(closedPolys[i], RegionDetect.PolyLineToCurveArray(closedPolys[j], tolerance))) { //Debug.Print("Poly inside poly detected"); judgement += 1; } counter += 1; } } if (judgement == counter) { parentPolys.Add(closedPolys[i]); } } } else { Debug.Print("There is no returning of geometries"); } Debug.Print("Got closedPolys: " + closedPolys.Count().ToString()); Debug.Print("Got parentPolys: " + parentPolys.Count().ToString()); string path = Util.TeighaText.GetCADPath(uidoc, import); Debug.Print("The path of linked CAD file is: " + path); List <Util.TeighaText.CADTextModel> texts = Util.TeighaText.GetCADText(path); int level; int levelCounter = 0; double floorHeight = Misc.MmToFoot(Properties.Settings.Default.floorHeight); Dictionary <int, PolyLine> frameDict = new Dictionary <int, PolyLine>(); // cache drawing borders Dictionary <int, XYZ> transDict = new Dictionary <int, XYZ>(); // cache transform vector from the left-bottom corner of the drawing border to the Origin Dictionary <int, List <GeometryObject> > geoDict = new Dictionary <int, List <GeometryObject> >(); // cache geometries of each floorplan Dictionary <int, List <Util.TeighaText.CADTextModel> > textDict = new Dictionary <int, List <Util.TeighaText.CADTextModel> >(); // cache text info of each floorplan if (texts.Count > 0) { foreach (var textmodel in texts) { level = Misc.GetLevel(textmodel.Text, "平面图"); Debug.Print("Got target label " + textmodel.Text); if (level != -1) { foreach (PolyLine frame in parentPolys) { if (RegionDetect.PointInPoly(RegionDetect.PolyLineToCurveArray(frame, tolerance), textmodel.Location)) { XYZ basePt = Algorithm.BubbleSort(frame.GetCoordinates().ToList())[0]; XYZ transVec = XYZ.Zero - basePt; Debug.Print("Add level " + level.ToString() + " with transaction (" + transVec.X.ToString() + ", " + transVec.Y.ToString() + ", " + transVec.Z.ToString() + ")"); if (!frameDict.Values.ToList().Contains(frame)) { frameDict.Add(level, frame); transDict.Add(level, transVec); levelCounter += 1; } } } } } // Too complicated using 2 iterations... uplift needed for (int i = 1; i <= levelCounter; i++) { textDict.Add(i, new List <Util.TeighaText.CADTextModel>()); geoDict.Add(i, new List <GeometryObject>()); CurveArray tempPolyArray = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance); foreach (var textmodel in texts) { if (RegionDetect.PointInPoly(tempPolyArray, textmodel.Location)) { textDict[i].Add(textmodel); } } foreach (GeometryObject go in dwg_geos) { XYZ centPt = XYZ.Zero; if (go is Line) { //get the revit model coordinates. Line go_line = go as Line; centPt = (go_line.GetEndPoint(0) + go_line.GetEndPoint(1)).Divide(2); } else if (go is Arc) { Arc go_arc = go as Arc; centPt = go_arc.Center; } else if (go is PolyLine) { PolyLine go_poly = go as PolyLine; centPt = go_poly.GetCoordinate(0); } // Assignment if (RegionDetect.PointInPoly(tempPolyArray, centPt) && centPt != XYZ.Zero) { geoDict[i].Add(go); } } } } Debug.Print("All levels: " + levelCounter.ToString()); Debug.Print("frameDict: " + frameDict.Count().ToString()); Debug.Print("transDict: " + transDict.Count().ToString()); for (int i = 1; i <= levelCounter; i++) { Debug.Print("geoDict-{0}: {1}", i, geoDict[i].Count().ToString()); } Debug.Print("textDict: " + textDict.Count().ToString() + " " + textDict[1].Count().ToString()); //////////////////// // MAIN TRANSACTIONS // Prepare a family and configurations for TextNote (Put it inside transactions) /* * TextNoteType tnt = new FilteredElementCollector(doc) * .OfClass(typeof(TextNoteType)).First() as TextNoteType; * TextNoteOptions options = new TextNoteOptions(); * options.HorizontalAlignment = HorizontalTextAlignment.Center; * options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); * BuiltInParameter paraIndex = BuiltInParameter.TEXT_SIZE; * Parameter textSize = tnt.get_Parameter(paraIndex); * textSize.Set(0.3); // in feet * * XYZ centPt = RegionDetect.PolyCentPt(frameDict[i]); * TextNoteOptions opts = new TextNoteOptions(tnt.Id); * * // The note may only show in the current view * // no matter we still need it anyway * TextNote txNote = TextNote.Create(doc, active_view.Id, centPt, floorView.Name, options); * txNote.ChangeTypeId(tnt.Id); * * // Draw model lines of frames as notation * Plane Geomplane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero + transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight); * SketchPlane sketch = SketchPlane.Create(doc, Geomplane); * CurveArray shatters = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance); * Transform alignModelLine = Transform.CreateTranslation(transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight); * foreach (Curve shatter in shatters) * { * Curve alignedCrv = shatter.CreateTransformed(alignModelLine); * ModelCurve modelline = doc.Create.NewModelCurve(alignedCrv, sketch) as ModelCurve; * } */ // ITERATION FLAG for (int i = 1; i <= levelCounter; i++) { pb.CustomizeStatus("On Floor " + i.ToString() + "... with lines", 5); if (pb.ProcessCancelled) { return(Result.Cancelled); } TransactionGroup tg = new TransactionGroup(doc, "Generate on floor-" + i.ToString()); { try { tg.Start(); // MILESTONE // Align the labels to the origin Transform alignment = Transform.CreateTranslation(transDict[i]); foreach (Util.TeighaText.CADTextModel label in textDict[i]) { label.Location = label.Location + transDict[i]; } // MILESTONE // Sort out lines List <Curve> wallCrvs = new List <Curve>(); List <Curve> columnCrvs = new List <Curve>(); List <Curve> doorCrvs = new List <Curve>(); List <Curve> windowCrvs = new List <Curve>(); foreach (GeometryObject go in geoDict[i]) { var gStyle = doc.GetElement(go.GraphicsStyleId) as GraphicsStyle; if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWall) { if (go.GetType().Name == "Line") { Curve wallLine = go as Curve; wallCrvs.Add(wallLine.CreateTransformed(alignment) as Line); } if (go.GetType().Name == "PolyLine") { CurveArray wallPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance); foreach (Curve crv in wallPolyLine_shattered) { wallCrvs.Add(crv.CreateTransformed(alignment) as Line); } } } if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerColumn) { if (go.GetType().Name == "Line") { Curve columnLine = go as Curve; columnCrvs.Add(columnLine.CreateTransformed(alignment)); } if (go.GetType().Name == "PolyLine") { CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance); foreach (Curve crv in columnPolyLine_shattered) { columnCrvs.Add(crv.CreateTransformed(alignment)); } } } if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerDoor) { Curve doorCrv = go as Curve; PolyLine poly = go as PolyLine; if (null != doorCrv) { doorCrvs.Add(doorCrv.CreateTransformed(alignment)); } if (null != poly) { CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance); foreach (Curve crv in columnPolyLine_shattered) { doorCrvs.Add(crv.CreateTransformed(alignment) as Line); } } } if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWindow) { Curve windowCrv = go as Curve; PolyLine poly = go as PolyLine; if (null != windowCrv) { windowCrvs.Add(windowCrv.CreateTransformed(alignment)); } if (null != poly) { CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance); foreach (Curve crv in columnPolyLine_shattered) { windowCrvs.Add(crv.CreateTransformed(alignment) as Line); } } } } // MILESTONE // Create additional levels (ignore what's present) // Consider to use sub-transaction here using (var t_level = new Transaction(doc)) { t_level.Start("Create levels"); Level floor = Level.Create(doc, (i - 1) * floorHeight); ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, floor.Id); floorView.Name = "F-" + i.ToString(); t_level.Commit(); } // Grab the current building level FilteredElementCollector colLevels = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.INVALID) .OfClass(typeof(Level)); Level currentLevel = colLevels.LastOrDefault() as Level; // The newly created level will append to the list, // but this is not a safe choice // Sub-transactions are packed within these functions. // The family names should be defined by the user in WPF // MILESTONE pb.CustomizeStatus("On Floor " + i.ToString() + "... with Walls", 90 / levelCounter / 4); if (pb.ProcessCancelled) { return(Result.Cancelled); } CreateWall.Execute(uiapp, wallCrvs, currentLevel, true); // MILESTONE pb.CustomizeStatus("On Floor " + i.ToString() + "... with Columns", 90 / levelCounter / 4); if (pb.ProcessCancelled) { return(Result.Cancelled); } CreateColumn.Execute(app, doc, columnCrvs, Properties.Settings.Default.name_columnRect, Properties.Settings.Default.name_columnRound, currentLevel, true); // MILESTONE pb.CustomizeStatus("On Floor " + i.ToString() + "... with Openings", 90 / levelCounter / 4); if (pb.ProcessCancelled) { return(Result.Cancelled); } CreateOpening.Execute(doc, doorCrvs, windowCrvs, wallCrvs, textDict[i], Properties.Settings.Default.name_door, Properties.Settings.Default.name_window, currentLevel, true); // Create floor // MILESTONE var footprint = CreateRegion.Execute(doc, wallCrvs, columnCrvs, windowCrvs, doorCrvs); using (var t_floor = new Transaction(doc)) { t_floor.Start("Generate Floor"); Floor newFloor = doc.Create.NewFloor(footprint, floorType, currentLevel, false, XYZ.BasisZ); newFloor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(0); t_floor.Commit(); } // Generate rooms after the topology is established pb.CustomizeStatus("On Floor " + i.ToString() + "... with Rooms", 90 / levelCounter / 4); if (pb.ProcessCancelled) { return(Result.Cancelled); } // MILESTONE using (var t_space = new Transaction(doc)) { t_space.Start("Create rooms"); doc.Regenerate(); PlanTopology planTopology = doc.get_PlanTopology(currentLevel); if (doc.ActiveView.ViewType == ViewType.FloorPlan) { foreach (PlanCircuit circuit in planTopology.Circuits) { if (null != circuit && !circuit.IsRoomLocated) { Room room = doc.Create.NewRoom(null, circuit); room.LimitOffset = floorHeight; room.BaseOffset = 0; string roomName = ""; foreach (Util.TeighaText.CADTextModel label in textDict[i]) { if (label.Layer == Properties.Settings.Default.layerSpace) { if (room.IsPointInRoom(label.Location + XYZ.BasisZ * (i - 1) * floorHeight)) { roomName += label.Text; } } } if (roomName != "") { room.Name = roomName; } } } } t_space.Commit(); } // Create roof when iterating to the last level // MILESTONE if (i == levelCounter) { using (var t_roof = new Transaction(doc)) { t_roof.Start("Create roof"); Level roofLevel = Level.Create(doc, i * floorHeight); ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, roofLevel.Id); floorView.Name = "Roof"; ModelCurveArray footPrintToModelCurveMapping = new ModelCurveArray(); FootPrintRoof footprintRoof = doc.Create.NewFootPrintRoof(footprint, roofLevel, roofType, out footPrintToModelCurveMapping); //ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator(); /* * iterator.Reset(); * while (iterator.MoveNext()) * { * ModelCurve modelCurve = iterator.Current as ModelCurve; * footprintRoof.set_DefinesSlope(modelCurve, true); * footprintRoof.set_SlopeAngle(modelCurve, 0.5); * } */ t_roof.Commit(); } } tg.Assimilate(); } catch { System.Windows.MessageBox.Show("Error", "Tips"); tg.RollBack(); } } pb.JobCompleted(); } return(Result.Succeeded); }
/// <summary> /// Add a roof over the rectangular profile of the walls we created earlier. /// </summary> public static void AddRoof(Document rvtDoc, List <Wall> walls) { // Hard coding the roof type we will use. // e.g., "Basic Roof: Generic - 400mm" const string roofFamilyName = "Basic Roof"; const string roofTypeName = Util.Constant.RoofTypeName; const string roofFamilyAndTypeName = roofFamilyName + ": " + roofTypeName; // Find the roof type RoofType roofType = ElementFiltering.FindFamilyType( rvtDoc, typeof(RoofType), roofFamilyName, roofTypeName, null ) as RoofType; if (roofType == null) { TaskDialog.Show( "Add roof", "Cannot find (" + roofFamilyAndTypeName + "). Maybe you use a different template? Try with DefaultMetric.rte."); } // Wall thickness to adjust the footprint of the walls // to the outer most lines. // Note: this may not be the best way. // but we will live with this for this exercise. //Dim wallThickness As Double = _ //walls(0).WallType.CompoundStructure.Layers.Item(0).Thickness() ' 2011 double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012 double dt = wallThickness / 2.0; List <XYZ> dts = new List <XYZ>(5); dts.Add(new XYZ(-dt, -dt, 0.0)); dts.Add(new XYZ(dt, -dt, 0.0)); dts.Add(new XYZ(dt, dt, 0.0)); dts.Add(new XYZ(-dt, dt, 0.0)); dts.Add(dts[0]); // Set the profile from four walls CurveArray footPrint = new CurveArray(); for (int i = 0; i <= 3; i++) { LocationCurve locCurve = (LocationCurve)walls[i].Location; XYZ pt1 = locCurve.Curve.GetEndPoint(0) + dts[i]; XYZ pt2 = locCurve.Curve.GetEndPoint(1) + dts[i + 1]; Line line = Line.CreateBound(pt1, pt2); footPrint.Append(line); } // Get the level2 from the wall. ElementId idLevel2 = walls[0].get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId(); //Level level2 = (Level)_doc.get_Element(idLevel2); // 2012 Level level2 = rvtDoc.GetElement(idLevel2) as Level; // since 2013 // Footprint to model curve mapping. ModelCurveArray mapping = new ModelCurveArray(); // Create a roof. FootPrintRoof aRoof = rvtDoc.Create.NewFootPrintRoof( footPrint, level2, roofType, out mapping); // Set the slope. foreach (ModelCurve modelCurve in mapping) { aRoof.set_DefinesSlope(modelCurve, true); aRoof.set_SlopeAngle(modelCurve, 0.5); } // Performed automatically by transaction commit. //rvtDoc.Regenerate(); //rvtDoc.AutoJoinElements(); }
private void Stream( ArrayList data, FootPrintRoof footPrintRoof ) { data.Add( new Snoop.Data.ClassSeparator( typeof( FootPrintRoof ) ) ); data.Add( new Snoop.Data.Enumerable( "Curtain grids", footPrintRoof.CurtainGrids ) ); // TBD: how to display Profiles and other functions? }
protected GCRoofFootPrint(FootPrintRoof elem) : base(elem) { }
private void AssignGuid(FootPrintRoof roof, Guid guid, Schema instanceSchema, int run, string nickName) { Entity entity = null; try { entity = roof.GetEntity(instanceSchema); } catch (Exception ex) { Debug.Write("Error", ex.Message); } try { if (!entity.IsValid()) { entity = new Entity(instanceSchema); } Field field = instanceSchema.GetField("InstanceID"); entity.Set<string>(field, guid.ToString()); field = instanceSchema.GetField("RunID"); entity.Set<int>(field, run); field = instanceSchema.GetField("NickName"); entity.Set<string>(field, nickName); roof.SetEntity(entity); } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } }
static public string CreateRoof(Dyn.Element roofElement, IList <Dyn.FamilyType> listOfFamilyTypes, Dyn.FamilyType ridgeFamilyType) { Document doc = DocumentManager.Instance.CurrentDBDocument; RoofStorage.revitApp = doc.Application; FootPrintRoof currentRoof = roofElement.InternalElement as FootPrintRoof; if (currentRoof == null) { throw new Exception("Error, element is not a footprint roof."); } Parameter selectedRoofSlopeParameter = currentRoof.get_Parameter(BuiltInParameter.ROOF_SLOPE); double selectedRoofSlope = selectedRoofSlopeParameter.AsDouble(); //Verify if the roof has all the same slopes if (selectedRoofSlope <= 0) { throw new Exception("Error, it was not possible to estabilish a unique slope for the roof, please, make sure all eaves have the same slope."); } //Verify if the roof has the minimal slope if (selectedRoofSlope < 0.098) { throw new Exception("Error, please make sure the roof has a minimum of 10% slope."); } IList <Reference> faceRefList = HostObjectUtils.GetTopFaces(currentRoof); IList <PlanarFace> planarFaceList = new List <PlanarFace>(); if (!IsListOfPlanarFaces(faceRefList, currentRoof, out planarFaceList)) { throw new Exception("Error, invalid roof selected, please make sure all faces of the roof are flat."); } FamilySymbol ridgeFamilySymbol = ridgeFamilyType.InternalElement as FamilySymbol; if (ridgeFamilySymbol == null) { throw new Exception("Error, ridgeFamilyType is not a valid Family Type."); } if (!AdaptiveComponentFamilyUtils.IsAdaptiveComponentFamily(ridgeFamilySymbol.Family)) { throw new Exception("Error, ridgeFamilyType is not a valid Adaptive component type"); } if (AdaptiveComponentFamilyUtils.GetNumberOfPlacementPoints(ridgeFamilySymbol.Family) != 2) { throw new Exception("Error, ridgeFamilyType must have two insertion points"); } IList <FamilySymbol> listOfFamilySymbols = ConvertDynFamilyTypeListToRevitFamilySymbolList(listOfFamilyTypes); if (listOfFamilySymbols.Count() < 1) { throw new Exception("Error, no adaptive family types were found on the input list"); } if (doc.ActiveView as View3D == null) { throw new Exception("Error, please use this command on a 3d view"); } //currentPointSymbol.Activate(); string results = ""; results += "Number of Roof Instances " + planarFaceList.Count() + "\n"; foreach (PlanarFace currentFace in planarFaceList) { int numberOfCurves = GetOuterCurveLoop(currentFace).Count(); FamilySymbol currentFamilySymbol = listOfFamilySymbols.Where(fs => AdaptiveComponentFamilyUtils.GetNumberOfPlacementPoints(fs.Family) == numberOfCurves).FirstOrDefault(); if (currentFamilySymbol == null) { continue; } CreateAdaptiveComponent(doc, currentFace, currentFamilySymbol); } IList <Curve> ridgeCurves = GetListOfRidgesHipsAndValleys(planarFaceList); results += "Number of Ridge Instances " + ridgeCurves.Count(); foreach (Curve currentCurve in ridgeCurves) { curveInfo curvI = GetCurveInformation(currentRoof, currentCurve, planarFaceList); if (curvI.roofLineType == RoofLineType.Ridge || curvI.roofLineType == RoofLineType.Hip) { CreateAdaptiveComponentFromLine(doc, currentCurve, ridgeFamilySymbol); } } return(results); }