Exemplo n.º 1
0
        public static void ExportToIFC(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("Export to IFC");

                IFCExportOptions opt = new IFCExportOptions();

                doc.Export(@".\", "output.ifc", opt);
                transaction.Commit();
            }

            LogTrace("Saving IFC file...");
        }
Exemplo n.º 2
0
        private static void DesignAutoFunction(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new InvalidDataException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            Document newDoc = rvtApp.NewProjectDocument(UnitSystem.Imperial);

            if (newDoc == null)
            {
                throw new InvalidOperationException("Could not create new document.");
            }
            string filePath     = "sketchIt.rvt";
            string filepathJson = "jsonDocument.json";
            string filepathXML  = "xmlDocument.xml";

            CreateWallsCommon.CreateBuilding cwc = new CreateWallsCommon.CreateBuilding();
            cwc.CreateBuildingElements(filepathJson, filepathXML, newDoc);
            newDoc.SaveAs(filePath);
        }
Exemplo n.º 3
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            var app = sender as Autodesk.Revit.ApplicationServices.Application;
            DesignAutomationData data = new DesignAutomationData(app, "InputFile.rvt");

            this.ExportFBX(data);
        }
Exemplo n.º 4
0
        private void ExtractInfo(DesignAutomationData _data)
        {
            var doc = _data.RevitDoc;

            LogTrace("Rvt File opened...");
            var inputParameters = JsonConvert.DeserializeObject <InputParams>(File.ReadAllText("params.json"));

            LogTrace($"HubId: {inputParameters.HubId}");
            LogTrace($"ProjectId: {inputParameters.ProjectId}");
            LogTrace($"Filename: {inputParameters.Filename}");

            GoodPracticeDocument data;

            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("Extract Good practices info");

                data = new GoodPracticeDocument(inputParameters.HubId, inputParameters.ProjectId, inputParameters.Filename, inputParameters.Version, doc);
                LogTrace("Data get ok...");

                trans.RollBack();
            }

            //Save the updated file by overwriting the existing file
            ModelPath ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(OUTPUT_FILE);
            var       _path            = ModelPathUtils.ConvertModelPathToUserVisiblePath(ProjectModelPath);

            //Save the project file with updated window's parameters
            LogTrace("Saving file...");
            var json = JsonConvert.SerializeObject(data);

            File.WriteAllText(_path, json);
        }
Exemplo n.º 5
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            DesignAutomationData data = new DesignAutomationData(app, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "sdk/csharp/src/revit/HyparRevitApp/hypar.rvt"));

            CreateHyparModel(data);
        }
Exemplo n.º 6
0
        public void CreateHyparModel(DesignAutomationData data)
        {
            #if !DEBUG
            var model = ParseExecution("execution.json");
            #else
            var model = ParseExecution(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "execution.json"));
            #endif

            var beamSymbol   = GetStructuralSymbol(data.RevitDoc, BuiltInCategory.OST_StructuralFraming, "200UB25.4");
            var columnSymbol = GetStructuralSymbol(data.RevitDoc, BuiltInCategory.OST_StructuralColumns, "450 x 450mm");
            var floorType    = GetFloorType(data.RevitDoc, "Insitu Concrete");
            var fec          = new FilteredElementCollector(data.RevitDoc);
            var levels       = fec.OfClass(typeof(Level)).Cast <Level>().ToList();

            Transaction trans = new Transaction(data.RevitDoc);
            trans.Start("Hypar");

            CreateBeams(model, beamSymbol, levels, data.RevitDoc, data.RevitApp);
            CreateWalls(model, levels, data.RevitDoc, data.RevitApp);
            CreateColumns(model, columnSymbol, levels, data.RevitDoc, data.RevitApp);
            CreateFloors(model, floorType, levels, data.RevitDoc, data.RevitApp);

            trans.Commit();

            #if !DEBUG
            var path = ModelPathUtils.ConvertUserVisiblePathToModelPath($"result.rvt");
            data.RevitDoc.SaveAs(path, new SaveAsOptions());
            #else
            data.RevitDoc.SaveAs(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"result.rvt"));
            #endif
        }
