Пример #1
1
        /// <summary>
        /// Finds all the views in the active document.
        /// </summary>
        /// <param name="doc">the active document</param>
        public static ViewSet GetAllViews (Document doc)
        {
            ViewSet allViews = new ViewSet();

            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(FloorType));
            fec.WherePasses(elementsAreWanted);
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach (Element element in elements)
            {
               Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;

               if (null == view)
               {
                  continue;
               }
               else
               {
                  
                  ElementType objType = doc.GetElement(view.GetTypeId()) as ElementType;
                  if (null == objType || objType.Name.Equals("Drawing Sheet"))
                  {
                     continue;
                  }
                  else
                  {
                     allViews.Insert(view);
                  }
               }
            }

            return allViews;
        }
        public static ElementId CreateJoinedWall(Document doc, ElementId wallId, FamilyInstance familyInstance)
        {
            //create a line to represent the wall center line
            var line = Line.CreateBound(XYZ.Zero, XYZ.BasisX);

            //find first level
            var collector = new FilteredElementCollector(doc);
            var filter    = new ElementClassFilter(typeof(Level));
            var level     = collector.WherePasses(filter).FirstElement() as Level;

            //create wall
            var wall = Wall.Create(doc, line, level.Id, false);

            //save the id so we can delete the wall later
            wallId = wall.Id;

            //if the selected element
            var subIds = familyInstance.GetSubComponentIds();

            if (subIds.Count > 0)
            {
                foreach (var id in subIds)
                {
                    var subelement = doc.GetElement(id);
                    JoinGeometryUtils.JoinGeometry(doc, wall, subelement);
                }
            }
            else
            {
                JoinGeometryUtils.JoinGeometry(doc, wall, familyInstance);
            }
            return(wallId);
        }
Пример #3
0
        // http://thebuildingcoder.typepad.com/blog/2010/01/findreferencesbydirection.html#comment-4055509541
        /// <summary>
        /// Return reference to ceiling face to place
        /// lighting fixture above a given point.
        /// </summary>
        Reference GetCeilingReferenceAbove(
            View3D view,
            XYZ p)
        {
            ElementClassFilter filter = new ElementClassFilter(
                typeof(Ceiling));

            ReferenceIntersector refIntersector
                = new ReferenceIntersector(filter,
                                           FindReferenceTarget.Face, view);

            refIntersector.FindReferencesInRevitLinks = true;

            ReferenceWithContext rwc = refIntersector.FindNearest(
                p, XYZ.BasisZ);

            Reference r = (null == rwc)
        ? null
        : rwc.GetReference();

            if (null == r)
            {
                System.Windows.MessageBox.Show("no intersecting geometry");
            }
            return(r);
        }
Пример #4
0
        public Result OnStartup(UIControlledApplication a)
        {
            //Create Ribbon Panel add the UI button on start up
            RibbonPanel alignViewsPanel = ribbonPanel(a);

            //Register location updater with Revit.
            LocationUpdater updater = new LocationUpdater(a.ActiveAddInId);
            UpdaterRegistry.RegisterUpdater(updater, true);

            ElementCategoryFilter viewPortFilter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports);
            ElementCategoryFilter viewFilter = new ElementCategoryFilter(BuiltInCategory.OST_Views);
            LogicalOrFilter filter = new LogicalOrFilter(viewPortFilter, viewFilter);

            //Parameter to send to the trigger.
            ElementClassFilter viewPort = new ElementClassFilter(typeof(Viewport));
            ElementId viewPortNumberId = new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER);

            //Set trigger
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), viewPort, Element.GetChangeTypeParameter(viewPortNumberId));
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition());

            //add buttons to ribbon
            addVRCommandButtons(alignViewsPanel);
            pushButton_Setting(alignViewsPanel);

            return Result.Succeeded;
        }
Пример #5
0
        /// <summary>
        /// Gather up all the available sheets.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="sheet"></param>
        /// <returns></returns>
        public static ElementSet GetAllSheets(Document doc)
        {
            ElementSet allSheets = new ElementSet();
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(ViewSheet));
            fec.WherePasses(elementsAreWanted);
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach (Element element in elements)
            {
               ViewSheet viewSheet = element as ViewSheet;

               if (null == viewSheet)
               {
                  continue;
               }
               else
               {
                  ElementId objId = viewSheet.GetTypeId();
                  if (ElementId.InvalidElementId == objId)
                  {
                     continue;
                  }
                  else
                  {
                     allSheets.Insert(viewSheet);
                  }
               }
            }

            return allSheets;
        }
Пример #6
0
        public static Pipe CreateDummyPipe(XYZ pointToConnect, XYZ directionPoint, PointInSpace endInstance, ElementSymbol elementSymbol)
        {
            Pipe pipe = null;

            ElementId pipeTypeId = elementSymbol.PipeType.Id;

            //Collect levels and select one level
            FilteredElementCollector levelCollector = new FilteredElementCollector(PCFImport.doc);
            ElementClassFilter       levelFilter    = new ElementClassFilter(typeof(Level));
            ElementId levelId = levelCollector.WherePasses(levelFilter).FirstElementId();

            //Create vector to define pipe
            XYZ pipeDir      = pointToConnect - directionPoint;
            XYZ helperPoint1 = pointToConnect.Add(pipeDir.Multiply(2));

            //Create pipe
            pipe = Pipe.Create(PCFImport.doc, elementSymbol.PipingSystemType.Id, pipeTypeId, levelId,
                               pointToConnect, helperPoint1);
            //Set pipe diameter
            Parameter parameter = pipe.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM);

            parameter.Set(endInstance.Diameter);

            return(pipe);
        }
Пример #7
0
        public void MarkUntagedFrame()
        {
            UIDocument uidoc = ActiveUIDocument;
            Document   doc   = uidoc.Document;

            ElementClassFilter           f1 = new ElementClassFilter(typeof(FamilyInstance));
            StructuralMaterialTypeFilter f2 = new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete);
            ElementClassFilter           f3 = new ElementClassFilter(typeof(Floor));
            ElementClassFilter           f4 = new ElementClassFilter(typeof(Wall));
            LogicalAndFilter             f5 = new LogicalAndFilter(f1, f2);
            LogicalOrFilter f6           = new LogicalOrFilter(f3, f4);
            LogicalOrFilter memberFilter = new LogicalOrFilter(f5, f6);

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.WherePasses(memberFilter);
            List <Element> members = collector.ToList();
            String         Tag     = null;

            foreach (Element e in members)
            {
                Tag = e.get_Parameter(BuiltInParameter.DOOR_NUMBER).AsString();

                if (Tag == "" || Tag == null)
                {
                    HiLighted(e.Id, uidoc, doc);
                }
                else
                {
                    UnHiLighted(e.Id, uidoc, doc);
                }

                Tag = null;
            }
        }
Пример #8
0
        /// <summary>
        /// Read all Revit model levels.
        /// </summary>
        private void ReadLevels()
        {
            var collector       = new FilteredElementCollector(a_doc);
            var filterCategory  = new ElementCategoryFilter(BuiltInCategory.OST_Levels);
            var filterNotSymbol = new ElementClassFilter(typeof(FamilySymbol), true);
            var filter          = new LogicalAndFilter(filterCategory, filterNotSymbol);
            var elements        = collector.WherePasses(filter).ToElements();
            var unSortedLevels  = new List <Tuple <double, string> >();

            foreach (var element in elements)
            {
                try
                {
                    if (element is Level)
                    {
                        var level     = element as Level;
                        var levelWork = new Tuple <double, string>(level.ProjectElevation, level.Name);
                        unSortedLevels.Add(levelWork);
                    }
                }
                catch (Exception e)
                {
                    ShowElementErrorMessage(element, e);
                }
            }
            // Sort level data by elevation, bottom to top
            a_levelData             = unSortedLevels.OrderBy(el => el.Item1).ToList();
            a_unknownLevelElevation = a_levelData.Count > 0 ? a_levelData[0].Item1 - 100 : 0.0;
        }
Пример #9
0
        /// <summary>
        /// Read all Revit model phases.
        /// </summary>
        private void ReadPhases()
        {
            var collector       = new FilteredElementCollector(a_doc);
            var filterCategory  = new ElementCategoryFilter(BuiltInCategory.OST_Phases);
            var filterNotSymbol = new ElementClassFilter(typeof(FamilySymbol), true);
            var filter          = new LogicalAndFilter(filterCategory, filterNotSymbol);
            var elements        = collector.WherePasses(filter).ToElements();

            foreach (var element in elements)
            {
                try
                {
                    if (element is Phase)
                    {
                        bool export = false;
                        if (element.Name.ToUpper().Contains("NEW"))
                        {
                            export = true;
                        }
                        this.a_revitPhases.Add(new RevitPhase(element.Name, export));
                    }
                }
                catch (Exception e)
                {
                    ShowElementErrorMessage(element, e);
                }
            }
        }
Пример #10
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;

            m_doc = app.ActiveUIDocument.Document;

            // filter for family instance and (door or window):

            ElementClassFilter       fFamInstClass = new ElementClassFilter(typeof(FamilyInstance));
            ElementCategoryFilter    fDoorCat      = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
            ElementCategoryFilter    fWindowCat    = new ElementCategoryFilter(BuiltInCategory.OST_Windows);
            LogicalOrFilter          fCat          = new LogicalOrFilter(fDoorCat, fWindowCat);
            LogicalAndFilter         f             = new LogicalAndFilter(fCat, fFamInstClass);
            FilteredElementCollector openings      = new FilteredElementCollector(m_doc);

            openings.WherePasses(f);

            // map with key = host element id and
            // value = list of hosted element ids:

            Dictionary <ElementId, List <ElementId> > ids =
                GetElementIds(openings);

            DumpHostedElements(ids);
            m_doc = null;

            return(Result.Succeeded);
        }
