コード例 #1
0
ファイル: Command.cs プロジェクト: x4maT/RvtVa3c
        /// <summary>
        /// Export a given 3D view to JSON using
        /// our custom exporter context.
        /// </summary>
        public void ExportView3D(
            View3D view3d,
            string filename)
        {
            AppDomain.CurrentDomain.AssemblyResolve
                += CurrentDomain_AssemblyResolve;

            Document doc = view3d.Document;

            Va3cExportContext context
                = new Va3cExportContext(doc, filename);

            CustomExporter exporter = new CustomExporter(
                doc, context);

            // Note: Excluding faces just suppresses the
            // OnFaceBegin calls, not the actual processing
            // of face tessellation. Meshes of the faces
            // will still be received by the context.

            exporter.IncludeFaces = false;

            exporter.ShouldStopOnError = false;

            exporter.Export(view3d);
        }
コード例 #2
0
        public static void ExportVa3c(string filename)
        {
            // 1. Get active document 3d view
            //local variables
            Document RvtDoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument.Document;

            // 2. Call ExportView3D from RvtVac3
            //RvtVa3c.Command.ExportView3D(RvtDoc.ActiveView as View3D, filename);

            //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            Va3cExportContext context = new Va3cExportContext(RvtDoc, filename);

            CustomExporter exporter = new CustomExporter(RvtDoc, context);

            exporter.IncludeFaces = false;

            exporter.ShouldStopOnError = false;


            try
            {
                exporter.Export(RvtDoc.ActiveView as View3D);
            }
            catch (Exception) // Autodesk.Revit.Exceptions.ExternalApplicationException
            {
                //throw;
            }

            string test = context.myjs;

            System.IO.File.WriteAllText(filename, test);
            // 3. Return Report
            //return test;
        }
コード例 #3
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title            = "场景导出到";
            sfd.Filter           = "file(*" + XObject.XData.Extension + ")|*" + XObject.XData.Extension + "";
            sfd.FilterIndex      = 2;
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == true)
            {
                string p = sfd.FileName.ToString();
                CommandData = commandData;
                Document    = commandData.Application.ActiveUIDocument.Document;
                View3D v = Get3DView(Document.ActiveView);
                if (v != null)
                {
                    XRContext = new XRContext(v, p);
                    Exporter  = new CustomExporter(Document, XRContext);
                    Exporter.Export(v);
                }
                else
                {
                    TaskDialog.Show("错误", "没找到View3D");
                }
                return(Result.Succeeded);
            }
            return(Result.Failed);
        }
コード例 #4
0
        public Result Execute(
            ExternalCommandData InCommandData,                          // contains reference to Application and View
            ref string OutCommandMessage,                               // error message to display in the failure dialog when the command returns "Failed"
            ElementSet OutElements                                      // set of problem elements to display in the failure dialog when the command returns "Failed"
            )
        {
            Autodesk.Revit.ApplicationServices.Application Application = InCommandData.Application.Application;

            if (string.Compare(Application.VersionNumber, "2018", StringComparison.Ordinal) == 0 && string.Compare(Application.SubVersionNumber, "2018.3", StringComparison.Ordinal) < 0)
            {
                string Message = string.Format("The running Revit is not supported.\nYou must use Revit 2018.3 or further updates to export.");
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (!CustomExporter.IsRenderingSupported())
            {
                string Message = "3D view rendering is not supported in the running Revit.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            UIDocument UIDoc = InCommandData.Application.ActiveUIDocument;

            if (UIDoc == null)
            {
                string Message = "You must be in a document to export.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            return(OnExecute(InCommandData, ref OutCommandMessage, OutElements));
        }
コード例 #5
0
ファイル: Command.cs プロジェクト: wrsjhhe/RevitExporter
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            UIApplication      uiapp        = commandData.Application;
            UIDocument         uidoc        = uiapp.ActiveUIDocument;
            Document           doc          = uidoc.Document;
            View3D             view         = doc.ActiveView as View3D;
            int                lodGltfValue = 8;
            GLTFExpoterContext contextGltf  = new GLTFExpoterContext(doc, lodGltfValue);

            SaveFileDialog sdial = new SaveFileDialog();

            sdial.Filter = "gltf|*.gltf|glb|*.glb";
            if (sdial.ShowDialog() == DialogResult.OK)
            {
                using (CustomExporter exporterGltf = new CustomExporter(doc, contextGltf))
                {
                    //是否包括Geom对象
                    exporterGltf.IncludeGeometricObjects = false;
                    exporterGltf.ShouldStopOnError       = true;
                    //导出3D模型
                    exporterGltf.Export(view);
                    contextGltf.Model.SaveGLB(sdial.FileName);
                    contextGltf.Model.SaveGLTF(sdial.FileName);
                }
            }
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
コード例 #6
0
        static void ExportView3D(
            Document document,
            View view3D)
        {
            MyExportContext context = new MyExportContext(
                document, "C:/tmp/test.dae");

            // Create an instance of a custom exporter by
            // giving it a document and the context.

            CustomExporter exporter = new CustomExporter(
                document, context);

            // Note: Excluding faces just excludes the calls,
            // not the actual processing of face tessellation.
            // Meshes of the faces will still be received by
            // the context.
            //exporter.IncludeFaces = false;

            exporter.ShouldStopOnError = false;

            try
            {
                exporter.Export(view3D);
            }
            catch (ExternalApplicationException ex)
            {
                Debug.Print("ExternalApplicationException "
                            + ex.Message);
            }
        }
コード例 #7
0
ファイル: Command.cs プロジェクト: stoneflyop1/RvtToObj
        public static Color DefaultColor = new Color(127, 127, 127);    //默认灰色

        /// <summary>
        /// 导出三维视图,调用CustomExporter.Export
        /// </summary>
        /// <param name="view3d"></param>
        /// <param name="filename"></param>
        public void ExportView3D(View3D view3d, string filename, AssetSet objlibraryAsset)
        {
            Document         doc      = view3d.Document;
            RvtExportContext context  = new RvtExportContext(doc, filename, objlibraryAsset);
            CustomExporter   exporter = new CustomExporter(doc, context);

            exporter.ShouldStopOnError = false;
            exporter.Export(view3d);
        }
コード例 #8
0
        internal void ExportView3D(Document document, View3D view3D)
        {
            BoldarcExportContext _exportContext = new BoldarcExportContext(document);
            CustomExporter       customExporter = new CustomExporter(document, _exportContext);

            customExporter.IncludeFaces      = false;
            customExporter.ShouldStopOnError = false;
            customExporter.Export(view3D);
        }
コード例 #9
0
        public void ExportView3D(View3D view3d, string filename, string directory, bool mode)
        {
            Document doc = view3d.Document;

            // Use our custom implementation of IExportContext as the exporter context.
            glTFExportContext ctx = new glTFExportContext(doc, filename, directory + "\\");
            // Create a new custom exporter with the context.
            CustomExporter exporter = new CustomExporter(doc, ctx);

            exporter.ShouldStopOnError = true;
            exporter.Export(view3d);
        }
コード例 #10
0
ファイル: Command.cs プロジェクト: shin820/Va3cEdit
        /// <summary>
        /// 使用我们的自定义导出器将给定的3D视图导出为JSON。
        /// </summary>
        public void ExportView3D(View3D view3d, string filename)
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Document          doc      = view3d.Document;
            HBUTExportContext context  = new HBUTExportContext(doc, filename);
            CustomExporter    exporter = new CustomExporter(doc, context);

            //注意:排除的面只是防止 OnFaceBegin 调用,而不是实际处理面细分。
            //面孔的网格仍将被上下文接收
            //exporter.IncludeFaces = false; // removed in Revit 2017

            exporter.ShouldStopOnError = false;
            exporter.Export(view3d);
        }
コード例 #11
0
ファイル: Command.cs プロジェクト: odys-z/Revit2glTF
        public glTFContainer ExportView3D(View3D view3d, string filename, string directory)
        {
            Document doc = view3d.Document;

            // Use our custom implementation of IExportContext as the exporter context.
            glTFExportContext ctx = new glTFExportContext(doc, filename, directory);
            // Create a new custom exporter with the context.
            CustomExporter exporter = new CustomExporter(doc, ctx);

            exporter.ShouldStopOnError = true;
            exporter.Export(view3d);

            return(ctx.gltfContainer);
        }
コード例 #12
0
ファイル: Command.cs プロジェクト: Zacharia2/RevitAddins
        /// <summary>
        /// //导出DAE模型,  文档、3D视图、用户设置
        /// </summary>
        /// <param name="document">Revit活动视图的文档</param>
        /// <param name="view">视图</param>
        /// <param name="userSetting">用户设置</param>
        internal void ExportView3D(Document document, Autodesk.Revit.DB.View view3D, ExportingOptions userSetting)
        {
            //将文档和导出模型设置提交给 导出上下文对象。
            MExportContext myExportContext = new MExportContext(document, userSetting);
            //TestExportContext testExportContext = new TestExportContext(document);
            //将文档和导出上下文对象提交给 autodesk默认导出对象。
            CustomExporter customExporter = new CustomExporter(document, myExportContext)
            {
                IncludeGeometricObjects = false,            //当通过导出上下文处理模型时,此标志将导出器设置为包括或排除几何对象(例如面和曲线)的输出。
                ShouldStopOnError       = false             //如果在任何一种导出方法中发生错误,此标志将指示导出过程停止或继续。
            };

            //使用CustomExporter导出模型。
            customExporter.Export(view3D);
        }
コード例 #13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc    = commandData.Application.ActiveUIDocument;
            var doc      = uidoc.Document;
            var filename = string.IsNullOrEmpty(doc.PathName)?
                           doc.Title:
                           Path.GetFileNameWithoutExtension(doc.PathName);
            var isrvt = doc.OwnerFamily != null ? false : true;

            var view = doc.ActiveView;

            if (view is View3D)
            {
                var wnd = new ConfigWnd();
                wnd.ShowDialog();
                if (wnd.DialogResult == true)
                {
                    var instancechecked = wnd.InstanceChecked;
                    var typecheced      = wnd.TypeChecked;

                    var dialog = new SaveFileDialog()
                    {
                        Filter           = "Json File(*.json)|",
                        FilterIndex      = 1,
                        RestoreDirectory = true,
                        FileName         = $"{filename}.json"
                    };
                    var result = dialog.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        var outputpath = dialog.FileName.ToString();
                        var context    = new CustomJsonContext(doc, outputpath, isrvt, instancechecked, typecheced);
                        var exporter   = new CustomExporter(doc, context)
                        {
                            ShouldStopOnError = false,
                        };
                        exporter.Export(view as View3D);
                    }
                }
            }
            else
            {
                TaskDialog.Show("Warning", "Please switch to 3D View");
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
コード例 #14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            App.Application app = uiapp.Application;
            Document        doc = uidoc.Document;

            if (null == uidoc)
            {
                message = "Please run this command in an active project document.";
                return(Result.Failed);
            }

            View3D view = doc.ActiveView as View3D;

            if (null == view)
            {
                message = "Please run this command in a 3D view.";
                return(Result.Failed);
            }

            SaveFileDialog sdial = new SaveFileDialog();

            sdial.Filter = "gltf|*.gltf|glb|*.glb";
            if (sdial.ShowDialog() == DialogResult.OK)
            {
                TestExportContext context = new TestExportContext(doc);

                using (CustomExporter exporter = new CustomExporter(doc, context))
                {
                    exporter.IncludeGeometricObjects = false;
                    exporter.Export(view);
                    context._model.SaveGLB(sdial.FileName);
                    context._model.SaveGLTF(sdial.FileName);
                }
            }
            return(Result.Succeeded);
        }
コード例 #15
0
ファイル: Command.cs プロジェクト: karthi1015/RevitSdkSamples
        private static void ExportView(Autodesk.Revit.DB.View exportableView,
                                       DisplayStyle displayStyle,
                                       bool includeGeometricObjects,
                                       bool export2DIncludingAnnotationObjects,
                                       bool export2DGeometricObjectsIncludingPatternLines,
                                       out IList <XYZ> points,
                                       out ResultsSummary resultsSummary)
        {
            TessellatedGeomAndText2DExportContext context = new TessellatedGeomAndText2DExportContext(out points);
            CustomExporter exporter = new CustomExporter(exportableView.Document, context);

            exporter.IncludeGeometricObjects                       = includeGeometricObjects;
            exporter.Export2DIncludingAnnotationObjects            = export2DIncludingAnnotationObjects;
            exporter.Export2DGeometricObjectsIncludingPatternLines = export2DGeometricObjectsIncludingPatternLines;
            exporter.ShouldStopOnError = true;
            exporter.Export(exportableView);
            exporter.Dispose();

            resultsSummary             = new ResultsSummary();
            resultsSummary.numElements = context.NumElements;
            resultsSummary.numTexts    = context.NumTexts;
            resultsSummary.texts       = context.Texts;
        }
コード例 #16
0
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using App = Autodesk.Revit.ApplicationServices;
using System.IO;
using System.Diagnostics;

namespace RevitExportObj2Gltf
{
    [Transaction(TransactionMode.Manual)]
    public class Command : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //以导出当前视图
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            App.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            //没打开文档
            if (null == doc)
            {
                message = "Please open the project.";
                return Result.Failed;
            }

            //没有打开文档
            if (null == uidoc)
            {
                message = "Please run this command in an active project document.";
                return Result.Failed;
            }

            //3D视图下
            View3D view = doc.ActiveView as View3D;
            if (null == view)
            {
                message = "Please run this command in a 3D view.";
                return Result.Failed;
            }


            //保存导出的文件 
            SaveFileDialog sdial = new SaveFileDialog();
            sdial.Filter = "gltf|*.gltf|glb|*.glb";
            if (sdial.ShowDialog() == DialogResult.OK)
            {
                RevitExportObj2Gltf contextObj = new RevitExportObj2Gltf(doc, sdial.FileName);
                MyGltfExportContext contextGltf = new MyGltfExportContext(doc);
                //拿到revit的doc  CustomExporter 用户自定义导出
                using (CustomExporter exporterObj = new CustomExporter(doc, contextObj))
                {
                    //是否包括Geom对象
                    exporterObj.IncludeGeometricObjects = false;
                    exporterObj.ShouldStopOnError = true;
                    //导出3D模型
                    exporterObj.Export(view);
                }  
                
                using (CustomExporter exporterGltf = new CustomExporter(doc, contextGltf))
                {
                    //是否包括Geom对象
                    exporterGltf.IncludeGeometricObjects = false;
                    exporterGltf.ShouldStopOnError = true;
                    //导出3D模型
                    exporterGltf.Export(view);
                    contextGltf._model.SaveGLB(sdial.FileName);
                    contextGltf._model.SaveGLTF(sdial.FileName);
                }

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();//启动程序
                          //使用gltf pipeline命令行工具
                          //向cmd窗口发送输入信息  (node.js已经是配置好了系统环境变量)
                          //string str = @"cd D:\cmder";
                          //p.StandardInput.WriteLine(str);

                ////obj2gltf -i model.obj -o model.gltf  
                ////obj转gltf
                //string obj2GltfStr = string.Format("obj2gltf -i {0} -o {1}", Path.GetDirectoryName(sdial.FileName) + "\\" +
                //    Path.GetFileNameWithoutExtension(sdial.FileName) + ".obj", Path.GetDirectoryName(sdial.FileName) + "\\" + Path.GetFileNameWithoutExtension(sdial.FileName) + ".gltf");
                //p.StandardInput.WriteLine(obj2GltfStr);
                //Debug.Print("obj2gltf successful.");

                //运用Draco算法将GLB压缩
                string glbName = Path.GetFileNameWithoutExtension(sdial.FileName) + "(Draco)" + ".glb";
                string glbstr = string.Format("gltf-pipeline.cmd gltf-pipeline -i {0} -o {1}", sdial.FileName, Path.GetDirectoryName(sdial.FileName) + "\\" + glbName);
                p.StandardInput.WriteLine(glbstr);

                //gltf-pipeline.c md gltf-pipeline -i model.gltf -o modelDraco.gltf -d
                //运用Draco算法将GLTF压缩
                string gltfDracoName = Path.GetFileNameWithoutExtension(sdial.FileName) + "(Draco)" + ".gltf";
                string gltfDraco = string.Format("gltf-pipeline.cmd gltf-pipeline -i {0} -o {1} -d", sdial.FileName, Path.GetDirectoryName(sdial.FileName) + "\\" + gltfDracoName);
                p.StandardInput.WriteLine(gltfDraco);

                p.StandardInput.AutoFlush = true;
                p.StandardInput.WriteLine("exit");

                //获取cmd窗口的输出信息
                string output = p.StandardOutput.ReadToEnd();
                MessageBox.Show(output);

            }
            return Result.Succeeded;

        }
    }
}