Exemplo n.º 7
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Application          app  = sender as Application;
            DesignAutomationData data = new DesignAutomationData(app, "C:\\Program Files\\Autodesk\\Revit 2019\\Samples\\Entry Door Handle 2018.rfa");

            UpgradeFile(data);
        }
Exemplo n.º 8
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            DesignAutomationData data = new DesignAutomationData(app, "C:\\Program Files\\Autodesk\\Revit 2019\\Samples\\WindowFamilyTmp.rft");

            CreateWindowFamily(data);
        }
Exemplo n.º 9
0
        private static void SketchItFunc(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new InvalidDataException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            Document newDoc = rvtApp.NewProjectDocument(UnitSystem.Imperial);

            if (newDoc == null)
            {
                throw new InvalidOperationException("Could not create new document.");
            }
            string filePath = "sketchIt.rvt";

            string         filepathJson     = "SketchItInput.json";
            SketchItParams jsonDeserialized = SketchItParams.Parse(filepathJson);

            CreateWalls(jsonDeserialized, newDoc);

            CreateFloors(jsonDeserialized, newDoc);

            newDoc.SaveAs(filePath);
        }
Exemplo n.º 10
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            String filePath           = Directory.GetCurrentDirectory() + "\\WindowFamilyTmp.rft";
            DesignAutomationData data = new DesignAutomationData(app, filePath);

            CreateWindowFamily(data);
        }
Exemplo n.º 11
0
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Application          app      = sender as Application;
            String               filePath = Directory.GetCurrentDirectory() + @"\Change to your local legacy RFA file for local test";
            DesignAutomationData data     = new DesignAutomationData(app, filePath);

            UpgradeFile(data);
        }
        public void HandleApplicationInitializedEvent(object sender,
                                                      Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            // We don't need to provide the file
            DesignAutomationData data = new DesignAutomationData(app, "C:\\tmp\\FindColumns-Basic.rvt");

            FindColumnsIOMain(data.RevitDoc);
        }
Exemplo n.º 13
0
        public static void ScheduleWalls(DesignAutomationData data)
        {
            InputParams inputParameters = JsonSerializer.Deserialize <InputParams>(File.ReadAllText("params.json"));

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }


            List <String> lines     = new List <string>();
            string        separator = ",";

            FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall));
            List <Wall> walls            = col.WhereElementIsNotElementType().ToElements().Cast <Wall>().ToList();

            foreach (Wall wall in walls)
            {
                string[] line = new string[5]
                {
                    wall.Id.ToString(),
                          wall.Name.ToString(),
                          wall.WallType.Name.ToString(),
                          wall.Width.ToString(),
                          wall.StructuralUsage.ToString()
                };

                lines.Add(string.Join(separator, line));
            }

            LogTrace("Saving Schedule file...");
            File.WriteAllLines(inputParameters.ScheduleName, lines.ToArray());
            // File.WriteAllLines("WallSchedule.csv", lines.ToArray());
        }
Exemplo n.º 14
0
        public void HandleDesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e)
        {
            // get the application
            Application app = sender as Application;

            // get the data
            string path = e.DesignAutomationData.FilePath;
            DesignAutomationData data = new DesignAutomationData(app, path);

            DeleteViewsNotOnSheets(data.RevitDoc);
            e.Succeeded = true;
        }
Exemplo n.º 15
0
        private static void Process(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new InvalidDataException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            System.Console.WriteLine("Start application...");

            System.Console.WriteLine("File Path" + data.FilePath);


            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                System.Console.WriteLine("No File Path");
            }

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            // SetUnits(doc);

            string          filepathJson     = "WoodProjectInput.json";
            WoodProjectItem jsonDeserialized = WoodProjectParams.Parse(filepathJson);

            CreateWalls(jsonDeserialized, doc);

            var saveAsOptions = new SaveAsOptions();

            saveAsOptions.OverwriteExistingFile = true;

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("woodproject_result.rvt");

            doc.SaveAs(path, saveAsOptions);
        }