Пример #11
0
      public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
      {
          Document    doc       = commandData.Application.ActiveUIDocument.Document;
          double      elevation = 3;
          Transaction trans     = new Transaction(doc);

          trans.Start("creatlevel");
          Level level = Level.Create(doc, elevation);

          trans.Commit();

          var classFilter = new ElementClassFilter(typeof(ViewFamilyType));
          FilteredElementCollector filterElements = new FilteredElementCollector(doc);

          filterElements.WherePasses(classFilter);
          foreach (ViewFamilyType viewFamilyType in filterElements)
          {
              if ((viewFamilyType.ViewFamily == ViewFamily.FloorPlan) || (viewFamilyType.ViewFamily == ViewFamily.CeilingPlan))
              {
                  trans.Start("creat view of type" + viewFamilyType.ViewFamily);
                  ViewPlan view = ViewPlan.Create(doc, viewFamilyType.Id, level.Id);
                  trans.Commit();
              }
          }

          return(Autodesk.Revit.UI.Result.Succeeded);
      }
Пример #12
0
        //***********************************OnStartup***********************************
        public Result OnStartup(UIControlledApplication a)
        {
            //Updater active using appication id.
            Updater updater = new Updater(a.ActiveAddInId); //Updater

            //Register the updater
            UpdaterRegistry.RegisterUpdater(updater);

            // Revit elements to trigger
            ElementClassFilter walls = new ElementClassFilter(typeof(Wall));
            ElementClassFilter SE    = new ElementClassFilter(typeof(FamilySymbol));
            ElementClassFilter MEP   = new ElementClassFilter(typeof(MEPSystem));

            //Set trigger to send to execute when modified, deleted, gemoetry change or anything.
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), walls, Element.GetChangeTypeElementAddition());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), walls, Element.GetChangeTypeElementDeletion());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), walls, Element.GetChangeTypeGeometry());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), walls, Element.GetChangeTypeAny());

            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SE, Element.GetChangeTypeElementAddition());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SE, Element.GetChangeTypeElementDeletion());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SE, Element.GetChangeTypeGeometry());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SE, Element.GetChangeTypeAny());

            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), MEP, Element.GetChangeTypeElementAddition());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), MEP, Element.GetChangeTypeElementDeletion());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), MEP, Element.GetChangeTypeGeometry());
            UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), MEP, Element.GetChangeTypeAny());

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              m_doc = app.ActiveUIDocument.Document;

              // filter for family instance and (door or window):

              ElementClassFilter fFamInstClass = new ElementClassFilter( typeof( FamilyInstance ) );
              ElementCategoryFilter fDoorCat = new ElementCategoryFilter( BuiltInCategory.OST_Doors );
              ElementCategoryFilter fWindowCat = new ElementCategoryFilter( BuiltInCategory.OST_Windows );
              LogicalOrFilter fCat = new LogicalOrFilter( fDoorCat, fWindowCat );
              LogicalAndFilter f = new LogicalAndFilter( fCat, fFamInstClass );
              FilteredElementCollector openings = new FilteredElementCollector( m_doc );
              openings.WherePasses( f );

              // map with key = host element id and
              // value = list of hosted element ids:

              Dictionary<ElementId, List<ElementId>> ids =
            GetElementIds( openings );

              DumpHostedElements( ids );
              m_doc = null;

              return Result.Succeeded;
        }
Пример #14
0
        private void CreateInstancesAndSetLocations(List <XYZ> locations, Room room)
        {
            FilteredElementCollector collector     = new FilteredElementCollector(Doc);
            Func <View3D, bool>      isNotTemplate = v3 => !(v3.IsTemplate);
            View3D view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate);

            BoundingBoxXYZ box    = room.get_BoundingBox(view3D);
            XYZ            center = box.Min.Add(box.Max).Multiply(0.5);

            // Project in the negative Z direction down to the floor.
            XYZ rayDirection = new XYZ(0, 0, 1);

            ElementClassFilter filter = new ElementClassFilter(typeof(Floor));

            ReferenceIntersector refIntersector       = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);
            ReferenceWithContext referenceWithContext = refIntersector.FindNearest(center, rayDirection);

            Reference reference = referenceWithContext.GetReference();

            var el     = Doc.GetElement(reference);
            var ids    = string.Empty;
            var vector = new XYZ(1, 0, 0);

            for (int i = 0; i < locations.Count; i++)
            {
                var fi = App.ActiveUIDocument.Document.Create.NewFamilyInstance(reference, locations[i], vector, this.symbol);
                ids += fi.Id.IntegerValue.ToString() + ";";
            }
        }
Пример #15
0
        public static List <Room> GetModelRoomsActView(Document doc)
        {
            List <Room> modelRooms = new List <Room>();

            ElementClassFilter classFilter = new ElementClassFilter(typeof(SpatialElement));

            IEnumerable <SpatialElement> seRooms = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                                   .OfCategory(BuiltInCategory.OST_Rooms)
                                                   .WherePasses(classFilter)
                                                   .Cast <SpatialElement>()
                                                   .Where(se => se.Location != null);

            foreach (SpatialElement se in seRooms)
            {
                try
                {
                    Room r = se as Room;
                    if (r != null)
                    {
                        modelRooms.Add(r);
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return(modelRooms);
        }
Пример #16
0
        private static void ExtractObjects()
        {
            FilteredElementCollector CeilingCollector = new FilteredElementCollector(_doc);
            ElementClassFilter       CeilingFilter    = new ElementClassFilter(typeof(Ceiling));

            _Ceiling = CeilingCollector.WherePasses(CeilingFilter).ToList();
        }
Пример #17
0
        /// <summary>
        /// Finds all the views in the active document.
        /// </summary>
        /// <param name="doc">the active document</param>
        public static ViewSet GetAllViews(Document doc)
        {
            ViewSet allViews = new ViewSet();

            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter       elementsAreWanted = new ElementClassFilter(typeof(FloorType));

            fec.WherePasses(elementsAreWanted);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;

                if (null == view)
                {
                    continue;
                }
                else
                {
                    ElementType objType = doc.GetElement(view.GetTypeId()) as ElementType;
                    if (null == objType || objType.Name.Equals("Drawing Sheet"))
                    {
                        continue;
                    }
                    else
                    {
                        allViews.Insert(view);
                    }
                }
            }

            return(allViews);
        }
Пример #18
0
        /// <summary>
        /// Gets a representative view generated by the level.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="viewType">The view type.</param>
        /// <param name="level">The level.</param>
        /// <returns>A view associate with the level.</returns>
        /// <remarks>This function will return the first view it finds with a bottom range set to an offset of the generating level.
        /// If no such view is found, but a view based on the generating level exists, that view will be returned.</remarks>
        public static View FindViewByLevel(Document document, ViewType viewType, Level level)
        {
            View possibleView = null;

            ElementFilter            elementFilter = new ElementClassFilter(typeof(View));
            FilteredElementCollector collector     = new FilteredElementCollector(document);

            collector.WherePasses(elementFilter);
            foreach (View view in collector)
            {
                if (view.ViewType != viewType)
                {
                    continue;
                }
                if (view.GenLevel != null && view.GenLevel.Id == level.Id)
                {
                    PlanViewRange viewRange         = (view as ViewPlan).GetViewRange();
                    ElementId     bottomClipPlaneId = viewRange.GetLevelId(PlanViewPlane.BottomClipPlane);
                    if (bottomClipPlaneId != level.Id)
                    {
                        possibleView = view;
                        continue;
                    }
                    return(view);
                }
            }
            return(possibleView);
        }
Пример #19
0
        public void MarkFrames()
        {
            UIDocument uidoc = ActiveUIDocument;
            Document   doc   = uidoc.Document;

            ElementClassFilter           f1 = new ElementClassFilter(typeof(FamilyInstance));
            StructuralMaterialTypeFilter f2 = new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete);
            ElementClassFilter           f3 = new ElementClassFilter(typeof(Floor));
            ElementClassFilter           f4 = new ElementClassFilter(typeof(Wall));
            LogicalAndFilter             f5 = new LogicalAndFilter(f1, f2);
            LogicalOrFilter f6           = new LogicalOrFilter(f3, f4);
            LogicalOrFilter memberFilter = new LogicalOrFilter(f5, f6);

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.WherePasses(memberFilter);
            List <Element> members = collector.ToList();
            int            SN      = 1;

            using (Transaction tx = new Transaction(doc, "MarkFrames")){
                tx.Start();
                foreach (Element e in members)
                {
                    e.get_Parameter(BuiltInParameter.DOOR_NUMBER).Set("C" + SN.ToString("00"));
                    SN++;
                }
                tx.Commit();
            }
        }
Пример #20
0
        public void ClearMarks()
        {
            Document doc = this.ActiveUIDocument.Document;
            FilteredElementCollector     collector = new FilteredElementCollector(doc);
            ElementClassFilter           f1        = new ElementClassFilter(typeof(FamilyInstance));
            StructuralMaterialTypeFilter f2        = new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete);
            ElementClassFilter           f3        = new ElementClassFilter(typeof(Floor));
            ElementClassFilter           f4        = new ElementClassFilter(typeof(Wall));
            LogicalAndFilter             f5        = new LogicalAndFilter(f1, f2);
            LogicalOrFilter f6 = new LogicalOrFilter(f3, f4);
            LogicalOrFilter f7 = new LogicalOrFilter(f5, f6);

            ICollection <Element> collection = collector.WherePasses(f7).ToElements();

            using (Transaction tx = new Transaction(doc, "CopyMarkToSN"))
            {
                tx.Start();
                foreach (Element e in collection)
                {
                    Parameter pSN = e.LookupParameter("編號");

                    if (null != pSN)
                    {
//			            Parameter pMark = e.LookupParameter("標註");
                        Parameter pMark = e.get_Parameter(BuiltInParameter.DOOR_NUMBER);
                        pMark.Set("");
                    }
                }
                tx.Commit();
            }
        }