コード例 #17
0
        public override Result OnExecute(ExternalCommandData InCommandData, ref string OutCommandMessage, ElementSet OutElements)
        {
            UIDocument UIDoc      = InCommandData.Application.ActiveUIDocument;
            Document   Doc        = UIDoc.Document;
            View3D     ActiveView = Doc.ActiveView as View3D;

            if (ActiveView == null)
            {
                string Message = "You must be in a 3D view to export.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (ActiveView.IsTemplate || !ActiveView.CanBePrinted)
            {
                string Message = "The active 3D view cannot be exported.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            Debug.Assert(FDirectLink.Get() != null);

            // Holding ctrl will force full sync.
            if (FDirectLink.Get().SyncCount > 0 && (System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                FDirectLink.DestroyInstance(FDirectLink.Get(), InCommandData.Application.Application);
                FDirectLink.ActivateInstance(Doc);
            }

            FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(
                InCommandData.Application.Application,
                Doc,
                null,
                new DatasmithRevitExportOptions(Doc),
                FDirectLink.Get());

            // Export the active 3D View to the given Unreal Datasmith file.
            using (CustomExporter Exporter = new CustomExporter(Doc, ExportContext))
            {
                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    Exporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    Exporter.ShouldStopOnError = true;

#if REVIT_API_2020
                    Exporter.Export(ActiveView as Autodesk.Revit.DB.View);
#else
                    Exporter.Export(ActiveView);
#endif
                }
                catch (System.Exception exception)
                {
                    OutCommandMessage = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace);
                    MessageBox.Show(OutCommandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(Result.Failed);
                }
                finally
                {
                    if (ExportContext.GetMessages().Count > 0)
                    {
                        string Messages = string.Join($"{System.Environment.NewLine}", ExportContext.GetMessages());
                        DatasmithRevitApplication.SetExportMessages(Messages);
                    }
                }
            }

            return(Result.Succeeded);
        }
コード例 #18
0
ファイル: COVERToolbar.cs プロジェクト: nixz/covise
        /// <summary>
        /// The main (and only :-) command 
        /// of our export sample
        /// </summary>
        public Result Execute(
            ExternalCommandData data,
            ref string msg,
            ElementSet elements)
        {
            // This command requires an active document

               UIDocument uidoc = data.Application
             .ActiveUIDocument;

               if (uidoc == null)
               {
               msg = "Please run this command in an active project document.";
               return Result.Failed;
               }

               Document doc = uidoc.Document;

               // Collect all 3D views in the document
               // (there must be at least one). The collection
               // will be listed in the option dialog for the
               // user to choose the ones to include in the
               // export.
               List<View3D> views = new List<View3D>(
            new FilteredElementCollector(doc)
              .OfClass(typeof(View3D))
              .Cast<View3D>()
              .Where<View3D>(v =>
            v.CanBePrinted && !v.IsTemplate));

               int n = views.Count;

               if (0 == n)
               {
               msg = "There are no 3D views in the document!";
               return Result.Failed;
               }

               // Initiate output with default path to
               // MyDocuments and the current document name

               string defaultName = Path.ChangeExtension(
             doc.Title, ".xml");

               string defaultFolder = System.Environment
             .GetFolderPath(
               Environment.SpecialFolder.MyDocuments);

               // Instantiate our custom context

               ExportContext context = new ExportContext(doc);

               // Instantiate a custom exporter with output
               // context given as the argument

               using (CustomExporter exporter
             = new CustomExporter(doc, context))
               {

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

               foreach (View3D v in views)
               {
                   viewsToExport.Add(v.Id);
               }
               try
               {
                   exporter.Export(viewsToExport);
               }
               catch (System.Exception ex)
               {
                   msg = "Exception: " + ex.Message;
                   return Result.Failed;
               }
               }
               return Result.Succeeded;
        }
コード例 #19
0
        // Implement the interface to execute the command.
        public Result Execute(
            ExternalCommandData InCommandData,                 // contains reference to Application and View
            ref string OutCommandMessage,                      // error message to display in the failure dialog when the command returns "Failed"
            ElementSet OutElements                             // set of problem elements to display in the failure dialog when the command returns "Failed"
            )
        {
            Autodesk.Revit.ApplicationServices.Application Application = InCommandData.Application.Application;

            if (string.Compare(Application.VersionNumber, "2018", StringComparison.Ordinal) == 0 && string.Compare(Application.SubVersionNumber, "2018.3", StringComparison.Ordinal) < 0)
            {
                string Message = string.Format("The running Revit is not supported.\nYou must use Revit 2018.3 or further updates to export.");
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (!CustomExporter.IsRenderingSupported())
            {
                string Message = "3D view rendering is not supported in the running Revit.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            UIDocument UIDoc = InCommandData.Application.ActiveUIDocument;

            if (UIDoc == null)
            {
                string Message = "You must be in a document to export.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            Document Doc = UIDoc.Document;

            string DocumentPath = Doc.PathName;

            if (string.IsNullOrWhiteSpace(DocumentPath))
            {
                string message = "Your document must be saved on disk before exporting.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            bool ExportActiveViewOnly = true;

            // Retrieve the Unreal Datasmith export options.
            DatasmithRevitExportOptions ExportOptions = new DatasmithRevitExportOptions(Doc);

            if ((System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                if (ExportOptions.ShowDialog() != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }
                ExportActiveViewOnly = false;
            }

            // Generate file path for each view.
            Dictionary <ElementId, string> FilePaths = new Dictionary <ElementId, string>();
            List <View3D> ViewsToExport = new List <View3D>();

            if (ExportActiveViewOnly)
            {
                View3D ActiveView = Doc.ActiveView as View3D;

                if (ActiveView == null)
                {
                    string Message = "You must be in a 3D view to export.";
                    MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                if (ActiveView.IsTemplate || !ActiveView.CanBePrinted)
                {
                    string Message = "The active 3D view cannot be exported.";
                    MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                string ViewFamilyName = ActiveView.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", "");
                string FileName       = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{ActiveView.Name}.udatasmith", @"\s+", "_");

                SaveFileDialog Dialog = new SaveFileDialog();

                Dialog.Title            = DIALOG_CAPTION;
                Dialog.InitialDirectory = Path.GetDirectoryName(DocumentPath);
                Dialog.FileName         = FileName;
                Dialog.DefaultExt       = "udatasmith";
                Dialog.Filter           = "Unreal Datasmith|*.udatasmith";
                Dialog.CheckFileExists  = false;
                Dialog.CheckPathExists  = true;
                Dialog.AddExtension     = true;
                Dialog.OverwritePrompt  = true;

                if (Dialog.ShowDialog() != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }

                string FilePath = Dialog.FileName;

                if (string.IsNullOrWhiteSpace(FilePath))
                {
                    string message = "The given Unreal Datasmith file name is blank.";
                    MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                FilePaths.Add(ActiveView.Id, FilePath);
                ViewsToExport.Add(ActiveView);
            }
            else
            {
                string SavePath;
                using (var FBD = new FolderBrowserDialog())
                {
                    FBD.ShowNewFolderButton = true;
                    DialogResult result = FBD.ShowDialog();

                    if (result != DialogResult.OK || string.IsNullOrWhiteSpace(FBD.SelectedPath))
                    {
                        return(Result.Cancelled);
                    }

                    SavePath = FBD.SelectedPath;
                }

                foreach (var View in ExportOptions.Selected3DViews)
                {
                    string ViewFamilyName = View.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", "");
                    string FileName       = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{View.Name}.udatasmith", @"\s+", "_");
                    FilePaths.Add(View.Id, Path.Combine(SavePath, FileName));
                    ViewsToExport.Add(View);
                }
            }

            // Prevent user interaction with the active 3D view to avoid the termination of the custom export,
            // without Revit providing any kind of internal or external feedback.
            EnableViewWindow(InCommandData.Application, false);

            // Create a custom export context for command Export to Unreal Datasmith.
            FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(InCommandData.Application.Application, Doc, FilePaths, ExportOptions);

            // Export the active 3D View to the given Unreal Datasmith file.
            using (CustomExporter Exporter = new CustomExporter(Doc, ExportContext))
            {
                // Add a progress bar callback.
                // application.ProgressChanged += exportContext.HandleProgressChanged;

                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    Exporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    Exporter.ShouldStopOnError = true;

                    // Initiate the export process for all 3D views.
                    foreach (var view in ViewsToExport)
                    {
#if REVIT_API_2020
                        Exporter.Export(view as Autodesk.Revit.DB.View);
#else
                        Exporter.Export(view);
#endif
                    }
                }
                catch (System.Exception exception)
                {
                    OutCommandMessage = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace);
                    MessageBox.Show(OutCommandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(Result.Failed);
                }
                finally
                {
                    // Remove the progress bar callback.
                    // application.ProgressChanged -= exportContext.HandleProgressChanged;

                    // Restore user interaction with the active 3D view.
                    EnableViewWindow(InCommandData.Application, true);

                    if (ExportContext.GetMessages().Count > 0)
                    {
                        string Messages = string.Join($"{System.Environment.NewLine}", ExportContext.GetMessages());
                        DatasmithRevitApplication.ShowExportMessages(Messages);
                    }
                }
            }

            return(Result.Succeeded);
        }
コード例 #20
0
        public static void Export3DViewsToDatasmith(Document InDocument, string InOutputPath, List <int> InViewIds, int InTesselation = 8)
        {
            if (InDocument == null)
            {
                Console.WriteLine("Invalid document.");
                return;
            }

            Autodesk.Revit.ApplicationServices.Application App = InDocument.Application;

            if (string.Compare(App.VersionNumber, "2018", StringComparison.Ordinal) == 0 && string.Compare(App.SubVersionNumber, "2018.3", StringComparison.Ordinal) < 0)
            {
                string Message = string.Format("The running Revit is not supported.\nYou must use Revit 2018.3 or further updates to export.");
                Console.WriteLine(Message);
                return;
            }

            try
            {
                // Validate the provided path
                InOutputPath = Path.GetFullPath(InOutputPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            if (!CustomExporter.IsRenderingSupported())
            {
                string Message = "3D view rendering is not supported in the running Revit.";
                Console.WriteLine(Message);
                return;
            }

            string DocumentPath = InDocument.PathName;

            Dictionary <ElementId, string> FilePaths = new Dictionary <ElementId, string>();
            List <View3D> ExportViews = new List <View3D>();

            foreach (var Id in InViewIds)
            {
                View3D View = InDocument.GetElement(new ElementId(Id)) as View3D;
                if (View != null && !View.IsTemplate && View.CanBePrinted)
                {
                    ExportViews.Add(View);
                    // Generate file path for each view.
                    string FileName = Regex.Replace($"{View.Name}.udatasmith", @"\s+", "_");
                    FilePaths.Add(View.Id, Path.Combine(InOutputPath, FileName));
                }
            }

            // Retrieve the Unreal Datasmith export options.
            DatasmithRevitExportOptions ExportOptions = new DatasmithRevitExportOptions(InDocument);

            // Create a custom export context for command Export to Unreal Datasmith.
            FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(
                App,
                InDocument,
                FilePaths,
                ExportOptions,
                null);

            // Clamp tesselation parameter to a valid range.
            ExportContext.LevelOfTessellation = Math.Min(Math.Max(InTesselation, -1), 15);

            using (CustomExporter Exporter = new CustomExporter(InDocument, ExportContext))
            {
                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    Exporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    Exporter.ShouldStopOnError = true;

                    // Initiate the export process for all 3D views.
                    foreach (var View in ExportViews)
                    {
#if REVIT_API_2020
                        Exporter.Export(View as Autodesk.Revit.DB.View);
#else
                        Exporter.Export(View);
#endif
                    }
                }
                catch (System.Exception InException)
                {
                    string Message = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", InException.Message, InException.StackTrace);
                    Console.WriteLine(Message);
                    return;
                }
            }
        }
コード例 #21
0
        bool IExportControl.Run()
        {
            var filePath = txtTargetPath.Text;

            if (string.IsNullOrEmpty(filePath))
            {
                ShowMessageBox(Strings.MessageSelectOutputPathFirst);
                return(false);
            }

#if !R2014
            if (CustomExporter.IsRenderingSupported() == false &&
                ShowConfirmBox(Strings.ExportWillFailBecauseMaterialLib) == false)
            {
                return(false);
            }
#endif

            if (File.Exists(filePath) &&
                ShowConfirmBox(Strings.OutputFileExistedWarning) == false)
            {
                return(false);
            }

            var homePath = InnerApp.GetHomePath();
            if (InnerApp.CheckHomeFolder(homePath) == false &&
                ShowConfirmBox(Strings.HomeFolderIsInvalid) == false)
            {
                return(false);
            }

            var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo;
            if (visualStyle != null)
            {
                foreach (var p in visualStyle.Features)
                {
                    _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value);
                }
            }

            var levelOfDetail = (cbLevelOfDetail.SelectedItem as ComboItemInfo) ?? _LevelOfDetailDefault;


            #region 更新界面选项到 _Features

            void SetFeature(FeatureType featureType, bool selected)
            {
                _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected);
            }

            SetFeature(FeatureType.Export2DViewAll, rb2DViewsAll.Checked);
            SetFeature(FeatureType.Export2DViewOnlySheet, rb2DViewsOnlySheet.Checked);

            SetFeature(FeatureType.GenerateThumbnail, cbGenerateThumbnail.Checked);
            //SetFeature(FeatureType.GenerateElementData, cbGeneratePropDbJson.Checked);
            SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked);
            SetFeature(FeatureType.GenerateLeaflet, cbGenerateLeaflet.Checked);
            SetFeature(FeatureType.GenerateDwgDrawing, cbGenerateDwg.Checked);

            SetFeature(FeatureType.ExportGrids, cbIncludeGrids.Checked);
            SetFeature(FeatureType.ExportRooms, cbIncludeRooms.Checked);

            SetFeature(FeatureType.ExcludeProperties, cbExcludeElementProperties.Checked);
            SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked);
            SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked);
            SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked);

            SetFeature(FeatureType.ConsolidateGroup, cbConsolidateArrayGroup.Checked);
            SetFeature(FeatureType.ConsolidateAssembly, cbConsolidateAssembly.Checked);

            SetFeature(FeatureType.UseLevelCategory, rbGroupByLevelDefault.Checked);
            SetFeature(FeatureType.UseNwLevelCategory, rbGroupByLevelNavisworks.Checked);
            SetFeature(FeatureType.UseBoundLevelCategory, rbGroupByLevelBoundingBox.Checked);

            SetFeature(FeatureType.UseCurrentViewport, cbUseCurrentViewport.Checked);

            #endregion

            var isCanncelled = false;
            using (var session = LicenseConfig.Create())
            {
                if (session.IsValid == false)
                {
                    LicenseConfig.ShowDialog(session, ParentForm);
                    return(false);
                }

                #region 保存设置

                var config = _LocalConfig;
                config.Features       = _Features.Where(x => x.Selected).Select(x => x.Type).ToList();
                config.LastTargetPath = txtTargetPath.Text;
                config.VisualStyle    = visualStyle?.Key;
                config.LevelOfDetail  = levelOfDetail?.Value ?? -1;
                _Config.Save();

                #endregion

                var sw = Stopwatch.StartNew();
                try
                {
                    var setting = new ExportSetting();
                    setting.LevelOfDetail      = config.LevelOfDetail;
                    setting.ExportType         = ExportType.Zip;
                    setting.OutputPath         = config.LastTargetPath;
                    setting.Features           = _Features.Where(x => x.Selected && x.Enabled).Select(x => x.Type).ToList();
                    setting.SelectedElementIds = _ElementIds?.Where(x => x.Value).Select(x => x.Key).ToList();
                    setting.Selected2DViewIds  = rb2DViewCustom.Checked ? _ViewIds : null;
                    setting.Oem = LicenseConfig.GetOemInfo(homePath);

                    var hasSuccess = false;
                    using (var progress = new ProgressExHelper(this.ParentForm, Strings.MessageExporting))
                    {
                        var cancellationToken = progress.GetCancellationToken();

#if !DEBUG
                        //在有些 Revit 会遇到时不时无法转换的问题,循环多次重试, 应该可以成功
                        for (var i = 0; i < 5; i++)
                        {
                            try
                            {
                                StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken);
                                hasSuccess = true;
                                break;
                            }
                            catch (Autodesk.Revit.Exceptions.ExternalApplicationException)
                            {
                                Application.DoEvents();
                            }
                            catch (IOException ex)
                            {
                                ShowMessageBox("文件保存失败: " + ex.Message);
                                hasSuccess = true;
                                break;
                            }
                        }
#endif

                        //如果之前多次重试仍然没有成功, 这里再试一次,如果再失败就会给出稍后重试的提示
                        if (hasSuccess == false)
                        {
                            StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken);
                        }

                        isCanncelled = cancellationToken.IsCancellationRequested;
                    }

                    sw.Stop();
                    var ts = sw.Elapsed;
                    ExportDuration = new TimeSpan(ts.Days, ts.Hours, ts.Minutes, ts.Seconds); //去掉毫秒部分

                    Debug.WriteLine(Strings.MessageOperationSuccessAndElapsedTime, ExportDuration);

                    if (isCanncelled == false)
                    {
                        {
                            ShowMessageBox(string.Format(Strings.MessageExportSuccess, ExportDuration));
                        }
                    }
                }
                catch (IOException ex)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(string.Format(Strings.MessageFileSaveFailure, ex.Message));
                }
                catch (Autodesk.Revit.Exceptions.ExternalApplicationException)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(Strings.MessageOperationFailureAndTryLater);
                }
                catch (Exception ex)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(ex.ToString());
                }
            }

            return(isCanncelled == false);
        }