Exemplo n.º 16
0
        protected bool CreateWindowFamily(DesignAutomationData data)
        {
            if (data == null)
            {
                return(false);
            }

            Application app = data.RevitApp;

            if (app == null)
            {
                return(false);
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                return(false);
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                return(false);
            }

            CreateWindowData createWindowData = new CreateWindowData();

            createWindowData.Application = app;
            createWindowData.Document    = doc;


            ////////////////////////////////////////////////////////////////
            if (!doc.IsFamilyDocument)
            {
                Console.WriteLine("It's not family document");
                return(false);
            }
            else
            {
                if (null != doc.OwnerFamily && null != doc.OwnerFamily.FamilyCategory &&
                    doc.OwnerFamily.FamilyCategory.Name != doc.Settings.Categories.get_Item(BuiltInCategory.OST_Windows).Name)
                // FamilyCategory.Name is not "Windows".
                {
                    Console.WriteLine("It's not windows family template");
                    return(false);
                }
                WindowWizard wizard = new WindowWizard(createWindowData);
                return(wizard.RunWizard());
            }
        }
Exemplo n.º 17
0
        public static void DeleteAllDoors(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            IList <Element> listOfDoors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors).WhereElementIsNotElementType().ToElements();
            int             taille      = listOfDoors.Count;

            using (Transaction tr = new Transaction(doc))
            {
                tr.Start("do");
                for (int i = 0; i < taille; i++)
                {
                    DeleteElement(doc, listOfDoors[i]);
                }

                tr.Commit();
            }
            ModelPath     path = ModelPathUtils.ConvertUserVisiblePathToModelPath("DeleteDoorsProjectResult.rvt");
            SaveAsOptions SAO  = new SaveAsOptions();

            SAO.OverwriteExistingFile = false;

            //Save the project file with updated window's parameters
            LogTrace("Saving file...");
            doc.SaveAs(path, SAO);
        }
        //local test entry point
        public void HandleApplicationInitializedEvent(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e)
        {
            try
            {
                Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;

                DesignAutomationData data = new DesignAutomationData(app, @"c:\temp\rac_advanced_sample_project.rvt");
                //DesignAutomationData data = new DesignAutomationData(app, @"c:\temp\result.rvt");

                DoJob(data);
            }
            catch (Exception)
            {
                throw new InvalidOperationException("Could not ini application!");
            }
        }
Exemplo n.º 19
0
        private void DesignAutomationBridge_DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e)
        {
            LogTrace("Design Automation Ready event triggered...");
            e.Succeeded = true;
            DesignAutomationData data   = e.DesignAutomationData;
            Application          rvtApp = data.RevitApp;
            string   modelPath          = data.FilePath;
            Document doc = data.RevitDoc;

            using (Transaction t = new Transaction(doc))
            {
                // Start the transaction
                t.Start("Export Sheets DWG");
                try
                {
                    var viewSheets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet)).Cast <ViewSheet>().Where(vw =>
                                                                                                                           vw.ViewType == ViewType.DrawingSheet && !vw.IsTemplate);

                    // create DWG export options
                    DWGExportOptions dwgOptions = new DWGExportOptions();
                    dwgOptions.MergedViews  = true;
                    dwgOptions.SharedCoords = true;
                    dwgOptions.FileVersion  = ACADVersion.R2018;

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

                    foreach (var sheet in viewSheets)
                    {
                        if (!sheet.IsPlaceholder)
                        {
                            views.Add(sheet.Id);
                        }
                    }

                    // For Web Deployment
                    //doc.Export(@"D:\sheetExporterLocation", "TEST", views, dwgOptions);
                    // For Local
                    doc.Export(Directory.GetCurrentDirectory() + "//exportedDwgs", "rvt", views, dwgOptions);
                }
                catch (Exception ex)
                {
                }
                // Commit the transaction
                t.Commit();
            }
        }
Exemplo n.º 20
0
        private static void GenerateRevitFile(DesignAutomationData daData)
        {
            var      rvtApp = daData.RevitApp;
            Document newDoc = rvtApp.NewProjectDocument(UnitSystem.Imperial) ?? throw new InvalidOperationException("Could not create new document.");

            var osmServie = ContainerStore.Resolve <OsmService>();

            using (Transaction t = new Transaction(newDoc, "Build City"))
            {
                t.Start();

                MapBounds mapBounds = MapBounds.Deserialize(File.ReadAllText(MapBoundsFile));
                OsmStore.Geolocate(mapBounds);
                osmServie.Run(newDoc);
                t.Commit();
            }

            newDoc.SaveAs(ResultFile);
        }
