public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiapp = commandData.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection sel = uidoc.Selection;


            Transaction ts =new Transaction(doc,"创建3d视图");
            ts.Start();

            //Find  a 3D view type
            IEnumerable<ViewFamilyType> viewFamilyTypes =
                from elem in new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))
                let type = elem as ViewFamilyType
                where type.ViewFamily == ViewFamily.ThreeDimensional
                select type;
            //create new Perspective View3D
            View3D view3D = View3D.CreatePerspective(doc, viewFamilyTypes.First().Id);
            if (null != view3D)
            {
                // by default, the 3d view uses a default orientation.
                XYZ eye = new XYZ(0, -100, 10);
                XYZ up = new XYZ(0, 0, 1);
                XYZ forward = new XYZ(0, 1, 0);
                view3D.SetOrientation(new ViewOrientation3D(eye, up, forward));
                //turn off the far clip plane with standard parameter API
                Parameter farClip = view3D.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                farClip.Set(1);
            }
            ts.Commit();


            return Result.Succeeded;
        }
示例#2
0
        public static View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective)
        {
            //http://adndevblog.typepad.com/aec/2012/05/viewplancreate-method.html

            IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new
                                                           FilteredElementCollector(dynRevitSettings.Doc.Document).OfClass(typeof(ViewFamilyType))
                                                           let type = elem as ViewFamilyType
                                                                      where type.ViewFamily == ViewFamily.ThreeDimensional
                                                                      select type;

            //create a new view
            View3D view = isPerspective ?
                          View3D.CreatePerspective(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id) :
                          View3D.CreateIsometric(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id);

            view.SetOrientation(orient);
            view.SaveOrientationAndLock();
            try
            {
                //will fail if name is not unique
                view.Name = name;
            }
            catch
            {
                view.Name = CreateUniqueViewName(name);
            }


            return(view);
        }
        /// <summary>
        /// Create perspective view with camera settings
        /// matching the Forge Viewer.
        /// </summary>
        void CreatePerspectiveViewMatchingCamera(
            Document doc,
            XYZ camera_position,
            XYZ target)
        {
            using (var trans = new Transaction(doc))
            {
                trans.Start("Map Forge Viewer Camera");

                ViewFamilyType typ
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .First <ViewFamilyType>(
                          x => x.ViewFamily.Equals(
                              ViewFamily.ThreeDimensional));

                // Create a new perspective 3D view

                View3D view3D = View3D.CreatePerspective(
                    doc, typ.Id);

                Random rnd = new Random();
                view3D.Name = string.Format("Camera{0}",
                                            rnd.Next());

                // By default, the 3D view uses a default
                // orientation. Change that by creating and
                // setting up a suitable ViewOrientation3D.

                //var position = new XYZ( -15.12436009332275,
                //  -8.984616232971192, 4.921260089050291 );

                var up = XYZ.BasisZ;

                //var target = new XYZ( -15.02436066552734,
                //  -8.984211875061035, 4.921260089050291 );

                var sightDir = target.Subtract(camera_position).Normalize();

                var orientation = new ViewOrientation3D(
                    camera_position, up, sightDir);

                view3D.SetOrientation(orientation);

                // Turn off the far clip plane, etc.

                view3D.LookupParameter("Far Clip Active")
                .Set(0);

                view3D.LookupParameter("Crop Region Visible")
                .Set(1);

                view3D.LookupParameter("Crop View")
                .Set(1);

                trans.Commit();
            }
        }
 private static void CreatePerspectiveFrom3D(UIDocument uiDoc, View3D view3D)
 {
     var viewOrientation3D = view3D.GetOrientation();
     var centerOfScreen = UserView.GetMiddleOfActiveViewWindow(UserView.ActiveUIView(uiDoc, view3D));
     var view = View3D.CreatePerspective(uiDoc.Document,
         UserView.Get3DViewFamilyTypes(uiDoc.Document).First().Id);
     view.SetOrientation(new ViewOrientation3D(
         new XYZ(centerOfScreen.X, centerOfScreen.Y, viewOrientation3D.EyePosition.Z),
         viewOrientation3D.UpDirection, viewOrientation3D.ForwardDirection));
     view.Dispose();
     viewOrientation3D.Dispose();
 }
        private View3D CreateDefaultPersView()
        {
            View3D view3D = null;

            try
            {
                var viewName  = "SmartBCF - Perspective - " + Environment.UserName;
                var collector = new FilteredElementCollector(ActiveDoc);
                var view3ds   = collector.OfClass(typeof(View3D)).ToElements().Cast <View3D>().ToList();
                //by the limitation of perspective view, create isometric instead
#if RELEASE2015 || RELEASE2016 || RELEASE2017 || RELEASE2018
                var viewfound = from view in view3ds where view.IsTemplate == false && view.IsPerspective == false && view.ViewName == viewName select view;
#else
                var viewfound = from view in view3ds where view.IsTemplate == false && view.IsPerspective == false && view.Name == viewName select view;
#endif
                if (viewfound.Any())
                {
                    view3D = viewfound.First();
                }
                else
                {
                    var viewFamilyTypeId = GetViewFamilyTypeId();
                    if (viewFamilyTypeId != ElementId.InvalidElementId)
                    {
                        using (var trans = new Transaction(ActiveDoc))
                        {
                            trans.Start("Create View");
                            try
                            {
                                view3D      = View3D.CreatePerspective(ActiveDoc, viewFamilyTypeId);
                                view3D.Name = viewName;
                                trans.Commit();
                            }
                            catch (Exception)
                            {
                                trans.RollBack();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(view3D);
        }
 private static void CreatePerspectiveFromPlan(UIDocument uiDoc, View currentView)
 {
     var view = UserView.ActiveUIView(uiDoc, currentView);
     var eye = UserView.GetMiddleOfActiveViewWindow(view);
     var up = new XYZ(0, 1, 0);
     var forward = new XYZ(0, 0, -1);
     var viewOrientation3D = new ViewOrientation3D(eye, up, forward);
     var view3D = View3D.CreatePerspective(uiDoc.Document, UserView.Get3DViewFamilyTypes(uiDoc.Document).First().Id);
     view3D.SetOrientation(new ViewOrientation3D(viewOrientation3D.EyePosition,
         viewOrientation3D.UpDirection,
         viewOrientation3D.ForwardDirection));
     UserView.ApplySectionBoxToView(UserView.ViewExtentsBoundingBox(view), view3D);
     view3D.Name = UserView.GetNewViewName(uiDoc.Document, view3D);
     view3D.ViewTemplateId = ElementId.InvalidElementId;
     viewOrientation3D.Dispose();
 }
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void CreatePerspectiveFromSection(UIDocument udoc, View sectionView)
        {
            UIView            view    = ActiveUIView(udoc, sectionView);
            XYZ               eye     = GetMiddleOfActiveViewWindow(view);
            XYZ               up      = new XYZ(0, 0, 1);
            XYZ               forward = new XYZ(0, 0, -1);
            ViewOrientation3D v       = new ViewOrientation3D(eye, up, forward);

            using (var t = new Transaction(udoc.Document))
            {
                t.Start("Create perspective view");
                View3D np = View3D.CreatePerspective(udoc.Document, Get3DViewFamilyTypes(udoc.Document).First().Id);
                np.SetOrientation(new ViewOrientation3D(v.EyePosition, v.UpDirection, v.ForwardDirection));
                ApplySectionBoxToView(SectionViewExtentsBoundingBox(view), np);
                t.Commit();
            }
        }
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void CreatePerspectiveFrom3D(UIDocument udoc, View3D view)
        {
            var v = view.GetOrientation();

            using (var t = new Transaction(udoc.Document))
            {
                if (t.Start("Create perspective view") == TransactionStatus.Started)
                {
                    var centreOfScreen = GetMiddleOfActiveViewWindow(ActiveUIView(udoc, view));
                    var np             = View3D.CreatePerspective(udoc.Document, Get3DViewFamilyTypes(udoc.Document).First().Id);
                    np.SetOrientation(new ViewOrientation3D(new XYZ(centreOfScreen.X, centreOfScreen.Y, v.EyePosition.Z), v.UpDirection, v.ForwardDirection));
                    t.Commit();
                    np.Dispose();
                }
            }
            v.Dispose();
        }
示例#9
0
        /// <summary>
        /// Creates a perspective View3D.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="eyePosition">The eye position in 3D model space for the new 3D view.</param>
        /// <param name="upDir">The up direction in 3D model space for the new 3D view.</param>
        /// <param name="forwardDir">The forward direction in 3D model space for the new 3D view.</param>
        /// <returns>The new View3D.</returns>
        private static View3D Create3DView(Document doc, XYZ eyePosition, XYZ upDir, XYZ forwardDir)
        {
            if (null == doc || null == eyePosition || null == upDir || null == forwardDir)
            {
                return(null);
            }

            var vft = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .FirstOrDefault(t => t.ViewFamily == ViewFamily.ThreeDimensional);

            View3D view3d = View3D.CreatePerspective(doc, vft.Id);

            if (null == view3d)
            {
                return(null);
            }

            view3d.SetOrientation(new ViewOrientation3D(eyePosition, upDir, forwardDir));

            return(view3d);
        }
示例#10
0
        public void SetView(XYZ camera, XYZ target, double focal_length)
        {
            const string khepriName = "Khepri-3D";
            //Do we have our own 3D view?
            var view3D = new FilteredElementCollector(doc).OfClass(typeof(View)).FirstOrDefault(v => v.Name == khepriName) as View3D;

            if (view3D == null)
            {
                var viewFamilyType = new FilteredElementCollector(doc)
                                     .OfClass(typeof(ViewFamilyType))
                                     .Cast <ViewFamilyType>()
                                     .First(type => type.ViewFamily == ViewFamily.ThreeDimensional);
                view3D      = View3D.CreatePerspective(doc, viewFamilyType.Id);
                view3D.Name = khepriName;
            }
            XYZ eye     = camera;
            XYZ forward = (target - camera).Normalize();
            XYZ up      = new XYZ(0, 0, 1);

            up = forward.CrossProduct(up).CrossProduct(forward);
            view3D.SetOrientation(new ViewOrientation3D(eye, up, forward));
            double original_focal_length = 38.6;
            double original_frame_width  = 150.0;
            double original_frame_height = 113.0;
            double frame_width           = original_frame_width * original_focal_length / focal_length;
            double frame_height          = original_frame_height * original_focal_length / focal_length;
            double scale = Math.Max(frame_width / original_frame_width, frame_height / original_frame_height);

            view3D.Outline.Min *= scale;
            view3D.Outline.Max *= scale;
            view3D.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).Set(0);
            CurrentTransaction.Commit();
            uiapp.ActiveUIDocument.ActiveView = view3D;
            uiapp.ActiveUIDocument.RefreshActiveView();
            CurrentTransaction.Start();
        }
示例#11
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument uidoc      = app.ActiveUIDocument;
                Document   doc        = uidoc.Document;
                var        uniqueView = UserSettings.GetBool("alwaysNewView");

                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = v.OrthogonalCamera.ViewToWorldScale.ToFeet();
                    var cameraDirection = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraDirection);
                    var cameraUpVector  = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraUpVector);
                    var cameraViewPoint = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraViewPoint);
                    var orient3D        = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true);

                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        var activeView3D = doc.ActiveView as View3D;
                        if (!activeView3D.IsPerspective)
                        {
                            orthoView = activeView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        //try to use an existing 3D view
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        if (viewcollector3D.Any(o => o.Name == "{3D}" || o.Name == "BCFortho"))
                        {
                            orthoView = viewcollector3D.First(o => o.Name == "{3D}" || o.Name == "BCFortho");
                        }
                    }
                    using (var trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view

                            if (orthoView == null || uniqueView)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = (uniqueView) ? "BCFortho" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFortho";
                            }
                            else
                            {
                                //reusing an existing view, I net to reset the visibility
                                //placed this here because if set afterwards it doesn't work
                                orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            }
                            orthoView.SetOrientation(orient3D);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = zoom / 2.5;
                    // **** CUSTOM VALUE FOR TEKLA **** //

                    double x = zoom;
                    //if(MySettings.Get("optTekla")=="1")
                    //    x = zoom / 2.5;

                    //set UI view position and zoom
                    XYZ m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                //perspective
                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    //not used since the fov cannot be changed in Revit
                    var zoom = v.PerspectiveCamera.FieldOfView;
                    //FOV - not used
                    //double z1 = 18 / Math.Tan(zoom / 2 * Math.PI / 180);
                    //double z = 18 / Math.Tan(25 / 2 * Math.PI / 180);
                    //double factor = z1 - z;

                    var cameraDirection = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraDirection);
                    var cameraUpVector  = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraUpVector);
                    var cameraViewPoint = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraViewPoint);
                    var orient3D        = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true);



                    View3D perspView = null;
                    //try to use an existing 3D view
                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any(o => o.Name == "BCFpersp"))
                    {
                        perspView = viewcollector3D.First(o => o.Name == "BCFpersp");
                    }

                    using (var trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView || uniqueView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = (uniqueView) ? "BCFpersp" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFpersp";
                            }
                            else
                            {
                                //reusing an existing view, I net to reset the visibility
                                //placed this here because if set afterwards it doesn't work
                                perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            }

                            perspView.SetOrientation(orient3D);

                            // turn off the far clip plane
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                //sheet
                else if (v.SheetCamera != null)
                {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("View " + v.SheetCamera.SheetName + " with Id=" + v.SheetCamera.SheetID + " not found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.RefreshActiveView();

                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y, v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y, v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                //no view included
                else
                {
                    return;
                }

                if (v.Components == null)
                {
                    return;
                }


                var elementsToSelect = new List <ElementId>();
                var elementsToHide   = new List <ElementId>();
                var elementsToShow   = new List <ElementId>();

                var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                   .WhereElementIsNotElementType()
                                   .WhereElementIsViewIndependent()
                                   .ToElementIds()
                                   .Where(e => doc.GetElement(e).CanBeHidden(doc.ActiveView)); //might affect performance, but it's necessary


                bool canSetVisibility = (v.Components.Visibility != null &&
                                         v.Components.Visibility.DefaultVisibilitySpecified &&
                                         v.Components.Visibility.Exceptions.Any())
                ;
                bool canSetSelection = (v.Components.Selection != null && v.Components.Selection.Any());



                //loop elements
                foreach (var e in visibleElems)
                {
                    var guid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, e));

                    if (canSetVisibility)
                    {
                        if (v.Components.Visibility.DefaultVisibility)
                        {
                            if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
                            {
                                elementsToHide.Add(e);
                            }
                        }
                        else
                        {
                            if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
                            {
                                elementsToShow.Add(e);
                            }
                        }
                    }

                    if (canSetSelection)
                    {
                        if (v.Components.Selection.Any(x => x.IfcGuid == guid))
                        {
                            elementsToSelect.Add(e);
                        }
                    }
                }



                using (var trans = new Transaction(uidoc.Document))
                {
                    if (trans.Start("Apply BCF visibility and selection") == TransactionStatus.Started)
                    {
                        if (elementsToHide.Any())
                        {
                            doc.ActiveView.HideElementsTemporary(elementsToHide);
                        }
                        //there are no items to hide, therefore hide everything and just show the visible ones
                        else if (elementsToShow.Any())
                        {
                            doc.ActiveView.IsolateElementsTemporary(elementsToShow);
                        }

                        if (elementsToSelect.Any())
                        {
                            uidoc.Selection.SetElementIds(elementsToSelect);
                        }
                    }
                    trans.Commit();
                }


                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