コード例 #22
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // This command requires an active document

            if (null == uidoc)
            {
                message = "Please run this command in an active project document.";
                return(Result.Failed);
            }

            View3D view = doc.ActiveView as View3D;

            if (null == view)
            {
                message = "Please run this command in a 3D view.";
                return(Result.Failed);
            }

            // Instantiate our custom context

            ExportContextAdnMesh context
                = new ExportContextAdnMesh(doc);

            // Instantiate a custom exporter with it

            using (CustomExporter exporter
                       = new CustomExporter(doc, context))
            {
                // Tell the exporter whether we need face info.
                // If not, it is better to exclude them, since
                // processing faces takes significant time and
                // memory. In any case, tessellated polymeshes
                // can be exported (and will be sent to the
                // context). Excluding faces just excludes the calls,
                // not the actual processing of face tessellation.
                // Meshes of the faces will still be received by
                // the context.

                exporter.IncludeFaces = false;

                exporter.Export(view);
            }

            // Save ADN mesh data in JSON format

            StreamWriter s = new StreamWriter(
                "C:/tmp/test.json");

            s.Write("[");

            int i = 0;

            foreach (AdnMeshData d in context.MeshData)
            {
                if (0 < i)
                {
                    s.Write(',');
                }

                s.Write(d.ToJson());

                ++i;
            }

            s.Write("\n]\n");
            s.Close();

            return(Result.Succeeded);
        }
