Ejemplo n.º 1
2
 /// <summary>
 /// Constructor with display unit type
 /// </summary>
 /// <param name="application">Revit application</param>
 /// <param name="labels">All existing labels in Revit's document</param>
 /// <param name="dut">Current length display unit type</param>
 public CreateGridsData(UIApplication application, ArrayList labels, DisplayUnitType dut)
 {
     m_revitDoc = application.ActiveUIDocument.Document;
     m_appCreator = application.Application.Create;
     m_docCreator = application.ActiveUIDocument.Document.Create;
     m_labelsList = labels;
     m_dut = dut;
 }
Ejemplo n.º 2
1
        Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit

        #endregion Fields

        #region Constructors

        // Methods
        /// <summary>
        /// Default constructor of LoadCombinationDeal
        /// </summary>
        public LoadCombinationDeal(Loads dataBuffer)
        {
            m_dataBuffer = dataBuffer;
            m_revit = dataBuffer.RevitApplication;
            UIApplication uiapplication = new UIApplication(m_revit);
            m_document = uiapplication.ActiveUIDocument.Document;
        }
Ejemplo n.º 3
1
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="app">Revit application</param>
 /// <param name="doc">Revit document</param>
 private ProximityDetection(
  Autodesk.Revit.ApplicationServices.Application app, 
  Autodesk.Revit.DB.Document doc)
 {
     m_app = app;
      m_doc = doc;
 }
Ejemplo n.º 4
1
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="app">Revit application</param>
 /// <param name="doc">Revit document</param>
 private WallJoinControl(
  Autodesk.Revit.ApplicationServices.Application app, 
  Autodesk.Revit.DB.Document doc)
 {
     m_app = app;
      m_doc = doc;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Basic setup -- stores references to the active document and PerformanceAdviser for later use
 /// </summary>
 /// <param name="performanceAdviser">The revit PerformanceAdviser class</param>
 /// <param name="document">The active document</param>
 public TestDisplayDialog(PerformanceAdviser performanceAdviser, Document document)
 {
     m_PerformanceAdviser = performanceAdviser;
      m_document = document;
      InitializeComponent();
      this.FormBorderStyle = FormBorderStyle.Fixed3D;
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Create sample custom FilterData with specified categories and FilterRuleBuilder
 /// </summary>
 /// <param name="doc">Revit active document.</param>
 /// <param name="categories">BuilInCategories of filter.</param>
 /// <param name="filterRules">FilterRuleBuilder set of filter.</param>
 public FilterData(Autodesk.Revit.DB.Document doc,
     ICollection<BuiltInCategory> categories, ICollection<FilterRuleBuilder> filterRules)
 {
     m_doc = doc;
     m_filterCategories = new List<BuiltInCategory>();
     m_filterCategories.AddRange(categories);
     m_filterRules = new List<FilterRuleBuilder>();
     m_filterRules.AddRange(filterRules);
 }
Ejemplo n.º 7
0
 public CollectorExt()
 {
     // add ourselves to the event list of all SnoopCollectors
     Snoop.Collectors.Collector.OnCollectorExt += new Snoop.Collectors.Collector.CollectorExt(CollectEvent);
     if (m_app != null && m_app.ActiveUIDocument != null && m_app.ActiveUIDocument.Document != null)
     {
         m_activeDoc = m_app.ActiveUIDocument.Document;
     }
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="doc">Revit document</param>
        /// <param name="proximityDetection">The object that is responsible for proximity detection</param>
        /// <param name="walljoinControl">The object that is responsible for controlling the joint of walls</param>
        public ProximityDetectionAndWallJoinControlForm(Autodesk.Revit.DB.Document doc, 
         ProximityDetection proximityDetection, 
         WallJoinControl walljoinControl)
        {
            InitializeComponent();

             m_doc = doc;
             m_proximityDetection = proximityDetection;
             m_walljoinControl = walljoinControl;
        }
Ejemplo n.º 9
0
        //Constructor
        public QREncoder(Document doc, UIDocument uidoc, Application app)
        {
            base.QRCodeEncodeMode = ENCODE_MODE.BYTE;
            base.QRCodeVersion = 7;
            base.QRCodeErrorCorrect = ERROR_CORRECTION.M;
            base.QRCodeScale = 1;

            _doc = doc;
            _uiDoc = uidoc;
            _app = app;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create a new dialog object and store a reference to the active document and applicationID of this addin.
        /// </summary>
        public UICommand(Autodesk.Revit.DB.Document doc, string applicationId)
        {
            InitializeComponent();
             this.Closing += new System.ComponentModel.CancelEventHandler(UICommand_Closing);
             m_Document = doc;

             //Create a new empty schemaWrapper.
             m_SchemaWrapper = SchemaWrapperTools.SchemaWrapper.NewSchema(Guid.Empty, Autodesk.Revit.DB.ExtensibleStorage.AccessLevel.Public, Autodesk.Revit.DB.ExtensibleStorage.AccessLevel.Public, "adsk", applicationId, "schemaName", "Schema documentation");
             this.m_label_applicationAppId.Content = applicationId;
             UpdateUI();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="exEvent"></param>
 /// <param name="handler"></param>
 public Interface(UIApplication uiapp, Autodesk.Revit.UI.ExternalEvent exEvent, RequestHandler handler)
 {
     this.uiapp = uiapp;
     this.uidoc = uiapp.ActiveUIDocument;
     this.doc = uidoc.Document;
     this.exEvent = exEvent;
     this.handler = handler;
     this.famParam = new SortedList<string, FamilyParameter>();
     InitializeComponent();
     this.SetStyle(
         ControlStyles.AllPaintingInWmPaint |
         ControlStyles.UserPaint |
         ControlStyles.DoubleBuffer, true);
     this.StartPosition = FormStartPosition.Manual;
     this.Location = new System.Drawing.Point(Screen.PrimaryScreen.WorkingArea.Width - 400, Convert.ToInt32(Screen.PrimaryScreen.WorkingArea.Height * 0.5 - this.Height * 0.5));
     CollectData();
 }
        public Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            m_uiApp = revit.Application;
              m_app = m_uiApp.Application;
              m_uiDoc = m_uiApp.ActiveUIDocument;
              m_doc = m_uiDoc.Document;

              TaskDialog.Show( "Test application",
            "Revit version: " + m_app.VersionBuild );

              m_writer = new StreamWriter( @"C:\SRD201483.txt" );

              WriteDimensionReferences( 161908 );
              WriteElementGeometry( 161900 );

              m_writer.Close();

              return Result.Succeeded;
        }
Ejemplo n.º 13
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;
            m_application = commandData.Application.Application;
            m_document = commandData.Application.ActiveUIDocument.Document;
            f = m_document.FamilyCreate;
            extrusions = new Extrusion[5];
            m_combineElements = new CombinableElementArray();

            m_transaction = new Transaction(m_document, "External Tool");
            m_transaction.Start();

            if (m_document.OwnerFamily.FamilyCategory.Name != "Mechanical Equipment")
            {
                message = "Please make sure you opened a template of Mechanical Equipment.";
                return retRes;
            }

            try
            {
                CreateExtrusions();
                m_document.Regenerate();
                CreateConnectors();
                m_document.Regenerate();
                m_document.CombineElements(m_combineElements);
                m_document.Regenerate();
            }
            catch(Exception x)
            {
                m_transaction.RollBack();
                message = x.Message;
                return retRes;
            }

            m_transaction.Commit();

            retRes = Autodesk.Revit.UI.Result.Succeeded;
            return retRes;
        }
Ejemplo n.º 14
0
      /// <summary>
      /// constructor
      /// </summary>
      /// <param name="commandData">
      /// object which contains reference of Revit Application
      /// </param>
      public MyDocument(ExternalCommandData commandData)
      {
         m_commandData = commandData;
         m_uiDocument = m_commandData.Application.ActiveUIDocument;
         m_document = m_uiDocument.Document;

         // initialize the curtain system data
         m_systemData = new CurtainSystem.SystemData(this);

         // get the curtain system type of the active Revit document
         GetCurtainSystemType();
      }
 public bool SolveOptionalType <T>(ref Optional <T> type, DB.Document doc, DB.ElementTypeGroup group, string paramName) where T : DB.ElementType
 {
     return(SolveOptionalType(ref type, doc, group, (document, name) => throw new ArgumentNullException(paramName), paramName));
 }
        void Iterate(IGH_DataAccess DA, DB.Document doc, CommitAction action)
        {
            var element = PreviousStructureEnumerator?.MoveNext() ?? false ?
                          (
                PreviousStructureEnumerator.Current is Types.Element x && doc.Equals(x.Document) ?
                doc.GetElement(x.Id) :
                null
                          ) :
                          null;

            if (element?.Pinned != false)
            {
                var previous = element;

                try
                {
                    action(doc, ref element);
                }
                catch (CancelException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Source}: {e.Message}");
                    element = null;
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException e)
                {
                    var message = e.Message.Split("\r\n".ToCharArray()).First().Replace("Application.ShortCurveTolerance", "Revit.ShortCurveTolerance");
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Source}: {message}");
                    element = null;
                }
                catch (Autodesk.Revit.Exceptions.ApplicationException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Source}: {e.Message}");
                    element = null;
                }
                catch (System.ComponentModel.WarningException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                    element = null;
                }
                catch (System.ArgumentNullException)
                {
                    // Grasshopper components use to send a Null when they receive a Null without throwing any error
                    element = null;
                }
                catch (System.ArgumentException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Source}: {e.Message}");
                    element = null;
                }
                catch (System.Exception e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                    DA.AbortComponentSolution();
                }
                finally
                {
                    if (previous is object && !ReferenceEquals(previous, element) && previous.IsValidObject)
                    {
                        previous.Document.Delete(previous.Id);
                    }

                    if (element?.IsValidObject == true)
                    {
                        element.Pinned = true;
                    }
                }
            }

            DA.SetData(0, element);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Overload the constructor
 /// </summary>
 /// <param name="commandData">an instance of Data class</param>
 public ViewFiltersForm(Autodesk.Revit.UI.ExternalCommandData commandData)
 {
     InitializeComponent();
     m_doc = commandData.Application.ActiveUIDocument.Document;
 }
