/// <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) { m_app = commandData.Application.Application; MessageManager.MessageBuff = new StringBuilder(); try { bool succeeded = LoadFamiliesAndAddParameters(); if (succeeded) { return Autodesk.Revit.UI.Result.Succeeded; } else { message = MessageManager.MessageBuff.ToString(); return Autodesk.Revit.UI.Result.Failed; } } catch (Exception e) { message = e.Message; return Autodesk.Revit.UI.Result.Failed; } }
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; }
/// <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; }
/// <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; }
/// <summary> /// constructor /// </summary> /// <param name="app"> /// the active revit application /// </param> /// <param name="doc"> /// the family document which will have parameters added in /// </param> public FamilyParameterAssigner(Autodesk.Revit.ApplicationServices.Application app, Document doc) { m_app = app; m_manager = doc.FamilyManager; m_familyParams = new Dictionary<string, FamilyParam>(); m_assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); m_paramLoaded = false; }
public Geometry(Autodesk.Revit.DB.Element elem, Autodesk.Revit.ApplicationServices.Application app) { this.Text = "Element Geometry"; m_elem = elem; m_app = app; m_tvObjs.BeginUpdate(); AddObjectsToTree(elem, m_tvObjs.Nodes); m_tvObjs.EndUpdate(); }
/// <summary> /// Constructor. /// </summary> /// <param name="revit"> /// The application object for the active instance of Autodesk Revit. /// </param> public DataGenerator(RevitApplication revitApp, Document doc, RevitView view) { //initialize the member variable if (revitApp != null) { m_RevitApp = revitApp; m_ActiveDocument = doc; m_ActiveView = view; m_ViewOptions = m_RevitApp.Create.NewGeometryOptions(); m_ViewOptions.View = m_ActiveView; } }
Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit application #endregion Fields #region Constructors // Methods /// <summary> /// Default constructor of LoadCaseDeal /// </summary> public LoadCaseDeal(Loads dataBuffer) { m_dataBuffer = dataBuffer; m_revit = dataBuffer.RevitApplication; m_newLoadNaturesName = new List<string>(); m_newLoadNaturesName.Add("EQ1"); m_newLoadNaturesName.Add("EQ2"); m_newLoadNaturesName.Add("W1"); m_newLoadNaturesName.Add("W2"); m_newLoadNaturesName.Add("W3"); m_newLoadNaturesName.Add("W4"); m_newLoadNaturesName.Add("Other"); }
public ElementGeometry(string label, Element val, Autodesk.Revit.ApplicationServices.Application app) : base(label) { m_val = val; m_app = app; m_hasGeometry = false; if (m_val != null && m_app != null) { Autodesk.Revit.DB.Options geomOp = m_app.Create.NewGeometryOptions(); geomOp.DetailLevel = ViewDetailLevel.Undefined; if (m_val.get_Geometry(geomOp) != null) m_hasGeometry = true; } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { uiApp = commandData.Application; uiDoc = uiApp.ActiveUIDocument; app = uiApp.Application; doc = uiDoc.Document; FilteredElementCollector refPlaneCollector = new FilteredElementCollector(doc); IList<Element> refPlanes = refPlaneCollector.OfClass(typeof(ReferencePlane)).ToElements(); ElementId nameParamterId = new ElementId(BuiltInParameter.DATUM_TEXT); ParameterValueProvider pvp = new ParameterValueProvider(nameParamterId); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); FilterRule rule = new FilterStringRule(pvp, evaluator, "", false); ElementFilter filter = new ElementParameterFilter(rule); FilteredElementCollector unnamedRefPlaneCollector = new FilteredElementCollector(doc); unnamedRefPlaneCollector.OfClass(typeof(ReferencePlane)); unnamedRefPlaneCollector.WherePasses(filter); IList<Element> unnamedRefPlanes = unnamedRefPlaneCollector.ToElements(); Transaction transaction = new Transaction(doc); transaction.Start("Purging unnamed reference planes"); foreach (Element refPlane in unnamedRefPlanes) doc.Delete(refPlane.Id); transaction.Commit(); TaskDialog.Show("Purge Unnamed Ref Planes", String.Format("{0} reference planes found.\n{1} unnamed reference planes deleted.", refPlanes.Count.ToString(), unnamedRefPlanes.Count.ToString())); return Result.Succeeded; } catch (Exception e) { TaskDialog.Show("Revit Quick Tools", e.Message); return Result.Failed; } }
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; // code ExportScheduleToExcelViewModel viewModel = new ExportScheduleToExcelViewModel(uidoc); ExportScheduleToExcelWindow window = new ExportScheduleToExcelWindow(viewModel); if (window.ShowDialog() == false) { return(Result.Cancelled); } return(Result.Succeeded); }
public virtual Result Execute( ExternalCommandData commandData, ref string msg, ElementSet elements) { UIApplication rvtuiapp = commandData.Application; UIDocument rvtuidoc = rvtuiapp.ActiveUIDocument; _app = rvtuiapp.Application; _doc = rvtuidoc.Document; try { Document doc = commandData.Application.ActiveUIDocument.Document; CurveArray selectedCurves = GetSelectedCurves(_doc); // Get all selected lines and arcs GridCreationOptionData gridCreationOption = new GridCreationOptionData(!selectedCurves.IsEmpty); using (GridCreationOptionForm gridCreationOptionForm = new GridCreationOptionForm(gridCreationOption)) { } } }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { UIApplication uiapp = revit.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; UIApplication uiApp = new UIApplication(revit.Application.Application); MatchFireDoorWallForm form = new MatchFireDoorWallForm(uidoc); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.MaximizeBox = false; form.MinimizeBox = false; form.StartPosition = FormStartPosition.CenterScreen; form.ShowDialog(); form.Dispose(); return(Result.Succeeded); }
public void Execute(UIApplication uiapp) { UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; if (isRunFirstTime) { AutomaticArrangementUserControl.Instance.TextBlockProjectTitle.Text = doc.Title; isRunFirstTime = false; } try { //TODO: Write Revit API code here } catch (Exception exception) { System.Windows.MessageBox.Show("Some error has occured. \n" + exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } //WpfWindowController.Instance.Window.Close(); //uncomment it to close the app }
bool LocationRotate(Autodesk.Revit.ApplicationServices.Application app, Autodesk.Revit.DB.Element element) { bool rotated = false; if (element.Location is LocationCurve curve) { Curve line = curve.Curve; XYZ aa = line.GetEndPoint(0); XYZ cc = new XYZ(aa.X, aa.Y, aa.Z + 10); Line axis = Line.CreateBound(aa, cc); rotated = curve.Rotate(axis, Math.PI / 4); } if (element.Location is LocationPoint location) { XYZ aa = location.Point; XYZ cc = new XYZ(aa.X, aa.Y, aa.Z + 10); Line axis = Line.CreateBound(aa, cc); rotated = location.Rotate(axis, Math.PI / 4); } return(rotated); }
/// <summary> /// Creates a new CurtainSystem for ceiling with transaction. /// </summary> /// <param name="doc"></param> /// <param name="app"></param> /// <param name="curtainParm"></param> /// <returns></returns> public static CurtainSystem CreateCurtainCeiling(this Document doc, App app, CurtainParm curtainParm) { if (doc is null) { throw new ArgumentNullException(nameof(doc)); } if (app is null) { throw new NullReferenceException(nameof(app)); } if (curtainParm is null) { throw new NullReferenceException(nameof(curtainParm)); } var loop = curtainParm.Room.GetRoomProfile(); var profile = loop.ToCurveArrArray(); return(doc.CreateCurtainSystem(app, profile, curtainParm, XYZ.BasisZ)); }
internal static BoundingBoxXYZ GrowBox(Autodesk.Revit.ApplicationServices.Application app, BoundingBoxXYZ box, double howMuch) { BoundingBoxXYZ newBox = null; for (int i = 0; i < 10; i++) { double offset = (double)i * howMuch; newBox = new BoundingBoxXYZ() { Min = new XYZ(box.Min.X - offset, box.Min.Y - offset, box.Min.Z - offset), Max = new XYZ(box.Max.X + offset, box.Max.Y + offset, box.Max.Z + offset) }; if (IsBoxTooSmall(app, newBox) == false) { return(newBox); } } // if we got here, we were unable to make it happy, but pass it back anyway? app.WriteJournalComment("Metamorphosis: Odd: Unable to grow box by " + howMuch + " and make it appropriate compared to " + app.ShortCurveTolerance, false); return(newBox); }
/// <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) { try { m_revit = commandData.Application.Application; m_familyDocument = commandData.Application.ActiveUIDocument.Document; // create new family document if active document is not a family document if (!m_familyDocument.IsFamilyDocument) { m_familyDocument = m_revit.NewFamilyDocument("Generic Model.rft"); if (null == m_familyDocument) { message = "Cannot open family document"; return(Autodesk.Revit.UI.Result.Failed); } } m_creationFamily = m_familyDocument.FamilyCreate; // create generic model family in the document CreateGenericModel(); if (0 == m_errCount) { return(Autodesk.Revit.UI.Result.Succeeded); } else { message = m_errorInfo; return(Autodesk.Revit.UI.Result.Failed); } } catch (Exception e) { message = e.ToString(); return(Autodesk.Revit.UI.Result.Failed); } }
/// <summary> /// PickPoints Support Everything In 3D View And Section /// </summary> /// <param name="commandData"></param> /// <param name="message"></param> /// <param name="elements"></param> /// <returns></returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { #region Init UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; #endregion try { using (Transaction tran = new Transaction(doc)) { tran.Start("run"); Plane plane = Plane.CreateByNormalAndOrigin(uidoc.ActiveView.ViewDirection, uidoc.ActiveView.Origin); SketchPlane sp = SketchPlane.Create(doc, plane); doc.ActiveView.SketchPlane = sp; doc.ActiveView.ShowActiveWorkPlane(); XYZ point = uidoc.Selection.PickPoint(ObjectSnapTypes.Intersections); doc.ActiveView.HideActiveWorkPlane(); sp.Dispose(); doc.Delete(sp.Id); MessageBox.Show(point.ToString()); tran.Commit(); } } catch (Autodesk.Revit.Exceptions.OperationCanceledException e) { MessageBox.Show($"You Has Press Esc\n{e}", "Warning", MessageBoxButtons.OK); return(Result.Cancelled); //Pressed Esc } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; ParameterCommands.Load(doc); SlackForm slackForm = new SlackForm(); slackForm.ShowDialog(); if (slackForm.DialogResult == DialogResult.OK) { Autodesk.Revit.ApplicationServices.Application app = doc.Application; if (doc.IsFamilyDocument) { TaskDialog.Show("Exception", "These settings can only be saved while in a Revit project, not in a Family."); } SlackSettings s = new SlackSettings(); s.slackCh = Variables.slackCh; s.slackChId = Variables.slackChId; s.slackOn = Variables.slackOn; s.slackWSWarn = Variables.slackWSWarn; s.slackModelWarn = Variables.slackModelWarn; s.slackBPWarn = Variables.slackBPWarn; s.slackWSInfo = Variables.slackWSInfo; s.slackModelInfo = Variables.slackModelInfo; s.slackBPInfo = Variables.slackBPInfo; s.slackExtraTrackPin = Variables.slackExtraTrackPin; s.tidySet = Variables.tidySet; s.giphySet = Variables.giphySet; s.slackToken = Variables.slackToken; ParameterCommands.Set(app, doc, Variables.defNameSettings, s); } return(Result.Succeeded); }
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; var relayTab = RibbonUtils.GetTab("Relay"); //create the panels for the sub directories foreach (var directory in Directory.GetDirectories(Globals.RelayGraphs)) { DirectoryInfo dInfo = new DirectoryInfo(directory); Autodesk.Revit.UI.RibbonPanel panelToUse = null; try { panelToUse = uiapp.CreateRibbonPanel("Relay", dInfo.Name); } catch (Exception) { panelToUse = uiapp.GetRibbonPanels("Relay").First(p => p.Name.Equals(dInfo.Name)); } var toCreate = Directory.GetFiles(directory, "*.dyn") .Where(f => RibbonUtils.GetButton("Relay", dInfo.Name, $"relay{new FileInfo(f).Name.Replace(" ", "")}") == null).ToArray(); RibbonUtils.AddItems(panelToUse, toCreate); } //subscribe to the events of the button to associate the current DYN Autodesk.Windows.ComponentManager.UIElementActivated -= ComponentManagerOnUIElementActivated; Autodesk.Windows.ComponentManager.UIElementActivated += ComponentManagerOnUIElementActivated; return(Result.Succeeded); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // This commands provide interact with active document UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Autodesk.Revit.DB.Document doc = uidoc.Document; View activeView = doc.ActiveView; Element cutter = GeometryHelper.GetStructuralColumnElement(doc, uidoc); IList <Element> intersects = GeometryHelper.GetIntersectsStructuralColumn(doc, activeView, cutter); using (Transaction tx = new Transaction(doc)) { // Start the transaction and give a unique name tx.Start("Cope Beam with Intersection"); try { GeometryHelper.CopeIntersects(doc, intersects, cutter, true); } catch (OperationCanceledException) { return(Result.Failed); } catch (Exception e) { TaskDialog.Show("ERROR", e.Message); } // End the transaction tx.Commit(); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "PointsParabola"); transaction.Start(); double yctr = 0; XYZ xyz = null; ReferencePoint rp = null; double power = 1.2; while (power < 1.5) { double xctr = 0; double zctr = 0; while (zctr < 100) { zctr = Math.Pow(xctr, power); xyz = new XYZ(xctr, yctr, zctr); rp = doc.FamilyCreate.NewReferencePoint(xyz); if (xctr > 0) { xyz = new XYZ(-xctr, yctr, zctr); rp = doc.FamilyCreate.NewReferencePoint(xyz); } xctr++; } power = power + 0.1; yctr = yctr + 50; zctr = 0; } transaction.Commit(); return(Result.Succeeded); }
//Gets a SharedParameter private ExternalDefinition GetSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name) { DefinitionFile defFile = app.OpenSharedParameterFile(); if (defFile == null) { DialogUtils.Failure("Error", $"Shared parameters file does not exist. You are trying to push a Shared Parameter into another Family - make sure you have setup a Shared Parameters file."); return(null); //throw new Exception("No SharedParameter File!"); } var v = (from DefinitionGroup dg in defFile.Groups from ExternalDefinition d in dg.Definitions where d.Name == name select d); if (v == null || v.Count() < 1) { return(null); //There is no Shared parameter with this name } ExternalDefinition def = v.First(); return(def); }
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; using (TransactionGroup transGr = new TransactionGroup(doc)) { transGr.Start("Auto Join"); AutoJoinViewModel viewModel = new AutoJoinViewModel(uidoc); AutoJoinWindow window = new AutoJoinWindow(viewModel); if (window.ShowDialog() == false) { return(Result.Cancelled); } transGr.Commit(); } return(Result.Succeeded); }
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; // Total Area of wall in project FilteredElementCollector collector = new FilteredElementCollector(doc); List <Element> listwall = collector.OfClass(typeof(Wall)).ToElements().ToList(); double total = 0; foreach (Element el in listwall) { Wall wall = el as Wall; if (wall != null) { total += wall.LookupParameter("Area").AsDouble(); } } MessageBox.Show("Total area of walls is: " + total); return(Result.Succeeded); }
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; // code // tạo ra 2 Instance Person m1 = new Person(); Person m2 = new Person(); // Gán giá trị property "CanNang" cho mỗi Instance List <double> q = new List <double>(); q.Add(m1.CanNang = 5); q.Add(m2.CanNang = 3); // Lấy ra giá trị "CanNang" lớn nhất double cannang = q.Max(); // Dùng vòng lặp "For" chạy từ 1 tới "CanNang" double a = cannang; for (int i = 1; i <= a; i++) { cannang = cannang * i; } // Show giá trị MessageBox.Show(cannang.ToString()); return(Result.Succeeded); }
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; //Task 01 Get element name. Reference refernce = uidoc.Selection.PickObject(ObjectType.Element); if (refernce != null) { //Get Id ElementId id = refernce.ElementId; Element element = doc.GetElement(id); MessageBox.Show("Element ID:" + id); MessageBox.Show("Element Name:" + element.Name); MessageBox.Show($"Category: {element.Category.Name}"); } return(Result.Succeeded); }
/// <summary> /// Creates a Brep product definition shape representation. /// </summary> /// <param name="application">The Revit application object.</param> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="categoryId">The category id.</param> /// <param name="geometryObject">The geometry object.</param> /// <param name="extraReps">Extra representations (e.g. Axis, Footprint). May be null.</param> /// <param name="options">The settings for how to export the body.</param> /// <param name="extrusionCreationData">The extrusion creation data.</param> /// <param name="bodyData">The body data.</param> /// <returns>The handle.</returns> public static IFCAnyHandle CreateBRepProductDefinitionShape(Autodesk.Revit.ApplicationServices.Application application, ExporterIFC exporterIFC, Element element, ElementId categoryId, IList <GeometryObject> geometryObjectIn, IList <IFCAnyHandle> extraReps, BodyExporterOptions bodyExporterOptions, IFCExtrusionCreationData extrusionCreationData, out BodyData bodyData) { bodyData = BodyExporter.ExportBody(application, exporterIFC, element, categoryId, geometryObjectIn, bodyExporterOptions, extrusionCreationData); IFCAnyHandle bodyRep = bodyData.RepresentationHnd; List <IFCAnyHandle> bodyReps = new List <IFCAnyHandle>(); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { if (extrusionCreationData != null) { extrusionCreationData.ClearOpenings(); } } else { bodyReps.Add(bodyRep); } if (extraReps != null) { foreach (IFCAnyHandle hnd in extraReps) { bodyReps.Add(hnd); } } if (bodyReps.Count == 0) { return(null); } return(IFCInstanceExporter.CreateProductDefinitionShape(exporterIFC.GetFile(), null, null, bodyReps)); }
public ParameterAssigner(Autodesk.Revit.ApplicationServices.Application app, Document doc) { m_app = app; m_manager = doc.FamilyManager; }
public void Execute(UpdaterData data) { Document doc = data.GetDocument(); Autodesk.Revit.ApplicationServices.Application app = doc.Application; View view = doc.GetElement(viewID) as View; FamilyInstance sphere = doc.GetElement(sphereID) as FamilyInstance; LocationPoint sphereLP = sphere.Location as LocationPoint; XYZ sphereXYZ = sphereLP.Point; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view); if (sfm == null) { sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point } sfm.Clear(); FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter); ICollection <Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Face face in GetFaces(elements)) { int idx = sfm.AddSpatialFieldPrimitive(face.Reference); List <double> doubleList = new List <double>(); IList <UV> uvPts = new List <UV>(); IList <ValueAtPoint> valList = new List <ValueAtPoint>(); BoundingBoxUV bb = face.GetBoundingBox(); for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15) { for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15) { UV uvPnt = new UV(u, v); uvPts.Add(uvPnt); XYZ faceXYZ = face.Evaluate(uvPnt); // Specify three values for each point doubleList.Add(faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); IList <int> registeredResults = new List <int>(); registeredResults = sfm.GetRegisteredResults(); int idx1 = 0; if (registeredResults.Count == 0) { idx1 = sfm.RegisterResult(resultSchema1); } else { idx1 = registeredResults.First(); } sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1); } }
public ModelCurveCreator(Document doc) { _doc = doc; _app = doc.Application; }
public AssemblyOptionsForm(ExternalCommandData commandData) { InitializeComponent(); ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = ui_app?.Application; Document doc = ui_doc?.Document; List <View3D> view3d = new List <View3D>(); List <Autodesk.Revit.DB.View> viewEl = new List <Autodesk.Revit.DB.View>(); List <Autodesk.Revit.DB.View> viewPl = new List <Autodesk.Revit.DB.View>(); List <ViewSchedule> viewSc = new List <ViewSchedule>(); List <string> tlist = new List <string>(); List <View3D> view3dF = new List <View3D>(); List <Autodesk.Revit.DB.View> viewPlF = new List <Autodesk.Revit.DB.View>(); List <Autodesk.Revit.DB.View> viewJSF = new List <Autodesk.Revit.DB.View>(); List <Autodesk.Revit.DB.View> viewTSF = new List <Autodesk.Revit.DB.View>(); List <ViewSchedule> viewScF = new List <ViewSchedule>(); List <string> tlistF = new List <string>(); List <DimensionType> dimL = new List <DimensionType>(); List <DimensionType> VertDimL = new List <DimensionType>(); FilteredElementCollector ViewCollector3D = new FilteredElementCollector(doc).OfClass(typeof(View3D)); FilteredElementCollector ViewCollectorEl = new FilteredElementCollector(doc).OfClass(typeof(Autodesk.Revit.DB.View)); FilteredElementCollector ViewCollectorSc = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)); FilteredElementCollector tempCollector = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_TitleBlocks); FilteredElementCollector dimCollector = new FilteredElementCollector(doc).OfClass(typeof(DimensionType)); addList(ViewCollector3D, view3d); addList(ViewCollectorEl, viewEl); addList(ViewCollectorEl, viewPl); addList(ViewCollectorSc, viewSc); addList(tempCollector, tlist); addList(ViewCollector3D, view3dF); addList(ViewCollectorEl, viewPlF); addList(ViewCollectorEl, viewJSF); addList(ViewCollectorEl, viewTSF); addList(ViewCollectorSc, viewScF); addList(tempCollector, tlistF); addList(dimCollector, dimL); addList(dimCollector, VertDimL); try { popCombo(v3dCombo, view3d, ViewCollector3D, doc, pstore.ReadSettings(doc)?.View3DTemplate); } catch (Exception) { popCombo(v3dCombo, view3d, ViewCollector3D, doc); } try { popCombo(vElCombo, viewEl, ViewCollectorEl, doc, pstore.ReadSettings(doc)?.ViewElTemplate); } catch (Exception) { popCombo(vElCombo, viewEl, ViewCollectorEl, doc); } try { popCombo(vPlCombo, viewPl, ViewCollectorEl, doc, pstore.ReadSettings(doc)?.ViewPlTemplate); } catch (Exception) { popCombo(vPlCombo, viewPl, ViewCollectorEl, doc); } try { popCombo(vPaCombo, viewSc, ViewCollectorSc, doc, pstore.ReadSettings(doc)?.ViewPaTemplate); } catch (Exception) { popCombo(vPaCombo, viewSc, ViewCollectorSc, doc); } try { popCombo(TemplCombo, tlist, tempCollector, doc, pstore.ReadSettings(doc)?.TemplateTemplate); } catch (Exception) { popCombo(TemplCombo, tlist, tempCollector, doc); } try { popCombo(v3DComboFlr, view3dF, ViewCollector3D, doc, pstore.ReadSettings(doc)?.View3DTemplateFlr); } catch (Exception) { popCombo(v3DComboFlr, view3dF, ViewCollector3D, doc); } try { popCombo(vPlComboFlr, viewPlF, ViewCollectorEl, doc, pstore.ReadSettings(doc)?.ViewPlanTemplateFlr); } catch (Exception) { popCombo(vPlComboFlr, viewPlF, ViewCollectorEl, doc); } try { popCombo(JSComboFlr, viewJSF, ViewCollectorEl, doc, pstore.ReadSettings(doc)?.ViewJoistTemplateFlr); } catch (Exception) { popCombo(JSComboFlr, viewJSF, ViewCollectorEl, doc); } try { popCombo(TSComboFlr, viewTSF, ViewCollectorEl, doc, pstore.ReadSettings(doc)?.ViewTrackTemplateFrl); } catch (Exception) { popCombo(TSComboFlr, viewTSF, ViewCollectorEl, doc); } try { popCombo(PaComboFlr, viewScF, ViewCollectorSc, doc, pstore.ReadSettings(doc)?.ViewPaTemplateFlr); } catch (Exception) { popCombo(PaComboFlr, viewScF, ViewCollectorSc, doc); } try { popCombo(ShComboFlr, tlistF, tempCollector, doc, pstore.ReadSettings(doc)?.TemplateTemplateFrl); } catch (Exception) { popCombo(ShComboFlr, tlistF, tempCollector, doc); } try { popCombo(HorCombo, dimL, dimCollector, doc, pstore.ReadSettings(doc)?.HorizontalDimFlr); } catch (Exception) { popCombo(HorCombo, dimL, dimCollector, doc); } try { popCombo(VertCombo, VertDimL, dimCollector, doc, pstore.ReadSettings(doc)?.VerticalDimFlr); } catch (Exception) { popCombo(VertCombo, VertDimL, dimCollector, doc); } }
/// <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; }
///<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, Autodesk.Revit.DB.ElementSet elements) { string assemblyLocation = Assembly.GetExecutingAssembly().Location; string log = assemblyLocation + "." + DateTime.Now.ToString("yyyyMMdd") + ".log"; if (File.Exists(log)) File.Delete(log); TraceListener txtListener = new TextWriterTraceListener(log); Trace.Listeners.Add(txtListener); try { // variable initialization m_application = commandData.Application.Application; m_document = commandData.Application.ActiveUIDocument.Document; Environment.CurrentDirectory = Path.GetDirectoryName(assemblyLocation); FindRoomBoundingRoofs(ref message, elements); // Not show TaskDialog in regression mode if (0 == commandData.JournalData.Count) { TaskDialog.Show("Roofs Rooms", message); } // Insert result to journal data for regression purpose. const string DataKey = "Results"; if (!commandData.JournalData.ContainsKey(DataKey)) { // In normal/recording mode commandData.JournalData.Add(DataKey, message); } else { // In regression/replaying mode commandData.JournalData[DataKey] = message; } return Autodesk.Revit.UI.Result.Succeeded; } catch (Exception ex) { Trace.WriteLine(ex.ToString()); message = ex.ToString(); return Autodesk.Revit.UI.Result.Failed; } finally { Trace.Flush(); txtListener.Close(); Trace.Close(); Trace.Listeners.Remove(txtListener); } }
public OriginalInstanceGeometry(string label, FamilyInstance val, Autodesk.Revit.ApplicationServices.Application app) : base(label) { m_val = val; m_app = app; m_hasGeometry = false; if (m_val != null && m_app != null) { Autodesk.Revit.DB.Options geomOp = m_app.Create.NewGeometryOptions(); geomOp.DetailLevel = ViewDetailLevel.Undefined; if (m_val.GetOriginalGeometry(geomOp) != null) m_hasGeometry = true; } }
/// <summary> /// Constructor /// </summary> /// <param name="app">Revit application</param> private GeometryCreation(Autodesk.Revit.ApplicationServices.Application app) { m_app = app; }
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; _app = app; _doc = doc; // Set project units to Meters then back after // This is how DIALux reads the data from the STF File. Units pUnit = doc.GetUnits(); FormatOptions formatOptions = pUnit.GetFormatOptions(UnitType.UT_Length); //DisplayUnitType curUnitType = pUnit.GetDisplayUnitType(); DisplayUnitType curUnitType = formatOptions.DisplayUnits; using (Transaction tx = new Transaction(doc)) { tx.Start("STF EXPORT"); const DisplayUnitType meters = DisplayUnitType.DUT_METERS; formatOptions.DisplayUnits = meters; // Comment out, different in 2014 //formatOptions.Units = meters; //formatOptions.Rounding = 0.0000000001;] formatOptions.Accuracy = 0.0000000001; // Fix decimal symbol for int'l versions (set back again after finish) if (pUnit.DecimalSymbol == DecimalSymbol.Comma) { intlVersion = true; //TESTING //TaskDialog.Show("INTL", "You have an internationalized version of Revit!"); formatOptions.UseDigitGrouping = false; pUnit.DecimalSymbol = DecimalSymbol.Dot; } try { // Filter for only active view. ElementLevelFilter filter = new ElementLevelFilter(doc.ActiveView.GenLevel.Id); FilteredElementCollector fec = new FilteredElementCollector(doc, doc.ActiveView.Id) .OfCategory(BuiltInCategory.OST_MEPSpaces) .WherePasses(filter); int numOfRooms = fec.Count(); writer += "[VERSION]\n" + "STFF=" + stfVersionNum + "\n" + "Progname=Revit\n" + "Progvers=" + app.VersionNumber + "\n" + "[Project]\n" + "Name=" + _doc.ProjectInformation.Name + "\n" + "Date=" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "\n" + "Operator=" + app.Username + "\n" + "NrRooms=" + numOfRooms + "\n"; for (int i = 1; i < numOfRooms + 1; i++) { string _dialuxRoomName = "Room" + i.ToString() + "=ROOM.R" + i.ToString(); writer += _dialuxRoomName + "\n"; } int increment = 1; // Space writer try { foreach (Element e in fec) { Space s = e as Space; string roomRNum = "ROOM.R" + increment.ToString(); writer += "[" + roomRNum + "]\n"; SpaceInfoWriter(s.Id, roomRNum); increment++; } // Write out Luminaires to bottom writeLumenairs(); // Reset back to original units formatOptions.DisplayUnits = curUnitType; if (intlVersion) pUnit.DecimalSymbol = DecimalSymbol.Comma; tx.Commit(); SaveFileDialog dialog = new SaveFileDialog { FileName = doc.ProjectInformation.Name, Filter = "STF File | *.stf", FilterIndex = 2, RestoreDirectory = true }; if (dialog.ShowDialog() == DialogResult.OK) { StreamWriter sw = new StreamWriter(dialog.FileName); string[] ar = writer.Split('\n'); for (int i = 0; i < ar.Length; i++) { sw.WriteLine(ar[i]); } sw.Close(); } return Result.Succeeded; } catch (IndexOutOfRangeException) { return Result.Failed; } } catch (NullReferenceException) { TaskDialog.Show("Incorrect View", "Cannot find Spaces to export.\nMake sure you are in a Floorplan or Ceiling Plan view and Spaces are visible."); return Result.Failed; } } }
/// <summary> /// Constructor /// </summary> /// <param name="commandData">Revit command data</param> /// <param name="exportFormat">Format to export</param> public ExportCivil3DData(ExternalCommandData commandData, ExportFormat exportFormat) : base(commandData, exportFormat) { m_application = commandData.Application.Application; m_document = commandData.Application.ActiveUIDocument.Document; m_dut = GetLengthUnitType(m_document); Initialize(); }
/// <summary> /// The top level command. /// </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 Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { m_app = revit.Application.Application; m_doc = revit.Application.ActiveUIDocument.Document; // Find a 3D view to use for the ray tracing operation FilteredElementCollector collector = new FilteredElementCollector(m_doc); Func<View3D, bool> isNotTemplate = v3 => !(v3.IsTemplate); m_view3D = collector.OfClass(typeof(View3D)).Cast<View3D>().First<View3D>(isNotTemplate); Autodesk.Revit.UI.Selection.Selection selection = revit.Application.ActiveUIDocument.Selection; // If skylight is selected, process it. m_skylight = null; if (selection.Elements.Size == 1) { foreach (Element e in selection.Elements) { if (e is FamilyInstance) { FamilyInstance instance = e as FamilyInstance; bool isWindow = (instance.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows); bool isHostedByRoof = (instance.Host.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Roofs); if (isWindow && isHostedByRoof) m_skylight = instance; } } } if (m_skylight == null) { message = "This tool requires exactly one skylight to be selected."; return Result.Cancelled; } // Find the floor to use for the measurement (hardcoded) ElementId id = new ElementId(150314); m_floor = m_doc.get_Element(id) as Floor; // Calculate the height Line line = CalculateLineAboveFloor(); // Create a model curve to show the distance Plane plane = m_app.Create.NewPlane(new XYZ(1, 0, 0), line.get_EndPoint(0)); SketchPlane sketchPlane = m_doc.Create.NewSketchPlane(plane); ModelCurve curve = m_doc.Create.NewModelCurve(line, sketchPlane); // Show a message with the length value TaskDialog.Show("Distance", "Distance to floor: " + String.Format("{0:f2}", line.Length)); return Result.Succeeded; }
//default execute method required by the IExternalCommand class public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { //call to the security check method to check for authentication security = SecurityLNT.Security_Check(); if (security == false) { return(Result.Succeeded); } //get the application data Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; //read the config file SpecificationData configFileData = UtilityMethods.ReadConfig(); //check for discipline if (configFileData.discipline != "PHE") { TaskDialog.Show("Failed!", "Sorry! Plug-in Not intended for your discipline."); return(Result.Succeeded); } //exception handled if (configFileData.offset == -1.0) { MessageBox.Show("Configuration data not found!"); return(Result.Succeeded); } //get all data from the specification file specsData = UtilityMethods.GetAllSpecs(configFileData); //exception handled if (specsData == null) { MessageBox.Show("Specifications not found!"); return(Result.Succeeded); } //open the active document in revit m_document = commandData.Application.ActiveUIDocument; //get the selected element set eleSet = m_document.Selection.Elements; if (eleSet.IsEmpty) { MessageBox.Show("Please select pipes before executing the Add-in!"); return(Result.Succeeded); } //call to method to get the transform required Transform transform = UtilityMethods.GetInverseTransform(m_document.Document, commandData.Application.Application); if (transform == null) { MessageBox.Show("Sorry! Couldn't find a possible transform."); return(Result.Succeeded); } //get family name from config data FamilyName = configFileData.selectedFamily; //check if family exists family = UtilityMethods.FindElementByName(m_document.Document, typeof(Family), FamilyName) as Family; //if existing if (family == null) { MessageBox.Show("Please load the family into the project and re-run the Add-in."); return(Result.Succeeded); } //get the family symbol symbol = UtilityMethods.GetFamilySymbol(family); //exception handled if (family == null) { MessageBox.Show("No family symbol for the family you specified!"); return(Result.Succeeded); } //create a logical filter for all the structural elements LogicalOrFilter filter = UtilityMethods.GetStructuralFilter(); //if no filter is returned if (filter == null) { return(Result.Succeeded); } //get the structural elements from the documents List <Element> structuralElements = new List <Element>(); structuralElements = UtilityMethods.GetStructuralElements(app, filter); if (structuralElements == null) { MessageBox.Show("Sorry! No structural element found"); return(Result.Succeeded); } //list to store all the planar botom faces of the structural elements List <PlanarFace> pFace = new List <PlanarFace>(); //find and add bottom planar faces to the list foreach (Element e in structuralElements) { PlanarFace pf = UtilityMethods.GetBottomFace(e); if (pf != null) { pFace.Add(pf); } } //clear the structural elements list as it is no longer required structuralElements.Clear(); //control variable for removing unwanted elements from the planar faces list int flag = 0; //iterate through all the selected elements foreach (Element ele in eleSet) { //check whether the selected element is of type pipe if (ele is Pipe) { //get the location curve of the pipe pipeCurve = ((LocationCurve)ele.Location).Curve; //if the length of pipe curve obtained is zero skip that pipe if (pipeCurve.Length == 0) { FailedToPlace.Add(ele.Id); continue; } //remove unwanted planes from the list if (flag == 0) { //remove unwanted faces from the list (this works only once) pFace = UtilityMethods.GetPossiblePlanes(pFace, pipeCurve.get_EndPoint(0), transform); flag = -1; } //if no plane is found for intersect to work if (pFace.Count == 0) { MessageBox.Show("Sorry! No structural element found"); return(Result.Succeeded); } //from the specification file, get the spacing corresponding to the pipe diameter spacing = UtilityMethods.GetSpacing(ele, specsData); //check if the spacing returned is -1 if (spacing == -1) { FailedToPlace.Add(ele.Id); continue; } //get the points for placing the family instances points = UtilityMethods.GetPlacementPoints(spacing, pipeCurve, 1000 * configFileData.offset, 1000 * configFileData.minSpacing); //check if the points is null exception if (points == null) { FailedToPlace.Add(ele.Id); continue; } //get the pipe level pipeLevel = ele.Level; //iterate through all the points for placing the family instances foreach (XYZ point in points) { try { //create the instances at each points tempEle = m_document.Document.Create.NewFamilyInstance (point, symbol, ele, pipeLevel, StructuralType.NonStructural); createdElements.Add(tempEle.Id); } catch { FailedToPlace.Add(ele.Id); continue; } //find the rod length required rodLength = UtilityMethods.ReturnLeastZ_Value(m_document.Document, pFace, point, transform); if (rodLength == -1) { FailedToPlace.Add(ele.Id); createdElements.Remove(tempEle.Id); m_document.Document.Delete(tempEle.Id); continue; } //adjust the newly created element properties based on the rodlength, //orientation and dia of pipe if (!UtilityMethods.AdjustElement(m_document.Document, tempEle, point, (Pipe)ele, rodLength, pipeCurve)) { FailedToPlace.Add(ele.Id); createdElements.Remove(tempEle.Id); m_document.Document.Delete(tempEle.Id); continue; } } } } return(Result.Succeeded); } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } throw new NotImplementedException(); }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { const string _prompt = "Please select two parallel opposing walls."; UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; List <Wall> walls = new List <Wall>(2); ICollection <ElementId> selectionIds = uidoc.Selection.GetElementIds(); if (selectionIds.Count > 0) { foreach (ElementId id in selectionIds) { Element elem = doc.GetElement(id); if (elem is Wall) { walls.Add(elem as Wall); } } if (2 != walls.Count) { message = _prompt; return(Result.Failed); } } List <Line> lines = new List <Line>(2); List <XYZ> midpoints = new List <XYZ>(2); XYZ normal = null; foreach (Wall wall in walls) { LocationCurve locCur = wall.Location as LocationCurve; Curve curve = locCur.Curve; if (!(curve is Line)) { message = _prompt; return(Result.Failed); } Line l = curve as Line; lines.Add(l); midpoints.Add(Midpoint(l)); if (null == normal) { normal = Normal(l); } else { if (!IsParallel(normal, Normal(l))) { message = _prompt; return(Result.Failed); } } } Options opt = app.Create.NewGeometryOptions(); opt.ComputeReferences = true; List <Face> faces = new List <Face>(2); faces.Add(GetClosestFace(walls[0], midpoints[1], normal, opt)); faces.Add(GetClosestFace(walls[1], midpoints[0], normal, opt)); CreateDimensionElement(doc, app, doc.ActiveView, midpoints[0], faces[0].Reference, midpoints[1], faces[1].Reference); return(Result.Succeeded); }
/// <summary> /// 创建共享参数 /// </summary> /// <param name="doc"></param> /// <param name="app"></param> /// <returns></returns> public static bool ShareParameterGenerate(Document doc, Autodesk.Revit.ApplicationServices.Application app) { //设置共享参数 string TxtFileName = app.RecordingJournalFilename; Definition IdDf; Definition areaDf; Definition sizeDf; Definition XDf; Definition YDf; Definition ZDf; string sNametmp = TxtFileName.Substring(0, TxtFileName.LastIndexOf("\\")) + "\\Teplate共享参数.txt"; if (!File.Exists(sNametmp)) { File.WriteAllText(sNametmp, "", Encoding.Default); app.SharedParametersFilename = sNametmp; } try { DefinitionFile dsFile = app.OpenSharedParameterFile(); DefinitionGroup dsGroup = dsFile.Groups.ToList().Where(m => m.Name == "模板信息").First(); IdDf = dsGroup.Definitions.get_Item("HostElemID"); areaDf = dsGroup.Definitions.get_Item("模板面积"); sizeDf = dsGroup.Definitions.get_Item("模板尺寸"); XDf = dsGroup.Definitions.get_Item("X"); YDf = dsGroup.Definitions.get_Item("Y"); ZDf = dsGroup.Definitions.get_Item("Z"); } catch { // 判断 路径是否有效,如果为空,读者可以创建一txt文件 //将路径赋值给app.SharedParametersFilename DefinitionFile dfile = app.OpenSharedParameterFile(); // 创建一个共享参数分组 DefinitionGroup dg = dfile.Groups.Create("模板信息"); // 参数创建的选项,包括参数名字,参数类型,用户是不是可以修改。。 ExternalDefinitionCreationOptions elemID = new ExternalDefinitionCreationOptions("HostElemID", ParameterType.Integer); elemID.UserModifiable = false; ExternalDefinitionCreationOptions TemplateArea = new ExternalDefinitionCreationOptions("模板面积", ParameterType.Area); TemplateArea.UserModifiable = false; ExternalDefinitionCreationOptions TemplateSize = new ExternalDefinitionCreationOptions("模板尺寸", ParameterType.Text); TemplateSize.UserModifiable = false; ExternalDefinitionCreationOptions X = new ExternalDefinitionCreationOptions("X", ParameterType.Number); X.UserModifiable = false; ExternalDefinitionCreationOptions Y = new ExternalDefinitionCreationOptions("Y", ParameterType.Number); Y.UserModifiable = false; ExternalDefinitionCreationOptions Z = new ExternalDefinitionCreationOptions("Z", ParameterType.Number); Z.UserModifiable = false; // 创建参数 IdDf = dg.Definitions.Create(elemID); areaDf = dg.Definitions.Create(TemplateArea); sizeDf = dg.Definitions.Create(TemplateSize); XDf = dg.Definitions.Create(X); YDf = dg.Definitions.Create(Y); ZDf = dg.Definitions.Create(Z); } if (IdDf == null || areaDf == null || YDf == null || XDf == null || ZDf == null || sizeDf == null) { return(false); } // 创建一个Category集合 CategorySet cateSet = app.Create.NewCategorySet(); // 获取墙的category Category TemplateCate = Category.GetCategory(doc, BuiltInCategory.OST_Parts); // 在Category集合中加入 模板的category bool flag = cateSet.Insert(TemplateCate); // 给 这个Category集合中的Category 创建一个实例绑定 InstanceBinding TemBd = app.Create.NewInstanceBinding(cateSet); //ElementBinding TemBd = app.Create.NewTypeBinding(cateSet); // 获取当前Document的BindingMap BindingMap bmap = doc.ParameterBindings; //创建共享参数和Category之间的Binding bmap.Insert(IdDf, TemBd); bmap.Insert(areaDf, TemBd); bmap.Insert(sizeDf, TemBd); bmap.Insert(XDf, TemBd); bmap.Insert(YDf, TemBd); bmap.Insert(ZDf, TemBd); //设置视图,打开组成部分 doc.ActiveView.PartsVisibility = PartsVisibility.ShowPartsOnly; Material partMat = null; try { partMat = FilterElementList <Material>(doc).Where(m => m.Name == "模板材质").First() as Material; } catch { partMat = doc.GetElement(Material.Create(doc, "模板材质")) as Material; partMat.Color = new Color(255, 0, 0); } doc.Settings.Categories.get_Item(BuiltInCategory.OST_Parts).Material = partMat; return(true); }
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; // Determine elements to export FilteredElementCollector collector = null; // Access current selection //SelElementSet set = uidoc.Selection.Elements; //int n = set.Size; int n = 0; if (0 < n) { // If any elements were preselected, // export those to OBJ //ICollection<ElementId> ids = set // .Cast<Element>() // .Select<Element, ElementId>( e => e.Id ) // .ToArray<ElementId>(); //collector = new FilteredElementCollector( doc, ids ); } else { // If nothing was preselected, export // all model elements to OBJ //collector = new FilteredElementCollector(doc); collector = new FilteredElementCollector(doc, doc.ActiveView.Id); } //collector.WhereElementIsNotElementType() // .WhereElementIsViewIndependent(); if (null == _export_folder_name) { _export_folder_name = Path.GetTempPath(); } if (!FileSelect(_export_folder_name, out string filename)) { return(Result.Cancelled); } _export_folder_name = Path.GetDirectoryName(filename); var exporter = new ObjExporter(); Options opt = app.Create.NewGeometryOptions(); opt.DetailLevel = ViewDetailLevel.Coarse; ExportElements(exporter, collector, opt); exporter.ExportTo(filename); //var levelOfDetail = 1.0; //SolidOrShellTessellationControls solidOrShellTessellationControls = new SolidOrShellTessellationControls(); //solidOrShellTessellationControls.LevelOfDetail = (double)levelOfDetail / 30.0; //solidOrShellTessellationControls.Accuracy = 0.1; //solidOrShellTessellationControls.MinAngleInTriangle = 0.0001; //solidOrShellTessellationControls.MinExternalAngleBetweenTriangles = 1.0; //TriangulatedSolidOrShell triangulatedSolidOrShell = // SolidUtils.TessellateSolidOrShell(solid, solidOrShellTessellationControls); return(Result.Succeeded); }
// Implement the interface to execute the command. public Result Execute( ExternalCommandData InCommandData, // contains reference to Application and View ref string OutCommandMessage, // error message to display in the failure dialog when the command returns "Failed" ElementSet OutElements // set of problem elements to display in the failure dialog when the command returns "Failed" ) { Autodesk.Revit.ApplicationServices.Application Application = InCommandData.Application.Application; if (string.Compare(Application.VersionNumber, "2018", StringComparison.Ordinal) == 0 && string.Compare(Application.SubVersionNumber, "2018.3", StringComparison.Ordinal) < 0) { string Message = string.Format("The running Revit is not supported.\nYou must use Revit 2018.3 or further updates to export."); MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } if (!CustomExporter.IsRenderingSupported()) { string Message = "3D view rendering is not supported in the running Revit."; MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } UIDocument UIDoc = InCommandData.Application.ActiveUIDocument; if (UIDoc == null) { string Message = "You must be in a document to export."; MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } Document Doc = UIDoc.Document; string DocumentPath = Doc.PathName; if (string.IsNullOrWhiteSpace(DocumentPath)) { string message = "Your document must be saved on disk before exporting."; MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } bool ExportActiveViewOnly = true; // Retrieve the Unreal Datasmith export options. DatasmithRevitExportOptions ExportOptions = new DatasmithRevitExportOptions(Doc); if ((System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control) { if (ExportOptions.ShowDialog() != DialogResult.OK) { return(Result.Cancelled); } ExportActiveViewOnly = false; } // Generate file path for each view. Dictionary <ElementId, string> FilePaths = new Dictionary <ElementId, string>(); List <View3D> ViewsToExport = new List <View3D>(); if (ExportActiveViewOnly) { View3D ActiveView = Doc.ActiveView as View3D; if (ActiveView == null) { string Message = "You must be in a 3D view to export."; MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } if (ActiveView.IsTemplate || !ActiveView.CanBePrinted) { string Message = "The active 3D view cannot be exported."; MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } string ViewFamilyName = ActiveView.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", ""); string FileName = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{ActiveView.Name}.udatasmith", @"\s+", "_"); SaveFileDialog Dialog = new SaveFileDialog(); Dialog.Title = DIALOG_CAPTION; Dialog.InitialDirectory = Path.GetDirectoryName(DocumentPath); Dialog.FileName = FileName; Dialog.DefaultExt = "udatasmith"; Dialog.Filter = "Unreal Datasmith|*.udatasmith"; Dialog.CheckFileExists = false; Dialog.CheckPathExists = true; Dialog.AddExtension = true; Dialog.OverwritePrompt = true; if (Dialog.ShowDialog() != DialogResult.OK) { return(Result.Cancelled); } string FilePath = Dialog.FileName; if (string.IsNullOrWhiteSpace(FilePath)) { string message = "The given Unreal Datasmith file name is blank."; MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(Result.Cancelled); } FilePaths.Add(ActiveView.Id, FilePath); ViewsToExport.Add(ActiveView); } else { string SavePath; using (var FBD = new FolderBrowserDialog()) { FBD.ShowNewFolderButton = true; DialogResult result = FBD.ShowDialog(); if (result != DialogResult.OK || string.IsNullOrWhiteSpace(FBD.SelectedPath)) { return(Result.Cancelled); } SavePath = FBD.SelectedPath; } foreach (var View in ExportOptions.Selected3DViews) { string ViewFamilyName = View.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", ""); string FileName = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{View.Name}.udatasmith", @"\s+", "_"); FilePaths.Add(View.Id, Path.Combine(SavePath, FileName)); ViewsToExport.Add(View); } } // Prevent user interaction with the active 3D view to avoid the termination of the custom export, // without Revit providing any kind of internal or external feedback. EnableViewWindow(InCommandData.Application, false); // Create a custom export context for command Export to Unreal Datasmith. FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(InCommandData.Application.Application, Doc, FilePaths, ExportOptions); // Export the active 3D View to the given Unreal Datasmith file. using (CustomExporter Exporter = new CustomExporter(Doc, ExportContext)) { // Add a progress bar callback. // application.ProgressChanged += exportContext.HandleProgressChanged; try { // The export process will exclude output of geometric objects such as faces and curves, // but the context needs to receive the calls related to Faces or Curves to gather data. // The context always receive their tessellated geometry in form of polymeshes or lines. Exporter.IncludeGeometricObjects = true; // The export process should stop in case an error occurs during any of the exporting methods. Exporter.ShouldStopOnError = true; // Initiate the export process for all 3D views. foreach (var view in ViewsToExport) { #if REVIT_API_2020 Exporter.Export(view as Autodesk.Revit.DB.View); #else Exporter.Export(view); #endif } } catch (System.Exception exception) { OutCommandMessage = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace); MessageBox.Show(OutCommandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); return(Result.Failed); } finally { // Remove the progress bar callback. // application.ProgressChanged -= exportContext.HandleProgressChanged; // Restore user interaction with the active 3D view. EnableViewWindow(InCommandData.Application, true); if (ExportContext.GetMessages().Count > 0) { string Messages = string.Join($"{System.Environment.NewLine}", ExportContext.GetMessages()); DatasmithRevitApplication.ShowExportMessages(Messages); } } } return(Result.Succeeded); }
Result IExternalCommand.Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { // cache admin data _appUI = commandData.Application; _app = _appUI.Application; _docUI = commandData.Application.ActiveUIDocument; _doc = _docUI.Document; try // generic { // Current View must be Sheet ViewSheet sheet = _doc.ActiveView as ViewSheet; if( null == sheet ) { Util.ErrorMsg( "Current View is NOT a Sheet!" ); return Result.Cancelled; } // There must be a Floor Plan named "Level 0" // which is the "master" to align to Viewport vpMaster = null; // There must be at least one more Floor Plan // View to align (move) List<Viewport> vpsSlave = new List<Viewport>(); // Find them: foreach( ElementId idVp in sheet.GetAllViewports() ) { Viewport vp = _doc.GetElement( idVp ) as Viewport; ViewRvt v = _doc.GetElement( vp.ViewId ) as ViewRvt; if( v.ViewType == ViewType.FloorPlan ) { if( v.Name.Equals( "Level 0", StringComparison .CurrentCultureIgnoreCase ) ) { vpMaster = vp; } else { vpsSlave.Add( vp ); } } //if FloorPlan } //foreeach idVp // Check if got them all if( null == vpMaster ) { Util.ErrorMsg( "NO 'Level 0' Floor Plan on the Sheet!" ); return Result.Cancelled; } else if( vpsSlave.Count == 0 ) { Util.ErrorMsg( "NO other Floor Plans to adjust on the Sheet!" ); return Result.Cancelled; } // Process Master // -------------- XYZ ptMasterVpCenter = vpMaster.GetBoxCenter(); ViewRvt viewMaster = _doc.GetElement( vpMaster.ViewId ) as ViewRvt; double scaleMaster = viewMaster.Scale; // Process Slaves // -------------- foreach( Viewport vpSlave in vpsSlave ) { XYZ ptSlaveVpCenter = vpSlave.GetBoxCenter(); ViewRvt viewSlave = _doc.GetElement( vpSlave.ViewId ) as ViewRvt; double scaleSlave = viewSlave.Scale; // MUST be the same scale, otherwise can't really overlap if( scaleSlave != scaleMaster ) continue; // Work out how to move the center of Slave // Viewport to coincide model-wise with Master // (must use center as only Viewport.SetBoxCenter // is provided in API) // We can ignore View.Outline as Viewport.GetBoxOutline // is ALWAYS the same dimensions enlarged by // 0.01 ft in each direction. // This guarantees that the center of View is // also center of Viewport, BUT there is a // problem when any Elevation Symbols outside // the crop box are visible (can't work out why // - BUG?, or how to calculate it all if BY-DESIGN) BoundingBoxXYZ bbm = viewMaster.CropBox; BoundingBoxXYZ bbs = viewSlave.CropBox; // 0) Center points in WCS XYZ wcsCenterMaster = 0.5 * bbm.Min.Add( bbm.Max ); XYZ wcsCenterSlave = 0.5 * bbs.Min.Add( bbs.Max ); // 1) Delta (in model's feet) of the slave center w.r.t master center double deltaX = wcsCenterSlave.X - wcsCenterMaster.X; double deltaY = wcsCenterSlave.Y - wcsCenterMaster.Y; // 1a) Scale to Delta in Sheet's paper-space feet deltaX *= 1.0 / (double) scaleMaster; deltaY *= 1.0 / (double) scaleMaster; // 2) New center point for the slave viewport, so *models* "overlap": XYZ newCenter = new XYZ( ptMasterVpCenter.X + deltaX, ptMasterVpCenter.Y + deltaY, ptSlaveVpCenter.Z ); vpSlave.SetBoxCenter( newCenter ); } } catch( Exception ex ) { Util.ErrorMsg( "Generic exception: " + ex.Message ); return Result.Failed; } return Result.Succeeded; }
public static bool ValidateMep(Autodesk.Revit.ApplicationServices.Application application) { return(application.IsPipingEnabled); }
/// <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; }
/// <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; }
public static IList <Autodesk.Revit.Utility.Asset> GetAssets(this Autodesk.Revit.ApplicationServices.Application app, Autodesk.Revit.Utility.AssetType assetType) { return(new Autodesk.Revit.Utility.Asset[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, Autodesk.Revit.DB.ElementSet elements) { m_revit = commandData.Application.Application; Transaction documentTransaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document"); documentTransaction.Start(); // Initialize the helper classes. m_combinationDeal = new LoadCombinationDeal(this); m_loadCaseDeal = new LoadCaseDeal(this); // Prepare some data for the form displaying PrepareData(); // Display the form and wait for the user's operate. // This class give some public methods to add or delete LoadUsage and delete LoadCombination // The form will use these methods to add or delete dynamically. // If the user press cancel button, return Cancelled to roll back All the changes. using (LoadsForm displayForm = new LoadsForm(this)) { if (DialogResult.OK != displayForm.ShowDialog()) { documentTransaction.RollBack(); return Autodesk.Revit.UI.Result.Cancelled; } } // If everything goes right, return succeeded. documentTransaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData , ref string message, Autodesk.Revit.DB.ElementSet elements) { m_revitApp = commandData.Application.Application; m_revitDoc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(m_revitDoc, "ManipulateForm"); try { transaction.Start(); // Create a loft form Form form = CreateLoft(); m_revitDoc.Regenerate(); // Add profile to the loft form int profileIndex = AddProfile(form); m_revitDoc.Regenerate(); // Move the edges on added profile MoveEdgesOnProfile(form, profileIndex); m_revitDoc.Regenerate(); // Move the added profile MoveProfile(form, profileIndex); m_revitDoc.Regenerate(); // Move the vertex on bottom profile MoveVertexesOnBottomProfile(form); m_revitDoc.Regenerate(); // Add edge to the loft form Reference edgeReference = AddEdge(form); m_revitDoc.Regenerate(); // Move the added edge Autodesk.Revit.DB.XYZ offset = new Autodesk.Revit.DB.XYZ (0, -40, 0); MoveSubElement(form, edgeReference, offset); m_revitDoc.Regenerate(); // Move the vertex on added profile MoveVertexesOnAddedProfile(form, profileIndex); m_revitDoc.Regenerate(); transaction.Commit(); } catch (Exception ex) { message = ex.Message; transaction.RollBack(); return Autodesk.Revit.UI.Result.Failed; } return Autodesk.Revit.UI.Result.Succeeded; }