Пример #21
0
        public void MarkReverseColumn()
        {
            UIDocument uidoc = ActiveUIDocument;
            Document   doc   = uidoc.Document;

            ElementClassFilter       f1        = new ElementClassFilter(typeof(FamilyInstance));
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.WherePasses(f1);
            List <Element> columns = collector.Where(q => q.Category.Name == "結構柱").ToList();

            foreach (Element e in columns)
            {
                Level BottomLevel = doc.GetElement(e.LookupParameter("基準樓層").AsElementId()) as Level;
                Level TopLevel    = doc.GetElement(e.LookupParameter("頂部樓層").AsElementId()) as Level;

                double BottomElevation = e.LookupParameter("基準偏移").AsDouble() + BottomLevel.Elevation;
                double TopElevation    = e.LookupParameter("頂部偏移").AsDouble() + TopLevel.Elevation;

                if (TopElevation < BottomElevation)
                {
                    HiLighted(e.Id, uidoc, doc);
                }
                else
                {
                    UnHiLighted(e.Id, uidoc, doc);
                }
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document                 doc                 = commandData.Application.ActiveUIDocument.Document;
            ElementFilter            door_Category       = new ElementCategoryFilter(BuiltInCategory.OST_Doors); //获取门类别
            ElementFilter            door_FamilyInstance = new ElementClassFilter(typeof(FamilyInstance));       //获取族实例
            LogicalAndFilter         doorFamilyInstance  = new LogicalAndFilter(door_Category, door_FamilyInstance);
            FilteredElementCollector doorFiltered        = new FilteredElementCollector(doc).WherePasses(doorFamilyInstance);
            IList <Element>          door_elements       = doorFiltered.ToElements();


            ParameterSet paras = null;

            foreach (Element elems in door_elements)
            {
                paras = elems.Parameters;
            }
            string paraName = "";

            foreach (Parameter para in paras)
            {
                paraName += "\n\t" + para.Definition.Name;
            }
            File.WriteAllText(@"D:\door.txt", paraName);


            return(Result.Succeeded);
        }
Пример #23
0
        Execute ()
        {
            //Get every level by iterating through all elements
            systemLevelsData = new List<LevelsDataSource>();

            FilteredElementCollector fec = new FilteredElementCollector(m_app.ActiveUIDocument.Document);
            ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(Level));
            fec.WherePasses(elementsAreWanted);
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach (Element element in elements)
            {
               Level systemLevel = element as Level;
               if (systemLevel != null)
               {
                  LevelsDataSource levelsDataSourceRow = new LevelsDataSource();

                  levelsDataSourceRow.LevelIDValue = systemLevel.Id.IntegerValue;
                  levelsDataSourceRow.Name = systemLevel.Name;

                  levelsDataSourceRow.Elevation = systemLevel.Elevation;

                  systemLevelsData.Add(levelsDataSourceRow);
               }
            }

            LevelsForm displayForm = new LevelsForm(this);
            displayForm.ShowDialog();

            return true;
        }
Пример #24
0
        GetAvailableViewsToExport(Document doc)
        {
            ViewSet viewSet = new ViewSet();

            // TBD: using a filter iterator will only give you the base class View, not derived classes
            // like View3D or ViewDrafting.

            /*ElementFilterIterator viewIter = m_revitApp.ActiveUIDocument.Document.GetElements(typeof(Autodesk.Revit.DB.View));
             * while (viewIter.MoveNext()) {
             *  Autodesk.Revit.DB.View tmpView = (Autodesk.Revit.DB.View)viewIter.Current;
             *  if (tmpView.CanBePrinted)
             *      viewSet.Insert((Autodesk.Revit.DB.View)viewIter.Current);
             * }*/

            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter       elementsAreWanted = new ElementClassFilter(typeof(View));

            fec.WherePasses(elementsAreWanted);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                Autodesk.Revit.DB.View tmpView = element as Autodesk.Revit.DB.View;

                if ((tmpView != null) && tmpView.CanBePrinted)
                {
                    viewSet.Insert(tmpView);
                }
            }

            return(viewSet);
        }
Пример #25
0
        private static bool RegisterSheetUpdater(Document doc, ref SheetManagerConfiguration config)
        {
            bool registered = false;

            try
            {
                Guid         updaterGuid  = Guid.NewGuid();
                SheetUpdater sheetUpdater = new SheetUpdater(addinId, updaterGuid, config);
                sheetUpdater.CollectCustomSheetParamIds(doc);
                sheetUpdater.CollectIdMaps(doc);

                UpdaterRegistry.RegisterUpdater(sheetUpdater, doc);

                ElementClassFilter sheetFilter = new ElementClassFilter(typeof(ViewSheet));
                UpdaterRegistry.AddTrigger(sheetUpdater.GetUpdaterId(), sheetFilter, Element.GetChangeTypeElementAddition());
                UpdaterRegistry.AddTrigger(sheetUpdater.GetUpdaterId(), sheetFilter, Element.GetChangeTypeElementDeletion());
                foreach (ElementId paramId in sheetUpdater.SheetParameters.Keys)
                {
                    UpdaterRegistry.AddTrigger(sheetUpdater.GetUpdaterId(), sheetFilter, Element.GetChangeTypeParameter(paramId));
                }

                if (!sheetUpdaters.ContainsKey(config.ModelId))
                {
                    sheetUpdaters.Add(config.ModelId, sheetUpdater);
                }

                registered = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to register sheet updater.\n" + ex.Message, "Register Sheet Updater", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(registered);
        }
Пример #26
0
        public void prependViewTemplateNames()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   dbDoc = this.ActiveUIDocument.Document;

            String prependString = Prompt.ShowDialog("String to prepend: ", "Prepend View Template Names");

            ElementClassFilter                   viewFilter = new ElementClassFilter(typeof(Autodesk.Revit.DB.View));
            FilteredElementCollector             collector  = new FilteredElementCollector(dbDoc);
            IEnumerable <Autodesk.Revit.DB.View> allViews   = collector.WherePasses(viewFilter).Cast <Autodesk.Revit.DB.View>().AsEnumerable();

            var viewTemplates = allViews.Where(t => t.IsTemplate);

            using (Transaction t = new Transaction(dbDoc, "Prepend View Template Names"))
            {
                t.Start();

                foreach (var vt in viewTemplates)
                {
                    vt.Name = (prependString + vt.Name);
                }

                t.Commit();
            }
        }
Пример #27
0
        Execute()
        {
            //Get every level by iterating through all elements
            systemLevelsData = new List <LevelsDataSource>();

            FilteredElementCollector fec = new FilteredElementCollector(m_app.ActiveUIDocument.Document);
            ElementClassFilter       elementsAreWanted = new ElementClassFilter(typeof(Level));

            fec.WherePasses(elementsAreWanted);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                Level systemLevel = element as Level;
                if (systemLevel != null)
                {
                    LevelsDataSource levelsDataSourceRow = new LevelsDataSource();

                    levelsDataSourceRow.LevelIDValue = systemLevel.Id.IntegerValue;
                    levelsDataSourceRow.Name         = systemLevel.Name;

                    levelsDataSourceRow.Elevation = systemLevel.Elevation;

                    systemLevelsData.Add(levelsDataSourceRow);
                }
            }

            LevelsForm displayForm = new LevelsForm(this);

            displayForm.ShowDialog();

            return(true);
        }
Пример #28
0
        GetAllSheets(Document doc)
        {
            ElementSet allSheets         = new ElementSet();
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter       elementsAreWanted = new ElementClassFilter(typeof(ViewSheet));

            fec.WherePasses(elementsAreWanted);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                ViewSheet viewSheet = element as ViewSheet;

                if (null == viewSheet)
                {
                    continue;
                }
                else
                {
                    ElementId objId = viewSheet.GetTypeId();
                    if (ElementId.InvalidElementId == objId)
                    {
                        continue;
                    }
                    else
                    {
                        allSheets.Insert(viewSheet);
                    }
                }
            }

            return(allSheets);
        }
Пример #29
0
        private List <double> GetDistancesToFloors(Document doc, View3D view3D, Room room)
        {
            LocationPoint point  = room.Location as LocationPoint;
            XYZ           origin = point.Point;
            XYZ           center = new XYZ(point.Point.X, point.Point.Y, point.Point.Z + 0.01);
            // Project in the positive Z direction up to the floor.
            XYZ rayDirection = new XYZ(0, 0, 1);

            ElementClassFilter filter = new ElementClassFilter(typeof(Floor));

            ReferenceIntersector refIntersector = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);

            refIntersector.FindReferencesInRevitLinks = true;
            IList <ReferenceWithContext> referencesWithContext = refIntersector.Find(center, rayDirection);

            IList <Reference>           intersectRefs            = new List <Reference>();
            Dictionary <Reference, XYZ> dictProvisionForVoidRefs = new Dictionary <Reference, XYZ>();
            List <double> result = new List <double>();

            foreach (ReferenceWithContext r in referencesWithContext)
            {
                XYZ  intersection = r.GetReference().GlobalPoint;
                Line line         = Line.CreateBound(origin, intersection);
                result.Add(line.Length);
            }
            result.Sort();
            return(result);
        }