コード例 #23
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //getting current document from command data
            UIApplication uiapp   = commandData.Application;
            UIDocument    uidoc   = uiapp.ActiveUIDocument;
            Document      doc     = uidoc.Document;
            string        docName = doc.Title;

            //filter elements visible in view
            if (doc.ActiveView is View3D)
            {
                RevitToGLTF.RevitToGLTFContext context = new RevitToGLTF.RevitToGLTFContext(doc, @"C:\Users\xpeng\Desktop\4D Model\revit2glTF.gltf");
                CustomExporter glTFExporter            = new CustomExporter(doc, context);

                glTFExporter.ShouldStopOnError = false;
                glTFExporter.Export(doc.ActiveView as View3D);
                //ElementCategoryFilter titleBlockFilter = new ElementCategoryFilter(BuiltInCategory.OST_TitleBlocks);
                //ElementCategoryFilter levelFilter = new ElementCategoryFilter(BuiltInCategory.OST_Levels, true);
                //ElementCategoryFilter genericAnnoFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericAnnotation);
                //ElementCategoryFilter detailFilter = new ElementCategoryFilter(BuiltInCategory.OST_DetailComponents);

                //FilteredElementCollector allElementsInView = new FilteredElementCollector(doc, doc.ActiveView.Id)
                //                                                .WhereElementIsNotElementType()
                //                                                .WherePasses(levelFilter);


                //IList elementsInView = (IList)allElementsInView.ToElements();
                //foreach (Element e in allElementsInView)
                //{
                //    if (e.Category != null)
                //    {
                //        string category = e.Category.Name;

                //        if (category != "Title Blocks" && category != "Generic Annotations" && category != "Detail Items")
                //        {
                //            MessageBox.Show(category);
                //            Reference reference = new Reference(e);
                //            var pri = e.GetGeometryObjectFromReference(reference);


                //        }
                //    }



                //}
            }
            else
            {
                MessageBox.Show("Select a 3D view to export GLTF");
            }

            //Convert Revit Elements

            //Create one GLTF object
            GLTF obj = GLTFUtilts.Convert2GLTF();



            var jso = JsonConvert.SerializeObject(obj);

            //File.WriteAllText(@"C:\Users\xpeng\Desktop\4D Model\revit2glTF.json", jso);

            using (StreamWriter file = File.CreateText(@"C:\Users\xpeng\Desktop\4D Model\revit2glTF.gltf"))
            {
                JsonSerializer serializer = new JsonSerializer
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
                serializer.Serialize(file, obj);
            }

            //@TODO generate blob/binary and return index of section
            //@TODO convert object/geometry into binary format
            MessageBox.Show(obj.nodes[0].name);
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
コード例 #24
0
        public void Export()
        {
#if !R2014
            if (CustomExporter.IsRenderingSupported() == false)
            {
                var message = @"检测到当前 Revit 实例对数据导出的支持存在问题, 原因可能是材质库未正确安装。 本次操作可能无法成功执行, 确定要继续吗?";
                if (MessageBox.Show(this, message, Text,
                                    MessageBoxButtons.OKCancel,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) != DialogResult.OK)
                {
                    return;
                }
            }
#endif
            var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo;

            if (visualStyle != null)
            {
                foreach (var p in visualStyle.Features)
                {
                    _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value);
                }
            }

            var levelOfDetail = (cbLevelOfDetail.SelectedItem as ComboItemInfo) ?? _LevelOfDetailDefault;

            #region 更新界面选项到 _Features

            void SetFeature(FeatureType featureType, bool selected)
            {
                _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected);
            }

            SetFeature(FeatureType.Export2DViewAll, rb2DViewsAll.Checked);
            SetFeature(FeatureType.Export2DViewOnlySheet, rb2DViewsOnlySheet.Checked);

            SetFeature(FeatureType.GenerateThumbnail, cbGenerateThumbnail.Checked);
            SetFeature(FeatureType.GenerateElementData, cbGeneratePropDbJson.Checked);
            SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked);

            SetFeature(FeatureType.ExportGrids, cbIncludeGrids.Checked);
            SetFeature(FeatureType.ExportRooms, cbIncludeRooms.Checked);

            SetFeature(FeatureType.ExcludeProperties, cbExcludeElementProperties.Checked);
            SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked);
            SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked);
            SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked);

            SetFeature(FeatureType.ConsolidateGroup, cbConsolidateArrayGroup.Checked);
            SetFeature(FeatureType.ConsolidateAssembly, cbConsolidateAssembly.Checked);

            SetFeature(FeatureType.UseLevelCategory, rbGroupByLevelDefault.Checked);
            SetFeature(FeatureType.UseNwLevelCategory, rbGroupByLevelNavisworks.Checked);
            SetFeature(FeatureType.UseBoundLevelCategory, rbGroupByLevelBoundingBox.Checked);

            SetFeature(FeatureType.UseCurrentViewport, cbUseCurrentViewport.Checked);

            #endregion

            var isCanncelled = false;

            using (var session = App.CreateSession(Application.licenseKey))
            {
                if (session.IsValid == false)
                {
                    new Plugin_manage().ShowDialog();

                    return;
                }

                #region 保存设置

                var config = _Config.Local;
                config.Features       = _Features.Where(x => x.Selected).Select(x => x.Type).ToList();
                config.LastTargetPath = Path.Combine(TempPath, modelName + ".svfzip");
                config.VisualStyle    = visualStyle?.Key;
                config.LevelOfDetail  = levelOfDetail?.Value ?? -1;
                _Config.Save();

                #endregion

                var features = _Features.Where(x => x.Selected && x.Enabled).ToDictionary(x => x.Type, x => true);

                using (var progress = new ProgressHelper(this, Strings.MessageExporting))
                {
                    var cancellationToken = progress.GetCancellationToken();
                    StartExport(_UIDocument, _View, config, ExportType.Zip, null, features, false, progress.GetProgressCallback(), cancellationToken);
                    isCanncelled = cancellationToken.IsCancellationRequested;
                }

                if (isCanncelled == false)
                {
                    var t = new Thread(UploadFile);
                    t.IsBackground = false;
                    t.Start();

                    Enabled = false;

                    progressBar1.Value = 50;
                }
            }
        }
