public Repository(ExternalCommandData commandData) { m_commandData = commandData; m_uiapp = m_commandData.Application; m_uidoc = m_uiapp.ActiveUIDocument; m_doc = m_uidoc.Document; }
public static void beginCommand(Document doc, string strDomain, bool bForAllSystems = false, bool bFitlerUnCalculationSystems = false) { PressureLossReportHelper helper = PressureLossReportHelper.instance; UIDocument uiDocument = new UIDocument(doc); if (bFitlerUnCalculationSystems) { ElementSet calculationOnElems = new ElementSet(); int nTotalCount = getCalculationElemSet(doc, strDomain, calculationOnElems, uiDocument.Selection.Elements); if (calculationOnElems.Size == 0) {//No item can be calculated popupWarning(ReportResource.allItemsCaculationOff, TaskDialogCommonButtons.Close, TaskDialogResult.Close); return; } else if (calculationOnElems.Size < nTotalCount) {//Part of them can be calculated if (popupWarning(ReportResource.partOfItemsCaculationOff, TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes, TaskDialogResult.Yes) == TaskDialogResult.No) return; } helper.initialize(doc, calculationOnElems, strDomain); invokeCommand(doc, helper, bForAllSystems); } else { helper.initialize(doc, uiDocument.Selection.Elements, strDomain); invokeCommand(doc, helper, bForAllSystems); } }
/// <summary> /// Constructor which takes a Revit.Document as parameter. /// </summary> /// <param name="rvtDoc">Revit.Document parameter</param> protected HostedSweepCreator(Autodesk.Revit.UI.UIDocument rvtDoc) { m_rvtUIDoc = rvtDoc; m_rvtDoc = rvtDoc.Document; m_elemGeom = new Dictionary<Autodesk.Revit.DB.Element, ElementGeometry>(); m_createdHostedSweeps = new List<ModificationData>(); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; doc = uidoc.Document; //creates a new instance of the wallselectionFilter ISelectionFilter wallfil = new WallSelectionFilter(); //gets the object selected Elementid, applies the selection filter and the string mesasge ElementId obj = uidoc.Selection.PickObject(ObjectType.Element, wallfil, "Select a Wall please").ElementId; //gets the element from the ElementID Element e = doc.GetElement(obj); //get the family type Elementid ElementId idType = e.GetTypeId(); //Get the Element Type ID Element pType = doc.GetElement(idType); //gets the instance length of the object string s = e.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsValueString(); //gets the type width of the object string t = pType.get_Parameter(BuiltInParameter.WALL_ATTR_WIDTH_PARAM).AsValueString(); //Shows the values TaskDialog.Show("Example", s + " " + t); return Result.Succeeded; }
//third exervise put into a user interface public static void updateDoor(Document doc, UIDocument uidoc) { //creates a Collection of the doors as FamilyInstances var doorColl = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .OfClass(typeof(FamilyInstance)); //Uses linq queries to select the door that have a ToRoom Value IEnumerable<FamilyInstance> doors = from FamilyInstance f in doorColl where f.ToRoom != null select f; //Start the transaction CRITICAL without transactions Revit cannot update using (Transaction t = new Transaction(doc, "Door Data Update")) { //Starts the transction t.Start(); //goes through each door based on the filter above foreach (FamilyInstance e in doors) { //gets the ToRoom number as a string string doorToRoom = e.ToRoom.Number.ToString(); //updates the comments parameter to the ToRoom value e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set(doorToRoom); } //Commits the changes to the Revit File t.Commit(); } }
public void Execute(UIDocument uiDocument, object data) { var filter = data as string; if (null == filter) return; var family = "TestAnno"; var parameters = new[] {"Series", "Number", "Text"}; var document = uiDocument.Document; var schedule = new FilteredElementCollector(document).OfClass(typeof (ViewSchedule)) .FirstOrDefault(s => s.Name.Contains(filter)); Element schedElem = null; using (var t = new Transaction(document)) { t.Start("Place schedule"); if (null == schedule) schedule = Schedule.Factory(uiDocument.Document, family, parameters, filter); schedElem = ScheduleSheetInstance.Create(uiDocument.Document, uiDocument.ActiveView.Id, schedule.Id, new XYZ()); t.Commit(); } uiDocument.Selection.SetElementIds(new List<ElementId>() { schedElem.Id }); //var uiapp = new UIApplication(document.Application); //uiapp.PostCommand(RevitCommandId.LookupCommandId("ID_EDIT_MOVE")); //uiDocument.PromptToPlaceViewOnSheet(schedule, false); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //setup class variables _dbDoc = commandData.Application.ActiveUIDocument.Document; _uiDoc = commandData.Application.ActiveUIDocument; //setup ScoreKeeper _scoreKeeper = new ScoreKeeper(_dbDoc); //Find out which game to play NewGameMenu menu = new NewGameMenu(); DialogResult result = menu.ShowDialog(); //check if they want to reset the scores //using a dialog result of No to trigger this. if (result == DialogResult.No) { _scoreKeeper.ResetScores(); return Result.Succeeded; } if (result != DialogResult.OK) return Result.Cancelled; //setup the game IGame game = SetupGame(menu.IsOnlineGame()); //run the game game.StartGame(); return Result.Succeeded; }
public AddIssueRevit(UIDocument uidoc2, string folder, ObservableCollection<Issuetype> _typesCollection, List<User> _assignees, ObservableCollection<Component> _compCollection, ObservableCollection<Priority> _PrioritiesCollection, bool comp, bool prior, bool assign) { try { uidoc = uidoc2; doc = uidoc.Document; snapshot = System.IO.Path.Combine(folder, "snapshot.png"); InitializeComponent(); TitleBox.Focus(); comboVisuals.ItemsSource = visuals; //comboStatuses.ItemsSource = statuses; //comboStatuses.SelectedIndex = 3; if (null != _typesCollection) { typesCollection = _typesCollection; issueTypeCombo.ItemsSource = typesCollection; issueTypeCombo.SelectedIndex = 0; } if (!comp) { compCollection = _compCollection; } else ComponentsStack.Visibility = System.Windows.Visibility.Collapsed; if (!assign && null != _assignees) { assignees = _assignees; } else assigneeStack.Visibility = System.Windows.Visibility.Collapsed; if (!prior && null != _PrioritiesCollection) { PrioritiesCollection = _PrioritiesCollection; priorityCombo.ItemsSource = PrioritiesCollection; priorityCombo.SelectedIndex = 0; } else PriorityStack.Visibility = System.Windows.Visibility.Collapsed; //select current visual style string currentV = doc.ActiveView.DisplayStyle.ToString(); for (int i = 0; i < comboVisuals.Items.Count; i++) { if (comboVisuals.Items[i].ToString() == currentV) { comboVisuals.SelectedIndex = i; } } updateImage(); } catch (System.Exception ex1) { TaskDialog.Show("Error!", "exception: " + ex1); } }
/// <summary> /// Initializes a new instance of the <see cref="clsElementSelection" /> class. /// </summary> /// <param name="uidoc">The uidoc.</param> public clsElementSelection(UIDocument uidoc) { _UiDoc = uidoc; _Doc = _UiDoc.Document; GetReferenceElement(); GetWallElement(); }
public UserControl(UIDocument doc) { InitializeComponent(); Packages = new List<string>(); RevitDoc = doc; webBrowser1.DocumentTitleChanged += webBrowser1_DocumentTitleChanged; var userName = Environment.UserDomainName + Environment.UserName; webBrowser1.Navigate(string.Format("http://bxc.mepcontent.com/?r=1&u={0}&v=13", userName)); }
/// <summary> /// Constructor, Store the Revit application /// </summary> /// <param name="app"></param> public FamilyInstanceCreator(Autodesk.Revit.UI.UIApplication app) { m_revitDoc = app.ActiveUIDocument; m_appCreator = app.Application.Create; if (!CheckSelectedElementSet()) { throw new Exception("Please select an element with face geometry."); } }
public UserControl(UIDocument Doc) { InitializeComponent(); Packages = new List<string>(); RevitDoc = Doc; webBrowser1.DocumentTitleChanged += webBrowser1_DocumentTitleChanged; string UserName = Environment.UserDomainName + Environment.UserName; webBrowser1.Navigate("http://bxc.mepcontent.com/?r=1&u=" + UserName); }
// public string GetImageFromView(UIDocument uidoc, Autodesk.Revit.DB.View view, bool isReload) { if (!isReload) { Selection choices = uidoc.Selection; try { Reference hasPickOne = choices.PickObject(ObjectType.Element); Import.selElement = uidoc.Document.GetElement(hasPickOne.ElementId); } catch (Exception) { MessageBox.Show("Необходимо выбрать графический вид!!!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Stop); return ""; } } IList<ElementId> ImageExportList = new List<ElementId>(); ImageExportList.Add(view.Id); var BilledeExportOptions = new ImageExportOptions { PixelSize = 512, ExportRange = ExportRange.SetOfViews, HLRandWFViewsFileType = ImageFileType.PNG, ImageResolution = ImageResolution.DPI_300, ZoomType = ZoomFitType.Zoom, ShadowViewsFileType = ImageFileType.PNG }; BilledeExportOptions.ViewName = ""; BilledeExportOptions.FilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Temp\" + view.Id.IntegerValue.ToString() + ".png"; BilledeExportOptions.SetViewsAndSheets(ImageExportList); try { uidoc.Document.ExportImage(BilledeExportOptions); } catch { return ""; } DirectoryInfo imagesDir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Temp\"); string nameFile = ""; nameFile = RenameFile(view, imagesDir, nameFile); //Image im = Image.FromFile(nameFile); //im = resizeImage(im, new Size(256, 256)); //string newName = Path.GetFileNameWithoutExtension(nameFile); //newName += "f.png"; //im.Save(newName); //using (var image = Image.FromFile(nameFile)) //using (var newImage = ScaleImage(image, 300, 400)) //{ // newImage.Save(@"c:\test.png", ImageFormat.Png); //} return nameFile; }
public UpgraderForm( ExternalCommandData commandData ) { InitializeComponent(); // Keep a local copy of the command data cmdData = commandData; previousDocument = null; }
//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; }
/// <summary> /// Prompt the user to select a face on an element /// and then pick a point on that face. The first /// picking of the face on the element temporarily /// redefines the active work plane, on which the /// second point can be picked. /// </summary> bool PickFaceSetWorkPlaneAndPickPoint( UIDocument uidoc, out XYZ point_in_3d) { point_in_3d = null; Document doc = uidoc.Document; Reference r = uidoc.Selection.PickObject( ObjectType.Face, "Please select a planar face to define work plane" ); Element e = doc.GetElement( r.ElementId ); if( null != e ) { PlanarFace face = e.GetGeometryObjectFromReference( r ) as PlanarFace; if( face != null ) { Plane plane = new Plane( face.Normal, face.Origin ); Transaction t = new Transaction( doc ); t.Start( "Temporarily set work plane" + " to pick point in 3D" ); //SketchPlane sp = doc.Create.NewSketchPlane( plane ); // 2013 SketchPlane sp = SketchPlane.Create( doc, plane ); // 2014 uidoc.ActiveView.SketchPlane = sp; uidoc.ActiveView.ShowActiveWorkPlane(); try { point_in_3d = uidoc.Selection.PickPoint( "Please pick a point on the plane" + " defined by the selected face" ); } catch( OperationCanceledException ) { } t.RollBack(); } } return null != point_in_3d; }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { uiApp = commandData.Application; uiDoc = commandData.Application.ActiveUIDocument; dbDoc = commandData.Application.ActiveUIDocument.Document; //don't run the command if the project isn't workshared if (!dbDoc.IsWorkshared) { TaskDialog.Show("Match Workset", "This project is not workshared"); return Result.Failed; } ElementSet selElements = uiDoc.Selection.Elements; //don't run the command if nothing is selected if (0 == selElements.Size) { TaskDialog.Show("Match Workset", "No assignable elements selected"); return Result.Failed; } Reference target; try { target = uiDoc.Selection.PickObject(ObjectType.Element, new ValidTargetFilter(), "Pick an element on the target workset"); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return Result.Cancelled; } //retrieve the Workset of the target Reference Workset targetWs = dbDoc.GetWorksetTable().GetWorkset( dbDoc.GetElement(target.ElementId).WorksetId ); using (Transaction t = new Transaction(dbDoc, "Match Workset")) { t.Start(); foreach (Element e in selElements) { Parameter wsParam = e.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM); if (!wsParam.IsReadOnly) { wsParam.Set(targetWs.Id.IntegerValue); } } t.Commit(); } return Result.Succeeded; }
WebclientX client = new WebclientX();//this is HTTP protocol class which is used to request to PHP server. public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { //this is our modification run();//is my main function which is exporting model and semantic information uidoc = revit.Application.ActiveUIDocument;//get uidoc, what is sentence of revit.Application.ActiveUIDocument for?? //I don't understand this line, but I know that I need to get uidoc to access component in revit for example at line "collector = new FilteredElementCollector(uidoc.Document);", I get collection of walls. //and in order to get uidoc, we need to use "revit.Application.ActiveUIDocument". I got this in manual //end modification uidoc.ActiveView.Scale = 1; //we cannot change the return return Autodesk.Revit.UI.Result.Succeeded;//page 26 in Revit SDK Manual } // the first execute function?? yes
public void Ungroup(Document doc, UIDocument uidoc) { IList<Category> categoryToDelete = new List<Category>(); List<Group> ungroupList = new List<Group>(); //Finds the groups in the project FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document).OfClass(typeof(Group)); FilteredElementIterator itr = collector.GetElementIterator(); //Gets the dictionary to lookup line getLines getlines = new getLines(path); var dictionary = getlines.DictionaryLines(); //iterators over all the groups while (itr.MoveNext()) { Element element = (Element)itr.Current; Group group = doc.GetElement(element.Id) as Group; List<ElementId> groupElements = group.GetMemberIds().ToList(); foreach (ElementId lineStyle in groupElements) { Element elements = doc.GetElement(lineStyle); CurveElement curveElement = elements as CurveElement; try { string lineStyleName = curveElement.LineStyle.Name; if (lineStyleName != null) { //compare lines to dictionary to ungroup. if (dictionary.ContainsKey(lineStyleName)) { ungroupList.Add(group); } } } catch { } } } foreach (Group group in ungroupList) { try { ungroup(doc, group); //CreateGroup(doc, uidoc); } catch { } } }
TrussGeometry trussGeometry; //TrussGeometry object store geometry info of Truss #endregion Fields #region Constructors /// <summary> /// constructor /// </summary> /// <param name="commandData">object which contains reference of Revit Application</param> public TrussForm(ExternalCommandData commandData) { m_commandData = commandData; m_activeDocument = m_commandData.Application.ActiveUIDocument; InitializeComponent(); m_trussTypes = new ArrayList(); //Get user selection if (!GetSelectTrussOrColumns()) { MessageBox.Show("Please select 1 existing truss or 2 columns before load this application."); this.Close(); } // get all the beam types, truss types and all the view plans from the active document DataInitialize(); }
/// <summary> /// Get all model and detail lines/arcs within selected elements /// </summary> /// <param name="document">Revit's document</param> /// <returns>ElementSet contains all model and detail lines/arcs within selected elements </returns> public static ElementSet GetSelectedModelLinesAndArcs(Document document) { UIDocument newUIdocument = new UIDocument(document); ElementSet elements = newUIdocument.Selection.Elements; ElementSet tmpSet = new ElementSet(); foreach (Autodesk.Revit.DB.Element element in elements) { if ((element is ModelLine) || (element is ModelArc) || (element is DetailLine) || (element is DetailArc)) { tmpSet.Insert(element); } } return tmpSet; }
/// <summary> /// Constructor with HostedSweep and CreationData as parameters. /// </summary> /// <param name="elem">Element to modify</param> /// <param name="creationData">CreationData</param> public ModificationData(HostedSweep elem, CreationData creationData) { m_rvtDoc = creationData.Creator.RvtDocument; m_rvtUIDoc = creationData.Creator.RvtUIDocument; m_elemToModify = elem; m_creationData = creationData; m_transaction = new Transaction(m_rvtDoc, "External Tool"); m_creationData.EdgeAdded += new CreationData.EdgeEventHandler(m_creationData_EdgeAdded); m_creationData.EdgeRemoved += new CreationData.EdgeEventHandler(m_creationData_EdgeRemoved); m_creationData.SymbolChanged += new CreationData.SymbolChangedEventHandler(m_creationData_SymbolChanged); }
/// <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 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) { try { _uiapp = commandData.Application; _uidoc = _uiapp.ActiveUIDocument; _doc = _uidoc.Document; BuildFamily(_doc); return Result.Succeeded; } catch (Exception ex) { message = ex.Message; return Result.Failed; } }
//second exercise put into a user interface public static void getCollection(Document doc, UIDocument uidoc) { //Creates a new stringbuilder Instance StringBuilder results = new StringBuilder(string.Empty); //Basic collection for walls ICollection<Element> elem = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements(); //foreach statement to get access to the data or elements foreach (Element e in elem) { //TaskDialog.Show("List of Instances", Name and e.Id.ToString() ); results.Append("Wall Name: " + e.Name + "- Id Number: " + e.Id.ToString() + "\n"); } //Dialog to show results TaskDialog.Show("List of Instances", results.ToString()); }
/// <summary> /// A ReferencePlaneMgr object constructor. /// </summary> /// <param name="commandData">The ExternalCommandData object for the active /// instance of Autodesk Revit.</param> public ReferencePlaneMgr(ExternalCommandData commandData) { Debug.Assert(null != commandData); m_document = commandData.Application.ActiveUIDocument; //Get an instance of this class from Application. Create m_options = commandData.Application.Application.Create.NewGeometryOptions(); //Set your preferences and pass it to Element.Geometry or Instance.Geometry. m_options.ComputeReferences = true; //m_options.DetailLevel = DetailLevels.Fine; m_options.View = m_document.Document.ActiveView; m_createHandler = new Dictionary<Type, CreateDelegate>(); m_createHandler.Add(typeof(Wall), new CreateDelegate(OperateWall)); m_createHandler.Add(typeof(Floor), new CreateDelegate(OperateSlab)); InitializeDataTable(); }
public SelectRunsForm(List<RunCollection> rcs, UIDocument _uiDoc) { runCollections = rcs; uiDoc = _uiDoc; InitializeComponent(); runNames = new List<string>(); for (int i = 0; i < runCollections.Count; i++) { string value = runCollections[i].NickName + " : " + runCollections[i].ComponentGuid.ToString(); runNames.Add(value); } // Setup the data. if (runCollections != null && runCollections.Count > 0) { guidComboBox.ItemsSource = runNames; //guidComboBox.DisplayMemberPath = "ComponentGuid"; guidComboBox.SelectedIndex = 0; } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { uiApp = commandData.Application; uiDoc = uiApp.ActiveUIDocument; app = uiApp.Application; doc = uiDoc.Document; CropBoxVisibility.setCropBoxVisibility(doc, false); } catch (Exception e) { TaskDialog.Show("Revit Quick Tools", e.Message); return Result.Failed; } return Result.Succeeded; }
/// <summary> /// The implementation of the FindSouthFacingWalls command. /// </summary> /// <param name="useProjectLocationNorth">true to use the active project location's north/south direction. /// false to use the default coordinate system's north/south (Y-axis).</param> protected void Execute(bool useProjectLocationNorth) { UIDocument uiDoc = new UIDocument(Document); Autodesk.Revit.UI.Selection.SelElementSet selElements = uiDoc.Selection.Elements; IEnumerable<Wall> walls = CollectExteriorWalls(); foreach (Wall wall in walls) { XYZ exteriorDirection = GetExteriorWallDirection(wall); if (useProjectLocationNorth) exteriorDirection = TransformByProjectLocation(exteriorDirection); bool isSouthFacing = IsSouthFacing(exteriorDirection); if (isSouthFacing) selElements.Insert(wall); } // Select all walls which had the proper direction. uiDoc.Selection.Elements = selElements; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uiDoc = commandData.Application.ActiveUIDocument; Document doc = uiDoc.Document; int boundcount = 0; List <Element> rooms = new FilteredElementCollector(doc, uiDoc.ActiveView.Id).OfCategory(BuiltInCategory.OST_Rooms).ToElements().ToList(); List <string> Lines = new List <string>(); foreach (Element e in rooms) { Room r = e as Room; var bounds = r.CollectBounds(); if (bounds.Count() > boundcount) { boundcount = bounds.Count(); } for (int i = 0; i < bounds.Count(); i++) { string result = "Y"; var b1 = bounds.GetBound(i - 2); var b2 = bounds.GetBound(i - 1); var b3 = bounds.GetBound(i); var b4 = bounds.GetBound(i + 1); var b5 = bounds.GetBound(i + 2); var D1 = b2.Direction(b3); var D2 = b3.Direction(b4); var D3 = b1.Direction(b2); var D4 = b4.Direction(b5); if (D1.AngleBetween(D2) < 0.0872665) { result = "N"; } if (D1.UnitLength() < 3) { if (D3.AngleBetween(D2) < 0.0872665) { result = "N"; } } if (D2.UnitLength() < 3) { if (D1.AngleBetween(D4) < 0.0872665) { result = "N"; } } string s = b1[0] + "," + b1[1] + "," + b1[2] + "," + b2[0] + "," + b2[1] + "," + b2[2] + "," + b3[0] + "," + b3[1] + "," + b3[2] + "," + b4[0] + "," + b4[1] + "," + b4[2] + "," + b5[0] + "," + b5[1] + "," + b5[2] + "," + result; Lines.Add(s); } } string fn = null; while (fn == null) { fn = Files.GetFile(); } TaskDialog.Show("Max Bounds", boundcount.ToString()); File.WriteAllLines(fn + "_Boundary.csv", Lines); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; FamilyFilter ff = new FamilyFilter(); IList <Reference> sel = uidoc.Selection.PickObjects(ObjectType.Element, ff); SiteLocation site = doc.SiteLocation; // Angles are in radians when coming from Revit API, so we // convert to degrees for display const double angleRatio = Math.PI / 180; // angle conversion factor // Get real-word coordinates of the building double projectLongitude = site.Longitude / angleRatio; double projectLatitude = site.Latitude / angleRatio; // Store the output data string pathLBeacon = doc.PathName.Remove(doc.PathName.Length - 4) + ".xml"; // Create a new list of LBeacons LBeacons = new List <LBeacon>(); foreach (Reference r in sel) { try { Element e = doc.GetElement(r); FamilyInstance fi = e as FamilyInstance; LocationPoint lp = fi.Location as LocationPoint; Level level = e.Document.GetElement(e.LevelId) as Level; // Create a new XYZ for Laser Pointer using in Revit coordinate system XYZ revitXYZ = new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z); // Create a new beacon and add it to the feature collection as a feature LBeacon beacon = new LBeacon(fi, revitXYZ, level); using (Transaction t = new Transaction(doc, "TextNote")) { t.Start("Create"); TextNote.Create(doc, uidoc.ActiveView.Id, revitXYZ, beacon.Mark, doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType)); t.Commit(); } // Translate the Revit coordinate to Real World coordinate Transform TrueNorthTransform = GetTrueNorthTransform(doc); XYZ TrueNorthCoordinates = TrueNorthTransform.OfPoint(lp.Point); // Convert feet to meter(Revit coordinate system unit is feet.) double xMeter = Utilities.feetToMeters(TrueNorthCoordinates.X); double yMeter = Utilities.feetToMeters(TrueNorthCoordinates.Y); double zMeter = Utilities.feetToMeters(TrueNorthCoordinates.Z); // Create new latitude/longitude double newLatitude = projectLatitude + Utilities.MeterToDecimalDegress(yMeter); double newLongitude = projectLongitude + Utilities.MeterToDecimalDegress(xMeter); // Create a new XYZ for LBeacon using in real-world map XYZ geoXYZ = new XYZ(newLongitude, newLatitude, zMeter); // Create a new beacon and add it to the feature collection as a feature LBeacons.Add(new LBeacon(fi, geoXYZ, level)); ReNameNeighbor(); LBeacons.Sort((x, y) => { return(x.ZLocation.CompareTo(y.ZLocation)); }); WriteXml(pathLBeacon, doc.Title); } catch (Exception e) { TaskDialog.Show("Revit", e.ToString()); } } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; List <Element> floors = new List <Element>(); if (!Util.GetSelectedElementsOrAll( floors, uidoc, typeof(Floor))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some floor elements." : "No floor elements found."; return(Result.Failed); } Options opt = app.Application.Create.NewGeometryOptions(); List <List <XYZ> > polygons = CmdSlabBoundary.GetFloorBoundaryPolygons( floors, opt); List <List <UV> > flat_polygons = Flatten(polygons); int i = 0, n = flat_polygons.Count; double[] areas = new double[n]; double a, maxArea = 0.0; foreach (List <UV> polygon in flat_polygons) { a = GetSignedPolygonArea(polygon); if (Math.Abs(maxArea) < Math.Abs(a)) { maxArea = a; } areas[i++] = a; } Debug.Print( "{0} boundary loop{1} found.", n, Util.PluralSuffix(n)); for (i = 0; i < n; ++i) { Debug.Print( " Loop {0} area is {1} square feet{2}", i, Util.RealString(areas[i]), (areas[i].Equals(maxArea) ? ", outer loop of largest floor slab" : "")); } using (Transaction t = new Transaction(doc)) { t.Start("Draw Polygons"); Creator creator = new Creator(doc); creator.DrawPolygons(polygons); t.Commit(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { if (null == _hWndRevit) { //Process[] processes // = Process.GetProcessesByName( "Revit" ); //if( 0 < processes.Length ) //{ // IntPtr h = processes[0].MainWindowHandle; // _hWndRevit = new WindowHandle( h ); //} Process process = Process.GetCurrentProcess(); IntPtr h = process.MainWindowHandle; _hWndRevit = new WindowHandle(h); } UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; using (CmdWindowHandleForm f = new CmdWindowHandleForm()) { f.Show(_hWndRevit); bool go = true; while (go) { //SelElementSet ss = sel.Elements; // 2014 //int n = ss.Size; ICollection <ElementId> ids = sel.GetElementIds(); // 2015 int n = ids.Count; string s = string.Format( "{0} element{1} selected{2}", n, Util.PluralSuffix(n), ((0 == n) ? ";\n" + _prompt : ":")); foreach (ElementId id in ids) { s += "\n"; s += Util.ElementDescription( doc.GetElement(id)); } f.LabelText = s; #if _2010 sel.StatusbarTip = _prompt; go = sel.PickOne(); #endif // _2010 Reference r = uidoc.Selection.PickObject( ObjectType.Element, _prompt); go = null != r; Debug.Print("go = " + go.ToString()); } } 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; // Filtering for Room elements throws an exception: // Input type is of an element type that exists in // the API, but not in Revit's native object model. // Try using Autodesk.Revit.DB.SpatialElement // instead, and then postprocessing the results to // find the elements of interest. //FilteredElementCollector a // = new FilteredElementCollector( doc ) // .OfClass( typeof( Room ) ); // Solution using SpatialElement and then // checking for Room type //FilteredElementCollector a // = new FilteredElementCollector( doc ) // .OfClass( typeof( SpatialElement ) ); //foreach( SpatialElement e in a ) //{ // Room room = e as Room; // if( null != room ) // { // ListRoomData( room ); // } //} // Improvement suggested by // Victor Chekalin using LINQ // http://thebuildingcoder.typepad.com/blog/2011/11/accessing-room-data.html // ?cid=6a00e553e168978833017c3690489f970b#comment-6a00e553e168978833017c3690489f970b // --> version 2013.0.100.2 //FilteredElementCollector collector // = new FilteredElementCollector( doc ); //var rooms = collector // .OfClass( typeof( SpatialElement ) ) // .OfType<Room>(); //FilteredElementCollector collector // = new FilteredElementCollector( doc ); //var rooms = collector // .OfClass( typeof( SpatialElement ) ) // .OfType<Room>(); FilteredElementCollector collector = new FilteredElementCollector(doc) .OfClass(typeof(SpatialElement)); IEnumerable <Element> rooms = collector .Where <Element>(e => e is Room); if (_exportCsv) { Debug.Print(_csv_headers); } foreach (Room room in rooms) { ListRoomData(room); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; ICollection <ElementId> ids = sel.GetElementIds(); Options opt = app.Application.Create.NewGeometryOptions(); Material mat; string msg = string.Empty; int i, n; foreach (ElementId id in ids) { Element e = doc.GetElement(id); // For 0310_ensure_material.htm: if (e is FamilyInstance) { mat = GetMaterial(doc, e as FamilyInstance); Util.InfoMsg( "Family instance element material: " + (null == mat ? "<null>" : mat.Name)); } GeometryElement geo = e.get_Geometry(opt); // If you are not interested in duplicate // materials, you can define a class that // overloads the Add method to only insert // a new entry if its value is not already // present in the list, instead of using // the standard List<> class: List <string> materials = GetMaterials(doc, geo); msg += "\n" + Util.ElementDescription(e); n = materials.Count; if (0 == n) { msg += " has no materials."; } else { i = 0; msg += string.Format( " has {0} material{1}:", n, Util.PluralSuffix(n)); foreach (string s in materials) { msg += string.Format( "\n {0} {1}", i++, s); } } } if (0 == msg.Length) { msg = "Please select some elements."; } Util.InfoMsg(msg); return(Result.Succeeded); }
///// <summary> ///// Allow selection of curve elements only. ///// </summary> //class CurveElementSelectionFilter : ISelectionFilter //{ // public bool AllowElement( Element e ) // { // return e is CurveElement; // } // public bool AllowReference( Reference r, XYZ p ) // { // 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; // Select all model curves in the entire model. List <CurveElement> curves = new List <CurveElement>( new FilteredElementCollector(doc) .OfClass(typeof(CurveElement)) .ToElements() .Cast <CurveElement>()); int n = curves.Count; // If there are less than two, // there is nothing we can do. if (2 > n) { message = _prompt; return(Result.Failed); } // If there are exactly two, pick those. if (2 < n) { // Else, check for a pre-selection. curves.Clear(); Selection sel = uidoc.Selection; ICollection <ElementId> ids = sel.GetElementIds(); n = ids.Count; Debug.Print("{0} pre-selected elements.", n); // If two or more model curves were pre- // selected, use the first two encountered. if (1 < n) { foreach (ElementId id in ids) { CurveElement c = doc.GetElement(id) as CurveElement; if (null != c) { curves.Add(c); if (2 == curves.Count) { Debug.Print("Found two model curves, " + "ignoring everything else."); break; } } } } // Else, prompt for an // interactive post-selection. if (2 != curves.Count) { curves.Clear(); ISelectionFilter f = new JtElementsOfClassSelectionFilter <CurveElement>(); try { Reference r = sel.PickObject( ObjectType.Element, f, "Please pick first model curve."); curves.Add(doc.GetElement(r.ElementId) as CurveElement); } catch (Autodesk.Revit.Exceptions .OperationCanceledException) { return(Result.Cancelled); } try { Reference r = sel.PickObject( ObjectType.Element, f, "Please pick second model curve."); curves.Add(doc.GetElement(r.ElementId) as CurveElement); } catch (Autodesk.Revit.Exceptions .OperationCanceledException) { return(Result.Cancelled); } } } // Extract data from the two selected curves. Curve c0 = curves[0].GeometryCurve; Curve c1 = curves[1].GeometryCurve; double sp0 = c0.GetEndParameter(0); double ep0 = c0.GetEndParameter(1); double step0 = (ep0 - sp0) / _nSegments; double sp1 = c1.GetEndParameter(0); double ep1 = c1.GetEndParameter(1); double step1 = (ep1 - sp1) / _nSegments; Debug.Print("Two curves' step size [start, end]:" + " {0} [{1},{2}] -- {3} [{4},{5}]", Util.RealString(step0), Util.RealString(sp0), Util.RealString(ep0), Util.RealString(step1), Util.RealString(sp1), Util.RealString(ep1)); // Modify document within a transaction. using (Transaction tx = new Transaction(doc)) { Creator creator = new Creator(doc); tx.Start("MidCurve"); // Current segment start points. double t0 = sp0; double t1 = sp1; XYZ p0 = c0.GetEndPoint(0); XYZ p1 = c1.GetEndPoint(0); XYZ p = Util.Midpoint(p0, p1); Debug.Assert( p0.IsAlmostEqualTo(c0.Evaluate(t0, false)), "expected equal start points"); Debug.Assert( p1.IsAlmostEqualTo(c1.Evaluate(t1, false)), "expected equal start points"); // Current segment end points. t0 += step0; t1 += step1; XYZ q0, q1, q; Line line; for (int i = 0; i < _nSegments; ++i, t0 += step0, t1 += step1) { q0 = c0.Evaluate(t0, false); q1 = c1.Evaluate(t1, false); q = Util.Midpoint(q0, q1); Debug.Print( "{0} {1} {2} {3}-{4} {5}-{6} {7}-{8}", i, Util.RealString(t0), Util.RealString(t1), Util.PointString(p0), Util.PointString(q0), Util.PointString(p1), Util.PointString(q1), Util.PointString(p), Util.PointString(q)); // Create approximating curve segment. line = Line.CreateBound(p, q); creator.CreateModelCurve(line); p0 = q0; p1 = q1; p = q; } tx.Commit(); } return(Result.Succeeded); }
public void Rebar_FromCurve_Top_Func(Element myBeam, List <Face> myListFacePicked, double divideFac, double coverBar, string myRebarShapeName, string myRebarTypeName) { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; //BoundingBox beam BoundingBoxXYZ myBoundBeam = myBeam.get_BoundingBox(null); double hBeam = myBoundBeam.Max.Z - myBoundBeam.Min.Z; LocationCurve myLocBeam = myBeam.Location as LocationCurve; Line myLocLine = myLocBeam.Curve as Line; XYZ p = myLocLine.GetEndPoint(0); XYZ q = myLocLine.GetEndPoint(1); XYZ v = q - p; XYZ pE = p - 0.5 * v; XYZ vE = q - pE; XYZ vRB = new XYZ(v.Y, -1 * v.X, v.Z); List <double> myListDisSortFace = getAndSortDisOfEndFaces(myListFacePicked, pE); double lengSeg_1 = myListDisSortFace[1] - myListDisSortFace[0]; double lengSeg_2 = myListDisSortFace[3] - myListDisSortFace[2]; XYZ ePR1_XY = pE + ((myListDisSortFace[1] - lengSeg_1 / divideFac) / vE.GetLength()) * vE; XYZ ePR2_XY = pE + ((myListDisSortFace[2] + lengSeg_2 / divideFac) / vE.GetLength()) * vE; XYZ ePR1 = new XYZ(ePR1_XY.X, ePR1_XY.Y, myBoundBeam.Max.Z - coverBar); XYZ ePR2 = new XYZ(ePR2_XY.X, ePR2_XY.Y, myBoundBeam.Max.Z - coverBar); Line curveOfRebar = Line.CreateBound(ePR1, ePR2); //Tang List <Curve> myShape = new List <Curve>() { curveOfRebar }; // RebarShape FilteredElementCollector fecRebarShape = new FilteredElementCollector(doc) .OfClass(typeof(RebarShape)); RebarShape myRebarShape = fecRebarShape.Cast <RebarShape>(). First <RebarShape>(myRebarShape2 => myRebarShape2.Name == myRebarShapeName); // Rebartype FilteredElementCollector fecRebarType = new FilteredElementCollector(doc) .OfClass(typeof(RebarBarType)); RebarBarType myRebarType = fecRebarType.Cast <RebarBarType>(). First <RebarBarType>(myRebarType2 => myRebarType2.Name == myRebarTypeName); // Hooktype FilteredElementCollector fec2 = new FilteredElementCollector(doc) .OfClass(typeof(RebarHookType)); IEnumerable <RebarHookType> iterRebarHookTypes = fec2.Cast <RebarHookType>(); RebarHookType myRebarHookType = iterRebarHookTypes.First(); using (Transaction trans = new Transaction(doc, "rebar test")) { trans.Start(); Rebar myRebar = Rebar.CreateFromCurves(doc, RebarStyle.Standard, myRebarType, null, null, myBeam, vRB, myShape, RebarHookOrientation.Left, RebarHookOrientation.Right, true, false); trans.Commit(); } }
// Select Faces boundaries public void rebarBeam_Top() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; double myConvertFactor = 304.8; //Load rebarShape // RebarShape FilteredElementCollector fecRebarShap = new FilteredElementCollector(doc) .OfClass(typeof(RebarShape)); IEnumerable <RebarShape> iterRebarBarShapes = fecRebarShap.Cast <RebarShape>(); // Load Rebar Type // Rebartype FilteredElementCollector fecBarType = new FilteredElementCollector(doc) .OfClass(typeof(RebarBarType)); IEnumerable <RebarBarType> iterRebarBarTypes = fecBarType.Cast <RebarBarType>(); // Top Layer // Layer1 bool isLB1Yes = true; double FB1 = 6; double CB1 = 80; string rebaNameShape_L1 = string.Empty; string rebaNameType_L1 = string.Empty; // Bottom Layer // Layer2 bool isLB2Yes = true; double FB2 = 3; double CB2 = 150; string rebaNameShape_L2 = string.Empty; string rebaNameType_L2 = string.Empty; bool inputSuccess = false; while (!inputSuccess) { using (var myInputFormSetting = new SettingDialog()) { //add rebar Shape list foreach (RebarShape myRebarShape in iterRebarBarShapes) { myInputFormSetting.RebarShap1Top_Cb.Items.Add(myRebarShape.Name); myInputFormSetting.RebarShap2Top_Cb.Items.Add(myRebarShape.Name); } //add rebar type list foreach (RebarBarType myRebarType in iterRebarBarTypes) { myInputFormSetting.RebarType1Top_Cb.Items.Add(myRebarType.Name); myInputFormSetting.RebarType2Top_Cb.Items.Add(myRebarType.Name); } myInputFormSetting.ShowDialog(); //Shape rebaNameShape_L1 = myInputFormSetting.RebarShap1Top_Cb.Text; rebaNameShape_L2 = myInputFormSetting.RebarShap2Top_Cb.Text; //type rebaNameType_L1 = myInputFormSetting.RebarType1Top_Cb.Text; rebaNameType_L2 = myInputFormSetting.RebarType2Top_Cb.Text; //Yes/ No bottom rebar if (!myInputFormSetting.yes1Top_Chb.Checked) { isLB1Yes = false; } if (!myInputFormSetting.yes2Top_Chb.Checked) { isLB2Yes = false; } // Layer1 FB1 = Convert.ToDouble(myInputFormSetting.FT1_Tb.Text); CB1 = Convert.ToDouble(myInputFormSetting.CT1_Tb.Text) / myConvertFactor; // Bottom Layer // Layer2 FB2 = Convert.ToDouble(myInputFormSetting.FT2_Tb.Text); CB2 = Convert.ToDouble(myInputFormSetting.CT2_Tb.Text) / myConvertFactor; if (myInputFormSetting.yes1Top_Chb.Checked == false && myInputFormSetting.yes2Top_Chb.Checked == false) { TaskDialog.Show("Warning!", "Tich vao Yes/No de bo tri it nhat 1 lop"); } else { //if the user hits cancel just drop out of macro if (myInputFormSetting.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return; } { //else do all this :) myInputFormSetting.Close(); } if (myInputFormSetting.DialogResult == System.Windows.Forms.DialogResult.OK) { //else do all this :) inputSuccess = true; myInputFormSetting.Close(); } } } } //Check mode // TaskDialog.Show("isL1", isLB1Yes.ToString()); // TaskDialog.Show("IsL2", isLB1Yes.ToString()); // // // // TaskDialog.Show("Rebar Shape1", rebaNameShape_L1); // TaskDialog.Show("Rebar Shape2", rebaNameShape_L2); // // // TaskDialog.Show("Rebar Shape1", rebaNameType_L1); // TaskDialog.Show("Rebar Shape2", rebaNameType_L2); List <int> myListIdCategoryRebar = new List <int>(); myListIdCategoryRebar.Add((int)BuiltInCategory.OST_StructuralFraming); Reference myRefmyBeam = uiDoc.Selection.PickObject(ObjectType.Element, new FilterByIdCategory(myListIdCategoryRebar), "Pick a Beam..."); Element myBeam = doc.GetElement(myRefmyBeam); //Get location curve of beam LocationCurve lc = myBeam.Location as LocationCurve; Line line = lc.Curve as Line; //Get vector of location cuver beam XYZ p = line.GetEndPoint(0); XYZ q = line.GetEndPoint(1); XYZ v = q - p; // Vector equation of line XYZ pE = p - 0.5 * v; XYZ vE = q - p; //Set current Beam be Joined setBeJoined(myBeam); while (true) { #region Pick faces //Pick Face end List <Reference> myListRef = uiDoc.Selection.PickObjects(ObjectType.Face) as List <Reference>; List <Face> myListFacePicked = new List <Face>(); foreach (Reference myRef in myListRef) { Element E = doc.GetElement(myRef); GeometryObject myGeoObj = E.GetGeometryObjectFromReference(myRef); Face myPickedFace = myGeoObj as Face; myListFacePicked.Add(myPickedFace); } #endregion #region Error picked faces if (myListFacePicked.Count != 4) { TaskDialog.Show("Error!", "Chua ho tro lua chon: " + myListFacePicked.Count() + " mat, Chon 4 mat"); continue; } #endregion else { string caseDistributionRebar = "Case 2: 4 Faces"; if (myListFacePicked.Count == 2) { caseDistributionRebar = "Case 1: 2 Faces"; } TaskDialog.Show("Info", caseDistributionRebar); if (isLB1Yes) { Rebar_FromCurve_Top_Func(myBeam, myListFacePicked, FB1, CB1, rebaNameShape_L1, rebaNameType_L1); } if (isLB2Yes) { Rebar_FromCurve_Top_Func(myBeam, myListFacePicked, FB2, CB2, rebaNameShape_L2, rebaNameType_L2); } } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; FilteredElementCollector col = new FilteredElementCollector(doc) .WhereElementIsNotElementType(); List <ElementId> ids = new List <ElementId>(); foreach (Element e in col) { if (ElementNameMayIndicateImageFileReference(e)) { Debug.Print(Util.ElementDescription(e)); ids.Add(e.Id); } } ICollection <ElementId> idsDeleted = null; Transaction t; int n = ids.Count; if (0 < n) { using (t = new Transaction(doc)) { t.Start("Delete non-ElementType '.jpg' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } int m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} non-ElementType element{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix(n), m)); col = new FilteredElementCollector(doc) .WhereElementIsElementType(); ids.Clear(); foreach (Element e in col) { if (ElementNameMayIndicateImageFileReference(e)) { Debug.Print(Util.ElementDescription(e)); ids.Add(e.Id); } } n = ids.Count; if (0 < n) { using (t = new Transaction(doc)) { t.Start("Delete element type '.jpg' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} element type{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix(n), m)); return(Result.Succeeded); }
internal static ILiveReloadAssetTracker <VisualTreeAsset> CreateVisualTreeAssetTrackerInstance(UIDocument owner) { return(new UIDocumentVisualTreeAssetTracker(owner)); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; //ElementSet ss = uidoc.Selection.Elements; // 2014 ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); Wall wall = null; if (0 < ids.Count) { // old pre-selection handling: // must be one single element only: if (1 != ids.Count) { message = "Please pre-select a single wall element."; return(Result.Failed); } // must be a wall: //ElementSetIterator it = ss.ForwardIterator(); //it.MoveNext(); //Element e = it.Current as Element; ElementId id = ids.First <ElementId>(); Element e = doc.GetElement(id); if (!(e is Wall)) { message = "Selected element is NOT a wall."; return(Result.Failed); } wall = e as Wall; } else { // new prompt for filtered selection allowing only walls: try { Reference r = uidoc.Selection.PickObject( ObjectType.Element, new WallSelectionFilter(), "Please pick a wall"); //wall = r.Element as Wall; // 2011 wall = uidoc.Document.GetElement(r) as Wall; // 2012 } catch (OperationCanceledException) { message = "Selection cancelled."; return(Result.Cancelled); } } // wall must be constrained to a level at the top (more on parameters later): Level topLev = null; try { ElementId id = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId(); topLev = doc.GetElement(id) as Level; } catch (Exception) { topLev = null; } if (null == topLev) { message = "Selected wall is not constrained to a level at the top."; return(Result.Failed); } // get the bottom level as well (this should never fail): Level botLev = null; try { ElementId id = wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId(); botLev = doc.GetElement(id) as Level; } catch (Exception) { botLev = null; } if (null == botLev) { message = "Selected wall is not constrained to a level at the bottom."; return(Result.Failed); } // Calculate the location points for the 3 columns (assuming straight wall) LocationCurve locCurve = wall.Location as LocationCurve; XYZ ptStart = locCurve.Curve.GetEndPoint(0); XYZ ptEnd = locCurve.Curve.GetEndPoint(1); XYZ ptMid = 0.5 * (ptStart + ptEnd); List <XYZ> locations = new List <XYZ>(3); locations.Add(ptStart); locations.Add(ptMid); locations.Add(ptEnd); string s = "{0} location{1} for the new columns in raw database coordinates, e.g. feet{2}"; List <string> a = new List <string>(); a.Add("Start: " + LabUtils.PointString(ptStart)); a.Add("Mid : " + LabUtils.PointString(ptMid)); a.Add("End : " + LabUtils.PointString(ptEnd)); LabUtils.InfoMsg(s, a); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfCategory(BuiltInCategory.OST_Columns); collector.OfClass(typeof(FamilySymbol)); #if SEARCH_FOR_SPECIFIC_NAME // retrieve the family type for the new instances. // if needed, change the names to match a column // type available in the model: string family_name = "M_Wood Timber Column"; string type_name = "191 x 292mm"; // LINQ query to find element with given name: // // ... note that this could also be achieved by // filtering for the element name parameter value. var column_types = from element in collector //where ((FamilySymbol)element).Family.Name == family_name where element.Name == type_name select element; FamilySymbol symbol = null; try { symbol = column_types.Cast <FamilySymbol>().First <FamilySymbol>(); } catch { } if (null == symbol) { message = string.Format( "Cannot find type '{0}' in family '{1}' in the current model - please load it first.", type_name, family_name); return(Result.Failed); } #endif // SEARCH_FOR_SPECIFIC_NAME FamilySymbol symbol = collector.Cast <FamilySymbol>().First <FamilySymbol>(); if (null == symbol) { message = "Cannot find a suitable column type."; return(Result.Failed); } // insert column family instances: foreach (XYZ p in locations) { try { // Note: Currently there is a problem. // If we set the type as NonStructural, it is treated as Annotation instance, // and it shows only in plan view. // FamilyInstance column = doc.Create.NewFamilyInstance( p, symbol, botLev, StructuralType.NonStuctural ); FamilyInstance column = doc.Create.NewFamilyInstance( p, symbol, botLev, StructuralType.Column); Parameter paramTopLevel = column.get_Parameter( BuiltInParameter.FAMILY_TOP_LEVEL_PARAM); ElementId id = topLev.Id; paramTopLevel.Set(id); } catch (Exception) { LabUtils.ErrorMsg("Failed to create or adjust column."); } } // Finally, move the wall so the columns are visible. // We move the wall perpendicularly to its location // curve by one tenth of its length: XYZ v = new XYZ( -0.1 * (ptEnd.Y - ptStart.Y), 0.1 * (ptEnd.X - ptStart.X), 0); if (!wall.Location.Move(v)) { LabUtils.ErrorMsg("Failed to move the wall."); } return(Result.Succeeded); }
public UseRequestMaker(UIDocument inputUIDoc) { useuiDoc = inputUIDoc; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Application app = commandData.Application.Application; Document doc = uidoc.Document; // Get the current shared params definition file DefinitionFile sharedParamsFile = GetSharedParamsFile(app); if (null == sharedParamsFile) { message = "Error getting the shared params file."; return(Result.Failed); } // Get or create the shared params group DefinitionGroup sharedParamsGroup = GetOrCreateSharedParamsGroup( sharedParamsFile, kSharedParamsGroupAPI); if (null == sharedParamsGroup) { message = "Error getting the shared params group."; return(Result.Failed); } Category cat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Doors); // Visibility of the new parameter: // Category.AllowsBoundParameters property indicates if a category can // have shared or project parameters. If it is false, it may not be bound // to shared parameters using the BindingMap. Please note that non-user-visible // parameters can still be bound to these categories. bool visible = cat.AllowsBoundParameters; // Get or create the shared params definition Definition fireRatingParamDef = GetOrCreateSharedParamsDefinition( sharedParamsGroup, ParameterType.Number, kSharedParamsDefFireRating, visible); if (null == fireRatingParamDef) { message = "Error in creating shared parameter."; return(Result.Failed); } // Create the category set for binding and add the category // we are interested in, doors or walls or whatever: CategorySet catSet = app.Create.NewCategorySet(); try { catSet.Insert(cat); } catch (Exception) { message = string.Format( "Error adding '{0}' category to parameters binding set.", cat.Name); return(Result.Failed); } using (Transaction transaction = new Transaction(doc)) { transaction.Start("Bind parameter"); // Bind the param try { Binding binding = app.Create.NewInstanceBinding(catSet); // We could check if already bound, but looks like Insert will just ignore it in such case doc.ParameterBindings.Insert(fireRatingParamDef, binding); transaction.Commit(); } catch (Exception ex) { message = ex.Message; transaction.RollBack(); return(Result.Failed); } } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Path of file string filePath = null; // Using Windows form to get file path using (Data form = new Data()) { OpenFileDialog browserDialog = new OpenFileDialog(); browserDialog.ShowDialog(); if (browserDialog.FileName != null) { filePath = browserDialog.FileName; } else { return(Result.Cancelled); } } // Get Dxf document DxfDocument document = DxfDocument.Load(filePath); // Get Revit UI document UIDocument uIDocument = commandData.Application.ActiveUIDocument; // Get Revit document Document rvtDocument = uIDocument.Document; //Get Level of revit file List <Level> levels = new FilteredElementCollector(rvtDocument) .OfCategory(BuiltInCategory.OST_Levels) .WhereElementIsNotElementType().Cast <Level>().ToList(); // Get Wall Type var wallType = new FilteredElementCollector(rvtDocument) .OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsElementType() .Cast <WallType>() .FirstOrDefault(); // Get Layers of dxf file List <Layer> layers = document.Layers.ToList(); // Declear variables string base_level_name = null; string top_level_name = null; string column_layer = null; string wall_layer = null; string floor_layer = null; // Get Data from user by form using (Data form = new Data()) { // Set dxf layers to comboBoxs form.ComboBox_wall_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray()); form.ComboBox_col_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray()); form.ComboBox_floor_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray()); // Set levels to ComboBoxs form.ComboBox_base_level.Items.AddRange(levels.Select(l => (object)l.Name).ToArray()); form.ComboBox_top_level.Items.AddRange(levels.Select(l => (object)l.Name).ToArray()); form.ShowDialog(); if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } else if (form.Button_ok.DialogResult == System.Windows.Forms.DialogResult.OK) { //Get Data from ComboBoxs base_level_name = form.ComboBox_base_level.SelectedItem.ToString(); top_level_name = form.ComboBox_top_level.SelectedItem.ToString(); wall_layer = form.ComboBox_wall_layer.SelectedItem.ToString(); column_layer = form.ComboBox_col_layer.SelectedItem.ToString(); floor_layer = form.ComboBox_floor_layer.SelectedItem.ToString(); } } // Get Data of vertix and its layer by sending document and layers Dxf_Vertices vertices = new Dxf_Vertices(document, column_layer, wall_layer, floor_layer); // Get Column Vertix Dxf_Column columns = new Dxf_Column(vertices); // Get Walls Vertix Dxf_Wall walls = new Dxf_Wall(vertices); // Get Floor Vertix Dxf_Floor floor = new Dxf_Floor(vertices); RVT_Col rVT_Col = new RVT_Col(columns.Points); RVT_Wall rVT_Wall = new RVT_Wall(walls.Walls_center); RVT_Floor rVT_Floor = new RVT_Floor(floor.Floor_boundary); Level base_level = GetLEVEL(rvtDocument, base_level_name); Level top_level = GetLEVEL(rvtDocument, top_level_name); FamilySymbol symbol; using (Transaction t = new Transaction(rvtDocument, "Load")) { t.Start(); bool ff = rvtDocument.LoadFamily($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\Concrete-Rectangular-Column.rfa"); symbol = new FilteredElementCollector(rvtDocument).OfClass(typeof(FamilySymbol)) .WhereElementIsElementType() .Cast <FamilySymbol>() .First(x => x.Name == "12 x 18"); symbol.Activate(); t.Commit(); } using (Transaction t = new Transaction(rvtDocument, "Create ")) { t.Start(); WallType newWallType = CreateWallType(rvtDocument, wallType, 300); rVT_Col.CreateColumns(rvtDocument, symbol, base_level, top_level); rVT_Wall.CreateWalls(rvtDocument, newWallType, base_level, top_level); rVT_Floor.CreateFloor(rvtDocument, top_level); t.Commit(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uiDoc = commandData.Application.ActiveUIDocument; Application app = commandData.Application.Application; Document doc = uiDoc.Document; using (Transaction transaction = new Transaction(doc)) { transaction.Start("PerDocParameter"); // get the current shared params definition file DefinitionFile sharedParamsFile = SharedParameter.GetSharedParamsFile(app); if (null == sharedParamsFile) { TaskDialog.Show("Per document parameter", "Error getting the shared params file."); return(Result.Failed); } // get or create the shared params group DefinitionGroup sharedParamsGroup = SharedParameter.GetOrCreateSharedParamsGroup(sharedParamsFile, kParamGroupName); if (null == sharedParamsGroup) { TaskDialog.Show("Per document parameter", "Error getting the shared params group."); return(Result.Failed); } // visible param Definition docParamDefVisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Integer, kParamNameVisible, true); if (null == docParamDefVisible) { TaskDialog.Show("Per document parameter", "Error creating visible per-doc parameter."); return(Result.Failed); } // invisible param Definition docParamDefInvisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Integer, kParamNameInvisible, false); if (null == docParamDefInvisible) { TaskDialog.Show("Per document parameter", "Error creating invisible per-doc parameter."); return(Result.Failed); } // bind the param try { CategorySet catSet = app.Create.NewCategorySet(); catSet.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_ProjectInformation)); Binding binding = app.Create.NewInstanceBinding(catSet); doc.ParameterBindings.Insert(docParamDefVisible, binding); doc.ParameterBindings.Insert(docParamDefInvisible, binding); } catch (Exception e) { TaskDialog.Show("Per document parameter", "Error binding shared parameter: " + e.Message); return(Result.Failed); } // set the initial values // get the singleton project info element Element projInfoElem = GetProjectInfoElem(doc); if (null == projInfoElem) { TaskDialog.Show("Per document parameter", "No project info elem found. Aborting command..."); return(Result.Failed); } // for simplicity, access params by name rather than by GUID: //projInfoElem.get_Parameter(kParamNameVisible).Set(55); //projInfoElem.get_Parameter(kParamNameInvisible).Set(0); // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete: // 'This property is obsolete in Revit 2015, as more than one parameter can have the same name on a given element. // Use Element.Parameters to obtain a complete list of parameters on this Element, // or Element.GetParameters(String) to get a list of all parameters by name, // or Element.LookupParameter(String) to return the first available parameter with the given name. // modified code for Revit 2015 projInfoElem.LookupParameter(kParamNameVisible).Set(55); projInfoElem.LookupParameter(kParamNameVisible).Set(0); transaction.Commit(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; // Retrieve selected floors, or all floors, if nothing is selected: List <Element> floors = new List <Element>(); if (!Util.GetSelectedElementsOrAll( floors, uidoc, typeof(Floor))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some floor elements." : "No floor elements found."; return(Result.Failed); } // Determine top face of each selected floor: int nNullFaces = 0; List <Face> topFaces = new List <Face>(); Options opt = app.Application.Create.NewGeometryOptions(); foreach (Floor floor in floors) { GeometryElement geo = floor.get_Geometry(opt); //GeometryObjectArray objects = geo.Objects; // 2012 foreach (GeometryObject obj in geo) { Solid solid = obj as Solid; if (solid != null) { PlanarFace f = GetTopFace(solid); if (null == f) { Debug.WriteLine( Util.ElementDescription(floor) + " has no top face."); ++nNullFaces; } topFaces.Add(f); } } } using (Transaction t = new Transaction(doc)) { t.Start("Create Model Lines and Floor"); // Create new floors from the top faces found. // Before creating the new floor, we would obviously // apply whatever modifications are required to the // new floor profile: Autodesk.Revit.Creation.Application creApp = app.Application.Create; Autodesk.Revit.Creation.Document creDoc = doc.Create; int i = 0; int n = topFaces.Count - nNullFaces; Debug.Print( "{0} top face{1} found.", n, Util.PluralSuffix(n)); foreach (Face f in topFaces) { Floor floor = floors[i++] as Floor; if (null != f) { EdgeArrayArray eaa = f.EdgeLoops; CurveArray profile; #region Attempt to include inner loops #if ATTEMPT_TO_INCLUDE_INNER_LOOPS bool use_original_loops = true; if (use_original_loops) { profile = Convert(eaa); } else #endif // ATTEMPT_TO_INCLUDE_INNER_LOOPS #endregion // Attempt to include inner loops { profile = new CurveArray(); // Only use first edge array, // the outer boundary loop, // skip the further items // representing holes: EdgeArray ea = eaa.get_Item(0); foreach (Edge e in ea) { IList <XYZ> pts = e.Tessellate(); int m = pts.Count; XYZ p = pts[0]; XYZ q = pts[m - 1]; Line line = Line.CreateBound(p, q); profile.Append(line); } } //Level level = floor.Level; // 2013 Level level = doc.GetElement(floor.LevelId) as Level; // 2014 // In this case we have a valid floor type given. // In general, not that NewFloor will only accept // floor types whose IsFoundationSlab predicate // is false. floor = creDoc.NewFloor(profile, floor.FloorType, level, true); XYZ v = new XYZ(5, 5, 0); //doc.Move( floor, v ); // 2011 ElementTransformUtils.MoveElement(doc, floor.Id, v); // 2012 } } t.Commit(); } return(Result.Succeeded); }
public Autodesk.Revit.UI.Result Execute( ExternalCommandData revit, ref string message, ElementSet elements) { try { // Get the active document and view UIDocument revitDoc = revit.Application.ActiveUIDocument; Autodesk.Revit.DB.View view = revitDoc.Document.ActiveView; foreach (Autodesk.Revit.DB.ElementId elemId in revitDoc.Selection.GetElementIds()) { //if( elem.GetType() == typeof( Autodesk.Revit.DB.Structure.Rebar ) ) Autodesk.Revit.DB.Element elem = revitDoc.Document.GetElement(elemId); if (elem is Rebar) { string str = ""; Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem; ParameterSet pars = rebar.Parameters; foreach (Parameter param in pars) { string val = ""; string name = param.Definition.Name; Autodesk.Revit.DB.StorageType type = param.StorageType; switch (type) { case Autodesk.Revit.DB.StorageType.Double: val = param.AsDouble().ToString(); break; case Autodesk.Revit.DB.StorageType.ElementId: Autodesk.Revit.DB.ElementId id = param.AsElementId(); Autodesk.Revit.DB.Element paraElem = revitDoc.Document.GetElement(id); if (paraElem != null) { val = paraElem.Name; } break; case Autodesk.Revit.DB.StorageType.Integer: val = param.AsInteger().ToString(); break; case Autodesk.Revit.DB.StorageType.String: val = param.AsString(); break; default: break; } str = str + name + ": " + val + "\r\n"; } TaskDialog.Show("Rebar parameters", str); return(Autodesk.Revit.UI.Result.Succeeded); } } message = "No rebar selected!"; return(Autodesk.Revit.UI.Result.Failed); } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } }
//<summary> //Generate a VisualizationInfo of the current view //</summary> //<returns></returns> public static VisualizationInfo GenerateViewpoint(UIDocument uidoc) { try { var doc = uidoc.Document; var v = new VisualizationInfo(); //Corners of the active UI view var topLeft = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0]; var bottomRight = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1]; //It's a 2D view //not supported by BCF, but I store it under a custom //fields using 2D coordinates and sheet id if (uidoc.ActiveView.ViewType != ViewType.ThreeD) { v.SheetCamera = new SheetCamera { SheetID = uidoc.ActiveView.Id.IntegerValue, TopLeft = new Point { X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z }, BottomRight = new Point { X = bottomRight.X, Y = bottomRight.Y, Z = bottomRight.Z } }; } //It's a 3d view else { var viewCenter = new XYZ(); var view3D = (View3D)uidoc.ActiveView; double zoomValue = 1; // it is a orthogonal view if (!view3D.IsPerspective) { double x = (topLeft.X + bottomRight.X) / 2; double y = (topLeft.Y + bottomRight.Y) / 2; double z = (topLeft.Z + bottomRight.Z) / 2; //center of the UI view viewCenter = new XYZ(x, y, z); //vector going from BR to TL XYZ diagVector = topLeft.Subtract(bottomRight); //length of the vector double dist = topLeft.DistanceTo(bottomRight) / 2; //ViewToWorldScale value zoomValue = dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)).ToMeters(); // **** CUSTOM VALUE FOR TEKLA **** // // calculated experimentally, not sure why but it works //if (UserSettings.Get("optTekla") == "1") // zoomValue = zoomValue * 2.5; // **** CUSTOM VALUE FOR TEKLA **** // ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false); XYZ c = t.EyePosition; XYZ vi = t.ForwardDirection; XYZ up = t.UpDirection; v.OrthogonalCamera = new OrthogonalCamera { CameraViewPoint = { X = c.X.ToMeters(), Y = c.Y.ToMeters(), Z = c.Z.ToMeters() }, CameraUpVector = { X = up.X.ToMeters(), Y = up.Y.ToMeters(), Z = up.Z.ToMeters() }, CameraDirection = { X = vi.X.ToMeters() * -1, Y = vi.Y.ToMeters() * -1, Z = vi.Z.ToMeters() * -1 }, ViewToWorldScale = zoomValue }; } // it is a perspective view else { viewCenter = uidoc.ActiveView.Origin; //revit default value zoomValue = 45; ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false); XYZ c = t.EyePosition; XYZ vi = t.ForwardDirection; XYZ up = t.UpDirection; v.PerspectiveCamera = new PerspectiveCamera { CameraViewPoint = { X = c.X.ToMeters(), Y = c.Y.ToMeters(), Z = c.Z.ToMeters() }, CameraUpVector = { X = up.X.ToMeters(), Y = up.Y.ToMeters(), Z = up.Z.ToMeters() }, CameraDirection = { X = vi.X.ToMeters() * -1, Y = vi.Y.ToMeters() * -1, Z = vi.Z.ToMeters() * -1 }, FieldOfView = zoomValue }; } } //COMPONENTS PART string versionName = doc.Application.VersionName; v.Components = new Components(); var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .ToElementIds(); var hiddenElems = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsHidden(doc.ActiveView) || !doc.ActiveView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, x.Id)).Select(x => x.Id) ;//would need to check how much this is affecting performance var selectedElems = uidoc.Selection.GetElementIds(); v.Components = new Components(); v.Components.Visibility = new ComponentVisibility(); //TODO: set ViewSetupHints //TODO: create clipping planes //list of hidden components is smaller than the list of visible components if (visibleElems.Count() > hiddenElems.Count()) { v.Components.Visibility.DefaultVisibility = true; v.Components.Visibility.DefaultVisibilitySpecified = true; v.Components.Visibility.Exceptions = hiddenElems.Select(x => new Component { OriginatingSystem = versionName, IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, x)), AuthoringToolId = x.IntegerValue.ToString() }).ToArray(); } //list of visible components is smaller or equals the list of hidden components else { v.Components.Visibility.DefaultVisibility = false; v.Components.Visibility.DefaultVisibilitySpecified = true; v.Components.Visibility.Exceptions = visibleElems.Select(x => new Component { OriginatingSystem = versionName, IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, x)), AuthoringToolId = x.IntegerValue.ToString() }).ToArray(); } //selected elements v.Components.Selection = selectedElems.Select(x => new Component { OriginatingSystem = versionName, IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, x)), AuthoringToolId = x.IntegerValue.ToString() }).ToArray(); return(v); } catch (System.Exception ex1) { TaskDialog.Show("Error generating viewpoint", "exception: " + ex1); } return(null); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Add an EventLogTraceListener object System.Diagnostics.Trace.Listeners.Add( new System.Diagnostics.EventLogTraceListener("Application")); // Lay the hands on the active document UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; // Set up a timer Timing myTimer = new Timing(); myTimer.StartTime(); StringBuilder strBld = new StringBuilder(); // Make some preparations List <ElementId> selectedElemIds = new List <ElementId>(); EnumValuesWnd wnd = null; try { if (doc.ActiveView.ViewType != ViewType.Schedule) { TaskDialog.Show("Exception", "Open a schedule view before running this command."); return(Result.Failed); } else if (uidoc.Selection.GetElementIds().Count == 0) { TaskDialog.Show("Exception", "No element has been picked out."); return(Result.Failed); } selectedElemIds = uidoc.Selection.GetElementIds().ToList(); ViewSchedule scheduleView = doc.ActiveView as ViewSchedule; ScheduleDefinition scheduleDefinition = scheduleView.Definition; bool sorted = scheduleDefinition.GetSortGroupFieldCount() > 0 ? true : false; List <TmpObject> tmpObjs = new List <TmpObject>(); for (int i = 0; i < selectedElemIds.Count; ++i) { Element elem = doc.GetElement(selectedElemIds[i]); TmpObject tmp = new TmpObject(elem.Id); for (int j = 0; j < scheduleDefinition.GetSortGroupFieldCount(); ++j) { ScheduleSortGroupField srtGrpField = scheduleDefinition.GetSortGroupField(j); ScheduleField schField = scheduleDefinition.GetField(srtGrpField.FieldId); Parameter p = GetScheduleFieldParameter(schField, elem); if (p != null) { tmp.AddParameter(p); } } tmpObjs.Add(tmp); } // Sort the elements by a series of parameters tmpObjs.Sort(); // Create the window and subscribe to its event IList <string> parameterNames = doc.GetElement(selectedElemIds[0]) .GetOrderedParameters() .Where(p => p.StorageType == StorageType.String && !p.IsReadOnly) .Select(p => p.Definition.Name) .ToList(); wnd = new EnumValuesWnd(parameterNames); wnd.OkClicked += (sender, args) => { using (Transaction t = new Transaction(doc)) { t.Start("Enumerate parameters"); // Deal with the first element TmpObject prevObj = tmpObjs[0]; doc.GetElement(prevObj.Id).LookupParameter(args.ParameterName).Set( string.Format("{0}{1}{2}", args.Prefix, args.Position, args.Suffix)); int position = args.Position; // See about the other elements in the list for (int i = 1; i < tmpObjs.Count; ++i) { TmpObject curObj = tmpObjs[i]; Element e = doc.GetElement(curObj.Id); if (curObj.CompareTo(prevObj) == 0 && sorted) { e.LookupParameter(args.ParameterName).Set( string.Format("{0}{1}{2}", args.Prefix, position, args.Suffix)); } else { ++position; e.LookupParameter(args.ParameterName).Set( string.Format("{0}{1}{2}", args.Prefix, position, args.Suffix)); } prevObj = curObj; } t.Commit(); } }; // Show the window wnd.ShowDialog(); return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { TaskDialog.Show("Exception", string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); System.Diagnostics.Trace.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } finally { wnd.Close(); myTimer.StopTime(); System.Diagnostics.Trace .Write(string.Format("Time elapsed: {0}s", myTimer.Duration.TotalSeconds)); } }
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; Selection SelectedObjs = uidoc.Selection; ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); Line dimDirCross = null; Line dimDir = null; int selectdim = 0; bool updateMode = false; ElementArray dimensions = new ElementArray(); ReferenceArray dimto = new ReferenceArray(); GetMenuValues(uiapp); foreach (ElementId eid in ids) { if (doc.GetElement(eid).GetType() == typeof(Grid)) { Grid grid = doc.GetElement(eid) as Grid; dimto.Append(new Reference(grid)); } else if (doc.GetElement(eid).GetType() == typeof(Dimension)) { updateMode = true; dimensions.Append(doc.GetElement(eid)); } else { GeometryElement geom = doc.GetElement(eid).get_Geometry(Store.Dimop(doc.ActiveView)); Line refLine = GetLineOfGeom(geom); if (selectdim == 0) { dimDir = Line.CreateBound(refLine.GetEndPoint(0), refLine.GetEndPoint(1)); dimDirCross = RackDim.GetPerpendicular(dimDir, Store.mod_place); selectdim = 1; } dimto.Append(refLine.Reference); } } if (updateMode) { foreach (Element elem in dimensions) { selectdim = 0; Dimension dim = elem as Dimension; ReferenceArray updatedref = new ReferenceArray(); foreach (Reference refe in dim.References) { if (doc.GetElement(refe.ElementId).GetType() == typeof(Grid)) { Grid grid = doc.GetElement(refe.ElementId) as Grid; updatedref.Append(new Reference(grid)); } else { GeometryElement geom = doc.GetElement(refe.ElementId).get_Geometry(Store.Dimop(doc.ActiveView)); Line refLine = GetLineOfGeom(geom); if (selectdim == 0) { dimDir = Line.CreateBound(refLine.GetEndPoint(0), refLine.GetEndPoint(1)); dimDirCross = RackDim.GetPerpendicular(dimDir, Store.mod_place); selectdim = 1; } updatedref.Append(refLine.Reference); } } RackDim.CreateRackDim(doc, uiapp, dimDir, dimDirCross, updatedref); using (Transaction deltrans = new Transaction(doc)) { deltrans.Start("Update Dimension"); doc.Delete(elem.Id); deltrans.Commit(); } } } else { RackDim.CreateRackDim(doc, uiapp, dimDir, dimDirCross, dimto); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Element e = Util.SelectSingleElement( uidoc, "an element"); if (null == e) { message = "No element selected"; return(Result.Failed); } // Trying to call this property returns the // compile time error: Property, indexer, or // event 'BoundingBox' is not supported by // the language; try directly calling // accessor method 'get_BoundingBox( View )' //BoundingBoxXYZ b = e.BoundingBox[null]; View v = null; BoundingBoxXYZ b = e.get_BoundingBox(v); if (null == b) { v = commandData.View; b = e.get_BoundingBox(v); } if (null == b) { Util.InfoMsg( Util.ElementDescription(e) + " has no bounding box."); } else { using (Transaction tx = new Transaction(doc)) { tx.Start("Draw Model Line Bounding Box Outline"); Debug.Assert(b.Transform.IsIdentity, "expected identity bounding box transform"); string in_view = (null == v) ? "model space" : "view " + v.Name; Util.InfoMsg(string.Format( "Element bounding box of {0} in " + "{1} extends from {2} to {3}.", Util.ElementDescription(e), in_view, Util.PointString(b.Min), Util.PointString(b.Max))); Creator creator = new Creator(doc); creator.DrawPolygon(new List <XYZ>( Util.GetBottomCorners(b))); Transform rotation = Transform.CreateRotation( XYZ.BasisZ, 60 * Math.PI / 180.0); b = RotateBoundingBox(b, rotation); Util.InfoMsg(string.Format( "Bounding box rotated by 60 degrees " + "extends from {0} to {1}.", Util.PointString(b.Min), Util.PointString(b.Max))); creator.DrawPolygon(new List <XYZ>( Util.GetBottomCorners(b))); tx.Commit(); } } return(Result.Succeeded); }
//Not working? Is this any good? 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; Selection SelectedObjs = uidoc.Selection; ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); Line dimLine = null; List <XYZ> dimpos = new List <XYZ>(); List <Dimension> dimlist = new List <Dimension>(); ReferenceArray updatedref = new ReferenceArray(); ReferenceArray cleanref = new ReferenceArray(); RackDim.GetMenuValues(uiapp); foreach (ElementId eid in ids) { Element elem = doc.GetElement(eid); if (elem.GetType() == typeof(Dimension)) { Dimension dim = elem as Dimension; dimlist.Add(dim); if (dimLine == null) { dimLine = dim.Curve as Line; } foreach (Reference refe in dim.References) { if (doc.GetElement(refe.ElementId).GetType() == typeof(Grid)) { Grid grid = doc.GetElement(refe.ElementId) as Grid; Reference refgrid = new Reference(grid); updatedref.Append(refgrid); } else { GeometryElement geom = doc.GetElement(refe.ElementId).get_Geometry(Store.Dimop(doc.ActiveView)); Line refLine = RackDim.GetLineOfGeom(geom); updatedref.Append(refLine.Reference); } } } } List <Dimension> dimsort = dimlist.OrderBy(o => o.Origin.X).ToList(); foreach (Dimension dim in dimsort) { foreach (DimensionSegment dimSeg in dim.Segments) { dimpos.Add(dimSeg.LeaderEndPosition); } } using (Transaction trans = new Transaction(doc)) { trans.Start("Unite Dimensions"); Dimension newDim = doc.Create.NewDimension(doc.ActiveView, dimLine, updatedref); int segCount = 0; foreach (DimensionSegment segment in newDim.Segments) { bool once = true; foreach (Reference upref in updatedref) { if (once && newDim.References.get_Item(segCount).ElementId == upref.ElementId) { cleanref.Append(upref); once = false; } } if (segment.Value == 0) { segCount += 1; } segCount += 1; } doc.Delete(newDim.Id); newDim = doc.Create.NewDimension(doc.ActiveView, dimLine, cleanref); int iter = 0; foreach (DimensionSegment seg in newDim.Segments) { if (iter < newDim.Segments.Size - 1) { seg.LeaderEndPosition = dimpos[iter]; iter += 1; } } trans.Commit(); } return(Result.Succeeded); }
// In Revit API discussion forum thread // https://forums.autodesk.com/t5/revit-api-forum/outer-loops-of-planar-face-with-separate-parts/m-p/7461348 public Result GetPlanarFaceOuterLoops( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication IntApp = commandData.Application; UIDocument IntUIDoc = IntApp.ActiveUIDocument; if (IntUIDoc == null) { return(Result.Failed); } Document IntDoc = IntUIDoc.Document; Reference R = null; try { R = IntUIDoc.Selection.PickObject(ObjectType.Face); } catch { } if (R == null) { return(Result.Cancelled); } Element F_El = IntDoc.GetElement(R.ElementId); if (F_El == null) { return(Result.Failed); } PlanarFace F = F_El.GetGeometryObjectFromReference(R) as PlanarFace; if (F == null) { return(Result.Failed); } //Create individual CurveLoops to compare from // the orginal CurveLoopArray //If floor has separate parts these will now be // separated out into individual faces rather // than one face with multiple loops. List <Tuple <PlanarFace, CurveLoop, int> > CLoop = new List <Tuple <PlanarFace, CurveLoop, int> >(); int Ix = 0; foreach (CurveLoop item in F.GetEdgesAsCurveLoops()) { List <CurveLoop> CLL = new List <CurveLoop>(); CLL.Add(item); //Create a solid extrusion for each CurveLoop // ( we want to get the planarFace from this // to use built in functionality (.PlanarFace.IsInside). //Would be nice if you could skip this step and // create PlanarFaces directly from CuveLoops? // Does not appear to be possible, I only looked // in GeometryCreationUtilities. //Below creates geometry in memory rather than // actual geometry in the document, therefore // no transaction required. Solid S = GeometryCreationUtilities .CreateExtrusionGeometry(CLL, F.FaceNormal, 1); foreach (Face Fx in S.Faces) { PlanarFace PFx = Fx as PlanarFace; if (PFx == null) { continue; } if (PFx.FaceNormal.IsAlmostEqualTo( F.FaceNormal)) { Ix += 1; CLoop.Add(new Tuple <PlanarFace, CurveLoop, int>(PFx, item, Ix)); } } } List <CurveLoop> OuterLoops = new List <CurveLoop>(); //If there is more than one outerloop we know the // original face has separate parts. //We could therefore stop the creation of floors // with separate parts via posting failures etc. // or more passively create a geometry checking // utility to identify them. List <CurveLoop> InnerLoops = new List <CurveLoop>(); foreach (Tuple <PlanarFace, CurveLoop, int> item in CLoop) { //To identify an inner loop we just need to see // if any of it's points are inside another face. //The exception to this is a loop compared to the // face it was taken from. This will also be // considered inside as the points are on the boundary. //Therefore give each item an integer ID to ensure // it isn't self comparing. An alternative would // be to look for J=1 instead of J=0 below (perhaps). int J = CLoop.ToList().FindAll(z => FirstPointIsInsideFace(item.Item2, z.Item1) == true && z.Item3 != item.Item3).Count; if (J == 0) { OuterLoops.Add(item.Item2); } else { InnerLoops.Add(item.Item2); } } using (Transaction Tx = new Transaction(IntDoc, "Outer loops")) { if (Tx.Start() == TransactionStatus.Started) { SketchPlane SKP = SketchPlane.Create(IntDoc, Plane.CreateByThreePoints(F.Origin, F.Origin + F.XVector, F.Origin + F.YVector)); foreach (CurveLoop Crv in OuterLoops) { foreach (Curve C in Crv) { IntDoc.Create.NewModelCurve(C, SKP); } } Tx.Commit(); } } return(Result.Succeeded); }
public Result Execute2( ExternalCommandData commandData, ref string message, ElementSet elements, bool delViews, bool delSheets) { // Get application and document objects UIApplication uiApp = commandData.Application; Document doc = uiApp.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; try { using (Transaction trans = new Transaction(doc, "UpperCase Views on Sheets.")) { // Get All Elements to delete List <Element> delElements = new List <Element>(); if (delViews == true) { // add views IList <Element> views = GetViewsToDelete(doc); foreach (Element e in views) { delElements.Add(e); } } if (delSheets == true) { // add sheets IList <Element> sheets = GetSheetsToDelete(doc); foreach (Element e in sheets) { delElements.Add(e); } } // Delete Elements based on input delElements int n = delElements.Count; string s = "{0} of " + n.ToString() + " Sheets/Views processed..."; string caption = "Delete All Views/Sheets"; using (ProgressForm pf = new ProgressForm(caption, s, n)) { foreach (Element e in delElements) { try { doc.Delete(e.Id); } catch (Exception x) { message = x.Message; } pf.Increment(); } } trans.Commit(); } return(Result.Succeeded); } // Catch any Exceptions and display them. catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception x) { message = x.Message; return(Result.Failed); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Wall wall = Util.SelectSingleElementOfType( uidoc, typeof(Wall), "a wall", false) as Wall; if (null == wall) { message = "Please select a single wall element."; return(Result.Failed); } ICollection <ElementId> delIds = null; using (Transaction t = new Transaction(doc)) { try { t.Start("Temporary Wall Deletion"); delIds = doc.Delete(wall.Id); t.RollBack(); } catch (Exception ex) { message = "Deletion failed: " + ex.Message; t.RollBack(); } } ContFooting footing = null; foreach (ElementId id in delIds) { footing = doc.GetElement(id) as ContFooting; if (null != footing) { break; } } string s = Util.ElementDescription(wall); Util.InfoMsg((null == footing) ? string.Format("No footing found for {0}.", s) : string.Format("{0} has {1}.", s, Util.ElementDescription(footing))); 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; Selection SelectedObjs = uidoc.Selection; ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); ElementId defTextType = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); List <double> cDiams = new List <double>(); Line LineDir = null; bool updateRack = false; List <string> Conduits = new List <string>(); TextNote toUpdate = null; RackDim.GetMenuValues(uiapp); Store.mod_split = 30; foreach (ElementId eid in ids) { Element elem = doc.GetElement(eid); if (elem.GetType() == typeof(TextNote)) { updateRack = true; toUpdate = elem as TextNote; } else { GeometryElement geom = elem.get_Geometry(Store.Dimop(doc.ActiveView)); cDiams.Add(elem.get_Parameter(BuiltInParameter.RBS_CONDUIT_DIAMETER_PARAM).AsDouble()); LineDir = RackDim.GetLineOfGeom(geom); } } if (toUpdate != null) { ids.Remove(toUpdate.Id); } double dMax = cDiams.Max(); foreach (string s in Conduits) { TaskDialog.Show("asd", s); } using (Transaction tx = new Transaction(doc)) { tx.Start("Create Text"); List <ElementId> Rows = new List <ElementId>(); List <List <ElementId> > allRows = SeparateRows(ids, doc, dMax); string diameters = ""; Double Distance = 0; List <double> leftXs = new List <double>(); List <ElementId> lefts = new List <ElementId>(); List <double> rightXs = new List <double>(); List <ElementId> rights = new List <ElementId>(); foreach (int i in SortRows(allRows, doc)) { string prev = ""; int typcount = 1; string diam; if (i == 0 && allRows.Count > 1) { diameters += "ABOVE: "; } else if (i == allRows.Count - 1 && allRows.Count != 1) { diameters += '\n' + "BELOW: "; } else if (allRows.Count > 1) { diameters += '\n' + "MIDDLE: "; } List <ElementId> SortedRows = SortX(allRows[i], doc); leftXs.Add(RackDim.GetRotatedToVert(SortedRows[0], doc).GetEndPoint(0).X); lefts.Add(SortedRows[0]); rightXs.Add(RackDim.GetRotatedToVert(SortedRows[SortedRows.Count - 1], doc).GetEndPoint(0).X); rights.Add(SortedRows[SortedRows.Count - 1]); foreach (ElementId eid in SortedRows) { diam = doc.GetElement(eid).get_Parameter(BuiltInParameter.RBS_CONDUIT_DIAMETER_PARAM).AsValueString(); if (diam == prev) { typcount += 1; } else { if (typcount != 1) { diameters = diameters + typcount + "-" + prev + "C, "; diameters = BreakLine(diameters, Store.mod_split); typcount = 1; } else if (prev != "") { diameters = diameters + prev + "C, "; diameters = BreakLine(diameters, Store.mod_split); } prev = diam; } } if (typcount != 1) { diameters = diameters + typcount + "-" + prev + "C"; } else { diameters = diameters + prev + "C"; } } ElementId firstEid = lefts[leftXs.IndexOf(leftXs.Max())]; ElementId lastEid = rights[rightXs.IndexOf(rightXs.Min())]; LocationCurve firstP = doc.GetElement(firstEid).Location as LocationCurve; LocationCurve lastP = doc.GetElement(lastEid).Location as LocationCurve; XYZ rotP = firstP.Curve.GetEndPoint(0); Distance = Math.Abs(RackDim.GetRotatedToVert(firstEid, doc, rotP).GetEndPoint(0).X - RackDim.GetRotatedToVert(lastEid, doc, rotP).GetEndPoint(0).X); Line firstL = firstP.Curve as Line; if (updateRack) { toUpdate.Text = diameters; } else { Line texRot = Line.CreateBound(firstP.Curve.GetEndPoint(0), firstP.Curve.GetEndPoint(1)); Double textAngle = texRot.Direction.AngleTo(new XYZ(0, -1, 0)); bool fix = false; if (textAngle >= Math.PI / 2) { textAngle = Math.PI - textAngle; fix = true; } TextNoteOptions textRotate = new TextNoteOptions { TypeId = defTextType, Rotation = textAngle }; TextNote text = TextNote.Create(doc, doc.ActiveView.Id, LineDir.Evaluate(Store.mod_place, true), diameters, textRotate); text.get_Parameter(BuiltInParameter.TEXT_ALIGN_HORZ).Set((Int32)TextAlignFlags.TEF_ALIGN_BOTTOM); if (fix) { text.Coord = firstP.Curve.Evaluate(Store.mod_place, true) .Add(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(Distance + (4 * Store.mod_firsty))); } else { text.Coord = firstP.Curve.Evaluate(Store.mod_place, true) .Subtract(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(Distance + (4 * Store.mod_firsty))); } text.Coord = new XYZ(text.Coord.X, text.Coord.Y + (1.4 * Store.mod_stepy), text.Coord.Z); text.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R); text.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R); IList <Leader> leaders = text.GetLeaders(); leaders[0].End = firstP.Curve.Evaluate(Store.mod_place, true); if (firstL.Direction.AngleTo(new XYZ(0, 1, 0)) >= Math.PI / 2) { leaders[1].End = leaders[0].End.Subtract(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(Distance)); } else { leaders[1].End = leaders[0].End.Add(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(Distance)); } if (fix) { leaders[0].Elbow = leaders[0].End.Subtract(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(1.4 * Store.mod_left)); leaders[1].Elbow = leaders[1].End.Add(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(1.4 * Store.mod_left)); } else { leaders[0].Elbow = leaders[0].End.Add(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(1.4 * Store.mod_left)); leaders[1].Elbow = leaders[1].End.Subtract(RackDim.GetPerpendicular(firstL, Store.mod_place) .Direction.Multiply(1.4 * Store.mod_left)); } } tx.Commit(); } return(Result.Succeeded); }
internal static Result PromptForInputs(UIDocument doc, IList <IGH_Param> inputs, out Dictionary <IGH_Param, IEnumerable <IGH_Goo> > values) { values = new Dictionary <IGH_Param, IEnumerable <IGH_Goo> >(); foreach (var input in inputs.OrderBy((x) => x.Attributes.Pivot.Y)) { switch (input) { case Param_Box box: var boxes = PromptBox(doc, input.NickName); if (boxes == null) { return(Result.Cancelled); } values.Add(input, boxes); break; case Param_Point point: var points = PromptPoint(doc, input.NickName); if (points == null) { return(Result.Cancelled); } values.Add(input, points); break; case Param_Line line: var lines = PromptLine(doc, input.NickName); if (lines == null) { return(Result.Cancelled); } values.Add(input, lines); break; case Param_Curve curve: var curves = PromptEdge(doc, input.NickName); if (curves == null) { return(Result.Cancelled); } values.Add(input, curves); break; case Param_Surface surface: var surfaces = PromptSurface(doc, input.NickName); if (surfaces == null) { return(Result.Cancelled); } values.Add(input, surfaces); break; case Param_Brep brep: var breps = PromptBrep(doc, input.NickName); if (breps == null) { return(Result.Cancelled); } values.Add(input, breps); break; } } 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; double tolerance = app.ShortCurveTolerance; // Pick Import Instance ImportInstance import = null; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>()); import = doc.GetElement(r) as ImportInstance; } catch { return(Result.Cancelled); } if (import == null) { System.Windows.MessageBox.Show("CAD not found", "Tips"); return(Result.Cancelled); } // Fetch baselines List <Curve> wallCrvs = new List <Curve>(); var wallLayers = Misc.GetLayerNames(Properties.Settings.Default.layerWall); try { foreach (string wallLayer in wallLayers) { wallCrvs.AddRange(Util.TeighaGeometry.ShatterCADGeometry(uidoc, import, wallLayer, tolerance)); } } catch (Exception e) { System.Windows.MessageBox.Show(e.Message, "Tips"); return(Result.Cancelled); } if (wallCrvs == null || wallCrvs.Count == 0) { System.Windows.MessageBox.Show("Baselines not found", "Tips"); return(Result.Cancelled); } // Grab the current building level FilteredElementCollector docLevels = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.INVALID) .OfClass(typeof(Level)); ICollection <Element> levels = docLevels.OfClass(typeof(Level)).ToElements(); Level defaultLevel = null; foreach (Level level in levels) { if (level.Id == import.LevelId) { defaultLevel = level; } } if (defaultLevel == null) { System.Windows.MessageBox.Show("Please make sure there's a base level in current view", "Tips"); return(Result.Cancelled); } TransactionGroup tg = new TransactionGroup(doc, "Create walls"); try { tg.Start(); CreateWall.Execute(uiapp, wallCrvs, defaultLevel, false); tg.Assimilate(); } catch (Exception e) { System.Windows.MessageBox.Show(e.Message); tg.RollBack(); return(Result.Cancelled); } return(Result.Succeeded); }
/// <summary> /// External Event Implementation /// </summary> /// <param name="app"></param> public void Execute(UIApplication app) { try { UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; //Selection m_elementsToHide = uidoc.Selection; //SelElementSet.Create(); List <ElementId> elementids = new List <ElementId>(); // IS ORTHOGONAL if (v.OrthogonalCamera != null) { if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null) { return; } //type = "OrthogonalCamera"; var zoom = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS); var CameraDirection = Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z); var CameraUpVector = Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z); var CameraViewPoint = Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z); var orient3d = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true); View3D orthoView = null; //if active view is 3d ortho use it if (doc.ActiveView.ViewType == ViewType.ThreeD) { View3D ActiveView3D = doc.ActiveView as View3D; if (!ActiveView3D.IsPerspective) { orthoView = ActiveView3D; } } if (orthoView == null) { IEnumerable <View3D> viewcollector3D = get3DViews(doc); //try to use default 3D view if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any()) { orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First(); } } using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Open orthogonal view") == TransactionStatus.Started) { //create a new 3d ortho view if (orthoView == null) { orthoView = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id); orthoView.Name = "BCFortho"; } orthoView.SetOrientation(orient3d); trans.Commit(); } } uidoc.ActiveView = orthoView; //adjust view rectangle // **** CUSTOM VALUE FOR TEKLA **** // // double x = touple.Item2 // **** CUSTOM VALUE FOR TEKLA **** // double customZoomValue = (ProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5; double x = zoom / customZoomValue; XYZ m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x)); XYZ m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x)); uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr); } else if (v.PerspectiveCamera != null) { if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null) { return; } var zoom = v.PerspectiveCamera.FieldOfView; double z1 = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1 double z = 18 / Math.Tan(25 / 2 * Math.PI / 180); //focale, da controllare il 18, vedi PDF double factor = z1 - z; var CameraDirection = Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z); var CameraUpVector = Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z); XYZ oldO = Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z); var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor))); var orient3d = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true); View3D perspView = null; IEnumerable <View3D> viewcollector3D = get3DViews(doc); if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any()) { perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First(); } using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Open perspective view") == TransactionStatus.Started) { if (null == perspView) { perspView = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id); perspView.Name = "BCFpersp"; } perspView.SetOrientation(orient3d); // turn off the far clip plane with standard parameter API if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue) { Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR); m_farClip.Set(0); } perspView.CropBoxActive = true; perspView.CropBoxVisible = true; trans.Commit(); } } uidoc.ActiveView = perspView; } else if (v.SheetCamera != null)//sheet { //using (Transaction trans = new Transaction(uidoc.Document)) //{ // if (trans.Start("Open sheet view") == TransactionStatus.Started) // { IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID); if (!viewcollectorSheet.Any()) { MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found."); return; } uidoc.ActiveView = viewcollectorSheet.First(); uidoc.RefreshActiveView(); // trans.Commit(); // } //} XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y, v.SheetCamera.TopLeft.Z); XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y, v.SheetCamera.BottomRight.Z); uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr); } else { return; } //select/hide elements if (v.Components != null && v.Components.Any()) { FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType(); ICollection <ElementId> collection = collector.ToElementIds(); foreach (var e in v.Components) { var bcfguid = IfcGuid.FromIfcGUID(e.IfcGuid); var ids = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o)); if (ids.Any()) { //m_elementsToHide.Add(doc.GetElement(ids.First())); elementids.Add(ids.First()); } } if (null != elementids && elementids.Count > 0) { //do transaction only if there is something to hide/select using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Apply visibility/selection") == TransactionStatus.Started) { if (UserSettings.Get("selattachedelems") == "0") { uidoc.ActiveView.IsolateElementsTemporary(elementids); } else { #if Version2014 uidoc.Selection.Elements.Clear(); foreach (var elementid in elementids) { uidoc.Selection.Elements.Add(doc.GetElement(elementid)); } #elif Version2015 uidoc.Selection.SetElementIds(elementids); #elif Version2016 uidoc.Selection.SetElementIds(elementids); #endif } } trans.Commit(); } } } uidoc.RefreshActiveView(); } catch (Exception ex) { TaskDialog.Show("Error!", "exception: " + ex); } }