Пример #30
0
        /// <summary>
        /// iterate all the symbols of levels and beams
        /// </summary>
        /// <returns>A value that signifies if the initialization was successful for true or failed for false</returns>
        private bool Initialize()
        {
            try
            {
                ElementClassFilter       levelFilter = new ElementClassFilter(typeof(Level));
                ElementClassFilter       famFilter   = new ElementClassFilter(typeof(Family));
                LogicalOrFilter          orFilter    = new LogicalOrFilter(levelFilter, famFilter);
                FilteredElementCollector collector   = new FilteredElementCollector(m_revit.ActiveUIDocument.Document);
                FilteredElementIterator  i           = collector.WherePasses(orFilter).GetElementIterator();
                i.Reset();
                bool moreElement = i.MoveNext();
                while (moreElement)
                {
                    object o = i.Current;

                    // add level to list
                    Level level = o as Level;
                    if (null != level)
                    {
                        m_levels.Add(new LevelMap(level));
                        goto nextLoop;
                    }

                    // get
                    Family f = o as Family;
                    if (null == f)
                    {
                        goto nextLoop;
                    }

                    foreach (ElementId elementId in f.GetFamilySymbolIds())
                    {
                        object       symbol     = m_revit.ActiveUIDocument.Document.GetElement(elementId);
                        FamilySymbol familyType = symbol as FamilySymbol;
                        if (null == familyType)
                        {
                            goto nextLoop;
                        }
                        if (null == familyType.Category)
                        {
                            goto nextLoop;
                        }

                        // add symbols of beams and braces to lists
                        string categoryName = familyType.Category.Name;
                        if ("Structural Framing" == categoryName)
                        {
                            m_beamMaps.Add(new SymbolMap(familyType));
                        }
                    }
nextLoop:
                    moreElement = i.MoveNext();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return(true);
        }
        //***********************************GetFamilySymbols***********************************
        public List <FamilyInstance> GetFamilyInstance(Document doc, string name, BuiltInCategory category)
        {
            List <FamilyInstance> List_FamilyInstance = new List <FamilyInstance>();

            ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
            // Category filter
            ElementCategoryFilter Categoryfilter = new ElementCategoryFilter(category);
            // Instance filter
            LogicalAndFilter InstancesFilter = new LogicalAndFilter(familyInstanceFilter, Categoryfilter);

            FilteredElementCollector collector = new FilteredElementCollector(doc);
            // Colletion Array of Elements
            ICollection <Element> Elements = collector.WherePasses(InstancesFilter).ToElements();

            foreach (Element e in Elements)
            {
                FamilyInstance familyInstance = e as FamilyInstance;

                if (null != familyInstance)
                {
                    try
                    {
                        if (familyInstance.Name.Contains(name))
                        {
                            List_FamilyInstance.Add(familyInstance);
                        }
                    }
                    catch (Exception ex)
                    {
                        string x = ex.Message;
                    }
                }
            }
            return(List_FamilyInstance);
        }
Пример #32
0
        //reate and Register Dynamic Model Updaters with the Current Session of Revit. It should only need to be registered one time per session, and affects
        //all documents opened there after
        private Result RegisterUpdaters(UIControlledApplication RevitApplication)
        {
            try
            {
                //Create a new instance of the ViewSheetUpdater Class and Pass the ActiveAddInId for this Application
                Updaters.ViewSheetUpdater viewSheetUpdater = new Updaters.ViewSheetUpdater(RevitApplication.ActiveAddInId);
                //Register the Updater for this Session of Revit. The IsOption bool at the end allows the modifications of the updater to persist even if another user
                //doesnt have the same add-in (For paid / propriatary add-in like Autodesk Subcription itsm)
                UpdaterRegistry.RegisterUpdater(viewSheetUpdater, true);
                //Filter the items being "watched" to just ViewSheets so we use a class filter
                ElementClassFilter viewSheetFilter = new ElementClassFilter(typeof(ViewSheet));
                //Add a trigger to the Updater so Revit knows When to execute the Updater. Here it is set for Element Addition
                //which is when a new sheet is created.
                UpdaterRegistry.AddTrigger(viewSheetUpdater.GetUpdaterId(), viewSheetFilter, Element.GetChangeTypeElementAddition());
                //This Method is set up as a Result becuase you may need to Unregister and Re-Register the updaters for other portions of the App and
                //it is good to know if it all worked or not
                return(Result.Succeeded);
            }

            //Catch any exceptions and present them to the User
            catch (Exception ex)
            {
                TaskDialog.Show("Error Registering Updaters", ex.ToString());
                return(Result.Failed);
            }
        }
Пример #33
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var uiDoc = uiApp.ActiveUIDocument;
            var app   = uiApp.Application;
            var doc   = uiDoc.Document;

            // Start code here

            // Lay nhung doi tuong dang chon
            try
            {
                var familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
                var doorsCategoryFilter  = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
                var listFilter           = new List <ElementFilter>()
                {
                    new ElementCategoryFilter(BuiltInCategory.OST_Doors)
                };

                //var doorInstancesFilters = new LogicalAndFilter(listFilter);
                var doorInstancesFilters = new LogicalAndFilter(familyInstanceFilter, doorsCategoryFilter);
                var collector            = new FilteredElementCollector(doc);
                var doors = collector.WherePasses(doorInstancesFilters).ToElements();
                TaskDialog.Show("Door Count", doors.Count().ToString());
                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Пример #34
0
        /// <summary>
        /// Delete all unnecessary lines
        /// </summary>
        public void DeleteLines()
        {
            int delLineNum = 0;

            try
            {
                SubTransaction transaction = new SubTransaction(m_app.ActiveUIDocument.Document);
                transaction.Start();
                List <Autodesk.Revit.DB.Element> list = new List <Autodesk.Revit.DB.Element>();
                ElementClassFilter       filter       = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement));
                FilteredElementCollector collector    = new FilteredElementCollector(m_app.ActiveUIDocument.Document);
                list.AddRange(collector.WherePasses(filter).ToElements());
                foreach (Autodesk.Revit.DB.Element e in list)
                {
                    ModelCurve mc = e as ModelCurve;
                    if (mc != null)
                    {
                        if (mc.LineStyle.Name == "bounce" || mc.LineStyle.Name == "normal")
                        {
                            m_app.ActiveUIDocument.Document.Delete(e.Id);
                            delLineNum++;
                        }
                    }
                }
                transaction.Commit();
            }
            catch (System.Exception)
            {
            }
        }
Пример #35
0
        private FloorType FindFloorType(Room room)
        {
            FloorType floorType = null;

            try
            {
                var typeName    = room.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR).AsString();
                var collector   = new FilteredElementCollector(m_doc);
                var classFilter = new ElementClassFilter(typeof(FloorType));
                collector.WherePasses(classFilter);

                var query = from element in collector
                            where element.Name == typeName
                            select element;

                var floorTypes = query.Cast <FloorType>().ToList <FloorType>();
                if (floorTypes.Count > 0)
                {
                    floorType = floorTypes[0];
                }

                if (floorTypes.Count == 0)
                {
                    floorType = CreateFloorType(room, typeName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot find the floor type.\n" + ex.Message, "Find Floor Type", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(floorType);
        }
Пример #36
0
 private static void ExtractObjects()
 {
     ElementFilter ductFilter = new ElementCategoryFilter(BuiltInCategory.OST_DuctCurves);
     ElementFilter faminsFilter = new ElementClassFilter(typeof(MEPCurve));
     FilteredElementCollector ductCollector = new FilteredElementCollector(_doc);
     ductCollector.WherePasses(ductFilter).WherePasses(faminsFilter);
     foreach (MEPCurve duct in ductCollector) _ducts.Add(duct);
 }
Пример #37
0
        private static void ExtractObjects()
        {
            List<ElementId> materials = null;
            Material material = null;
            ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
            ElementFilter NonStruWallFilter = new StructuralWallUsageFilter(StructuralWallUsage.NonBearing);
            ElementFilter WallClassFilter = new ElementClassFilter(typeof(Wall));
            FilteredElementCollector GypWalls = new FilteredElementCollector(_doc);
            GypWalls.WherePasses(WallFilter).WherePasses(NonStruWallFilter);
            int[] count1 = new int[2];              //0:Gyp, 1:wallpaper, 2:ceramic
            foreach (Wall wall in GypWalls)
            {
                materials = wall.GetMaterialIds(false).ToList();

                foreach (ElementId eleId in materials)
                {
                    material = _doc.GetElement(eleId) as Material;
                    if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Gypsum]) ++count1[0];
                    else if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.WallPaper]) ++count1[1];
                    else if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Ceramic]) ++count1[2];
                }
                //assert: count1[i] is non-negative
                if (count1[0] == 0) continue;
                if (count1[1] == 0 && count1[2] == 0) _GypWalls.Add(new RichWall(wall,FinishType.None));
                else if(count1[2] == 0)             //assert: count1[1] != 0
                {
                    if (count1[1] == 1) _GypWalls.Add(new RichWall(wall,FinishType.OneWallpaper));
                    else if (count1[1] == 2) _GypWalls.Add(new RichWall(wall,FinishType.TwoWallpaper));
                }
                else if(count1[1] == 0)             //assert: count1[2] != 0
                {
                    if (count1[2] == 1) _GypWalls.Add(new RichWall(wall,FinishType.OneCeramic));
                    else if (count1[2] == 2) _GypWalls.Add(new RichWall(wall,FinishType.TwoCeramic));
                }
                else _abandonWriter.WriteAbandonment(wall, AbandonmentTable.TooManyFinishes);
            }

            if (_addiInfo.requiredComp[(byte)PGComponents.WallFinish])
            {
                int count2 = 0;
                FilteredElementCollector GeneticWalls = new FilteredElementCollector(_doc);
                GeneticWalls.WherePasses(WallFilter).WherePasses(WallClassFilter);
                foreach (Wall wall in GeneticWalls)
                {
                    materials = wall.GetMaterialIds(false).ToList();
                    foreach (ElementId eleId in materials)
                    {
                        material = _doc.GetElement(eleId) as Material;
                        if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Wood]
                        || material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Marble]) ++count2;
                    }
                    if (count2 == 1) _GeneticWalls.Add(new RichWall(wall,FinishType.OneWood));
                    else if (count2 == 2) _GeneticWalls.Add(new RichWall(wall,FinishType.TwoWood));
                    else if (2 <= count2) _abandonWriter.WriteAbandonment(wall, AbandonmentTable.TooManyFinishes);
                }
            }
        }
Пример #38
0
        public static IList<Element> OfElementType(Type elementType)
        {
            var elFilter = new ElementClassFilter(elementType);
            var fec = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument);
            fec.WherePasses(elFilter);

            var instances = fec.ToElements()
                .Select(x => ElementSelector.ByElementId(x.Id.IntegerValue)).ToList();
            return instances;
        }
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
            , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            // get all PanelScheduleView instances in the Revit document.
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter PanelScheduleViewsAreWanted = new ElementClassFilter(typeof(PanelScheduleView));
            fec.WherePasses(PanelScheduleViewsAreWanted);
            List<Element> psViews = fec.ToElements() as List<Element>;

            bool noPanelScheduleInstance = true;

            foreach (Element element in psViews)
            {
                PanelScheduleView psView = element as PanelScheduleView;
                if (psView.IsPanelScheduleTemplate())
                {
                    // ignore the PanelScheduleView instance which is a template.
                    continue;
                }
                else
                {
                    noPanelScheduleInstance = false;
                }

                // choose what format export to, it can be CSV or HTML.
                TaskDialog alternativeDlg = new TaskDialog("Choose Format to export");
                alternativeDlg.MainContent = "Click OK to export in .CSV format, Cancel to export in HTML format.";
                alternativeDlg.CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel;
                alternativeDlg.AllowCancellation = true;
                TaskDialogResult exportToCSV = alternativeDlg.Show();
                
                Translator translator = TaskDialogResult.Cancel == exportToCSV ? new HTMLTranslator(psView) : new CSVTranslator(psView) as Translator;
                string exported = translator.Export();

                // open the file if export successfully.
                if (!string.IsNullOrEmpty(exported))
                {
                    System.Diagnostics.Process.Start(exported);
                }
            }

            if (noPanelScheduleInstance)
            {
                TaskDialog messageDlg = new TaskDialog("Warnning Message");
                messageDlg.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                messageDlg.MainContent = "No panel schedule view is in the current document.";
                messageDlg.Show();
                return Result.Cancelled;
            }

            return Result.Succeeded;
        }