Exemplo n.º 21
0
        /// <summary>
        /// delete elements depends on the input params.json file
        /// </summary>
        /// <param name="data"></param>
        public void DeleteAllElements(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            _doc = data.RevitDoc;
            if (_doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }


            _tt = new Transaction(_doc, "Generate Facades");

            countItParams = DeleteElementsParams.Parse("params.json");


            GenerateFacade();


            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");

            _doc.SaveAs(path, new SaveAsOptions());
        }
Exemplo n.º 22
0
        public static void DeleteAllWalls(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            using (Transaction transaction = new Transaction(doc))
            {
                FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall));
                transaction.Start("Delete All Walls");
                doc.Delete(col.ToElementIds());
                transaction.Commit();
            }

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");

            doc.SaveAs(path, new SaveAsOptions());
        }
        public static bool ProcessParameters(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            InputParams inputParams = InputParams.Parse("params.json");

            if (inputParams.Export)
            {
                return(ExportToExcel(rvtApp, doc, inputParams.IncludeFireRating, inputParams.IncludeComments));
            }
            else
            {
                return(ImportFromExcel(rvtApp, doc, inputParams.IncludeFireRating, inputParams.IncludeComments));
            }
        }
Exemplo n.º 24
0
        private void EditWindowParametersMethod(Application app, string projectPath)
        {
            // Get the data of the project file(i.e)the project in which families are present
            DesignAutomationData data = new DesignAutomationData(app, projectPath);
            //get the revit project document
            Document doc = data.RevitDoc;

            //Modifying the window parameters
            //Open transaction
            using (Transaction windowTransaction = new Transaction(doc))
            {
                windowTransaction.Start("Update window parameters");

                //Filter for windows
                FilteredElementCollector WindowCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsNotElementType();
                IList <ElementId>        windowIds       = WindowCollector.ToElementIds() as IList <ElementId>;

                foreach (ElementId windowId in windowIds)
                {
                    Element        Window  = doc.GetElement(windowId);
                    FamilyInstance FamInst = Window as FamilyInstance;
                    FamilySymbol   FamSym  = FamInst.Symbol;
                    SetElementParameter(FamSym, BuiltInParameter.WINDOW_HEIGHT, windowHeight);
                    SetElementParameter(FamSym, BuiltInParameter.WINDOW_WIDTH, windowWidth);
                }

                //To save all the changes commit the transaction
                windowTransaction.Commit();
            }

            //Save the updated file by overwriting the existing file
            ModelPath     ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(projectPath);
            SaveAsOptions SAO = new SaveAsOptions();

            SAO.OverwriteExistingFile = true;

            //Save the project file with updated window's parameters
            doc.SaveAs(ProjectModelPath, SAO);
        }
Exemplo n.º 25
0
        protected void UpgradeFile(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            BasicFileInfo fileInfo = BasicFileInfo.Extract(modelPath);

            if (fileInfo.Format.Equals("2019"))
            {
                return;
            }

            string pathName = doc.PathName;

            string[]  pathParts = pathName.Split('\\');
            string[]  nameParts = pathParts[pathParts.Length - 1].Split('.');
            string    extension = nameParts[nameParts.Length - 1];
            string    filePath  = "revitupgrade." + extension;
            ModelPath path      = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            SaveAsOptions saveOpts = new SaveAsOptions();

            // Check for permanent preview view
            if (doc
                .GetDocumentPreviewSettings()
                .PreviewViewId
                .Equals(ElementId.InvalidElementId))
            {
                // use 3D view as preview
                View view = new FilteredElementCollector(doc)
                            .OfClass(typeof(View))
                            .Cast <View>()
                            .Where(vw =>
                                   vw.ViewType == ViewType.ThreeD && !vw.IsTemplate
                                   )
                            .FirstOrDefault();

                if (view != null)
                {
                    saveOpts.PreviewViewId = view.Id;
                }
            }
            doc.SaveAs(path, saveOpts);
        }