コード例 #25
0
ファイル: CmdExporter.cs プロジェクト: yangbing007/TwglExport
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication           uiapp = commandData.Application;
            UIDocument              uidoc = uiapp.ActiveUIDocument;
            Document                doc   = uidoc.Document;
            Selection               sel   = uidoc.Selection;
            ICollection <ElementId> ids   = sel.GetElementIds();

            if (1 != ids.Count)
            {
                message = "Please select an element to export to TWGL.";
                return(Result.Failed);
            }

            Element e = null;

            foreach (ElementId id in ids)
            {
                e = doc.GetElement(id);
            }

            // Determine bounding box in order to translate
            // all coordinates to bounding box midpoint.

            BoundingBoxXYZ bb    = e.get_BoundingBox(null);
            XYZ            pmin  = bb.Min;
            XYZ            pmax  = bb.Max;
            XYZ            vsize = pmax - pmin;
            XYZ            pmid  = pmin + 0.5 * vsize;

            using (TransactionGroup tg
                       = new TransactionGroup(doc))
            {
                // Create 3D view

                ViewFamilyType viewType
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .OfType <ViewFamilyType>()
                      .FirstOrDefault(x => x.ViewFamily
                                      == ViewFamily.ThreeDimensional);

                View3D view;

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create 3D View");

                    view = View3D.CreateIsometric(
                        doc, viewType.Id);

                    t.Commit();

                    view.IsolateElementTemporary(e.Id);

                    t.Commit();

                    TwglExportContext context
                        = new TwglExportContext(doc, pmid);

                    CustomExporter exporter
                        = new CustomExporter(doc, context);

                    // Note: Excluding faces just suppresses the
                    // OnFaceBegin calls, not the actual processing
                    // of face tessellation. Meshes of the faces
                    // will still be received by the context.

                    exporter.IncludeFaces = false;

                    exporter.ShouldStopOnError = false;

                    exporter.Export(view);

                    // Scale the vertices to a [-1,1] cube
                    // centered around the origin. Translation
                    // to the origin was already performed above.

                    double scale = 2.0 / Util.FootToMm(
                        Util.MaxCoord(vsize));

                    string json_geometry_data
                        = CmdElemGeom.GetJsonGeometryData(scale,
                                                          context.FaceIndices, context.FaceVertices,
                                                          context.FaceNormals);

                    CmdElemGeom.DisplayWgl(json_geometry_data);
                }
                // Roll back entire operation.

                //tg.Commit();
            }
            return(Result.Succeeded);
        }
コード例 #26
0
        /// <summary>
        /// The main (and only :-) command
        /// of our export sample
        /// </summary>
        public Result Execute(
            ExternalCommandData data,
            ref string msg,
            ElementSet elements)
        {
            // This command requires an active document

            UIDocument uidoc = data.Application
                               .ActiveUIDocument;

            if (uidoc == null)
            {
                msg = "Please run this command in an active project document.";
                return(Result.Failed);
            }

            Document doc = uidoc.Document;

            // Collect all 3D views in the document
            // (there must be at least one). The collection
            // will be listed in the option dialog for the
            // user to choose the ones to include in the
            // export.
            List <View3D> views = new List <View3D>(
                new FilteredElementCollector(doc)
                .OfClass(typeof(View3D))
                .Cast <View3D>()
                .Where <View3D>(v =>
                                v.CanBePrinted && !v.IsTemplate));

            int n = views.Count;

            if (0 == n)
            {
                msg = "There are no 3D views in the document!";
                return(Result.Failed);
            }

            // Initiate output with default path to
            // MyDocuments and the current document name

            string defaultName = Path.ChangeExtension(
                doc.Title, ".xml");

            string defaultFolder = System.Environment
                                   .GetFolderPath(
                Environment.SpecialFolder.MyDocuments);



            // Instantiate our custom context

            ExportContext context = new ExportContext(doc);

            // Instantiate a custom exporter with output
            // context given as the argument

            using (CustomExporter exporter
                       = new CustomExporter(doc, context))
            {
                List <ElementId> viewsToExport = new List <ElementId>();

                foreach (View3D v in views)
                {
                    viewsToExport.Add(v.Id);
                }
                try
                {
                    exporter.Export(viewsToExport);
                }
                catch (System.Exception ex)
                {
                    msg = "Exception: " + ex.Message;
                    return(Result.Failed);
                }
            }
            return(Result.Succeeded);
        }
コード例 #27
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //以导出当前视图
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            App.Application app = uiapp.Application;
            Document        doc = uidoc.Document;

            //没打开文档
            if (null == doc)
            {
                message = "Please open the project.";
                return(Result.Failed);
            }
            //没有打开文档
            if (null == uidoc)
            {
                message = "Please run this command in an active project document.";
                return(Result.Failed);
            }
            //3D视图下
            View3D view = doc.ActiveView as View3D;

            if (null == view)
            {
                message = "Please run this command in a 3D view.";
                return(Result.Failed);
            }
            //保存导出的文件
            SaveFileDialog sdial = new SaveFileDialog();

            sdial.Filter = "gltf|*.gltf|glb|*.glb";
            if (sdial.ShowDialog() == DialogResult.OK)
            {
                //默认值lod为等级8 (达到减面的效果 可以导出高模瑜低模)
                int lodGltfValue = 8;
                int lodObjValue  = 8;
                RevitExportObj2Gltf contextObj  = new RevitExportObj2Gltf(doc, sdial.FileName, lodObjValue);
                MyGltfExportContext contextGltf = new MyGltfExportContext(doc, lodGltfValue);
                //拿到revit的doc  CustomExporter 用户自定义导出
                using (CustomExporter exporterObj = new CustomExporter(doc, contextObj))
                {
                    //是否包括Geom对象
                    exporterObj.IncludeGeometricObjects = false;
                    exporterObj.ShouldStopOnError       = true;
                    //导出3D模型
                    exporterObj.Export(view);
                }
                using (CustomExporter exporterGltf = new CustomExporter(doc, contextGltf))
                {
                    //是否包括Geom对象
                    exporterGltf.IncludeGeometricObjects = false;
                    exporterGltf.ShouldStopOnError       = true;
                    //导出3D模型
                    exporterGltf.Export(view);
                    contextGltf._model.SaveGLB(sdial.FileName);
                    contextGltf._model.SaveGLTF(sdial.FileName);
                }
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName        = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;
                //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;
                //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;
                //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;       //不显示程序窗口
                p.Start();
                //启动程序
                //使用gltf pipeline命令行工具
                //向cmd窗口发送输入信息  (node.js已经是配置好了系统环境变量)
                //string str = @"cd D:\cmder";
                //p.StandardInput.WriteLine(str);
                ////obj2gltf -i model.obj -o model.gltf
                ////obj转gltf
                //string obj2GltfStr = string.Format("obj2gltf -i {0} -o {1}", Path.GetDirectoryName(sdial.FileName) + "\\" +
                //    Path.GetFileNameWithoutExtension(sdial.FileName) + ".obj", Path.GetDirectoryName(sdial.FileName) + "\\" + Path.GetFileNameWithoutExtension(sdial.FileName) + ".gltf");
                //p.StandardInput.WriteLine(obj2GltfStr);
                //Debug.Print("obj2gltf successful.");
                //运用Draco算法将GLB压缩
                string glbName = Path.GetFileNameWithoutExtension(sdial.FileName) + "(Draco)" + ".glb";
                string glbstr  = string.Format("gltf-pipeline.cmd gltf-pipeline -i {0} -o {1}", sdial.FileName, Path.GetDirectoryName(sdial.FileName) + "\\" + glbName);
                p.StandardInput.WriteLine(glbstr);
                //gltf-pipeline.c md gltf-pipeline -i model.gltf -o modelDraco.gltf -d
                //运用Draco算法将GLTF压缩
                string gltfDracoName = Path.GetFileNameWithoutExtension(sdial.FileName) + "(Draco)" + ".gltf";
                string gltfDraco     = string.Format("gltf-pipeline.cmd gltf-pipeline -i {0} -o {1} -d", sdial.FileName, Path.GetDirectoryName(sdial.FileName) + "\\" + gltfDracoName);
                p.StandardInput.WriteLine(gltfDraco);
                p.StandardInput.AutoFlush = true;
                p.StandardInput.WriteLine("exit");
                //获取cmd窗口的输出信息
                string output = p.StandardOutput.ReadToEnd();
                MessageBox.Show(output);
            }
            return(Result.Succeeded);
        }