Пример #40
0
        public static IList<Element> OfFamilyType(FamilySymbol familyType)
        {
            var instanceFilter = new ElementClassFilter(typeof(Autodesk.Revit.DB.FamilyInstance));
            var fec = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument);

            var familyInstances = fec.WherePasses(instanceFilter)
                .WhereElementIsNotElementType()
                .ToElements()
                .Cast<Autodesk.Revit.DB.FamilyInstance>()
                .Where(x => x.Symbol.IsSimilarType(familyType.InternalFamilySymbol.Id));

            var instances = familyInstances
                .Select(x => ElementSelector.ByElementId(x.Id.IntegerValue)).ToList();
            return instances;
        }
Пример #41
0
        /// <summary>
        /// Finds all windows in the active document.
        /// </summary>
        /// <returns>An enumerable containing all windows.</returns>
        protected IEnumerable<FamilyInstance> CollectWindows()
        {
            // Windows are family instances whose category is correctly set.

            ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
            ElementCategoryFilter windowCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows);
            LogicalAndFilter andFilter = new LogicalAndFilter(familyInstanceFilter, windowCategoryFilter);
            FilteredElementCollector collector = new FilteredElementCollector(Document);
               ICollection<Element> elementsToProcess = collector.WherePasses(andFilter).ToElements();

            // Convert to IEnumerable of FamilyInstance using LINQ
            IEnumerable<FamilyInstance> windows = from window in elementsToProcess.Cast<FamilyInstance>() select window;

            return windows;
        }
Пример #42
0
        /// <summary>
        /// Given an Enumerable set of Elements, walk through them and filter out the ones of a specific 
        /// category.
        /// </summary>
        /// <param name="filterForCategoryEnum">The BuiltInCategory enum to filter for</param>
        /// <param name="doc">The current Document object</param>
        /// <returns>The filtered ElementSet</returns>
        public static ElementSet FilterToCategory(BuiltInCategory filterForCategoryEnum, bool includeSymbols, Document doc)
        {
            ElementSet elemSet = new ElementSet();
               FilteredElementCollector fec = new FilteredElementCollector(doc);
               ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(Element));
               fec.WherePasses(elementsAreWanted);
               List<Element> elements = fec.ToElements() as List<Element>;

               foreach (Element element in elements)
               {
              elemSet.Insert(element);
               }

            return FilterToCategory(elemSet, filterForCategoryEnum, includeSymbols, doc);
        }
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
            , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            // get one sheet view to place panel schedule.
            ViewSheet sheet = doc.ActiveView as ViewSheet;
            if (null == sheet)
            {
                message = "please go to a sheet view.";
                return Result.Failed;
            }

            // get all PanelScheduleView instances in the Revit document.
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter PanelScheduleViewsAreWanted = new ElementClassFilter(typeof(PanelScheduleView));
            fec.WherePasses(PanelScheduleViewsAreWanted);
            List<Element> psViews = fec.ToElements() as List<Element>;

            Transaction placePanelScheduleOnSheet = new Transaction(doc, "placePanelScheduleOnSheet");
            placePanelScheduleOnSheet.Start();

            XYZ nextOrigin = new XYZ(0.0, 0.0, 0.0);
            foreach (Element element in psViews)
            {
                PanelScheduleView psView = element as PanelScheduleView;
                if (psView.IsPanelScheduleTemplate())
                {
                    // ignore the PanelScheduleView instance which is a template.
                    continue;
                }

                PanelScheduleSheetInstance onSheet = PanelScheduleSheetInstance.Create(doc, psView.Id, sheet);
                onSheet.Origin = nextOrigin;
                BoundingBoxXYZ bbox = onSheet.get_BoundingBox(doc.ActiveView);
                double width = bbox.Max.X - bbox.Min.X;
                nextOrigin = new XYZ(onSheet.Origin.X + width, onSheet.Origin.Y, onSheet.Origin.Z);
            }

            placePanelScheduleOnSheet.Commit();

            return Result.Succeeded;

        }
Пример #44
0
        public Result OnStartup(UIControlledApplication a)
        {
            DeletionUpdater deletionUpdater
              = new DeletionUpdater(a.ActiveAddInId);

            UpdaterRegistry.RegisterUpdater(
              deletionUpdater);

            ElementClassFilter filter
              = new ElementClassFilter(
                typeof(Dimension), true);

            UpdaterRegistry.AddTrigger(
              deletionUpdater.GetUpdaterId(), filter,
              Element.GetChangeTypeElementDeletion());

            //FailureDefinitionRegistry

            return Result.Succeeded;
        }
Пример #45
0
        /// <summary>
        /// populate with levels
        /// </summary>
        private void InitializeListView()
        {
            FilteredElementCollector fec = new FilteredElementCollector(m_app.ActiveUIDocument.Document);
               ElementClassFilter levelsAreWanted = new ElementClassFilter(typeof(Level));
               fec.WherePasses(levelsAreWanted);
               List<Element> elements = fec.ToElements() as List<Element>;

               foreach (Element element in elements)
               {
              Autodesk.Revit.DB.Level sysLevel = element as Autodesk.Revit.DB.Level;
              if (sysLevel != null)
              {
                 ListViewItem lev = new ListViewItem(sysLevel.Name);
                 lev.SubItems.Add(sysLevel.Elevation.ToString());
                 lev.Tag = sysLevel;

                 m_levlv.Items.Add(lev);
              }
               }
        }
Пример #46
0
        private void docOpen(object sender, DocumentOpenedEventArgs e)
        {
            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
             UIApplication uiApp = new UIApplication(app);
             Document doc = uiApp.ActiveUIDocument.Document;

             FilteredElementCollector collector = new FilteredElementCollector(doc);
             collector.WherePasses(new ElementClassFilter(typeof(FamilyInstance)));
             var sphereElements = from element in collector where element.Name == "sphere" select element;
             if (sphereElements.Count() == 0)
             {
            TaskDialog.Show("Error", "Sphere family must be loaded");
            return;
             }
             FamilyInstance sphere = sphereElements.Cast<FamilyInstance>().First<FamilyInstance>();
             FilteredElementCollector viewCollector = new FilteredElementCollector(doc);
             ICollection<Element> views = viewCollector.OfClass(typeof(View3D)).ToElements();
             var viewElements = from element in viewCollector where element.Name == "AVF" select element;
             if (viewElements.Count() == 0)
             {
            TaskDialog.Show("Error", "A 3D view named 'AVF' must exist to run this application.");
            return;
             }
             View view = viewElements.Cast<View>().First<View>();

             SpatialFieldUpdater updater = new SpatialFieldUpdater(uiApp.ActiveAddInId, sphere.Id, view.Id);
             if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater);
             ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
             ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance));
             ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass);
             IList<ElementFilter> filterList = new List<ElementFilter>();
             filterList.Add(wallFilter);
             filterList.Add(familyFilter);
             filterList.Add(massFilter);
             LogicalOrFilter filter = new LogicalOrFilter(filterList);

             UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry());
             UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion());
        }
Пример #47
0
        public Result OnStartup(UIControlledApplication application)
        {
            AddRibbonPanel(application);

            // Failure Definition Registry
            // Implemented in Prevent Deletion Tool
            PreventDeletionUpdater deletionUpdater
              = new PreventDeletionUpdater(application.ActiveAddInId);

            UpdaterRegistry.RegisterUpdater(
              deletionUpdater);

            ElementClassFilter filter
              = new ElementClassFilter(
                typeof(Dimension), true);

            UpdaterRegistry.AddTrigger(
              deletionUpdater.GetUpdaterId(), filter,
              Element.GetChangeTypeElementDeletion());

            return Result.Succeeded;
        }
Пример #48
0
        public void CanCreateAndDeleteAReferencePoint()
        {
            using (var trans = new Transaction(RevitData.Document.Document, "CreateAndDeleteAreReferencePoint"))
            {
                trans.Start();

                FailureHandlingOptions fails = trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                trans.SetFailureHandlingOptions(fails);

                ReferencePoint rp = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ());

                //make a filter for reference points.
                ElementClassFilter ef = new ElementClassFilter(typeof(ReferencePoint));
                FilteredElementCollector fec = new FilteredElementCollector(dynRevitSettings.Doc.Document);
                fec.WherePasses(ef);
                Assert.AreEqual(1, fec.ToElements().Count());

                RevitData.Document.Document.Delete(rp);
                trans.Commit();
            }
        }
Пример #49
0
        /// <summary>
        /// This function gets all the walls in the current Revit document
        /// </summary>
        /// <param name="startNewTransaction">whether do the filtering in a new transaction</param>
        /// <returns>the walls</returns>
        private static IList<Element> GetAllWallElements(bool startNewTransaction)
        {
            if (startNewTransaction)
            {
                using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "FilteringElements"))
                {
                    trans.Start();

                    ElementClassFilter ef = new ElementClassFilter(typeof(Wall));
                    FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                    fec.WherePasses(ef);

                    trans.Commit();
                    return fec.ToElements();
                }
            }
            else
            {
                ElementClassFilter ef = new ElementClassFilter(typeof(Wall));
                FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                fec.WherePasses(ef);
                return fec.ToElements();
            }
        }