Ejemplo n.º 18
0
        public PlotPointsForm(Autodesk.Revit.DB.Document doc)
        {
            InitializeComponent();

            this.doc = doc;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Create sample custom FilterData with specified category id and FilterRuleBuilder
 /// </summary>
 /// <param name="doc">Revit active document.</param>
 /// <param name="categories">BuilInCategory ids of filter.</param>
 /// <param name="filterRules">FilterRuleBuilder set of filter.</param>
 public FilterData(Autodesk.Revit.DB.Document doc,
     ICollection<ElementId> categories, ICollection<FilterRuleBuilder> filterRules)
 {
     m_doc = doc;
     m_filterCategories = new List<BuiltInCategory>();
     foreach (ElementId catId in categories)
         m_filterCategories.Add((BuiltInCategory)catId.IntegerValue);
     m_filterRules = new List<FilterRuleBuilder>();
     m_filterRules.AddRange(filterRules);
 }
Ejemplo n.º 20
0
 abstract public void WriteParameter(RVTDocument doc, string paramName, StorageType stype, object Value, bool rewrite);
Ejemplo n.º 21
0
        void ReconstructWallByCurve
        (
            DB.Document doc,
            ref DB.Wall element,

            Rhino.Geometry.Curve curve,
            Optional <DB.WallType> type,
            Optional <DB.Level> level,
            [Optional] double height,
            [Optional] DB.WallLocationLine locationLine,
            [Optional] bool flipped,
            [Optional, NickName("J")] bool allowJoins,
            [Optional] DB.Structure.StructuralWallUsage structuralUsage
        )
        {
#if REVIT_2020
            if
            (
                !(curve.IsLinear(Revit.VertexTolerance * Revit.ModelUnits) || curve.IsArc(Revit.VertexTolerance * Revit.ModelUnits) || curve.IsEllipse(Revit.VertexTolerance * Revit.ModelUnits)) ||
                !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance * Revit.ModelUnits) ||
                axisPlane.ZAxis.IsParallelTo(Rhino.Geometry.Vector3d.ZAxis) == 0
            )
            {
                ThrowArgumentException(nameof(curve), "Curve must be a horizontal line, arc or ellipse curve.");
            }
#else
            if
            (
                !(curve.IsLinear(Revit.VertexTolerance * Revit.ModelUnits) || curve.IsArc(Revit.VertexTolerance * Revit.ModelUnits)) ||
                !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance * Revit.ModelUnits) ||
                axisPlane.ZAxis.IsParallelTo(Rhino.Geometry.Vector3d.ZAxis) == 0
            )
            {
                ThrowArgumentException(nameof(curve), "Curve must be a horizontal line or arc curve.");
            }
#endif

            SolveOptionalType(ref type, doc, DB.ElementTypeGroup.WallType, nameof(type));

            bool levelIsEmpty = SolveOptionalLevel(doc, curve, ref level, out var bbox);

            if (height < Revit.VertexTolerance * Revit.ModelUnits)
            {
                height = type.GetValueOrDefault()?.GetCompoundStructure()?.SampleHeight *Revit.ModelUnits ?? LiteralLengthValue(6.0);
            }

            // Axis
            var levelPlane = new Rhino.Geometry.Plane(new Rhino.Geometry.Point3d(0.0, 0.0, level.Value.Elevation * Revit.ModelUnits), Rhino.Geometry.Vector3d.ZAxis);
            curve = Rhino.Geometry.Curve.ProjectToPlane(curve, levelPlane);

            var centerLine = curve.ToCurve();

            // LocationLine
            if (locationLine != DB.WallLocationLine.WallCenterline)
            {
                double offsetDist        = 0.0;
                var    compoundStructure = type.Value.GetCompoundStructure();
                if (compoundStructure == null)
                {
                    switch (locationLine)
                    {
                    case DB.WallLocationLine.WallCenterline:
                    case DB.WallLocationLine.CoreCenterline:
                        break;

                    case DB.WallLocationLine.FinishFaceExterior:
                    case DB.WallLocationLine.CoreExterior:
                        offsetDist = type.Value.Width / +2.0;
                        break;

                    case DB.WallLocationLine.FinishFaceInterior:
                    case DB.WallLocationLine.CoreInterior:
                        offsetDist = type.Value.Width / -2.0;
                        break;
                    }
                }
                else
                {
                    if (!compoundStructure.IsVerticallyHomogeneous())
                    {
                        compoundStructure = DB.CompoundStructure.CreateSimpleCompoundStructure(compoundStructure.GetLayers());
                    }

                    offsetDist = compoundStructure.GetOffsetForLocationLine(locationLine);
                }

                if (offsetDist != 0.0)
                {
                    centerLine = centerLine.CreateOffset(flipped ? -offsetDist : offsetDist, DB.XYZ.BasisZ);
                }
            }

            // Type
            ChangeElementTypeId(ref element, type.Value.Id);

            DB.Wall newWall = null;
            if (element is DB.Wall previousWall && previousWall.Location is DB.LocationCurve locationCurve && centerLine.IsSameKindAs(locationCurve.Curve))
            {
                newWall = previousWall;

                locationCurve.Curve = centerLine;
            }
Ejemplo n.º 22
0
 /// <summary>
 /// Yield the Parameter.
 /// </summary>
 /// <param name="defGroup">Definition group</param>
 public abstract void Commit(Autodesk.Revit.DB.Document doc, DefinitionGroup defGroup);
Ejemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="cat"></param>
        /// <param name="paramName"></param>
        /// <param name="grpName"></param>
        /// <param name="paramType"></param>
        /// <param name="visible"></param>
        /// <param name="instanceBinding"></param>
        /// <returns></returns>
        public static BindSharedParamResult BindSharedParam(DocRvt doc, Category cat, string paramName, string grpName,
                                                            ParameterType paramType, bool visible, bool instanceBinding)
        {
            try // generic
            {
                AppRvt app = doc.Application;

                // This is needed already here to store old ones for re-inserting
                CategorySet catSet = app.Create.NewCategorySet();

                // Loop all Binding Definitions
                // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !? For multiple categories, there is really one pair per each
                //                 category, even though the Definitions are the same...
                DefinitionBindingMapIterator iter = doc.ParameterBindings.ForwardIterator();
                while (iter.MoveNext())
                {
                    Definition     def      = iter.Key;
                    ElementBinding elemBind = (ElementBinding)iter.Current;

                    // Got param name match
                    if (paramName.Equals(def.Name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Check for category match - Size is always 1!
                        if (elemBind.Categories.Contains(cat))
                        {
                            // Check Param Type
                            if (paramType != def.ParameterType)
                            {
                                return(BindSharedParamResult.eWrongParamType);
                            }
                            // Check Binding Type
                            if (instanceBinding)
                            {
                                if (elemBind.GetType() != typeof(InstanceBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }
                            else
                            {
                                if (elemBind.GetType() != typeof(TypeBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }
                            // Check Visibility - cannot (not exposed)
                            // If here, everything is fine, ie already defined correctly
                            return(BindSharedParamResult.eAlreadyBound);
                        }
                        // If here, no category match, hence must store "other" cats for re-inserting
                        else
                        {
                            foreach (Category catOld in elemBind.Categories)
                            {
                                catSet.Insert(catOld);                                              //1 only, but no index...
                            }
                        }
                    }
                }

                // If here, there is no Binding Definition for it, so make sure Param defined and then bind it!
                DefinitionFile  defFile    = GetOrCreateSharedParamsFile(app);
                DefinitionGroup defGrp     = GetOrCreateSharedParamsGroup(defFile, grpName);
                Definition      definition = GetOrCreateSharedParamDefinition(defGrp, paramType, paramName, visible);
                catSet.Insert(cat);
                BindingRvt bind = null;
                if (instanceBinding)
                {
                    bind = app.Create.NewInstanceBinding(catSet);
                }
                else
                {
                    bind = app.Create.NewTypeBinding(catSet);
                }

                // There is another strange API "feature". If param has EVER been bound in a project (in above iter pairs or even if not there but once deleted), .Insert always fails!? Must use .ReInsert in that case.
                // See also similar findings on this topic in: http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html - the code-idiom below may be more generic:
                if (doc.ParameterBindings.Insert(definition, bind))
                {
                    return(BindSharedParamResult.eSuccessfullyBound);
                }
                else
                {
                    if (doc.ParameterBindings.ReInsert(definition, bind))
                    {
                        return(BindSharedParamResult.eSuccessfullyBound);
                    }
                    else
                    {
                        return(BindSharedParamResult.eFailed);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error in Binding Shared Param: {0}", ex.Message));
                return(BindSharedParamResult.eFailed);
            }

            //return BindSharedParamResult.eSuccessfullyBound;
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Gets or Creates Project Information (per-doc) shared param
 /// </summary>
 /// <param name="doc">Revit Document</param>
 /// <param name="paramName">Parameter Name</param>
 /// <param name="grpName">Param Group Name (relevant only when Creation takes place)</param>
 /// <param name="paramType">Param Type (relevant only when Creation takes place)</param>
 /// <param name="visible">Param UI Visibility (relevant only when Creation takes place)</param>
 /// <returns></returns>
 public static Parameter GetOrCreateProjInfoSharedParam(DocRvt doc, string paramName, string grpName, ParameterType paramType, bool visible)
 {
     // Just delegate the call using ProjectInfo Element
     return(GetOrCreateElemSharedParam(doc.ProjectInformation, paramName, grpName, paramType, visible, true));
 }
Ejemplo n.º 25
0
 internal Element(DB.Document doc, DB.ElementId id) : base(doc, id)
 {
 }
Ejemplo n.º 26
0
        public SheetsISFLRequest(UIApplication uiApp, String text)
        {
            MainUI     uiForm = BARevitTools.Application.thisApp.newMainUi;
            UIDocument uidoc  = uiApp.ActiveUIDocument;

            //Start a transaction
            Transaction t1 = new Transaction(uidoc.Document, "InsertSheetsFromLink");

            t1.Start();
            //Cycle through each row in the DataGridView
            foreach (DataGridViewRow row in uiForm.sheetsISFLDataGridView.Rows)
            {
                if (row.Cells["To Add"].Value != null)
                {
                    //If the checkbox to add the sheet is checked, and the sheet already exists
                    if (row.Cells["To Add"].Value.ToString() == "True" && row.Cells["Pre-exists"].Value.ToString() == "True")
                    {
                        //Get the sheet number of the old sheet
                        string sheetToDelete = row.Cells["Sheet Number"].Value.ToString();
                        //Collect the sheets in the project
                        IList <Element> sheetsCollector = new FilteredElementCollector(uidoc.Document).OfClass(typeof(ViewSheet)).ToElements();
                        foreach (Element elem in sheetsCollector)
                        {
                            ViewSheet viewSheet = elem as ViewSheet;
                            //If the sheet number of the sheet to delete matches the sheet being evaluated, and the sheet being evaluated is a placeholder, continue
                            //It is important that the sheet is placeholder and not a sheet that could potentially have views on it
                            if (viewSheet.SheetNumber == sheetToDelete && viewSheet.IsPlaceholder == true)
                            {
                                try
                                {
                                    //Use a subtransaction to delete the sheet view
                                    SubTransaction deleteTransaction = new SubTransaction(uidoc.Document);
                                    deleteTransaction.Start();
                                    uidoc.Document.Delete(viewSheet.Id);
                                    deleteTransaction.Commit();
                                }
                                catch { continue; }
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    //Otherwise, if the sheet does not already exist, continue
                    if (row.Cells["To Add"].Value.ToString() == "True")
                    {
                        try
                        {
                            //Create a new placeholder sheet
                            ViewSheet newSheet = ViewSheet.CreatePlaceholder(uidoc.Document);
                            newSheet.SheetNumber = row.Cells["Sheet Number"].Value.ToString();
                            //Set the new placeholder sheet's name
                            if (row.Cells["Host Sheet Name"].Value.ToString() == "" || row.Cells["Host Sheet Name"].Value.ToString() == "Sheet")
                            {
                                newSheet.Name = row.Cells["Link Sheet Name"].Value.ToString();
                            }
                            else
                            {
                                newSheet.Name = row.Cells["Host Sheet Name"].Value.ToString();
                            }
                            //Get the list of sheet parameters and find the BA Sheet Discipline parameter
                            IList <Parameter> disciplineParameters = newSheet.GetParameters(Properties.Settings.Default.BASheetDisciplineParameter);
                            foreach (Parameter param in disciplineParameters)
                            {
                                try
                                {
                                    //Set the BA Sheet Discipline from the value in the DataGridView
                                    param.Set(row.Cells["Discipline"].Value.ToString());
                                }
                                catch { continue; }
                            }
                        }
                        catch { continue; }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
            t1.Commit();
            //Update the DataGridView with fresh data using the inserted sheets and sheets from the link
            RVTDocument linkDoc = uiForm.SheetsISFLGetLinkDoc();

            uiForm.SheetsISFLUpdateDataGridView(linkDoc);
        }
 public DatumPlane(DB.Document doc, DB.ElementId id) : base(doc, id)
 {
 }
 public Level(DB.Document doc, DB.ElementId id) : base(doc, id)
 {
 }
 public FrmCutVoidConnection(a.Document doc)
 {
     _doc = doc;
     InitializeComponent();
     dic = CutVoidConnection.Instance.GetAllConnection(_doc);
 }
Ejemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="curve"></param>
        /// <param name="barType"></param>
        /// <param name="barStyle"></param>
        /// <param name="host"></param>
        /// <param name="startHook"></param>
        /// <param name="endHook"></param>
        /// <param name="startHookOrientation"></param>
        /// <param name="endHookOrientation"></param>
        /// <param name="normal"></param>
        /// <param name="useExistingShape"></param>
        /// <param name="createNewShape"></param>
        private void InitRebarContainer(System.Collections.Generic.List <object> curves,
                                        Autodesk.Revit.DB.Structure.RebarBarType barType,
                                        Autodesk.Revit.DB.Structure.RebarStyle barStyle,
                                        Autodesk.Revit.DB.Element host,
                                        Autodesk.Revit.DB.Structure.RebarHookType startHook,
                                        Autodesk.Revit.DB.Structure.RebarHookType endHook,
                                        Autodesk.Revit.DB.Structure.RebarHookOrientation startHookOrientation,
                                        Autodesk.Revit.DB.Structure.RebarHookOrientation endHookOrientation,
                                        System.Collections.Generic.List <Autodesk.Revit.DB.XYZ> normals,
                                        bool useExistingShape,
                                        bool createNewShape)
        {
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;

            TransactionManager.Instance.EnsureInTransaction(document);

            var rebarElem = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.Structure.RebarContainer>(document);

            // Parse Geometry

            List <List <Curve> > curvature = new List <List <Curve> >();

            foreach (object curve in curves)
            {
                List <Curve> geometry = new List <Curve>();

                if (curve.GetType() == typeof(DynamoRebar.RevitPolyCurve))
                {
                    DynamoRebar.RevitPolyCurve polycurve = (DynamoRebar.RevitPolyCurve)curve;
                    geometry = polycurve.Curves;
                }
                else
                {
                    geometry.Add((Curve)curve);
                }

                curvature.Add(geometry);
            }



            if (rebarElem == null)
            {
                ElementId stdC = Autodesk.Revit.DB.Structure.RebarContainerType.CreateDefaultRebarContainerType(DocumentManager.Instance.CurrentDBDocument);
                rebarElem = Autodesk.Revit.DB.Structure.RebarContainer.Create(DocumentManager.Instance.CurrentDBDocument, host, stdC);
            }
            else
            {
                //rebarElem.ClearItems();
                rebarElem.SetHostId(document, host.Id);
            }


            int counter = rebarElem.ItemsCount;

            for (int i = 0; i < counter; i++)
            {
                Autodesk.Revit.DB.Structure.RebarContainerItem item = rebarElem.GetItem(i);

                int index = GeometryMatches(item.ComputeDrivingCurves(), curvature);

                if (index == -1)
                {
                    rebarElem.RemoveItem(item);
                }
                else
                {
                    item.SetHookOrientation(0, startHookOrientation);
                    item.SetHookOrientation(1, endHookOrientation);
                    item.SetHookTypeId(0, startHook.Id);
                    item.SetHookTypeId(1, endHook.Id);
                    curvature.RemoveAt(index);
                    if (normals.Count > 1)
                    {
                        normals.RemoveAt(index);
                    }
                }
            }



            for (int i = 0; i < curvature.Count; i++)
            {
                // If there is only one normal in the list use this one for all curves
                XYZ          normal   = (normals.Count == 1) ? normals[0] : normals[i];
                List <Curve> geometry = curvature[i];

                rebarElem.AppendItemFromCurves(barStyle, barType, startHook, endHook, normal, geometry, startHookOrientation, endHookOrientation, useExistingShape, createNewShape);
            }



            // Update Quantity Parameter
            Autodesk.Revit.DB.Parameter quantityParameter = rebarElem.get_Parameter(BuiltInParameter.REBAR_ELEM_QUANTITY_OF_BARS);
            Autodesk.Revit.DB.Structure.RebarContainerParameterManager containerParameters = rebarElem.GetParametersManager();
            containerParameters.AddOverride(quantityParameter.Id, curves.Count);


            InternalSetRebarContainer(rebarElem);

            TransactionManager.Instance.TransactionTaskDone();


            if (rebarElem != null)
            {
                ElementBinder.CleanupAndSetElementForTrace(document, this.InternalElement);
            }
            else
            {
                ElementBinder.SetElementForTrace(this.InternalElement);
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Overload the constructor
 /// </summary>
 /// <param name="commandData">an instance of Data class</param>
 public ViewFiltersForm(Autodesk.Revit.UI.ExternalCommandData commandData)
 {
     InitializeComponent();
     m_doc = commandData.Application.ActiveUIDocument.Document;
 }
Ejemplo n.º 32
0
        /// <summary>
        /// This node will collect all elements of the given category from given document.
        /// </summary>
        /// <param name="document">The document to collect from.</param>
        /// <param name="category">The category to collect.</param>
        /// <returns name="element">The elements.</returns>
        /// <search>
        /// All Elements of Category in Document
        /// </search>
        public static List <global::Revit.Elements.Element> ElementsOfCategoryInDocument(Autodesk.Revit.DB.Document document, global::Revit.Elements.Category category)
        {
            //generate the category id from the input user viewable category
            Autodesk.Revit.DB.ElementId categoryId = new ElementId(category.Id);

            FilteredElementCollector coll = new FilteredElementCollector(document);
            List <global::Revit.Elements.Element> elems =
                new List <global::Revit.Elements.Element>(coll.OfCategoryId(categoryId).ToElements()
                                                          .Select(e => e.ToDSType(true)));

            return(elems);
        }
 // Step 2.
 protected override void OnAfterStart(DB.Document document, string strTransactionName)
 {
     PreviousStructureEnumerator = PreviousStructure?.GetEnumerator();
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Constructor without display unit type
 /// </summary>
 /// <param name="application">Revit application</param>
 /// <param name="labels">All existing labels in Revit's document</param>
 public CreateGridsData(UIApplication application, ArrayList labels)
 {
     m_revitDoc = application.ActiveUIDocument.Document;
     m_appCreator = application.Application.Create;
     m_docCreator = application.ActiveUIDocument.Document.Create;
     m_labelsList = labels;
 }
 // Step 5.2.A
 public override void OnCommitted(DB.Document document, string strTransactionName)
 {
     // Update previous elements
     PreviousStructure = Params.Output[0].VolatileData.AllData(false).ToArray();
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Extracts a sequence of <see cref="Mesh"/> from a sequence of <see cref="DB.GeometryObject"/>.
        /// </summary>
        /// <remarks>
        /// Empty <see cref="DB.Mesh"/> and empty <see cref="DB.Solid"/> will be skipped,
        /// so output <see cref="IEnumerable{T}"/> may be shorter than the input.
        /// Output is warranted to be free of nulls, an empty <see cref="Mesh"/> is returned in case of error.
        /// </remarks>
        /// <param name="geometries"></param>
        /// <param name="meshingParameters"></param>
        /// <returns>An <see cref="IEnumerable{Mesh}"/></returns>
        /// <seealso cref="GetPreviewMaterials(IEnumerable{DB.GeometryObject}, DB.Document, DB.Material)"/>
        internal static IEnumerable <Mesh> GetPreviewMeshes
        (
            this IEnumerable <DB.GeometryObject> geometries,
            DB.Document doc,
            MeshingParameters meshingParameters
        )
        {
            foreach (var geometry in geometries)
            {
                if (geometry.Visibility != DB.Visibility.Visible)
                {
                    continue;
                }

                switch (geometry)
                {
                case DB.GeometryInstance instance:
                {
                    var xform = instance.Transform.ToTransform();
                    foreach (var g in instance.SymbolGeometry.GetPreviewMeshes(doc, meshingParameters))
                    {
                        g.Transform(xform);
                        yield return(g);
                    }
                    break;
                }

                case DB.Mesh mesh:
                {
                    if (mesh.NumTriangles <= 0)
                    {
                        continue;
                    }

                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    var f = Geometry.Raw.RawDecoder.ToRhino(mesh);
                    UnitConverter.Scale(f, UnitConverter.ToRhinoUnits);

                    yield return(f ?? new Rhino.Geometry.Mesh());

                    break;
                }

                case DB.Face face:
                {
                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    var faceMesh = face.Triangulate(meshingParameters.LevelOfDetail());
                    var f        = Geometry.Raw.RawDecoder.ToRhino(faceMesh);
                    UnitConverter.Scale(f, UnitConverter.ToRhinoUnits);

                    yield return(f ?? new Rhino.Geometry.Mesh());

                    break;
                }

                case DB.Solid solid:
                {
                    if (solid.Faces.IsEmpty)
                    {
                        continue;
                    }

                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    var solidFaces = solid.Faces.OfType <DB.Face>();
                    foreach (var face in solidFaces)
                    {
                        var faceMesh = face.Triangulate(meshingParameters.LevelOfDetail());
                        var f        = Geometry.Raw.RawDecoder.ToRhino(faceMesh);
                        UnitConverter.Scale(f, UnitConverter.ToRhinoUnits);

                        yield return(f ?? new Rhino.Geometry.Mesh());
                    }
                    break;
                }
                }
            }
        }
 public bool SolveOptionalLevel(DB.Document doc, Rhino.Geometry.Point3d point, ref Optional <DB.Level> level, out Rhino.Geometry.BoundingBox bbox)
 {
     bbox = new Rhino.Geometry.BoundingBox(point, point);
     return(SolveOptionalLevel(doc, point.IsValid ? point.Z : double.NaN, ref level));
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Extracts a sequence of <see cref="DB.Material"/> from a sequence of <see cref="DB.GeometryObject"/>.
        /// </summary>
        /// <remarks>
        /// Empty <see cref="DB.Mesh"/> and empty <see cref="DB.Solid"/> will be skipped,
        /// so output <see cref="IEnumerable{T}"/> may be shorter than the input.
        /// Output is warranted to be free of nulls.
        /// </remarks>
        /// <param name="geometries"></param>
        /// <param name="doc"></param>
        /// <param name="currentMaterial"></param>
        /// <returns>An <see cref="IEnumerable{DB.Material}"/></returns>
        /// <seealso cref="GetPreviewMeshes(IEnumerable{DB.GeometryObject}, MeshingParameters)"/>
        internal static IEnumerable <DB.Material> GetPreviewMaterials
        (
            this IEnumerable <DB.GeometryObject> geometries,
            DB.Document doc,
            DB.Material currentMaterial
        )
        {
            foreach (var geometry in geometries)
            {
                if (geometry.Visibility != DB.Visibility.Visible)
                {
                    continue;
                }

                switch (geometry)
                {
                case DB.GeometryInstance instance:
                    foreach (var g in instance.SymbolGeometry.GetPreviewMaterials(doc, instance.SymbolGeometry.MaterialElement ?? currentMaterial))
                    {
                        yield return(g);
                    }
                    break;

                case DB.Mesh mesh:
                    if (mesh.NumTriangles <= 0)
                    {
                        continue;
                    }

                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    yield return(doc.GetElement(mesh.MaterialElementId) as DB.Material ?? currentMaterial);

                    break;

                case DB.Face face:
                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    yield return(doc.GetElement(face.MaterialElementId) as DB.Material ?? currentMaterial);

                    break;

                case DB.Solid solid:
                    if (solid.Faces.IsEmpty)
                    {
                        continue;
                    }

                    if (SkipGeometryObject(geometry, doc))
                    {
                        continue;
                    }

                    var solidFaces = solid.Faces.OfType <DB.Face>();
                    foreach (var face in solidFaces)
                    {
                        yield return(doc.GetElement(face.MaterialElementId) as DB.Material ?? currentMaterial);
                    }

                    break;
                }
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// The constructor of FramReinMaker
        /// </summary>
        /// <param name="commandData">the ExternalCommandData reference</param>
        /// <param name="hostObject">the host family instance</param>
        protected FramReinMaker(ExternalCommandData commandData, FamilyInstance hostObject)
        {
            // Get and store reinforcement create handle and host family instance
            m_revitDoc = commandData.Application.ActiveUIDocument.Document;
            m_hostObject = hostObject;

            // Get all the rebar types in revit
            if (!GetRebarTypes(commandData))
            {
                throw new Exception("Can't get any rebar type from revit.");
            }

            // Get all the rebar hook types in revit
            if (!GetHookTypes(commandData))
            {
                throw new Exception("Can't get any rebar hook type from revit.");
            }
        }
Ejemplo n.º 40
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 Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            // Get the document from external command data.
            UIDocument activeDoc = commandData.Application.ActiveUIDocument;

            Autodesk.Revit.DB.Document doc = activeDoc.Document;

            if (null == doc)
            {
                return(Result.Failed);
            }

            try
            {
                // Start detailed steel modeling transaction
                using (FabricationTransaction trans = new FabricationTransaction(doc, false, "Create shortening"))
                {
                    Reference eRef = activeDoc.Selection.PickObject(ObjectType.Element, "Pick a beam to add shortening on it");
                    Element   elem = null;

                    if (eRef != null && eRef.ElementId != ElementId.InvalidElementId)
                    {
                        elem = (doc.GetElement(eRef.ElementId));
                    }

                    if (null == elem)
                    {
                        return(Result.Failed);
                    }

                    // adding fabrication information, if the element doesn't already have it.
                    SteelElementProperties cell = SteelElementProperties.GetSteelElementProperties(elem);
                    if (null == cell)
                    {
                        List <ElementId> elemsIds = new List <ElementId>();
                        elemsIds.Add(elem.Id);
                        SteelElementProperties.AddFabricationInformationForRevitElements(doc, elemsIds);
                    }

                    // Create the modifier using AdvanceSteel API.
                    // For more details, please consult http://www.autodesk.com/adv-steel-api-walkthroughs-2019-enu
                    FilerObject filerObj = Utilities.Functions.GetFilerObject(doc, eRef);
                    if (null != filerObj)
                    {
                        if (!(filerObj is Beam))
                        {
                            return(Result.Failed);
                        }
                        Beam           beam      = filerObj as Beam;
                        Beam.eEnd      end       = Utilities.Functions.CalculateBeamEnd(beam, new XYZ(10, 20, 20));
                        BeamShortening beamShort = new BeamShortening(end, 150.0);
                        beam.AddFeature(beamShort);
                    }

                    trans.Commit();
                }
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 41
0
 /// <summary>
 /// Constructor of ElementsBatchCreation
 /// </summary>
 /// <param name="cmdData">A reference to the external application</param>
 public ElementsBatchCreation(ExternalCommandData cmdData)
 {
     m_cmdData = cmdData;
     m_doc = cmdData.Application.ActiveUIDocument.Document;
 }
Ejemplo n.º 42
0
        void ReconstructFamilyInstanceByLocation
        (
            DB.Document doc,
            ref DB.FamilyInstance element,

            [Description("Location where to place the element. Point or plane is accepted.")]
            Plane location,
            DB.FamilySymbol type,
            Optional <DB.Level> level,
            [Optional] DB.Element host
        )
        {
            if (!location.IsValid)
            {
                ThrowArgumentException(nameof(location), "Location is not valid.");
            }

            if (!type.IsActive)
            {
                type.Activate();
            }

            {
                FamilyInstanceCreationData creationData;
                switch (type.Family.FamilyPlacementType)
                {
                case DB.FamilyPlacementType.OneLevelBased:
                    creationData = CreateOneLevelBased(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.OneLevelBasedHosted:
                    creationData = CreateOneLevelBasedHosted(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.TwoLevelsBased:
                    creationData = CreateTwoLevelsBased(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.WorkPlaneBased:
                    creationData = CreateWorkPlaneBased(doc, location, type, level, host);
                    break;

                default:
                    creationData = CreateDefault(doc, location, type, level, host);
                    break;
                }

                var dataList = new List <FamilyInstanceCreationData>()
                {
                    creationData
                };
                var newElementIds = doc.IsFamilyDocument ?
                                    doc.FamilyCreate.NewFamilyInstances2(dataList) :
                                    doc.Create.NewFamilyInstances2(dataList);

                if (newElementIds.Count != 1)
                {
                    doc.Delete(newElementIds);
                    throw new InvalidOperationException();
                }

                var parametersMask = new DB.BuiltInParameter[]
                {
                    DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                    DB.BuiltInParameter.ELEM_FAMILY_PARAM,
                    DB.BuiltInParameter.ELEM_TYPE_PARAM,
                    DB.BuiltInParameter.FAMILY_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_BASE_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.FAMILY_TOP_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.SCHEDULE_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_BASE_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_BASE_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.SCHEDULE_TOP_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_TOP_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM,
                    DB.BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM
                };

                ReplaceElement(ref element, doc.GetElement(newElementIds.First()) as DB.FamilyInstance, parametersMask);
                doc.Regenerate();

                if (element.Pinned)
                {
                    try { element.Pinned = false; }
                    catch (Autodesk.Revit.Exceptions.InvalidOperationException) { }
                }
            }

            element?.SetLocation(location.Origin.ToXYZ(), location.XAxis.ToXYZ(), location.YAxis.ToXYZ());
        }
Ejemplo n.º 43
0
        /*
        public virtual bool QrGeneric(string content)
        {
            return (QRCodeUtility.IsUniCode(content) ?
                QrGeneric(content, Encoding.Unicode) :
                QrGeneric(content, Encoding.ASCII)
                );
        }

        public bool QrGeneric(string content, Encoding encoding)
        {

            double ScaleModifier = 0.0833; //0.0026; // 1/32" size boxes
            SketchPlane _sp = FindElement(_doc, typeof(SketchPlane), "Ref. Level") as SketchPlane;

            bool[][] matrix = calQrcode(encoding.GetBytes(content));

            try
            {
                for (int i = 0; i < matrix.Length; i++)
                {
                    for (int j = 0; j < matrix.Length; j++)
                    {
                        if (matrix[j][i])
                        {
                            XYZ start = new XYZ(j * (QRCodeScale * ScaleModifier), i * (QRCodeScale * ScaleModifier), 0);
                            XYZ end = new XYZ((j + 1) * (QRCodeScale * ScaleModifier), i * (QRCodeScale * ScaleModifier), 0);
                            XYZ end2 = new XYZ((j + 1) * (QRCodeScale * ScaleModifier), (i + 1) * (QRCodeScale * ScaleModifier), 0);
                            XYZ end3 = new XYZ(j * (QRCodeScale * ScaleModifier), (i + 1) * (QRCodeScale * ScaleModifier), 0);

                            Line l = _app.Create.NewLineBound(start, end);
                            Line l1 = _app.Create.NewLineBound(end, end2);
                            Line l2 = _app.Create.NewLineBound(end2, end3);
                            Line l3 = _app.Create.NewLineBound(end3, start);

                            CurveArrArray crrProf = new CurveArrArray();
                            CurveArray cArr = new CurveArray();
                            cArr.Append(l); cArr.Append(l1); cArr.Append(l2); cArr.Append(l3);

                            crrProf.Append(cArr);

                            Random random = new Random();
                            double dblRand = random.Next(1,5);

                            FamilyItemFactory factory = _doc.FamilyCreate;
                            factory.NewExtrusion(true, crrProf, _sp, dblRand);

                            crrProf.Clear();
                            cArr.Clear();

                        }

                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        */
        Element FindElement(Document doc, Type targetType, string targetName)
        {
            return new FilteredElementCollector(doc)
            .OfClass(targetType)
            .First<Element>(e => e.Name.Equals(targetName));
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="doc">Revit document</param>
 private AnalysisVisualizationFramework(Autodesk.Revit.DB.Document doc)
 {
     m_doc = doc;
 }
Ejemplo n.º 45
0
Archivo: COVER.cs Proyecto: nixz/covise
        public bool ConnectToOpenCOVER(string host, int port, Autodesk.Revit.DB.Document doc)
        {
            document = doc;
             handler = new externalMessageHandler();
             messageEvent = Autodesk.Revit.UI.ExternalEvent.Create(handler);
             messageQueue = new Queue<COVERMessage>();

             System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("Revit");
             callCounter = 0;

             if (0 < processes.Length)
             {
             ApplicationWindow = processes[0].MainWindowHandle;
             }
             try
             {
             if (toCOVER != null)
             {
                 messageThread.Abort(); // stop reading from the old toCOVER connection
                 toCOVER.Close();
                 toCOVER = null;
             }

             toCOVER = new TcpClient(host, port);
             if (toCOVER.Connected)
             {
                 // Sends data immediately upon calling NetworkStream.Write.
                 toCOVER.NoDelay = true;
                 LingerOption lingerOption = new LingerOption(false, 0);
                 toCOVER.LingerState = lingerOption;

                 NetworkStream s = toCOVER.GetStream();
                 Byte[] data = new Byte[256];
                 data[0] = 1;
                 try
                 {
                     //toCOVER.ReceiveTimeout = 1000;
                     s.Write(data, 0, 1);
                     //toCOVER.ReceiveTimeout = 10000;
                 }
                 catch (System.IO.IOException e)
                 {
                     // probably socket closed
                     return false;
                 }

                 int numRead = 0;
                 try
                 {
                     //toCOVER.ReceiveTimeout = 1000;
                     numRead = s.Read(data, 0, 1);
                     //toCOVER.ReceiveTimeout = 10000;
                 }
                 catch (System.IO.IOException e)
                 {
                     // probably socket closed
                     return false;
                 }
                 if (numRead == 1)
                 {

                     messageThread = new Thread(new ThreadStart(this.handleMessages));

                     // Start the thread
                     messageThread.Start();
                 }

                 return true;
             }
             System.Windows.Forms.MessageBox.Show("Could not connect to OpenCOVER on localhost, port 31821");
             }
             catch
             {
             System.Windows.Forms.MessageBox.Show("Connection error while trying to connect to OpenCOVER on localhost, port 31821");
             }
             return false;
        }
Ejemplo n.º 46
0
 internal void Document(Autodesk.Revit.DB.Document doc)
 {
     this.doc = doc;
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Constructor, Initialize the fields.
 /// </summary>
 /// <param name="rvtApp">Revit Application object</param>
 /// <param name="shapeDef">RebarShapeDef object</param>
 public NewRebarShapeForm(Autodesk.Revit.DB.Document rvtDoc, RebarShapeDef shapeDef)
     : this()
 {
     m_rebarShapeDef = shapeDef;
     m_rvtDoc = rvtDoc;
     m_rvtApp = rvtDoc.Application;
 }
Ejemplo n.º 48
0
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            PlunkOClass plunkThis        = new PlunkOClass(commandData.Application);
            string      wsName           = "ELEC LIGHTING DIAGNOSTIC";
            string      FamilyName       = "OCC-SENSOR-DETECTION-CMR09";
            string      FamilySymbolName = "DET BLADES ALL";
            string      pNameOccHeight   = "HEIGHT_ABOVE_FLOOR";

            bool            oneShot   = true;
            BuiltInCategory bicFamily = BuiltInCategory.OST_LightingDevices;

            if (plunkThis.NotInThisView())
            {
                return(Result.Succeeded);
            }

            CheckThisFamilyPairing(doc, typeof(FamilySymbol), FamilyName, FamilySymbolName, bicFamily);

            Element elemPlunked = null;
            double  optOffset   = plunkThis.GetCeilingHeight("OCC Sensor Tool Plunk");
            Double  pOffSetX    = 0.0;
            Double  pOffSetY    = 0.0;
            Double  pOffSetZ    = 0.0 + optOffset;
            Units   unit        = commandData.Application.ActiveUIDocument.Document.GetUnits();
            string  optMSG      = " : will be at " + UnitFormatUtils.Format(unit, UnitType.UT_Length, optOffset, false, false);

            if (optOffset != 0.0)
            {
                plunkThis.PlunkThisFamilyType(FamilyName, FamilySymbolName, wsName, bicFamily, out elemPlunked, oneShot, pOffSetX, pOffSetY, pOffSetZ, optMSG);
            }

            /// At this point there may or may not have been an element placed.
            #region SetParametersSection
            if (elemPlunked != null)
            {
                using (Transaction tp = new Transaction(doc, "PlunkOMatic:SetParam")) {
                    tp.Start();
                    //TaskDialog.Show(_pName, _pName);
                    Parameter parToSet = null;
                    parToSet = elemPlunked.LookupParameter(pNameOccHeight);
                    string strVal = UnitFormatUtils.Format(unit, UnitType.UT_Length, optOffset, false, false);
                    if (null != parToSet)
                    {
                        parToSet.SetValueString(strVal); // this parameter is distance, therefore valuestring
                    }
                    else
                    {
                        FamilyUtils.SayMsg("Cannot Set Parameter Value: " + strVal, "... because parameter:\n" + pNameOccHeight
                                           + "\ndoes not exist in the family:\n" + FamilyName
                                           + "\nof Category:\n" + bicFamily.ToString().Replace("OST_", ""));
                    }
                    tp.Commit();
                }
            }
            #endregion
            return(Result.Succeeded);
        }
Ejemplo n.º 49
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Application app = uiapp.Application;
            Document doc = uidoc.Document;
            _doc = doc;

            //Prompt for Input contents

            Document fdocX = app.NewFamilyDocument("C:\\ProgramData\\Autodesk\\RVT 2013\\Family Templates\\English_I\\Annotations\\Generic Annotation.rft");
            //Document fdocX = app.NewFamilyDocument("C:\\ProgramData\\Autodesk\\RVT 2013\\Family Templates\\English_I\\Generic Model.rft");

            //New Qrencoder using the family document
            QREncoder qrcode = new QREncoder(fdocX, uidoc, app);

            string contents = Microsoft.VisualBasic.Interaction.InputBox("Enter and text to QR encode.", "QR Encode Prompt", "", -1, -1);

            if (contents != "")
            {

                if (null == fdocX)
                {
                    return Result.Failed;
                }

                // Modify document within a transaction
                using (Transaction tx = new Transaction(fdocX))
                {
                    tx.Start("Generate QR Code");

                    //GenerateQR(fdoc, qrcode, contents);
                    GenerateQR(fdocX, qrcode, contents);

                    tx.Commit();
                }

                //save background family doc
                string dir = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));

                //Clean invalid filename characters
                string fileNameClean = CleanChars(contents);
                _familyName += fileNameClean;

                string filename = Path.Combine(dir, _familyName + ".rfa");
                SaveAsOptions opt = new SaveAsOptions();
                opt.OverwriteExistingFile = true;
                fdocX.SaveAs(filename, opt);
                fdocX.Close(false);

                //Insert new family into document
                using (Transaction tx2 = new Transaction(doc))
                {
                    tx2.Start("Insert QRCode");

                    Family fam = null;

                    FilteredElementCollector fec = new FilteredElementCollector(doc)
                    .OfClass(typeof(Family));

                    foreach (Family f in fec)
                    {
                        if (f.Name.Equals(_familyName))
                        {
                            fam = f;
                        }
                        else
                        {
                            doc.LoadFamily(filename, out fam);
                        }
                    }

                    FamilySymbol fs = null;

                    foreach (FamilySymbol symbol in fam.Symbols)
                    {
                        fs = symbol;
                        break;
                    }

                    XYZ p = uidoc.Selection.PickPoint("Please pick point to place QR code");

                    AnnotationSymbolTypeSet annoset = _doc.AnnotationSymbolTypes;
                    AnnotationSymbolType annoSymbolType = null;

                    foreach (AnnotationSymbolType type in annoset)
                    {
                        if (type.Name.Equals(_familyName))
                        {
                            annoSymbolType = type;
                        }
                    }

                    //Deprecated in 2013, but too lazy to implement new
                    doc.Create.NewAnnotationSymbol(p, annoSymbolType, uidoc.ActiveView);

                    //doc.Create.NewFamilyInstance(p, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                    tx2.Commit();
                }

                return Result.Succeeded;
            }
            else
            {
                return Result.Cancelled;
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Gets the rectangular openings.
        /// </summary>
        /// <returns></returns>
        /// <remarks>This method uses walls, doors, windows and generic models bounding boxes to determine the rectangles.
        /// These objects can be in the host file or in linked Revit files.</remarks>
        public static IList <Autodesk.DesignScript.Geometry.Rectangle> GetRectangularOpenings()
        {
            Utils.Log(string.Format("OpeningUtils.GetRectangularOpenings started...", ""));

            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            //look for Walls, Doors, Windows, Generic Models in the current document and in the linked documents
            ElementCategoryFilter wallFilter    = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
            ElementCategoryFilter doorFilter    = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
            ElementCategoryFilter windowFilter  = new ElementCategoryFilter(BuiltInCategory.OST_Windows);
            ElementCategoryFilter genericFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel);

            IList <ElementFilter> filterList = new List <ElementFilter>()
            {
                wallFilter, doorFilter, windowFilter, genericFilter
            };

            LogicalOrFilter orFilter = new LogicalOrFilter(filterList);

            IList <Autodesk.DesignScript.Geometry.Solid> solids = new List <Autodesk.DesignScript.Geometry.Solid>();

            IList <Autodesk.DesignScript.Geometry.Rectangle> output = new List <Autodesk.DesignScript.Geometry.Rectangle>();

            foreach (Autodesk.Revit.DB.Element e in new FilteredElementCollector(doc)
                     .WherePasses(orFilter)
                     .WhereElementIsNotElementType()
                     .Where(x =>
                            x.Parameters.Cast <Autodesk.Revit.DB.Parameter>()
                            .First(p => p.Id.IntegerValue == (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).HasValue))
            {
                string comments = e.Parameters.Cast <Autodesk.Revit.DB.Parameter>().First(p => p.Id.IntegerValue == (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString();

                if (comments.ToLower() != "opening")
                {
                    continue;
                }

                Transform tr = Transform.Identity;

                if (e is Instance)
                {
                    Instance instance = e as Instance;
                    tr = instance.GetTotalTransform();
                }

                IList <Autodesk.Revit.DB.Solid> temp = new List <Autodesk.Revit.DB.Solid>();

                foreach (GeometryObject go in e.get_Geometry(new Options()))
                {
                    if (go is GeometryInstance)
                    {
                        GeometryInstance geoInstance = go as GeometryInstance;

                        foreach (var gi in geoInstance.SymbolGeometry)
                        {
                            if (gi is Autodesk.Revit.DB.Solid)
                            {
                                Autodesk.Revit.DB.Solid s = gi as Autodesk.Revit.DB.Solid;
                                s = SolidUtils.CreateTransformed(s, tr);
                                temp.Add(s);
                            }
                        }
                    }
                    else
                    {
                        if (go is Autodesk.Revit.DB.Solid)
                        {
                            Autodesk.Revit.DB.Solid s = go as Autodesk.Revit.DB.Solid;
                            s = SolidUtils.CreateTransformed(s, tr);
                            temp.Add(s);
                        }
                    }
                }

                if (temp.Count > 0)
                {
                    Autodesk.Revit.DB.Solid s0 = temp[0];
                    for (int i = 1; i < temp.Count; ++i)
                    {
                        s0 = BooleanOperationsUtils.ExecuteBooleanOperation(s0, temp[i], BooleanOperationsType.Union);
                    }

                    solids.Add(s0.ToProtoType());
                }
            }

            foreach (RevitLinkInstance rli in new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance)).WhereElementIsNotElementType())
            {
                Autodesk.Revit.DB.Document link = rli.GetLinkDocument();

                foreach (Autodesk.Revit.DB.Element e in new FilteredElementCollector(link)
                         .WherePasses(orFilter)
                         .WhereElementIsNotElementType()
                         .Where(x =>
                                x.Parameters.Cast <Autodesk.Revit.DB.Parameter>()
                                .First(p => p.Id.IntegerValue == (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).HasValue))
                {
                    Transform tr = rli.GetTotalTransform();

                    string comments = e.Parameters.Cast <Autodesk.Revit.DB.Parameter>().First(p => p.Id.IntegerValue == (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString();

                    if (comments.ToLower() != "opening")
                    {
                        continue;
                    }

                    if (e is Instance)
                    {
                        Instance instance = e as Instance;
                        tr = tr.Multiply(instance.GetTotalTransform());
                    }

                    IList <Autodesk.Revit.DB.Solid> temp = new List <Autodesk.Revit.DB.Solid>();

                    foreach (var go in e.get_Geometry(new Options()))
                    {
                        if (go is GeometryInstance)
                        {
                            GeometryInstance geoInstance = go as GeometryInstance;

                            foreach (var gi in geoInstance.SymbolGeometry)
                            {
                                if (gi is Autodesk.Revit.DB.Solid)
                                {
                                    Autodesk.Revit.DB.Solid s = gi as Autodesk.Revit.DB.Solid;
                                    s = SolidUtils.CreateTransformed(s, tr);
                                    temp.Add(s);
                                }
                            }
                        }
                        else
                        {
                            if (go is Autodesk.Revit.DB.Solid)
                            {
                                Autodesk.Revit.DB.Solid s = go as Autodesk.Revit.DB.Solid;
                                s = SolidUtils.CreateTransformed(s, tr);
                                temp.Add(s);
                            }
                        }
                    }

                    if (temp.Count > 0)
                    {
                        Autodesk.Revit.DB.Solid s0 = temp[0];
                        for (int i = 1; i < temp.Count; ++i)
                        {
                            s0 = BooleanOperationsUtils.ExecuteBooleanOperation(s0, temp[i], BooleanOperationsType.Union);
                        }

                        solids.Add(s0.ToProtoType());
                    }
                }
            }

            foreach (var s in solids)
            {
                IList <Autodesk.DesignScript.Geometry.Point> points = new List <Autodesk.DesignScript.Geometry.Point>();

                foreach (var v in s.Vertices)
                {
                    points.Add(v.PointGeometry);
                }

                points = Autodesk.DesignScript.Geometry.Point.PruneDuplicates(points);

                Autodesk.DesignScript.Geometry.Plane plane = Autodesk.DesignScript.Geometry.Plane.ByBestFitThroughPoints(points);

                plane = Autodesk.DesignScript.Geometry.Plane.ByOriginNormal(points.Last(), plane.Normal);

                IList <Autodesk.DesignScript.Geometry.Point> temp = new List <Autodesk.DesignScript.Geometry.Point>();

                foreach (var p in points)
                {
                    foreach (var q in p.Project(plane, plane.Normal))
                    {
                        temp.Add(q as Autodesk.DesignScript.Geometry.Point);
                    }

                    foreach (var q in p.Project(plane, plane.Normal.Reverse()))
                    {
                        temp.Add(q as Autodesk.DesignScript.Geometry.Point);
                    }
                }

                temp = Autodesk.DesignScript.Geometry.Point.PruneDuplicates(temp);

                CoordinateSystem cs = CoordinateSystem.ByPlane(plane);

                IList <Autodesk.DesignScript.Geometry.Point> relative = new List <Autodesk.DesignScript.Geometry.Point>();

                foreach (var p in temp)
                {
                    relative.Add(p.Transform(cs.Inverse()) as Autodesk.DesignScript.Geometry.Point);
                }

                var min = Autodesk.DesignScript.Geometry.Point.ByCoordinates(relative.Min(p => p.X),
                                                                             relative.Min(p => p.Y),
                                                                             relative.Min(p => p.Z));
                //.Transform(cs) as Autodesk.DesignScript.Geometry.Point;

                var max = Autodesk.DesignScript.Geometry.Point.ByCoordinates(relative.Max(p => p.X),
                                                                             relative.Max(p => p.Y),
                                                                             relative.Max(p => p.Z));
                //.Transform(cs) as Autodesk.DesignScript.Geometry.Point;

                double width  = max.X - min.X;
                double height = max.Y - min.Y;

                min = min.Transform(cs) as Autodesk.DesignScript.Geometry.Point;
                max = max.Transform(cs) as Autodesk.DesignScript.Geometry.Point;

                plane = Autodesk.DesignScript.Geometry.Plane.ByOriginNormal(Autodesk.DesignScript.Geometry.Line.ByStartPointEndPoint(min, max).PointAtParameter(0.5), plane.Normal);

                Autodesk.DesignScript.Geometry.Rectangle rectangle = Autodesk.DesignScript.Geometry.Rectangle.ByWidthLength(plane,
                                                                                                                            width,
                                                                                                                            height);

                output.Add(rectangle);

                plane.Dispose();
                cs.Dispose();
                min.Dispose();
                max.Dispose();
            }

            Utils.Log(string.Format("OpeningUtils.GetRectangularOpenings completed.", ""));

            return(output);
        }
Ejemplo n.º 51
0
        public bool ConnectToOpenCOVER(string host, int port, Autodesk.Revit.DB.Document doc)
        {
            document = doc;
             handler = new externalMessageHandler();
             messageEvent = Autodesk.Revit.UI.ExternalEvent.Create(handler);
             messageQueue = new Queue<COVERMessage>();

             System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("Revit");

             if (0 < processes.Length)
             {
             ApplicationWindow = processes[0].MainWindowHandle;
             }
             try
             {
             if (toCOVER != null)
             {
                 messageThread.Abort(); // stop reading from the old toCOVER connection
                 toCOVER.Close();
                 toCOVER = null;
                 setConnected(false);
             }

             toCOVER = new TcpClient(host, port);
             if (toCOVER.Connected)
             {
                 // Sends data immediately upon calling NetworkStream.Write.
                 toCOVER.NoDelay = true;
                 LingerOption lingerOption = new LingerOption(false, 0);
                 toCOVER.LingerState = lingerOption;

                 NetworkStream s = toCOVER.GetStream();
                 Byte[] data = new Byte[256];
                 data[0] = 1;
                 try
                 {
                     //toCOVER.ReceiveTimeout = 1000;
                     s.Write(data, 0, 1);
                     //toCOVER.ReceiveTimeout = 10000;
                 }
                 catch (System.IO.IOException)
                 {
                     // probably socket closed
                     setConnected(false);
                     return false;
                 }

                 int numRead = 0;
                 try
                 {
                     //toCOVER.ReceiveTimeout = 1000;
                     numRead = s.Read(data, 0, 1);
                     //toCOVER.ReceiveTimeout = 10000;
                 }
                 catch (System.IO.IOException)
                 {
                     // probably socket closed
                     setConnected(false);
                     return false;
                 }

                 List<View3D> views = new List<View3D>(
             new FilteredElementCollector(doc)
               .OfClass(typeof(View3D))
               .Cast<View3D>()
               .Where<View3D>(v =>
             v.CanBePrinted && !v.IsTemplate));
                 int n = views.Count;

                 if (0 == n)
                 {
                     setConnected(false);
                     return false;
                 }
                 MessageBuffer mb = new MessageBuffer();
                 mb.add(n);
                 foreach (View3D v in views)
                 {
                     mb.add(v.Name);
                 }
                 sendMessage(mb.buf, MessageTypes.Views);

                 if (numRead == 1)
                 {
                     setConnected(true);
                     messageThread = new Thread(new ThreadStart(this.handleMessages));

                     // Start the thread
                     messageThread.Start();

                 }

                 return true;
             }
             System.Windows.Forms.MessageBox.Show("Could not connect to OpenCOVER on localhost, port 31821");
             }
             catch
             {

             setConnected(false);
             System.Windows.Forms.MessageBox.Show("Connection error while trying to connect to OpenCOVER on localhost, port 31821");
             }
             return false;
        }
Ejemplo n.º 52
0
 protected Element(DB.Document doc, DB.ElementId id) : base(doc, id)
 {
 }
Ejemplo n.º 53
0
        public static Result SetTextCase(Document doc, Selection selection, string textCase)
        {
            try
            {
                List<Element> textElements;

                if (selection.Elements.IsEmpty)
                {
                    TaskDialog selectAllDialog = new TaskDialog("Select all?");
                    selectAllDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
                    selectAllDialog.MainInstruction = "No elements have been selected. Do you want to select all text elements in the project?";
                    selectAllDialog.MainContent = string.Format("Press YES if you want to change all text elements in the project to {0} case or press NO if you want to cancel.", textCase);

                    if (selectAllDialog.Show() == TaskDialogResult.Yes)
                    {
                        FilteredElementCollector textSelector = new FilteredElementCollector(doc);
                        textElements = textSelector.OfClass(typeof(TextElement)).ToElements().ToList<Element>();
                        if (textElements == null || textElements.ToList<Element>().Count == 0)
                            return Result.Cancelled;
                    }
                    else
                    {
                        return Result.Cancelled;
                    }
                }
                else
                {
                    textElements = new List<Element>();
                    foreach (Element element in selection.Elements)
                        textElements.Add(element);
                }

                Transaction transaction = new Transaction(doc);
                transaction.Start(string.Format("Setting text to {0} case", textCase));

                foreach (Element element in textElements)
                {
                    TextElement item = element as TextElement;

                    if (item == null)
                        continue;
                    else
                    {
                        switch (textCase)
                        {
                            case ("upper"):
                                item.Text = item.Text.ToUpper();
                                break;
                            case ("lower"):
                                item.Text = item.Text.ToLower();
                                break;
                            case ("title"):
                                item.Text = ToTitleCase(item.Text);
                                break;
                            default:
                                item.Text = ToSentenceCase(item.Text);
                                break;
                        }
                    }
                }
                transaction.Commit();

                return Result.Succeeded;
            }
            catch
            {
                return Result.Failed;
            }
        }
Ejemplo n.º 54
0
        protected override void TrySolveInstance(IGH_DataAccess DA, DB.Document doc)
        {
            var  viewDiscipline     = default(DB.ViewDiscipline);
            var  _Discipline_       = Params.IndexOfInputParam("Discipline");
            bool nofilterDiscipline = (!DA.GetData(_Discipline_, ref viewDiscipline) && Params.Input[_Discipline_].Sources.Count == 0);

            var viewType = DB.ViewType.Undefined;

            DA.GetData("Type", ref viewType);

            string name = null;

            DA.GetData("Name", ref name);

            var  Template         = default(DB.View);
            var  _Template_       = Params.IndexOfInputParam("Template");
            bool nofilterTemplate = (!DA.GetData(_Template_, ref Template) && Params.Input[_Template_].DataType == GH_ParamData.@void);

            bool IsTemplate         = false;
            var  _IsTemplate_       = Params.IndexOfInputParam("IsTemplate");
            bool nofilterIsTemplate = (!DA.GetData(_IsTemplate_, ref IsTemplate) && Params.Input[_IsTemplate_].DataType == GH_ParamData.@void);

            bool IsAssembly         = false;
            var  _IsAssembly_       = Params.IndexOfInputParam("IsAssembly");
            bool nofilterIsAssembly = (!DA.GetData(_IsAssembly_, ref IsAssembly) && Params.Input[_IsAssembly_].DataType == GH_ParamData.@void);

            bool IsPrintable         = false;
            var  _IsPrintable_       = Params.IndexOfInputParam("IsPrintable");
            bool nofilterIsPrintable = (!DA.GetData(_IsPrintable_, ref IsPrintable) && Params.Input[_IsPrintable_].DataType == GH_ParamData.@void);

            DB.ElementFilter filter = null;
            DA.GetData("Filter", ref filter);

            using (var collector = new DB.FilteredElementCollector(doc))
            {
                var viewsCollector = collector.WherePasses(ElementFilter);

                if (filter is object)
                {
                    viewsCollector = viewsCollector.WherePasses(filter);
                }

                var views = collector.Cast <DB.View>();

                if (!nofilterDiscipline)
                {
                    views = views.Where((x) =>
                    {
                        try { return(x.Discipline == viewDiscipline); }
                        catch (Autodesk.Revit.Exceptions.InvalidOperationException) { return(false); }
                    });
                }

                if (!nofilterTemplate)
                {
                    views = views.Where((x) => x.ViewTemplateId.IntegerValue == Template.Id.IntegerValue);
                }

                if (!nofilterIsTemplate)
                {
                    views = views.Where((x) => x.IsTemplate == IsTemplate);
                }

                if (!nofilterIsAssembly)
                {
                    views = views.Where((x) => x.IsAssemblyView == IsAssembly);
                }

                if (!nofilterIsPrintable)
                {
                    views = views.Where((x) => x.CanBePrinted == IsPrintable);
                }

                if (viewType != DB.ViewType.Undefined)
                {
                    views = views.Where((x) => x.ViewType == viewType);
                }

                if (!string.IsNullOrEmpty(name))
                {
                    views = views.Where(x => x.Name.IsSymbolNameLike(name));
                }

                DA.SetDataList("Views", views);
            }
        }
Ejemplo n.º 55
0
        void ReconstructView3DByPlane
        (
            DB.Document doc,
            ref DB.View3D view,

            Rhino.Geometry.Plane plane,
            Optional <DB.ElementType> type,
            Optional <string> name,
            Optional <bool> perspective
        )
        {
            SolveOptionalType(ref type, doc, DB.ElementTypeGroup.ViewType3D, nameof(type));

            var orientation = new DB.ViewOrientation3D
                              (
                plane.Origin.ToXYZ(),
                plane.YAxis.ToXYZ(),
                -plane.ZAxis.ToXYZ()
                              );

            if (view is null)
            {
                var newView = perspective.IsNullOrMissing ?
                              DB.View3D.CreatePerspective
                              (
                    doc,
                    type.Value.Id
                              ) :
                              DB.View3D.CreateIsometric
                              (
                    doc,
                    type.Value.Id
                              );

                var parametersMask = new DB.BuiltInParameter[]
                {
                    DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                    DB.BuiltInParameter.ELEM_FAMILY_PARAM,
                    DB.BuiltInParameter.ELEM_TYPE_PARAM
                };

                newView.SetOrientation(orientation);
                newView.get_Parameter(DB.BuiltInParameter.VIEWER_CROP_REGION).Set(0);
                ReplaceElement(ref view, newView, parametersMask);
            }
            else
            {
                view.SetOrientation(orientation);

                if (perspective.HasValue)
                {
                    view.get_Parameter(DB.BuiltInParameter.VIEWER_PERSPECTIVE).Set(perspective.Value ? 1 : 0);
                }

                ChangeElementTypeId(ref view, type.Value.Id);
            }

            if (name.HasValue && view is object)
            {
                try { view.Name = name.Value; }
                catch (Autodesk.Revit.Exceptions.ArgumentException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"{e.Message.Replace($".{Environment.NewLine}", ". ")}");
                }
            }
        }
Ejemplo n.º 56
0
 public Form_Command(UIApplication application)
 {
     m_app = application;
     m_doc = application.ActiveUIDocument.Document;
     InitializeComponent();
 }
Ejemplo n.º 57
0
        void GenerateQR(Document doc, QREncoder qrencoder, string contents)
        {
            FilteredElementCollector fec = new FilteredElementCollector(doc)
            .OfClass(typeof(TextNote));

            foreach (Element e in fec)
            {
                doc.Delete(e);
            }

            qrencoder.Qrfilled(contents);

            //qrencoder.QrGeneric(contents);
        }
Ejemplo n.º 58
0
        public static List <global::Revit.Elements.Element> CopyDraftingViewsFromDocument(Autodesk.Revit.DB.Document sourceDocument, List <global::Revit.Elements.Element> draftingViews)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            //converts elements to ids in a collection
            ICollection <ElementId> idCollection = new List <ElementId>();

            foreach (global::Revit.Elements.Element view in draftingViews)
            {
                idCollection.Add(view.InternalElement.Id);
            }

            TransactionManager.Instance.ForceCloseTransaction();
            List <View> newDraftingViews =
                ViewUtils.DuplicateDraftingViews(sourceDocument, idCollection, doc);
            List <global::Revit.Elements.Element> vList = new List <global::Revit.Elements.Element>(newDraftingViews.Select(v => v.ToDSType(true)));

            return(vList);
        }
Ejemplo n.º 59
0
        public static List <global::Revit.Elements.Element> CopyElementsFromLinkedDocument(Autodesk.Revit.DB.Document sourceDocument,
                                                                                           global::Revit.Elements.Element sourceInstance, List <global::Revit.Elements.Element> elements)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //converts elements to ids in a collection
            ICollection <ElementId> idCollection = new List <ElementId>();

            foreach (global::Revit.Elements.Element element in elements)
            {
                idCollection.Add(element.InternalElement.Id);
            }
            Autodesk.Revit.DB.RevitLinkInstance internalInstance = (Autodesk.Revit.DB.RevitLinkInstance)sourceInstance.InternalElement;

            //creates blank copy paste options
            CopyPasteOptions copyOpts = new CopyPasteOptions();
            //creates blank transform.
            Transform transform = Transform.CreateTranslation(Vector.XAxis().ToRevitType());

            //commits the transaction
            TransactionManager.Instance.EnsureInTransaction(doc);
            ICollection <ElementId> newElementIds = ElementTransformUtils.CopyElements(sourceDocument, idCollection, doc, internalInstance.GetTransform(), copyOpts);

            TransactionManager.Instance.TransactionTaskDone();
            //create a new list for the new elements
            List <global::Revit.Elements.Element> newElements = new List <global::Revit.Elements.Element>();

            //gets the new elements
            foreach (ElementId id in newElementIds)
            {
                newElements.Add(doc.GetElement(id).ToDSType(true));
            }

            return(newElements);
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="revit">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(Autodesk.Revit.UI.ExternalCommandData revit,
                                                              ref string message,
                                                              ElementSet elements)
        {
            try
            {
                m_application = revit.Application.Application;
                m_document = revit.Application.ActiveUIDocument.Document;

                // it can support in truss family document only
                if (!m_document.IsFamilyDocument
                    || m_document.OwnerFamily.FamilyCategory.Id.IntegerValue != (int)BuiltInCategory.OST_Truss)
                {
                    message = "Cannot execute truss creation in non-truss family document";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                m_appCreator = m_application.Create;
                m_familyCreator = m_document.FamilyCreate;

                Transaction newTran = new Transaction(m_document);
                newTran.Start("NewTrussCurve");

                // Start the truss creation
                MakeNewTruss();

                newTran.Commit();
            }
            catch (Exception ex)
            {
                message = ex.ToString();
                return Autodesk.Revit.UI.Result.Failed;
            }
            return Autodesk.Revit.UI.Result.Succeeded;
        }