示例#12
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument       uidoc            = app.ActiveUIDocument;
                Document         doc              = uidoc.Document;
                SelElementSet    m_elementsToHide = SelElementSet.Create();
                List <ElementId> elementids       = new List <ElementId>();



                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.SetOrientation(orient3d);

                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }
                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid = IfcGuid.FromIfcGUID(e.IfcGuid);
                        var ids     = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o));
                        if (ids.Any())
                        {
                            m_elementsToHide.Add(doc.GetElement(ids.First()));
                            elementids.Add(ids.First());
                        }
                    }
                    if (null != m_elementsToHide && !m_elementsToHide.IsEmpty)
                    {
                        //do transaction only if there is something to hide/select
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Apply visibility/selection") == TransactionStatus.Started)
                            {
                                if (MySettings.Get("selattachedelems") == "0")
                                {
                                    uidoc.ActiveView.IsolateElementsTemporary(elementids);
                                }
                                else
                                {
                                    uidoc.Selection.Elements = m_elementsToHide;
                                }
                            }
                            trans.Commit();
                        }
                    }
                }


                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
示例#13
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument    uidoc            = app.ActiveUIDocument;
                Document      doc              = uidoc.Document;
                SelElementSet m_elementsToHide = SelElementSet.Create();

                List <ElementId> elementsToBeIsolated = new List <ElementId>();
                List <ElementId> elementsToBeHidden   = new List <ElementId>();
                List <ElementId> elementsToBeSelected = new List <ElementId>();


                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            perspView.SetOrientation(orient3d);

                            // turn on the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(1);
                            }
                            // reset far clip offset
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).HasValue)
                            {
                                Parameter m_farClipOffset = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                                m_farClipOffset.SetValueString("35");
                            }
                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }

                //apply BCF clipping planes to Revit section box
                View3D view3D = doc.ActiveView as View3D;
                if (view3D != null)
                {
                    if (v.ClippingPlanes != null)
                    {
                        if (v.ClippingPlanes.Count() > 0)
                        {
                            var result = getBoundingBoxFromClippingPlanes(doc, v.ClippingPlanes);

                            if (result != null)
                            {
                                BoundingBoxXYZ computedBox = result.Item1;
                                Transform      rotate      = result.Item2;

                                using (Transaction trans = new Transaction(uidoc.Document))
                                {
                                    if (trans.Start("Apply Section Box") == TransactionStatus.Started)
                                    {
                                        view3D.IsSectionBoxActive = true;
                                        view3D.SetSectionBox(computedBox);

                                        if (rotate != null)
                                        {
                                            // Transform the View3D's section box with the rotation transform
                                            computedBox.Transform = computedBox.Transform.Multiply(rotate);

                                            // Set the section box back to the view (requires an open transaction)
                                            view3D.SetSectionBox(computedBox);
                                        }
                                    }
                                    trans.Commit();
                                }
                            }
                        }
                    }
                }

                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    if (v.Components.Count > 100)
                    {
                        var result = MessageBox.Show("Too many elements attached. It may take for a while to isolate/select them. Do you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.No)
                        {
                            uidoc.RefreshActiveView();
                            return;
                        }
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid         = IfcGuid.FromIfcGUID(e.IfcGuid);
                        int authoringToolId = string.IsNullOrWhiteSpace(e.AuthoringToolId) ? -1 : int.Parse(e.AuthoringToolId);
                        var ids             = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o) | authoringToolId == Convert.ToInt32(doc.GetElement(o).UniqueId.Substring(37), 16));
                        if (ids.Any())
                        {
                            // handle visibility
                            if (e.Visible)
                            {
                                elementsToBeIsolated.Add(ids.First());
                            }
                            else
                            {
                                elementsToBeHidden.Add(ids.First());
                            }

                            // handle selection
                            if (e.Selected)
                            {
                                elementsToBeSelected.Add(ids.First());
                            }
                        }
                    }

                    if (elementsToBeHidden.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Hide Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden);
                            }
                            trans.Commit();
                        }
                    }
                    else if (elementsToBeIsolated.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Isolate Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.IsolateElementsTemporary(elementsToBeIsolated);
                            }
                            trans.Commit();
                        }
                    }

                    if (elementsToBeSelected.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Select Elements") == TransactionStatus.Started)
                            {
                                SelElementSet selectedElements = SelElementSet.Create();
                                elementsToBeSelected.ForEach(id => {
                                    selectedElements.Add(doc.GetElement(id));
                                });

                                uidoc.Selection.Elements = selectedElements;
                            }
                            trans.Commit();
                        }
                    }
                }

                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