Пример #50
0
        /// <summary>
        ///  Used by the SimpleShed to create its floors and the fake roof
        /// </summary>
        /// <param name="profile"></param>
        public Revit.ElementId SimpleFloor( CurveArray profile, Level level )
        {
            Autodesk.Revit.Creation.Document doc = m_revitApp.ActiveUIDocument.Document.Create;
              Autodesk.Revit.Creation.Application applic = m_revitApp.Application.Create;

              // Obtain the required floor type
              FloorType floorType = null;

              try
              {
            FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
            ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( FloorType ) );
            fec.WherePasses( elementsAreWanted );
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach( Element element in elements )
            {
              FloorType fType = element as FloorType;

              if( fType == null )
              {
            continue;
              }

              if( fType.Name == "Generic - 12\"" )
              {
            floorType = fType;
              }
            }
              }
              catch( Exception e )
              {
            throw e;
              }

              // Set the stuctural value
              bool structural = true;

              Revit.ElementId elemId = new ElementId( 0 );

              // Create the floor instance
              try
              {
            if( level.Name == "Level 2" )
            {
              level.Elevation = 10.0;

              Floor f = doc.NewFloor( profile, floorType, level, structural );

              Revit.ElementId fId = f.Id;
              m_shedElements.Add( fId );

              // This param need to be set for any level above Level 1 for the floor to move to the correct level
              Revit.Parameter midFloorparam = f.get_Parameter( BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM );
              midFloorparam.Set( 0.0 );

              return f.LevelId;
            }

            if( level.Name == "Level 1" )
            {

              Floor f = doc.NewFloor( profile, floorType, level, structural );

              Revit.ElementId fId = f.Id;
              m_shedElements.Add( fId );

              return f.LevelId;
            }

            // if none of the types match
            return elemId;
              }
              catch( Exception e )
              {
            throw e;
              }
        }
Пример #51
0
        /// <summary>
        /// Create a floor for the selected set of walls.
        /// </summary>
        public void SimpleFloor()
        {
            Autodesk.Revit.Creation.Document doc = m_revitApp.ActiveUIDocument.Document.Create;
              Autodesk.Revit.Creation.Application applic = m_revitApp.Application.Create;

              // first filter out to only Wall elements
              Revit.ElementSet wallSet = Utils.Selection.FilterToCategory( m_revitApp.ActiveUIDocument.Selection.Elements,
                                              Revit.BuiltInCategory.OST_Walls, false, m_revitApp.ActiveUIDocument.Document );

              if( wallSet.IsEmpty )
              {
            MessageBox.Show( "No wall elements are currently selected" );
            return;
              }

              // Get the wall profile needed for the floor
              CurveArray profile = applic.NewCurveArray();

              foreach( Wall w in wallSet )
              {
            Revit.LocationCurve curve = w.Location as Revit.LocationCurve;
            profile.Append( curve.Curve );
              }

              // Obtain the required floor type
              FloorType floorType = null;

              try
              {
            FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
            ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( FloorType ) );
            fec.WherePasses( elementsAreWanted );
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach( Element element in elements )
            {
              FloorType f = element as FloorType;

              if( null == f )
              {
            continue;
              }

              if( f.Name == "Generic - 12\"" )
              {
            floorType = f;
              }
            }

              }
              catch( Exception e )
              {
            throw e;
              }

              // Set the stuctural value
              bool structural = true;

              // Create the floor instance
              try
              {
            Floor f = doc.NewFloor( profile, floorType, doc.NewLevel( 0.0 ), structural );
              }
              catch( Exception e )
              {
            throw e;
              }
        }
Пример #52
0
        /// <summary>
        /// Modify the width of a wall by changing the layer thickness.
        /// </summary>
        public void ModifyWallWidth()
        {
            Revit.Document doc = m_revitApp.ActiveUIDocument.Document;
              WallType outerWallType = null;

              FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
              ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( WallType ) );
              fec.WherePasses( elementsAreWanted );
              List<Element> elements = fec.ToElements() as List<Element>;

              foreach( Element element in elements )
              {
            WallType wallType = element as WallType;

            if( wallType != null )
            {
              // hardwired to affect a Generic - 8\" Wall Type
              if( wallType.Name == "Generic - 8\"" )
              {
            outerWallType = wallType;
              }
            }
              }

              Boolean success = UpdateHostCompoudStructures( outerWallType );
        }
Пример #53
0
        /// <summary>
        /// Swap any selected door with a hardwired double door.
        /// </summary>
        private void SimpleSwap()
        {
            FamilySymbol doubleDoorSymbol = null;

              Autodesk.Revit.Creation.Document doc = m_revitApp.ActiveUIDocument.Document.Create;
              Revit.Document docu = m_revitApp.ActiveUIDocument.Document;
              Autodesk.Revit.UI.Selection.Selection sel = m_revitApp.ActiveUIDocument.Selection;
              Autodesk.Revit.Creation.Application applic = m_revitApp.Application.Create;

              // first filter out to only Door elements
              Revit.ElementSet doorSet = Utils.Selection.FilterToCategory( m_revitApp.ActiveUIDocument.Selection.Elements,
                                              Revit.BuiltInCategory.OST_Doors, false, m_revitApp.ActiveUIDocument.Document );

              if( doorSet.IsEmpty )
              {
            MessageBox.Show( "No door element is currently selected" );
            return;
              }

              // Load the concerned door family
              FilteredElementCollector fec = new FilteredElementCollector( docu );
              ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( Family ) );
              fec.WherePasses( elementsAreWanted );
              List<Element> elements = fec.ToElements() as List<Element>;

              foreach( Element element in elements )
              {
            Family fam = element as Family;
            if( fam != null )
            {
              if( fam.Name == "Double-Glass 1" )
              {
            doubleDoorSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "72\" x 78\"" );
              }
            }
              }

              string fileName = string.Empty;
              bool success = false;

              // Load the required family

              fileName = "../Data/Platform/Imperial/Library/Architectural/Doors/Double-Glass 1.rfa";
              Family doubleDoorFamily = null;

              if( doubleDoorSymbol == null )
              {
            success = m_revitApp.ActiveUIDocument.Document.LoadFamily( fileName, out doubleDoorFamily );
            doubleDoorSymbol = Utils.FamilyUtil.GetFamilySymbol( doubleDoorFamily, "72\" x 78\"" );
              }

              if( doubleDoorSymbol == null )
              {
            MessageBox.Show( "Please load Double-Glass 1 into project" );
            Utils.UserInput.LoadFamily( null, m_revitApp.ActiveUIDocument.Document );
              }

              // Perform the swap.
              Revit.ElementSet elemSet = sel.Elements;
              System.Collections.IEnumerator iters = elemSet.GetEnumerator();

              while( iters.MoveNext() )
              {
            FamilyInstance famInst = (FamilyInstance) iters.Current;
            famInst.Symbol = doubleDoorSymbol;
              }
        }