Exemplo n.º 26
0
        private bool ExportFBX(DesignAutomationData data)
        {
            if (data == null)
            {
                return(false);
            }

            Application app = data.RevitApp;

            if (app == null)
            {
                return(false);
            }

            string modelPath = data.FilePath;

            if (string.IsNullOrWhiteSpace(modelPath))
            {
                return(false);
            }

            var doc = data.RevitDoc;

            if (doc == null)
            {
                return(false);
            }

            using (var collector = new FilteredElementCollector(doc))
            {
                LogTrace("Collecting 3D views...");

                var exportPath = Path.Combine(Directory.GetCurrentDirectory(), "exported");
                if (!Directory.Exists(exportPath))
                {
                    try
                    {
                        Directory.CreateDirectory(exportPath);
                    }
                    catch (Exception ex)
                    {
                        this.PrintError(ex);
                        return(false);
                    }
                }

                LogTrace(string.Format("Export Path: {0}", exportPath));

                var veiwIds = collector.WhereElementIsNotElementType()
                              .OfClass(typeof(View3D))
                              .WhereElementIsNotElementType()
                              .Cast <View3D>()
                              .Where(v => !v.IsTemplate)
                              .Select(v => v.Id);

                if (veiwIds == null || veiwIds.Count() <= 0)
                {
                    LogTrace("No 3D views to be exported...");
                    return(false);
                }

                LogTrace("Starting the export task...");

                try
                {
                    foreach (var viewId in veiwIds)
                    {
                        var exportOpts = new FBXExportOptions();
                        exportOpts.StopOnError          = true;
                        exportOpts.WithoutBoundaryEdges = true;

                        var view = doc.GetElement(viewId) as View3D;
                        var name = view.Name;
                        name = name.Replace("{", "_").Replace("}", "_").ReplaceInvalidFileNameChars();
                        var filename = string.Format("{0}.fbx", name);

                        LogTrace(string.Format("Exporting {0}...", filename));

                        var viewSet = new ViewSet();
                        viewSet.Insert(view);

                        doc.Export(exportPath, filename, viewSet, exportOpts);
                    }
                }
                catch (Autodesk.Revit.Exceptions.InvalidPathArgumentException ex)
                {
                    this.PrintError(ex);
                    return(false);
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException ex)
                {
                    this.PrintError(ex);
                    return(false);
                }
                catch (Autodesk.Revit.Exceptions.InvalidOperationException ex)
                {
                    this.PrintError(ex);
                    return(false);
                }
                catch (Exception ex)
                {
                    this.PrintError(ex);
                    return(false);
                }
            }

            return(true);
        }
        public static void DoJob(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document rvtDoc = data.RevitDoc;

            if (rvtDoc == null)
            {
                throw new InvalidOperationException("Could not open document!");
            }

            //add shared parameter definition
            AddSetOfSharedParameters(rvtDoc);

            try
            {
                // Deleting existing DirectShape
                // might need to filter out the shapes for room only?
                // get ready to filter across just the elements visible in a view
                FilteredElementCollector coll = new FilteredElementCollector(rvtDoc);
                coll.OfClass(typeof(DirectShape));
                IEnumerable <DirectShape> DSdelete = coll.Cast <DirectShape>();

                using (Transaction tx = new Transaction(rvtDoc))
                {
                    tx.Start("Delete Direct Shape");

                    try
                    {
                        foreach (DirectShape ds in DSdelete)
                        {
                            ICollection <ElementId> ids = rvtDoc.Delete(ds.Id);
                        }

                        tx.Commit();
                    }
                    catch (ArgumentException)
                    {
                        tx.RollBack();
                        throw new InvalidOperationException("Delete Direct Shape Failed!");
                    }
                }

                //get all rooms
                FilteredElementCollector m_Collector = new FilteredElementCollector(rvtDoc);
                m_Collector.OfCategory(BuiltInCategory.OST_Rooms);
                IList <Element> m_Rooms  = m_Collector.ToElements();
                int             roomNbre = 0;

                ElementId roomId = null;

                //  Iterate the list and gather a list of boundaries
                foreach (Room room in m_Rooms)
                {
                    //  Avoid unplaced rooms
                    if (room.Area > 1)
                    {
                        String _family_name = "testRoom-" + room.UniqueId.ToString();

                        using (Transaction tr = new Transaction(rvtDoc))
                        {
                            tr.Start("Create Mass");

                            // Found BBOX

                            BoundingBoxXYZ bb = room.get_BoundingBox(null);
                            XYZ            pt = new XYZ((bb.Min.X + bb.Max.X) / 2, (bb.Min.Y + bb.Max.Y) / 2, bb.Min.Z);


                            //  Get the room boundary
                            IList <IList <BoundarySegment> > boundaries = room.GetBoundarySegments(new SpatialElementBoundaryOptions()); // 2012


                            // a room may have a null boundary property:
                            int n = 0;

                            if (null != boundaries)
                            {
                                n = boundaries.Count;
                            }


                            //  The array of boundary curves
                            CurveArray m_CurveArray = new CurveArray();


                            // Add Direct Shape
                            List <CurveLoop> curveLoopList = new List <CurveLoop>();

                            if (0 < n)
                            {
                                int iBoundary = 0, iSegment;

                                foreach (IList <BoundarySegment> b in boundaries) // 2012
                                {
                                    List <Curve> profile = new List <Curve>();
                                    ++iBoundary;
                                    iSegment = 0;

                                    foreach (BoundarySegment s in b)
                                    {
                                        ++iSegment;
                                        Curve curve = s.GetCurve(); // 2016
                                        profile.Add(curve);         //add shape for instant object
                                    }


                                    try
                                    {
                                        CurveLoop curveLoop = CurveLoop.Create(profile);
                                        curveLoopList.Add(curveLoop);
                                    }
                                    catch (Exception ex)
                                    {
                                        //Debug.WriteLine(ex.Message);
                                    }
                                }
                            }

                            try
                            {
                                SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);

                                Frame frame = new Frame(pt, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY);

                                //  Simple insertion point
                                XYZ pt1 = new XYZ(0, 0, 0);
                                //  Our normal point that points the extrusion directly up
                                XYZ ptNormal = new XYZ(0, 0, 100);
                                //  The plane to extrude the mass from
                                Plane       m_Plane       = Plane.CreateByNormalAndOrigin(ptNormal, pt1);
                                SketchPlane m_SketchPlane = SketchPlane.Create(rvtDoc, m_Plane); // 2014

                                Location loc = room.Location;

                                LocationPoint lp = loc as LocationPoint;

                                Level oBelow = getNearestBelowLevel(rvtDoc, lp.Point.Z);
                                Level oUpper = getNearestUpperLevel(rvtDoc, lp.Point.Z);

                                double height = oUpper.Elevation - oBelow.Elevation;

                                Solid roomSolid;
                                roomSolid = GeometryCreationUtilities.CreateExtrusionGeometry(curveLoopList, ptNormal, height);

                                DirectShape ds = DirectShape.CreateElement(rvtDoc, new ElementId(BuiltInCategory.OST_GenericModel));

                                ds.SetShape(new GeometryObject[] { roomSolid });

                                roomId = ds.Id;


                                roomNbre += 1;
                                tr.Commit();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }

                        using (Transaction tx = new Transaction(rvtDoc))
                        {
                            tx.Start("Change P");

                            Element   readyDS = rvtDoc.GetElement(roomId);
                            Parameter p       = readyDS.LookupParameter("RoomNumber");
                            if (p != null)
                            {
                                p.Set(room.Number.ToString());
                            }
                            tx.Commit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.ToString());
            }
        }
Exemplo n.º 28
0
        public static void InsertObjects(DesignAutomationData data)
        {
            //Get data from Design Automation
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            //Revit file path and open document
            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }
            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            //Load all families in the model
            List <FamilyParams.BaseStruct> famParams = FamilyParams.Parse(@"families/list.json");

            using (Transaction tr_fam = new Transaction(doc, "SubTansactionLaodFamilies"))
            {
                tr_fam.Start();
                foreach (FamilyParams.BaseStruct _fam_params in famParams)
                {
                    using (SubTransaction subTr_fam = new SubTransaction(doc))
                    {
                        subTr_fam.Start();

                        string famName = _fam_params.path;

                        bool isLoaded = LoadFamily(doc, @"families/" + famName, famName.Replace(".rfa", ""));

                        subTr_fam.Commit();
                    }
                }
                tr_fam.Commit();
            }


            //Params from JSON file
            List <InputParams.BaseStruct> inputParams = InputParams.Parse("params.json");

            if (inputParams == null)
            {
                throw new InvalidOperationException("Cannot parse JSON");
            }


            //Prepare output params
            List <OutputParams.BaseStruct> list_outputs = new List <OutputParams.BaseStruct>();

            using (Transaction tr = new Transaction(doc, "SubTransactionUses"))
            {
                tr.Start();
                foreach (InputParams.BaseStruct _params in inputParams)
                {
                    using (SubTransaction subTr = new SubTransaction(doc))
                    {
                        subTr.Start();

                        //Output Params
                        OutputParams.BaseStruct outputParams = new OutputParams.BaseStruct();

                        if (_params.status == "new")
                        {
                            Element elt_create = CreateElement(doc, _params);
                            SetParameters(elt_create, _params);

                            outputParams.id      = _params.id;
                            outputParams.RevitID = elt_create.Id.IntegerValue;
                            outputParams.status  = "new";
                            list_outputs.Add(outputParams);
                        }
                        else if (_params.status == "changedPK")
                        {
                            int elt_ID = (int)double.Parse(_params.RevitID, System.Globalization.CultureInfo.InvariantCulture);
                            doc.Delete(new ElementId(elt_ID));

                            Element elt_create = CreateElement(doc, _params);
                            SetParameters(elt_create, _params);

                            outputParams.id      = _params.id;
                            outputParams.RevitID = elt_create.Id.IntegerValue;
                            outputParams.status  = "changedPK";
                            list_outputs.Add(outputParams);
                        }
                        else if (_params.status == "changedParameters")
                        {
                            int     elt_ID     = (int)double.Parse(_params.RevitID, System.Globalization.CultureInfo.InvariantCulture);
                            Element elt_create = doc.GetElement(new ElementId(elt_ID));
                            SetParameters(elt_create, _params);

                            outputParams.id      = _params.id;
                            outputParams.RevitID = elt_create.Id.IntegerValue;
                            outputParams.status  = "changedParameters";
                            list_outputs.Add(outputParams);
                        }
                        else if (_params.status == "deleted")
                        {
                            int elt_ID = (int)double.Parse(_params.RevitID, System.Globalization.CultureInfo.InvariantCulture);
                            doc.Delete(new ElementId(elt_ID));

                            outputParams.id      = _params.id;
                            outputParams.RevitID = -1;
                            outputParams.status  = "deleted";
                            list_outputs.Add(outputParams);
                        }
                        subTr.Commit();
                    }
                }
                tr.Commit();
            }

            //Save JSON file
            string jsonContent = JsonConvert.SerializeObject(list_outputs);

            //write string to file
            File.WriteAllText("result.json", jsonContent);

            //Save Revit file
            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");

            doc.SaveAs(path, new SaveAsOptions());
        }
Exemplo n.º 29
0
        private void compoundStructureLayeToJson(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            JArray wallInfoResult = new JArray();

            FilteredElementCollector wallCollector = new FilteredElementCollector(doc).OfClass(typeof(Wall)).WhereElementIsNotElementType();

            foreach (Element e in wallCollector)
            {
                Wall     w     = e as Wall;
                WallType wtype = w.WallType;

                //CURTAIN WALL doesn't contain compound structure layers
                if (wtype != null && !wtype.Name.Contains("Curtain"))
                {
                    CompoundStructure compoundStruct = wtype.GetCompoundStructure();
                    IList <CompoundStructureLayer> compoundStructLayers = compoundStruct.GetLayers() as IList <CompoundStructureLayer>;
                    if (compoundStructLayers.Count == 0)
                    {
                        continue;
                    }

                    dynamic wallLayersInfo = new JObject();
                    wallLayersInfo.uniqueId = w.UniqueId;
                    wallLayersInfo.layers   = new JArray();

                    foreach (CompoundStructureLayer compoundStructLayer in compoundStructLayers)
                    {
                        dynamic layerInfo = new JObject();
                        layerInfo.function = compoundStructLayer.Function.ToString();
                        layerInfo.material = ((Material)doc.GetElement(compoundStructLayer.MaterialId)).Name;
                        layerInfo.width    = compoundStructLayer.Width;

                        wallLayersInfo.layers.Add(layerInfo);
                    }

                    wallInfoResult.Add(wallLayersInfo);
                }
            }

            // save all to a .json file
            using (StreamWriter file = File.CreateText("result.json"))
                using (JsonTextWriter writer = new JsonTextWriter(file))
                {
                    wallInfoResult.WriteTo(writer);
                }
        }
Exemplo n.º 30
0
        public static void ParseRooms(DesignAutomationData data)
        {
            LogTrace("Parsing the file for rooms...");

            Document doc = data.RevitDoc;


            List <Autodesk.Revit.DB.Architecture.Room> rooms = new FilteredElementCollector(doc)
                                                               .OfCategory(BuiltInCategory.OST_Rooms)
                                                               .WhereElementIsNotElementType()
                                                               .ToElements()
                                                               .Cast <Autodesk.Revit.DB.Architecture.Room>()
                                                               .ToList();

            Dictionary <ElementId, SvgDocument> svgDocumentsDictonary = BuildSvgDocumentsDictonary(doc);

            List <string> roomNames = new List <string>();


            BoundingBox boundingBox = new BoundingBox();

            foreach (Autodesk.Revit.DB.Architecture.Room room in rooms)
            {
                if (room != null)
                {
                    roomNames.Add(room.Name);

                    SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions();
                    opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish;

                    IList <IList <Autodesk.Revit.DB.BoundarySegment> > boundarySegmentArray = room.GetBoundarySegments(opt);
                    if (null == boundarySegmentArray)  //the room may not be bound
                    {
                        continue;
                    }

                    if (svgDocumentsDictonary.ContainsKey(room.Level.Id))
                    {
                        SvgGroup svgGroup = new SvgGroup();
                        svgGroup.CustomAttributes["roomId"]   = room.Id.ToString();
                        svgGroup.CustomAttributes["roomName"] = room.Name;

                        svgDocumentsDictonary[room.Level.Id].Children.Add(svgGroup);

                        foreach (IList <Autodesk.Revit.DB.BoundarySegment> boundarySegArr in boundarySegmentArray)
                        {
                            if (0 == boundarySegArr.Count)
                            {
                                continue;
                            }
                            else
                            {
                                List <Curve> curves = new List <Curve>();

                                foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in boundarySegArr)
                                {
                                    Curve boundaryCurve = boundarySegment.GetCurve();


                                    if (boundaryCurve != null)
                                    {
                                        curves.Add(boundaryCurve);

                                        boundingBox.UpdateBox(boundaryCurve.GetEndPoint(0));
                                        boundingBox.UpdateBox(boundaryCurve.GetEndPoint(1));
                                    }
                                }

                                svgGroup.Children.Add(SvgConversion.ConvertCurve(curves));
                            }
                        }
                    }
                }
            }



            foreach (KeyValuePair <ElementId, SvgDocument> item in svgDocumentsDictonary)
            {
                item.Value.Width   = new SvgUnit((float)boundingBox.GetWidth());
                item.Value.Height  = new SvgUnit((float)boundingBox.GetHeight());
                item.Value.ViewBox = new SvgViewBox((float)boundingBox.minX, (float)boundingBox.minY, (float)boundingBox.GetWidth(), (float)boundingBox.GetHeight());

                // string path = $".\rooms{}.svg";
                string path = @".\rooms" + item.Key.ToString() + ".svg";
                item.Value.Write(path);
            }

            LogTrace("Rooms file saved in the working directory");
        }