Exemple #1
0
        /// <summary>
        /// Method that creates a phase object equal to the last phase in the active document
        /// </summary>
        /// <returns></returns>
        static public Phase CreatePhase()
        {
            PhaseArray phases = EADocumentData.Doc.Phases;
            int        n      = phases.Size;

            return(phases.get_Item(n - 1));
        }
        /// <summary>
        /// Initializes the comboboxes via the configuration options.
        /// </summary>
        private void InitializeConfigurationOptions()
        {
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x2));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x3));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x3CV2));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFCCOBIE));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFCBCA));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC4));

            foreach (IFCFileFormat fileType in Enum.GetValues(typeof(IFCFileFormat)))
            {
                IFCFileFormatAttributes item = new IFCFileFormatAttributes(fileType);
                comboboxFileType.Items.Add(item);
            }

            for (int level = 0; level <= 2; level++)
            {
                IFCSpaceBoundariesAttributes item = new IFCSpaceBoundariesAttributes(level);
                comboboxSpaceBoundaries.Items.Add(item);
            }

            PhaseArray phaseArray = IFCCommandOverrideApplication.TheDocument.Phases;

            comboboxActivePhase.Items.Add(new IFCPhaseAttributes(ElementId.InvalidElementId));  // Default.
            foreach (Phase phase in phaseArray)
            {
                comboboxActivePhase.Items.Add(new IFCPhaseAttributes(phase.Id));
            }

            // Initialize level of detail combo box
            comboBoxLOD.Items.Add(Properties.Resources.DetailLevelExtraLow);
            comboBoxLOD.Items.Add(Properties.Resources.DetailLevelLow);
            comboBoxLOD.Items.Add(Properties.Resources.DetailLevelMedium);
            comboBoxLOD.Items.Add(Properties.Resources.DetailLevelHigh);
        }
        /// <summary>
        /// Initializes the comboboxes via the configuration options.
        /// </summary>
        private void InitializeConfigurationOptions()
        {
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x2));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x3));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFC2x3CV2));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFCCOBIE));
            comboboxIfcType.Items.Add(new IFCVersionAttributes(IFCVersion.IFCBCA));
            // TODO - how to handle IFC4?

            foreach (IFCFileFormat fileType in Enum.GetValues(typeof(IFCFileFormat)))
            {
                IFCFileFormatAttributes item = new IFCFileFormatAttributes(fileType);
                comboboxFileType.Items.Add(item);
            }

            for (int level = 0; level <= 2; level++)
            {
                IFCSpaceBoundariesAttributes item = new IFCSpaceBoundariesAttributes(level);
                comboboxSpaceBoundaries.Items.Add(item);
            }

            PhaseArray phaseArray = IFCCommandOverrideApplication.TheDocument.Phases;

            comboboxActivePhase.Items.Add(new IFCPhaseAttributes(ElementId.InvalidElementId));  // Default.
            foreach (Phase phase in phaseArray)
            {
                comboboxActivePhase.Items.Add(new IFCPhaseAttributes(phase.Id));
            }
        }
Exemple #4
0
        private void PopulatePhases(Document doc)
        {
            CbPhases = new ObservableCollection <ComboBoxItem>();

            // Select phases
            PhaseArray aPhase = doc.Phases;

            IOrderedEnumerable <Phase> phases = aPhase.Cast <Phase>().OrderBy(ph => ph.Name);

            int count = 0;

            foreach (var ph in phases)
            {
                ComboBoxItem comb = new ComboBoxItem();
                comb.Content = ph.Name;
                comb.Tag     = ph;
                CbPhases.Add(comb);

                if (count == 0)
                {
                    SelectedComboItemPhase = comb;
                }

                count++;
            }
        }
Exemple #5
0
        /// <summary>
        /// Function to craete comboBox with title blocks
        /// </summary>
        /// <param name="doc"></param>
        private void PopulateTitleBlocks(Document doc)
        {
            CbTitleBlocks = new ObservableCollection <ComboBoxItem>();

            // Select TitleBlocks
            PhaseArray aPhase = doc.Phases;
            FilteredElementCollector titleBlocksCollector = new FilteredElementCollector(doc)
                                                            .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                            .WhereElementIsElementType();

            IOrderedEnumerable <FamilySymbol> titleBlocks = titleBlocksCollector.Cast <FamilySymbol>().OrderBy(tb => tb.Family.Name);

            int count = 0;

            foreach (var tb in titleBlocks)
            {
                if (count == 0)
                {
                    ComboBoxItem combo = new ComboBoxItem();
                    combo.Content = "Current Title Block";
                    CbTitleBlocks.Add(combo);
                    SelectedComboItemTitleBlock = combo;
                }

                ComboBoxItem comb = new ComboBoxItem();
                comb.Content = tb.Family.Name + " - " + tb.Name;
                comb.Tag     = tb;
                CbTitleBlocks.Add(comb);

                count++;
            }
        }
        /// <summary>
        /// Gets element filter that match certain phases.
        /// </summary>
        /// <param name="document">The Revit document.</param>
        /// <returns>The element filter.</returns>
        private static ElementFilter GetPhaseStatusFilter(Document document, Element filterView)
        {
            List <ElementOnPhaseStatus> phaseStatuses = new List <ElementOnPhaseStatus>();

            phaseStatuses.Add(ElementOnPhaseStatus.None);  //include "none" because we might want to export phaseless elements.
            phaseStatuses.Add(ElementOnPhaseStatus.Existing);
            phaseStatuses.Add(ElementOnPhaseStatus.New);

            PhaseArray phaseArray = document.Phases;

            ElementId phaseId = ElementId.InvalidElementId;

            if (filterView != null)
            {
                Parameter currPhase = filterView.get_Parameter(BuiltInParameter.VIEW_PHASE);
                if (currPhase != null)
                {
                    phaseId = currPhase.AsElementId();
                }
            }
            if (phaseId == ElementId.InvalidElementId)
            {
                Phase lastPhase = phaseArray.get_Item(phaseArray.Size - 1);
                phaseId = lastPhase.Id;
            }

            return(new ElementPhaseStatusFilter(phaseId, phaseStatuses));
        }
