Exemplo n.º 1
0
        /// <summary>
        /// Получает конструкцию, которой принадлежит IFC-стержень
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="curView"></param>
        /// <param name="rebar"></param>
        /// <param name="concreteElements"></param>
        /// <returns></returns>
        public static Element GetHostElementForIfcRebar(Document doc, View view, Element rebar, List <Element> concreteElements, Transform transform2)
        {
            Element        hostElem       = null;
            List <Element> intersectElems = Intersection.GetAllIntersectionElements(doc, view, rebar, concreteElements, transform2);

            if (intersectElems == null || intersectElems.Count == 0)
            {
                //эта ifc-арматура висит в воздухе, пропускаем
                return(null);
            }

            if (intersectElems.Count == 1)
            {
                hostElem = intersectElems.First();                            //ifc-арматура пересекается только с одной конструкцией, это и есть её основа
            }
            //если пересекает несколько конструкций - берем нижнюю
            if (intersectElems.Count > 1)
            {
                View defaultView = ViewSupport.GetDefaultView(doc);
                hostElem = Intersection.GetBottomElement(intersectElems, defaultView);
            }

            return(hostElem);
        }
Exemplo n.º 2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document    mainDoc  = commandData.Application.ActiveUIDocument.Document;
            Application revitApp = commandData.Application.Application;

            //открываю окно выбора параметров, которые буду заполняться
            FormSelectParams formSelectParams = new FormSelectParams();

            formSelectParams.ShowDialog();
            if (formSelectParams.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }


            RebarDocumentWorker mainWorker = new RebarDocumentWorker();
            List <Element>      mainDocConcreteElements = new List <Element>();



            string mainWorkerMessage = mainWorker.Start(mainDoc, revitApp, Transform.Identity, out mainDocConcreteElements);

            if (!string.IsNullOrEmpty(mainWorkerMessage))
            {
                message = mainWorkerMessage + ". Документ " + mainDoc.Title;
                return(Result.Failed);
            }

            if (Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.NoLinks)
            {
                return(Result.Succeeded);
            }

            List <RevitLinkInstance> linksAll = new FilteredElementCollector(mainDoc)
                                                .OfClass(typeof(RevitLinkInstance))
                                                .Cast <RevitLinkInstance>()
                                                .ToList();

            List <RevitLinkInstance> linksLib = linksAll
                                                .Where(i => i.Name.Contains(".lib"))
                                                .ToList();

            // имя ссылки lib и список конструкций, которые она пересекает
            Dictionary <string, List <Element> > hostElemsForLibLinks = new Dictionary <string, List <Element> >();

            foreach (RevitLinkInstance rli in linksLib)
            {
                string  linkInstanceTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                Element hostElem          = LinksSupport.GetConcreteElementIsHostForLibLinkFile(mainDoc, ViewSupport.GetDefaultView(mainDoc), mainDocConcreteElements, rli);
                if (hostElem == null)
                {
                    continue;
                }
                if (hostElemsForLibLinks.ContainsKey(linkInstanceTitle))
                {
                    hostElemsForLibLinks[linkInstanceTitle].Add(hostElem);
                }
                else
                {
                    hostElemsForLibLinks.Add(linkInstanceTitle, new List <Element> {
                        hostElem
                    });
                }
            }
            List <RevitLinkInstance> linksWithoutDuplicates = LinksSupport.DeleteDuplicates(linksAll);

            foreach (RevitLinkInstance rli in linksWithoutDuplicates)
            {
                RevitLinkType rlt     = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType;
                Document      linkDoc = rli.GetLinkDocument();
                if (linkDoc == null)
                {
                    continue;
                }

                string linkDocTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                if (!linkDocTitle.Contains("-КР-"))
                {
                    continue;
                }
                if (!linkDocTitle.Contains("lib") && Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.OnlyLibs)
                {
                    continue;
                }



                ModelPath mPath = linkDoc.GetWorksharingCentralModelPath();

                rlt.Unload(new SaveCoordinates());

                OpenOptions oo = new OpenOptions();

                linkDoc = revitApp.OpenDocumentFile(mPath, oo);


                RebarDocumentWorker linkWorker = new RebarDocumentWorker();
                if (linkDocTitle.Contains("lib"))
                {
                    if (hostElemsForLibLinks.ContainsKey(linkDocTitle))
                    {
                        List <Element> mainElemsForLib = hostElemsForLibLinks[linkDocTitle];
                        if (mainElemsForLib.Count > 0)
                        {
                            linkWorker.MainElementsForLibFile = mainElemsForLib;
                        }
                    }
                }
                Transform      linkTransform        = rli.GetTransform();
                List <Element> linkConcreteElements = new List <Element>();
                string         linkWorkerMessage    = linkWorker.Start(linkDoc, revitApp, linkTransform, out linkConcreteElements);
                if (!string.IsNullOrEmpty(linkWorkerMessage))
                {
                    message = linkWorkerMessage + ". Связь " + linkDoc.Title;
                    return(Result.Failed);
                }



                TransactWithCentralOptions    transOpt = new TransactWithCentralOptions();
                SynchronizeWithCentralOptions syncOpt  = new SynchronizeWithCentralOptions();

                RelinquishOptions relOpt = new RelinquishOptions(true);
                syncOpt.SetRelinquishOptions(relOpt);

                linkDoc.SynchronizeWithCentral(transOpt, syncOpt);

                linkDoc.Close();
#if R2017
                RevitLinkLoadResult rllr = rlt.Reload();
#else
                LinkLoadResult llr = rlt.Reload();
#endif
            }

            return(Result.Succeeded);
        }
