diff --git a/CDMUtil/CDM.Interop.Revit.csproj b/CDMUtil/CDM.Interop.Revit.csproj new file mode 100644 index 0000000..6bd03a9 --- /dev/null +++ b/CDMUtil/CDM.Interop.Revit.csproj @@ -0,0 +1,110 @@ + + + + + Debug + AnyCPU + {6538FD90-4B43-4CE3-A066-A8BCE39DD907} + Library + Properties + CDM.Interop.Revit + CDM.Interop.Revit + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + 4.5.3.2 + + + 2016.0.0 + + + + + \ No newline at end of file diff --git a/CDMUtil/CDM/rfa/矩形柱.rfa b/CDMUtil/CDM/rfa/矩形柱.rfa new file mode 100644 index 0000000..dd0588d Binary files /dev/null and b/CDMUtil/CDM/rfa/矩形柱.rfa differ diff --git a/CDMUtil/CDM/rfa/矩形梁.rfa b/CDMUtil/CDM/rfa/矩形梁.rfa new file mode 100644 index 0000000..1ce33b9 Binary files /dev/null and b/CDMUtil/CDM/rfa/矩形梁.rfa differ diff --git a/CDMUtil/CDM/xlsx/柱.xlsx b/CDMUtil/CDM/xlsx/柱.xlsx new file mode 100644 index 0000000..b652eaa Binary files /dev/null and b/CDMUtil/CDM/xlsx/柱.xlsx differ diff --git a/CDMUtil/CDM/xlsx/梁.xlsx b/CDMUtil/CDM/xlsx/梁.xlsx new file mode 100644 index 0000000..6adb609 Binary files /dev/null and b/CDMUtil/CDM/xlsx/梁.xlsx differ diff --git a/CDMUtil/CDM/xlsx/楼板.xlsx b/CDMUtil/CDM/xlsx/楼板.xlsx new file mode 100644 index 0000000..cb22a13 Binary files /dev/null and b/CDMUtil/CDM/xlsx/楼板.xlsx differ diff --git a/CDMUtil/CDM/xlsx/楼梯.xlsx b/CDMUtil/CDM/xlsx/楼梯.xlsx new file mode 100644 index 0000000..c3ba83b Binary files /dev/null and b/CDMUtil/CDM/xlsx/楼梯.xlsx differ diff --git a/CDMUtil/CmdCDMToRevit.cs b/CDMUtil/CmdCDMToRevit.cs new file mode 100644 index 0000000..e683ef3 --- /dev/null +++ b/CDMUtil/CmdCDMToRevit.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.Utility; +using CDM.Interop.Revit.RevitCompoent; +using Microsoft.Win32; + +namespace CDM.Interop.Revit +{ + [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] + [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] + class CmdCDMToRevit : Autodesk.Revit.UI.IExternalCommand + { + static string AddInPath = typeof(CmdCDMToRevit).Assembly.Location; + public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) + { + Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; + Document doc = commandData.Application.ActiveUIDocument.Document; + Level level = null; + Family family = null; + IList levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements(); + foreach (Level l in levels) + { + //if (l.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsDouble() == 0) + if (l.ProjectElevation == 0) + { + level = l; + break; + } + } + List columns = new List(); + List beams = new List(); + List walls = new List(); + List floors = new List(); + List stairs = new List(); + + string filter = "读取CDM集(*.xlsx)|*.xlsx"; + OpenFileDialog openDialog = new OpenFileDialog(); + openDialog.Multiselect = true; + openDialog.Filter = filter; + openDialog.Title = "选择CDM文件"; + openDialog.ShowDialog(); + + string[] paths = openDialog.FileNames; + if (paths.Count() == 0) + { + return Result.Cancelled; + } + + #region 备用 + //List list = new List(); + //for (int i = 0; i < paths.Count(); i++) + //{ + // string filename = System.IO.Path.GetFileNameWithoutExtension(paths[i]); + // FilePathInfo fpi = new FilePathInfo() + // { + // FileName = filename, + // Path = paths[i], + // }; + // if (filename.Contains("A21005")) + // { + // fpi.Category = "墙"; + // } + // else if (filename.Contains("A21002")) + // { + // fpi.Category = "梁"; + // } + // else if (filename.Contains("A21003")) + // { + // fpi.Category = "板"; + // } + // else if (filename.Contains("A21001")) + // { + // fpi.Category = "柱"; + // } + // else if (filename.Contains("A21008")) + // { + // fpi.Category = "楼梯"; + // } + // else + // { + // fpi.Category = "未知"; + // } + // list.Add(fpi); + //} + + #endregion + + foreach (var path in paths) + { + if (path.Contains("A21003")) + { + RevitFloor floor = new RevitFloor(path); + floors.Add(floor); + } + else if (path.Contains("A21005")) + { + RevitWall wall = new RevitWall(); + + walls.Add(wall); + } + else if (path.Contains("A21002")) + { + RevitBeam beam = new RevitBeam(path); + beams.Add(beam); + } + else if (path.Contains("A21001")) + { + RevitColumn column = new RevitColumn(path); + columns.Add(column); + } + if (path.Contains("A21004")) + { + RevitStairs stair = new RevitStairs(path); + stairs.Add(stair); + } + } + if (columns.Count > 0) + { + string columnPath = Path.GetDirectoryName(AddInPath)+ "\\CDM\\rfa\\矩形柱.rfa"; + using (Document famdoc = app.OpenDocumentFile(columnPath)) + { + family = famdoc.LoadFamily(doc, new FamilyLoadOptions()); + } + ColumnUtil.PlaceColumns(doc, family, columns, level); + } + if (beams.Count > 0) + { + string beamPath = Path.GetDirectoryName(AddInPath) + "\\CDM\\rfa\\矩形梁.rfa"; + using (Document famdoc = app.OpenDocumentFile(beamPath)) + { + family = famdoc.LoadFamily(doc, new FamilyLoadOptions()); + } + BeamUtil.PlaceBeams(doc, family, beams, level); + } + if (floors.Count > 0) + { + FloorUtil.PlaceFloors(doc, floors, level); + } + if (stairs.Count > 0) + { + StairsUtil.PlaceStairs(doc, stairs, level); + } + //RevitWallUtil.PlaceWalls(doc,walls, level); + + + + return Result.Succeeded; + } + } + class FamilyLoadOptions : IFamilyLoadOptions + { + public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) + { + + overwriteParameterValues = true; + return true; + + } + + public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues) + { + source = FamilySource.Project; + overwriteParameterValues = true; + return true; + } + } +} diff --git a/CDMUtil/CmdRevitToCDM.cs b/CDMUtil/CmdRevitToCDM.cs new file mode 100644 index 0000000..7b253a1 --- /dev/null +++ b/CDMUtil/CmdRevitToCDM.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.CDMComponent; + +namespace CDM.Interop.Revit +{ + [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] + [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] + class CmdRevitToCDM : Autodesk.Revit.UI.IExternalCommand + { + static string AddInPath = typeof(CmdRevitToCDM).Assembly.Location; + + public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) + { + Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; + UIDocument uidoc = commandData.Application.ActiveUIDocument; + Document doc = uidoc.Document; + //string AddInPath = typeof(CmdRevitToCDM).Assembly.Location; + //string dirAssembly = Path.GetDirectoryName(AddInPath); + + VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog + { + Multiselect = false + }; + dialog.ShowDialog(); + if (dialog.SelectedPath == null) + { + return Result.Cancelled; + } + string path = dialog.SelectedPath; + //View3D view3d; + //using (Transaction ts = new Transaction(doc, "3dview")) + //{ + // ts.Start(); + // ViewFamilyType viewtype = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)) + // .Cast() + // .FirstOrDefault( + // x => ViewFamily.ThreeDimensional + // == x.ViewFamily); + // view3d = View3D.CreateIsometric(doc, viewtype.Id); + + // ts.Commit(); + + //} + //uidoc.ActiveView = view3d; + View3D v3d = null; + var v3ds = new FilteredElementCollector(doc).OfClass(typeof(View3D)); + foreach (View3D view in v3ds) + { + if ("{三维}".Equals(view.Name)) + { + v3d = view; + break; + } + } + + uidoc.ActiveView = v3d; + + var levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements(); + + #region 柱 + + List cdmColumns = Utility.ColumnUtil.GetColumnCDM(doc, levels); + + if (cdmColumns.Count > 0) + { + string sourceColumnFile = Path.GetDirectoryName(AddInPath) + "\\CDM\\xlsx\\柱.xlsx"; + string destColumnsDirectory = path + "\\结构柱"; + if (!Directory.Exists(destColumnsDirectory)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(destColumnsDirectory); + directoryInfo.Create(); + } + CDMComponent2Excel.CDMColumnsToExcel(cdmColumns, sourceColumnFile, destColumnsDirectory); + } + + #endregion + + #region 板 + + List cdmFloors = Utility.FloorUtil.GetFloorsCDM(doc, levels, v3d); + if (cdmFloors.Count > 0) + { + string sourceFloorFile = Path.GetDirectoryName(AddInPath)+ "\\CDM\\xlsx\\楼板.xlsx"; + //string sourceFloorFile = Path.GetDirectoryName(AddInPath) + "\\xlsx\\楼板.xlsx"; + string destFloorsPath = path + "\\结构板"; + if (!Directory.Exists(destFloorsPath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(destFloorsPath); + directoryInfo.Create(); + } + CDMComponent2Excel.CDMFloorsToExcel(cdmFloors, sourceFloorFile, destFloorsPath); + } + #endregion + + #region 梁 + + List cdmBeams = Utility.BeamUtil.GetBeamsCDM(doc, levels); + + if (cdmBeams.Count > 0) + { + string sourceBeamFile = Path.GetDirectoryName(AddInPath) + "\\CDM\\xlsx\\梁.xlsx"; + string destBeamsDirectory = path + "\\结构梁"; + if (!Directory.Exists(destBeamsDirectory)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(destBeamsDirectory); + directoryInfo.Create(); + } + CDMComponent2Excel.CDMBeamsToExcel(cdmBeams, sourceBeamFile, destBeamsDirectory); + } + + #endregion + + + #region 墙 + + //List cdmWalls = new List(); + //cdmWalls = Utility.WallUtil.GetWallsCDM(uidoc, levels); + //string sourceWallFile = Path.GetDirectoryName(AddInPath) + "\\xlsx\\现浇剪力墙.xls"; + //destPath = path + "\\现浇剪力墙"; + //if (!Directory.Exists(destPath)) + //{ + // DirectoryInfo directoryInfo = new DirectoryInfo(destPath); + // directoryInfo.Create(); + //} + //WriteCDMUtil.WriteCDMWallsToExcel(cdmWalls, sourceWallFile, destPath); + + #endregion + + #region 楼梯 + + List cdmStairs = Utility.StairsUtil.GetStairsCDM(doc, levels, v3d); + + if (cdmStairs.Count > 0) + { + string sourceStairsFile = Path.GetDirectoryName(AddInPath) + "\\CDM\\xlsx\\楼梯.xlsx"; + string destStairsPath = path + "\\楼梯"; + if (!Directory.Exists(destStairsPath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(destStairsPath); + directoryInfo.Create(); + } + CDMComponent2Excel.CDMStairsToExcel(cdmStairs, sourceStairsFile, destStairsPath); + } + + #endregion + + return Result.Succeeded; + } + } +} diff --git a/CDMUtil/Common/CDMComponent2Excel.cs b/CDMUtil/Common/CDMComponent2Excel.cs new file mode 100644 index 0000000..54a6275 --- /dev/null +++ b/CDMUtil/Common/CDMComponent2Excel.cs @@ -0,0 +1,205 @@ +using CDM.Interop.Revit.CDMComponent; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; + +namespace CDM.Interop.Revit +{ + class CDMComponent2Excel + { + //Math.Round(number, 2, MidpointRounding.AwayFromZero)四舍五入 + public static void CDMFloorsToExcel(List floors, string sourceFileName, string destFolder) + { + foreach (var floor in floors) + { + string destFileName = destFolder + "\\" + floor.HcdmClass + "-" + floor.HcdmNumber + ".xlsx"; + File.Copy(sourceFileName, destFileName, true); + + FileInfo fi = new FileInfo(destFileName); + using (ExcelPackage package = new ExcelPackage(fi)) + { + //var worksheet = package.Workbook.Worksheets["基本构件"]; + var worksheet = package.Workbook.Worksheets[1]; + + //构件标准名称 + worksheet.Cells["G2"].Value = floor.Name; + worksheet.Cells["G3"].Value = floor.HcdmClass; + worksheet.Cells["G4"].Value = floor.HcdmClass + "-" + floor.HcdmNumber; + + worksheet.Cells["H14"].Value = floor.Xl; + worksheet.Cells["H15"].Value = floor.Yw; + worksheet.Cells["H16"].Value = floor.Zh; + worksheet.Cells["H17"].Value = 0; + + worksheet.Cells["H18"].Value = floor.L; + worksheet.Cells["H19"].Value = floor.W; + worksheet.Cells["H20"].Value = floor.T; + + var worksheet1 = package.Workbook.Worksheets["方形洞口"]; + try + { + worksheet1.Cells["H7"].Value = floor.CDMopenings[0].Xl; + worksheet1.Cells["H8"].Value = floor.CDMopenings[0].Yw; + worksheet1.Cells["H9"].Value = floor.CDMopenings[0].Length; + worksheet1.Cells["H10"].Value = floor.CDMopenings[0].Width; + + worksheet1.Cells["H11"].Value = floor.CDMopenings[1].Xl; + worksheet1.Cells["H12"].Value = floor.CDMopenings[1].Yw; + worksheet1.Cells["H13"].Value = floor.CDMopenings[1].Length; + worksheet1.Cells["H14"].Value = floor.CDMopenings[1].Width; + } + catch (Exception) + { + continue; + } + finally + { + package.Save(); + } + + }; + + } + } + public static void CDMColumnsToExcel(List columns, string sourceFileName, string destFolder) + { + foreach (var column in columns) + { + string destFileName = destFolder + "\\" + column.HcdmClass + "-" + column.HcdmNumber + ".xlsx"; + File.Copy(sourceFileName, destFileName, true); + + + FileInfo fi = new FileInfo(destFileName); + using (ExcelPackage package = new ExcelPackage(fi)) + { + var worksheet = package.Workbook.Worksheets[1]; + //var worksheet = package.Workbook.Worksheets["基本构件"]; + + //构件标准名称 + worksheet.Cells["G2"].Value = column.Name; + worksheet.Cells["G3"].Value = column.HcdmClass; + worksheet.Cells["G4"].Value = column.HcdmClass + "-" + column.HcdmNumber; + + worksheet.Cells["H14"].Value = column.Xl; + worksheet.Cells["H15"].Value = column.Yw; + worksheet.Cells["H16"].Value = column.Zh; + worksheet.Cells["H17"].Value = 0;//均不旋转,方向角为0 + worksheet.Cells["H18"].Value = column.SectionB; + worksheet.Cells["H19"].Value = column.SectionH; + worksheet.Cells["H20"].Value = column.L; + package.Save(); + }; + + } + } + public static void CDMBeamsToExcel(List beams, string sourceFileName, string destFolder) + { + foreach (var beam in beams) + { + string destFileName = destFolder + "\\" + beam.HcdmClass + "-" + beam.HcdmNumber + ".xlsx"; + File.Copy(sourceFileName, destFileName, true); + + FileInfo fi = new FileInfo(destFileName); + using (ExcelPackage package = new ExcelPackage(fi)) + { + var worksheet = package.Workbook.Worksheets[1]; + //var worksheet = package.Workbook.Worksheets["基本构件"]; + + //构件标准名称 + worksheet.Cells["G2"].Value = beam.Name; + worksheet.Cells["G3"].Value = beam.HcdmClass; + worksheet.Cells["G4"].Value = beam.HcdmClass + "-" + beam.HcdmNumber; + + worksheet.Cells["H14"].Value = beam.Xl; + worksheet.Cells["H15"].Value = beam.Yw; + worksheet.Cells["H16"].Value = beam.Zh; + worksheet.Cells["H17"].Value = beam.DegreesWithXAxis; + + worksheet.Cells["H18"].Value = beam.L; + worksheet.Cells["H19"].Value = beam.SectionB; + worksheet.Cells["H20"].Value = beam.SectionH; + package.Save(); + }; + } + } + public static void CDMWallsToExcel(List walls, string sourceFileName, string destFolder) + { + foreach (var wall in walls) + { + + string destFileName = destFolder + "\\" + wall.HcdmClass + "-" + wall.HcdmNumber + ".xlsx"; + File.Copy(sourceFileName, destFileName, true); + FileInfo fi = new FileInfo(destFileName); + using (ExcelPackage package = new ExcelPackage(fi)) + { + var worksheet = package.Workbook.Worksheets[1]; + //var worksheet = package.Workbook.Worksheets["基本构件"]; + + //构件标准名称 + worksheet.Cells["G2"].Value = wall.Name; + worksheet.Cells["G3"].Value = wall.HcdmClass; + worksheet.Cells["G4"].Value = wall.HcdmClass + "-" + wall.HcdmNumber; + + worksheet.Cells["H14"].Value = wall.Xl; + worksheet.Cells["H15"].Value = wall.Yw; + worksheet.Cells["H16"].Value = wall.Zh; + + package.Save(); + }; + } + } + public static void CDMStairsToExcel(List stairs, string sourceFileName, string destFolder) + { + foreach (var stair in stairs) + { + string destFileName = destFolder + "\\" + stair.HcdmClass + "-" + stair.HcdmNumber + ".xlsx"; + File.Copy(sourceFileName, destFileName, true); + FileInfo fi = new FileInfo(destFileName); + using (ExcelPackage package = new ExcelPackage(fi)) + { + var worksheet = package.Workbook.Worksheets[1]; + //var worksheet = package.Workbook.Worksheets["基本构件"]; + + //构件标准名称 + worksheet.Cells["G2"].Value = stair.Name; + worksheet.Cells["G3"].Value = stair.HcdmClass; + worksheet.Cells["G4"].Value = stair.HcdmClass + "-" + stair.HcdmNumber; + + worksheet.Cells["H14"].Value = stair.Runs[0].Xl; + worksheet.Cells["H15"].Value = stair.Runs[0].Yw; + worksheet.Cells["H16"].Value = stair.Runs[0].Zh; + worksheet.Cells["H17"].Value = stair.Runs[0].DegreesWithXAxis; + worksheet.Cells["H18"].Value = stair.Runs[0].Length; + worksheet.Cells["H19"].Value = stair.Runs[0].Width; + worksheet.Cells["H20"].Value = stair.Runs[0].Height; + worksheet.Cells["H21"].Value = stair.Runs[0].Thickness; + worksheet.Cells["H22"].Value = stair.Runs[0].NumberOfRisers; + + worksheet.Cells["H23"].Value = stair.Landing.Xl; + worksheet.Cells["H24"].Value = stair.Landing.Yw; + worksheet.Cells["H25"].Value = stair.Landing.Zh; + worksheet.Cells["H26"].Value = stair.Landing.Length; + worksheet.Cells["H27"].Value = stair.Landing.Width; + worksheet.Cells["H28"].Value = stair.Landing.Thickness; + + worksheet.Cells["H29"].Value = stair.Runs[1].Xl; + worksheet.Cells["H30"].Value = stair.Runs[1].Yw; + worksheet.Cells["H31"].Value = stair.Runs[1].Zh; + worksheet.Cells["H32"].Value = stair.Runs[1].DegreesWithXAxis; + worksheet.Cells["H33"].Value = stair.Runs[1].Length; + worksheet.Cells["H34"].Value = stair.Runs[1].Width; + worksheet.Cells["H35"].Value = stair.Runs[1].Height; + worksheet.Cells["H36"].Value = stair.Runs[1].Thickness; + worksheet.Cells["H37"].Value = stair.Runs[1].NumberOfRisers; + + + + + package.Save(); + }; + } + } + } +} diff --git a/CDMUtil/Common/FilePathInfo.cs b/CDMUtil/Common/FilePathInfo.cs new file mode 100644 index 0000000..240dd31 --- /dev/null +++ b/CDMUtil/Common/FilePathInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit +{ + class FilePathInfo + { + + public string Path { get; set; } + public string FileName { get; set; } + + public string Category { get; set; } + } +} diff --git a/CDMUtil/Common/VistaFolderBrowserDialog.cs b/CDMUtil/Common/VistaFolderBrowserDialog.cs new file mode 100644 index 0000000..ee00ae2 --- /dev/null +++ b/CDMUtil/Common/VistaFolderBrowserDialog.cs @@ -0,0 +1,343 @@ +using Microsoft.Win32; +using System; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Interop; + +/// +/// Prompts the user to select a folder with a vista style dialog. +/// +sealed class VistaFolderBrowserDialog +{ + #region Properties + + /// + /// Gets or sets the path selected by the user. + /// + public string SelectedPath { get; set; } + + /// + /// Gets the name of the element selected by the user. + /// + public string SelectedElementName { get; private set; } + + /// + /// Gets an array of paths selected by the user. + /// + public string[] SeletcedPaths { get; private set; } + + /// + /// Gets an array of element names selected by the user. + /// + public string[] SelectedElementNames { get; private set; } + + /// + /// Gets or sets a valie indicating whether the user is able to select non storage places. + /// + public bool AllowNonStoragePlaces { get; set; } + + /// + /// Gets or sets a valie indicating whether the user can select multiple folders or elements. + /// + public bool Multiselect { get; set; } + + #endregion Properties + + #region Public Methods + + /// + /// Shows the dialog with the default owner. + /// + /// true if the user clicks OK in the dialog box; otherwise false + public bool ShowDialog() => ShowDialog(IntPtr.Zero); + + /// + /// Shows the dialog with as the owner. + /// + /// The owner of the dialog box. + /// true if the user clicks OK in the dialog box; otherwise false + public bool ShowDialog(Window owner) => ShowDialog(owner == null ? IntPtr.Zero : new WindowInteropHelper(owner).Handle); + + /// + /// Shows the dialog with as the owner. + /// + /// The owner of the dialog box. + /// true if the user clicks OK in the dialog box; otherwise false + public bool ShowDialog(IWin32Window owner) => ShowDialog(owner == null ? IntPtr.Zero : owner.Handle); + + /// + /// Shows the dialog with as the owner. + /// + /// The owner of the dialog box. + /// true if the user clicks OK in the dialog box; otherwise false + public bool ShowDialog(IntPtr owner) + { + if (Environment.OSVersion.Version.Major < 6) + { + throw new InvalidOperationException("The dialog need at least Windows Vista to work."); + } + + var dialog = CreateNativeDialog(); + try + { + SetInitialFolder(dialog); + SetOptions(dialog); + + if (dialog.Show(owner) != 0) + { + return false; + } + + SetDialogResults(dialog); + + return true; + } + finally + { + Marshal.ReleaseComObject(dialog); + } + } + + #endregion Public Methods + + #region Helper + + private void GetPathAndElementName(IShellItem item, out string path, out string elementName) + { + item.GetDisplayName(SIGDN.PARENTRELATIVEFORADDRESSBAR, out elementName); + try + { + item.GetDisplayName(SIGDN.FILESYSPATH, out path); + } + catch (ArgumentException ex) when (ex.HResult == -2147024809) + { + path = null; + } + } + + private IFileOpenDialog CreateNativeDialog() + { + return new FileOpenDialog() as IFileOpenDialog; + } + + private void SetInitialFolder(IFileOpenDialog dialog) + { + IShellItem item; + if (!string.IsNullOrEmpty(SelectedPath)) + { + IntPtr idl; + uint atts = 0; + if (NativeMethods.SHILCreateFromPath(SelectedPath, out idl, ref atts) == 0 + && NativeMethods.SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0) + { + dialog.SetFolder(item); + } + } + } + + private void SetOptions(IFileOpenDialog dialog) + { + dialog.SetOptions(GetDialogOptions()); + } + + private FOS GetDialogOptions() + { + var options = FOS.PICKFOLDERS; + if (this.Multiselect) + { + options |= FOS.ALLOWMULTISELECT; + } + if (!AllowNonStoragePlaces) + { + options |= FOS.FORCEFILESYSTEM; + } + return options; + } + + private void SetDialogResults(IFileOpenDialog dialog) + { + IShellItem item; + if (!this.Multiselect) + { + dialog.GetResult(out item); + string path, value; + GetPathAndElementName(item, out path, out value); + this.SelectedPath = path; + this.SeletcedPaths = new[] { path }; + this.SelectedElementName = value; + this.SelectedElementNames = new[] { value }; + } + else + { + IShellItemArray items; + dialog.GetResults(out items); + + uint count; + items.GetCount(out count); + + this.SeletcedPaths = new string[count]; + this.SelectedElementNames = new string[count]; + + for (uint i = 0; i < count; ++i) + { + items.GetItemAt(i, out item); + string path, value; + GetPathAndElementName(item, out path, out value); + this.SeletcedPaths[i] = path; + this.SelectedElementNames[i] = value; + } + + this.SelectedPath = null; + this.SelectedElementName = null; + } + } + + #endregion Helper + + #region Types + + private class NativeMethods + { + [DllImport("shell32.dll")] + public static extern int SHILCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath, out IntPtr ppIdl, ref uint rgflnOut); + + [DllImport("shell32.dll")] + public static extern int SHCreateShellItem(IntPtr pidlParent, IntPtr psfParent, IntPtr pidl, out IShellItem ppsi); + + [DllImport("user32.dll")] + public static extern IntPtr GetActiveWindow(); + } + + [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv); + + void GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); + + void GetDisplayName([In] SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName); + + void GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs); + + void Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder); + } + + [ComImport, Guid("B63EA76D-1F85-456F-A19C-48159EFA858B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItemArray + { + void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, out IntPtr ppvOut); + + void GetPropertyStore([In] int Flags, [In] ref Guid riid, out IntPtr ppv); + + void GetPropertyDescriptionList([In, MarshalAs(UnmanagedType.Struct)] ref IntPtr keyType, [In] ref Guid riid, out IntPtr ppv); + + void GetAttributes([In, MarshalAs(UnmanagedType.I4)] IntPtr dwAttribFlags, [In] uint sfgaoMask, out uint psfgaoAttribs); + + void GetCount(out uint pdwNumItems); + + void GetItemAt([In] uint dwIndex, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); + + void EnumItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenumShellItems); + } + + [ComImport, Guid("d57c7288-d4ad-4768-be02-9d969532d960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), CoClass(typeof(FileOpenDialog))] + private interface IFileOpenDialog //: IFileDialog + { + [PreserveSig] + int Show([In] IntPtr parent); + + void SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.Struct)] ref IntPtr rgFilterSpec); + + void SetFileTypeIndex([In] uint iFileType); + + void GetFileTypeIndex(out uint piFileType); + + void Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie); + + void Unadvise([In] uint dwCookie); + + void SetOptions([In] FOS fos); + + void GetOptions(out FOS pfos); + + void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); + + void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); + + void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); + + void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); + + void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName); + + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName); + + void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle); + + void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText); + + void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel); + + void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); + + void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, FileDialogCustomPlace fdcp); + + void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension); + + void Close([MarshalAs(UnmanagedType.Error)] int hr); + + void SetClientGuid([In] ref Guid guid); + + void ClearClientData(); + + void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter); + + void GetResults([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppenum); + + void GetSelectedItems([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppsai); + } + + [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] + private class FileOpenDialog + { } + + private enum SIGDN : uint + { + DESKTOPABSOLUTEEDITING = 0x8004c000, + DESKTOPABSOLUTEPARSING = 0x80028000, + FILESYSPATH = 0x80058000, + NORMALDISPLAY = 0, + PARENTRELATIVE = 0x80080001, + PARENTRELATIVEEDITING = 0x80031001, + PARENTRELATIVEFORADDRESSBAR = 0x8007c001, + PARENTRELATIVEPARSING = 0x80018001, + URL = 0x80068000 + } + + [Flags] + private enum FOS + { + ALLNONSTORAGEITEMS = 0x80, + ALLOWMULTISELECT = 0x200, + CREATEPROMPT = 0x2000, + DEFAULTNOMINIMODE = 0x20000000, + DONTADDTORECENT = 0x2000000, + FILEMUSTEXIST = 0x1000, + FORCEFILESYSTEM = 0x40, + FORCESHOWHIDDEN = 0x10000000, + HIDEMRUPLACES = 0x20000, + HIDEPINNEDPLACES = 0x40000, + NOCHANGEDIR = 8, + NODEREFERENCELINKS = 0x100000, + NOREADONLYRETURN = 0x8000, + NOTESTFILECREATE = 0x10000, + NOVALIDATE = 0x100, + OVERWRITEPROMPT = 2, + PATHMUSTEXIST = 0x800, + PICKFOLDERS = 0x20, + SHAREAWARE = 0x4000, + STRICTFILETYPES = 4 + } + + #endregion Types +} \ No newline at end of file diff --git a/CDMUtil/Properties/AssemblyInfo.cs b/CDMUtil/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f8d56ea --- /dev/null +++ b/CDMUtil/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("CDMUtil")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CDMUtil")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("6538fd90-4b43-4ce3-a066-a8bce39dd907")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/CDMUtil/ToCDM/CDMBeam.cs b/CDMUtil/ToCDM/CDMBeam.cs new file mode 100644 index 0000000..5c7a2eb --- /dev/null +++ b/CDMUtil/ToCDM/CDMBeam.cs @@ -0,0 +1,68 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMBeam : CDMComponent + { + //梁定位线始终在几何中心线,仅适用于水平-矩形-不发生旋转的矩形混凝土梁 + public CDMBeam(FamilyInstance beam) + { + self = beam; + + base.SymbolId = beam.GetTypeId(); + base.EleId = beam.Id; + base.LevelId = beam.Host.Id; + base.CDMTypeId = HcdmType.CDMBeam; + + m_b = GetPara(beam, "b"); + m_h = GetPara(beam, "h"); + if (beam.HasSweptProfile() == true) + { + Line line = beam.GetSweptProfile().GetDrivingCurve() as Line; + //var c = (LocationCurve)beam.Location; + //Line line = c.Curve as Line; + var rOrigin = line.Origin; + var rDirection = line.Direction; + base.Xl = rOrigin.X * 0.3048; + base.Yw = rOrigin.Y * 0.3048; + base.Zh = (rOrigin.Z - m_h.AsDouble() / 2) * 0.3048; + base.DegreesWithXAxis = rDirection.AngleTo(new XYZ(1, 0, 0)) * 180 / Math.PI; + if (Math.Round(rDirection.Y, 2, MidpointRounding.AwayFromZero) < 0) + { + DegreesWithXAxis += 180; + } + } + else + { + MessageBox.Show("可能存在重叠梁"); + } + //base.Name = beam.Symbol.FamilyName + "@" + beam.Name; + + } + private Parameter m_b; + private Parameter m_h; + + /// + /// 梁长 + /// + public double L => self.GetSweptProfile().GetDrivingCurve().Length * 304.8; + /// + /// 截面梁宽 + /// + public string SectionB => m_b.AsValueString(); + /// + /// 截面梁高 + /// + public string SectionH => m_h.AsValueString(); + /// + /// 顶部高程 + /// + private FamilyInstance self; + } +} diff --git a/CDMUtil/ToCDM/CDMColumn.cs b/CDMUtil/ToCDM/CDMColumn.cs new file mode 100644 index 0000000..98b5a0f --- /dev/null +++ b/CDMUtil/ToCDM/CDMColumn.cs @@ -0,0 +1,58 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + //柱定位线始终在几何中心线,仅适用垂直-截面矩形-不发生旋转的矩形混凝土柱 + class CDMColumn : CDMComponent + { + public CDMColumn(FamilyInstance column) + { + self = column; + base.SymbolId = column.GetTypeId(); + base.EleId = column.Id; + base.LevelId = column.LevelId; + + m_b = GetPara(column, "b"); + m_h = GetPara(column, "h"); + + //base.Name = column.Symbol.FamilyName + "@" + column.Name; + base.CDMTypeId = HcdmType.CDMColumn; + + Line line = column.GetSweptProfile().GetDrivingCurve() as Line; + var rOrigin = line.Origin; + base.Xl = (rOrigin.X - m_b.AsDouble() / 2) * 0.3048; + base.Yw = rOrigin.Y * 0.3048; + base.Zh = rOrigin.Z * 0.3048; + + } + /// + /// 截面宽度 + /// + private Parameter m_b; + /// + /// 截面高度 + /// + private Parameter m_h; + /// + /// 关联的柱子 + /// + private FamilyInstance self; + /// + /// 柱高 + /// + public double L => self.GetSweptProfile().GetDrivingCurve().Length * 304.8; + /// + /// 柱截面边长/mm + /// + public string SectionB => m_b.AsValueString(); + /// + /// 柱截面边长/mm + /// + public string SectionH => m_h.AsValueString(); + } +} diff --git a/CDMUtil/ToCDM/CDMComponent.cs b/CDMUtil/ToCDM/CDMComponent.cs new file mode 100644 index 0000000..8e130e2 --- /dev/null +++ b/CDMUtil/ToCDM/CDMComponent.cs @@ -0,0 +1,150 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMComponent + { + /// + /// 构件名 + /// + public string Name + { + get + { + switch (CDMTypeId) + { + case HcdmType.CDMWall: + return "墙"; + case HcdmType.CDMBeam: + return "梁"; + case HcdmType.CDMFloor: + return "板"; + case HcdmType.CDMColumn: + return "柱"; + case HcdmType.CDMStair: + return "楼梯"; + default: + return "INVAIL"; + } + } + } + /// + /// 阶段 + /// + public string Phase { get; set; } + /// + /// 交付日期 + /// + public string DateOfDelivery { get; set; } + /// + /// 负责人姓名 + /// + public string NameOfLeader { get; set; } + /// + /// 负责人身份证 + /// + public string IdOfLeader { get; set; } + /// + /// 构件所属楼层编码 + /// + public string LevelCode; + /// + /// 各楼层中的构件编码001~... + /// + public string LevelComponentCode { get; set; } + /// + /// 定位点X坐标 + /// + public double Xl { get; set; } + /// + /// 定位点Y坐标 + /// + public double Yw { get; set; } + /// + /// 定位点Z坐标 + /// + public double Zh { get; set; } + /// + /// 方向角(逆时针为正) + /// + public double DegreesWithXAxis { get; set; } + /// + /// 方向角(弧度) + /// + public double RadiansWithXAxis => Math.PI / 180 * DegreesWithXAxis; + /// + /// 类别编码 + /// + public string CategoryCode; + /// + /// 族类型Id + /// + public ElementId SymbolId { get; set; } + /// + /// Revit构件Id + /// + public ElementId EleId { get; set; } + /// + /// 标高Id + /// + public ElementId LevelId { get; set; } + /// + /// 基点 + /// + public XYZ BasePoint { get; set; } + /// + /// 类型ID + /// + /// + public HcdmType CDMTypeId { get; set; } + /// + /// 根据数据模型类型返回编码 + /// + public string HcdmClass + { + get + { + switch (CDMTypeId) + { + case HcdmType.CDMWall: + return "A21005"; + case HcdmType.CDMBeam: + return "A21002"; + case HcdmType.CDMFloor: + return "A21003"; + case HcdmType.CDMColumn: + return "A21001"; + case HcdmType.CDMStair: + return "A21004"; + default: + return "INVAIL"; + } + } + } + /// + /// HcdmNumber编码 + /// + public string HcdmNumber => string.Format("{0}-{1}-{2}", CategoryCode, LevelCode, LevelComponentCode); + /// + /// 获取参数值 + /// + /// 族实例 + /// 参数名 + /// + public Parameter GetPara(FamilyInstance instance, string paraname) => instance.Symbol.GetParameters(paraname).FirstOrDefault(); + + } + enum HcdmType + { + CDMWall = 0, + CDMBeam = 1, + CDMFloor = 2, + CDMColumn = 3, + CDMStair = 4 + } +} diff --git a/CDMUtil/ToCDM/CDMFloor.cs b/CDMUtil/ToCDM/CDMFloor.cs new file mode 100644 index 0000000..ed0ffcb --- /dev/null +++ b/CDMUtil/ToCDM/CDMFloor.cs @@ -0,0 +1,62 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMFloor : CDMComponent + { + public CDMFloor(Document doc, Floor floor, View3D v3d) + { + self = floor; + + base.SymbolId = floor.FloorType.Id; + base.LevelId = floor.LevelId; + base.EleId = floor.Id; + + //base.Name = floor.FloorType.FamilyName + "@" + floor.Name; + base.CDMTypeId = HcdmType.CDMFloor; + + max = floor.get_BoundingBox(v3d).Max; + min = floor.get_BoundingBox(v3d).Min; + base.Xl = min.X * 0.3048; + base.Yw = (max.Y + min.Y) / 2 * 0.3048; + base.Zh = Convert.ToDouble(floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_TOP).AsValueString()) / 1000; + + CDMopenings = GetCDMOpenings(doc, v3d); + } + private List GetCDMOpenings(Document doc, View3D view3D) + { + var openingcol = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_FloorOpening).OfClass(typeof(Opening)).Cast(); + var openings = from open in openingcol + where open.Host.Id == self.Id + select open; + var CDMOpenings = new List(); + foreach (var opening in openings) + { + CDMOpening cdmopening = new CDMOpening(opening, view3D); + CDMOpenings.Add(cdmopening); + } + return CDMOpenings; + } + private XYZ max; + private XYZ min; + private Floor self; + /// + /// 板长 + /// + public double L => (max.X - min.X) * 304.8; + /// + /// 板宽 + /// + public double W => (max.Y - min.Y) * 304.8; + /// + /// 板厚 + /// + public double T => Convert.ToDouble(self.FloorType.get_Parameter(BuiltInParameter.FLOOR_ATTR_DEFAULT_THICKNESS_PARAM).AsValueString()); + public List CDMopenings { get; set; } + } +} diff --git a/CDMUtil/ToCDM/CDMOpening.cs b/CDMUtil/ToCDM/CDMOpening.cs new file mode 100644 index 0000000..f4bf309 --- /dev/null +++ b/CDMUtil/ToCDM/CDMOpening.cs @@ -0,0 +1,33 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMOpening : CDMComponent + { + public CDMOpening(Opening Opening, View3D view3D) + { + self = Opening; + + var boundingBox = Opening.get_BoundingBox(view3D); + Length = (boundingBox.Max.X - boundingBox.Min.X) * 304.8; + Width = (boundingBox.Max.Y - boundingBox.Min.Y) * 304.8; + //Xl = boundingBox.Min.X * 304.8 / 1000; + //Yw = boundingBox.Min.Y * 304.8 / 1000; + //Zh = boundingBox.Min.Z * 304.8 / 1000; + + Xl = boundingBox.Min.X * 304.8 / 1000; + Yw = boundingBox.Min.Y * 304.8 / 1000 + Width / 1000 / 2; + Zh = boundingBox.Min.Z * 304.8 / 1000; + + } + public double Length { get; private set; } + public double Width { get; private set; } + + public Opening self; + } +} diff --git a/CDMUtil/ToCDM/CDMStairs.cs b/CDMUtil/ToCDM/CDMStairs.cs new file mode 100644 index 0000000..5c8de94 --- /dev/null +++ b/CDMUtil/ToCDM/CDMStairs.cs @@ -0,0 +1,277 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.DB.Architecture; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMStairs : CDMComponent + { + public CDMStairs(Document doc, View3D view3D, Stairs stairs) + { + self = stairs; + + base.SymbolId = stairs.GetTypeId(); + base.EleId = stairs.Id; + base.LevelId = stairs.get_Parameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM).AsElementId(); + //base.Name = stairsType.Name + "@" + stairs.Name; + base.CDMTypeId = HcdmType.CDMStair; + + + var stairsType = doc.GetElement(stairs.GetTypeId()) as StairsType; + + + var stairsLandingType = doc.GetElement(stairsType.LandingType) as StairsLandingType; + + StairsLanding stairsLanding = doc.GetElement(stairs.GetStairsLandings().FirstOrDefault()) as StairsLanding; + //var curve = stairsLanding.GetStairsPath(); + var bounding = stairsLanding.get_BoundingBox(view3D); + XYZ origin = (bounding.Max + bounding.Min) / 2 - new XYZ((bounding.Max.X - bounding.Min.X) / 2, 0, 0); + Landing = new CDMStairsLanding() + { + Xl = origin.X * 304.8 / 1000, + Yw = origin.Y * 304.8 / 1000, + Zh = origin.Z * 304.8 / 1000, + Thickness = stairsLandingType.Thickness * 304.8, + Width = (bounding.Max.Y - bounding.Min.Y) * 304.8, + Length = (bounding.Max.X - bounding.Min.X) * 304.8 + }; + + + StairsRunType runType = doc.GetElement(stairsType.RunType) as StairsRunType; + List StairsRunsIds = stairs.GetStairsRuns().ToList(); + Runs = new List(); + foreach (ElementId stairsRunId in StairsRunsIds) + { + var stairsRun = doc.GetElement(stairsRunId) as StairsRun; + var l = stairsRun.GetStairsPath().FirstOrDefault() as Line; + + var radian = l.Direction.AngleTo(new XYZ(1, 0, 0)); + var degrees = radian * 180 / Math.PI; + if (Math.Round(l.Direction.Y, 2, MidpointRounding.AwayFromZero) < 0) + { + degrees += 180; + } + CDMStairsRun CDMStairsRun = new CDMStairsRun() + { + Xl = l.Origin.X * 304.8 / 1000, + Yw = l.Origin.Y * 304.8 / 1000, + Zh = (l.Origin.Z + stairsRun.BaseElevation) * 304.8 / 1000, + DegreesWithXAxis = degrees, + Thickness = runType.StructuralDepth * 304.8, + Width = stairsRun.ActualRunWidth * 304.8, + Height = stairsRun.Height * 304.8, + Length = stairsRun.ActualTreadsNumber * stairs.ActualTreadDepth * 304.8, + NumberOfRisers = stairsRun.ActualRisersNumber + }; + Runs.Add(CDMStairsRun); + } + + //ThicknessOfLanding = Convert.ToDouble(doc.GetElement(stairsType.LandingType).get_Parameter(BuiltInParameter.STAIRS_LANDINGTYPE_THICKNESS).AsValueString()); + + //ThicknessOfLanding = stairsLanding.Thickness; + //var bounding = stairsLanding.get_BoundingBox(view3D); + //LengthOfLanding = bounding.Max.X - bounding.Min.X; + //WidthOfLanding = bounding.Max.Y - bounding.Min.Y; + //bounding.Max.X + + // ElevationOfLanding = stairsLanding.BaseElevation; + + ////var stairsRun = doc.GetElement(stair.GetStairsRuns().FirstOrDefault()) as StairsRun; + //ThicknessOfStairRun = Convert.ToDouble(doc.GetElement(stairsType.RunType).get_Parameter(BuiltInParameter.STAIRS_RUNTYPE_STRUCTURAL_DEPTH).AsValueString()); + + + + + } + public List Runs; + + public CDMStairsLanding Landing; + /// + /// 楼梯信息 + /// + /// + /// + private Stairs GetStairInfo(Document document) + { + Stairs stairs = null; + + FilteredElementCollector collector = new FilteredElementCollector(document); + ICollection stairsIds = collector.WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Stairs).ToElementIds(); + foreach (ElementId stairId in stairsIds) + { + if (Stairs.IsByComponent(document, stairId) == true) + { + stairs = document.GetElement(stairId) as Stairs; + + // Format the information + String info = "\nNumber of stories: " + stairs.NumberOfStories; + info += "\nHeight of stairs: " + stairs.Height; + info += "\nNumber of treads: " + stairs.ActualTreadsNumber; + info += "\nTread depth: " + stairs.ActualTreadDepth; + + } + } + + return stairs; + } + /// + /// 楼梯类型 + /// + /// + private void GetStairsType(Stairs stairs) + { + StairsType stairsType = stairs.Document.GetElement(stairs.GetTypeId()) as StairsType; + + // Format stairs type info for display + string info = "Stairs Type: " + stairsType.Name; + info += "\nLeft Lateral Offset: " + stairsType.LeftLateralOffset; + info += "\nRight Lateral Offset: " + stairsType.RightLateralOffset; + info += "\nMax Riser Height: " + stairsType.MaxRiserHeight; + info += "\nMin Run Width: " + stairsType.MinRunWidth; + } + /// + /// 添加梯段 + /// + /// + private void AddStartandEndRisers(Stairs stairs) + { + ICollection runIds = stairs.GetStairsRuns(); + + foreach (ElementId runId in runIds) + { + StairsRun run = stairs.Document.GetElement(runId) as StairsRun; + if (null != run) + { + run.BeginsWithRiser = true; + run.EndsWithRiser = true; + } + } + } + /// + /// 梯段类型 + /// + /// + private void GetRunType(Stairs stairs) + { + ICollection runIds = stairs.GetStairsRuns(); + + ElementId firstRunId = runIds.First(); + + StairsRun firstRun = stairs.Document.GetElement(firstRunId) as StairsRun; + if (null != firstRun) + { + StairsRunType runType = stairs.Document.GetElement(firstRun.GetTypeId()) as StairsRunType; + // Format landing type info for display + string info = "Stairs Run Type: " + runType.Name; + info += "\nRiser Thickness: " + runType.RiserThickness; + info += "\nTread Thickness: " + runType.TreadThickness; + } + } + /// + /// 休息平台 + /// + /// + private void GetStairLandings(Stairs stairs) + { + ICollection landingIds = stairs.GetStairsLandings(); + string info = "Number of landings: " + landingIds.Count; + + int landingIndex = 0; + foreach (ElementId landingId in landingIds) + { + landingIndex++; + StairsLanding landing = stairs.Document.GetElement(landingId) as StairsLanding; + if (null != landing) + { + info += "\nThickness of Landing " + landingIndex + ": " + landing.Thickness; + } + } + } + /// + /// 楼梯支撑 + /// + /// + private void GetStairSupports(Stairs stairs) + { + ICollection supportIds = stairs.GetStairsSupports(); + string info = "Number of supports: " + supportIds.Count; + + int supportIndex = 0; + foreach (ElementId supportId in supportIds) + { + supportIndex++; + Element support = stairs.Document.GetElement(supportId); + if (null != support) + { + info += "\nName of support " + supportIndex + ": " + support.Name; + } + } + } + + private Stairs self; + /// + /// 底部标高 + /// + public double BaseElevation => self.BaseElevation * 304.8; + + + } + class CDMStairsRun : CDMComponent + { + /// + /// 踢面数 + /// + public int NumberOfRisers; + + /// + /// 梯段宽度 + /// + public double Width { get; set; } + + public double Length { get; set; } + /// + /// 楼梯高度 + /// + public double Height; + + /// + /// 梯段厚度 + /// + public double Thickness { get; set; } + + } + class CDMStairsLanding : CDMComponent + { + + public CDMStairsLanding() + { + + + //Xl; + //Yw; + //Zh; + } + /// + /// 平台板厚度 + /// + public double Thickness { get; set; } + /// + /// 平台板长度 + /// + public double Length { get; set; } + /// + /// 平台板宽度 + /// + public double Width { get; set; } + /// + /// 平台高程 + /// + public double Elevation { get; set; } + + } +} diff --git a/CDMUtil/ToCDM/CDMWall.cs b/CDMUtil/ToCDM/CDMWall.cs new file mode 100644 index 0000000..8fc30fc --- /dev/null +++ b/CDMUtil/ToCDM/CDMWall.cs @@ -0,0 +1,43 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.CDMComponent +{ + class CDMWall : CDMComponent + { + + public string BaseElev + { + get + { + return BaseLevel.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsValueString(); + } + } + + + public string TopElev + { + get + { + double result = Convert.ToDouble(BaseElev) + Convert.ToDouble(self.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsValueString()); + return result.ToString(); + } + } + + + public string Thickness { get; set; } + + public string StrExtendPoint => string.Format("({0},{1})", ExtendPoint.X * 304.8, ExtendPoint.Y * 304.8); + + public Wall self; + + public Level BaseLevel { get; set; } + public XYZ ExtendPoint { get; set; } + public List Holes { get; set; } + + } +} diff --git a/CDMUtil/ToRevit/RevitBeam.cs b/CDMUtil/ToRevit/RevitBeam.cs new file mode 100644 index 0000000..b581e6c --- /dev/null +++ b/CDMUtil/ToRevit/RevitBeam.cs @@ -0,0 +1,66 @@ +using Autodesk.Revit.DB; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitBeam : RevitComponent + { + public RevitBeam(string path) + { + using (ExcelPackage package = new ExcelPackage(new FileStream(path, FileMode.Open))) + { + + ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + //ExcelWorksheet sheet = package.Workbook.Worksheets["基本构件"]; + + this.Name = sheet.Cells["G2"].Value.ToString(); + + this.Comment = sheet.Cells["G4"].Value.ToString(); + + base.Xl = Convert.ToDouble(sheet.Cells["H14"].Value); + base.Yw = Convert.ToDouble(sheet.Cells["H15"].Value); + base.Zh = Convert.ToDouble(sheet.Cells["H16"].Value); + base.DegreesWithXAxis = Convert.ToDouble(sheet.Cells["H17"].Value); + + this.L = Convert.ToDouble(sheet.Cells["H18"].Value); + this.SectionB = Convert.ToDouble(sheet.Cells["H19"].Value); + this.SectionH = Convert.ToDouble(sheet.Cells["H20"].Value); + + + } + } + /// + /// Revit中的定位点 + /// + public XYZ rOrigin => new XYZ(base.Xl, base.Yw, base.Zh + SectionH / 2 / 1000) / 304.8 * 1000; + /// + /// 方向 + /// + public XYZ rDirection => new XYZ(Math.Cos(Radians), Math.Sin(Radians), 0); + /// + /// 终点 + /// + public XYZ rEndPoint => rOrigin + rDirection * L / 304.8; + + public double Radians => Math.PI / 180 * DegreesWithXAxis; + /// + /// 梁长 + /// + public double L { get; set; } + /// + /// 截面梁宽 + /// + public double SectionB { get; set; } + /// + /// 截面梁高 + /// + public double SectionH { get; set; } + + } +} diff --git a/CDMUtil/ToRevit/RevitColumn.cs b/CDMUtil/ToRevit/RevitColumn.cs new file mode 100644 index 0000000..3ec0dd0 --- /dev/null +++ b/CDMUtil/ToRevit/RevitColumn.cs @@ -0,0 +1,62 @@ +using Autodesk.Revit.DB; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitColumn : RevitComponent + { + //公制单位 + public RevitColumn(string path) + { + using (ExcelPackage package = new ExcelPackage(new FileStream(path, FileMode.Open))) + { + + ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + //ExcelWorksheet sheet = package.Workbook.Worksheets["基本构件"]; + + this.Name = sheet.Cells["G2"].Value.ToString(); + + this.Comment = sheet.Cells["G4"].Value.ToString(); + + base.Xl = Convert.ToDouble(sheet.Cells["H14"].Value); + base.Yw = Convert.ToDouble(sheet.Cells["H15"].Value); + base.Zh = Convert.ToDouble(sheet.Cells["H16"].Value); + base.DegreesWithXAxis = Convert.ToDouble(sheet.Cells["H17"].Value); + + this.SectionB = Convert.ToDouble(sheet.Cells["H18"].Value); + this.SectionH = Convert.ToDouble(sheet.Cells["H19"].Value); + this.L = Convert.ToDouble(sheet.Cells["H20"].Value); + + } + } + /// + /// 柱高 + /// + public double L { get; private set; } + /// + /// 柱截面宽 + /// + public double SectionB { get; private set; } + /// + /// 柱截面高 + /// + public double SectionH { get; private set; } + /// + /// CDM定位点 + /// + public XYZ cOrigion => new XYZ(Xl, Yw, Zh); + + public double BaseOffest => Zh * 1000; + public double TopOffest => Zh * 1000 + L; + /// + /// revit中的定位点(英制) + /// + public XYZ rOrigin => (cOrigion + new XYZ(SectionB / 2 / 1000, 0, 0)) * 1000 / 304.8; + } +} diff --git a/CDMUtil/ToRevit/RevitComponent.cs b/CDMUtil/ToRevit/RevitComponent.cs new file mode 100644 index 0000000..9e9d17d --- /dev/null +++ b/CDMUtil/ToRevit/RevitComponent.cs @@ -0,0 +1,32 @@ +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitComponent + { + /// + /// 构件类型名称 + /// + public string Name { get; set; } + /// + /// 注释 + /// + public string Comment { get; set; } + /// + /// 方向角 + /// + public double DegreesWithXAxis { get; set; } + + public double Xl { get; set; } + + public double Yw { get; set; } + + public double Zh { get; set; } + } +} diff --git a/CDMUtil/ToRevit/RevitFloor.cs b/CDMUtil/ToRevit/RevitFloor.cs new file mode 100644 index 0000000..dfd4248 --- /dev/null +++ b/CDMUtil/ToRevit/RevitFloor.cs @@ -0,0 +1,76 @@ +using Autodesk.Revit.DB; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitFloor : RevitComponent + { + public RevitFloor(string path) + { + using (ExcelPackage package = new ExcelPackage(new FileStream(path, FileMode.Open))) + { + + //ExcelWorksheet sheet = package.Workbook.Worksheets["基本构件"]; + ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + + this.Name = sheet.Cells["G2"].Value.ToString(); + + this.Comment = sheet.Cells["G4"].Value.ToString(); + + base.Xl = Convert.ToDouble(sheet.Cells["H14"].Value); + base.Yw = Convert.ToDouble(sheet.Cells["H15"].Value); + base.Zh = Convert.ToDouble(sheet.Cells["H16"].Value); + base.DegreesWithXAxis = Convert.ToDouble(sheet.Cells["H17"].Value); + + this.Length = Convert.ToDouble(sheet.Cells["H18"].Value); + this.Width = Convert.ToDouble(sheet.Cells["H19"].Value); + this.Thickness = Convert.ToDouble(sheet.Cells["H20"].Value); + + ExcelWorksheet sheet1 = package.Workbook.Worksheets[2]; + //ExcelWorksheet sheet1 = package.Workbook.Worksheets["方形洞口"]; + Openings = new List() + { + new RevitOpening() + { + Xl=Convert.ToDouble(sheet1.Cells["H7"].Value), + Yw=Convert.ToDouble(sheet1.Cells["H8"].Value), + Zh=Zh, + Length=Convert.ToDouble(sheet1.Cells["H9"].Value), + Width=Convert.ToDouble(sheet1.Cells["H10"].Value) + }, + new RevitOpening() + { + Xl=Convert.ToDouble(sheet1.Cells["H11"].Value), + Yw=Convert.ToDouble(sheet1.Cells["H12"].Value), + Zh=Zh, + Length=Convert.ToDouble(sheet1.Cells["H13"].Value), + Width=Convert.ToDouble(sheet1.Cells["H14"].Value) + } + }; + } + } + /// + /// 板厚 + /// + public double Thickness { get; internal set; } + public XYZ cOrigin => new XYZ(Xl, Yw, Zh); + public XYZ rOrigin => new XYZ(Xl, Yw, Zh) * 1000 / 304.8; + public double Offest => Zh * 1000; + /// + /// 板长 + /// + public double Length { get; set; } + /// + /// 板宽 + /// + public double Width { get; set; } + + public List Openings { get; set; } + } +} diff --git a/CDMUtil/ToRevit/RevitOpening.cs b/CDMUtil/ToRevit/RevitOpening.cs new file mode 100644 index 0000000..5a37f85 --- /dev/null +++ b/CDMUtil/ToRevit/RevitOpening.cs @@ -0,0 +1,21 @@ +using Autodesk.Revit.DB; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitOpening : RevitComponent + { + public double Length { get; set; } + public double Width { get; set; } + + public XYZ cOrigin => new XYZ(Xl, Yw, Zh); + + public XYZ rOrigin => new XYZ(Xl, Yw, Zh) * 1000 / 304.8; + } +} diff --git a/CDMUtil/ToRevit/RevitStairs.cs b/CDMUtil/ToRevit/RevitStairs.cs new file mode 100644 index 0000000..1fe19d1 --- /dev/null +++ b/CDMUtil/ToRevit/RevitStairs.cs @@ -0,0 +1,215 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.DB.Architecture; +using CDM.Interop.Revit.RevitCompoent; +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitStairs : RevitComponent + { + public RevitStairs(string path) + { + using (ExcelPackage package = new ExcelPackage(new FileStream(path, FileMode.Open))) + { + + ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + //ExcelWorksheet sheet = package.Workbook.Worksheets["基本构件"]; + + this.Name = sheet.Cells["G2"].Value.ToString(); + + this.Comment = sheet.Cells["G4"].Value.ToString(); + + + + Runs = new List(); + var run1 = new RevitStairsRun() + { + Xl = Convert.ToDouble(sheet.Cells["H14"].Value), + Yw = Convert.ToDouble(sheet.Cells["H15"].Value), + Zh = Convert.ToDouble(sheet.Cells["H16"].Value), + DegreesWithXAxis = Convert.ToDouble(sheet.Cells["H17"].Value), + Length = Convert.ToDouble(sheet.Cells["H18"].Value), + Width = Convert.ToDouble(sheet.Cells["H19"].Value), + Height = Convert.ToDouble(sheet.Cells["H20"].Value), + Thickness = Convert.ToDouble(sheet.Cells["H21"].Value), + NumberOfRisers = Convert.ToInt32(sheet.Cells["H22"].Value) + }; + var run2 = new RevitStairsRun() + { + Xl = Convert.ToDouble(sheet.Cells["H29"].Value), + Yw = Convert.ToDouble(sheet.Cells["H30"].Value), + Zh = Convert.ToDouble(sheet.Cells["H31"].Value), + DegreesWithXAxis = Convert.ToDouble(sheet.Cells["H32"].Value), + Length = Convert.ToDouble(sheet.Cells["H33"].Value), + Width = Convert.ToDouble(sheet.Cells["H34"].Value), + Height = Convert.ToDouble(sheet.Cells["H35"].Value), + Thickness = Convert.ToDouble(sheet.Cells["H36"].Value), + NumberOfRisers = Convert.ToInt32(sheet.Cells["H37"].Value), + }; + + Runs.Add(run1); + Runs.Add(run2); + + ThreadDepth = run1.Length / (run1.NumberOfRisers - 1) / 304.8; + Landing = new RevitStairsLanding() + { + Xl = Convert.ToDouble(sheet.Cells["H23"].Value), + Yw = Convert.ToDouble(sheet.Cells["H24"].Value), + Zh = Convert.ToDouble(sheet.Cells["H25"].Value), + Length = Convert.ToDouble(sheet.Cells["H26"].Value), + Width = Convert.ToDouble(sheet.Cells["H27"].Value), + Thickness = Convert.ToDouble(sheet.Cells["H28"].Value), + }; + + if (run1.Zh < run2.Zh) + { + Landing.RelativeElevation = run1.Height; + run1.RelativeBaseElevation = 0; + run1.RelativeTopELevation = run1.Height; + run2.RelativeBaseElevation = Landing.RelativeElevation; + run2.RelativeTopELevation = Landing.RelativeElevation + run2.Height; + } + else + { + Landing.RelativeElevation = run2.Height; + run2.RelativeBaseElevation = 0; + run2.RelativeTopELevation = run2.Height; + run1.RelativeBaseElevation = Landing.RelativeElevation; + run1.RelativeTopELevation = Landing.RelativeElevation + run1.Height; + } + TopElevation = getTopElevation(run1, run2); + BaseElevation = getBaseElevationn(run1, run2); + } + } + public List Runs; + public RevitStairsLanding Landing; + public double TopElevation; + public double BaseElevation; + public int GetNumberOfRisers(List runs) + { + int num = 0; + foreach (var run in runs) + { + num += run.NumberOfRisers; + } + return num; + } + /// + /// 顶部偏移 + /// + private double getTopElevation(RevitStairsRun run1, RevitStairsRun run2) + { + if (run1.Zh > run2.Zh) + { + return (run1.Zh * 1000 + run1.Height) / 304.8; + } + else + { + return (run2.Zh * 1000 + run2.Height) / 304.8; + } + } + /// + /// 底部偏移 + /// + private double getBaseElevationn(RevitStairsRun run1, RevitStairsRun run2) + { + if (run1.Zh > run2.Zh) + { + return run2.Zh * 1000 / 304.8; + } + else + { + return run1.Zh * 1000 / 304.8; + } + } + public double ThreadDepth { get; private set; } + } + class RevitStairsRun : RevitComponent + { + /// + /// Revit中的定位点 + /// + public XYZ rOrigin => new XYZ(Xl, Yw, RelativeBaseElevation / 1000) * 1000 / 304.8; + + public double Radians => Math.PI / 180 * DegreesWithXAxis; + public XYZ rDirection => new XYZ(Math.Cos(Radians), Math.Sin(Radians), 0); + + public XYZ rEndPoint => rOrigin + rDirection * Length / 304.8; + + /// + /// 踢面数 + /// + public int NumberOfRisers { get; set; } + + /// + /// 梯段宽度 + /// + public double Width { get; set; } + /// + /// 梯段长度 + /// + + public double Length { get; set; } + /// + /// 楼梯高度 + /// + public double Height { get; set; } + + /// + /// 梯段厚度 + /// + public double Thickness { get; set; } + + public Line LocationLine => Line.CreateBound(rOrigin, rEndPoint); + + public double RelativeBaseElevation { get; set; } + + public double RelativeTopELevation { get; set; } + } + class RevitStairsLanding : RevitComponent + { + + /// + /// 平台板厚度 + /// + public double Thickness { get; set; } + /// + /// 平台板长度 + /// + public double Length { get; set; } + /// + /// 平台板宽度 + /// + public double Width { get; set; } + /// + /// 相对基准平台高程 + /// + public double RelativeElevation { get; set; } + + public CurveLoop GetCurves() + { + CurveLoop landingLoop = new CurveLoop(); + XYZ p1 = new XYZ(Xl * 1000, Yw * 1000 - Width / 2, 0) / 304.8; + XYZ p2 = new XYZ(Xl * 1000, Yw * 1000 + Width / 2, 0) / 304.8; + XYZ p3 = new XYZ(Xl * 1000 + Length, Yw * 1000 + Width / 2, 0) / 304.8; + XYZ p4 = new XYZ(Xl * 1000 + Length, Yw * 1000 - Width / 2, 0) / 304.8; + + Line curve_1 = Line.CreateBound(p1, p2); + Line curve_2 = Line.CreateBound(p2, p3); + Line curve_3 = Line.CreateBound(p3, p4); + Line curve_4 = Line.CreateBound(p4, p1); + + landingLoop.Append(curve_1); + landingLoop.Append(curve_2); + landingLoop.Append(curve_3); + landingLoop.Append(curve_4); + return landingLoop; + } + } +} diff --git a/CDMUtil/ToRevit/RevitWall.cs b/CDMUtil/ToRevit/RevitWall.cs new file mode 100644 index 0000000..153b1d2 --- /dev/null +++ b/CDMUtil/ToRevit/RevitWall.cs @@ -0,0 +1,44 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.RevitCompoent +{ + class RevitWall + { + public string StrBaseElev { get; set; } + public string StrTopElev { get; set; } + public string StrBasePoint { get; set; } + public string Thickness { get; set; } + public string StrExtendPoint { get; set; } + + public double Height => Convert.ToDouble(StrTopElev) - Convert.ToDouble(StrBaseElev); + public XYZ BasePoint + { + get + { + char[] separator = { '(', ',', ')' }; + string[] arr = StrBasePoint.Split(separator); + double x = Convert.ToDouble(arr[1]) /304.8; + double y = Convert.ToDouble(arr[2]) /304.8; + //double z = Convert.ToDouble(StrBaseElev) ; + return new XYZ(x, y, 0); + } + } + public XYZ ExtendPoint + { + get + { + char[] separator = { '(', ',', ')' }; + string[] arr = StrExtendPoint.Split(separator); + double x = Convert.ToDouble(arr[1]) / 304.8; + double y = Convert.ToDouble(arr[2]) /304.8; + //double z = Convert.ToDouble(StrTopElev); + return new XYZ(x, y, 0); + } + } + } +} diff --git a/CDMUtil/UIRibbon.cs b/CDMUtil/UIRibbon.cs new file mode 100644 index 0000000..8342690 --- /dev/null +++ b/CDMUtil/UIRibbon.cs @@ -0,0 +1,36 @@ +using Autodesk.Revit.UI; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit +{ + class UIRibbon : IExternalApplication + { + // 程序集路径 + static string AddInPath = typeof(UIRibbon).Assembly.Location; + // 按钮图标目录 + //static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath); + // uiApplication + //static UIApplication uiApplication = null; + + public Result OnShutdown(UIControlledApplication application) + { + return Result.Succeeded; + } + + public Result OnStartup(UIControlledApplication application) + { + RibbonPanel ribbonPanel = application.CreateRibbonPanel("CDM-Revit交换"); + PushButtonData cdmtorevit = new PushButtonData("导入CDM集", "导入CDM集", AddInPath, "CDM.Interop.Revit.CmdCDMToRevit"); + PushButton cdmtorevitData = ribbonPanel.AddItem(cdmtorevit) as PushButton; + PushButtonData revittocdm = new PushButtonData("导出CDM集", "导出CDM集", AddInPath, "CDM.Interop.Revit.CmdRevitToCDM"); + PushButton revittocdmData = ribbonPanel.AddItem(revittocdm) as PushButton; + + return Result.Succeeded; + } + } +} diff --git a/CDMUtil/Utility/BeamUtil.cs b/CDMUtil/Utility/BeamUtil.cs new file mode 100644 index 0000000..80e5e88 --- /dev/null +++ b/CDMUtil/Utility/BeamUtil.cs @@ -0,0 +1,157 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.DB.Structure; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.CDMComponent; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.Utility +{ + class BeamUtil : Utility + { + public static List GetBeamsCDM(Document doc, IList levels) + { + List cdmBeams = new List(); + var beams = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).OfClass(typeof(FamilyInstance)).ToElements(); + //得到标高+编码 + Dictionary dictLevelId_LevelCodes = GetDictLevelId_LevelCodes(doc); + //梁类型与编码 + Dictionary dicBeams = new Dictionary(); + int num = 1; + for (int i = 0; i < beams.Count; i++) + { + ElementId beamtypeId = beams[i].GetTypeId(); + try + { + + if (num > 9 && num <= 99) + { + dicBeams.Add(beamtypeId, string.Format("0{0}", num)); + } + else if (num > 99) + { + dicBeams.Add(beamtypeId, string.Format("{0}", num)); + } + else + { + dicBeams.Add(beamtypeId, string.Format("00{0}", num)); + } + num += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (FamilyInstance beam in beams) + { + //View3D v = (View3D)uidoc.ActiveView; + //if (v == null) + //{ + // var vi = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).OfClass(typeof(View3D)).ToElements(); + // uidoc.ActiveView = (View3D)vi.FirstOrDefault(); + //} + //直线梁 + XYZ s = ((LocationCurve)beam.Location).Curve.GetEndPoint(0); + XYZ e = ((LocationCurve)beam.Location).Curve.GetEndPoint(1); + //XYZ s = beam.GetSweptProfile().GetDrivingCurve().GetEndPoint(0); + //XYZ e = beam.GetSweptProfile().GetDrivingCurve().GetEndPoint(1); + if (beam.HasSweptProfile() == true) + { + CDMBeam cdmbeam = new CDMBeam(beam); + //通过out,将获取到的值复制给cdm的类型id,out参数必须在函数内初始化值 + dicBeams.TryGetValue(cdmbeam.SymbolId, out cdmbeam.CategoryCode); + dictLevelId_LevelCodes.TryGetValue(cdmbeam.LevelId, out cdmbeam.LevelCode); + cdmBeams.Add(cdmbeam); + } + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicBeams.Count; j++) + { + ElementId id = dicBeams.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from b in cdmBeams + where b.LevelId.Equals(levels[i].Id) && b.SymbolId.Equals(id) + select b; + List CdmBeamsordered = targetcdm.OrderByDescending(p => p.Yw).ThenBy(p => p.Xl).ToList(); + //排序 + //var li = targetcdm.ToList(); + //List li = targetcdm.OrderByDescending(p => p.BasePoint.Y).ThenBy(p => p.BasePoint.X).ToList(); + + for (int k = 0; k < CdmBeamsordered.Count; k++) + { + if (k > 8) + { + if (k > 98) + { + CdmBeamsordered[k].LevelComponentCode = string.Format("{0}", k + 1); + } + else + { + CdmBeamsordered[k].LevelComponentCode = string.Format("0{0}", k + 1); + } + } + else + { + CdmBeamsordered[k].LevelComponentCode = string.Format("00{0}", k + 1); + } + } + + } + } + return cdmBeams; + } + public static void PlaceBeams(Document doc, Family family, List rbeams, Level level) + { + if (rbeams == null || level == null) + { + return; + } + FamilySymbol defaultfamilysymbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol; + FamilySymbol targetBeamSymbol = null; + + using (Transaction trans = new Transaction(doc)) + { + trans.Start("布置梁"); + foreach (var beam in rbeams) + { + //var targetSymbolName = beam.Name.Substring(beam.Name.IndexOf('@') + 1); + var targetSymbolName = beam.SectionB + " x " + beam.SectionH + "mm"; + var symbolIds = family.GetFamilySymbolIds(); + var symbols = from symbolid in symbolIds + where doc.GetElement(symbolid).Name == targetSymbolName + select doc.GetElement(symbolid) as FamilySymbol; + //string symbolname = String.Format("{0}{1}{2}mm", beam.SectionB, "x", beam.SectionH); + if (symbols.Count() == 0) + { + targetBeamSymbol = defaultfamilysymbol.Duplicate(targetSymbolName) as FamilySymbol; + targetBeamSymbol.GetParameters("b").FirstOrDefault().SetValueString(beam.SectionB.ToString()); + targetBeamSymbol.GetParameters("h").FirstOrDefault().SetValueString(beam.SectionH.ToString()); + } + else + { + targetBeamSymbol = symbols.FirstOrDefault(); + } + + Autodesk.Revit.DB.Line line = Autodesk.Revit.DB.Line.CreateBound(beam.rOrigin, beam.rEndPoint); + + if (!targetBeamSymbol.IsActive) + targetBeamSymbol.Activate(); + FamilyInstance fi = doc.Create.NewFamilyInstance(line, targetBeamSymbol, level, StructuralType.Beam); + //原点=2,左=0,中心=1,右=3 + fi.get_Parameter(BuiltInParameter.Y_JUSTIFICATION).Set(2); + fi.get_Parameter(BuiltInParameter.Z_JUSTIFICATION).Set(2); + } + trans.Commit(); + } + } + } +} diff --git a/CDMUtil/Utility/ColumnUtil.cs b/CDMUtil/Utility/ColumnUtil.cs new file mode 100644 index 0000000..cab048b --- /dev/null +++ b/CDMUtil/Utility/ColumnUtil.cs @@ -0,0 +1,140 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.CDMComponent; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.Utility +{ + class ColumnUtil : Utility + { + + public static List GetColumnCDM(Document doc, IList levels) + { + List cdmColumns = new List(); + var columns = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns).OfClass(typeof(FamilyInstance)).ToElements(); + //得到标高+编码 + Dictionary dictLevelId_LevelCodes = GetDictLevelId_LevelCodes(doc); + //柱子类型ID+赋予序号 + Dictionary dictColumnTypeId_TypeCodes = new Dictionary(); + int num = 1; + for (int i = 0; i < columns.Count; i++) + { + ElementId columntypeId = columns[i].GetTypeId(); + try + { + dictColumnTypeId_TypeCodes.Add(columntypeId, string.Format("00{0}", num)); + num += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (FamilyInstance column in columns) + { + //View3D v = (View3D)uidoc.ActiveView; + //if (v == null) + //{ + // var vi = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).OfClass(typeof(View3D)).FirstOrDefault() as View3D; + // uidoc.ActiveView = vi; + //} + CDMColumn cdmcolumn = new CDMColumn(column); + ////通过out,将获取到的值复制给cdm的类型id,out参数必须在函数内初始化值 + dictColumnTypeId_TypeCodes.TryGetValue(cdmcolumn.SymbolId, out cdmcolumn.CategoryCode); + dictLevelId_LevelCodes.TryGetValue(cdmcolumn.LevelId, out cdmcolumn.LevelCode); + cdmColumns.Add(cdmcolumn); + } + + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dictColumnTypeId_TypeCodes.Count; j++) + { + ElementId id = dictColumnTypeId_TypeCodes.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from c in cdmColumns + where c.LevelId.Equals(levels[i].Id) && c.SymbolId.Equals(id) + select c; + List CdmColumnsordered = targetcdm.OrderByDescending(p => p.Yw).ThenBy(p => p.Xl).ToList(); + //排序 + for (int k = 0; k < CdmColumnsordered.Count; k++) + { + if (k > 8) + { + if (k > 98) + { + CdmColumnsordered[k].LevelComponentCode = string.Format("{0}", k + 1); + } + else + { + CdmColumnsordered[k].LevelComponentCode = string.Format("0{0}", k + 1); + } + } + else + { + CdmColumnsordered[k].LevelComponentCode = string.Format("00{0}", k + 1); + } + } + + } + } + return cdmColumns; + } + public static void PlaceColumns(Document doc, Family family, List columns, Level level) + { + + using (Transaction trans = new Transaction(doc, "布置柱")) + { + + trans.Start(); + + //用于复制创建新类型 + FamilySymbol defaultfamilysymbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol; + FamilySymbol targetColumnSymbol = null; + foreach (var column in columns) + { + //var targetSymbolName = column.Name.Substring(column.Name.IndexOf('@') + 1); + var targetSymbolName = column.SectionB + "x" + column.SectionH + " mm"; + var symbolIds = family.GetFamilySymbolIds(); + var symbols = from symbolid in symbolIds + where doc.GetElement(symbolid).Name == targetSymbolName + select doc.GetElement(symbolid) as FamilySymbol; + + //不存在则创建并布置,存在则激活布置 + if (symbols.Count() == 0) + { + targetColumnSymbol = defaultfamilysymbol.Duplicate(targetSymbolName) as FamilySymbol; + targetColumnSymbol.GetParameters("b").FirstOrDefault().SetValueString(column.SectionB.ToString()); + targetColumnSymbol.GetParameters("h").FirstOrDefault().SetValueString(column.SectionH.ToString()); + } + else + { + targetColumnSymbol = symbols.FirstOrDefault(); + } + + + if (!targetColumnSymbol.IsActive) + targetColumnSymbol.Activate();//设为Activate状态 + + FamilyInstance fi = doc.Create.NewFamilyInstance(column.rOrigin, targetColumnSymbol, level, Autodesk.Revit.DB.Structure.StructuralType.Column); + //Parameter p = fi.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM); + //Parameter p1 = fi.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM); + //Parameter p2 = fi.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM); + //Parameter p3 = fi.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM); + fi.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).Set(level.Id); + fi.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).Set(level.Id); + fi.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).Set(column.BaseOffest / 304.8); + fi.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).Set(column.TopOffest / 304.8); + } + trans.Commit(); + } + } + } +} diff --git a/CDMUtil/Utility/FloorUtil.cs b/CDMUtil/Utility/FloorUtil.cs new file mode 100644 index 0000000..3abc6af --- /dev/null +++ b/CDMUtil/Utility/FloorUtil.cs @@ -0,0 +1,175 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.CDMComponent; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CDM.Interop.Revit.Utility +{ + class FloorUtil : Utility + { + public static List GetFloorsCDM(Document doc, IList levels, View3D v3d) + { + List cdmFloors = new List(); + var floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors).OfClass(typeof(Floor)).ToElements(); + //楼板类型及编号 + Dictionary dicFloors = new Dictionary(); + Dictionary dictLevelId_LevelCodes = GetDictLevelId_LevelCodes(doc); + int num = 1; + for (int i = 0; i < floors.Count; i++) + { + ElementId floortypeId = floors[i].GetTypeId(); + try + { + dicFloors.Add(floortypeId, string.Format("00{0}", num)); + num += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (Floor floor in floors) + { + CDMFloor cdmfloor = new CDMFloor(doc, floor, v3d); + + ////通过out,将获取到的值复制给cdm的类型id,out参数必须在函数内初始化值 + dicFloors.TryGetValue(floor.FloorType.Id, out cdmfloor.CategoryCode); + dictLevelId_LevelCodes.TryGetValue(cdmfloor.LevelId, out cdmfloor.LevelCode); + cdmFloors.Add(cdmfloor); + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicFloors.Count; j++) + { + ElementId id = dicFloors.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmFloors + where d.LevelId.Equals(levels[i].Id) && d.SymbolId.Equals(id) + select d; + //排序 + //var li = targetcdm.ToList(); + List li = targetcdm.OrderByDescending(p => p.Yw).ThenBy(p => p.Xl).ToList(); + for (int k = 0; k < li.Count; k++) + { + if (k > 8) + { + if (k > 98) + { + li[k].LevelComponentCode = string.Format("{0}", k + 1); + } + else + { + li[k].LevelComponentCode = string.Format("0{0}", k + 1); + } + } + else + { + li[k].LevelComponentCode = string.Format("00{0}", k + 1); + } + } + } + } + return cdmFloors; + } + private static CurveArray SetBoundary(XYZ rOrigin, double length, double width) + { + XYZ p1 = new XYZ(rOrigin.X, rOrigin.Y - width / 2, 0); + XYZ p2 = new XYZ(rOrigin.X, rOrigin.Y + width / 2, 0); + XYZ p3 = new XYZ(rOrigin.X + length, rOrigin.Y + width / 2, 0); + XYZ p4 = new XYZ(rOrigin.X + length, rOrigin.Y - width / 2, 0); + Autodesk.Revit.DB.Line line1 = Autodesk.Revit.DB.Line.CreateBound(p1, p2); + Autodesk.Revit.DB.Line line2 = Autodesk.Revit.DB.Line.CreateBound(p2, p3); + Autodesk.Revit.DB.Line line3 = Autodesk.Revit.DB.Line.CreateBound(p3, p4); + Autodesk.Revit.DB.Line line4 = Autodesk.Revit.DB.Line.CreateBound(p4, p1); + CurveArray lines = new CurveArray(); + lines.Append(line1); + lines.Append(line2); + lines.Append(line3); + lines.Append(line4); + return lines; + } + public static void PlaceFloors(Document doc, List rfloors, Level level) + { + if (rfloors == null || level == null) + { + return; + } + var fts = new FilteredElementCollector(doc).OfClass(typeof(FloorType)); + + FloorType defft = new FilteredElementCollector(doc).OfClass(typeof(FloorType)).FirstOrDefault() as FloorType; + var floorTypesCol = new FilteredElementCollector(doc).OfClass(typeof(FloorType)); + FloorType targetFloorType = null; + using (Transaction trans = new Transaction(doc, "布置板")) + { + trans.Start(); + foreach (RevitFloor rfloor in rfloors) + { + Floor fl = null; + + //var targetFloorName = rfloor.Name.Substring(rfloor.Name.IndexOf('@') + 1); + var targetFloorName = rfloor.Thickness + "mm"; + var floorTypes = from f in floorTypesCol + where f.Name == targetFloorName + select f as FloorType; + if (floorTypes.Count() == 0) + { + targetFloorType = defft.Duplicate(targetFloorName) as FloorType; + CompoundStructure compound = targetFloorType.GetCompoundStructure(); + compound.SetLayerWidth(0, rfloor.Thickness / 304.8); + targetFloorType.SetCompoundStructure(compound); + } + else + { + targetFloorType = floorTypes.FirstOrDefault(); + } + + var arr = SetBoundary(rfloor.rOrigin, rfloor.Length / 304.8, rfloor.Width / 304.8); + + fl = doc.Create.NewFloor(arr, targetFloorType, level, true); + fl.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(rfloor.Offest / 304.8); + + doc.Regenerate();//设置完偏移量参数刷新 + + CreateOpenings(doc, fl, rfloor.Openings); + } + trans.Commit(); + } + } + public static void CreateOpenings(Document doc, Floor floor, List ropenings) + { + foreach (var opening in ropenings) + { + try + { + XYZ p1 = new XYZ(opening.rOrigin.X, opening.rOrigin.Y - opening.Width / 304.8 / 2, opening.rOrigin.Z); + XYZ p2 = new XYZ(opening.rOrigin.X, opening.rOrigin.Y + opening.Width / 304.8 / 2, opening.rOrigin.Z); + XYZ p3 = new XYZ(opening.rOrigin.X + opening.Length / 304.8, opening.rOrigin.Y + opening.Width / 304.8 / 2, opening.rOrigin.Z); + XYZ p4 = new XYZ(opening.rOrigin.X + opening.Length / 304.8, opening.rOrigin.Y - opening.Width / 304.8 / 2, opening.rOrigin.Z); + CurveArray curves = new CurveArray(); + + Line l1 = Line.CreateBound(p1, p2); + Line l2 = Line.CreateBound(p2, p3); + Line l3 = Line.CreateBound(p3, p4); + Line l4 = Line.CreateBound(p4, p1); + + curves.Append(l1); + curves.Append(l2); + curves.Append(l3); + curves.Append(l4); + + doc.Create.NewOpening(floor, curves, true); + } + catch (Exception) + { + continue; + } + } + } + } +} diff --git a/CDMUtil/Utility/StairsUtil.cs b/CDMUtil/Utility/StairsUtil.cs new file mode 100644 index 0000000..dafd0f9 --- /dev/null +++ b/CDMUtil/Utility/StairsUtil.cs @@ -0,0 +1,319 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.DB.Architecture; +using CDM.Interop.Revit.CDMComponent; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CDM.Interop.Revit.Utility +{ + class StairsUtil : Utility + { + public static List GetStairsCDM(Document doc, IList levels, View3D v3d) + { + List cdmStairs = new List(); + var stairsLi = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Stairs).OfClass(typeof(Stairs)).ToElements(); + //楼板类型及编号 + Dictionary dicStairs = new Dictionary(); + Dictionary dictLevelId_LevelCodes = GetDictLevelId_LevelCodes(doc); + int num = 1; + for (int i = 0; i < stairsLi.Count; i++) + { + ElementId stairstypeId = stairsLi[i].GetTypeId(); + try + { + dicStairs.Add(stairstypeId, string.Format("00{0}", num)); + num += 1; + } + catch (Exception) + { + continue; + } + } + + foreach (Stairs stair in stairsLi) + { + CDMStairs cdmStair = new CDMStairs(doc, v3d, stair); + + ////通过out,将获取到的值复制给cdm的类型id,out参数必须在函数内初始化值 + dicStairs.TryGetValue(stair.GetTypeId(), out cdmStair.CategoryCode); + dictLevelId_LevelCodes.TryGetValue(cdmStair.LevelId, out cdmStair.LevelCode); + cdmStairs.Add(cdmStair); + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicStairs.Count; j++) + { + ElementId id = dicStairs.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmStairs + where d.LevelId.Equals(levels[i].Id) && d.SymbolId.Equals(id) + select d; + //排序 + //var li = targetcdm.ToList(); + List li = targetcdm.OrderByDescending(p => p.Yw).ThenBy(p => p.Xl).ToList(); + for (int k = 0; k < li.Count; k++) + { + if (k > 8) + { + if (k > 98) + { + li[k].LevelComponentCode = string.Format("{0}", k + 1); + } + else + { + li[k].LevelComponentCode = string.Format("0{0}", k + 1); + } + } + else + { + li[k].LevelComponentCode = string.Format("00{0}", k + 1); + } + } + } + } + return cdmStairs; + } + + public static void PlaceStairs(Document doc, List rstairs, Level level) + { + FilteredElementCollector levelcol = new FilteredElementCollector(doc).OfClass(typeof(Level)); + Level leveltop = null; + foreach (Level l in levelcol.Cast().Where(l => l.ProjectElevation > 0)) + { + if (l.ProjectElevation > 0) + { + leveltop = l; + break; + } + } + if (rstairs == null || level == null) + { + return; + } + //CreateSampleStairs(doc, level, leveltop); + + CreateStairs(doc, rstairs, level, leveltop); + } + private static void CreateStairs(Document doc, List rstairses, Level levelBottom, Level levelTop) + { + using (TransactionGroup transG = new TransactionGroup(doc, "创建楼梯")) + { + transG.Start(); + foreach (var rstairs in rstairses) + { + using (StairsEditScope newStairsScope = new StairsEditScope(doc, "新建楼梯")) + { + ElementId stairsId = newStairsScope.Start(levelBottom.Id, levelTop.Id); + var stairs = doc.GetElement(stairsId) as Stairs; + var typeid = doc.GetElement(stairsId).GetTypeId(); + var stairsType = doc.GetElement(typeid) as StairsType; + using (Transaction stairsTrans = new Transaction(doc, "添加梯段和平台到楼梯")) + { + stairsTrans.Start(); + stairs.get_Parameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM).Set(levelBottom.Id); + stairs.get_Parameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM).Set(levelBottom.Id); + stairs.get_Parameter(BuiltInParameter.STAIRS_BASE_OFFSET).Set(rstairs.BaseElevation); + stairs.get_Parameter(BuiltInParameter.STAIRS_TOP_OFFSET).Set(rstairs.TopElevation); + if (stairsType.get_Parameter(BuiltInParameter.STAIRS_ATTR_MINIMUM_TREAD_DEPTH).AsDouble() > rstairs.ThreadDepth) + { + stairsType.get_Parameter(BuiltInParameter.STAIRS_ATTR_MINIMUM_TREAD_DEPTH).Set(rstairs.ThreadDepth); + } + + stairs.get_Parameter(BuiltInParameter.STAIRS_ACTUAL_TREAD_DEPTH).Set(rstairs.ThreadDepth); + stairs.get_Parameter(BuiltInParameter.STAIRS_DESIRED_NUMBER_OF_RISERS).Set(rstairs.GetNumberOfRisers(rstairs.Runs)); + doc.GetElement(stairsType.RunType).get_Parameter(BuiltInParameter.STAIRS_RUNTYPE_STRUCTURAL_DEPTH).Set(rstairs.Runs[0].Thickness / 304.8); + doc.GetElement(stairsType.LandingType).get_Parameter(BuiltInParameter.STAIRS_LANDINGTYPE_THICKNESS).Set(rstairs.Landing.Thickness / 304.8); + #region 草图楼梯 + StairsRun run1 = CreateStairsSketchedRun(doc, rstairs.Runs[0], rstairs.Runs[0].RelativeBaseElevation / 304.8, stairsId); + //run1.BaseElevation = rstairs.Runs[0].BaseElevation; + //run1.TopElevation = rstairs.Runs[0].TopELevation; + + + StairsRun run2 = CreateStairsSketchedRun(doc, rstairs.Runs[1], rstairs.Runs[1].RelativeBaseElevation / 304.8, stairsId); + //run2.BaseElevation = rstairs.Runs[1].BaseElevation; + //run2.TopElevation = rstairs.Runs[1].TopELevation; + StairsLanding newLanding = StairsLanding.CreateSketchedLanding(doc, stairsId, rstairs.Landing.GetCurves(), rstairs.Landing.RelativeElevation / 304.8); + + //newLanding.BaseElevation = rstairs.Landing.Elevation / 304.8; + #endregion + + #region 备用 + //StairsRun newRun1 = StairsRun.CreateStraightRun(doc, stairsId, rstairs.Runs[0].LocationLine, StairsRunJustification.Center); + //newRun1.ActualRunWidth = rstairs.Runs[0].Width / 304.8; + //newRun1.TopElevation = rstairs.Runs[0].RelativeTopELevation / 304.8; + //newRun1.BaseElevation = rstairs.Runs[0].RelativeBaseElevation / 304.8; + + + //StairsRun newRun2 = StairsRun.CreateStraightRun(doc, stairsId, rstairs.Runs[1].LocationLine, StairsRunJustification.Center); + //newRun2.ActualRunWidth = rstairs.Runs[1].Width / 304.8; + //newRun2.TopElevation = rstairs.Runs[1].RelativeTopELevation / 304.8; + //newRun2.BaseElevation = rstairs.Runs[1].RelativeBaseElevation / 304.8; + + //添加休息平台 + + //LinkElementId stairsLinkId = new LinkElementId(stairsId); + //ICollection stairsPathIds =new FilteredElementCollector(doc).OfClass(typeof(StairsPathType)).ToElementIds(); + //var plan = new FilteredElementCollector(doc).OfClass(typeof(ViewPlan)).Cast().Where(v => v.GenLevel.ProjectElevation == 0).FirstOrDefault(); + //StairsPath.Create(doc, stairsLinkId, typeid, plan.Id); + #endregion + + stairsTrans.Commit(); + + } + // 编辑模式提交的时产生的错误处理 + newStairsScope.Commit(new StairsFailurePreprocessor()); + } + } + using(Transaction trans=new Transaction(doc, "删除栏杆")) + { + trans.Start(); + var ids = new FilteredElementCollector(doc).OfClass(typeof(Railing)).ToElementIds(); + foreach (var id in ids) + { + doc.Delete(id); + } + trans.Commit(); + } + transG.Assimilate(); + } + } + private static StairsRun CreateStairsSketchedRun(Document doc, RevitStairsRun rstairsrun, double levelBottom, ElementId stairsId) + { + IList bdryCurves = new List(); + IList riserCurves = new List(); + + IList pathCurves = new List(); + + Line locationline = rstairsrun.LocationLine; + Line l1 = locationline.CreateOffset(rstairsrun.Width / 2 / 304.8, new XYZ(0, 0, 1)) as Line; + Line l2 = locationline.CreateOffset(-rstairsrun.Width / 2 / 304.8, new XYZ(0, 0, 1)) as Line; + // boundaries + bdryCurves.Add(l1); + bdryCurves.Add(l2); + + // riser curves + int riserNum = rstairsrun.NumberOfRisers - 1; + for (int ii = 0; ii <= riserNum; ii++) + { + XYZ end0 = l1.Evaluate(ii / (double)riserNum, true); + XYZ end1 = l2.Evaluate(ii / (double)riserNum, true); + //XYZ end0 = (l1.GetEndPoint(0) + l1.GetEndPoint(1)) * ii / (double)riserNum; + //XYZ end1 = (l2.GetEndPoint(0) + l2.GetEndPoint(1)) * ii / (double)riserNum; + //XYZ end2 = new XYZ(end1.X, 10, 0); + riserCurves.Add(Line.CreateBound(end0, end1)); + } + + //stairs path curves + pathCurves.Add(locationline); + + StairsRun newRun = StairsRun.CreateSketchedRun(doc, stairsId, levelBottom, bdryCurves, riserCurves, pathCurves); + + return newRun; + } + private static ElementId CreateSampleStairs(Document document, Level levelBottom, Level levelTop) + { + ElementId newStairsId = null; + + using (StairsEditScope newStairsScope = new StairsEditScope(document, "New Stairs")) + { + newStairsId = newStairsScope.Start(levelBottom.Id, levelTop.Id); + + using (Transaction stairsTrans = new Transaction(document, "Add Runs and Landings to Stairs")) + { + stairsTrans.Start(); + + // Create a sketched run for the stairs + IList bdryCurves = new List(); + IList riserCurves = new List(); + IList pathCurves = new List(); + XYZ pnt1 = new XYZ(0, 0, 0); + XYZ pnt2 = new XYZ(15, 0, 0); + XYZ pnt3 = new XYZ(0, 10, 0); + XYZ pnt4 = new XYZ(15, 10, 0); + + // boundaries + bdryCurves.Add(Line.CreateBound(pnt1, pnt2)); + bdryCurves.Add(Line.CreateBound(pnt3, pnt4)); + + // riser curves + const int riserNum = 20; + for (int ii = 0; ii <= riserNum; ii++) + { + XYZ end0 = (pnt1 + pnt2) * ii / (double)riserNum; + XYZ end1 = (pnt3 + pnt4) * ii / (double)riserNum; + XYZ end2 = new XYZ(end1.X, 10, 0); + riserCurves.Add(Line.CreateBound(end0, end2)); + } + + //stairs path curves + XYZ pathEnd0 = (pnt1 + pnt3) / 2.0; + XYZ pathEnd1 = (pnt2 + pnt4) / 2.0; + pathCurves.Add(Line.CreateBound(pathEnd0, pathEnd1)); + + StairsRun newRun1 = StairsRun.CreateSketchedRun(document, newStairsId, levelBottom.Elevation, bdryCurves, riserCurves, pathCurves); + + // Add a straight run + Line locationLine = Line.CreateBound(new XYZ(20, -5, newRun1.TopElevation), new XYZ(35, -5, newRun1.TopElevation)); + StairsRun newRun2 = StairsRun.CreateStraightRun(document, newStairsId, locationLine, StairsRunJustification.Center); + newRun2.ActualRunWidth = 10; + + // Add a landing between the runs + CurveLoop landingLoop = new CurveLoop(); + XYZ p1 = new XYZ(15, 10, 0); + XYZ p2 = new XYZ(20, 10, 0); + XYZ p3 = new XYZ(20, -10, 0); + XYZ p4 = new XYZ(15, -10, 0); + Line curve_1 = Line.CreateBound(p1, p2); + Line curve_2 = Line.CreateBound(p2, p3); + Line curve_3 = Line.CreateBound(p3, p4); + Line curve_4 = Line.CreateBound(p4, p1); + + landingLoop.Append(curve_1); + landingLoop.Append(curve_2); + landingLoop.Append(curve_3); + landingLoop.Append(curve_4); + StairsLanding newLanding = StairsLanding.CreateSketchedLanding(document, newStairsId, landingLoop, newRun1.TopElevation); + + stairsTrans.Commit(); + } + // A failure preprocessor is to handle possible failures during the edit mode commitment process. + newStairsScope.Commit(new StairsFailurePreprocessor()); + } + + return newStairsId; + } + } + + class StairsFailurePreprocessor : IFailuresPreprocessor + { + public FailureProcessingResult PreprocessFailures(FailuresAccessor failuresAccessor) + { + IList listFma = failuresAccessor.GetFailureMessages(); + if (listFma.Count == 0) + return FailureProcessingResult.Continue; + foreach (FailureMessageAccessor fma in listFma) + { + // 如果是错误,则尝试解决 + if (fma.GetSeverity() == FailureSeverity.Error) + { + // 模拟手动单击"删除连接"按钮 + if (fma.HasResolutions()) + failuresAccessor.ResolveFailure(fma); + } + // 如果是警告,则禁止弹框 + if (fma.GetSeverity() == FailureSeverity.Warning) + { + //failuresAccessor.DeleteAllWarnings(); + failuresAccessor.DeleteWarning(fma); + } + } + return FailureProcessingResult.ProceedWithCommit; + // Use default failure processing + //return FailureProcessingResult.Continue; + } + } + +} \ No newline at end of file diff --git a/CDMUtil/Utility/Utility.cs b/CDMUtil/Utility/Utility.cs new file mode 100644 index 0000000..eddf32e --- /dev/null +++ b/CDMUtil/Utility/Utility.cs @@ -0,0 +1,59 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.Utility +{ + class Utility + { + public static Dictionary GetDictLevelId_LevelCodes(Document doc) + { + var levelCol = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast(); + var groundLevel = from l in levelCol + where l.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsDouble() >= 0 + select l; + var undergroundLevel = from l in levelCol + where l.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsDouble() < 0 + select l; + + var groundLevelOrdered = levelCol.OrderBy(l => l.ProjectElevation).ToList(); + var undergroundLevelOrdered = undergroundLevel.OrderByDescending(l => l.ProjectElevation).ToList(); + Dictionary LevelId_LevelCodes = new Dictionary(); + int groundLevelCode = 1; + int undergroundLevelCode = 901; + for (int i = 0; i < groundLevelOrdered.Count; i++) + { + ElementId levelid = groundLevelOrdered[i].Id; + string str; + if (groundLevelCode > 9) + { + if (groundLevelCode > 99) + { + str = string.Format("{0}", groundLevelCode); + } + else + { + str = string.Format("0{0}", groundLevelCode); + } + } + else + { + str = string.Format("00{0}", groundLevelCode); + } + LevelId_LevelCodes.Add(levelid, str); + groundLevelCode += 1; + } + for (int i = 0; i < undergroundLevelOrdered.Count; i++) + { + ElementId levelid = undergroundLevelOrdered[i].Id; + + LevelId_LevelCodes.Add(levelid, string.Format("{0}", undergroundLevelCode)); + undergroundLevelCode += 1; + } + return LevelId_LevelCodes; + } + } +} diff --git a/CDMUtil/Utility/WallUtil.cs b/CDMUtil/Utility/WallUtil.cs new file mode 100644 index 0000000..aaccf4d --- /dev/null +++ b/CDMUtil/Utility/WallUtil.cs @@ -0,0 +1,143 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using CDM.Interop.Revit.CDMComponent; +using CDM.Interop.Revit.RevitCompoent; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CDM.Interop.Revit.Utility +{ + class WallUtil : Utility + { + public static List GetWallsCDM(UIDocument uidoc, IList levels) + { + List cdmWalls = new List(); + Document doc = uidoc.Document; + var walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).OfClass(typeof(Wall)).ToElements(); + //楼板类型及编号 + Dictionary dicWalls = new Dictionary(); + int num1 = 1; + for (int i = 0; i < walls.Count; i++) + { + ElementId flId = walls[i].GetTypeId(); + try + { + dicWalls.Add(flId, string.Format("0{0}", num1)); + num1 += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (Wall wall in walls) + { + View3D v = (View3D)uidoc.ActiveView; + if (v == null) + { + var vi = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).OfClass(typeof(View3D)).ToElements(); + uidoc.ActiveView = (View3D)vi.FirstOrDefault(); + } + + //XYZ p = beam.GetTransform().Origin; + XYZ s = ((LocationCurve)wall.Location).Curve.GetEndPoint(0); + XYZ e = ((LocationCurve)wall.Location).Curve.GetEndPoint(1); + + Level level = (Level)doc.GetElement(wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId()); + + CDMWall cdmwall = new CDMWall + { + self = wall, + //AbsLevel= floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_TOP).AsValueString() + BaseLevel = (Level)doc.GetElement(wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId()), + LevelCode = doc.GetElement(wall.LevelId).Name, + SymbolId = wall.GetTypeId(), + //CDMTypeId = HcdmType.CDMWall, + Thickness = wall.WallType.get_Parameter(BuiltInParameter.WALL_ATTR_WIDTH_PARAM).AsValueString(), + //Thickness=wall.Width.ToString(), + BasePoint = s, + ExtendPoint = e + }; + ////通过out,将获取到的值复制给cdm的类型id,out参数必须在函数内初始化值 + dicWalls.TryGetValue(cdmwall.SymbolId, out cdmwall.CategoryCode); + cdmWalls.Add(cdmwall); + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicWalls.Count; j++) + { + ElementId id = dicWalls.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from b in cdmWalls + where b.BaseLevel.Id.Equals(levels[i].Id) && b.SymbolId.Equals(id) + select b; + List li = targetcdm.OrderByDescending(p => p.BasePoint.Y).ThenBy(p => p.BasePoint.X).ToList(); + //排序 + //var li = targetcdm.ToList(); + //List li = targetcdm.OrderByDescending(p => p.BasePoint.Y).ThenBy(p => p.BasePoint.X).ToList(); + + for (int k = 0; k < li.Count; k++) + { + if (k > 8) + { + if (k > 98) + { + li[k].LevelComponentCode = string.Format("{0}", k + 1); + } + else + { + li[k].LevelComponentCode = string.Format("0{0}", k + 1); + } + } + else + { + li[k].LevelComponentCode = string.Format("00{0}", k + 1); + } + } + + } + } + return cdmWalls; + } + public static void PlaceWalls(Document doc, List rwalls, Level level) + { + if (rwalls == null || level == null) + { + return; + } + var wallTypes = new FilteredElementCollector(doc).OfClass(typeof(WallType)).ToElements(); + + using (Transaction trans = new Transaction(doc)) + { + trans.Start("创建墙"); + foreach (var wall in rwalls) + { + foreach (WallType t in wallTypes) + { + if (t.Kind == WallKind.Basic) + { + string x = t.get_Parameter(BuiltInParameter.WALL_ATTR_WIDTH_PARAM).AsValueString(); + if (x == wall.Thickness) + { + //var l = wall.BasePoint - wall.ExtendPoint; + Autodesk.Revit.DB.Line line = Autodesk.Revit.DB.Line.CreateBound(wall.BasePoint, wall.ExtendPoint); + var levelelev = level.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsValueString(); + Wall.Create(doc, line, t.Id, level.Id, wall.Height / 304.8, (Convert.ToDouble(wall.StrBaseElev) - Convert.ToDouble(levelelev)) / 304.8, false, false); + //Wall.Create(doc, line, t.Id, level.Id, wall.Height / 304.8, Convert.ToDouble(wall.StrTopElev) / 304.8, false, false); + break; + } + } + + } + } + trans.Commit(); + } + } + } +} diff --git a/CDM_Revit.sln b/CDM_Revit.sln new file mode 100644 index 0000000..62f3026 --- /dev/null +++ b/CDM_Revit.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29306.81 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CivilModelCreator", "CivilModelCreator\CivilModelCreator.csproj", "{73DF41F6-474A-42DA-97F8-463C35CD8D1C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CDM.Interop.Revit", "CDMUtil\CDM.Interop.Revit.csproj", "{6538FD90-4B43-4CE3-A066-A8BCE39DD907}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {73DF41F6-474A-42DA-97F8-463C35CD8D1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {73DF41F6-474A-42DA-97F8-463C35CD8D1C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {73DF41F6-474A-42DA-97F8-463C35CD8D1C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {73DF41F6-474A-42DA-97F8-463C35CD8D1C}.Release|Any CPU.Build.0 = Release|Any CPU + {6538FD90-4B43-4CE3-A066-A8BCE39DD907}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6538FD90-4B43-4CE3-A066-A8BCE39DD907}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6538FD90-4B43-4CE3-A066-A8BCE39DD907}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6538FD90-4B43-4CE3-A066-A8BCE39DD907}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D18D4028-5837-4F8B-9EE1-F67AA6E39FF1} + EndGlobalSection +EndGlobal diff --git a/CivilModelCreator/CDMData.cs b/CivilModelCreator/CDMData.cs new file mode 100644 index 0000000..c1b5517 --- /dev/null +++ b/CivilModelCreator/CDMData.cs @@ -0,0 +1,92 @@ +using Autodesk.Revit.DB; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + public class CDMData + { + public Level Level; + /// + /// 族类型ID + /// + public ElementId TypeId; + /// + /// 参数编号(自定义) + /// + public string Id; + /// + /// 构件分类 + /// + public string Category; + /// + /// 构件类别编号 + /// + public string CategoryId; + /// + /// 构件名 + /// + public string Name; + /// + /// 标高名 + /// + public string LevelName => Level.Name; + /// + /// 层构件编号 + /// + public string Code; + /// + /// 设计者 + /// + public string Designer; + /// + /// 底标高 + /// + public double BaseLevel; + /// + /// 中心点X坐标 + /// + public double Center_X; + /// + /// 中心点Y坐标 + /// + public double Center_Y; + /// + /// 长度 + /// + public double Length; + /// + /// 宽度 + /// + public double Width; + /// + /// 顶部标高 + /// + public double TopLevel; + /// + /// 强度 + /// + public string Strength; + /// + /// 材料 + /// + public string Material; + /// + /// 长度单位 + /// + public string Unit; + /// + /// 身份证 + /// + public string Iden; + public string HcdmClass; + public string HcdmNumber => string.Format("{0}-{1}-{2}", CategoryId, LevelName, Code); + /// + /// 备注 + /// + public string Remark; + } +} diff --git a/CivilModelCreator/CDMToExcelModeless.cs b/CivilModelCreator/CDMToExcelModeless.cs new file mode 100644 index 0000000..3e52e45 --- /dev/null +++ b/CivilModelCreator/CDMToExcelModeless.cs @@ -0,0 +1,54 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + class CDMToExcelModeless + { + ExternalEvent ExternalEvent { get; set; } + + List cdmData { get; set; } + string path { get; set; } + + public CDMToExcelModeless(string path, List cdm) + { + cdmData = cdm; + this.path = path; + } + internal void ProgressModeless() + { + if (cdmData == null) + throw new Exception("无数据"); + + ProgressMonitorView currentUI = new ProgressMonitorView(); + + ProcessEventHandler progressEventHandler = new ProcessEventHandler + { + CdmData = cdmData, + CurrentUI = currentUI, + Path = path + }; + ProgressMonitorControl currentControl = new ProgressMonitorControl(); + + currentControl.MaxValue = cdmData.Count; + progressEventHandler.CurrentControl = currentControl; + + ExternalEvent = ExternalEvent.Create(progressEventHandler); + + currentUI.DataContext = currentControl; + currentUI.ContentRendered += CurrentUI_ContentRendered; + currentUI.Topmost = true; + currentUI.Show(); + } + + private void CurrentUI_ContentRendered(object sender, EventArgs e) + { + ExternalEvent.Raise(); + } + } +} diff --git a/CivilModelCreator/CivilModelCreator.csproj b/CivilModelCreator/CivilModelCreator.csproj new file mode 100644 index 0000000..98ecaef --- /dev/null +++ b/CivilModelCreator/CivilModelCreator.csproj @@ -0,0 +1,91 @@ + + + + + Debug + AnyCPU + {73DF41F6-474A-42DA-97F8-463C35CD8D1C} + Library + Properties + CivilModelCreator + CivilModelCreator + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ProgressMonitorView.xaml + + + + + WpfCivilCreator.xaml + + + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + + + 2.4.1 + + + + \ No newline at end of file diff --git a/CivilModelCreator/CmdCDMToExcel.cs b/CivilModelCreator/CmdCDMToExcel.cs new file mode 100644 index 0000000..8ae9308 --- /dev/null +++ b/CivilModelCreator/CmdCDMToExcel.cs @@ -0,0 +1,271 @@ +using Autodesk.Revit.Attributes; +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using Autodesk.Revit.UI.Selection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + [Transaction(TransactionMode.Manual)] + class CmdCDMToExcel : IExternalCommand + { + public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) + { + Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; + Document doc = commandData.Application.ActiveUIDocument.Document; + VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog + { + Multiselect = false + }; + dialog.ShowDialog(); + if (dialog.SelectedPath == null) + { + return Result.Cancelled; + } + string path = dialog.SelectedPath; + + + + + var levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements(); + + + #region 柱 + + List cdmData = NewMethod(doc, levels); + #endregion + + #region 板 + GetFloorsCDM(doc, levels, cdmData); + #endregion + + var beams = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).OfClass(typeof(FamilyInstance)).ToElements(); + foreach (FamilyInstance beam in beams) + { + CDMData cdm = new CDMData(); + } + cdmData = cdmData.OrderBy(c => c.CategoryId).ThenBy(c => c.LevelName).ThenBy(c => c.Code).ToList(); + try + { + CDMToExcelModeless model = new CDMToExcelModeless(path, cdmData); + model.ProgressModeless(); + } + catch (Exception e) + { + + if (!(e is Autodesk.Revit.Exceptions.OperationCanceledException)) + { + message = e.Message; + return Result.Failed; + } + } + return Result.Succeeded; + } + + private static List NewMethod(Document doc, IList levels) + { + var StColumns = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns).OfClass(typeof(FamilyInstance)).ToElements(); + + Dictionary dicfsColoumn = new Dictionary(); + int num = 1; + //查找所有具有实例的柱子类型及赋予编码 + for (int i = 0; i < StColumns.Count(); i++) + { + ElementId fiId = ((FamilyInstance)StColumns[i]).Symbol.Id; + try + { + dicfsColoumn.Add(fiId, string.Format("0{0}", num)); + num += 1; + } + catch (Exception) + { + continue; + } + } + List cdmData = new List(); + + //将柱数据转成cdm数据 + foreach (FamilyInstance column in StColumns) + { + //cdm.SymbolId = column.GetTypeId(); + //坐标 + XYZ p1 = column.GetTotalTransform().Origin; + CDMData cdm = new CDMData + { + TypeId = column.Symbol.Id, + Center_X = p1.X * 304.8 / 1000, + Center_Y = p1.Y * 304.8 / 1000, + HcdmClass = "A2001", + Level = (Level)doc.GetElement(column.LevelId), + Name = column.Symbol.Family.Name + ":" + column.Symbol.Name, + Category = "柱", + + }; + dicfsColoumn.TryGetValue(column.Symbol.Id, out cdm.CategoryId); + //底部标高名称 + string baselevelname = column.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsValueString(); + //顶部标高名称 + string toplevelname = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsValueString(); + //var value = dict.Where(q => q.Key == column.Symbol.Id).Select(q => q.Value).FirstOrDefault(); + //cdm.HcdmNumber = String.Format("{0}-{1}", value.ToString(), baselevelname); + + foreach (Level lev in levels) + { + //以深度去布置柱子,底标高和顶标高相反 + if (lev.Name == baselevelname) + { + //底部偏移 + double baseoffest = column.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble(); + cdm.BaseLevel = UnitUtils.ConvertFromInternalUnits(lev.Elevation + baseoffest, DisplayUnitType.DUT_METERS); + //md.BaseLevel = lev.Elevation * 304.8 / 1000 + baseof; + } + if (lev.Name == toplevelname) + { + //顶部偏移 + double topoffest = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble(); + cdm.TopLevel = UnitUtils.ConvertFromInternalUnits(lev.Elevation + topoffest, DisplayUnitType.DUT_METERS); + } + } + double b = 0; + double h = 0; + try + { + b = column.Symbol.LookupParameter("b").AsDouble(); + h = column.Symbol.LookupParameter("h").AsDouble(); + } + catch (Exception ex) + { + System.Windows.MessageBox.Show(ex.Message); + } + cdm.Length = UnitUtils.ConvertFromInternalUnits(b, DisplayUnitType.DUT_METERS); + cdm.Width = UnitUtils.ConvertFromInternalUnits(h, DisplayUnitType.DUT_METERS); + cdmData.Add(cdm); + + //md.Length=from Parameter para in fi.Parameters + // where para.Definition.Name=="b" + // select + //md.Length=fi.get_Parameter() + + + } + //层构件编号 + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicfsColoumn.Count; j++) + { + ElementId id = dicfsColoumn.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmData + where d.Level.Id.Equals(levels[i].Id) && d.TypeId.Equals(id) + select d; + //排序 + List li = targetcdm.OrderByDescending(c => c.Center_Y).ThenBy(c => c.Center_X).ToList(); + //var li = targetcdm.ToList(); + //IEnumerable enuCdm = from cdm in targetcdm + // orderby cdm.Center_Y + // select cdm; + //li.Sort(); + //while (itr.MoveNext) + //{ + // Element e = (Element)itr.Current; + + //} + for (int k = 0; k < li.ToList().Count; k++) + { + if (k > 8) + { + li[k].Code = string.Format("0{0}", k + 1); + } + else + { + li[k].Code = string.Format("00{0}", k + 1); + } + } + } + } + + return cdmData; + } + + private static void GetFloorsCDM(Document doc, IList levels, List cdmData) + { + var floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors).OfClass(typeof(Floor)).ToElements(); + + Dictionary dicFloors = new Dictionary(); + int num1 = 1; + for (int i = 0; i < floors.Count; i++) + { + ElementId flId = floors[i].GetTypeId(); + try + { + dicFloors.Add(flId, string.Format("0{0}", num1)); + num1 += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (Floor floor in floors) + { + View3D v = (View3D)doc.ActiveView; + if (v == null) + { + System.Windows.MessageBox.Show("请使用三维视图"); + } + XYZ max = floor.get_BoundingBox(v).Max; + XYZ min = floor.get_BoundingBox(v).Min; + XYZ p = (max + min) / 2; + CDMData cdm = new CDMData + { + Level = (Level)doc.GetElement(floor.LevelId), + TypeId = floor.FloorType.Id, + HcdmClass = "A2002", + Center_X = p.X * 304.8 / 1000, + Center_Y = p.Y * 304.8 / 1000, + Length = UnitUtils.ConvertFromInternalUnits(max.X - min.X, DisplayUnitType.DUT_METERS), + Width = UnitUtils.ConvertFromInternalUnits(max.Y - min.Y, DisplayUnitType.DUT_METERS), + BaseLevel = Convert.ToDouble(floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_BOTTOM).AsValueString()) / 1000, + TopLevel = Convert.ToDouble(floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_TOP).AsValueString()) / 1000, + Name = floor.FloorType.FamilyName + ":" + floor.Name, + Category = "板", + }; + dicFloors.TryGetValue(floor.FloorType.Id, out cdm.CategoryId); + cdmData.Add(cdm); + + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicFloors.Count; j++) + { + ElementId id = dicFloors.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmData + where d.Level.Id.Equals(levels[i].Id) && d.TypeId.Equals(id) + select d; + //排序 + //var li = targetcdm.ToList(); + List li = targetcdm.OrderByDescending(c => c.Center_Y).ThenBy(c => c.Center_X).ToList(); + for (int k = 0; k < li.Count; k++) + { + if (k > 8) + { + li[k].Code = string.Format("0{0}", k + 1); + } + else + { + li[k].Code = string.Format("00{0}", k + 1); + } + } + } + } + } + } +} diff --git a/CivilModelCreator/CmdCivilCreator.cs b/CivilModelCreator/CmdCivilCreator.cs new file mode 100644 index 0000000..729df66 --- /dev/null +++ b/CivilModelCreator/CmdCivilCreator.cs @@ -0,0 +1,25 @@ +using Autodesk.Revit.Attributes; +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + [Transaction(TransactionMode.Manual)] + [Regeneration(RegenerationOption.Manual)] + public class CmdCivilCreator : IExternalCommand + { + public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) + { + Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; + Document doc = commandData.Application.ActiveUIDocument.Document; + + new WpfCivilCreator(app, doc).ShowDialog(); + return Result.Succeeded; + } + } +} diff --git a/CivilModelCreator/CmdExportCDMDataToExcel.cs b/CivilModelCreator/CmdExportCDMDataToExcel.cs new file mode 100644 index 0000000..605fe45 --- /dev/null +++ b/CivilModelCreator/CmdExportCDMDataToExcel.cs @@ -0,0 +1,488 @@ +using Autodesk.Revit.Attributes; +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Autodesk.Revit.DB.Structure; +using System.IO; +using NPOI.SS.UserModel; +using NPOI.HSSF.UserModel; +using NPOI.XSSF.UserModel; +using System.Data; + +namespace CivilModelCreator +{ + [Transaction(TransactionMode.Manual)] + [Regeneration(RegenerationOption.Manual)] + public class CmdExportCDMDataToExcel : IExternalCommand + { + public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) + { + Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; + Document doc = commandData.Application.ActiveUIDocument.Document; + VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog + { + Multiselect = false + }; + dialog.ShowDialog(); + if (dialog.SelectedPath == null) + { + return Result.Cancelled; + } + string path = dialog.SelectedPath; + + var StColumns = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns).OfClass(typeof(FamilyInstance)).ToElements(); + + var floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors).OfClass(typeof(Floor)).ToElements(); + + var beams = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).OfClass(typeof(FamilyInstance)).ToElements(); + + var levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements(); + + + #region 柱 + Dictionary dicfsColoumn = new Dictionary(); + int num = 1; + //查找所有具有实例的柱子类型及赋予编码 + for (int i = 0; i < StColumns.Count(); i++) + { + ElementId fiId = ((FamilyInstance)StColumns[i]).Symbol.Id; + try + { + dicfsColoumn.Add(fiId, string.Format("0{0}", num)); + num += 1; + } + catch (Exception) + { + continue; + } + } + List cdmData = new List(); + + //将柱数据转成cdm数据 + foreach (FamilyInstance column in StColumns) + { + //cdm.SymbolId = column.GetTypeId(); + //坐标 + XYZ p1 = column.GetTotalTransform().Origin; + CDMData cdm = new CDMData + { + TypeId = column.Symbol.Id, + Center_X = p1.X * 304.8 / 1000, + Center_Y = p1.Y * 304.8 / 1000, + HcdmClass = "A2001", + Level = (Level)doc.GetElement(column.LevelId), + Name = column.Symbol.Family.Name + ":" + column.Symbol.Name, + Category = "柱", + + }; + dicfsColoumn.TryGetValue(column.Symbol.Id, out cdm.CategoryId); + //底部标高名称 + string baselevelname = column.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsValueString(); + //顶部标高名称 + string toplevelname = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsValueString(); + //var value = dict.Where(q => q.Key == column.Symbol.Id).Select(q => q.Value).FirstOrDefault(); + //cdm.HcdmNumber = String.Format("{0}-{1}", value.ToString(), baselevelname); + + foreach (Level lev in levels) + { + //以深度去布置柱子,底标高和顶标高相反 + if (lev.Name == baselevelname) + { + //底部偏移 + double baseoffest = column.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble(); + cdm.BaseLevel = UnitUtils.ConvertFromInternalUnits(lev.Elevation + baseoffest, DisplayUnitType.DUT_METERS); + //md.BaseLevel = lev.Elevation * 304.8 / 1000 + baseof; + } + if (lev.Name == toplevelname) + { + //顶部偏移 + double topoffest = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble(); + cdm.TopLevel = UnitUtils.ConvertFromInternalUnits(lev.Elevation + topoffest, DisplayUnitType.DUT_METERS); + } + } + double b = 0; + double h = 0; + try + { + b = column.Symbol.LookupParameter("b").AsDouble(); + h = column.Symbol.LookupParameter("h").AsDouble(); + } + catch (Exception ex) + { + System.Windows.MessageBox.Show(ex.Message); + } + cdm.Length = UnitUtils.ConvertFromInternalUnits(b, DisplayUnitType.DUT_METERS); + cdm.Width = UnitUtils.ConvertFromInternalUnits(h, DisplayUnitType.DUT_METERS); + cdmData.Add(cdm); + + //md.Length=from Parameter para in fi.Parameters + // where para.Definition.Name=="b" + // select + //md.Length=fi.get_Parameter() + + + } + //层构件编号 + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicfsColoumn.Count; j++) + { + ElementId id = dicfsColoumn.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmData + where d.Level.Id.Equals(levels[i].Id) && d.TypeId.Equals(id) + select d; + //排序 + List li = targetcdm.OrderByDescending(c => c.Center_Y).ThenBy(c => c.Center_X).ToList(); + //var li = targetcdm.ToList(); + //IEnumerable enuCdm = from cdm in targetcdm + // orderby cdm.Center_Y + // select cdm; + //li.Sort(); + //while (itr.MoveNext) + //{ + // Element e = (Element)itr.Current; + + //} + for (int k = 0; k < li.ToList().Count; k++) + { + if (k > 8) + { + li[k].Code = string.Format("0{0}", k + 1); + } + else + { + li[k].Code = string.Format("00{0}", k + 1); + } + } + } + } + #endregion + #region 板 + + Dictionary dicFloors = new Dictionary(); + int num1 = 1; + for (int i = 0; i < floors.Count; i++) + { + ElementId flId = floors[i].GetTypeId(); + try + { + dicFloors.Add(flId, string.Format("0{0}", num1)); + num1 += 1; + } + catch (Exception) + { + + continue; + } + } + + foreach (Floor floor in floors) + { + View3D v = (View3D)doc.ActiveView; + if (v == null) + { + System.Windows.MessageBox.Show("请使用三维视图"); + } + XYZ max = floor.get_BoundingBox(v).Max; + XYZ min = floor.get_BoundingBox(v).Min; + XYZ p = (max + min) / 2; + CDMData cdm = new CDMData + { + Level = (Level)doc.GetElement(floor.LevelId), + TypeId = floor.FloorType.Id, + HcdmClass = "A2002", + Center_X = p.X * 304.8 / 1000, + Center_Y = p.Y * 304.8 / 1000, + Length = UnitUtils.ConvertFromInternalUnits(max.X - min.X, DisplayUnitType.DUT_METERS), + Width = UnitUtils.ConvertFromInternalUnits(max.Y - min.Y, DisplayUnitType.DUT_METERS), + BaseLevel = Convert.ToDouble(floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_BOTTOM).AsValueString()) / 1000, + TopLevel = Convert.ToDouble(floor.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_TOP).AsValueString()) / 1000, + Name = floor.FloorType.FamilyName + ":" + floor.Name, + Category = "板", + }; + dicFloors.TryGetValue(floor.FloorType.Id, out cdm.CategoryId); + cdmData.Add(cdm); + + } + + for (int i = 0; i < levels.Count(); i++) + { + for (int j = 0; j < dicFloors.Count; j++) + { + ElementId id = dicFloors.ElementAt(j).Key; + //归类cdm中同标高同类型 + IEnumerable targetcdm = from d in cdmData + where d.Level.Id.Equals(levels[i].Id) && d.TypeId.Equals(id) + select d; + //排序 + //var li = targetcdm.ToList(); + List li = targetcdm.OrderByDescending(c => c.Center_Y).ThenBy(c => c.Center_X).ToList(); + for (int k = 0; k < li.Count; k++) + { + if (k > 8) + { + li[k].Code = string.Format("0{0}", k + 1); + } + else + { + li[k].Code = string.Format("00{0}", k + 1); + } + } + } + } + #endregion + foreach (FamilyInstance beam in beams) + { + CDMData cdm = new CDMData(); + } + cdmData = cdmData.OrderBy(c => c.CategoryId).ThenBy(c => c.LevelName).ThenBy(c => c.Code).ToList(); + //ExportToSingleExcel(path, cdmData); + DataTable dt = WriteToDataTable(cdmData); + ExportToExcel(path, dt); + return Result.Succeeded; + } + public DataTable WriteToDataTable(List cdms) + { + DataTable dt = new DataTable(); + dt.Columns.Add("构件分类", typeof(string)); + dt.Columns.Add("族类型", typeof(string)); + dt.Columns.Add("编号", typeof(string)); + dt.Columns.Add("底标高(m)", typeof(double)); + dt.Columns.Add("中心(X)", typeof(double)); + dt.Columns.Add("中心(Y)", typeof(double)); + dt.Columns.Add("边长X(m)", typeof(double)); + dt.Columns.Add("边长Y(m)", typeof(double)); + dt.Columns.Add("顶标高(m)", typeof(double)); + foreach (var cdm in cdms) + { + DataRow dr = dt.NewRow(); + dr[0] = cdm.HcdmClass; + dr[1] = cdm.Name; + dr[2] = cdm.HcdmNumber; + dr[3] = cdm.BaseLevel; + dr[4] = cdm.Center_X; + dr[5] = cdm.Center_Y; + dr[6] = cdm.Length; + dr[7] = cdm.Width; + //dr[7] = UnitUtils.ConvertFromInternalUnits(h, DisplayUnitType.DUT_METERS); + dr[8] = cdm.TopLevel; + dt.Rows.Add(dr); + } + return dt; + } + + static void ExportToSingleExcel(string path, List cdms) + { + foreach (CDMData cdm in cdms) + { + XSSFWorkbook workbook = new XSSFWorkbook(); + ISheet firstSheet = workbook.CreateSheet("CDM数据表"); + #region 表格 + firstSheet.CreateRow(0); + firstSheet.GetRow(0).CreateCell(0); + firstSheet.GetRow(0).CreateCell(1); + firstSheet.GetRow(0).CreateCell(2); + firstSheet.GetRow(0).GetCell(0).SetCellValue("HcdmClass"); + firstSheet.GetRow(0).GetCell(1).SetCellValue(cdm.Category + "CDM专用标准"); + firstSheet.GetRow(0).GetCell(2).SetCellValue(cdm.HcdmClass); + + firstSheet.CreateRow(1); + firstSheet.GetRow(1).CreateCell(0); + firstSheet.GetRow(1).CreateCell(1); + firstSheet.GetRow(1).GetCell(0).SetCellValue("构件名称"); + firstSheet.GetRow(1).GetCell(1).SetCellValue(cdm.Category); + + firstSheet.CreateRow(2); + firstSheet.GetRow(2).CreateCell(0); + firstSheet.GetRow(2).CreateCell(1); + firstSheet.GetRow(2).CreateCell(2); + firstSheet.GetRow(2).GetCell(0).SetCellValue("HcdmClass"); + firstSheet.GetRow(2).GetCell(1).SetCellValue("XXXXX(自动生成)"); + firstSheet.GetRow(2).GetCell(2).SetCellValue(cdm.HcdmNumber); + + firstSheet.CreateRow(4); + firstSheet.GetRow(4).CreateCell(0); + firstSheet.GetRow(4).CreateCell(1); + firstSheet.GetRow(4).CreateCell(2); + firstSheet.GetRow(4).CreateCell(3); + firstSheet.GetRow(4).CreateCell(4); + firstSheet.GetRow(4).GetCell(0).SetCellValue("字段编码"); + firstSheet.GetRow(4).GetCell(1).SetCellValue("字段名称"); + firstSheet.GetRow(4).GetCell(2).SetCellValue("单位"); + firstSheet.GetRow(4).GetCell(3).SetCellValue("备注"); + firstSheet.GetRow(4).GetCell(4).SetCellValue("字段值"); + + firstSheet.CreateRow(5); + firstSheet.GetRow(5).CreateCell(0); + firstSheet.GetRow(5).CreateCell(1); + firstSheet.GetRow(5).GetCell(0).SetCellValue("101"); + firstSheet.GetRow(5).GetCell(1).SetCellValue("编号(自定义)"); + + firstSheet.CreateRow(6); + firstSheet.GetRow(6).CreateCell(0); + firstSheet.GetRow(6).CreateCell(1); + firstSheet.GetRow(6).CreateCell(2); + firstSheet.GetRow(6).CreateCell(4); + firstSheet.GetRow(6).GetCell(0).SetCellValue("102"); + firstSheet.GetRow(6).GetCell(1).SetCellValue(cdm.Category + "底标高"); + firstSheet.GetRow(6).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(6).GetCell(4).SetCellValue(Math.Round(cdm.BaseLevel, 2, MidpointRounding.AwayFromZero)); + + + firstSheet.CreateRow(7); + firstSheet.GetRow(7).CreateCell(0); + firstSheet.GetRow(7).CreateCell(1); + firstSheet.GetRow(7).CreateCell(2); + firstSheet.GetRow(7).CreateCell(4); + firstSheet.GetRow(7).GetCell(0).SetCellValue("103"); + firstSheet.GetRow(7).GetCell(1).SetCellValue(cdm.Category + "中心点坐标X"); + firstSheet.GetRow(7).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(7).GetCell(4).SetCellValue(Math.Round(cdm.Center_X, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(8); + firstSheet.GetRow(8).CreateCell(0); + firstSheet.GetRow(8).CreateCell(1); + firstSheet.GetRow(8).CreateCell(2); + firstSheet.GetRow(8).CreateCell(4); + firstSheet.GetRow(8).GetCell(0).SetCellValue("104"); + firstSheet.GetRow(8).GetCell(1).SetCellValue(cdm.Category + "中心点坐标Y"); + firstSheet.GetRow(8).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(8).GetCell(4).SetCellValue(Math.Round(cdm.Center_Y, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(9); + firstSheet.GetRow(9).CreateCell(0); + firstSheet.GetRow(9).CreateCell(1); + firstSheet.GetRow(9).CreateCell(2); + firstSheet.GetRow(9).CreateCell(4); + firstSheet.GetRow(9).GetCell(0).SetCellValue("105"); + firstSheet.GetRow(9).GetCell(1).SetCellValue(cdm.Category + "边长X"); + firstSheet.GetRow(9).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(9).GetCell(4).SetCellValue(Math.Round(cdm.Length, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(10); + firstSheet.GetRow(10).CreateCell(0); + firstSheet.GetRow(10).CreateCell(1); + firstSheet.GetRow(10).CreateCell(2); + firstSheet.GetRow(10).CreateCell(4); + firstSheet.GetRow(10).GetCell(0).SetCellValue("106"); + firstSheet.GetRow(10).GetCell(1).SetCellValue(cdm.Category + "边长Y"); + firstSheet.GetRow(10).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(10).GetCell(4).SetCellValue(Math.Round(cdm.Width, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(11); + firstSheet.GetRow(11).CreateCell(0); + firstSheet.GetRow(11).CreateCell(1); + firstSheet.GetRow(11).CreateCell(2); + firstSheet.GetRow(11).CreateCell(4); + firstSheet.GetRow(11).GetCell(0).SetCellValue("107"); + firstSheet.GetRow(11).GetCell(1).SetCellValue(cdm.Category + "顶标高"); + firstSheet.GetRow(11).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(11).GetCell(4).SetCellValue(Math.Round(cdm.TopLevel, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(12); + firstSheet.GetRow(12).CreateCell(0); + firstSheet.GetRow(12).CreateCell(1); + firstSheet.GetRow(12).CreateCell(2); + firstSheet.GetRow(12).CreateCell(4); + firstSheet.GetRow(12).GetCell(0).SetCellValue("108"); + firstSheet.GetRow(12).GetCell(1).SetCellValue(cdm.Category + "身材料"); + firstSheet.GetRow(12).GetCell(2).SetCellValue("混凝土、砖、其他"); + firstSheet.GetRow(12).GetCell(4).SetCellValue(cdm.Material); + + firstSheet.CreateRow(13); + firstSheet.GetRow(13).CreateCell(0); + firstSheet.GetRow(13).CreateCell(1); + firstSheet.GetRow(13).CreateCell(2); + firstSheet.GetRow(13).CreateCell(4); + firstSheet.GetRow(13).GetCell(0).SetCellValue("109"); + firstSheet.GetRow(13).GetCell(1).SetCellValue(cdm.Category + "材料强度(标准值)"); + firstSheet.GetRow(13).GetCell(2).SetCellValue("MPa"); + firstSheet.GetRow(13).GetCell(4).SetCellValue(cdm.Strength); + + firstSheet.CreateRow(14); + firstSheet.GetRow(14).CreateCell(0); + firstSheet.GetRow(14).CreateCell(1); + firstSheet.GetRow(14).CreateCell(2); + firstSheet.GetRow(14).CreateCell(4); + firstSheet.GetRow(14).GetCell(0).SetCellValue("110"); + firstSheet.GetRow(14).GetCell(1).SetCellValue("设计负责人"); + firstSheet.GetRow(14).GetCell(2).SetCellValue("姓名"); + firstSheet.GetRow(14).GetCell(4).SetCellValue(cdm.Designer); + + firstSheet.CreateRow(15); + firstSheet.GetRow(15).CreateCell(0); + firstSheet.GetRow(15).CreateCell(1); + //firstSheet.GetRow(15).CreateCell(2); + firstSheet.GetRow(15).CreateCell(4); + firstSheet.GetRow(15).GetCell(0).SetCellValue("111"); + firstSheet.GetRow(15).GetCell(1).SetCellValue("身份证"); + //firstSheet.GetRow(15).GetCell(2).SetCellValue(""); + firstSheet.GetRow(15).GetCell(4).SetCellValue(cdm.Iden); + + firstSheet.AutoSizeColumn(0); + firstSheet.AutoSizeColumn(1); + firstSheet.AutoSizeColumn(2); + firstSheet.AutoSizeColumn(3); + firstSheet.AutoSizeColumn(4); + #endregion + + + using (FileStream excelStream = File.Create(path + "\\" + cdm.HcdmClass + "-" + cdm.HcdmNumber + ".xlsx")) + { + workbook.Write(excelStream); + } + } + } + static void ExportToExcel(string path, DataTable dt) + { + string exportedExcelFullName = path + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx"; + if (dt != null && dt.Rows.Count > 0) + { + XSSFWorkbook workBook = new XSSFWorkbook(); + ISheet firstSheet = workBook.CreateSheet("CDM数据表"); + IRow headerRow = firstSheet.CreateRow(0); + + for (int i = 0; i < dt.Columns.Count; i++) + { + ICell headerCell = headerRow.CreateCell(i); + headerCell.SetCellValue(dt.Columns[i].ColumnName?.ToString()); + } + + for (int i = 0; i < dt.Rows.Count; i++) + { + IRow dataRow = firstSheet.CreateRow(i + 1); + for (int j = 0; j < dt.Columns.Count; j++) + { + ICell dataCell = dataRow.CreateCell(j); + //dataCell.SetCellValue(dt.Rows[i][j]?.ToString()); + var str = dt.Rows[i][j]?.ToString(); + double value = 0.0; + //能否转换为数字 + if (double.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out value)) + { + dataCell.SetCellValue(Math.Round(value, 2, MidpointRounding.AwayFromZero)); + } + else + { + dataCell.SetCellValue(dt.Rows[i][j]?.ToString()); + } + } + } + for (int i = 0; i < dt.Columns.Count; i++) + { + firstSheet.AutoSizeColumn(i); + } + + using (FileStream excelStream = File.Create(exportedExcelFullName)) + { + workBook.Write(excelStream); + } + } + } + } +} diff --git a/CivilModelCreator/Component/CDMBeam.cs b/CivilModelCreator/Component/CDMBeam.cs new file mode 100644 index 0000000..f3fa362 --- /dev/null +++ b/CivilModelCreator/Component/CDMBeam.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + class CDMBeam : CDMData + { + + } +} diff --git a/CivilModelCreator/Component/CDMColumns.cs b/CivilModelCreator/Component/CDMColumns.cs new file mode 100644 index 0000000..c048449 --- /dev/null +++ b/CivilModelCreator/Component/CDMColumns.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + class CDMWall : CDMData + { + + } +} diff --git a/CivilModelCreator/Component/CDMFloor.cs b/CivilModelCreator/Component/CDMFloor.cs new file mode 100644 index 0000000..b6072b2 --- /dev/null +++ b/CivilModelCreator/Component/CDMFloor.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + class CDMFloor : CDMData + { + + } +} diff --git a/CivilModelCreator/Component/CDMStair.cs b/CivilModelCreator/Component/CDMStair.cs new file mode 100644 index 0000000..cf89a27 --- /dev/null +++ b/CivilModelCreator/Component/CDMStair.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + class CDMStair:CDMData + { + } +} diff --git a/CivilModelCreator/Enum/ModelType.cs b/CivilModelCreator/Enum/ModelType.cs new file mode 100644 index 0000000..22083a6 --- /dev/null +++ b/CivilModelCreator/Enum/ModelType.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + public enum ModelType + { + 墙 = 0, + 梁 = 1, + 板 = 2, + 柱 = 3 + } +} diff --git a/CivilModelCreator/ProcessEventHandler.cs b/CivilModelCreator/ProcessEventHandler.cs new file mode 100644 index 0000000..b9edae2 --- /dev/null +++ b/CivilModelCreator/ProcessEventHandler.cs @@ -0,0 +1,248 @@ +using Autodesk.Revit.DB; +using Autodesk.Revit.UI; +using NPOI.SS.UserModel; +using NPOI.XSSF.UserModel; +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace CivilModelCreator +{ + internal class ProcessEventHandler : IExternalEventHandler + { + public ProgressMonitorView CurrentUI { get; set; } + public ProgressMonitorControl CurrentControl { get; set; } + private bool Cancel = false; + + public List CdmData { get; set; } + public string Path { get; set; } + + private delegate void ProgressBarDelegate(); + + public void Execute(UIApplication app) + { + if (app == null) + { + CloseWindow(); + return; + } + + if (app.ActiveUIDocument == null || app.ActiveUIDocument.Document == null || CdmData == null || CurrentUI == null || CurrentControl == null || Path == null) + return; + + CurrentUI.btnCancel.Click += CurrentUI_Closed; + + for (CurrentControl.CurrentValue = 0; CurrentControl.CurrentValue < CurrentControl.MaxValue; ++CurrentControl.CurrentValue) + { + int index = Convert.ToInt16(CurrentControl.CurrentValue); + if (Cancel) + break; + + System.Threading.Thread.Sleep(10); + + #region 做操作 + + try + { + CDMtoExcel(CdmData[index]); + } + catch (Exception e) + { + MessageBox.Show(e.Message); + //CloseWindow(); + return; + } + + #endregion 做操作 + + CurrentControl.CurrentContext = string.Format("进度已完成 {0} of {1} ", CurrentControl.CurrentValue, CurrentControl.MaxValue); + CurrentUI.Dispatcher.Invoke(new ProgressBarDelegate(CurrentControl.NotifyUI), System.Windows.Threading.DispatcherPriority.Background); + } + + CloseWindow(); + } + + private void CDMtoExcel(CDMData cdm) + { + XSSFWorkbook workbook = new XSSFWorkbook(); + ISheet firstSheet = workbook.CreateSheet("CDM数据表"); + + #region 表格 + + firstSheet.CreateRow(0); + firstSheet.GetRow(0).CreateCell(0); + firstSheet.GetRow(0).CreateCell(1); + firstSheet.GetRow(0).CreateCell(2); + firstSheet.GetRow(0).GetCell(0).SetCellValue("HcdmClass"); + firstSheet.GetRow(0).GetCell(1).SetCellValue(cdm.Category + "CDM专用标准"); + firstSheet.GetRow(0).GetCell(2).SetCellValue(cdm.HcdmClass); + + firstSheet.CreateRow(1); + firstSheet.GetRow(1).CreateCell(0); + firstSheet.GetRow(1).CreateCell(1); + firstSheet.GetRow(1).GetCell(0).SetCellValue("构件名称"); + firstSheet.GetRow(1).GetCell(1).SetCellValue(cdm.Category); + + firstSheet.CreateRow(2); + firstSheet.GetRow(2).CreateCell(0); + firstSheet.GetRow(2).CreateCell(1); + firstSheet.GetRow(2).CreateCell(2); + firstSheet.GetRow(2).GetCell(0).SetCellValue("HcdmClass"); + firstSheet.GetRow(2).GetCell(1).SetCellValue("XXXXX(自动生成)"); + firstSheet.GetRow(2).GetCell(2).SetCellValue(cdm.HcdmNumber); + + firstSheet.CreateRow(4); + firstSheet.GetRow(4).CreateCell(0); + firstSheet.GetRow(4).CreateCell(1); + firstSheet.GetRow(4).CreateCell(2); + firstSheet.GetRow(4).CreateCell(3); + firstSheet.GetRow(4).CreateCell(4); + firstSheet.GetRow(4).GetCell(0).SetCellValue("字段编码"); + firstSheet.GetRow(4).GetCell(1).SetCellValue("字段名称"); + firstSheet.GetRow(4).GetCell(2).SetCellValue("单位"); + firstSheet.GetRow(4).GetCell(3).SetCellValue("备注"); + firstSheet.GetRow(4).GetCell(4).SetCellValue("字段值"); + + firstSheet.CreateRow(5); + firstSheet.GetRow(5).CreateCell(0); + firstSheet.GetRow(5).CreateCell(1); + firstSheet.GetRow(5).GetCell(0).SetCellValue("101"); + firstSheet.GetRow(5).GetCell(1).SetCellValue("编号(自定义)"); + + firstSheet.CreateRow(6); + firstSheet.GetRow(6).CreateCell(0); + firstSheet.GetRow(6).CreateCell(1); + firstSheet.GetRow(6).CreateCell(2); + firstSheet.GetRow(6).CreateCell(4); + firstSheet.GetRow(6).GetCell(0).SetCellValue("102"); + firstSheet.GetRow(6).GetCell(1).SetCellValue(cdm.Category + "底标高"); + firstSheet.GetRow(6).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(6).GetCell(4).SetCellValue(Math.Round(cdm.BaseLevel, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(7); + firstSheet.GetRow(7).CreateCell(0); + firstSheet.GetRow(7).CreateCell(1); + firstSheet.GetRow(7).CreateCell(2); + firstSheet.GetRow(7).CreateCell(4); + firstSheet.GetRow(7).GetCell(0).SetCellValue("103"); + firstSheet.GetRow(7).GetCell(1).SetCellValue(cdm.Category + "中心点坐标X"); + firstSheet.GetRow(7).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(7).GetCell(4).SetCellValue(Math.Round(cdm.Center_X, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(8); + firstSheet.GetRow(8).CreateCell(0); + firstSheet.GetRow(8).CreateCell(1); + firstSheet.GetRow(8).CreateCell(2); + firstSheet.GetRow(8).CreateCell(4); + firstSheet.GetRow(8).GetCell(0).SetCellValue("104"); + firstSheet.GetRow(8).GetCell(1).SetCellValue(cdm.Category + "中心点坐标Y"); + firstSheet.GetRow(8).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(8).GetCell(4).SetCellValue(Math.Round(cdm.Center_Y, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(9); + firstSheet.GetRow(9).CreateCell(0); + firstSheet.GetRow(9).CreateCell(1); + firstSheet.GetRow(9).CreateCell(2); + firstSheet.GetRow(9).CreateCell(4); + firstSheet.GetRow(9).GetCell(0).SetCellValue("105"); + firstSheet.GetRow(9).GetCell(1).SetCellValue(cdm.Category + "边长X"); + firstSheet.GetRow(9).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(9).GetCell(4).SetCellValue(Math.Round(cdm.Length, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(10); + firstSheet.GetRow(10).CreateCell(0); + firstSheet.GetRow(10).CreateCell(1); + firstSheet.GetRow(10).CreateCell(2); + firstSheet.GetRow(10).CreateCell(4); + firstSheet.GetRow(10).GetCell(0).SetCellValue("106"); + firstSheet.GetRow(10).GetCell(1).SetCellValue(cdm.Category + "边长Y"); + firstSheet.GetRow(10).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(10).GetCell(4).SetCellValue(Math.Round(cdm.Width, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(11); + firstSheet.GetRow(11).CreateCell(0); + firstSheet.GetRow(11).CreateCell(1); + firstSheet.GetRow(11).CreateCell(2); + firstSheet.GetRow(11).CreateCell(4); + firstSheet.GetRow(11).GetCell(0).SetCellValue("107"); + firstSheet.GetRow(11).GetCell(1).SetCellValue(cdm.Category + "顶标高"); + firstSheet.GetRow(11).GetCell(2).SetCellValue("m"); + firstSheet.GetRow(11).GetCell(4).SetCellValue(Math.Round(cdm.TopLevel, 2, MidpointRounding.AwayFromZero)); + + firstSheet.CreateRow(12); + firstSheet.GetRow(12).CreateCell(0); + firstSheet.GetRow(12).CreateCell(1); + firstSheet.GetRow(12).CreateCell(2); + firstSheet.GetRow(12).CreateCell(4); + firstSheet.GetRow(12).GetCell(0).SetCellValue("108"); + firstSheet.GetRow(12).GetCell(1).SetCellValue(cdm.Category + "身材料"); + firstSheet.GetRow(12).GetCell(2).SetCellValue("混凝土、砖、其他"); + firstSheet.GetRow(12).GetCell(4).SetCellValue(cdm.Material); + + firstSheet.CreateRow(13); + firstSheet.GetRow(13).CreateCell(0); + firstSheet.GetRow(13).CreateCell(1); + firstSheet.GetRow(13).CreateCell(2); + firstSheet.GetRow(13).CreateCell(4); + firstSheet.GetRow(13).GetCell(0).SetCellValue("109"); + firstSheet.GetRow(13).GetCell(1).SetCellValue(cdm.Category + "材料强度(标准值)"); + firstSheet.GetRow(13).GetCell(2).SetCellValue("MPa"); + firstSheet.GetRow(13).GetCell(4).SetCellValue(cdm.Strength); + + firstSheet.CreateRow(14); + firstSheet.GetRow(14).CreateCell(0); + firstSheet.GetRow(14).CreateCell(1); + firstSheet.GetRow(14).CreateCell(2); + firstSheet.GetRow(14).CreateCell(4); + firstSheet.GetRow(14).GetCell(0).SetCellValue("110"); + firstSheet.GetRow(14).GetCell(1).SetCellValue("设计负责人"); + firstSheet.GetRow(14).GetCell(2).SetCellValue("姓名"); + firstSheet.GetRow(14).GetCell(4).SetCellValue(cdm.Designer); + + firstSheet.CreateRow(15); + firstSheet.GetRow(15).CreateCell(0); + firstSheet.GetRow(15).CreateCell(1); + //firstSheet.GetRow(15).CreateCell(2); + firstSheet.GetRow(15).CreateCell(4); + firstSheet.GetRow(15).GetCell(0).SetCellValue("111"); + firstSheet.GetRow(15).GetCell(1).SetCellValue("身份证"); + //firstSheet.GetRow(15).GetCell(2).SetCellValue(""); + firstSheet.GetRow(15).GetCell(4).SetCellValue(cdm.Iden); + + firstSheet.AutoSizeColumn(0); + firstSheet.AutoSizeColumn(1); + firstSheet.AutoSizeColumn(2); + firstSheet.AutoSizeColumn(3); + firstSheet.AutoSizeColumn(4); + + #endregion 表格 + + using (FileStream excelStream = File.Create(Path + "\\" + cdm.HcdmClass + "-" + cdm.HcdmNumber + ".xlsx")) + { + workbook.Write(excelStream); + } + } + + private void CloseWindow() + { + CurrentUI.Closed -= CurrentUI_Closed; + CurrentUI.Close(); + } + + private void CurrentUI_Closed(object sender, EventArgs e) + { + Cancel = true; + } + + public string GetName() + { + return "处理进度"; + } + } +} \ No newline at end of file diff --git a/CivilModelCreator/ProgressMonitorControl.cs b/CivilModelCreator/ProgressMonitorControl.cs new file mode 100644 index 0000000..7a52937 --- /dev/null +++ b/CivilModelCreator/ProgressMonitorControl.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CivilModelCreator +{ + internal class ProgressMonitorControl : INotifyPropertyChanged + { + public event PropertyChangedEventHandler PropertyChanged; + + public double MaxValue { get; set; } + public double CurrentValue { get; set; } + public string CurrentContext { get; set; } + + public ProgressMonitorControl() + { + //最大值 + MaxValue = 100; + //当前进度 + CurrentValue = 0; + CurrentContext = string.Empty; + } + + public void NotifyUI() + { + Type classType = this.GetType(); + if (classType != null) + { + System.Reflection.PropertyInfo[] currentProperties = classType.GetProperties(); + foreach (System.Reflection.PropertyInfo currentProperty in currentProperties) + OnPropertyChanged(currentProperty.Name); + } + } + + private void OnPropertyChanged(string targetProperty) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(targetProperty)); + } + } +} \ No newline at end of file diff --git a/CivilModelCreator/ProgressMonitorView.xaml b/CivilModelCreator/ProgressMonitorView.xaml new file mode 100644 index 0000000..97cad5e --- /dev/null +++ b/CivilModelCreator/ProgressMonitorView.xaml @@ -0,0 +1,26 @@ + + + + + + + + + +