Пример #54
0
        /// <summary>
        /// 
        /// </summary>
        public void ClassRoom()
        {
            Revit.Document doc = m_revitApp.ActiveUIDocument.Document;

              // get the symbols in the beginning itself , so that
              // if one is missing you can load it
              FamilySymbol columnSymbol = null;
              FamilySymbol chairSymbol = null;
              FamilySymbol deskSymbol = null;
              FamilySymbol chairMainSymbol = null;
              //FamilySymbol chairSym = null;
              FamilySymbol doorSymbol = null;
              Family columnfamily;
              Family deskfamily;
              Family doorfamily;

              FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
              ElementClassFilter familiesAreWanted = new ElementClassFilter( typeof( Family ) );
              fec.WherePasses( familiesAreWanted );
              List<Element> elements = fec.ToElements() as List<Element>;

              foreach( Element element in elements )
              {
            Family fam = element as Family;
            if( fam != null )
            {
              if( fam.Name == "Rectangular Column" )
              {
            columnSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "24\" x 24\"" );
              }

              if( fam.Name == "Desk" )
              {
            deskSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "60\" x 30\"" );
              }

              if( fam.Name == "Single-Flush" )
              {
            doorSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "36\" x 84\"" );
              }

              if( fam.Name == "Chair-Tablet Arm" )
              {
            chairSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "Chair-Tablet" );
              }

              if( fam.Name == "Chair-Breuer" )
              {
            chairMainSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "Chair-Breuer" );
              }
            }
              }

              String familyNameToLoad = "";

              // check for required families
              if( columnSymbol == null )
              {
            MessageBox.Show( "Please load Rectangular Column 24\" x 24\" into project" );

            String famName = Utils.UserInput.GetFamilyNameFromUser( null, ref familyNameToLoad );

            m_revitApp.ActiveUIDocument.Document.LoadFamily( famName, out columnfamily );
            if( columnfamily != null )
            {
              columnSymbol = Utils.FamilyUtil.GetFamilySymbol( columnfamily, "24\" x 24\"" );
            }
              }

              if( deskSymbol == null )
              {
            MessageBox.Show( "Please load Desk 60\" x 30\" into project" );

            String famName = Utils.UserInput.GetFamilyNameFromUser( null, ref familyNameToLoad );

            m_revitApp.ActiveUIDocument.Document.LoadFamily( famName, out deskfamily );
            if( deskfamily != null )
            {
              deskSymbol = Utils.FamilyUtil.GetFamilySymbol( deskfamily, "36\" x 84\"" );
            }
              }

              if( doorSymbol == null )
              {
            MessageBox.Show( "Please load door Single Flush 36\" x 84\" into project" );

            String famName = Utils.UserInput.GetFamilyNameFromUser( null, ref familyNameToLoad );

            m_revitApp.ActiveUIDocument.Document.LoadFamily( famName, out doorfamily );
            if( doorfamily != null )
            {
              doorSymbol = Utils.FamilyUtil.GetFamilySymbol( doorfamily, "36\" x 84\"" );
            }
              }

              IDictionary<String, String> libsPaths = m_revitApp.Application.GetLibraryPaths();
              string pathName = string.Empty;
              foreach( KeyValuePair<String, String> libPath in libsPaths )
              {
            pathName = libPath.Value;
            break;
              }

              string fileName = string.Empty;
              bool success = false;

              fileName = pathName + @"\Furniture\Chair-Tablet Arm.rfa";

              //Boolean load = m_revitApp.ActiveUIDocument.Document.LoadFamilySymbol(fileName, "Chair-Tablet Arm", ref chairSym);

              Family chairFamily;
              // if not found in doc try to load automatically
              if( chairSymbol == null )
              {
            success = m_revitApp.ActiveUIDocument.Document.LoadFamily( fileName, out chairFamily );
            chairSymbol = Utils.FamilyUtil.GetFamilySymbol( chairFamily, "Chair-Tablet Arm" );
              }
              // last ditch effort by trying to load manually
              if( chairSymbol == null )
              {
            MessageBox.Show( "Please load Chair-Tablet Arm into project" );
            Utils.UserInput.LoadFamily( null, m_revitApp.ActiveUIDocument.Document );
              }

              fileName = pathName + @"\Furniture\Chair-Breuer.rfa";
              Family chairMainFamily;
              // if not found in doc try to load automatically
              if( chairMainSymbol == null )
              {
            success = m_revitApp.ActiveUIDocument.Document.LoadFamily( fileName, out chairMainFamily );
            chairMainSymbol = Utils.FamilyUtil.GetFamilySymbol( chairMainFamily, "Chair-Breuer" );
              }
              // last ditch effort by trying to load manually
              if( chairMainSymbol == null )
              {
            MessageBox.Show( "Please load Chair-Breuer into project" );
            Utils.UserInput.LoadFamily( null, m_revitApp.ActiveUIDocument.Document );
              }

              // get the level on which we want to build
              Level level1 = null;
              FilteredElementCollector levelFec = new FilteredElementCollector( doc );
              ElementClassFilter levelsAreWanted = new ElementClassFilter( typeof( Level ) );
              levelFec.WherePasses( levelsAreWanted );
              List<Element> levels = levelFec.ToElements() as List<Element>;

              foreach( Element element in levels )
              {
            Level levelTemp = element as Level;
            if( levelTemp != null )
            {
              if( levelTemp.Name == "Level 1" )
              {
            level1 = levelTemp;
            break;
              }
            }
              }

              // draw 4 lines
              XYZ startPt1 = new XYZ( 0.0, 0.0, 0.0 );
              XYZ endPt1 = new XYZ( 56.5, 0.0, 0.0 );
              Line line1 = Line.CreateBound( startPt1, endPt1 );

              XYZ startPt2 = endPt1;
              XYZ endPt2 = new XYZ( 56.5, 61.5, 0.0 );
              Line line2 = Line.CreateBound( startPt2, endPt2 );

              XYZ startPt3 = endPt2;
              XYZ endPt3 = new XYZ( 0.0, 61.5, 0.0 );
              Line line3 = Line.CreateBound( startPt3, endPt3 );

              XYZ startPt4 = endPt3;
              XYZ endPt4 = startPt1;
              Line line4 = Line.CreateBound( startPt4, endPt4 );

              // get the wall types we want
              WallType curtainWallType = null;
              WallType outerWallType = null;

              FilteredElementCollector wallTypeFec = new FilteredElementCollector( doc );
              ElementClassFilter wallTypesAreWanted = new ElementClassFilter( typeof( WallType ) );
              wallTypeFec.WherePasses( wallTypesAreWanted );
              List<Element> wallTypes = wallTypeFec.ToElements() as List<Element>;
              foreach( Element element in wallTypes )
              {
            WallType wallType = element as WallType;
            if( wallType != null )
            {
              if( wallType.Name == "Curtain Wall 1" )
              {
            curtainWallType = wallType;
              }
              if( wallType.Name == "Generic - 6\" Masonry" )
              {
            outerWallType = wallType;
              }
            }
              }

              // draw 4 walls
              Autodesk.Revit.DB.Document activeDoc = m_revitApp.ActiveUIDocument.Document;
              Wall wall1 = Wall.Create( activeDoc, line1, outerWallType.Id, level1.Id, 7.0, 0.0, false, false );
              Wall wall2 = Wall.Create( activeDoc, line2, curtainWallType.Id, level1.Id, 7.0, 0.0, false, false );
              Wall wall3 = Wall.Create( activeDoc, line3, curtainWallType.Id, level1.Id, 7.0, 0.0, false, false );
              Wall wall4 = Wall.Create( activeDoc, line4, curtainWallType.Id, level1.Id, 7.0, 0.0, false, false );

              FamilyInstance StructColumn1 = m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( startPt1, columnSymbol, wall1, level1, StructuralType.Column );
              FamilyInstance StructColumn2 = m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( startPt2, columnSymbol, wall2, level1, StructuralType.Column );
              FamilyInstance StructColumn3 = m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( startPt3, columnSymbol, wall3, level1, StructuralType.Column );
              FamilyInstance StructColumn4 = m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( startPt4, columnSymbol, wall4, level1, StructuralType.Column );

              int row = 5;
              int col = 8;

              double x = 5.0;
              double y = 11.0;
              double z = 0.0;

              XYZ refDirection = new XYZ( 1, 10, 0 );

              // place all the chairs
              for( int i = 0; i < row; i++ )
              {
            y = y + 8;
            for( int j = 0; j < col; j++ )
            {
              x = x + 5;
              XYZ location = new XYZ( x, y, z );
              FamilyInstance famInst = m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( location, chairSymbol, StructuralType.UnknownFraming );

              // flip the chairs 180 degrees
              XYZ pt = location;
              XYZ dir = GeomUtils.kZAxis;
              Line zAxis = Line.CreateUnbound( pt, dir );
              famInst.Location.Rotate( zAxis, GeomUtils.kRad180 );
            }
            x = x - ( col * 5 );
              }

              // place the desk
              XYZ deskPosition = new XYZ( 15.0, 8.0, 0.0 );
              m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( deskPosition, deskSymbol, StructuralType.UnknownFraming );

              // place the chair
              XYZ chairPosition = new XYZ( 18, 7.0, 0.0 );
              m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( chairPosition, chairMainSymbol, StructuralType.UnknownFraming );

              // place the door
              XYZ doorPosition = new XYZ( 46.0, 0.0, 0.0 );
              m_revitApp.ActiveUIDocument.Document.Create.NewFamilyInstance( doorPosition, doorSymbol, wall1, StructuralType.Brace );
        }
Пример #55
0
        /// <summary>
        /// Creates a simple shed consisting of a door, window, a few floors and walls
        /// </summary>
        public void SimpleShed()
        {
            FamilySymbol doorSymbol = null;
              FamilySymbol windowSymbol = null;
              Family doorFamily = null;
              Family windowFamily = null;
              Autodesk.Revit.Creation.Document doc = m_revitApp.ActiveUIDocument.Document.Create;
              Revit.Document docu = m_revitApp.ActiveUIDocument.Document;
              Autodesk.Revit.Creation.Application applic = m_revitApp.Application.Create;

              //The levels for the floors and the fake roof
              Level floorLevel = null;
              Level midLevel = null;

              Revit.ElementSet wallSet = new ElementSet();

              // Create a new CurveArray to provide the profile of the walls to the floor
              CurveArray curArray = applic.NewCurveArray();

              // iterate through all available levels...
              FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
              ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( Level ) );
              fec.WherePasses( elementsAreWanted );
              List<Element> elements = fec.ToElements() as List<Element>;

              foreach( Element element in elements )
              {
            Level sysLevel = element as Level;
            if( sysLevel != null )
            {
              String name = sysLevel.Name;

              if( name == "Level 1" )
              {
            floorLevel = sysLevel;
              }

              if( name == "Level 2" )
              {
            midLevel = sysLevel;
              }
            }
              }

              // first create 4 walls

              // wall1
              XYZ pt1 = new XYZ( 10.0, 10.0, 0.0 );
              XYZ pt2 = new XYZ( 30.0, 10.0, 0.0 );

              Line line = Line.CreateBound( pt1, pt2 );

              Wall windowHost = Wall.Create( docu, line, floorLevel.Id, false );

              curArray.Append( line );
              wallSet.Insert( windowHost );

              Revit.ElementId windowHostId = windowHost.Id;
              m_shedElements.Add( windowHostId );

              // wall2
              XYZ pt3 = new XYZ( 10.0, 10.0, 0.0 );
              XYZ pt4 = new XYZ( 10.0, 30.0, 0.0 );

              Line line1 = Line.CreateBound( pt3, pt4 );

              Wall wall2 = Wall.Create( docu, line1, floorLevel.Id, false );

              curArray.Append( line1 );
              wallSet.Insert( wall2 );

              Revit.ElementId wall2Id = wall2.Id;
              m_shedElements.Add( wall2Id );

              // wall3
              XYZ pt5 = new XYZ( 10.0, 30.0, 0.0 );
              XYZ pt6 = new XYZ( 30.0, 30.0, 0.0 );

              Line line2 = Line.CreateBound( pt5, pt6 );

              Wall doorHost = Wall.Create( docu, line2, floorLevel.Id, false );

              curArray.Append( line2 );
              wallSet.Insert( doorHost );

              Revit.ElementId doorHostId = doorHost.Id;
              m_shedElements.Add( doorHostId );

              // wall4
              XYZ pt7 = new XYZ( 30.0, 30.0, 0.0 );
              XYZ pt8 = new XYZ( 30.0, 10.0, 0.0 );

              Line line3 = Line.CreateBound( pt7, pt8 );

              Wall wall4 = Wall.Create( docu, line3, floorLevel.Id, false );

              curArray.Append( line3 );
              wallSet.Insert( wall4 );

              Revit.ElementId wall4Id = wall4.Id;
              m_shedElements.Add( wall4Id );

              if( curArray != null )
              {
            // add two floors to the walls created above
            Revit.ElementId floorId = SimpleFloor( curArray, floorLevel );
            SimpleFloor( curArray, midLevel );

            // set the top/bottom constraint and room bounding  params for the walls

            // Note: The WALL_TOP/BOTTOM_IS_ATTACHED parameter's value when set, does not seem to stick. This needs
            // to be looked into as well. arj 7/25/06

            // The WALL_TOP/BOTTOM_IS_ATTACHED parameters are Read Only and cannot be set. arj 01/17/07
            foreach( Wall wall in wallSet )
            {
              Revit.Parameter wallRoomBound = wall.get_Parameter( BuiltInParameter.WALL_ATTR_ROOM_BOUNDING );
              wallRoomBound.Set( 1 );

              Revit.Parameter wallBaseConstr = wall.get_Parameter( BuiltInParameter.WALL_BASE_CONSTRAINT );
              wallBaseConstr.Set( floorId );
            }
              }

              // set the location for elements such as doors, windows

              XYZ doorLocation = new XYZ( 20.0, 30.0, 0.0 );
              XYZ windowLocation = new XYZ( 20.0, 10.0, 10.0 );

              // check for required symbols
              FilteredElementCollector familyFec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
              ElementClassFilter familiesAreWanted = new ElementClassFilter( typeof( Family ) );
              familyFec.WherePasses( familiesAreWanted );
              List<Element> families = familyFec.ToElements() as List<Element>;

              foreach( Element element in families )
              {
            Family fam = element as Family;
            if( fam != null )
            {
              if( fam.Name == "Single-Flush" )
              {
            doorSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "36\" x 84\"" );
              }

              if( fam.Name == "Fixed" )
              {
            windowSymbol = Utils.FamilyUtil.GetFamilySymbol( fam, "24\" x 48\"" );
              }
            }
              }

              // check for required symbols

              String familyNameToLoad = "";

              if( doorSymbol == null )
              {
            MessageBox.Show( "Please load Single-Flush 34\" x 84\" into project" );

            String famName = Utils.UserInput.GetFamilyNameFromUser( null, ref familyNameToLoad );

            m_revitApp.ActiveUIDocument.Document.LoadFamily( famName, out doorFamily );
            if( doorFamily != null )
            {
              doorSymbol = Utils.FamilyUtil.GetFamilySymbol( doorFamily, "36\" x 84\"" );
            }
              }

              if( windowSymbol == null )
              {
            MessageBox.Show( "Please load Fixed 24\" x 48\" into project" );

            String famName = Utils.UserInput.GetFamilyNameFromUser( null, ref familyNameToLoad );

            m_revitApp.ActiveUIDocument.Document.LoadFamily( famName, out windowFamily );
            if( windowFamily != null )
            {
              windowSymbol = Utils.FamilyUtil.GetFamilySymbol( windowFamily, "24\" x 48\"" );
            }
              }

              // Create the door instance

              floorLevel.Elevation = 0.0;
              FamilyInstance doorInst = doc.NewFamilyInstance( doorLocation, doorSymbol, doorHost, floorLevel, StructuralType.Column );

              Revit.ElementId doorInstId = doorInst.Id;
              m_shedElements.Add( doorInstId );

              // Create the window instance

              floorLevel.Elevation = 0.0;
              FamilyInstance windowInst = doc.NewFamilyInstance( windowLocation, windowSymbol, windowHost, floorLevel, StructuralType.Column );

              // The sill height needs to be set to 4.0 or less for the window to be visible in Level 1 view.
              Revit.Parameter sillHeightParam = windowInst.get_Parameter( BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM );
              sillHeightParam.Set( 4.0 );

              Revit.ElementId windowInstId = windowInst.Id;
              m_shedElements.Add( windowInstId );
        }