コード例 #28
0
        public bool Export(AssetSet appearanceAssetSet, View3D view, ExportSetting setting, out Exception ex)
        {
            ex = new Exception();

            try
            {
                ConvertEntity converter = new ConvertEntity();
                converter.ExportSetting = setting;
                if (setting.SystemSetting.IsExportRebar)
                {
                    converter.Rebars = Tools.GetRebaresInDocument(view.Document);
                }
                else
                {
                    ElementColorOverride colorOverride = new ElementColorOverride();
                    if (!setting.SystemSetting.IsOriginMaterial && !view.Document.IsFamilyDocument)
                    {
                        colorOverride.ArrangeElemlentColor(view.Document, view);
                    }

                    RevitEnvironmentSetting envSetting = new RevitEnvironmentSetting(view.Document);
                    if (setting.SystemSetting.IsModifyUnit)
                    {
                        envSetting.ReadOriginUnitsAndSetNew();
                    }

                    ModelExportContext context = new ModelExportContext(view.Document);
                    context.ExportSetting = setting;
                    context.BuiltInMaterialLibraryAsset = appearanceAssetSet;
                    context.IsPackageEntityToBlock      = true;
                    context.ExtraMaterial            = colorOverride.GetMaterials();
                    context.ExtraElementColorSetting = colorOverride.GetElementColorSetting();
                    context.IsOptimisePipeEntity     = true;
                    CustomExporter exporter = new CustomExporter(view.Document, context);

                    //exporter.IncludeFaces = false;

                    exporter.ShouldStopOnError = false;
                    exporter.Export(view);

                    if (setting.SystemSetting.IsModifyUnit)
                    {
                        envSetting.RecoverOriginUnits();
                    }

                    converter.Materials  = context.Materials;
                    converter.ModelBlock = context.ModelSpaceBlock;
                    converter.DictBlocks = context.DictBlocks;
                    converter.Levels     = Tools.GetLevelsFromDocument(view.Document);
                    if (setting.SystemSetting.IsExportGrid)
                    {
                        converter.Grids = Tools.GetGridFromDocument(view.Document);
                    }
                }

                converter.WndParent = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
                converter.BeginConvert();
            }
            catch (Exception e)
            {
                ex = e;
                return(false);
            }

            return(true);
        }
コード例 #29
0
        bool IExportControl.Run()
        {
            var siteInfo = GetSiteInfo();

            if (siteInfo == null)
            {
                ShowMessageBox(Strings.SiteLocationInvalid);
                return(false);
            }

            var filePath = txtTargetPath.Text;

            if (string.IsNullOrEmpty(filePath))
            {
                ShowMessageBox(Strings.MessageSelectOutputPathFirst);
                return(false);
            }

#if !R2014
            if (CustomExporter.IsRenderingSupported() == false &&
                ShowConfirmBox(Strings.ExportWillFailBecauseMaterialLib) == false)
            {
                return(false);
            }
#endif

            if (File.Exists(filePath) &&
                ShowConfirmBox(Strings.OutputFileExistedWarning) == false)
            {
                return(false);
            }

            var homePath = InnerApp.GetHomePath();
            if (InnerApp.CheckHomeFolder(homePath) == false &&
                ShowConfirmBox(Strings.HomeFolderIsInvalid) == false)
            {
                return(false);
            }

            var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo;
            if (visualStyle != null)
            {
                foreach (var p in visualStyle.Features)
                {
                    _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value);
                }
            }

            var levelOfDetail = (cbLevelOfDetail.SelectedItem as ComboItemInfo) ?? _LevelOfDetailDefault;

            #region 更新界面选项到 _Features

            void SetFeature(FeatureType featureType, bool selected)
            {
                _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected);
            }

            //SetFeature(FeatureType.ExportGrids, cbIncludeGrids.Checked);

            SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked);
            SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked);
            SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked);

            SetFeature(FeatureType.UseGoogleDraco, cbUseDraco.Checked);
            //SetFeature(FeatureType.ExtractShell, cbUseExtractShell.Checked);
            SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked);
            SetFeature(FeatureType.ExportSvfzip, cbExportSvfzip.Checked);
            SetFeature(FeatureType.EnableQuantizedAttributes, cbEnableQuantizedAttributes.Checked);
            SetFeature(FeatureType.EnableTextureWebP, cbEnableTextureWebP.Checked);
            SetFeature(FeatureType.GenerateThumbnail, cbGenerateThumbnail.Checked);
            SetFeature(FeatureType.EnableUnlitMaterials, cbEnableUnlitMaterials.Checked);

            SetFeature(FeatureType.EnableEmbedGeoreferencing, cbEmbedGeoreferencing.Checked);

            #endregion

            var isCancelled = false;
            using (var session = LicenseConfig.Create())
            {
                if (session.IsValid == false)
                {
                    LicenseConfig.ShowDialog(session, ParentForm);
                    return(false);
                }

                #region 保存设置

                var config = _LocalConfig;
                config.Features       = _Features.Where(x => x.Selected).Select(x => x.Type).ToList();
                config.LastTargetPath = txtTargetPath.Text;
                config.VisualStyle    = visualStyle?.Key;
                config.LevelOfDetail  = levelOfDetail?.Value ?? -1;

                if (rbModeShellMesh.Checked)
                {
                    config.Mode = 2;
                }
                else if (rbModeShellElement.Checked)
                {
                    config.Mode = 3;
                }
                else
                {
                    config.Mode = 0;
                }

                _Config.Save();

                #endregion

                var sw = Stopwatch.StartNew();
                try
                {
                    var setting = new ExportSetting();
                    setting.LevelOfDetail      = config.LevelOfDetail;
                    setting.OutputPath         = config.LastTargetPath;
                    setting.Mode               = config.Mode;
                    setting.Features           = _Features.Where(x => x.Selected && x.Enabled).Select(x => x.Type).ToList();
                    setting.SelectedElementIds = _ElementIds?.Where(x => x.Value).Select(x => x.Key).ToList();
                    setting.Site               = siteInfo;
                    setting.Oem = LicenseConfig.GetOemInfo(homePath);
                    setting.PreExportSeedFeatures = InnerApp.GetPreExportSeedFeatures(@"3DTiles");

                    var hasSuccess = false;
                    using (var progress = new ProgressExHelper(this.ParentForm, Strings.MessageExporting))
                    {
                        var cancellationToken = progress.GetCancellationToken();

#if !DEBUG
                        //在有些 Revit 会遇到时不时无法转换的问题,循环多次重试, 应该可以成功
                        for (var i = 0; i < 5; i++)
                        {
                            try
                            {
                                StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken);
                                hasSuccess = true;
                                break;
                            }
                            catch (Autodesk.Revit.Exceptions.ExternalApplicationException)
                            {
                                Application.DoEvents();
                            }
                            catch (IOException ex)
                            {
                                ShowMessageBox("文件保存失败: " + ex.Message);
                                hasSuccess = true;
                                break;
                            }
                        }
#endif

                        //如果之前多次重试仍然没有成功, 这里再试一次,如果再失败就会给出稍后重试的提示
                        if (hasSuccess == false)
                        {
                            StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken);
                        }

                        isCancelled = cancellationToken.IsCancellationRequested;
                    }

                    sw.Stop();
                    var ts = sw.Elapsed;
                    ExportDuration = new TimeSpan(ts.Days, ts.Hours, ts.Minutes, ts.Seconds); //去掉毫秒部分

                    Debug.WriteLine(Strings.MessageOperationSuccessAndElapsedTime, ExportDuration);

                    if (isCancelled == false)
                    {
                        ShowMessageBox(string.Format(Strings.MessageExportSuccess, ExportDuration));
                    }
                }
                catch (IOException ex)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(string.Format(Strings.MessageFileSaveFailure, ex.Message));
                }
                catch (Autodesk.Revit.Exceptions.ExternalApplicationException)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(Strings.MessageOperationFailureAndTryLater);
                }
                catch (Exception ex)
                {
                    sw.Stop();
                    Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed);

                    ShowMessageBox(ex.ToString());
                }
            }

            return(isCancelled == false);
        }