Exemple #7
0
        private void CollectSourceItems()
        {
            try
            {
                sourceItems = new List <ItemInfo>();

                //workset
                FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(m_doc);
                IList <Workset>          worksets         = worksetCollector.ToWorksets();
                var userWorksets = from ws in worksets where ws.Kind == WorksetKind.UserWorkset select ws;
                if (userWorksets.Count() > 0)
                {
                    foreach (Workset workset in userWorksets)
                    {
                        ItemInfo info = new ItemInfo(workset, ViewBy.Workset);
                        sourceItems.Add(info);
                    }
                }

                //phase
                PhaseArray phases = m_doc.Phases;
                if (phases.Size > 0)
                {
                    foreach (Phase phase in phases)
                    {
                        ItemInfo info = new ItemInfo(phase, ViewBy.Phase);
                        sourceItems.Add(info);
                    }
                }

                //design option
                FilteredElementCollector collector = new FilteredElementCollector(m_doc);
                IList <DesignOption>     options   = collector.OfClass(typeof(DesignOption)).ToElements().Cast <DesignOption>().ToList();
                foreach (DesignOption dOption in options)
                {
                    ItemInfo info = new ItemInfo(dOption, ViewBy.DesignOption);
                    sourceItems.Add(info);
                }

                //linked models
                collector = new FilteredElementCollector(m_doc);
                IList <RevitLinkType> types = collector.OfClass(typeof(RevitLinkType)).ToElements().Cast <RevitLinkType>().ToList();
                foreach (RevitLinkType linkType in types)
                {
                    ItemInfo info = new ItemInfo(linkType, ViewBy.Link);
                    sourceItems.Add(info);
                }

                sourceItems = sourceItems.OrderBy(o => o.ItemName).ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to collect source items.\n" + ex.Message, "Collect Source Items", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        public Phase GetActivePhase(Document doc)
        {
            PhaseArray phases = doc.Phases;
            Phase      phase  = null;

            if (0 != phases.Size)
            {
                phase = doc.GetElement(doc.ActiveView.get_Parameter(BuiltInParameter.VIEW_PHASE).AsElementId()) as Phase;
            }
            return(phase);
        }
        /// <summary>
        /// The name of the default phase to export (the last phase).
        /// </summary>
        /// <returns></returns>
        static public string GetDefaultPhaseName()
        {
            PhaseArray phases = IFCCommandOverrideApplication.TheDocument.Phases;

            if (phases == null || phases.Size == 0)
            {
                return("");
            }
            Phase lastPhase = phases.get_Item(phases.Size - 1);

            return(lastPhase.Name);
        }
Exemple #10
0
 public static Phase GetLatestPhase(Document doc)
 {
     try
     {
         PhaseArray allPhases = doc.Phases;
         return(allPhases.get_Item(allPhases.Size - 1));
     }
     catch (Exception e)
     {
         WF.MessageBox.Show($"Error in RevitMethods.GetLatestPhase: {e}");
         return(null);
     }
 }
Exemple #11
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            List <FamilyInstance> karkas = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                           .WhereElementIsNotElementType()
                                           .Cast <FamilyInstance>()
                                           .ToList();

            List <FamilyInstance> kolon = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();

            //List
            List <FamilyInstance> myKar = new List <FamilyInstance>();

            foreach (FamilyInstance i in karkas)
            {
                if (i.StructuralType.ToString() != "NonStructural")
                {
                    myKar.Add(i);
                }
            }

            using (Transaction tr = new Transaction(doc, "metall"))
            {
                tr.Start();

                foreach (FamilyInstance i in myKar)
                {
                    i.LookupParameter("АММО_Длина_КМ").Set(i.get_Parameter(BuiltInParameter.STRUCTURAL_FRAME_CUT_LENGTH).AsDouble());
                }
                foreach (FamilyInstance i in kolon)
                {
                    i.LookupParameter("АММО_Длина_КМ").Set(i.get_Parameter(BuiltInParameter.INSTANCE_LENGTH_PARAM).AsDouble());
                }
                tr.Commit();
            }
            return(Result.Succeeded);
        }
Exemple #12
0
        public static Dictionary <string, object> Phase()
        {
            List <dynamic> phases    = new List <dynamic>();
            List <dynamic> phaseName = new List <dynamic>();
            var            doc       = DocumentManager.Instance.CurrentDBDocument;
            PhaseArray     phase     = doc.Phases;

            foreach (Autodesk.Revit.DB.Phase i in phase)
            {
                phases.Add(i.Id);
                phaseName.Add(i.Name);
            }

            return(new Dictionary <string, object>
            {
                { "Phase Name", phaseName },
                { "Phase", phases }
            });
        }
Exemple #13
0
        public RoomsCDRTRequest(UIApplication uiApp, String text)
        {
            RVTDocument doc = uiApp.ActiveUIDocument.Document;

            Autodesk.Revit.DB.View activeView = doc.ActiveView;

            //Verify the active view is a floor plan view
            if (activeView.ViewType != ViewType.FloorPlan)
            {
                MessageBox.Show("Please run from a demo floor plan view.");
            }
            else
            {
                //Get the current phase of the active view
                Phase     currentPhase    = doc.GetElement(activeView.get_Parameter(BuiltInParameter.VIEW_PHASE).AsElementId()) as Phase;
                ElementId currentPhaseId  = currentPhase.Id;
                ElementId previousPhaseId = null;
                //Collect the phases of the document
                PhaseArray phaseArray = doc.Phases;

                //Cycle through the phases in the project to get the previous phase
                for (int i = 0; i < phaseArray.Size; i++)
                {
                    //By finding the index of the current phase, which must not be the first phase, the phase in the previous index can be obtained
                    if (phaseArray.get_Item(i).ToString() == currentPhase.ToString() && i != 0)
                    {
                        previousPhaseId = phaseArray.get_Item(i - 1).Id;
                    }
                    i++;
                }

                //Collect the rooms in the current view where their phase is equal to the active view's phase
                List <Room>   currentVisibleRooms       = new FilteredElementCollector(doc, activeView.Id).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements().Cast <Room>().Where(r => r.get_Parameter(BuiltInParameter.ROOM_PHASE).AsElementId() == currentPhaseId).ToList();
                List <string> currentVisibleRoomNumbers = new List <string>();

                //Get the list of currently visible rooms' numbers
                foreach (Room room in currentVisibleRooms)
                {
                    currentVisibleRoomNumbers.Add(room.Number);
                }

                //Only continue if the previous phase was found
                if (previousPhaseId != null)
                {
                    List <Room> previousRoomsToTag = new List <Room>();
                    Outline     outline            = null;
                    try
                    {
                        //This portion will require a new outline from the view's bounding box
                        BoundingBoxXYZ viewBBox = activeView.get_BoundingBox(activeView);
                        //Get the active view as a plan view so the view range can be obtained for the height of the outline
                        ViewPlan      viewPlan      = activeView as ViewPlan;
                        PlanViewRange planViewRange = viewPlan.GetViewRange();
                        double        minX          = viewBBox.Min.X;
                        double        minY          = viewBBox.Min.Y;
                        //The bottom Z point of the outline will be the elevation of the view's level plus the bottom offset
                        double minZ = activeView.GenLevel.Elevation + planViewRange.GetOffset(PlanViewPlane.BottomClipPlane);
                        double maxX = viewBBox.Max.X;
                        double maxY = viewBBox.Max.Y;
                        //The top Z point of the outline will be the elevation of the view's level plust the top offset
                        double maxZ = activeView.GenLevel.Elevation + planViewRange.GetOffset(PlanViewPlane.TopClipPlane);
                        //Generate the minimum and maximum points
                        XYZ minPoint = new XYZ(minX, minY, minZ);
                        XYZ maxPoint = new XYZ(maxX, maxY, maxZ);
                        //Make a new outline from the points
                        outline = new Outline(minPoint, maxPoint);

                        //Establish a new bounding box filter using the outline
                        BoundingBoxIntersectsFilter bboxFilter = new BoundingBoxIntersectsFilter(outline);
                        //The previous rooms will be those that pass the bounding box intersects filter (their bounding boxes intersect the view bounding box) and they belong to the previous phase
                        var previousNonVisibleRooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().WherePasses(bboxFilter).ToElements().Where(r => r.get_Parameter(BuiltInParameter.ROOM_PHASE).AsElementId() == previousPhaseId);
                        foreach (Element elem in previousNonVisibleRooms)
                        {
                            //Get the rooms and their numbers
                            Room   room       = elem as Room;
                            string roomNumber = room.Number;
                            //Verify the room number is not in the current view's list of visible room numbers
                            if (!currentVisibleRoomNumbers.Contains(roomNumber))
                            {
                                previousRoomsToTag.Add(room);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //If something went wrong in getting the demoed rooms, report an error
                        MessageBox.Show(e.ToString(), "Getting Demo Rooms Error");
                    }

                    //Start a transaction to make the new tags
                    Transaction t = new Transaction(doc, "Create Demo Room Tags");
                    t.Start();
                    FamilySymbol symbol = null;
                    //Create a new instance of the load options
                    IFamilyLoadOptions loadOptions = new RVTFamilyLoadOptions();

                    try
                    {
                        //Get the versioned symbol family to use as a "tag"
                        string roomTagSymbolPath = RVTOperations.GetVersionedFamilyFilePath(uiApp, Properties.Settings.Default.RevitRoomTagSymbol);
                        try
                        {
                            //Load only the particular type of tag
                            doc.LoadFamilySymbol(roomTagSymbolPath, Properties.Settings.Default.RevitRoomTagSymbolType, loadOptions, out FamilySymbol symb);
                            symbol = symb;
                        }
                        catch
                        {
                            //If it could not be loaded, let the user know it needs added to the family for the script to work
                            MessageBox.Show(String.Format("The family type {0} could not be found in {1}. Please add it for this tool to work.",
                                                          Properties.Settings.Default.RevitRoomTagSymbolType,
                                                          Properties.Settings.Default.RevitRoomTagSymbol));
                        }
                    }
                    catch
                    {
                        //If the family itself could not be loaded, let the user know where the family was expected to be found.
                        MessageBox.Show(String.Format("The {0} family could not be found at {1}. Please place the {0} family in the {1} folder for this tool to work.",
                                                      Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitRoomTagSymbol),
                                                      Path.GetDirectoryName(Properties.Settings.Default.RevitRoomTagSymbol)));
                    }

                    try
                    {
                        //Verify there are rooms to tag and the family symbol to use is not null
                        if (previousRoomsToTag.Count > 0 && symbol != null)
                        {
                            //Cycle through the demoed rooms
                            foreach (Room demoRoom in previousRoomsToTag)
                            {
                                //Get the location point of the demo room as a point
                                LocationPoint roomLocationPoint = demoRoom.Location as LocationPoint;
                                //Make a new symbol at the locatoin
                                FamilyInstance newSymbol = doc.Create.NewFamilyInstance(roomLocationPoint.Point, symbol, activeView);
                                //Update the parameter values for room Name and Number in the symbol
                                newSymbol.GetParameters("Name").First().Set(demoRoom.get_Parameter(BuiltInParameter.ROOM_NAME).AsString());
                                newSymbol.GetParameters("Number").First().Set(demoRoom.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                            }
                        }
                        t.Commit();
                    }
                    catch (Exception f)
                    {
                        //Well, crap, the symbol didn't place in the view
                        MessageBox.Show(f.ToString(), "Placement Error");
                        t.RollBack();
                    }
                }
                else
                {
                    //If the previous phase was null, then the current phase of the view is the first phase, so let the user know
                    MessageBox.Show("The currently viewed phase is the earliest phase in the project. Please verify you are viewing a new construction phase, but showing previous and demoed elements.");
                }
            }
        }
Exemple #14
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            //Application app = uiapp.Application;
            Document doc = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;

            //ICollection<ElementId> selectedElementIds = uidoc.Selection.GetElementIds();
            //List<Element> selElem = selectedElementIds.Select(x => doc.GetElement(x)).ToList();
            //Element foundtype = doc.GetElement(selElem[0].GetTypeId());
            //List<string> parlist = new List<string>();
            //foreach (Parameter item in foundtype.Parameters)
            //{
            //    parlist.Add(item.Definition.Name);
            //}
            //int parvalue = foundtype.LookupParameter("шт/м/м2/м3").AsInteger();
            FilterableValueProvider valueProvider = new ParameterValueProvider(new ElementId(BuiltInParameter.PHASE_CREATED));

            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();
            ElementId ruleValue = idPhase;
            ElementParameterFilter stageFilter = new ElementParameterFilter(new FilterElementIdRule(valueProvider, evaluator, ruleValue));

            List <List <Element> > collectFromModel = new List <List <Element> >();

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Where(x => ((FamilyInstance)x).StructuralType.ToString() != "NonStructural")
                                 .Cast <Element>()
                                 .ToList());
            //collectFromModel.Add(karkas);

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());

            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Rebar))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(RebarInSystem))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Railing))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(HostedSweep))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Roofs)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(FabricSheet))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionPlates)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionAnchors)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .Where(x => x.Name != "cube")
                                 .ToList());


            List <Element> floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(stageFilter)
                                    .Cast <Element>()
                                    .ToList();
            List <Element> walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                   .WhereElementIsNotElementType()
                                   .WherePasses(stageFilter)
                                   .Cast <Element>()
                                   .ToList();
            List <Element> fundament = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFoundation)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(stageFilter)
                                       .Cast <Element>()
                                       .ToList();
            List <Element> lestnici = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Stairs)
                                      .WhereElementIsNotElementType()
                                      .WherePasses(stageFilter)
                                      .Cast <Element>()
                                      .ToList();
            List <string> ororo = fundament.Select(x => x.Name).ToList();

            //genModel = genModel.Where(x => x.Name != "cube").ToList();
            List <Cube> allCube = new List <Cube>();

            //List<Cube> someCube = new List<Cube>();

            foreach (Element f in floors)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element w in walls)
            {
                foreach (ElementId m in w.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), w);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element f in fundament)
            {
                if (doc.GetElement(f.GetTypeId()).LookupParameter("шт/м/м2/м3") != null && doc.GetElement(f.GetTypeId()).LookupParameter("шт/м/м2/м3").AsInteger() == 0)
                {
                    Cube abc = new Cube(f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
                else
                {
                    foreach (ElementId m in f.GetMaterialIds(false))
                    {
                        Cube abc = new Cube(doc.GetElement(m), f);
                        if (abc.out_Name != null)
                        {
                            allCube.Add(abc);
                        }
                    }
                }
            }
            foreach (Element f in lestnici)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }
            foreach (List <Element> a in collectFromModel)
            {
                foreach (Element e in a)
                {
                    Cube abc = new Cube(e);
                    if (abc.out_Name == null)
                    {
                        abc.out_Name   = "Исключение: " + abc.typeName;
                        abc.DontSetPos = true;
                    }
                    allCube.Add(abc);
                }
            }
            List <List <Cube> > groupingCube = new List <List <Cube> >();

            //List<string> groupNum=allCube.Select(x => x.Group).Distinct().ToList();

            foreach (string eqGroup in allCube.Select(x => x.out_Group).Distinct())
            {
                if (eqGroup == "" | eqGroup == null)
                {
                    continue;
                }
                List <Cube> similarGroup = new List <Cube>();
                foreach (Cube c in allCube)
                {
                    if (c.out_Group == eqGroup)
                    {
                        similarGroup.Add(c);
                    }
                }
                groupingCube.Add(similarGroup);
            }

            List <Cube> outCube = new List <Cube>();

            foreach (List <Cube> item in groupingCube)
            {
                int a = 1;
                //int addpos = 1;
                foreach (myTypes mt in item.Select(x => x.mType).Distinct())
                {
                    foreach (string eqName in item.Select(x => x.out_Name).Distinct())
                    {
                        List <Cube> b = item
                                        .Where(x => x.mType == mt)
                                        .Where(y => y.out_Name == eqName)
                                        .ToList();
                        if (b.Count == 0)
                        {
                            continue;
                        }
                        (Cube addCube, int addpos) = Meta.forgeCube(b, a);
                        if (!addCube.DontSetPos)
                        {
                            a += addpos;
                        }


                        outCube.Add(addCube);
                    }
                }
            }

            List <List <Cube> > secondOutCube = new List <List <Cube> >();

            foreach (string eqGr in outCube.Select(x => x.out_Name).Distinct())
            {
                foreach (Cube cube in outCube)
                {
                }
            }
            //foreach (string eqGroup in outCube.Select(x => x.out_Group).Distinct())
            //{
            //    List<Cube> similarGroup = new List<Cube>();
            //    foreach (Cube c in allCube)
            //    {
            //        if (c.out_Group == eqGroup)
            //        {
            //            similarGroup.Add(c);
            //        }
            //    }
            //    int i = 1;
            //    similarGroup.OrderBy(x => x.Prior);
            //    foreach (var item in similarGroup)
            //    {
            //        item.out_Pos = i.ToString();
            //        i++;
            //        secondOutCube.Add(item);
            //    }

            //    //similarGroup.short
            //    //secondOutCube.Add(similarGroup.Select());
            //}
            //outCube = secondOutCube;



            ElementParameterFilter cubeFilter = new ElementParameterFilter(new FilterStringRule(new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME)), new FilterStringEquals(), "cube", false));
            List <FamilyInstance>  existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList();


            using (Transaction tr = new Transaction(doc, "ModelledSpec"))
            {
                tr.Start();
                foreach (FamilyInstance i in existCubes)
                {
                    doc.Delete(i.Id);
                }
                foreach (Cube i in outCube)
                {
                    if (i.posElements.Count != 0)
                    {
                        foreach (ElementExt e in i.posElements)
                        {
                            try
                            {
                                e.refElement.LookupParameter("СП_Позиция").Set(i.out_Pos);
                                e.refElement.LookupParameter("АН__Верх").Set(i.textUP);
                                e.refElement.LookupParameter("АН__Низ").Set(e.textDOWN);
                            }
                            catch
                            {
                            }
                        }
                    }

                    i.Create(doc);
                }

                tr.Commit();
            }

            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = outCube.Count.ToString();
            msg.Show();
            return(Result.Succeeded);
        }
        /// <summary>
        /// Creates a new export options cache from the data in the ExporterIFC passed from Revit.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC handle passed during export.</param>
        /// <returns>The new cache.</returns>
        public static ExportOptionsCache Create(ExporterIFC exporterIFC, Document document, Autodesk.Revit.DB.View filterView)
        {
            IDictionary <String, String> options = exporterIFC.GetOptions();

            ExportOptionsCache cache = new ExportOptionsCache();

            cache.FileVersion            = exporterIFC.FileVersion;
            cache.FileName               = exporterIFC.FileName;
            cache.ExportBaseQuantities   = exporterIFC.ExportBaseQuantities;
            cache.WallAndColumnSplitting = exporterIFC.WallAndColumnSplitting;
            cache.SpaceBoundaryLevel     = exporterIFC.SpaceBoundaryLevel;
            // Export Part element only if 'Current View Only' is checked and 'Show Parts' is selected. Or if it is exported as IFC4RV
            cache.ExportParts = (filterView != null && filterView.PartsVisibility == PartsVisibility.ShowPartsOnly);
            cache.ExportPartsAsBuildingElementsOverride = null;
            cache.ExportAnnotationsOverride             = null;

            // We are going to default to "true" for IncludeSteelElements to allow the default API
            // export to match the default UI.
            bool?includeSteelElements = OptionsUtil.GetNamedBooleanOption(options, "IncludeSteelElements");

            cache.IncludeSteelElements = includeSteelElements.HasValue && includeSteelElements.Value;

            // There is a bug in the native code that doesn't allow us to cast the filterView to any sub-type of View.  Work around this by re-getting the element pointer.
            if (filterView != null)
            {
                cache.FilterViewForExport = filterView.Document.GetElement(filterView.Id) as View;
            }
            else
            {
                cache.FilterViewForExport = null;
            }

            cache.ExportBoundingBoxOverride = null;
            cache.IncludeSiteElevation      = false;

            cache.PropertySetOptions = PropertySetOptions.Create(exporterIFC, cache);

            String use2DRoomBoundary       = Environment.GetEnvironmentVariable("Use2DRoomBoundaryForRoomVolumeCalculationOnIFCExport");
            bool?  use2DRoomBoundaryOption = OptionsUtil.GetNamedBooleanOption(options, "Use2DRoomBoundaryForVolume");

            cache.Use2DRoomBoundaryForRoomVolumeCreation =
                ((use2DRoomBoundary != null && use2DRoomBoundary == "1") ||
                 cache.ExportAs2x2 ||
                 (use2DRoomBoundaryOption != null && use2DRoomBoundaryOption.GetValueOrDefault()));

            bool?exportAdvancedSweptSolids = OptionsUtil.GetNamedBooleanOption(options, "ExportAdvancedSweptSolids");

            cache.ExportAdvancedSweptSolids = (exportAdvancedSweptSolids.HasValue) ? exportAdvancedSweptSolids.Value : false;

            // Set GUIDOptions here.
            {
                // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                cache.GUIDOptions.Use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                bool?allowGUIDParameterOverride = OptionsUtil.GetNamedBooleanOption(options, "AllowGUIDParameterOverride");
                if (allowGUIDParameterOverride != null)
                {
                    cache.GUIDOptions.AllowGUIDParameterOverride = allowGUIDParameterOverride.Value;
                }

                bool?storeIFCGUID = OptionsUtil.GetNamedBooleanOption(options, "StoreIFCGUID");
                if (storeIFCGUID != null)
                {
                    cache.GUIDOptions.StoreIFCGUID = storeIFCGUID.Value;
                }
            }

            // Set NamingOptions here.
            cache.NamingOptions = new NamingOptions();
            {
                bool?useFamilyAndTypeNameForReference = OptionsUtil.GetNamedBooleanOption(options, "UseFamilyAndTypeNameForReference");
                cache.NamingOptions.UseFamilyAndTypeNameForReference =
                    (useFamilyAndTypeNameForReference != null) && useFamilyAndTypeNameForReference.GetValueOrDefault();

                bool?useVisibleRevitNameAsEntityName = OptionsUtil.GetNamedBooleanOption(options, "UseVisibleRevitNameAsEntityName");
                cache.NamingOptions.UseVisibleRevitNameAsEntityName =
                    (useVisibleRevitNameAsEntityName != null) && useVisibleRevitNameAsEntityName.GetValueOrDefault();

                bool?useOnlyTypeNameForIfcType = OptionsUtil.GetNamedBooleanOption(options, "UseTypeNameOnlyForIfcType");
                cache.NamingOptions.UseTypeNameOnlyForIfcType =
                    (useOnlyTypeNameForIfcType != null) && useOnlyTypeNameForIfcType.GetValueOrDefault();
            }

            // "SingleElement" export option - useful for debugging - only one input element will be processed for export
            String singleElementValue;
            String elementsToExportValue;

            if (options.TryGetValue("SingleElement", out singleElementValue))
            {
                ElementId elementId = ParseElementId(singleElementValue);

                List <ElementId> ids = new List <ElementId>();
                ids.Add(elementId);
                cache.ElementsForExport = ids;
            }
            else if (options.TryGetValue("ElementsForExport", out elementsToExportValue))
            {
                IList <ElementId> ids = ParseElementIds(elementsToExportValue);
                cache.ElementsForExport = ids;
            }
            else
            {
                cache.ElementsForExport = new List <ElementId>();
            }

            // "ExportAnnotations" override
            cache.ExportAnnotationsOverride = OptionsUtil.GetNamedBooleanOption(options, "ExportAnnotations");

            // "ExportSeparateParts" override
            cache.ExportPartsAsBuildingElementsOverride = OptionsUtil.GetNamedBooleanOption(options, "ExportPartsAsBuildingElements");

            // "ExportBoundingBox" override
            cache.ExportBoundingBoxOverride = OptionsUtil.GetNamedBooleanOption(options, "ExportBoundingBox");

            bool?exportRoomsInView = OptionsUtil.GetNamedBooleanOption(options, "ExportRoomsInView");

            cache.ExportRoomsInView = exportRoomsInView != null ? exportRoomsInView.Value : false;

            // Using the alternate UI or not.
            cache.AlternateUIVersionOverride = OptionsUtil.GetNamedStringOption(options, "AlternateUIVersion");

            // Include IFCSITE elevation in the site local placement origin
            bool?includeIfcSiteElevation = OptionsUtil.GetNamedBooleanOption(options, "IncludeSiteElevation");

            cache.IncludeSiteElevation = includeIfcSiteElevation != null ? includeIfcSiteElevation.Value : false;

            string siteTransformation = OptionsUtil.GetNamedStringOption(options, "SitePlacement");

            if (!string.IsNullOrEmpty(siteTransformation))
            {
                SiteTransformBasis trfBasis = SiteTransformBasis.Shared;
                if (Enum.TryParse(siteTransformation, out trfBasis))
                {
                    cache.SiteTransformation = trfBasis;
                }
            }
            // We have two ways to get information about level of detail:
            // 1. The old Boolean "UseCoarseTessellation".
            // 2. The new double "TessellationLevelOfDetail".
            // We will combine these both into a LevelOfDetail integer that can be used by different elements differently.
            // The scale is from 1 (Extra Low) to 4 (High), where :
            // UseCoarseTessellation = true -> 1, UseCoarseTessellation = false -> 4
            // TessellationLevelOfDetail * 4 = LevelOfDetail
            // TessellationLevelOfDetail takes precedence over UseCoarseTessellation.

            cache.LevelOfDetail = ExportTessellationLevel.Low;

            bool?useCoarseTessellation = OptionsUtil.GetNamedBooleanOption(options, "UseCoarseTessellation");

            if (useCoarseTessellation.HasValue)
            {
                cache.LevelOfDetail = useCoarseTessellation.Value ? ExportTessellationLevel.ExtraLow : ExportTessellationLevel.High;
            }

            double?tessellationLOD = OptionsUtil.GetNamedDoubleOption(options, "TessellationLevelOfDetail");

            if (tessellationLOD.HasValue)
            {
                int levelOfDetail = (int)(tessellationLOD.Value * 4.0 + 0.5);
                // Ensure LOD is between 1 to 4, inclusive.
                levelOfDetail       = Math.Min(Math.Max(levelOfDetail, 1), 4);
                cache.LevelOfDetail = (ExportTessellationLevel)levelOfDetail;
            }

            bool?useOnlyTriangulation = OptionsUtil.GetNamedBooleanOption(options, "UseOnlyTriangulation");

            cache.UseOnlyTriangulation = useOnlyTriangulation.HasValue ? useOnlyTriangulation.Value : false;

            /// Allow exporting a mix of extrusions and BReps as a solid model, if possible.
            bool?canExportSolidModelRep = OptionsUtil.GetNamedBooleanOption(options, "ExportSolidModelRep");

            cache.CanExportSolidModelRep = canExportSolidModelRep != null ? canExportSolidModelRep.Value : false;

            // Set the phase we are exporting
            cache.ActivePhaseId = ElementId.InvalidElementId;

            String activePhaseElementValue;

            if (options.TryGetValue("ActivePhase", out activePhaseElementValue))
            {
                cache.ActivePhaseId = ParseElementId(activePhaseElementValue);
            }

            if ((cache.ActivePhaseId == ElementId.InvalidElementId) && (cache.FilterViewForExport != null))
            {
                Parameter currPhase = cache.FilterViewForExport.get_Parameter(BuiltInParameter.VIEW_PHASE);
                if (currPhase != null)
                {
                    cache.ActivePhaseId = currPhase.AsElementId();
                }
            }

            if (cache.ActivePhaseId == ElementId.InvalidElementId)
            {
                PhaseArray phaseArray = document.Phases;
                Phase      lastPhase  = phaseArray.get_Item(phaseArray.Size - 1);
                cache.ActivePhaseId      = lastPhase.Id;
                cache.ActivePhaseElement = lastPhase;
            }
            else
            {
                cache.ActivePhaseElement = document.GetElement(cache.ActivePhaseId) as Phase;
            }

            bool?useActiveViewGeometry = OptionsUtil.GetNamedBooleanOption(options, "UseActiveViewGeometry");

            cache.UseActiveViewGeometry = useActiveViewGeometry.HasValue ? useActiveViewGeometry.Value : false;

            if (cache.UseActiveViewGeometry)
            {
                int? viewId       = OptionsUtil.GetNamedIntOption(options, "ActiveViewId");
                int  activeViewId = viewId.HasValue ? viewId.Value : -1;
                View activeView   = null;
                try
                {
                    activeView = document.GetElement(new ElementId(activeViewId)) as View;
                }
                catch
                {
                }
                cache.ActiveView = activeView;
            }

            // "FileType" - note - setting is not respected yet
            ParseFileType(options, cache);

            string erName = OptionsUtil.GetNamedStringOption(options, "ExchangeRequirement");

            Enum.TryParse(erName, out cache.m_exchangeRequirement);
            // Get stored File Header information from the UI and use it for export
            IFCFileHeaderItem fileHeaderItem = new IFCFileHeaderItem();

            new IFCFileHeader().GetSavedFileHeader(document, out fileHeaderItem);
            if (cache.m_exchangeRequirement != KnownERNames.NotDefined)
            {
                // It override existing value (if present) in the saved FileHeader, to use the selected ER from the UI
                fileHeaderItem.FileDescription = "ExchangeRequirement [" + erName + "]";
            }
            cache.FileHeaderItem = fileHeaderItem;

            cache.SelectedConfigName = OptionsUtil.GetNamedStringOption(options, "ConfigName");

            cache.SelectedParametermappingTableName = OptionsUtil.GetNamedStringOption(options, "ExportUserDefinedParameterMappingFileName");

            bool?bExportLinks = OptionsUtil.GetNamedBooleanOption(options, "ExportingLinks");

            cache.ExportingLink = (bExportLinks.HasValue && bExportLinks.Value == true);

            if (cache.ExportingLink)
            {
                int?numInstances = OptionsUtil.GetNamedIntOption(options, "NumberOfExportedLinkInstances");
                for (int ii = 0; ii < numInstances; ii++)
                {
                    string optionName             = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString();
                    String aLinkInstanceTransform = OptionsUtil.GetNamedStringOption(options, optionName);

                    Transform currTransform = null;
                    if (!String.IsNullOrEmpty(aLinkInstanceTransform))
                    {
                        //reconstruct transform
                        Transform tr = ParseTransform(aLinkInstanceTransform);
                        //set to cache
                        if (tr != null)
                        {
                            currTransform = tr;
                        }
                    }

                    string fileName = null;

                    if (ii > 0)
                    {
                        optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString();
                        fileName   = OptionsUtil.GetNamedStringOption(options, optionName);
                    }

                    if (currTransform == null)
                    {
                        cache.m_LinkInstanceInfos.Add(new Tuple <string, Transform>(fileName, Transform.Identity));
                    }
                    else
                    {
                        cache.m_LinkInstanceInfos.Add(new Tuple <string, Transform>(fileName, currTransform));
                    }
                }
            }

            cache.ExcludeFilter = OptionsUtil.GetNamedStringOption(options, "ExcludeFilter");

            // Geo Reference info
            cache.GeoRefCRSName       = OptionsUtil.GetNamedStringOption(options, "GeoRefCRSName");
            cache.GeoRefCRSDesc       = OptionsUtil.GetNamedStringOption(options, "GeoRefCRSDesc");
            cache.GeoRefEPSGCode      = OptionsUtil.GetNamedStringOption(options, "GeoRefEPSGCode");
            cache.GeoRefGeodeticDatum = OptionsUtil.GetNamedStringOption(options, "GeoRefGeodeticDatum");
            cache.GeoRefMapUnit       = OptionsUtil.GetNamedStringOption(options, "GeoRefMapUnit");

            return(cache);
        }