示例#14
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument uidoc = app.ActiveUIDocument;
                Document   doc   = uidoc.Document;
                //Selection m_elementsToHide = uidoc.Selection; //SelElementSet.Create();

                BlockingCollection <ElementId> elementsToBeIsolated = new BlockingCollection <ElementId>();
                BlockingCollection <ElementId> elementsToBeHidden   = new BlockingCollection <ElementId>();
                BlockingCollection <ElementId> elementsToBeSelected = new BlockingCollection <ElementId>();

                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    string userDefault3dViewName = "{3D - " + app.Application.Username + "}";
                    string default3dViewName     = "{3D}";
                    string userBCForthoViewName  = string.Format("BCFortho_{0}", app.Application.Username);
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //find a orthographic 3D view
                        if (viewcollector3D.Any())
                        {
                            if (viewcollector3D.Where(o => o.Name == userDefault3dViewName).Any()) // 1) try to find user specific 3D view in workshared environment
                            {
                                orthoView = viewcollector3D.Where(o => o.Name == userDefault3dViewName).First();
                            }
                            else if (viewcollector3D.Where(o => o.Name == default3dViewName).Any()) // 2) try to find the default 3D view if 1) not found
                            {
                                orthoView = viewcollector3D.Where(o => o.Name == default3dViewName).First();
                            }
                            else if (viewcollector3D.Where(o => o.Name == userBCForthoViewName).Any()) // 3) try to find BCFortho 3D view generated by AIT previously if 2) is not found
                            {
                                orthoView = viewcollector3D.Where(o => o.Name == userBCForthoViewName).First();
                            }
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new user-specific 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = userBCForthoViewName;
                            }

                            orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);

                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    string userPersp3dViewName           = string.Format("BCFperps_{0}", app.Application.Username);
                    // find a perspective view
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == userPersp3dViewName).Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == userPersp3dViewName).First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = userPersp3dViewName;
                            }

                            perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            perspView.SetOrientation(orient3d);

                            // turn on the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(1);
                            }
                            // reset far clip offset
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).HasValue)
                            {
                                Parameter m_farClipOffset = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                                m_farClipOffset.SetValueString("35");
                            }
                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }

                //apply BCF clipping planes to Revit section box
                View3D view3D = doc.ActiveView as View3D;
                if (view3D != null)
                {
                    // resume section box state
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Resume Section Box") == TransactionStatus.Started)
                        {
                            view3D.IsSectionBoxActive = false;
                        }
                        trans.Commit();
                    }

                    if (v.ClippingPlanes != null)
                    {
                        if (v.ClippingPlanes.Count() > 0)
                        {
                            var result = getBoundingBoxFromClippingPlanes(doc, v.ClippingPlanes);

                            if (result != null)
                            {
                                BoundingBoxXYZ computedBox = result.Item1;
                                Transform      rotate      = result.Item2;

                                using (Transaction trans = new Transaction(uidoc.Document))
                                {
                                    if (trans.Start("Apply Section Box") == TransactionStatus.Started)
                                    {
                                        view3D.IsSectionBoxActive = true;
                                        view3D.SetSectionBox(computedBox);

                                        if (rotate != null)
                                        {
                                            // Transform the View3D's section box with the rotation transform
                                            computedBox.Transform = computedBox.Transform.Multiply(rotate);

                                            // Set the section box back to the view (requires an open transaction)
                                            view3D.SetSectionBox(computedBox);
                                        }
                                    }
                                    trans.Commit();
                                }
                            }
                        }
                    }
                }

                // resume visibility and selection
                using (Transaction trans = new Transaction(uidoc.Document))
                {
                    if (trans.Start("Resume Visibility/Selection") == TransactionStatus.Started)
                    {
#if REVIT2014
                        uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                        uidoc.Selection.Elements.Clear();
#elif REVIT2015
                        uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                        uidoc.Selection.SetElementIds(new List <ElementId>());
#else
                        uidoc.ActiveView.TemporaryViewModes.DeactivateAllModes();
                        uidoc.Selection.SetElementIds(new List <ElementId>());
#endif
                    }
                    trans.Commit();
                }

                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    //if (v.Components.Count > 100)
                    //{
                    //    var result = MessageBox.Show("Too many elements attached. It may take for a while to isolate/select them. Do you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    //    if (result == MessageBoxResult.No)
                    //    {
                    //        uidoc.RefreshActiveView();
                    //        return;
                    //    }
                    //}

                    revitWindow.initializeProgressWin(v.Components.Count);

                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id);
                    var allElementIds = collector.ToElementIds();
                    Dictionary <Guid, ElementId> exportIdElementIdDic = new Dictionary <Guid, ElementId>();
                    Dictionary <int, ElementId>  uniqueIdElementIdDic = new Dictionary <int, ElementId>();
                    foreach (ElementId eId in allElementIds)
                    {
                        Guid guid             = ExportUtils.GetExportId(doc, eId);
                        int  elementIdInteger = Convert.ToInt32(doc.GetElement(eId).UniqueId.Substring(37), 16);
                        if (!exportIdElementIdDic.ContainsKey(guid))
                        {
                            exportIdElementIdDic.Add(guid, eId);
                        }
                        if (!uniqueIdElementIdDic.ContainsKey(elementIdInteger))
                        {
                            uniqueIdElementIdDic.Add(elementIdInteger, eId);
                        }
                    }
                    //System.Threading.Tasks.Parallel.For(0, v.Components.Count, i => {
                    for (int i = 0; i < v.Components.Count; i++)
                    {
                        double percentage = ((double)i / (double)v.Components.Count) * 100;
                        revitWindow.updateProgressWin((int)percentage, i, v.Components.Count);

                        ARUP.IssueTracker.Classes.BCF2.Component e = v.Components[i];
                        ElementId currentElementId = null;

                        // find by ElementId first if OriginatingSystem is Revit
                        if (e.OriginatingSystem != null)
                        {
                            if (e.OriginatingSystem.Contains("Revit") && !string.IsNullOrEmpty(e.AuthoringToolId))
                            {
                                int elementId = -1;
                                int.TryParse(e.AuthoringToolId, out elementId);
                                if (elementId != -1)
                                {
                                    Element ele = doc.GetElement(new ElementId(elementId));
                                    if (ele != null)
                                    {
                                        currentElementId = ele.Id;
                                    }
                                }
                            }
                        }

                        // find by IfcGuid if ElementId not found
                        if (currentElementId == null)
                        {
                            var bcfguid = IfcGuid.FromIfcGUID(e.IfcGuid);
                            if (exportIdElementIdDic.ContainsKey(bcfguid))
                            {
                                currentElementId = exportIdElementIdDic[bcfguid];
                            }
                        }

                        // find by UniqueId if IfcGuid not found
                        if (currentElementId == null)
                        {
                            int authoringToolId = -1;
                            int.TryParse(e.AuthoringToolId, out authoringToolId);
                            if (uniqueIdElementIdDic.ContainsKey(authoringToolId))
                            {
                                currentElementId = uniqueIdElementIdDic[authoringToolId];
                            }
                        }

                        if (currentElementId != null)
                        {
                            // handle visibility
                            if (e.Visible)
                            {
                                elementsToBeIsolated.Add(currentElementId);
                            }
                            else
                            {
                                elementsToBeHidden.Add(currentElementId);
                            }

                            // handle selection
                            if (e.Selected)
                            {
                                elementsToBeSelected.Add(currentElementId);
                            }
                        }
                    }
                    ;

                    if (elementsToBeHidden.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Hide Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden.ToList());
                            }
                            trans.Commit();
                        }
                    }
                    else if (elementsToBeIsolated.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Isolate Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.IsolateElementsTemporary(elementsToBeIsolated.ToList());
                            }
                            trans.Commit();
                        }
                    }

                    if (elementsToBeSelected.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Select Elements") == TransactionStatus.Started)
                            {
#if REVIT2014
                                SelElementSet selectedElements = SelElementSet.Create();
                                elementsToBeSelected.ToList().ForEach(id =>
                                {
                                    selectedElements.Add(doc.GetElement(id));
                                });

                                uidoc.Selection.Elements = selectedElements;
#else
                                uidoc.Selection.SetElementIds(elementsToBeSelected.ToList());
#endif
                            }
                            trans.Commit();
                        }
                    }

                    revitWindow.disposeProgressWin();
                }

                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
