Esempio n. 1
0
        public void ShowElements(List <MonitorMessage> selectedMessages)
        {
            try
            {
                UIDocument       uidoc       = m_app.ActiveUIDocument;
                List <ElementId> selectedIds = new List <ElementId>();

#if RELEASE2013 || RELEASE2014
                SelElementSet selElements = SelElementSet.Create();
                foreach (MonitorMessage message in selectedMessages)
                {
                    selElements.Add(message.ElementObj);
                    selectedIds.Add(message.ElementObj.Id);
                }
                uidoc.Selection.Elements = selElements;
                uidoc.ShowElements(selectedIds);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                foreach (MonitorMessage message in selectedMessages)
                {
                    selectedIds.Add(message.ElementObj.Id);
                }
                uidoc.Selection.SetElementIds(selectedIds);
                uidoc.ShowElements(selectedIds);
#endif
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to show elements.\n" + ex.Message, "Show Elements", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Esempio n. 2
0
        private void HighlightElement()
        {
            using (var trans = new Transaction(CurrentDocument))
            {
                trans.Start("Select Element");
                try
                {
                    var uidoc = new UIDocument(CurrentDocument);
#if RELEASE2014
                    Element element = m_doc.GetElement(selectedLinkedInfo.LinkedElementId);
                    if (null != element)
                    {
                        SelElementSet selElements = uidoc.Selection.Elements;
                        selElements.Insert(element);

                        uidoc.Selection.Elements = selElements;
                    }
#else
                    var selectedIds = new List <ElementId>
                    {
                        SelectedLinkedInfo.LinkedElementId
                    };
                    uidoc.Selection.SetElementIds(selectedIds);
#endif
                    uidoc.ShowElements(SelectedLinkedInfo.LinkedElementId);
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.RollBack();
                    MessageBox.Show("Failed to select an element.\n" + ex.Message, "Select Element", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
Esempio n. 3
0
        private void menuViewElement_Click(object sender, EventArgs e)
        {
            using (Transaction trans = new Transaction(doc))
            {
                try
                {
                    trans.Start("Show Elements");
                    UIDocument       uidoc      = m_app.ActiveUIDocument;
                    List <ElementId> elementIds = new List <ElementId>();

#if RELEASE2013 || RELEASE2014
                    SelElementSet newSelection = SelElementSet.Create();

                    foreach (DataGridViewRow row in dataGridViewRoom.SelectedRows)
                    {
                        if (null != row.Tag)
                        {
                            RoomProperties rp        = row.Tag as RoomProperties;
                            ElementId      elementId = new ElementId(rp.ID);
                            Element        element   = doc.GetElement(elementId);
                            if (null != element)
                            {
                                newSelection.Add(element);
                                elementIds.Add(elementId);
                            }
                        }
                    }
                    uidoc.ShowElements(elementIds);
                    uidoc.Selection.Elements = newSelection;
#elif RELEASE2015 || RELEASE2016
                    Selection selection = uidoc.Selection;

                    foreach (DataGridViewRow row in dataGridViewRoom.SelectedRows)
                    {
                        if (null != row.Tag)
                        {
                            RoomProperties rp        = row.Tag as RoomProperties;
                            ElementId      elementId = new ElementId(rp.ID);
                            Element        element   = doc.GetElement(elementId);
                            if (null != element)
                            {
                                elementIds.Add(elementId);
                            }
                        }
                    }
                    uidoc.ShowElements(elementIds);
                    selection.SetElementIds(elementIds);
#endif
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to view elements.\n" + ex.Message, "Form_RoomMass: menuViewElement_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                }
            }
        }
Esempio n. 4
0
        //execute or cancel
        private void HighlightElement(bool execute, Document doc)
        {
            try
            {
                UIDocument uidoc = new UIDocument(doc);
                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Highlight");
                    try
                    {
                        Element element = m_doc.GetElement(new ElementId(currentElement.ElementId));
                        if (null != element)
                        {
                            if (execute)
                            {
#if RELEASE2013 || RELEASE2014
                                SelElementSet selElements = SelElementSet.Create();
                                selElements.Add(element);
                                uidoc.Selection.Elements = selElements;
                                uidoc.ShowElements(element);
#elif RELEASE2015 || RELEASE2016
                                List <ElementId> selectedIds = new List <ElementId>();
                                selectedIds.Add(element.Id);
                                uidoc.Selection.SetElementIds(selectedIds);
                                uidoc.ShowElements(element.Id);
#endif
                            }
                            else
                            {
#if RELEASE2013 || RELEASE2014
                                SelElementSet selElementSet = SelElementSet.Create();
                                uidoc.Selection.Elements = selElementSet;
#elif RELEASE2015 || RELEASE2016
                                uidoc.Selection.SetElementIds(new List <ElementId>());
#endif
                            }
                            uidoc.RefreshActiveView();
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(currentElement.ElementName + ": Failed to highlight elements.\n" + ex.Message, "Highlight Element", MessageBoxButton.OK, MessageBoxImage.Warning);
                        trans.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to highlight elements.\n" + ex.Message, "Highlight Elements", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Esempio n. 5
0
        public override void selectElements(List <string> elementIds)
        {
            SelElementSet elementsToBeSelected = SelElementSet.Create();

            elementIds.ForEach(eId => {
                Element e = doc.GetElement(new ElementId(int.Parse(eId)));
                if (e != null)
                {
                    elementsToBeSelected.Add(e);
                }
            });
            uidoc.Selection.Elements = elementsToBeSelected;
            uidoc.RefreshActiveView();
        }
Esempio n. 6
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            m_application = commandData.Application;
            m_document    = m_application.ActiveUIDocument;

            Transaction transaction = new Transaction(m_document.Document, "Create CompoundStructure for Wall");

            try
            {
                // Select at least a wall.
                SelElementSet selectedElements = m_document.Selection.Elements;
                if (selectedElements.IsEmpty)
                {
                    TaskDialog.Show("Error", "Please select one wall at least.");
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                // Create the CompoundStructure for wall.
                transaction.Start();
                if (selectedElements.IsEmpty)
                {
                    return(Result.Failed);
                }


                foreach (Element elem in selectedElements)
                {
                    Wall wall = elem as Wall;
                    if (wall != null)
                    {
                        CreateCSforWall(wall);
                        break;
                    }
                }
                transaction.Commit();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                // If any error, give error information and return failed
                message = ex.Message;
                transaction.RollBack();
                return(Result.Failed);
            }
        }
        private void showElementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                UIDocument       uidoc      = m_app.ActiveUIDocument;
                Document         m_doc      = uidoc.Document;
                List <ElementId> elementIds = new List <ElementId>();

#if RELEASE2013 || RELEASE2014
                SelElementSet newSelection = SelElementSet.Create();

                foreach (DataGridViewRow row in dataGridViewElement.SelectedRows)
                {
                    if (null != row.Tag)
                    {
                        ElementProperties ep        = row.Tag as ElementProperties;
                        ElementId         elementId = new ElementId(ep.ElementId);
                        elementIds.Add(elementId);
                        newSelection.Add(ep.ElementObj);
                    }
                }
                uidoc.ShowElements(elementIds);
                uidoc.Selection.Elements = newSelection;
#elif RELEASE2015 || RELEASE2016
                Selection selection = uidoc.Selection;

                foreach (DataGridViewRow row in dataGridViewElement.SelectedRows)
                {
                    if (null != row.Tag)
                    {
                        ElementProperties ep        = row.Tag as ElementProperties;
                        ElementId         elementId = new ElementId(ep.ElementId);
                        elementIds.Add(elementId);
                    }
                }
                uidoc.ShowElements(elementIds);
                selection.SetElementIds(elementIds);
#endif
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to show elements.\n" + ex.Message, "Form_OverlapMass:buttonDetermine_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                LogFileManager.AppendLog("showElementToolStripMenuItem_Click", ex.Message);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// get selected floor (slab)
        /// </summary>
        /// <param name="commandData">object which contains reference of Revit Application.</param>
        /// <returns>selected floor (slab)</returns>
        private Floor GetSelectFloor(ExternalCommandData commandData)
        {
            SelElementSet eleSet = commandData.Application.ActiveUIDocument.Selection.Elements;

            if (eleSet.Size != 1)
            {
                return(null);
            }

            IEnumerator iter = eleSet.GetEnumerator();

            iter.Reset();
            while (iter.MoveNext())
            {
                return(iter.Current as Floor);
            }
            return(null);
        }
        private void showElementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                UIDocument       uidoc      = m_app.ActiveUIDocument;
                Document         m_doc      = uidoc.Document;
                List <ElementId> elementIds = new List <ElementId>();

#if RELEASE2013 || RELEASE2014
                SelElementSet newSelection = SelElementSet.Create();

                foreach (DataGridViewRow row in dataGridViewElement.SelectedRows)
                {
                    if (null != row.Tag)
                    {
                        ElementProperties ep        = row.Tag as ElementProperties;
                        ElementId         elementId = new ElementId(ep.ElementId);
                        elementIds.Add(elementId);
                        newSelection.Add(ep.ElementObj);
                    }
                }
                uidoc.ShowElements(elementIds);
                uidoc.Selection.Elements = newSelection;
#else
                Selection selection = uidoc.Selection;

                foreach (DataGridViewRow row in dataGridViewElement.SelectedRows)
                {
                    if (null != row.Tag)
                    {
                        ElementProperties ep        = row.Tag as ElementProperties;
                        ElementId         elementId = new ElementId(ep.ElementId);
                        elementIds.Add(elementId);
                    }
                }
                uidoc.ShowElements(elementIds);
                selection.SetElementIds(elementIds);
#endif
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Esempio n. 10
0
        public void selectElements(List <Component> components)
        {
#if REVIT2014
            SelElementSet elementsToBeSelected = SelElementSet.Create();
            components.ForEach(component =>
            {
                Element e = doc.GetElement(new ElementId(int.Parse(component.AuthoringToolId)));
                if (e != null)
                {
                    elementsToBeSelected.Add(e);
                }
            });
            uidoc.Selection.Elements = elementsToBeSelected;
            uidoc.RefreshActiveView();
#else
            List <ElementId> elementsToBeSelected = new List <ElementId>();
            components.ForEach(component => elementsToBeSelected.Add(new ElementId(int.Parse(component.AuthoringToolId))));
            uidoc.Selection.SetElementIds(elementsToBeSelected);
#endif
        }
Esempio n. 11
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
                                                        , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                // Verify if the active document is null
                UIDocument activeDoc = commandData.Application.ActiveUIDocument;
                if (activeDoc == null)
                {
                    MessageBox.Show("There's no active document in Revit.", "No Active Document",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Verify the number of selected elements
                SelElementSet selElements = activeDoc.Selection.Elements;
                if (selElements.Size != 1)
                {
                    message = "Please select ONLY one element from current project.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Get the selected element
                Element selectedElement = null;
                foreach (Element element in selElements)
                {
                    selectedElement = element;
                    break;
                }

                // Get the expected mechanical or piping system from selected element
                // Some elements in a non-well-connected system may get lost when traversing
                //the system in the direction of flow; and
                // flow direction of elements in a non-well-connected system may not be right,
                // therefore the sample will only support well-connected system.
                MEPSystem system = ExtractMechanicalOrPipingSystem(selectedElement);
                if (system == null)
                {
                    message = "The selected element does not belong to any well-connected mechanical or piping system. " +
                              "The sample will not support well-connected systems for the following reasons: " +
                              Environment.NewLine +
                              "- Some elements in a non-well-connected system may get lost when traversing the system in the " +
                              "direction of flow" + Environment.NewLine +
                              "- Flow direction of elements in a non-well-connected system may not be right";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Traverse the system and dump the traversal into an XML file
                TraversalTree tree = new TraversalTree(activeDoc.Document, system);
                tree.Traverse();
                String fileName;
                fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "traversal.xml");
                tree.DumpIntoXML(fileName);

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Esempio n. 12
0
        public static void SelectElements(UIApplication uiApp, List <ElementId> elementIds)
        {
            var uidoc = uiApp.ActiveUIDocument;

            if (uidoc != null)
            {
                var doc = uiApp.ActiveUIDocument.Document;

                // is there is only one element and it has owner view
                // open the view, isolate the element, zoom fit the view, unisolate
                // this would zoom in on that element only
                if (doc != null && elementIds.Count >= 1)
                {
                    // get all open ui views, to be able to zoom later on
                    var openUIViews = uidoc.GetOpenUIViews();

                    // get the first one
                    var el = doc.GetElement(elementIds[0]);

                    // if element is a view, open the view
                    if (el.GetType().IsSubclassOf(typeof(View)))
                    {
                        uidoc.ActiveView = (View)el;
                    }
                    // if element is a 2D element and has an owner view
                    // open the view and zoom to element
                    else if (el.OwnerViewId != ElementId.InvalidElementId)
                    {
                        // if all 2D elements are in the same view
                        bool sameOwnerView = true;
                        foreach (var elid in elementIds)
                        {
                            if (doc.GetElement(elid).OwnerViewId != el.OwnerViewId)
                            {
                                sameOwnerView = false;
                            }
                        }

                        if (sameOwnerView)
                        {
                            // get the view and activate
                            View view = (View)doc.GetElement(el.OwnerViewId);
                            uidoc.ActiveView = view;

                            // islolate the element, deselect, and zoom fit
                            // add host elements for tags since tags will not be visible without their host
                            var elementIdsToIsolate = new List <ElementId>();
                            foreach (var elid in elementIds)
                            {
                                var element = doc.GetElement(elid);
                                if (element.GetType() == typeof(IndependentTag))
                                {
                                    var hostId = ((IndependentTag)element).TaggedLocalElementId;
                                    if (hostId != ElementId.InvalidElementId)
                                    {
                                        elementIdsToIsolate.Add(hostId);
                                    }
                                }
                            }

                            elementIdsToIsolate.AddRange(elementIds);
                            view.IsolateElementsTemporary(elementIdsToIsolate);
                            uidoc.Selection.Elements = SelElementSet.Create();
                            foreach (var uiview in openUIViews)
                            {
                                if (uiview.ViewId == view.Id)
                                {
                                    uiview.ZoomToFit();
                                }
                            }

                            // set the view back to normal
                            view.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                        }
                    }
                    // if element is a 3D element and does not have an owner view
                    // get the current view and try to zoom the element
                    else if (el.OwnerViewId == ElementId.InvalidElementId)
                    {
                        // get the current view
                        View view = (View)uidoc.ActiveView;

                        // islolate the element, deselect, and zoom fit
                        view.IsolateElementsTemporary(elementIds);
                        uidoc.Selection.Elements = SelElementSet.Create();
                        foreach (var uiview in openUIViews)
                        {
                            if (uiview.ViewId == view.Id)
                            {
                                uiview.ZoomToFit();
                            }
                        }

                        // set the view back to normal
                        view.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    }
                }

                // now select the element(s)
                var elementSet = SelElementSet.Create();
                foreach (ElementId elId in elementIds)
                {
                    var element = doc.GetElement(elId);
                    if (element != null)
                    {
                        elementSet.Add(element);
                    }
                }

                uidoc.Selection.Elements = elementSet;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of TagBeamData.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command</param>
        public TagBeamData(ExternalCommandData commandData)
        {
            //Get beams selected
            m_revitDoc   = commandData.Application.ActiveUIDocument;
            m_docCreator = m_revitDoc.Document.Create;
            m_view       = m_revitDoc.Document.ActiveView;

            SelElementSet      elementSet = m_revitDoc.Selection.Elements;
            ElementSetIterator itor       = elementSet.ForwardIterator();

            while (itor.MoveNext())
            {
                FamilyInstance familyInstance = itor.Current as FamilyInstance;
                if ((familyInstance != null) && (familyInstance.StructuralType == Autodesk.Revit.DB.Structure.StructuralType.Beam))
                {
                    m_beamList.Add(familyInstance);
                }
            }
            if (m_beamList.Count < 1)
            {
                throw new ApplicationException("there is no beam selected");
            }

            //Get the family symbols of tag in this document.
            FilteredElementCollector collector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document);
            IList <Element>          elements  = collector.OfClass(typeof(Family)).ToElements();

            foreach (Family family in elements)
            {
                if (family != null && family.Symbols != null)
                {
                    FamilySymbolSetIterator it = family.Symbols.ForwardIterator();
                    while (it.MoveNext())
                    {
                        try
                        {
                            FamilySymbol tagSymbol = it.Current as FamilySymbol;
                            if (tagSymbol != null)
                            {
                                switch (tagSymbol.Category.Name)
                                {
                                case "Structural Framing Tags":
                                    m_categoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                case "Material Tags":
                                    m_materialTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                case "Multi-Category Tags":
                                    m_multiCategoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                default:
                                    continue;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            if (ProductType.MEP != app.Application.Product)
            {
                message = "Please run this command in Revit MEP.";
                return(Result.Failed);
            }

            SelElementSet sel = uidoc.Selection.Elements;

            if (0 == sel.Size)
            {
                message = "Please select some rectangular ducts.";
                return(Result.Failed);
            }

            // set up log file:

            string log = Assembly.GetExecutingAssembly().Location
                         + "." + DateTime.Now.ToString("yyyyMMdd")
                         + ".log";

            if (File.Exists(log))
            {
                File.Delete(log);
            }

            TraceListener listener
                = new TextWriterTraceListener(log);

            Trace.Listeners.Add(listener);

            try
            {
                Trace.WriteLine("Begin");

                // loop over all selected ducts:

                foreach (Duct duct in sel)
                {
                    if (null == duct)
                    {
                        Trace.TraceError("The selection is not a duct!");
                    }
                    else
                    {
                        // process each duct:

                        Trace.WriteLine("========================");
                        Trace.WriteLine("Duct: Id = " + duct.Id.IntegerValue);

                        AnalyseDuct(duct);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            finally
            {
                Trace.Flush();
                listener.Close();
                Trace.Close();
                Trace.Listeners.Remove(listener);
            }
            return(Result.Failed);
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
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);
            }
        }
Esempio n. 17
0
        private void buttonShow_Click(object sender, EventArgs e)
        {
            try
            {
                if (listViewComponents.SelectedItems.Count > 0)
                {
                    //Would you like to create a 3dview?
                    if (!view3dDictionary.ContainsKey(selectedView))
                    {
                        DialogResult dr = MessageBox.Show("Would you like to create a 3DView including all components for the selected issues?\n View Name:" + selectedView, "Create a 3DView", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            if (Create3DView())
                            {
                                MessageBox.Show("[" + selectedView + "] was successfully created in 3DView.\n Please open this view to find the model elements.", "Created 3DView", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }

                    UIDocument       uidoc      = m_app.ActiveUIDocument;
                    List <ElementId> elementIds = new List <ElementId>();
#if RELEASE2015
                    Selection selection = uidoc.Selection;
                    foreach (ListViewItem item in listViewComponents.SelectedItems)
                    {
                        if (null != item.Tag)
                        {
                            Element element = item.Tag as Element;
                            if (null != element)
                            {
                                ElementId elementId = element.Id;
                                elementIds.Add(elementId);
                            }
                        }
                    }


                    if (elementIds.Count > 0)
                    {
                        //uidoc.ActiveView.IsolateElementsTemporary(elementIds);
                        uidoc.ShowElements(elementIds);//+ make selection
                        selection.SetElementIds(elementIds);;
                    }
#else
                    SelElementSet newSelection = SelElementSet.Create();

                    foreach (ListViewItem item in listViewComponents.SelectedItems)
                    {
                        if (null != item.Tag)
                        {
                            Element element = item.Tag as Element;
                            if (null != element)
                            {
                                ElementId elementId = element.Id;
                                elementIds.Add(elementId);
                                newSelection.Add(element);
                            }
                        }
                    }
                    if (elementIds.Count > 0)
                    {
                        //uidoc.ActiveView.IsolateElementsTemporary(elementIds);
                        uidoc.ShowElements(elementIds);//+ make selection
                        uidoc.Selection.Elements = newSelection;
                    }
#endif
                }
                else
                {
                    MessageBox.Show("Please select at least one component item to show elements in Revit UI.", "Select an Item.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to show Revit elements.\n" + ex.Message, "CommandForm:buttonShow_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// found the element which using the GUID
        /// that was assigned to the shared parameter in the shared parameters file.
        /// </summary>
        /// <param name="UniqueIdValue"></param>
        public void FindElement(string UniqueIdValue)
        {
            SelElementSet seleElements = m_revit.ActiveUIDocument.Selection.Elements;

            // all the elements of current document
            IEnumerator i = seleElements.GetEnumerator();


            // if the selections include beams and slabs,
            // find out the element using the select value for display
            i.Reset();
            bool moreElements = i.MoveNext();

            while (moreElements)
            {
                // Get beams and slabs from selections
                Element component = i.Current as Autodesk.Revit.DB.Element;

                if (null == component)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (null == component.Category)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (("Structural Framing" != component.Category.Name) &&
                    ("Floors" != component.Category.Name))
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                // Get "Unique ID" parameter
                ParameterSet attributes = component.Parameters;

                foreach (object o in attributes)
                {
                    Parameter attribute = o as Parameter;

                    if ("Unique ID" == attribute.Definition.Name)
                    {
                        if (null == attribute.AsString())
                        {
                            break;
                        }

                        // compare if the parameter's value is the same as the selected value.
                        // Clear the SelElementSet and add the found element into it.
                        // So this element will highlight in Revit UI
                        if (UniqueIdValue == attribute.AsString())
                        {
                            seleElements.Clear();
                            seleElements.Add(component);
                            return;
                        }

                        break;
                    }
                }

                moreElements = i.MoveNext();
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message,
                                                ElementSet elements)
        {
            // set out default result to failure.
            Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed;

            Autodesk.Revit.UI.UIApplication app = commandData.Application;

            // get the elements selected
            // The current selection can be retrieved from the active
            // document via the selection object
            SelElementSet seletion = app.ActiveUIDocument.Selection.Elements;

            // we need to make sure that only one element is selected.
            if (seletion.Size == 1)
            {
                // we need to get the first and only element in the selection. Do this by getting
                // an iterator. MoveNext and then get the current element.
                ElementSetIterator it = seletion.ForwardIterator();
                it.MoveNext();
                Element element = it.Current as Element;

                // Next we need to iterate through the parameters of the element,
                // as we iterating, we will store the strings that are to be displayed
                // for the parameters in a string list "parameterItems"
                List <string> parameterItems = new List <string>();
                ParameterSet  parameters     = element.Parameters;
                foreach (Parameter param in parameters)
                {
                    if (param == null)
                    {
                        continue;
                    }

                    // We will make a string that has the following format,
                    // name type value
                    // create a StringBuilder object to store the string of one parameter
                    // using the character '\t' to delimit parameter name, type and value
                    StringBuilder sb = new StringBuilder();

                    // the name of the parameter can be found from its definition.
                    sb.AppendFormat("{0}\t", param.Definition.Name);

                    // Revit parameters can be one of 5 different internal storage types:
                    // double, int, string, Autodesk.Revit.DB.ElementId and None.
                    // if it is double then use AsDouble to get the double value
                    // then int AsInteger, string AsString, None AsStringValue.
                    // Switch based on the storage type
                    switch (param.StorageType)
                    {
                    case Autodesk.Revit.DB.StorageType.Double:
                        // append the type and value
                        sb.AppendFormat("double\t{0}", param.AsDouble());
                        break;

                    case Autodesk.Revit.DB.StorageType.ElementId:
                        // for element ids, we will try and retrieve the element from the
                        // document if it can be found we will display its name.
                        sb.Append("Element\t");

                        // using ActiveDocument.GetElement(the element id) to
                        // retrieve the element from the active document
                        Autodesk.Revit.DB.ElementId elemId = new ElementId(param.AsElementId().IntegerValue);
                        Element elem = app.ActiveUIDocument.Document.GetElement(elemId);

                        // if there is an element then display its name,
                        // otherwise display the fact that it is not set
                        sb.Append(elem != null ? elem.Name : "Not set");
                        break;

                    case Autodesk.Revit.DB.StorageType.Integer:
                        // append the type and value
                        sb.AppendFormat("int\t{0}", param.AsInteger());
                        break;

                    case Autodesk.Revit.DB.StorageType.String:
                        // append the type and value
                        sb.AppendFormat("string\t{0}", param.AsString());
                        break;

                    case Autodesk.Revit.DB.StorageType.None:
                        // append the type and value
                        sb.AppendFormat("none\t{0}", param.AsValueString());
                        break;

                    default:
                        break;
                    }

                    // add the completed line to the string list
                    parameterItems.Add(sb.ToString());
                }

                // Create our dialog, passing it the parameters array for display.
                PropertiesForm propertiesForm = new PropertiesForm(parameterItems.ToArray());
                propertiesForm.StartPosition = FormStartPosition.CenterParent;
                propertiesForm.ShowDialog();
                retRes = Autodesk.Revit.UI.Result.Succeeded;
            }
            else
            {
                message = "Please select only one element";
            }
            return(retRes);
        }
Esempio n. 20
0
        /// <summary>
        /// Program entry point
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns>Result</returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                UIApplication uiapp = commandData.Application;
                UIDocument    uidoc = uiapp.ActiveUIDocument;
                Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                Document doc = uidoc.Document;

                // Determine elements to export
                FilteredElementCollector collector = null;

                // Access current selection
                SelElementSet set = uidoc.Selection.Elements;

                int n = set.Size;

                if (0 < n)
                {
                    // If any elements were preselected, export those
                    ICollection <ElementId> ids = set
                                                  .Cast <Element>()
                                                  .Select <Element, ElementId>(e => e.Id)
                                                  .ToArray <ElementId>();

                    collector = new FilteredElementCollector(doc, ids);
                }
                else
                {
                    // If nothing was preselected, export everything
                    collector = new FilteredElementCollector(doc);
                }

                collector.WhereElementIsNotElementType()
                .WhereElementIsViewIndependent();

                if (null == _exportFolderName)
                {
                    _exportFolderName = Path.GetTempPath();
                }

                string filename = null;

                if (!FileSelect(_exportFolderName,
                                out filename))
                {
                    return(Result.Cancelled);
                }

                _exportFolderName = Path.GetDirectoryName(filename);
                Command exporter = new Command();
                Options opt      = app.Create.NewGeometryOptions();
                ExportElements(exporter, collector, opt);
                exporter.ExportTo(filename);

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, ElementSet elements)
        {
            Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded;
            try
            {
                UIDocument activeDoc = commandData.Application.ActiveUIDocument;
                string     str;

                Material materialElement = null;

                SelElementSet selection = activeDoc.Selection.Elements;
                if (selection.Size != 1)
                {
                    message = "Please select only one element.";
                    res     = Autodesk.Revit.UI.Result.Failed;
                    return(res);
                }

                System.Collections.IEnumerator iter;
                iter = activeDoc.Selection.Elements.ForwardIterator();
                iter.MoveNext();

                // we need verify the selected element is a family instance
                FamilyInstance famIns = iter.Current as FamilyInstance;
                if (famIns == null)
                {
                    TaskDialog.Show("Revit", "Not a type of FamilyInsance!");
                    res = Autodesk.Revit.UI.Result.Failed;
                    return(res);
                }

                // we need select a column instance
                foreach (Parameter p in famIns.Parameters)
                {
                    string parName = p.Definition.Name;
                    // The "Beam Material" and "Column Material" family parameters have been replaced
                    // by the built-in parameter "Structural Material".
                    //if (parName == "Column Material" || parName == "Beam Material")
                    if (parName == "Structural Material")
                    {
                        Autodesk.Revit.DB.ElementId elemId = p.AsElementId();
                        materialElement = activeDoc.Document.GetElement(elemId) as Material;
                        break;
                    }
                }

                if (materialElement == null)
                {
                    TaskDialog.Show("Revit", "Not a column!");
                    res = Autodesk.Revit.UI.Result.Failed;
                    return(res);
                }

                // the PHY_MATERIAL_PARAM_TYPE built in parameter contains a number
                // that represents the type of material
                Parameter materialType =
                    materialElement.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_TYPE);

                str = "Material type: " +
                      (materialType.AsInteger() == 0 ?
                       "Generic" : (materialType.AsInteger() == 1 ? "Concrete" : "Steel")) + "\r\n";

                // A material type of more than 0 : 0 = Generic, 1 = Concrete, 2 = Steel
                if (materialType.AsInteger() > 0)
                {
                    // Common to all types

                    // Young's Modulus
                    double[] youngsModulus = new double[3];

                    youngsModulus[0] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD1).AsDouble();
                    youngsModulus[1] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD2).AsDouble();
                    youngsModulus[2] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD3).AsDouble();
                    str = str + "Young's modulus: " + youngsModulus[0].ToString() +
                          "," + youngsModulus[1].ToString() + "," + youngsModulus[2].ToString() +
                          "\r\n";

                    // Poisson Modulus
                    double[] PoissonRatio = new double[3];

                    PoissonRatio[0] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD1).AsDouble();
                    PoissonRatio[1] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD2).AsDouble();
                    PoissonRatio[2] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD3).AsDouble();
                    str = str + "Poisson modulus: " + PoissonRatio[0].ToString() +
                          "," + PoissonRatio[1].ToString() + "," + PoissonRatio[2].ToString() +
                          "\r\n";

                    // Shear Modulus
                    double[] shearModulus = new double[3];

                    shearModulus[0] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD1).AsDouble();
                    shearModulus[1] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD2).AsDouble();
                    shearModulus[2] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD3).AsDouble();
                    str = str + "Shear modulus: " + shearModulus[0].ToString() +
                          "," + shearModulus[1].ToString() + "," + shearModulus[2].ToString() + "\r\n";

                    // Thermal Expansion Coefficient
                    double[] thermalExpCoeff = new double[3];

                    thermalExpCoeff[0] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF1).AsDouble();
                    thermalExpCoeff[1] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF2).AsDouble();
                    thermalExpCoeff[2] = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF3).AsDouble();
                    str = str + "Thermal expansion coefficient: " + thermalExpCoeff[0].ToString() +
                          "," + thermalExpCoeff[1].ToString() + "," + thermalExpCoeff[2].ToString() +
                          "\r\n";

                    // Unit Weight
                    double unitWeight;
                    unitWeight = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_UNIT_WEIGHT).AsDouble();
                    str = str + "Unit weight: " + unitWeight.ToString() + "\r\n";

                    // Damping Ratio
                    double dampingRatio;
                    dampingRatio = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_DAMPING_RATIO).AsDouble();
                    str = str + "Damping ratio: " + dampingRatio.ToString() + "\r\n";

                    // Behavior 0 = Isotropic, 1 = Orthotropic
                    int behaviour;
                    behaviour = materialElement.get_Parameter(
                        BuiltInParameter.PHY_MATERIAL_PARAM_BEHAVIOR).AsInteger();
                    str = str + "Behavior: " + behaviour.ToString() + "\r\n";

                    // Concrete Only
                    if (materialType.AsInteger() == 1)
                    {
                        // Concrete Compression
                        double concreteCompression;
                        concreteCompression = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_CONCRETE_COMPRESSION).AsDouble();
                        str = str + "Concrete compression: " + concreteCompression.ToString() + "\r\n";

                        // Lightweight
                        double lightWeight;
                        lightWeight = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_LIGHT_WEIGHT).AsDouble();
                        str = str + "Lightweight: " + lightWeight.ToString() + "\r\n";

                        // Shear Strength Reduction
                        double shearStrengthReduction;
                        shearStrengthReduction = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_STRENGTH_REDUCTION).AsDouble();
                        str = str + "Shear strength reduction: " + shearStrengthReduction.ToString() + "\r\n";
                    }
                    // Steel only
                    else if (materialType.AsInteger() == 2)
                    {
                        // Minimum Yield Stress
                        double minimumYieldStress;
                        minimumYieldStress = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_YIELD_STRESS).AsDouble();
                        str = str + "Minimum yield stress: " + minimumYieldStress.ToString() + "\r\n";

                        // Minimum Tensile Strength
                        double minimumTensileStrength;
                        minimumTensileStrength = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_TENSILE_STRENGTH).AsDouble();
                        str = str + "Minimum tensile strength: " +
                              minimumTensileStrength.ToString() + "\r\n";

                        // Reduction Factor
                        double reductionFactor;
                        reductionFactor = materialElement.get_Parameter(
                            BuiltInParameter.PHY_MATERIAL_PARAM_REDUCTION_FACTOR).AsDouble();
                        str = str + "Reduction factor: " + reductionFactor.ToString() + "\r\n";
                    } // end of if/else materialType.Integer == 1
                }     // end if materialType.Integer > 0

                TaskDialog.Show("Physical materials", str);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("PhysicalProp", ex.Message);
                res = Autodesk.Revit.UI.Result.Failed;
            }
            finally
            {
            }

            return(res);
        } // end command
Esempio n. 22
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);
            }
        }