Exemple #16
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp     = commandData.Application;
            UIDocument    uidoc     = uiapp.ActiveUIDocument;
            Application   app       = uiapp.Application;
            Document      doc       = uidoc.Document;
            PhaseArray    xcom      = doc.Phases;
            Phase         lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId     idPhase   = lastPhase.Id;
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            GlobalParameter GlobePar2 = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ?
                                        doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter :null;
            FinishForm MainForm = new FinishForm(doc);

            MainForm.ShowDialog();
            using (Transaction tr = new Transaction(doc, "setGP"))
            {
                tr.Start();
                GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ?
                                           doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter :
                                           GlobalParameter.Create(doc, "FinData", ParameterType.Text);
                GlobePar.SetValue(new StringParameterValue(string.Join("|", MainForm.wTypeBoxes)));
                //int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value;
                tr.Commit();
            }

            lastPhase = MainForm.retPhase;
            idPhase   = lastPhase.Id;

            List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc)
                                                            .OfClass(typeof(SharedParameterElement))
                                                            .Cast <SharedParameterElement>()
                                                            .ToList();
            //Фильтр: Помещения на последней стадии
            FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterElementIdRule     rRule        = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            ElementParameterFilter  room_filter  = new ElementParameterFilter(rRule);
            //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id);
            FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals();
            IList <Element>           rooms        = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                                     .WhereElementIsNotElementType()
                                                     .WherePasses(room_filter)
                                                     //.WherePasses(roomSc_filter)
                                                     .ToElements();

            //Фильтр: Стены созданные на последней стадии
            FilterableValueProvider provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule     fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter  door_filter = new ElementParameterFilter(fRule);

            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(door_filter)
                                       .ToElements();

            //Фильтр: экземпляры дверей
            List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();


            foreach (Element e in rooms)
            {
                RoomFinishing.Rooms.Add(new RoomFinishing(e));
            }
            RoomFinishing.Rooms = RoomFinishing.Rooms.OrderBy(x => x.Num).ToList();

            List <GhostWall> cWalls = new List <GhostWall>();

            foreach (Element wall in allWalls)
            {
                if (wall.LookupParameter("Помещение").AsString() != null & wall.LookupParameter("Помещение").AsString() != "")
                {
                    cWalls.Add(new GhostWall(wall, MainForm.LocType));
                }
            }

            foreach (GhostWall w in cWalls)
            {
                foreach (RoomFinishing r in RoomFinishing.Rooms)
                {
                    if (r.Num == w.Room)
                    {
                        if (w.typeName == MainForm.LocType.Name)
                        {
                            r.unitLocalWallVal += w.Area;
                            r.LocalWallText     = w.sostav;
                        }
                        else if (w.typeName == MainForm.ColType.Name)
                        {
                            r.unitKolonWallVal += w.Area;
                            r.KolonWallText     = w.sostav;
                        }
                        else
                        {
                            r.unitMainWallVal += w.Area;
                        }
                        if (w.countNewW)
                        {
                            r.unitNewWallVal += w.Area;
                        }
                    }
                }
            }


            //Плинтус
            foreach (FamilyInstance d in doors)
            {
                foreach (RoomFinishing r in RoomFinishing.Rooms)
                {
                    try
                    {
                        if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id)
                        {
                            r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            RoomFinishing.makeFinish(MainForm);
            RoomFinishing.makeFloor(MainForm.splitLevel);
            using (Transaction tr = new Transaction(doc, "otdelka"))
            {
                tr.Start();
                GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ?
                                           doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter :
                                           GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo);
                int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value;

                int withNames = MainForm.withnames;
                MoreThenOneLevel = MainForm.levels;

                RoomFinishing.FinishTableCommit(doc, MainForm);
                RoomFinishing.FloorTableCommit(MoreThenOneLevel, withNames, doc);

                tr.Commit();
            }
            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = $"Выполнен расчет отделки для стадии \"{MainForm.retPhase.Name}\"";
            msg.Show();
            return(Result.Succeeded);
        }
Exemple #17
0
        /// <summary>
        /// Creates a new export options cache from the data in the ExporterIFC passed from Revit.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC handle passed during export.</param>
        /// <returns>The new cache.</returns>
        public static ExportOptionsCache Create(ExporterIFC exporterIFC, Document document, Autodesk.Revit.DB.View filterView)
        {
            IDictionary <String, String> options = exporterIFC.GetOptions();

            ExportOptionsCache cache = new ExportOptionsCache();

            cache.FileVersion            = exporterIFC.FileVersion;
            cache.FileName               = exporterIFC.FileName;
            cache.ExportBaseQuantities   = exporterIFC.ExportBaseQuantities;
            cache.WallAndColumnSplitting = exporterIFC.WallAndColumnSplitting;
            cache.SpaceBoundaryLevel     = exporterIFC.SpaceBoundaryLevel;
            // Export Part element only if 'Current View Only' is checked and 'Show Parts' is selected.
            cache.ExportParts = filterView != null && filterView.PartsVisibility == PartsVisibility.ShowPartsOnly;
            cache.ExportPartsAsBuildingElementsOverride = null;
            cache.ExportAllLevels           = false;
            cache.ExportAnnotationsOverride = null;

            // There is a bug in the native code that doesn't allow us to cast the filterView to any sub-type of View.  Work around this by re-getting the element pointer.
            if (filterView != null)
            {
                cache.FilterViewForExport = filterView.Document.GetElement(filterView.Id) as View;
            }
            else
            {
                cache.FilterViewForExport = null;
            }

            cache.ExportBoundingBoxOverride = null;
            cache.IncludeSiteElevation      = false;
            cache.UseCoarseTessellation     = true;

            cache.PropertySetOptions = PropertySetOptions.Create(exporterIFC, cache);

            String use2DRoomBoundary       = Environment.GetEnvironmentVariable("Use2DRoomBoundaryForRoomVolumeCalculationOnIFCExport");
            bool?  use2DRoomBoundaryOption = GetNamedBooleanOption(options, "Use2DRoomBoundaryForVolume");

            cache.Use2DRoomBoundaryForRoomVolumeCreation =
                ((use2DRoomBoundary != null && use2DRoomBoundary == "1") ||
                 cache.ExportAs2x2 ||
                 (use2DRoomBoundaryOption != null && use2DRoomBoundaryOption.GetValueOrDefault()));

            bool?exportAdvancedSweptSolids = GetNamedBooleanOption(options, "ExportAdvancedSweptSolids");

            cache.ExportAdvancedSweptSolids = (exportAdvancedSweptSolids.HasValue) ? exportAdvancedSweptSolids.Value : false;

            // Set GUIDOptions here.
            {
                // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                cache.GUIDOptions.Use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                bool?allowGUIDParameterOverride = GetNamedBooleanOption(options, "AllowGUIDParameterOverride");
                if (allowGUIDParameterOverride != null)
                {
                    cache.GUIDOptions.AllowGUIDParameterOverride = allowGUIDParameterOverride.Value;
                }

                bool?storeIFCGUID = GetNamedBooleanOption(options, "StoreIFCGUID");
                if (storeIFCGUID != null)
                {
                    cache.GUIDOptions.StoreIFCGUID = storeIFCGUID.Value;
                }
            }

            // Set NamingOptions here.
            cache.NamingOptions = new NamingOptions();
            {
                bool?useFamilyAndTypeNameForReference = GetNamedBooleanOption(options, "UseFamilyAndTypeNameForReference");
                cache.NamingOptions.UseFamilyAndTypeNameForReference =
                    (useFamilyAndTypeNameForReference != null) && useFamilyAndTypeNameForReference.GetValueOrDefault();

                bool?useVisibleRevitNameAsEntityName = GetNamedBooleanOption(options, "UseVisibleRevitNameAsEntityName");
                cache.NamingOptions.UseVisibleRevitNameAsEntityName =
                    (useVisibleRevitNameAsEntityName != null) && useVisibleRevitNameAsEntityName.GetValueOrDefault();
            }

            // "SingleElement" export option - useful for debugging - only one input element will be processed for export
            String singleElementValue;
            String elementsToExportValue;

            if (options.TryGetValue("SingleElement", out singleElementValue))
            {
                ElementId elementId = ParseElementId(singleElementValue);

                List <ElementId> ids = new List <ElementId>();
                ids.Add(elementId);
                cache.ElementsForExport = ids;
            }
            else if (options.TryGetValue("ElementsForExport", out elementsToExportValue))
            {
                IList <ElementId> ids = ParseElementIds(elementsToExportValue);
                cache.ElementsForExport = ids;
            }
            else
            {
                cache.ElementsForExport = new List <ElementId>();
            }

            // "ExportAnnotations" override
            cache.ExportAnnotationsOverride = GetNamedBooleanOption(options, "ExportAnnotations");

            // "ExportSeparateParts" override
            cache.ExportPartsAsBuildingElementsOverride = GetNamedBooleanOption(options, "ExportPartsAsBuildingElements");

            // "ExportBoundingBox" override
            cache.ExportBoundingBoxOverride = GetNamedBooleanOption(options, "ExportBoundingBox");

            bool?exportRoomsInView = GetNamedBooleanOption(options, "ExportRoomsInView");

            cache.ExportRoomsInView = exportRoomsInView != null ? exportRoomsInView.Value : false;

            // Using the alternate UI or not.
            cache.AlternateUIVersionOverride = GetNamedStringOption(options, "AlternateUIVersion");

            // Include IFCSITE elevation in the site local placement origin
            bool?includeIfcSiteElevation = GetNamedBooleanOption(options, "IncludeSiteElevation");

            cache.IncludeSiteElevation = includeIfcSiteElevation != null ? includeIfcSiteElevation.Value : false;

            // Use coarse tessellation for floors, railings, ramps, spaces and stairs.
            bool?useCoarseTessellation = GetNamedBooleanOption(options, "UseCoarseTessellation");

            cache.UseCoarseTessellation = useCoarseTessellation != null ? useCoarseTessellation.Value : true;

            // Tessellation level of detail as set by the UI
            double?tessellationLOD = GetNamedDoubleOption(options, "TessellationLevelOfDetail");

            if (tessellationLOD.HasValue)
            {
                cache.TessellationLevelOfDetail = tessellationLOD.Value;
            }
            else
            {
                cache.TessellationLevelOfDetail = cache.UseCoarseTessellation ? 0.25 : 1.0;
            }

            /// Allow exporting a mix of extrusions and BReps as a solid model, if possible.
            bool?canExportSolidModelRep = GetNamedBooleanOption(options, "ExportSolidModelRep");

            cache.CanExportSolidModelRep = canExportSolidModelRep != null ? canExportSolidModelRep.Value : false;

            // Set the phase we are exporting
            cache.ActivePhaseId = ElementId.InvalidElementId;

            String activePhaseElementValue;

            if (options.TryGetValue("ActivePhase", out activePhaseElementValue))
            {
                cache.ActivePhaseId = ParseElementId(activePhaseElementValue);
            }

            if ((cache.ActivePhaseId == ElementId.InvalidElementId) && (cache.FilterViewForExport != null))
            {
                Parameter currPhase = cache.FilterViewForExport.get_Parameter(BuiltInParameter.VIEW_PHASE);
                if (currPhase != null)
                {
                    cache.ActivePhaseId = currPhase.AsElementId();
                }
            }

            if (cache.ActivePhaseId == ElementId.InvalidElementId)
            {
                PhaseArray phaseArray = document.Phases;
                Phase      lastPhase  = phaseArray.get_Item(phaseArray.Size - 1);
                cache.ActivePhaseId      = lastPhase.Id;
                cache.ActivePhaseElement = lastPhase;
            }
            else
            {
                cache.ActivePhaseElement = document.GetElement(cache.ActivePhaseId) as Phase;
            }

            // "FileType" - note - setting is not respected yet
            ParseFileType(options, cache);

            cache.SelectedConfigName = GetNamedStringOption(options, "ConfigName");

            bool?bExportLinks = GetNamedBooleanOption(options, "ExportingLinks");

            cache.ExportingLink = (bExportLinks.HasValue && bExportLinks.Value == true);

            if (cache.ExportingLink)
            {
                int?numInstances = GetNamedIntOption(options, "NumberOfExportedLinkInstances");
                for (int ii = 0; ii < numInstances; ii++)
                {
                    string optionName             = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString();
                    String aLinkInstanceTransform = GetNamedStringOption(options, optionName);

                    Transform currTransform = null;
                    if (!String.IsNullOrEmpty(aLinkInstanceTransform))
                    {
                        //reconstruct transform
                        Transform tr = ParseTransform(aLinkInstanceTransform);
                        //set to cache
                        if (tr != null)
                        {
                            currTransform = tr;
                        }
                    }

                    string fileName = null;

                    if (ii > 0)
                    {
                        optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString();
                        fileName   = GetNamedStringOption(options, optionName);
                    }

                    if (currTransform == null)
                    {
                        cache.m_LinkInstanceInfos.Add(new Tuple <string, Transform>(fileName, Transform.Identity));
                    }
                    else
                    {
                        cache.m_LinkInstanceInfos.Add(new Tuple <string, Transform>(fileName, currTransform));
                    }
                }
            }

            return(cache);
        }
Exemple #18
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            //GlobalParameter.
            //GlobalParameter one = ;
            FinishForm questions = new FinishForm(doc);

            questions.Show();
            questions.Activate();


            double     FT        = 0.3048;
            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc)
                                                            .OfClass(typeof(SharedParameterElement))
                                                            .Cast <SharedParameterElement>()
                                                            .ToList();
            //SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First();

            //Фильтр: Помещения на последней стадии
            FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterElementIdRule     rRule        = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            ElementParameterFilter  room_filter  = new ElementParameterFilter(rRule);
            //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id);
            FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals();
            //FilterRule rScRule = new FilterStringRule(provRoomSchool, StrEvaluator, "",false);
            //ElementParameterFilter roomSc_filter = new ElementParameterFilter(rScRule);

            IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(room_filter)
                                    //.WherePasses(roomSc_filter)
                                    .ToElements();

            //Фильтр: Стены созданные на последней стадии
            FilterableValueProvider provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule     fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter  door_filter = new ElementParameterFilter(fRule);

            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(door_filter)
                                       .ToElements();

            //Фильтр: экземпляры дверей
            List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();

            List <FamilySymbol> ento = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Entourage)
                                       .WhereElementIsElementType()
                                       .Cast <FamilySymbol>()
                                       .ToList();

            List <String> entoName = new List <string>();

            foreach (FamilySymbol i in ento)
            {
                entoName.Add(i.Name);
            }

            List <String> entoFamily = new List <string>();

            //List<otdelka> otd = new List<otdelka>();
            foreach (FamilySymbol f in ento)
            {
                //otd.Add(new otdelka(f.FamilyName+':'+f.Name,f.getP("АР_Состав отделки")));
                entoFamily.Add(f.FamilyName);
            }
            //List<String> one = new List<string>();

            //foreach (FamilySymbol f in ento)
            //{

            //    one.Add(f.getP("АР_Состав отделки"));
            //}
            //string two = doc.GetElement(rooms[0].LookupParameter("ОТД_Пол").AsElementId()).Name;

            List <Element>   walls  = new List <Element>();
            List <GhostWall> cWalls = new List <GhostWall>();

            foreach (Element item in allWalls)
            {
                if (item.LookupParameter("Помещение").AsString() != null & item.LookupParameter("Помещение").AsString() != "")
                {
                    bool isLocal = (item as Wall).WallType.LookupParameter("rykomoika").AsInteger() == 1 ? true : false;
                    walls.Add(item);

                    cWalls.Add(new GhostWall(
                                   item.getP("Помещение"),
                                   item.LevelId,
                                   item.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(),
                                   isLocal
                                   ));
                }
            }
            List <ElementId> Levels = new List <ElementId>();

            rooms = rooms.OrderBy(x => x.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()).ToList();
            List <RoomFinishing> novaRooms = new List <RoomFinishing>();

            foreach (Element e in rooms)
            {
                novaRooms.Add(new RoomFinishing(e));
            }

            novaRooms = novaRooms.OrderBy(x => x.Num).ToList();

            List <ElementId> wallLevels = new List <ElementId>();

            foreach (Element i in rooms)
            {
                Levels.Add(i.LevelId);
            }
            foreach (Element i in walls)
            {
                wallLevels.Add(i.LevelId);
            }
            IEnumerable <String> LevelsName = new List <String>();

            //Levels=Levels.Distinct().ToList();
            //Levels = Levels.OrderBy(x=>doc.GetElement(x).Name).ToList();

            foreach (ElementId i in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name))
            {
                LevelsName = LevelsName.Append(doc.GetElement(i).Name);
            }
            String str = String.Join(",", LevelsName);


            IEnumerable <bool>             isNewC           = new List <bool>();
            IEnumerable <bool>             isNewW           = new List <bool>();
            IEnumerable <bool>             SecFin           = new List <bool>();
            List <String>                  CeilText         = new List <String>();
            List <String>                  MainText         = new List <String>();
            List <String>                  FloorText        = new List <String>();
            List <string>                  WallsLocal       = new List <string>();
            List <List <Element> >         roomByLevel      = new List <List <Element> >();
            List <List <String> >          roomNumByLevel   = new List <List <String> >();
            List <List <String> >          CeilTextByLevel  = new List <List <string> >();
            List <List <String> >          MainTextByLevel  = new List <List <string> >();
            List <List <String> >          FloorTextByLevel = new List <List <string> >();
            List <List <List <Element> > > FinishTable      = new List <List <List <Element> > >();
            List <List <List <String> > >  FinishTableNum   = new List <List <List <String> > >();
            List <List <List <double> > >  FinishTableW3S   = new List <List <List <double> > >();
            List <List <Element> >         wallByLevel      = new List <List <Element> >();
            List <List <String> >          wallNumByLevel   = new List <List <String> >();
            List <List <double> >          wallAreaByLevel  = new List <List <double> >();
            List <List <double> >          WallS1           = new List <List <double> >();
            List <List <double> >          WallS2           = new List <List <double> >();
            List <List <string> >          WallsLocalText   = new List <List <string> >();
            List <List <List <Element> > > floorTable       = new List <List <List <Element> > >();
            List <List <List <string> > >  floorTableNum    = new List <List <List <string> > >();
            List <List <List <double> > >  plintTable       = new List <List <List <double> > >();
            List <List <double> >          plintByLevel     = new List <List <double> >();
            List <List <double> >          perimByLevel     = new List <List <double> >();


            foreach (ElementId lev in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name))
            {
                List <Element> s   = new List <Element>();
                List <String>  n   = new List <String>();
                List <String>  ct  = new List <String>();
                List <String>  mt  = new List <String>();
                List <String>  ft  = new List <String>();
                List <double>  ws  = new List <double>();
                List <double>  ws2 = new List <double>();
                List <string>  wt  = new List <string>();
                List <double>  pl  = new List <double>();
                List <double>  pr  = new List <double>();

                for (int i = 0; i < Levels.Count(); i++)
                {
                    if (Levels[i] == lev)
                    {
                        s.Add(rooms.ElementAt(i));
                        n.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                        ct.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString());
                        mt.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString());
                        ft.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString());
                        pr.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_PERIMETER).AsDouble());
                        ws.Add(0);
                        ws2.Add(0);
                        pl.Add(0);
                        wt.Add("");

                        CeilText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString());
                        MainText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString());
                        FloorText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString());
                    }
                }
                roomByLevel.Add(s);
                roomNumByLevel.Add(n);
                CeilTextByLevel.Add(ct);
                MainTextByLevel.Add(mt);
                FloorTextByLevel.Add(ft);
                WallS1.Add(ws);
                WallS2.Add(ws2);
                WallsLocalText.Add(wt);
                plintByLevel.Add(pl);
                perimByLevel.Add(pr);


                List <Element> w  = new List <Element>();
                List <String>  wn = new List <String>();
                List <double>  wa = new List <double>();
                //List<Wall> est = walls as List<Wall>;
                for (int i = 0; i < wallLevels.Count(); i++)
                {
                    if (wallLevels[i] == lev)
                    {
                        w.Add(walls[i]);
                        wn.Add(walls[i].LookupParameter("Помещение").AsString());
                        wa.Add(walls[i].get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble());
                    }
                }
                wallAreaByLevel.Add(wa);
                wallByLevel.Add(w);
                wallNumByLevel.Add(wn);
            }

            //Плинтус
            foreach (FamilyInstance d in doors)
            {
                foreach (RoomFinishing r in novaRooms)
                {
                    try
                    {
                        if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id)
                        {
                            r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //Задаём площади отделки помещений и указываем неизменные помещения
            foreach (ElementId lev in novaRooms.Select(x => x.Level).Distinct())
            {
                foreach (RoomFinishing r in novaRooms.Where(x => x.Level == lev))
                {
                    //Стены
                    for (int i = 0; i < novaRooms.Select(x => x.Level).Distinct().Count(); i++)
                    {
                        for (int w = 0; w < wallNumByLevel[i].Count(); w++)
                        {
                            if (wallByLevel[i][w].LevelId != lev)
                            {
                                continue;
                            }
                            Wall checkWall = (Wall)wallByLevel[i][w];
                            if (r.Num == wallNumByLevel[i][w])
                            {
                                if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1)
                                {
                                    r.LocalWallVal += wallAreaByLevel[i][w];
                                    r.LocalWallText = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString();
                                    WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString());
                                    continue;
                                }
                                r.MainWallVal += wallAreaByLevel[i][w];
                                WallsLocal.Add("");
                            }
                        }
                    }
                }
            }


            for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
            {
                for (int r = 0; r < roomNumByLevel[lev].Count(); r++)
                {
                    //Плинтус
                    for (int i = 0; i < doors.Count(); i++)
                    {
                        try
                        {
                            if (doors[i].get_FromRoom(lastPhase).Id == roomByLevel[lev][r].Id | doors[i].get_ToRoom(lastPhase).Id == roomByLevel[lev][r].Id)
                            {
                                plintByLevel[lev][r] += doors[i].LookupParameter("Ширина").AsDouble();
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    //Стены
                    for (int w = 0; w < wallNumByLevel[lev].Count(); w++)
                    {
                        Wall checkWall = (Wall)wallByLevel[lev][w];
                        if (roomNumByLevel[lev][r] == wallNumByLevel[lev][w])
                        {
                            if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1)
                            {
                                WallS2[lev][r]        += wallAreaByLevel[lev][w];
                                WallsLocalText[lev][r] = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString();
                                WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString());
                                continue;
                            }
                            WallS1[lev][r] += wallAreaByLevel[lev][w];
                            WallsLocal.Add("");
                        }
                    }
                }
            }
            WallsLocal = WallsLocal.OrderBy(x => x).ToList();


            //Сортируем помещения по типу отделки потолка и стен
            int finishTypes = 0;
            List <List <RoomFinishing> > novaFinishTable = new List <List <RoomFinishing> >();


            if (WallsLocal.Count == 0)
            {
                foreach (string c in novaRooms.Select(x => x.CeilType).Distinct())
                {
                    foreach (string w in novaRooms.Select(x => x.WallType).Distinct())
                    {
                        List <RoomFinishing> cw = novaRooms
                                                  .Where(x => x.CeilType == c)
                                                  .Where(y => y.WallType == w)
                                                  .ToList();
                        novaFinishTable.Add(cw);
                        foreach (RoomFinishing r in cw)
                        {
                            r.SimilarWallVal = cw.Sum(x => x.MainWallVal);
                        }
                    }
                }
            }
            else
            {
                foreach (string wt3 in WallsLocal.Distinct())
                {
                    foreach (string c in novaRooms.Select(x => x.CeilType).Distinct())
                    {
                        foreach (string w in novaRooms.Select(x => x.WallType).Distinct())
                        {
                            List <RoomFinishing> cw = novaRooms
                                                      .Where(x => x.CeilType == c)
                                                      .Where(y => y.WallType == w)
                                                      .ToList();
                            novaFinishTable.Add(cw);
                            foreach (RoomFinishing r in cw)
                            {
                                r.SimilarWallVal = cw.Sum(x => x.MainWallVal);
                            }
                        }
                    }
                }
            }


            if (WallsLocal.Count == 0)
            {
                foreach (String i in CeilText.Distinct())
                {
                    foreach (String j in MainText.Distinct())
                    {
                        FinishTable.Add(new List <List <Element> >());
                        FinishTableNum.Add(new List <List <string> >());
                        FinishTableW3S.Add(new List <List <double> >());

                        for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                        {
                            List <Element> SimilarFinish    = new List <Element>();
                            List <String>  SimilarFinishNum = new List <String>();
                            List <double>  SimW3S           = new List <double>();
                            for (int r = 0; r < roomByLevel[lev].Count(); r++)
                            {
                                if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j)
                                {
                                    SimilarFinish.Add(roomByLevel[lev][r]);
                                    SimilarFinishNum.Add(roomNumByLevel[lev][r]);
                                    SimW3S.Add(WallS2[lev][r]);
                                }
                            }
                            FinishTable[finishTypes].Add(SimilarFinish);
                            FinishTableNum[finishTypes].Add(SimilarFinishNum);
                            FinishTableW3S[finishTypes].Add(SimW3S);
                        }
                        finishTypes++;
                    }
                }
            }
            else
            {
                foreach (string wt3 in WallsLocal.Distinct())
                {
                    foreach (String i in CeilText.Distinct())
                    {
                        foreach (String j in MainText.Distinct())
                        {
                            FinishTable.Add(new List <List <Element> >());
                            FinishTableNum.Add(new List <List <string> >());
                            FinishTableW3S.Add(new List <List <double> >());

                            for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                            {
                                List <Element> SimilarFinish    = new List <Element>();
                                List <String>  SimilarFinishNum = new List <String>();
                                List <double>  SimW3S           = new List <double>();
                                for (int r = 0; r < roomByLevel[lev].Count(); r++)
                                {
                                    if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j & WallsLocalText[lev][r] == wt3)
                                    {
                                        SimilarFinish.Add(roomByLevel[lev][r]);
                                        SimilarFinishNum.Add(roomNumByLevel[lev][r]);
                                        SimW3S.Add(WallS2[lev][r]);
                                    }
                                }
                                FinishTable[finishTypes].Add(SimilarFinish);
                                FinishTableNum[finishTypes].Add(SimilarFinishNum);
                                FinishTableW3S[finishTypes].Add(SimW3S);
                            }
                            finishTypes++;
                        }
                    }
                }
            }

            List <List <RoomFinishing> > novaFloorTable = new List <List <RoomFinishing> >();

            foreach (string i in novaRooms.Select(x => x.FloorType).Distinct())
            {
                foreach (string pl in novaRooms.Select(x => x.PlintusType).Distinct())
                {
                    List <RoomFinishing> flpl = novaRooms
                                                .Where(x => x.FloorType == i)
                                                .Where(y => y.PlintusType == pl)
                                                .ToList();
                    novaFloorTable.Add(flpl);
                    foreach (RoomFinishing r in flpl)
                    {
                        r.SimilarPlintusVal = flpl.Sum(x => x.Perimeter);
                    }
                }
            }

            //Сортируем помещения по типу пола
            int floorTypes = 0;

            foreach (string i in FloorText.Distinct())
            {
                floorTable.Add(new List <List <Element> >());
                floorTableNum.Add(new List <List <string> >());
                plintTable.Add(new List <List <double> >());
                for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                {
                    List <Element> simFloor    = new List <Element>();
                    List <string>  simFloorNum = new List <string>();
                    List <double>  simPlint    = new List <double>();
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        if (FloorTextByLevel[lev][r] == i)
                        {
                            simFloor.Add(roomByLevel[lev][r]);
                            simFloorNum.Add(roomNumByLevel[lev][r]);
                            simPlint.Add(perimByLevel[lev][r] - plintByLevel[lev][r]);
                        }
                    }
                    floorTable[floorTypes].Add(simFloor);
                    floorTableNum[floorTypes].Add(simFloorNum);
                    plintTable[floorTypes].Add(simPlint);
                }

                floorTypes++;
            }



            using (Transaction tr = new Transaction(doc, "otdelka"))
            {
                tr.Start();
                GlobalParameter ohohoh = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ?
                                         doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter :
                                         GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo);



                int MoreThenOneLevel = ((IntegerParameterValue)ohohoh.GetValue()).Value;

                //Передаем номера помещений с одинаковым типом отделки стен и потолка
                for (int lev = 0; lev < roomByLevel.Count(); lev++)
                {
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        roomByLevel[lev][r].LookupParameter("SanT").Set(WallsLocalText[lev][r]);
                        roomByLevel[lev][r].LookupParameter("ДлинаПроемов").Set(plintByLevel[lev][r]);
                    }
                }

                for (int i = 0; i < FinishTable.Count(); i++)
                {
                    String fillText = "";
                    //String fillText2 = "";
                    double sumW3S = 0;
                    for (int lev = 0; lev < FinishTable[i].Count(); lev++)
                    {
                        sumW3S += FinishTableW3S[i][lev].Sum() * (FT * FT);
                        if (FinishTable[i][lev].Count() == 0)
                        {
                            continue;
                        }
                        else
                        {
                            if (MoreThenOneLevel == 1)
                            {
                                fillText += (lev + 1).ToString() + " этаж:\n";
                            }
                            fillText += Meta.shortLists(FinishTableNum[i][lev]);
                            fillText += "\n";
                        }
                    }
                    for (int lev = 0; lev < FinishTable[i].Count(); lev++)
                    {
                        for (int r = 0; r < FinishTable[i][lev].Count(); r++)
                        {
                            try
                            {
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            FinishTable[i][lev][r].LookupParameter("testW").Set(fillText);
                            //FinishTable[i][lev][r].LookupParameter("unitTest").Set(fillText2);
                            FinishTable[i][lev][r].LookupParameter("SanS").Set(sumW3S > 0 ? sumW3S.ToString("F1") : "");
                            FinishTable[i][lev][r].LookupParameter("snS").Set(FinishTableW3S[i][lev][r]);
                        }
                    }
                }

                for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                {
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        roomByLevel[lev][r].LookupParameter("WallS1n").Set(WallS1[lev][r]);
                    }
                }



                int withNames = questions.withnames;                //Если нужны имена помещений
                                                                    //Передаем номера помещений с одинаковым типом стен потолка
                foreach (List <RoomFinishing> item in novaFinishTable)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    String fillText = "";
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        if (MoreThenOneLevel == 1)
                        {
                            fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n";
                        }
                        if (withNames == 1)
                        {
                            foreach (RoomFinishing gg in item.Where(x => x.Level == lev))
                            {
                                fillText += gg.Name + "-" + gg.Num + ", ";
                            }
                            fillText = fillText.Remove(fillText.Length - 2, 2) + "\n";
                            continue;
                        }
                        fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n";
                    }
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        foreach (RoomFinishing r in item.Where(x => x.Level == lev))
                        {
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                            }
                            r.refElement.LookupParameter("testW").Set(fillText);
                            //r.refElement.LookupParameter("ОТД_Кол.Стены").Set(0);
                            r.refElement.LookupParameter("ОТД_Кол.Стены").Set(r.SimilarWallVal);


                            //r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter);
                            //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText));
                            //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal));
                        }
                    }
                }

                //Передаем номера помещений с одинаковым типом отделки пола
                foreach (List <RoomFinishing> item in novaFloorTable)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    String fillText = "";
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        if (MoreThenOneLevel == 1)
                        {
                            fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n";
                        }
                        if (withNames == 1)
                        {
                            foreach (RoomFinishing gg in item.Where(x => x.Level == lev))
                            {
                                fillText += gg.Name + "-" + gg.Num + ", ";
                            }
                            fillText = fillText.Remove(fillText.Length - 2, 2) + "\n";
                            continue;
                        }
                        fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n";
                    }
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        foreach (RoomFinishing r in item.Where(x => x.Level == lev))
                        {
                            r.refElement.LookupParameter("ОТД_Состав.Пол").Set("");
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Плинтус").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set("НЕТ ОТДЕЛКИ");
                            }
                            r.refElement.LookupParameter("testF").Set(fillText);
                            r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set("");

                            if (r.PlintusType != "__Отделка : ---")
                            {
                                r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set((r.SimilarPlintusVal * FT).ToString("F1"));
                            }

                            r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter);
                            //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText));
                            //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal));
                        }
                    }
                }
                //          for (int i = 0; i < floorTable.Count(); i++)
                //          {
                //              double sumPlint = 0;
                //              String fillText = "";
                //              for (int lev = 0; lev < floorTable[i].Count(); lev++)
                //              {
                //                  sumPlint += plintTable[i][lev].Sum() * FT;
                //                  if (floorTable[i][lev].Count() == 0)
                //                  {
                //                      continue;
                //                  }
                //                  else
                //                  {
                //	if (MoreThenOneLevel==1)
                //	{
                //		fillText += (lev + 1).ToString() + " этаж:\n";
                //	}
                //                      fillText += Meta.shortLists(floorTableNum[i][lev]);
                //                      fillText += "\n";
                //                  }
                //              }



                //              for (int lev = 0; lev < floorTable[i].Count(); lev++)
                //              {
                //for (int r = 0; r < floorTable[i][lev].Count(); r++)
                //{
                //                      try
                //                      {
                //		floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(floorTable[i][lev][r].LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString());

                //	}
                //                      catch (Exception)
                //                      {
                //		floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ");

                //	}
                //                      floorTable[i][lev][r].LookupParameter("testF").Set(fillText);
                //                      floorTable[i][lev][r].LookupParameter("PlintusTotal").Set(sumPlint);
                //                      if (floorTable[i][lev][r].LookupParameter("плинтус").AsInteger() == 1)
                //                      {
                //                          floorTable[i][lev][r].setP("PlintusTotalT", (sumPlint * FT).ToString("F1"));
                //                      }


                //                  }
                //              }
                //          }
                tr.Commit();
            }
            //String output = String.Join(", ", roomNumByLevel[0]);
            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = "Ok";             //output;// FinishTable.Count().ToString();
            msg.Show();

            return(Result.Succeeded);
        }