コード例 #30
0
 // Token: 0x060000B6 RID: 182 RVA: 0x0000C1E0 File Offset: 0x0000A3E0
 private void buttonShowPatterns_Click(object sender, EventArgs e)
 {
     try
     {
         this.m_AllViews.FindPatterns = true;
         Autodesk.Revit.ApplicationServices.Application application = this.p_commandData.Application.Application;
         Document document = this.p_commandData.Application.ActiveUIDocument.Document;
         FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
         ICollection <Element>    collection = filteredElementCollector.OfClass(typeof(View3D)).ToElements();
         View3D view3D = null;
         FilteredElementCollector filteredElementCollector2 = new FilteredElementCollector(document);
         ICollection <Element>    collection2 = filteredElementCollector2.OfClass(typeof(View3D)).ToElements();
         FilteredElementCollector filteredElementCollector3 = new FilteredElementCollector(document);
         ICollection <Element>    collection3 = filteredElementCollector3.OfClass(typeof(FamilySymbol)).ToElements();
         FilteredElementCollector filteredElementCollector4 = new FilteredElementCollector(document);
         ICollection <Element>    collection4 = filteredElementCollector4.OfClass(typeof(FamilySymbol)).ToElements();
         FilteredElementCollector filteredElementCollector5 = new FilteredElementCollector(document);
         ICollection <Element>    collection5 = filteredElementCollector5.OfClass(typeof(FamilyInstance)).ToElements();
         List <string>            list        = new List <string>();
         MessageBoxIcon           icon        = MessageBoxIcon.Exclamation;
         MessageBoxButtons        buttons     = MessageBoxButtons.OK;
         string caption  = "ef | Export To Unity";
         int    num      = 1;
         bool   @checked = this.radioButtonSingleObject.Checked;
         if (@checked)
         {
             num = 1;
         }
         bool checked2 = this.radioButtonByTypes.Checked;
         if (checked2)
         {
             num = 5;
         }
         bool checked3 = this.radioButtonMaterialsFast.Checked;
         if (checked3)
         {
             num = 6;
         }
         bool flag  = false;
         bool flag2 = document.ActiveView.ViewType != ViewType.ThreeD;
         if (flag2)
         {
             MessageBox.Show("The active view must be a 3D view type.");
             base.Close();
         }
         bool flag3 = document.ActiveView.ViewType == ViewType.ThreeD & document.ActiveView.IsTemplate;
         if (flag3)
         {
             MessageBox.Show("The active view is a template view and is not exportable.");
             flag = true;
             base.Close();
         }
         bool flag4 = document.ActiveView.ViewType == ViewType.ThreeD & !document.ActiveView.IsTemplate;
         if (flag4)
         {
             view3D = (document.ActiveView as View3D);
         }
         bool checked4 = this.checkBoxStartVU.Checked;
         if (checked4)
         {
         }
         Transaction transaction = new Transaction(document);
         transaction.Start("HideAnnotations");
         foreach (object obj in document.Settings.Categories)
         {
             Category category = (Category)obj;
             bool     flag5    = category.get_AllowsVisibilityControl(view3D);
             if (flag5)
             {
                 bool flag6 = category.CategoryType != CategoryType.Model;
                 if (flag6)
                 {
                     view3D.SetCategoryHidden(category.Id, true);
                 }
             }
         }
         transaction.Commit();
         int  num2  = 500000;
         int  num3  = 2000000;
         int  num4  = num3 * 2;
         bool flag7 = !this.checkBoxMaxVertices.Checked;
         if (flag7)
         {
             bool flag8 = !flag;
             if (flag8)
             {
                 bool flag9 = view3D != null;
                 if (flag9)
                 {
                     CheckExportContext checkExportContext = new CheckExportContext(document, this.m_AllViews);
                     new CustomExporter(document, checkExportContext)
                     {
                         IncludeGeometricObjects = false,
                         ShouldStopOnError       = false
                     }.Export(view3D);
                     this.m_AllViews.GroupingOptions = 0;
                     bool checked5 = this.radioButtonSingleObject.Checked;
                     if (checked5)
                     {
                         this.m_AllViews.GroupingOptions = 3;
                     }
                     bool checked6 = this.radioButtonByTypes.Checked;
                     if (checked6)
                     {
                         this.m_AllViews.GroupingOptions = 5;
                     }
                     bool checked7 = this.radioButtonMaterialsFast.Checked;
                     if (checked7)
                     {
                         this.m_AllViews.GroupingOptions = 6;
                     }
                     bool flag10 = checkExportContext.TotalNBofPoints > num2;
                     if (flag10)
                     {
                         DialogResult dialogResult = MessageBox.Show("Cette vue contient " + checkExportContext.TotalNBofPoints.ToString() + " vertices.\nVoulez-vous vraiment continuer?", "Avertissement", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                         bool         flag11       = dialogResult == DialogResult.No;
                         if (flag11)
                         {
                             flag = true;
                         }
                     }
                     bool flag12 = checkExportContext.TotalNBofPoints > num4;
                     if (flag12)
                     {
                         MessageBox.Show(string.Concat(new string[]
                         {
                             "This 3D View contains ",
                             checkExportContext.TotalNBofPoints.ToString(),
                             " Vertices.\nMax Vertices per Export: ",
                             num4.ToString(),
                             "."
                         }), caption, buttons, icon);
                         flag = true;
                     }
                 }
             }
         }
         bool flag13 = flag;
         if (flag13)
         {
             base.Close();
         }
         bool flag14 = application.VersionNumber.Contains("2019") | application.VersionNumber.Contains("2020");
         if (flag14)
         {
             bool flag15 = !this.checkBoxMaxVertices.Checked;
             if (flag15)
             {
                 bool flag16 = view3D != null & !flag;
                 if (flag16)
                 {
                     this.context = new CheckExportContext(document, this.m_AllViews);
                     CustomExporter customExporter = new CustomExporter(document, this.context);
                     customExporter.IncludeGeometricObjects = false;
                     customExporter.ShouldStopOnError       = false;
                     try
                     {
                         this.m_AllViews.ExportSubCategories = false;
                         bool flag17 = num == 1 | num == 5 | num == 6;
                         if (flag17)
                         {
                             int num5 = 1000;
                             FilteredElementCollector filteredElementCollector6 = new FilteredElementCollector(document, view3D.Id);
                             ICollection <ElementId>  collection6 = filteredElementCollector6.ToElementIds();
                             ICollection <ElementId>  collection7 = filteredElementCollector6.ToElementIds();
                             collection7.Clear();
                             List <int> list2  = new List <int>();
                             List <int> list3  = new List <int>();
                             List <int> list4  = new List <int>();
                             bool       flag18 = false;
                             foreach (ElementId elementId in collection6)
                             {
                                 bool    flag19  = false;
                                 Element element = document.GetElement(elementId);
                                 bool    flag20  = element != null;
                                 if (flag20)
                                 {
                                     bool flag21 = element.Category != null;
                                     if (flag21)
                                     {
                                         bool flag22 = element.Category.CategoryType == CategoryType.Model;
                                         if (flag22)
                                         {
                                             flag19 = true;
                                         }
                                         bool flag23 = element.Category.Id.IntegerValue == -2001340;
                                         if (flag23)
                                         {
                                             flag18 = true;
                                         }
                                         bool flag24 = element.Category.Id.IntegerValue == -2001352;
                                         if (flag24)
                                         {
                                             flag18 = true;
                                         }
                                     }
                                     bool flag25 = element.GetTypeId() != null;
                                     if (flag25)
                                     {
                                         int  integerValue = element.GetTypeId().IntegerValue;
                                         bool flag26       = flag19 & !flag18;
                                         if (flag26)
                                         {
                                             GeometryElement geometryElement = element.get_Geometry(new Options
                                             {
                                                 ComputeReferences = true
                                             });
                                             bool flag27 = geometryElement != null;
                                             if (flag27)
                                             {
                                                 foreach (GeometryObject geometryObject in geometryElement)
                                                 {
                                                     bool flag28 = geometryObject is Solid;
                                                     if (flag28)
                                                     {
                                                         Solid solid  = geometryObject as Solid;
                                                         bool  flag29 = null != solid;
                                                         if (flag29)
                                                         {
                                                             bool flag30 = solid.Faces.Size > 0;
                                                             if (flag30)
                                                             {
                                                                 flag18 = true;
                                                                 break;
                                                             }
                                                         }
                                                     }
                                                     GeometryInstance geometryInstance = geometryObject as GeometryInstance;
                                                     bool             flag31           = null != geometryInstance;
                                                     if (flag31)
                                                     {
                                                         foreach (GeometryObject geometryObject2 in geometryInstance.SymbolGeometry)
                                                         {
                                                             Solid solid2 = geometryObject2 as Solid;
                                                             bool  flag32 = null != solid2;
                                                             if (flag32)
                                                             {
                                                                 bool flag33 = solid2.Faces.Size > 0;
                                                                 if (flag33)
                                                                 {
                                                                     flag18 = true;
                                                                     break;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                         bool flag34 = !list2.Contains(integerValue) && flag18;
                                         if (flag34)
                                         {
                                             list2.Add(integerValue);
                                         }
                                     }
                                 }
                                 flag18 = false;
                             }
                             for (int i = 0; i < list2.Count; i++)
                             {
                                 int  item   = list2[i];
                                 int  num6   = 0;
                                 bool flag35 = num6 <= num5;
                                 if (flag35)
                                 {
                                     list4.Add(item);
                                 }
                                 bool flag36 = num6 > num5;
                                 if (flag36)
                                 {
                                     list3.Add(item);
                                 }
                             }
                             bool flag37 = list4.Count > 0;
                             if (flag37)
                             {
                                 bool flag38 = false;
                                 foreach (ElementId elementId2 in collection6)
                                 {
                                     Element element2 = document.GetElement(elementId2);
                                     bool    flag39   = element2 != null;
                                     if (flag39)
                                     {
                                         int  integerValue2 = element2.GetTypeId().IntegerValue;
                                         bool flag40        = !list4.Contains(integerValue2);
                                         if (flag40)
                                         {
                                             bool flag41 = element2.Category != null;
                                             if (flag41)
                                             {
                                                 bool flag42 = element2.Category.Id.IntegerValue == -2001340;
                                                 if (flag42)
                                                 {
                                                     flag38 = true;
                                                 }
                                             }
                                             bool flag43 = !flag18;
                                             if (flag43)
                                             {
                                                 GeometryElement geometryElement2 = element2.get_Geometry(new Options
                                                 {
                                                     ComputeReferences = true
                                                 });
                                                 bool flag44 = geometryElement2 != null;
                                                 if (flag44)
                                                 {
                                                     foreach (GeometryObject geometryObject3 in geometryElement2)
                                                     {
                                                         bool flag45 = geometryObject3 is Solid;
                                                         if (flag45)
                                                         {
                                                             Solid solid3 = geometryObject3 as Solid;
                                                             bool  flag46 = null != solid3;
                                                             if (flag46)
                                                             {
                                                                 bool flag47 = solid3.Faces.Size > 0;
                                                                 if (flag47)
                                                                 {
                                                                     flag38 = true;
                                                                     break;
                                                                 }
                                                             }
                                                         }
                                                         GeometryInstance geometryInstance2 = geometryObject3 as GeometryInstance;
                                                         bool             flag48            = null != geometryInstance2;
                                                         if (flag48)
                                                         {
                                                             foreach (GeometryObject geometryObject4 in geometryInstance2.SymbolGeometry)
                                                             {
                                                                 Solid solid4 = geometryObject4 as Solid;
                                                                 bool  flag49 = null != solid4;
                                                                 if (flag49)
                                                                 {
                                                                     bool flag50 = solid4.Faces.Size > 0;
                                                                     if (flag50)
                                                                     {
                                                                         flag38 = true;
                                                                         break;
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                             bool flag51 = flag38;
                                             if (flag51)
                                             {
                                                 bool flag52 = element2.CanBeHidden(view3D);
                                                 if (flag52)
                                                 {
                                                     collection7.Add(elementId2);
                                                 }
                                             }
                                         }
                                     }
                                     flag38 = false;
                                 }
                                 Transaction transaction2 = new Transaction(document);
                                 transaction2.Start("TempHideType");
                                 bool flag53 = collection7.Count > 0;
                                 if (flag53)
                                 {
                                     view3D.HideElements(collection7);
                                 }
                                 transaction2.Commit();
                                 customExporter.Export(view3D);
                                 Transaction transaction3 = new Transaction(document);
                                 transaction3.Start("TempUnhideType");
                                 bool flag54 = collection7.Count > 0;
                                 if (flag54)
                                 {
                                     view3D.UnhideElements(collection7);
                                 }
                                 transaction3.Commit();
                                 collection7.Clear();
                             }
                             bool flag55 = list3.Count > 0;
                             if (flag55)
                             {
                                 foreach (int num7 in list3)
                                 {
                                     bool flag56 = false;
                                     bool flag57 = num7 != -1;
                                     if (flag57)
                                     {
                                         foreach (ElementId elementId3 in collection6)
                                         {
                                             Element element3 = document.GetElement(elementId3);
                                             bool    flag58   = element3 != null;
                                             if (flag58)
                                             {
                                                 int  integerValue3 = element3.GetTypeId().IntegerValue;
                                                 bool flag59        = num7 != integerValue3;
                                                 if (flag59)
                                                 {
                                                     bool flag60 = element3.Category != null;
                                                     if (flag60)
                                                     {
                                                         bool flag61 = element3.Category.Id.IntegerValue == -2001340;
                                                         if (flag61)
                                                         {
                                                             flag56 = true;
                                                         }
                                                     }
                                                     bool flag62 = !flag56;
                                                     if (flag62)
                                                     {
                                                         GeometryElement geometryElement3 = element3.get_Geometry(new Options
                                                         {
                                                             ComputeReferences = true
                                                         });
                                                         bool flag63 = geometryElement3 != null;
                                                         if (flag63)
                                                         {
                                                             foreach (GeometryObject geometryObject5 in geometryElement3)
                                                             {
                                                                 bool flag64 = geometryObject5 is Solid;
                                                                 if (flag64)
                                                                 {
                                                                     Solid solid5 = geometryObject5 as Solid;
                                                                     bool  flag65 = null != solid5;
                                                                     if (flag65)
                                                                     {
                                                                         bool flag66 = solid5.Faces.Size > 0;
                                                                         if (flag66)
                                                                         {
                                                                             flag56 = true;
                                                                             break;
                                                                         }
                                                                     }
                                                                 }
                                                                 GeometryInstance geometryInstance3 = geometryObject5 as GeometryInstance;
                                                                 bool             flag67            = null != geometryInstance3;
                                                                 if (flag67)
                                                                 {
                                                                     foreach (GeometryObject geometryObject6 in geometryInstance3.SymbolGeometry)
                                                                     {
                                                                         Solid solid6 = geometryObject6 as Solid;
                                                                         bool  flag68 = null != solid6;
                                                                         if (flag68)
                                                                         {
                                                                             bool flag69 = solid6.Faces.Size > 0;
                                                                             if (flag69)
                                                                             {
                                                                                 flag56 = true;
                                                                                 break;
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     bool flag70 = flag56;
                                                     if (flag70)
                                                     {
                                                         bool flag71 = element3.CanBeHidden(view3D);
                                                         if (flag71)
                                                         {
                                                             collection7.Add(elementId3);
                                                         }
                                                     }
                                                 }
                                             }
                                             flag56 = false;
                                         }
                                         Transaction transaction4 = new Transaction(document);
                                         transaction4.Start("TempHideType");
                                         bool flag72 = collection7.Count > 0;
                                         if (flag72)
                                         {
                                             view3D.HideElements(collection7);
                                         }
                                         transaction4.Commit();
                                         customExporter.Export(view3D);
                                         Transaction transaction5 = new Transaction(document);
                                         transaction5.Start("TempUnhideType");
                                         bool flag73 = collection7.Count > 0;
                                         if (flag73)
                                         {
                                             view3D.UnhideElements(collection7);
                                         }
                                         transaction5.Commit();
                                         collection7.Clear();
                                     }
                                 }
                             }
                         }
                     }
                     catch (ExternalApplicationException ex)
                     {
                         Debug.Print("ExternalApplicationException " + ex.Message);
                     }
                     bool flag74 = !flag;
                     if (flag74)
                     {
                         foreach (int num8 in this.context.ListMaterialID)
                         {
                             bool flag75 = num8 != ElementId.InvalidElementId.IntegerValue & !num8.ToString().Contains("-") & num8.ToString() != "-1";
                             if (flag75)
                             {
                                 ElementId elementId4 = new ElementId(num8);
                                 Material  material   = document.GetElement(elementId4) as Material;
                                 bool      flag76     = material != null;
                                 if (flag76)
                                 {
                                     FillPatternElement fillPatternElement = document.GetElement(material.SurfaceForegroundPatternId) as FillPatternElement;
                                     bool flag77 = fillPatternElement != null;
                                     if (flag77)
                                     {
                                         bool flag78 = !list.Contains(fillPatternElement.Name);
                                         if (flag78)
                                         {
                                             list.Add(fillPatternElement.Name);
                                             this.h_MatIDPatID.Add(material.Id.IntegerValue, fillPatternElement.Id.IntegerValue);
                                             this.key_MatIDPatID = this.h_MatIDPatID.Keys;
                                         }
                                     }
                                 }
                             }
                         }
                         bool flag79 = list != null;
                         if (flag79)
                         {
                             bool flag80 = list.Count > 0;
                             if (flag80)
                             {
                                 this.listBoxPatterns.DataSource = list;
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex2)
     {
         MessageBox.Show(ex2.Message);
     }
 }
コード例 #31
0
ファイル: Command.cs プロジェクト: khoaho/RvtVa3c
        /// <summary>
        /// Export a given 3D view to JSON using
        /// our custom exporter context.
        /// </summary>
        void ExportView3D( View3D view3d, string filename )
        {
            AppDomain.CurrentDomain.AssemblyResolve
            += CurrentDomain_AssemblyResolve;

              Document doc = view3d.Document;

              Va3cExportContext context
            = new Va3cExportContext( doc, filename );

              CustomExporter exporter = new CustomExporter(
            doc, context );

              // Note: Excluding faces just suppresses the
              // OnFaceBegin calls, not the actual processing
              // of face tessellation. Meshes of the faces
              // will still be received by the context.

              exporter.IncludeFaces = false;

              exporter.ShouldStopOnError = false;

              exporter.Export( view3d );
        }
コード例 #32
0
        public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            if (uidoc == null)
            {
                MessageBox.Show("当前没有打开的Revit文档!");
                return(Result.Cancelled);
            }

            Document doc = uidoc.Document;

            if (!(uidoc.ActiveView is View3D))
            {
                MessageBox.Show("请在3D视图下使用此命令!");
                return(Result.Cancelled);
            }

            //var dicProfileData = GetProfileDictFromDocument(doc);

            Process process = Process.GetCurrentProcess();
            IntPtr  h       = process.MainWindowHandle;

            string filePath = System.IO.Path.GetDirectoryName(doc.PathName);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(doc.PathName);

            FormSettings dlg = new FormSettings();

            dlg.ExportSetting.SystemSetting.ExportFilePath = filePath + "\\" + fileName + ".vdcl";
            DialogResult dr = dlg.ShowDialog(new WindowHandle(h));

            if (dr != DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            ElementColorOverride colorOverride = new ElementColorOverride();

            if (!dlg.ExportSetting.SystemSetting.IsOriginMaterial)
            {
                colorOverride.ArrangeElemlentColor(doc, uidoc.ActiveView as View3D);
            }

            RevitEnvironmentSetting setting = new RevitEnvironmentSetting(doc);

            if (dlg.ExportSetting.SystemSetting.IsModifyUnit)
            {
                setting.ReadOriginUnitsAndSetNew();
            }

            ModelExportContext context = new ModelExportContext(doc);

            context.IsPackageEntityToBlock   = true;
            context.IsExportProperty         = dlg.ExportSetting.SystemSetting.IsExportProperty;
            context.ExtraMaterial            = colorOverride.GetMaterials();
            context.ExtraElementColorSetting = colorOverride.GetElementColorSetting();
            CustomExporter exporter = new CustomExporter(doc, context);

            exporter.IncludeFaces      = false;
            exporter.ShouldStopOnError = false;
            exporter.Export(doc.ActiveView as View3D);

            if (dlg.ExportSetting.SystemSetting.IsModifyUnit)
            {
                setting.RecoverOriginUnits();
            }

            ConvertEntity converter = new ConvertEntity();

            converter.OptimizeTriangle = dlg.ExportSetting.SystemSetting.IsOptimizeCylinderFace;
            converter.ExportSetting    = dlg.ExportSetting;
            converter.Materials        = context.Materials;
            converter.ModelBlock       = context.ModelSpaceBlock;
            converter.WndParent        = new WindowHandle(h);
            if (dlg.ExportSetting.SystemSetting.IsExportGrid)
            {
                converter.Grids = GetGridFromDocument(doc);
            }
            //converter.FamilySketchDictionary = dicProfileData;
            converter.InstanceLocationCurveDictionary = context.InstanceLocation;
            converter.BeginConvert(dlg.ExportSetting.SystemSetting.ExportFilePath);

            return(Result.Succeeded);
        }