Exemplo n.º 3
0
        public string Start(Document doc, Autodesk.Revit.ApplicationServices.Application revitApp, Transform linkTransform, out List <Element> concreteElements)
        {
            haveConcreteClass    = true;
            defaultConcreteClass = 25;
            Category rebarCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Rebar);

            rebarCatSet = revitApp.Create.NewCategorySet();
            rebarCatSet.Insert(rebarCat);
            ElementId rebarCategoryId = new ElementId(BuiltInCategory.OST_Rebar);

            //собираю арматуру
            List <Element> rebarsAll = new FilteredElementCollector(doc)
                                       .WhereElementIsNotElementType()
                                       .OfCategory(BuiltInCategory.OST_Rebar)
                                       .ToElements()
                                       .ToList();

            List <Rebar> StandartRebars = new FilteredElementCollector(doc)
                                          .OfClass(typeof(Rebar))
                                          .Cast <Rebar>()
                                          .ToList();

            List <RebarInSystem> RebarsInSystem = new FilteredElementCollector(doc)
                                                  .OfClass(typeof(RebarInSystem))
                                                  .Cast <RebarInSystem>()
                                                  .ToList();

            List <FamilyInstance> rebarsIfcAll = new FilteredElementCollector(doc)
                                                 .OfClass(typeof(FamilyInstance))
                                                 .OfCategory(BuiltInCategory.OST_Rebar)
                                                 .Cast <FamilyInstance>()
                                                 .ToList();

            List <FamilyInstance> rebarsIfcSingle = new FilteredElementCollector(doc)
                                                    .OfClass(typeof(FamilyInstance))
                                                    .OfCategory(BuiltInCategory.OST_Rebar)
                                                    .Cast <FamilyInstance>()
                                                    .Where(i => i.SuperComponent == null)
                                                    .ToList();

            List <FamilyInstance> rebarsIfcNested = new FilteredElementCollector(doc)
                                                    .OfClass(typeof(FamilyInstance))
                                                    .OfCategory(BuiltInCategory.OST_Rebar)
                                                    .Cast <FamilyInstance>()
                                                    .Where(i => i.SuperComponent != null)
                                                    .ToList();

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

            rebarsNotNested.AddRange(StandartRebars);
            rebarsNotNested.AddRange(RebarsInSystem);
            rebarsNotNested.AddRange(rebarsIfcSingle);


            //сгруппирую вложенные семейства по родительским
            foreach (FamilyInstance nestedRebar in rebarsIfcNested)
            {
                FamilyInstance parentFamily = ParentFamilyContainer.GetMainParentFamily(nestedRebar);
                int            parentId     = parentFamily.Id.IntegerValue;
                if (parentFamiliesBase.ContainsKey(parentId))
                {
                    parentFamiliesBase[parentId].childFamilies.Add(nestedRebar);
                }
                else
                {
                    List <FamilyInstance> fams = new List <FamilyInstance>()
                    {
                        nestedRebar
                    };
                    ParentFamilyContainer pfc = new ParentFamilyContainer(parentFamily, nestedRebar);
                    parentFamiliesBase.Add(parentId, pfc);
                }
            }



            //собираю бетонные элементы
            CategoriesSupport catSupport          = new CategoriesSupport(revitApp, doc);
            List <ElementId>  concreteCategodyIds = catSupport.GetConcreteCategodyIds();
            View defaultView3d = ViewSupport.GetDefaultView(doc);

            concreteElements = new FilteredElementCollector(doc, defaultView3d.Id)
                               .WhereElementIsNotElementType()
                               .Where(x => x.Category != null)
                               .Where(x => x.Category.Id != rebarCategoryId)
                               .Where(x => concreteCategodyIds.Contains(x.Category.Id))
                               .Where(x => Intersection.ContainsSolids(x))
                               .Where(x => Intersection.CheckElementIsConcrete(x))
                               .ToList();

            if (Settings.UseHostMark && MainElementsForLibFile == null)
            {
                string errorIds = "";
                foreach (Element elem in concreteElements)
                {
                    Parameter markParam = elem.get_Parameter(BuiltInParameter.ALL_MODEL_MARK);

                    string tempMark = markParam.AsString();
                    if (string.IsNullOrEmpty(tempMark))
                    {
                        errorIds += elem.Id.IntegerValue.ToString() + "; ";
                    }
                }
                if (errorIds != "")
                {
                    string msg = "Не заполнена Марка у конструкций: " + errorIds;
                    return(msg);
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Rebar BDS");

                //заполняю массу, длину и диаметр
                foreach (Element elem in rebarsAll)
                {
                    Parameter p = ParametersSupport.GetParameter(elem, "Орг.ИзделиеТипПодсчета");
                    if (p == null)
                    {
                        continue;            //отсеиваем левую арматуру без параметров
                    }
                    int c = p.AsInteger();
                    if (c < 1 || c > 5)
                    {
                        continue;                 //отсеиваем каркасы и закладные детали
                    }
                    MyRebar myrebar = new MyRebar(elem);

                    if (!myrebar.IsValid)
                    {
                        continue;
                    }

                    if (Settings.UseRebarWeight)
                    {
                        Parameter paramWeight = ParametersSupport.CheckAndAddSharedParameter(elem, revitApp, rebarCatSet, "BDS_Weight", BuiltInParameterGroup.INVALID, true);
                        paramWeight.Set(myrebar.weightFinal);
                    }

                    if (Settings.UseRebarLength)
                    {
                        Parameter paramLength = ParametersSupport.CheckAndAddSharedParameter(elem, revitApp, rebarCatSet, "BDS_Length", BuiltInParameterGroup.INVALID, true);
                        paramLength.Set(myrebar.lengthMm);
                    }

                    if (Settings.UseRebarDiameter)
                    {
                        Parameter diamParam = ParametersSupport.CheckAndAddSharedParameter(elem, revitApp, rebarCatSet, "BDS_Diameter", BuiltInParameterGroup.INVALID, true);
                        diamParam.Set(myrebar.diameterMm);
                    }
                }

                doc.Regenerate();


                //заполняю марку основы для не вложенных стержней
                foreach (Element rebarNotNested in rebarsNotNested)
                {
                    ElementId      hostId    = null;
                    List <Element> hostElems = null;

                    if (MainElementsForLibFile != null) //если основной бетонный элемент задан принудительно
                    {
                        hostElems = MainElementsForLibFile;
                    }
                    else
                    {
                        if (rebarNotNested is Rebar)
                        {
                            hostId = (rebarNotNested as Rebar).GetHostId();
                        }
                        if (rebarNotNested is RebarInSystem)
                        {
                            hostId = (rebarNotNested as RebarInSystem).GetHostId();
                        }
                        if (rebarNotNested is FamilyInstance)
                        {
                            Element tempHost = Intersection.GetHostElementForIfcRebar(doc, defaultView3d, rebarNotNested, concreteElements, linkTransform);
                            if (tempHost == null)
                            {
                                rebarWithoutHost.Add(rebarNotNested);
                                continue;
                            }
                            hostId = tempHost.Id;
                        }

                        if (hostId == null)
                        {
                            rebarWithoutHost.Add(rebarNotNested);
                            continue;
                        }
                        Element hostElem = doc.GetElement(hostId);
                        hostElems = new List <Element>()
                        {
                            hostElem
                        };
                    }

                    string msg = ParametersSupport.WriteHostInfoSingleRebar(revitApp, rebarCatSet, rebarNotNested, hostElems);
                    if (msg != string.Empty)
                    {
                        return(msg);
                    }
                }

                //заполняю марку основы для стержней, вложенных в сложные семейства
                foreach (var kvp in parentFamiliesBase)
                {
                    ParentFamilyContainer pfc          = kvp.Value;
                    FamilyInstance        parentFamily = pfc.parentFamily;

                    Dictionary <int, Element> hostElemsBase = new Dictionary <int, Element>();

                    List <Element> mainHostElems = null;

                    if (MainElementsForLibFile != null)  //если основной бетонный элемент задан принудительно
                    {
                        mainHostElems = MainElementsForLibFile;
                    }
                    else
                    {
                        if (parentFamily.Host is Wall || parentFamily.Host is Floor) //родительское семейство - на основе стены или пола, можно легко получить основу
                        {
                            Element mainHostElem = parentFamily.Host;
                            mainHostElems = new List <Element>()
                            {
                                mainHostElem
                            };
                        }
                        else
                        {
                            foreach (FamilyInstance nestedRebar in pfc.childFamilies)
                            {
                                Element hostElem = Intersection.GetHostElementForIfcRebar(doc, defaultView3d, nestedRebar, concreteElements, linkTransform);
                                if (hostElem == null)
                                {
                                    continue;
                                }
                                int hostElemId = hostElem.Id.IntegerValue;
                                if (!hostElemsBase.ContainsKey(hostElemId))
                                {
                                    hostElemsBase.Add(hostElemId, hostElem);
                                }
                            }
                            if (hostElemsBase.Count == 0)
                            {
                                rebarWithoutHost.Add(parentFamily);
                                continue;
                            }

                            if (hostElemsBase.Count == 1)
                            {
                                Element mainHostElem = hostElemsBase.First().Value;
                                mainHostElems = new List <Element>()
                                {
                                    mainHostElem
                                };
                            }
                            if (hostElemsBase.Count > 1)
                            {
                                List <Element> hosts        = hostElemsBase.Values.ToList();
                                View           defaultView  = ViewSupport.GetDefaultView(doc);
                                Element        mainHostElem = Intersection.GetBottomElement(hosts, defaultView);
                                mainHostElems = new List <Element>()
                                {
                                    mainHostElem
                                };
                            }
                        }
                    }

                    if (Settings.UseHostMark)
                    {
                        string hostMark = "";
                        foreach (Element mainHostElem in mainHostElems)
                        {
                            Parameter hostMarkParam = mainHostElem.get_Parameter(BuiltInParameter.ALL_MODEL_MARK);
                            string    tempHostMark  = hostMarkParam.AsString();
                            if (string.IsNullOrEmpty(tempHostMark))
                            {
                                return("Не заполнена марка у конструкции: " + mainHostElem.Id.IntegerValue.ToString() + " в файле " + mainHostElem.Document.Title);
                            }

                            if (hostMark != "")
                            {
                                hostMark += "|";
                            }
                            hostMark += tempHostMark;
                        }
                        ParametersSupport.TryWriteParameter(parentFamily, "Мрк.МаркаКонструкции", hostMark);
                    }

                    foreach (FamilyInstance nestedRebar in pfc.childFamilies)
                    {
                        ParametersSupport.WriteHostInfoSingleRebar(revitApp, rebarCatSet, nestedRebar, mainHostElems);
                    }
                }


                t.Commit();
            }
            return(string.Empty);
        }