Exemple #19
0
        public FinishForm(Document Doc)
        {
            this.doc = Doc;
            if (GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId)
            {
                GlobalParameter GlobePar2 = doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter;

                StringParameterValue strPar = GlobePar2.GetValue() as StringParameterValue;
                String GPar = strPar.Value;
                wTypeBoxes = GPar.Split('|').ToList();
            }

            PhaseArray     xcom       = doc.Phases;
            List <Element> walltypes1 = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToList();

            walltypes1 = walltypes1.OrderBy(x => x.Name).ToList();
            List <Element> walltypes2 = walltypes1.Select(x => x).ToList();
            List <Element> walltypes3 = walltypes1.Select(x => x).ToList();



            //xcom.


            //PhaseSelector.SelectedItem = xcom;

            InitializeComponent();
            comboBox1.DataSource    = walltypes1;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember   = "Id";

            try
            {
                comboBox1.SelectedIndex = walltypes1.IndexOf(walltypes1.First(x => x.Name == wTypeBoxes[0]));
            }
            catch (Exception)
            {
            }


            LocFinSelector.DataSource    = walltypes2;
            LocFinSelector.DisplayMember = "Name";
            LocFinSelector.ValueMember   = "Id";
            try
            {
                LocFinSelector.SelectedIndex = walltypes2.IndexOf(walltypes2.First(x => x.Name == wTypeBoxes[1]));
            }
            catch (Exception)
            {
            }
            ColumnFinSelector.DataSource    = walltypes3;
            ColumnFinSelector.DisplayMember = "Name";
            ColumnFinSelector.ValueMember   = "Id";
            try
            {
                ColumnFinSelector.SelectedIndex = walltypes3.IndexOf(walltypes3.First(x => x.Name == wTypeBoxes[2]));
            }
            catch (Exception)
            {
            }

            PhaseSelector.DataSource    = xcom as IList <Phase>;
            PhaseSelector.DisplayMember = "Name";
            PhaseSelector.ValueMember   = "Id";
            foreach (Phase item in xcom)
            {
                PhaseSelector.Items.Add(item);
            }
            PhaseSelector.SelectedIndex = xcom.Size - 1;
        }