Пример #56
0
        private void ProcessElements( Document doc )
        {
            FilteredElementCollector fec = new FilteredElementCollector( doc );
              ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( Element ) );
              fec.WherePasses( elementsAreWanted );
              List<Element> elements = fec.ToElements() as List<Element>;

              foreach( Element element in elements )
              {
            RawObjStats( element );

            if( element != null )
            {
              SymbolRefStats( element );
              CategoryStats( element );
            }
              }
        }
Пример #57
0
        GetAvailableViewsToExport (Document doc)
        {
            ViewSet viewSet = new ViewSet();

            // TBD: using a filter iterator will only give you the base class View, not derived classes
            // like View3D or ViewDrafting.
            /*ElementFilterIterator viewIter = m_revitApp.ActiveUIDocument.Document.GetElements(typeof(Autodesk.Revit.DB.View));
            while (viewIter.MoveNext()) {
                Autodesk.Revit.DB.View tmpView = (Autodesk.Revit.DB.View)viewIter.Current;
                if (tmpView.CanBePrinted)
                    viewSet.Insert((Autodesk.Revit.DB.View)viewIter.Current);
            }*/

            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(View));
            fec.WherePasses(elementsAreWanted);
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach (Element element in elements)
            {
               Autodesk.Revit.DB.View tmpView = element as Autodesk.Revit.DB.View;

               if ((tmpView != null) && tmpView.CanBePrinted)
               {
                  viewSet.Insert(tmpView);
               }
            }

            return viewSet;
        }
Пример #58
0
        // should be handled by the ModelUpdater class. But there are some
        // cases where the document modifications handled there do no catch
        // certain document interactions. Those should be registered here.
        /// <summary>
        ///     Register some document updaters. Generally, document updaters
        /// </summary>
        /// <param name="application"></param>
        private static void RegisterAdditionalUpdaters(UIControlledApplication application)
        {
            var sunUpdater = new SunPathUpdater(application.ActiveAddInId);

            if (!UpdaterRegistry.IsUpdaterRegistered(sunUpdater.GetUpdaterId()))
                UpdaterRegistry.RegisterUpdater(sunUpdater);

            var sunFilter = new ElementClassFilter(typeof(SunAndShadowSettings));
            var filterList = new List<ElementFilter> { sunFilter };
            ElementFilter filter = new LogicalOrFilter(filterList);
            UpdaterRegistry.AddTrigger(
                sunUpdater.GetUpdaterId(),
                filter,
                Element.GetChangeTypeAny());
            Updaters.Add(sunUpdater);
        }
            public Result Execute(
                ExternalCommandData commandData,
                ref string message,
                ElementSet elements)
            {
                try
                {
                  UIApplication uiApp = commandData.Application;
                  UIDocument uidoc = uiApp.ActiveUIDocument;
                  Application app = uiApp.Application;
                  Document doc = uidoc.Document;

                  Stopwatch sw = Stopwatch.StartNew();

                  // f5 = f1 && f4
                  // = f1 && (f2 || f3)
                  // = family instance and (door or window)

                  #region Filters and collector definitions

                  ElementClassFilter f1
                = new ElementClassFilter(
                  typeof( FamilyInstance ) );

                  ElementCategoryFilter f2
                = new ElementCategoryFilter(
                  BuiltInCategory.OST_Doors );

                  ElementCategoryFilter f3
                = new ElementCategoryFilter(
                  BuiltInCategory.OST_Windows );

                  LogicalOrFilter f4
                = new LogicalOrFilter( f2, f3 );

                  LogicalAndFilter f5
                = new LogicalAndFilter( f1, f4 );

                  FilteredElementCollector collector
                = new FilteredElementCollector( doc );

                  #endregion

                  //#region Filtering with a class filter
                  //List<Element> openingInstances =
                  //  collector.WherePasses(f5).ToElements()
                  //    as List<Element>;
                  //#endregion

                  //#region Filtering with an anonymous method
                  //List<Element> openings = collector
                  //  .WherePasses(f4)
                  //  .ToElements() as List<Element>;
                  //List<Element> openingInstances
                  //  = openings.FindAll(
                  //    e => e is FamilyInstance );
                  //#endregion

                  #region Filtering with LINQ
                  List<Element> openings = collector
                .WherePasses( f4 )
                .ToElements() as List<Element>;

                  List<Element> openingInstances
                = ( from instances in openings
                where instances is FamilyInstance
                select instances ).ToList<Element>();
                  #endregion

                  int n = openingInstances.Count;
                  sw.Stop();

                  Debug.WriteLine( string.Format(
                "Time to get {0} elements: {1}ms",
                n, sw.ElapsedMilliseconds ) );

                  return Result.Succeeded;
                }
                catch( Exception ex )
                {
                  message = ex.Message + ex.StackTrace;
                  return Result.Failed;
                }
            }
Пример #60
0
        /// <summary>
        /// Demonstrates the increase of floor to floor height by iterating over a set of available
        /// levels.
        /// </summary>
        public void SimpleLevelIteration()
        {
            // Clear all related elements if a shed has already been created to prevent overlapping elements.
              m_revitApp.ActiveUIDocument.Document.Delete( m_shedElements );

              // Use the simple shed sample to demonstrate the increase in floor to floor height.
              SimpleShed();

              DialogResult dlgRes = MessageBox.Show( "This will increase the floor to floor height of the Simple Shed by 10 Ft \n \t\t Hit Cancel to see original shed.", "Test Framework", MessageBoxButtons.OKCancel, MessageBoxIcon.Information );

              if( dlgRes == System.Windows.Forms.DialogResult.OK )
              {

            ArrayList levels = new ArrayList();
            ArrayList elevations = new ArrayList();
            Hashtable hash = new Hashtable();

            FilteredElementCollector fec = new FilteredElementCollector( m_revitApp.ActiveUIDocument.Document );
            ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( Level ) );
            fec.WherePasses( elementsAreWanted );
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach( Element element in elements )
            {
              Level systemLevel = element as Level;
              if( null != systemLevel )
              {
            // collect all the levels
            levels.Add( systemLevel );
              }
            }

            // Polulates a hashtable with the [key. value] pair represented as [Elevation, Level]
            // Also populate a list of elevations.

            for( Int32 i = 0; i < levels.Count; i++ )
            {

              Level lev = (Level) levels[i];

              if( !hash.ContainsKey( lev.Elevation ) && !hash.ContainsValue( lev ) )
              {
            hash.Add( lev.Elevation, lev );
              }

              elevations.Add( lev.Elevation );
            }

            // Sort the elevations
            elevations.Sort();

            Double elevation = (Double) elevations[0];

            // Now that we have the elevations sorted, get the levels corresponding to them and bump
            // them up by a desired value.

            for( Int32 z = 1; z < elevations.Count; z++ )
            {

              Double elev = (Double) elevations[z];

              if( elev != 0.0 )
              {
            Level level = (Level) hash[elev];

            elevation = elevation + 20.0;
            level.Elevation = elevation;
              }
            }
              }
        }