示例#15
0
        private bool DuplicateCameraView(ModelInfo sModel, ModelInfo rModel, CameraViewInfo cameraInfo, ViewFamilyType vFamilyType, out CameraViewInfo createdViewInfo)
        {
            bool duplicated = false;

            createdViewInfo = null;
            try
            {
                Document sourceDoc    = sModel.ModelDoc;
                Document recipientDoc = rModel.ModelDoc;

                using (Transaction trans = new Transaction(recipientDoc))
                {
                    trans.Start("Create Camera View");
                    try
                    {
                        View3D createdView = View3D.CreatePerspective(recipientDoc, vFamilyType.Id);
                        if (CanHaveViewName(rModel, cameraInfo.ViewName))
                        {
                            createdView.Name = cameraInfo.ViewName;
                        }
                        createdView.SetOrientation(cameraInfo.Orientation);
                        createdView.CropBoxActive      = cameraInfo.IsCropBoxOn;
                        createdView.CropBox            = cameraInfo.CropBox;
                        createdView.IsSectionBoxActive = cameraInfo.IsSectionBoxOn;
                        createdView.SetSectionBox(cameraInfo.SectionBox);
                        createdView.DisplayStyle = cameraInfo.Display;
                        //createdView.SetRenderingSettings(cameraInfo.Rendering);

                        foreach (string paramName in cameraInfo.ViewParameters.Keys)
                        {
                            Parameter sourceParam    = cameraInfo.ViewParameters[paramName];
                            Parameter recipientParam = createdView.LookupParameter(paramName);
                            if (parametersToSkip.Contains(sourceParam.Id.IntegerValue))
                            {
                                continue;
                            }

                            if (null != recipientParam && sourceParam.HasValue)
                            {
                                if (!recipientParam.IsReadOnly)
                                {
                                    switch (sourceParam.StorageType)
                                    {
                                    case StorageType.Double:
                                        try { recipientParam.Set(sourceParam.AsDouble()); }
                                        catch { }
                                        break;

                                    case StorageType.ElementId:
                                        /*
                                         * try { recipientParam.Set(sourceParam.AsElementId()); }
                                         * catch { }
                                         */
                                        break;

                                    case StorageType.Integer:
                                        try { recipientParam.Set(sourceParam.AsInteger()); }
                                        catch { }
                                        break;

                                    case StorageType.String:
                                        try { recipientParam.Set(sourceParam.AsString()); }
                                        catch { }
                                        break;
                                    }
                                }
                            }
                        }

                        if (cameraInfo.ViewTemplateId != ElementId.InvalidElementId)
                        {
                            ElementId templateId = GetLinkedItem(sModel, rModel, MapType.ViewTemplate, cameraInfo.ViewTemplateId);
                            if (templateId != ElementId.InvalidElementId && createdView.IsValidViewTemplate(templateId))
                            {
                                createdView.ViewTemplateId = templateId;
                            }
                            else
                            {
                                MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "View Template", "");
                                missingItems.Add(missingItem);
                            }
                        }

                        if (cameraInfo.PhaseId != ElementId.InvalidElementId)
                        {
                            ElementId phaseId = GetLinkedItem(sModel, rModel, MapType.Phase, cameraInfo.PhaseId);
                            if (phaseId != ElementId.InvalidElementId)
                            {
                                Parameter param = createdView.get_Parameter(BuiltInParameter.VIEW_PHASE);
                                if (null != param)
                                {
                                    param.Set(phaseId);
                                }
                            }
                            else
                            {
                                MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "Phase", "");
                                missingItems.Add(missingItem);
                            }
                        }

                        if (viewConfig.ApplyWorksetVisibility && cameraInfo.WorksetVisibilities.Count > 0)
                        {
                            bool worksetFound = true;
                            foreach (WorksetId wsId in cameraInfo.WorksetVisibilities.Keys)
                            {
                                WorksetVisibility wsVisibility = cameraInfo.WorksetVisibilities[wsId];
                                WorksetId         worksetId    = GetLinkedWorkset(sModel, rModel, wsId);
                                if (worksetId != WorksetId.InvalidWorksetId)
                                {
                                    createdView.SetWorksetVisibility(worksetId, wsVisibility);
                                }
                                else
                                {
                                    worksetFound = false;
                                }
                            }
                            if (!worksetFound)
                            {
                                MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "Workset", "");
                                missingItems.Add(missingItem);
                            }
                        }

                        createdViewInfo = new CameraViewInfo(createdView);
                        createdViewInfo.LinkedViewId = cameraInfo.ViewId;
                        createdViewInfo.Linked       = true;
                        duplicated = true;
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.RollBack();
                        string message = ex.Message;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to duplicate camera views.\n" + ex.Message, "Duplicate Camera Views", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(duplicated);
        }