Exemple #20
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            FilterableValueProvider    providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterableValueProvider    provider     = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterNumericRuleEvaluator evaluator    = new FilterNumericEquals();

            double FT = 0.3048;

            ElementId              idPhase     = lastPhase.Id;
            FilterElementIdRule    rRule       = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            FilterElementIdRule    fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter room_filter = new ElementParameterFilter(rRule);
            ElementParameterFilter door_filter = new ElementParameterFilter(fRule);


            IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(room_filter)
                                    .ToElements();

            IList <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                           .WhereElementIsNotElementType()
                                           .WherePasses(door_filter).Cast <FamilyInstance>().ToList();
            IList <FamilyInstance> windows = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows)
                                             .WhereElementIsNotElementType()
                                             .WherePasses(door_filter).Cast <FamilyInstance>().ToList();

            FamilySymbol   neocube = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(q => q.Name == "cube").First() as FamilySymbol;
            IList <XYZ>    a       = new List <XYZ>();
            IList <String> b       = new List <String>();
            //Room two = rooms[0] as Room;
            int g = 0;
            FilterStringRuleEvaluator cubeEval   = new FilterStringEquals();
            FilterableValueProvider   cubeProv   = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME));
            FilterStringRule          cubeRule   = new FilterStringRule(cubeProv, cubeEval, "cube", false);
            ElementParameterFilter    cubeFilter = new ElementParameterFilter(cubeRule);

            List <FamilyInstance> existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList();


            using (Transaction tr = new Transaction(doc, "creating"))
            {
                tr.Start();

                foreach (FamilyInstance i in existCubes)
                {
                    doc.Delete(i.Id);
                }
                foreach (Element i in rooms)
                {
                    for (int ind = 0; ind < doors.Count; ind++)
                    {
                        FamilyInstance dr = doors[ind];
                        try
                        {
                            if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id)
                            {
                                BoundingBoxXYZ bBox   = i.get_BoundingBox(null);
                                LocationPoint  origin = (LocationPoint)i.Location;

                                XYZ center = origin.Point;
                                if (!neocube.IsActive)
                                {
                                    neocube.Activate();
                                }
                                FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                                cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString());
                                cubeIns.setType();

                                b.Append("ok");                                //dr.LookupParameter("ADSK_Марка").AsValueString());
                                doors.Remove(dr);
                                ind--;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    /*
                     * foreach (FamilyInstance dr in doors)
                     * {
                     *      try
                     *      {
                     *              if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id)
                     *              {
                     *
                     *                      BoundingBoxXYZ bBox = i.get_BoundingBox(null);
                     *                      LocationPoint origin = (LocationPoint)i.Location;
                     *
                     *                      XYZ center = origin.Point;
                     *                      if (!neocube.IsActive)
                     *                              neocube.Activate();
                     *                      FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                     *                      cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                     *                      cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString());
                     *                      cubeIns.LookupParameter("isAreo").Set(0);
                     *
                     *                      b.Append("ok");//dr.LookupParameter("ADSK_Марка").AsValueString());
                     *
                     *              }
                     *      }
                     *      catch (Exception)
                     *      {
                     *
                     *      }
                     * }
                     */
                    foreach (FamilyInstance dr in windows)
                    {
                        try
                        {
                            if (dr.get_FromRoom(lastPhase).Id == i.Id)
                            {
                                LocationPoint origin = (LocationPoint)i.Location;

                                XYZ center = origin.Point;
                                if (!neocube.IsActive)
                                {
                                    neocube.Activate();
                                }
                                FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                                cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString());
                                cubeIns.setType();


                                FamilyInstance winOtkos = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                winOtkos.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                                winOtkos.LookupParameter("MainText").Set("Площадь откосов: ");
                                winOtkos.LookupParameter("Area").Set(dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble()
                                                                     * (dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble()));
                                winOtkos.setType("area");

                                FamilyInstance winPodok = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                winPodok.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                                String output = String.Format("Подоконник {0:f2}x{1:f2}", dr.LookupParameter("VIDNAL_Ширина проема").AsDouble() * FT, dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * FT);
                                winPodok.LookupParameter("MainText").Set(output);
                                winPodok.setType();

                                FamilyInstance winUgol = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                winUgol.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                                winUgol.LookupParameter("MainText").Set("ПВХ уголок 60х60");
                                winUgol.LookupParameter("dlina").Set(dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble());
                                winUgol.setType("len");
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                foreach (Element i in rooms)
                {
                    if (i.LookupParameter("ЗаменаПокрытияПола").AsInteger() == 1)
                    {
                        LocationPoint origin = (LocationPoint)i.Location;
                        XYZ           center = origin.Point;
                        if (!neocube.IsActive)
                        {
                            neocube.Activate();
                        }
                        FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                        cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                        cubeIns.LookupParameter("MainText").Set(i.LookupParameter("snosF").AsString());
                        cubeIns.LookupParameter("Area").Set(i.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble());
                        cubeIns.setType("area");
                        if (cubeIns.LookupParameter("MainText").AsString() == "")
                        {
                            doc.Delete(cubeIns.Id);
                        }
                    }
                    if (i.LookupParameter("НоваяОтделка").AsInteger() == 1)
                    {
                        LocationPoint origin = (LocationPoint)i.Location;
                        XYZ           center = origin.Point;
                        if (!neocube.IsActive)
                        {
                            neocube.Activate();
                        }
                        FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                        cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                        cubeIns.LookupParameter("MainText").Set("Демонтаж штукатурки");
                        cubeIns.LookupParameter("Area").Set(i.LookupParameter("WallS").AsDouble());
                        cubeIns.setType("area");
                    }
                }
                tr.Commit();
            }


            //XYZ origin = new XYZ(0,0,0);

            /*
             * using (Transaction tr = new Transaction(doc,"creating"))
             * {
             *      tr.Start();
             *
             *      for (int i = 0; i < a.Count; i++)
             *      {
             *              if (!neocube.IsActive)
             *                      neocube.Activate();
             *              FamilyInstance cubeIns = doc.Create.NewFamilyInstance(a[i], neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
             *              cubeIns.LookupParameter("MainText").Set(b[i]);
             *      }
             *
             *
             *      tr.Commit();
             *
             * }
             */

            //FamilySymbol elt = doors[0].Symbol;
            //FamilySymbol one=elt as FamilySymbol;
            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = g.ToString();
            msg.Show();



            return(Result.Succeeded);
        }
Exemple #21
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;
            FinishForm MainForm  = new FinishForm(doc);

            MainForm.disFElements("Number");
            MainForm.ShowDialog();
            lastPhase = MainForm.retPhase;
            idPhase   = lastPhase.Id;



            FilterNumericRuleEvaluator evaluator   = new FilterNumericEquals();
            FilterableValueProvider    provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule        fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter     door_filter = new ElementParameterFilter(fRule);

            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(door_filter)
                                       .ToElements();

            List <Element> otdWalls   = allWalls.Where(x => x.Name.StartsWith("I__Отделка")).ToList();
            List <Room>    roomofWall = new List <Room>();



            using (Transaction tr = new Transaction(doc, "creating"))
            {
                tr.Start();
                foreach (Element i in otdWalls)
                {
                    BoundingBoxXYZ bBox = i.get_BoundingBox(null);

                    if (bBox != null)
                    {
                        XYZ origin = new XYZ((bBox.Max.X + bBox.Min.X) / 2, (bBox.Max.Y + bBox.Min.Y) / 2, (bBox.Max.Z + bBox.Min.Z) / 2);
                        try
                        {
                            i.setP("Помещение", doc.GetRoomAtPoint(origin, lastPhase).Number);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }



                tr.Commit();
            }

            return(Result.Succeeded);
        }
Exemple #22
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;


            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .ToElements();

            IList <Element> allDoors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                       .WhereElementIsNotElementType()
                                       .ToElements();

            IList <Element> allKolons = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Columns)
                                        .WhereElementIsNotElementType()
                                        .ToElements();


            using (Transaction tr = new Transaction(doc, "otdelka"))
            {
                tr.Start();
                foreach (Element w in allWalls)
                {
                    if (w.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString() == "обозначения")
                    {
                        continue;
                    }
                    LocationCurve loc = w.Location as LocationCurve;

                    w.LookupParameter("СП_Стадия возведения").Set(w.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString());
                    //BoundingBoxXYZ bbox=w.get_Geometry(new Options).
                    w.LookupParameter("СП_Стадия сноса").Set(w.get_Parameter(BuiltInParameter.PHASE_DEMOLISHED).AsValueString());
                    w.LookupParameter("СП_Высота").Set(w.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsDouble());


                    //w.LookupParameter("СП_Длина").Set(w.getP(BuiltInParameter.));
                }
                foreach (Element w in allDoors)
                {
                    w.LookupParameter("СП_Стадия возведения").Set(w.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString());
                }
                foreach (Element k in allKolons)
                {
                    k.LookupParameter("СП_Стадия возведения").Set(k.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString());
                    k.LookupParameter("СП_Стадия сноса").Set(k.get_Parameter(BuiltInParameter.PHASE_DEMOLISHED).AsValueString());
                }
                tr.Commit();
            }



            //TaskDialog msg = new TaskDialog("Info");
            //msg.MainInstruction = one[3];
            //msg.Show();



            return(Result.Succeeded);
        }
Exemple #23
0
        /// <summary>
        /// Creates a new export options cache from the data in the ExporterIFC passed from Revit.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC handle passed during export.</param>
        /// <returns>The new cache.</returns>
        public static ExportOptionsCache Create(ExporterIFC exporterIFC, Document document, Autodesk.Revit.DB.View filterView)
        {
            IDictionary <String, String> options = exporterIFC.GetOptions();

            ExportOptionsCache cache = new ExportOptionsCache();

            cache.FileVersion            = exporterIFC.FileVersion;
            cache.FileName               = exporterIFC.FileName;
            cache.ExportBaseQuantities   = exporterIFC.ExportBaseQuantities;
            cache.WallAndColumnSplitting = exporterIFC.WallAndColumnSplitting;
            cache.SpaceBoundaryLevel     = exporterIFC.SpaceBoundaryLevel;
            // Export Part element only if 'Current View Only' is checked and 'Show Parts' is selected.
            cache.ExportParts = filterView != null && filterView.PartsVisibility == PartsVisibility.ShowPartsOnly;
            cache.ExportPartsAsBuildingElementsOverride = null;
            cache.ExportAllLevels           = false;
            cache.ExportAnnotationsOverride = null;
            cache.FilterViewForExport       = filterView;
            cache.ExportBoundingBoxOverride = null;
            cache.IncludeSiteElevation      = false;
            cache.UseCoarseTessellation     = true;

            cache.PropertySetOptions = PropertySetOptions.Create(exporterIFC, cache);

            String use2DRoomBoundary       = Environment.GetEnvironmentVariable("Use2DRoomBoundaryForRoomVolumeCalculationOnIFCExport");
            bool?  use2DRoomBoundaryOption = GetNamedBooleanOption(options, "Use2DRoomBoundaryForVolume");

            cache.Use2DRoomBoundaryForRoomVolumeCreation =
                ((use2DRoomBoundary != null && use2DRoomBoundary == "1") ||
                 cache.ExportAs2x2 ||
                 (use2DRoomBoundaryOption != null && use2DRoomBoundaryOption.GetValueOrDefault()));

            bool?exportAdvancedSweptSolids = GetNamedBooleanOption(options, "ExportAdvancedSweptSolids");

            cache.ExportAdvancedSweptSolids = (exportAdvancedSweptSolids.HasValue) ? exportAdvancedSweptSolids.Value : false;

            // Set GUIDOptions here.
            {
                // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                cache.GUIDOptions.Use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                bool?allowGUIDParameterOverride = GetNamedBooleanOption(options, "AllowGUIDParameterOverride");
                if (allowGUIDParameterOverride != null)
                {
                    cache.GUIDOptions.AllowGUIDParameterOverride = allowGUIDParameterOverride.Value;
                }

                bool?storeIFCGUID = GetNamedBooleanOption(options, "StoreIFCGUID");
                if (storeIFCGUID != null)
                {
                    cache.GUIDOptions.StoreIFCGUID = storeIFCGUID.Value;
                }
            }

            // Set NamingOptions here.
            cache.NamingOptions = new NamingOptions();
            {
                bool?useFamilyAndTypeNameForReference = GetNamedBooleanOption(options, "UseFamilyAndTypeNameForReference");
                cache.NamingOptions.UseFamilyAndTypeNameForReference =
                    (useFamilyAndTypeNameForReference != null) && useFamilyAndTypeNameForReference.GetValueOrDefault();

                bool?useVisibleRevitNameAsEntityName = GetNamedBooleanOption(options, "UseVisibleRevitNameAsEntityName");
                cache.NamingOptions.UseVisibleRevitNameAsEntityName =
                    (useVisibleRevitNameAsEntityName != null) && useVisibleRevitNameAsEntityName.GetValueOrDefault();
            }

            // "SingleElement" export option - useful for debugging - only one input element will be processed for export
            String singleElementValue;
            String elementsToExportValue;

            if (options.TryGetValue("SingleElement", out singleElementValue))
            {
                ElementId elementId = ParseElementId(singleElementValue);

                List <ElementId> ids = new List <ElementId>();
                ids.Add(elementId);
                cache.ElementsForExport = ids;
            }
            else if (options.TryGetValue("ElementsForExport", out elementsToExportValue))
            {
                IList <ElementId> ids = ParseElementIds(elementsToExportValue);
                cache.ElementsForExport = ids;
            }
            else
            {
                cache.ElementsForExport = new List <ElementId>();
            }

            // "ExportAnnotations" override
            cache.ExportAnnotationsOverride = GetNamedBooleanOption(options, "ExportAnnotations");

            // "ExportSeparateParts" override
            cache.ExportPartsAsBuildingElementsOverride = GetNamedBooleanOption(options, "ExportPartsAsBuildingElements");

            // "ExportBoundingBox" override
            cache.ExportBoundingBoxOverride = GetNamedBooleanOption(options, "ExportBoundingBox");

            // Using the alternate UI or not.
            cache.AlternateUIVersionOverride = GetNamedStringOption(options, "AlternateUIVersion");

            // Include IFCSITE elevation in the site local placement origin
            bool?includeIfcSiteElevation = GetNamedBooleanOption(options, "IncludeSiteElevation");

            cache.IncludeSiteElevation = includeIfcSiteElevation != null ? includeIfcSiteElevation.Value : false;

            // Use coarse tessellation for floors, railings, ramps, spaces and stairs.
            bool?useCoarseTessellation = GetNamedBooleanOption(options, "UseCoarseTessellation");

            cache.UseCoarseTessellation = useCoarseTessellation != null ? useCoarseTessellation.Value : true;

            /// Allow exporting a mix of extrusions and BReps as a solid model, if possible.
            bool?canExportSolidModelRep = GetNamedBooleanOption(options, "ExportSolidModelRep");

            cache.CanExportSolidModelRep = canExportSolidModelRep != null ? canExportSolidModelRep.Value : false;

            // Set the phase we are exporting
            cache.ActivePhase = ElementId.InvalidElementId;

            String activePhaseElementValue;

            if (options.TryGetValue("ActivePhase", out activePhaseElementValue))
            {
                cache.ActivePhase = ParseElementId(activePhaseElementValue);
            }

            if ((cache.ActivePhase == ElementId.InvalidElementId) && (cache.FilterViewForExport != null))
            {
                Parameter currPhase = cache.FilterViewForExport.get_Parameter(BuiltInParameter.VIEW_PHASE);
                if (currPhase != null)
                {
                    cache.ActivePhase = currPhase.AsElementId();
                }
            }

            if (cache.ActivePhase == ElementId.InvalidElementId)
            {
                PhaseArray phaseArray = document.Phases;
                Phase      lastPhase  = phaseArray.get_Item(phaseArray.Size - 1);
                cache.ActivePhase = lastPhase.Id;
            }

            // "FileType" - note - setting is not respected yet
            ParseFileType(options, cache);

            cache.SelectedConfigName = GetNamedStringOption(options, "ConfigName");

            return(cache);
        }
Exemple #24
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;


            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;


            FilterableValueProvider    valueProvider = new ParameterValueProvider(new ElementId(BuiltInParameter.PHASE_CREATED));
            FilterNumericRuleEvaluator evaluator     = new FilterNumericEquals();
            ElementId ruleValue = idPhase;
            ElementParameterFilter stageFilter = new ElementParameterFilter(new FilterElementIdRule(valueProvider, evaluator, ruleValue));

            List <List <Element> > collectFromModel = new List <List <Element> >();

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Where(x => ((FamilyInstance)x).StructuralType.ToString() != "NonStructural")
                                 .Cast <Element>()
                                 .ToList());
            //collectFromModel.Add(karkas);

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());

            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Rebar))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(RebarInSystem))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Railing))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(HostedSweep))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Roofs)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionPlates)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionAnchors)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .Where(x => x.Name != "cube")
                                 .ToList());


            List <Element> floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(stageFilter)
                                    .Cast <Element>()
                                    .ToList();
            List <Element> walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                   .WhereElementIsNotElementType()
                                   .WherePasses(stageFilter)
                                   .Cast <Element>()
                                   .ToList();
            List <Element> fundament = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFoundation)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(stageFilter)
                                       .Cast <Element>()
                                       .ToList();
            List <Element> lestnici = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Stairs)
                                      .WhereElementIsNotElementType()
                                      .WherePasses(stageFilter)
                                      .Cast <Element>()
                                      .ToList();



            //genModel = genModel.Where(x => x.Name != "cube").ToList();
            List <Cube> allCube = new List <Cube>();

            foreach (List <Element> a in collectFromModel)
            {
                foreach (Element e in a)
                {
                    Cube abc = new Cube(e);
                    if (abc.out_Name == null | abc.out_Name == "")
                    {
                        abc.out_Name = "Исключение: " + abc.typeName;
                    }
                    allCube.Add(abc);
                }
            }

            foreach (Element f in floors)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element w in walls)
            {
                foreach (ElementId m in w.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), w);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element f in fundament)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }
            foreach (Element f in lestnici)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }



            List <List <Cube> > groupingCube = new List <List <Cube> >();

            //List<string> groupNum=allCube.Select(x => x.Group).Distinct().ToList();

            foreach (string eqGroup in allCube.Select(x => x.out_Group).Distinct())
            {
                List <Cube> similarGroup = new List <Cube>();
                foreach (Cube c in allCube)
                {
                    if (c.out_Group == eqGroup)
                    {
                        similarGroup.Add(c);
                    }
                }
                groupingCube.Add(similarGroup);
            }

            List <Cube> outCube = new List <Cube>();

            foreach (List <Cube> item in groupingCube)
            {
                int a = 1;
                //int addpos = 1;

                foreach (string eqName in item.Select(x => x.out_Name).Distinct())
                {
                    List <Cube> b = new List <Cube>();

                    foreach (Cube i in item)
                    {
                        if (i.out_Name == eqName)
                        {
                            b.Add(i);
                        }
                    }
                    (Cube addCube, int addpos) = Meta.forgeCube(b, a);
                    if (addCube.out_Name.Contains("Исключение"))
                    {
                        a--;
                    }
                    a += addpos;
                    outCube.Add(addCube);
                }
            }
            List <ElementId>   argh   = uidoc.Selection.GetElementIds().ToList();
            List <wtf.Product> TabSel = new List <wtf.Product>();

            foreach (var item in argh)
            {
                TabSel.Add(new wtf.TABSCreator().Create(doc.GetElement(item)));
            }
            foreach (var item in TabSel)
            {
                foreach (Cube c in outCube)
                {
                    if (item.grouping == c.out_Group)
                    {
                        item.linkedElt.Add(c);
                    }
                }
            }
            using (Transaction tr = new Transaction(doc, "SetCurrentSpec"))
            {
                tr.Start();
                foreach (wtf.Product i in TabSel)
                {
                    if (i.linkedElt.Count < 2)
                    {
                        continue;
                    }
                }
                int rowCount = 0;
                foreach (wtf.Product e in TabSel)
                {
                    e.refElt.refElement.setP("Лист", doc.GetElement(e.refElt.refElement.OwnerViewId).getP("Номер листа"));
                    e.refElt.refElement.setP("Строк", e.linkedElt.Count);
                    e.linkedElt = e.linkedElt.OrderBy(x => x.Prior).ToList();
                    foreach (Cube cube in e.linkedElt)
                    {
                        if (cube.out_Name.Contains("Исключение"))
                        {
                            continue;
                        }
                        rowCount++;
                        e.refElt.refElement.setP($"Поз__{rowCount}", cube.out_Pos);
                        e.refElt.refElement.setP($"Обозначение__{rowCount}", cube.out_Gost);
                        e.refElt.refElement.setP($"Наименование__{rowCount}", cube.out_Name);
                        e.refElt.refElement.setP($"К__{rowCount}", cube.out_Kol_vo);
                        e.refElt.refElement.setP($"М__{rowCount}", cube.out_Mass);
                        e.refElt.refElement.setP($"Прим__{rowCount}", cube.out_Other);
                    }
                    rowCount = 0;
                }
                tr.Commit();
            }
            return(Result.Succeeded);
        }