private void buttonUpdateParameters_Click(object sender, RoutedEventArgs e) { try { if (massConfig.UpdateType != ParameterUpdateType.None && massConfig.MassParameters.Count > 0) { var areaList = (List <AreaProperties>)dataGridArea.ItemsSource; var selectedAreas = areaList.Where(x => x.IsSelected).ToList(); if (!selectedAreas.Any()) { return; } statusLable.Text = "Updating Parameters ..."; progressBar.Visibility = System.Windows.Visibility.Visible; progressBar.Value = 0; progressBar.Maximum = selectedAreas.Count(); var updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue); using (var tg = new TransactionGroup(doc)) { tg.Start("Update Parameters"); try { double count = 0; foreach (var ap in selectedAreas) { using (var trans = new Transaction(doc)) { trans.Start("Update Parameter"); var options = trans.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new DuplicateWarningSwallower()); trans.SetFailureHandlingOptions(options); try { var updated = false; if (null != ap.Linked2dMass) { updated = UpdateParameter(ap.AreaElement, ap.Linked2dMass.MassElement); } if (null != ap.Linked3dMass) { updated = UpdateParameter(ap.AreaElement, ap.Linked3dMass.MassElement); } if (updated) { var updatedArea = new AreaProperties(ap) { IsSelected = false }; AreaDictionary.Remove(ap.AreaUniqueId); AreaDictionary.Add(ap.AreaUniqueId, updatedArea); } trans.Commit(); } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); trans.RollBack(); } } count++; Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, ProgressBar.ValueProperty, count); } DisplayAreaInfo(); tg.Assimilate(); } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); tg.RollBack(); MessageBox.Show("Failed to update parameters of linked masses.\n" + ex.Message, "Update Parameters", MessageBoxButton.OK, MessageBoxImage.Warning); } } progressBar.Visibility = System.Windows.Visibility.Hidden; statusLable.Text = "Ready"; } else { MessageBox.Show( "Please set the configuration for the parameter mappings.\nGo to the Parameters Settings button for more detail.", "Parameters Settings Missing", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); MessageBox.Show("Failed to update parameter values.\n" + ex.Message, "Update Parameters", MessageBoxButton.OK, MessageBoxImage.Warning); } }
private bool CopyLinkedRoomData(List <FamilyInstance> doorInstances) { bool result = true; try { Dictionary <int, LinkedInstanceProperties> linkedInstanceDictionary = CollectLinkedInstances(); StringBuilder strBuilder = new StringBuilder(); using (TransactionGroup tg = new TransactionGroup(m_doc, "Set Door Parameters")) { tg.Start(); try { foreach (FamilyInstance door in doorInstances) { using (Transaction trans = new Transaction(m_doc, "Set Parameter")) { trans.Start(); try { DoorProperties dp = new DoorProperties(door); if (null != dp.FromPoint && null != dp.ToPoint) { GeometryElement geomElem = door.get_Geometry(new Options()); XYZ direction = door.FacingOrientation; Dictionary <int, LinkedRoomProperties> linkedRooms = new Dictionary <int, LinkedRoomProperties>(); foreach (LinkedInstanceProperties lip in linkedInstanceDictionary.Values) { GeometryElement trnasformedElem = geomElem.GetTransformed(lip.TransformValue.Inverse); BoundingBoxXYZ bb = trnasformedElem.GetBoundingBox(); //extended bounding box XYZ midPt = 0.5 * (bb.Min + bb.Max); XYZ extMin = bb.Min + (bb.Min - midPt).Normalize(); XYZ extMax = bb.Max + (bb.Max - midPt).Normalize(); Outline outline = new Outline(extMin, extMax); BoundingBoxIntersectsFilter bbIntersectFilter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter bbInsideFilter = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter orFilter = new LogicalOrFilter(bbIntersectFilter, bbInsideFilter); FilteredElementCollector collector = new FilteredElementCollector(lip.LinkedDocument); List <Room> roomList = collector.OfCategory(BuiltInCategory.OST_Rooms).WherePasses(orFilter).WhereElementIsNotElementType().ToElements().Cast <Room>().ToList(); if (roomList.Count > 0) { foreach (Room room in roomList) { LinkedRoomProperties lrp = new LinkedRoomProperties(room); lrp.LinkedInstance = lip; if (!linkedRooms.ContainsKey(lrp.RoomId)) { linkedRooms.Add(lrp.RoomId, lrp); } } } } LinkedRoomProperties fromRoom = null; LinkedRoomProperties toRoom = null; if (linkedRooms.Count > 0) { foreach (LinkedRoomProperties lrp in linkedRooms.Values) { XYZ tFrom = lrp.LinkedInstance.TransformValue.Inverse.OfPoint(dp.FromPoint); XYZ tTo = lrp.LinkedInstance.TransformValue.Inverse.OfPoint(dp.ToPoint); if (lrp.RoomObject.IsPointInRoom(tFrom)) { dp.FromRoom = lrp.RoomObject; fromRoom = lrp; } if (lrp.RoomObject.IsPointInRoom(tTo)) { dp.ToRoom = lrp.RoomObject; toRoom = lrp; } } } if (null != fromRoom) { Parameter fParam = door.LookupParameter(fromRoomNumber); if (null != fParam) { fParam.Set(fromRoom.RoomNumber); } fParam = door.LookupParameter(fromRoomName); if (null != fParam) { fParam.Set(fromRoom.RoomName); } } if (null != toRoom) { Parameter tParam = door.LookupParameter(toRoomNumber); if (null != tParam) { tParam.Set(toRoom.RoomNumber); } tParam = door.LookupParameter(toRoomName); if (null != tParam) { tParam.Set(toRoom.RoomName); } } if (!doorDictionary.ContainsKey(dp.DoorId)) { doorDictionary.Add(dp.DoorId, dp); } } trans.Commit(); } catch (Exception ex) { trans.RollBack(); string message = ex.Message; result = false; strBuilder.AppendLine(door.Id.IntegerValue + "\t" + door.Name + ": " + ex.Message); } } } tg.Assimilate(); } catch (Exception ex) { tg.RollBack(); string message = ex.Message; } if (strBuilder.Length > 0) { MessageBox.Show("The following doors have been skipped due to some issues.\n\n" + strBuilder.ToString(), "Skipped Door Elements", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Exception ex) { MessageBox.Show("Failed to collect door data.\n" + ex.Message, "Collect Door Data", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(result); }
public static Result StartPlaceSupportsProcedure(ExternalCommandData commandData) { UIApplication uiApp = commandData.Application; Document doc = commandData.Application.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; try { using (TransactionGroup txGp = new TransactionGroup(doc)) { txGp.Start("Place support"); Pipe pipe; Element support; Pipe dummyPipe; Connector supportConnector; using (Transaction trans1 = new Transaction(doc)) { trans1.Start("Place supports!"); SupportChooser sc = new SupportChooser(commandData); sc.ShowDialog(); sc.Close(); (pipe, support) = PlaceSupports(commandData, "Support Symbolic: " + sc.supportName); trans1.Commit(); } using (Transaction trans2 = new Transaction(doc)) { trans2.Start("Define correct system type for support."); (dummyPipe, supportConnector) = SetSystemType(commandData, pipe, support); trans2.Commit(); } using (Transaction trans3 = new Transaction(doc)) { trans3.Start("Disconnect pipe."); Connector connectorToDisconnect = (from Connector c in dummyPipe.ConnectorManager.Connectors where c.IsConnectedTo(supportConnector) select c).FirstOrDefault(); connectorToDisconnect.DisconnectFrom(supportConnector); trans3.Commit(); } using (Transaction trans4 = new Transaction(doc)) { trans4.Start("Divide the MEPSystem."); dummyPipe.MEPSystem.DivideSystem(doc); trans4.Commit(); } using (Transaction trans5 = new Transaction(doc)) { trans5.Start("Delete the dummy pipe."); doc.Delete(dummyPipe.Id); trans5.Commit(); } txGp.Assimilate(); } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { return(Result.Failed); } }
public static Result Move(UIApplication uiApp) { Document doc = uiApp.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; try { using (TransactionGroup txGp = new TransactionGroup(doc)) { txGp.Start("Move elements to distance!"); Selection selection = uidoc.Selection; var selIds = selection.GetElementIds(); if (selIds.Count == 0) { throw new Exception("Empty selection: must select element(s) to move first!"); } HashSet <Element> elsToMove = selIds.Select(x => doc.GetElement(x)).ToHashSet(); var elId = uidoc.Selection.PickObject(ObjectType.Element, "Select element to move to!"); Element MoveToEl = doc.GetElement(elId); double distanceToKeep; //Ask for a length input InputBoxBasic ds = new InputBoxBasic(); ds.ShowDialog(); distanceToKeep = double.Parse(ds.DistanceToKeep).MmToFt(); //Business logic to move but keep desired distance HashSet <Connector> toMoveCons = SpecialGetAllConnectors(elsToMove); HashSet <Connector> moveToCons = SpecialGetAllConnectors(new HashSet <Element> { MoveToEl }); var listToCompare = new List <(Connector toMoveCon, Connector MoveToCon, double Distance)>(); foreach (Connector c1 in toMoveCons) { foreach (Connector c2 in moveToCons) { listToCompare.Add((c1, c2, c1.Origin.DistanceTo(c2.Origin))); } } var(toMoveCon, MoveToCon, Distance) = listToCompare.MinBy(x => x.Distance).FirstOrDefault(); XYZ moveVector = (MoveToCon.Origin - toMoveCon.Origin) * (1 - distanceToKeep / Distance); using (Transaction trans3 = new Transaction(doc)) { trans3.Start("Move Element!"); { if (elsToMove.Count > 1) { ElementTransformUtils.MoveElements(doc, selIds, moveVector); } else { foreach (Element elToMove in elsToMove) { ElementTransformUtils.MoveElement(doc, elToMove.Id, moveVector); } } } trans3.Commit(); } txGp.Assimilate(); } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { throw new Exception(ex.Message); } }
private void BtnOK_Click(object sender, EventArgs e) { // handle error if no data is selected if (CbxCategories.SelectedItem == null) { // show Wrong Selection form using (UI.Info.Form_Info1 thisForm = new UI.Info.Form_Info1()) { thisForm.ShowDialog(); } } else { Category cat = CbxCategories.SelectedItem as Category; elemTry = GetInstances(m_doc, cat).Count(); KeyValuePair <Parameter, string> targetKeyValuePair = (KeyValuePair <Parameter, string>)CbxTargetParameters.SelectedItem; Parameter targetParam = targetKeyValuePair.Key; using (TransactionGroup tg = new TransactionGroup(m_doc, "Parameter Mapper")) { tg.Start(); // for each element of the selected category foreach (Element elem in GetInstances(m_doc, cat)) { using (Transaction t = new Transaction(m_doc, "Parameter Mapper Single Transaction")) { t.Start(); try { Parameter elemTargetParam = elem.get_Parameter(targetParam.Definition); if (RbtElementId.Checked == true) // when Element Id is selected { string eId = elem.Id.ToString(); elemTargetParam.Set(eId); t.Commit(); } else if (RbtSourceParam.Checked == true && RbtAsText.Checked == true) // when "Number As Text" is selected { KeyValuePair <Parameter, string> sourceKeyValuePair = (KeyValuePair <Parameter, string>)CbxSourceParameters.SelectedItem; Parameter sourceParam = sourceKeyValuePair.Key; Parameter elemSourceParam = elem.get_Parameter(sourceParam.Definition); string sourceValueString = GetParamValueAsString(elemSourceParam); elemTargetParam.Set(sourceValueString); t.Commit(); } else // when "Number As Number" is selected { KeyValuePair <Parameter, string> sourceKeyValuePair = (KeyValuePair <Parameter, string>)CbxSourceParameters.SelectedItem; Parameter sourceParam = sourceKeyValuePair.Key; Parameter elemSourceParam = elem.get_Parameter(sourceParam.Definition); if (elemSourceParam.StorageType != StorageType.Double) { string sourceValueString = GetParamValueAsString(elemSourceParam); elemTargetParam.Set(sourceValueString); t.Commit(); } else { if (RbtAsNumber.Checked == true) { double sourceValueDouble = elemSourceParam.AsDouble(); elemTargetParam.Set(sourceValueDouble); t.Commit(); } else { string sourceValueString = GetParamValueAsString(elemSourceParam); elemTargetParam.Set(sourceValueString); t.Commit(); } } } } catch (Exception) { elemFail += 1; } } } tg.Assimilate(); } using (UI.Info.Form_Results thisForm = new UI.Info.Form_Results()) { thisForm.ShowDialog(); } DialogResult = DialogResult.OK; } }
//Get the Selected Viewports from the linked model, check to see if the sheet they are on exists and if they are already placed. //If not, create and set the properties of both. private void btnOK_Click(object sender, EventArgs e) { int itemCount = 0; bool TitleLocation = true; ElementId typeId = (ElementId)cbViewPortTypes.SelectedValue; ElementType vpType = doc.GetElement(typeId) as ElementType; //Check to see if the Viewport Type has the Show Title property set to Yes, if it is not, we can't calculate its location //relative to the viewport to move it to the same location as the Linked Model if (vpType.LookupParameter("Show Title").AsInteger() != 1) { if (TaskDialog.Show("Viewport Show Title", "The Viewport Type selected does not have the 'Show Title' property set to Yes and the View placement may not be as expected.\nWould you like to continue?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.No) { return; } else { TitleLocation = false; } } //Use a Transaction Group for multiple transactions to be grouped as one. This enables the creation of sheets and views during the method //without throwing an exception that the elements don't exist using (TransactionGroup tGroup = new TransactionGroup(doc, "Create Linked Views")) { tGroup.Start(); using (Transaction t = new Transaction(doc)) { ElementId vpTypeId = ((Element)cboTitleBlock.SelectedValue).Id; foreach (DataGridViewRow row in dgvLinkedViews.SelectedRows) { //use a try block to make sure any errors don't crash revit try { t.Start("Create View"); string detailNumber = (string)row.Cells[1].Value; ViewFamilyType viewfamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.Drafting); TextNoteType textnoteType = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).Cast <TextNoteType>().FirstOrDefault(); ViewDrafting draftingView = ViewDrafting.Create(doc, viewfamilyType.Id); draftingView.Name = (string)row.Cells[3].Value; draftingView.LookupParameter("Title on Sheet").Set("REFERENCE VIEW - DO NOT PRINT"); //Set additional View Parameters based on Firm standards and Project Broswer Sorting templates //if (dView.LookupParameter("Sheet Sort") is Parameter sSort) //{ // sSort.Set("PLANS"); //} //Set the Linked View Yes/No Parameter to "Yes" for the Reload Function to Track if (draftingView.LookupParameter("Linked View") is Parameter lView) { //Using 0 or 1 to set Yes (1) / No (0) parameters lView.Set(1); } else { TaskDialog.Show("Missing Parameter", "Linked View Yes/No parameter is missing from View category and cannot continue."); break; } //Set the Linked View GUID parameter to track the view in the Linked model if (draftingView.LookupParameter("Linked View GUID") is Parameter lGUID) { lGUID.Set((string)row.Cells[5].Value); } else { TaskDialog.Show("Missing Parameter", "Linked View GUID Text parameter is missing from View category and cannot continue."); break; } //Set the Link Name parameter to trak which Linked Model it came from. if (draftingView.LookupParameter("Link Name") is Parameter lName) { lName.Set(cboLinks.Text); } else { TaskDialog.Show("Missing Parameter", "Link Name Text parameter is missing from View category and cannot continue."); break; } //Creates one Text Note in the middle of the view to alert users that it is a Linked View and not to print it. TextNote.Create(doc, draftingView.Id, new XYZ(0, 0, 0), "REFERENCE VIEW - DO NOT PRINT", textnoteType.Id); t.Commit(); //Check to see if sheet with that number exits in the document t.Start("Create Sheet"); ViewSheet sheet = CheckSheet((string)row.Cells[2].Value, vpTypeId); t.Commit(); //Place the Drafting View reference on the sheet in the same location as in the Linked Model t.Start("Place View"); if (sheet != null) { //Check to see if Viewport can be placed on sheet if (Viewport.CanAddViewToSheet(doc, sheet.Id, draftingView.Id)) { if (CheckViewport(detailNumber, sheet)) { XYZ labelPoint = (XYZ)row.Cells[7].Value; Viewport vPort = Viewport.Create(doc, sheet.Id, draftingView.Id, labelPoint); draftingView.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(detailNumber); if (typeId != ElementId.InvalidElementId) { vPort.ChangeTypeId(typeId); } if (TitleLocation) { //Get the location of the Viewport and Viewport Label and Move the Viewport to match the Linked Document ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint - vPort.GetLabelOutline().MinimumPoint); } else { //If the Viewport Type does not have the Show Title property set to yes, we can't calculate the location //and we just place it int he location from the Linked model. This may not be the same location. ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint); } } else { TaskDialog.Show("Existing Viewport", "Sheet " + sheet.SheetNumber + "-" + sheet.Name + " already contains a Viewport with Detail Number " + detailNumber + ", but detail " + draftingView.Name + " was created."); } } } t.Commit(); itemCount++; } catch (Exception ex) { //This Exception will check if the View already exits in the project if (ex.GetType() == typeof(Autodesk.Revit.Exceptions.ArgumentException)) { TaskDialog.Show("Existing View", "View '" + (string)row.Cells[3].Value + "' already exists and will not be created."); if (t.HasStarted()) { t.RollBack(); } continue; } else { TaskDialog.Show("Error", ex.ToString()); //Check to see if a Transaction is active and roll it back if so if (t.HasStarted()) { t.RollBack(); } //check to see if the Group Transaction has started and roll it back if so if (tGroup.HasStarted()) { tGroup.RollBack(); } } } } } //Commit all of the changes from the Transaction group and other transactions tGroup.Assimilate(); DialogResult = DialogResult.OK; Close(); } }
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; if (doc.IsFamilyDocument) { TaskDialog.Show("ОТМЕНЕНО", "Данная команда предназначена для запуска в документе проекта"); return(Result.Cancelled); } try { Transform projectTransform = Utils.GetProjectCoordinatesTransform(doc); //выбрать несколько xml с расположением водосбросов string[] filenames = null; WinForms.OpenFileDialog openFileDialog1 = new WinForms.OpenFileDialog(); string curDocPath = doc.PathName; if (!String.IsNullOrEmpty(curDocPath)) { openFileDialog1.InitialDirectory = Path.GetDirectoryName(curDocPath); } openFileDialog1.Filter = "xml files (*.xml)|*.xml"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; openFileDialog1.Multiselect = true; openFileDialog1.Title = "Выберите таблицы CSV с координатами 3d-полилиний"; if (openFileDialog1.ShowDialog() == WinForms.DialogResult.OK) { Creation.Document crDoc = doc.Create; filenames = openFileDialog1.FileNames; using (TransactionGroup trGr = new TransactionGroup(doc)) { trGr.Start("CreateSpillways"); foreach (string filename in filenames) { //распаристь xml PositionData positionData = null; using (StreamReader sr = new StreamReader(filename)) { string serializedData = sr.ReadToEnd(); var xmlSerializer = new XmlSerializer(typeof(PositionData)); var stringReader = new StringReader(serializedData); positionData = (PositionData)xmlSerializer.Deserialize(stringReader); } if (positionData != null) { foreach (SpillwayPosition sp in positionData.SpillwayPositions) { //Загрузка семейства водосброса если еще нет Family spillwayFamily = null; if (sp.Slopes.Count == 2) { spillwayFamily = Utils.GetFamily(doc, "Водосброс2Укл"); } else if (sp.Slopes.Count == 3) { spillwayFamily = Utils.GetFamily(doc, "Водосброс3Укл"); } if (spillwayFamily != null) { ElementId symId = spillwayFamily.GetFamilySymbolIds().First(); FamilySymbol familySymbol = (FamilySymbol)doc.GetElement(symId); using (Transaction tr = new Transaction(doc)) { tr.Start("CreateSpillway"); //активировать типоразмер if (!familySymbol.IsActive) { familySymbol.Activate(); doc.Regenerate(); } //Вставка водосбросов в заданные координаты //Поворот на заданный угол //Если водосброс направлен направо, то использовать отражение (с поворотом в противоположную сторону) XYZ location = projectTransform.OfPoint(Utils.PointByMeters(sp.X, sp.Y, sp.Z)); FamilyInstance fi = crDoc.NewFamilyInstance(location, familySymbol, StructuralType.NonStructural); Line rotationAxis = Line.CreateBound(location, location + XYZ.BasisZ); double rotationAngle = sp.Z_Rotation / (180 / Math.PI); if (sp.ToTheRight) { rotationAngle = rotationAngle + Math.PI; } fi.Location.Rotate(rotationAxis, rotationAngle); if (sp.ToTheRight) { XYZ spillwayDir = Transform.CreateRotation(XYZ.BasisZ, rotationAngle).OfVector(XYZ.BasisY); Plane mirrorPlane = Plane.CreateByNormalAndOrigin(spillwayDir, location); ElementTransformUtils.MirrorElements(doc, new List <ElementId>() { fi.Id }, mirrorPlane, false); //doc.Delete(fi.Id); } //Назначение параметров уклонов водосброса for (int i = 0; i < sp.Slopes.Count; i++) { string lengthParamName = "Длина" + (i + 1); string slopeParamName = "Уклон" + (i + 1); Parameter lengthParam = fi.LookupParameter(lengthParamName); Parameter slopeParam = fi.LookupParameter(slopeParamName); if (lengthParam != null && slopeParam != null) { Slope s = sp.Slopes[i]; lengthParam.Set(UnitUtils.Convert(s.Len, DisplayUnitType.DUT_METERS, DisplayUnitType.DUT_DECIMAL_FEET)); slopeParam.Set(s.S); } } tr.Commit(); } } } } } trGr.Assimilate(); } } } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Succeeded); } catch (Exception ex) { CommonException(ex, "Ошибка при расстановке водосбросов в Revit"); return(Result.Succeeded); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { m_app = commandData.Application; m_doc = m_app.ActiveUIDocument.Document; Log.AppendLog(LogMessageType.INFO, "Started"); // (Konrad) We are gathering information about the addin use. This allows us to // better maintain the most used plug-ins or discontiue the unused ones. AddinUtilities.PublishAddinLog(new AddinLog("Utilities-RoomMeasure", commandData.Application.Application.VersionNumber)); try { var collector = new FilteredElementCollector(m_doc); var rooms = collector.OfCategory(BuiltInCategory.OST_Rooms).ToElements().Cast <Room>().ToList(); if (rooms.Count > 0) { var sampleRoom = rooms.First(); if (MeasureUtil.ExistRoomParameter(sampleRoom)) { using (var tg = new TransactionGroup(m_doc)) { tg.Start("Calculate Rooms"); try { var roomCount = 0; foreach (var room in rooms) { if (room.Area == 0) { continue; } using (var trans = new Transaction(m_doc)) { double width = 0; double length = 0; var directShapeId = ElementId.InvalidElementId; var perpendicularSwitch = false; trans.Start("Create Room DirecShape"); try { var directShape = MeasureUtil.CreateRoomDirectShape(room); if (null != directShape) { directShapeId = directShape.Id; MeasureUtil.RotateDirectShape(directShape, room, out perpendicularSwitch); } trans.Commit(); } catch (Exception ex) { trans.RollBack(); var exMsg = ex.Message; } trans.Start("Calculate Dimension"); try { var directShape = m_doc.GetElement(directShapeId) as DirectShape; if (null != directShape) { MeasureUtil.CalculateWidthAndLength(directShape, out width, out length); } m_doc.Delete(directShapeId); trans.Commit(); } catch (Exception ex) { trans.RollBack(); var exMsg = ex.Message; } trans.Start("Set Parameter"); try { if (perpendicularSwitch) { var tempVal = width; width = length; length = tempVal; } var param = room.LookupParameter(roomWidthParamName); param?.Set(width); param = room.LookupParameter(roomLengthParamName); param?.Set(length); trans.Commit(); } catch (Exception ex) { trans.RollBack(); var exMsg = ex.Message; } roomCount++; } } tg.Assimilate(); MessageBox.Show("Parameters [Room Width] and [Room Length] have been updated in " + roomCount + " rooms.", "Successfully Completed!", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { tg.RollBack(); MessageBox.Show("Failed to measure the width and length of rooms.\n" + ex.Message, "Measuring Rooms", MessageBoxButton.OK, MessageBoxImage.Warning); } } } } else { MessageBox.Show("Room doesn't exist in the current project.", "Room Not Found", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); } Log.AppendLog(LogMessageType.INFO, "Ended"); return(Result.Succeeded); }
private List <MonitorMessage> VerifyDoorParameters(MonitorProjectSetup projectSetup) { List <MonitorMessage> warningMessages = new List <MonitorMessage>(); try { using (TransactionGroup transGroup = new TransactionGroup(m_doc)) { transGroup.Start("Verify Doors"); ElementFilter catFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); FilteredElementCollector collector = new FilteredElementCollector(m_doc); List <FamilyInstance> doorInstances = collector.WherePasses(catFilter).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList(); foreach (FamilyInstance doorInstance in doorInstances) { #if RELEASE2013 || RELEASE2014 Parameter pullParam = doorInstance.get_Parameter(pullParamName); #elif RELEASE2015 || RELEASE2016 || RELEASE2017 Parameter pullParam = doorInstance.LookupParameter(pullParamName); #endif if (null != pullParam) { string pullValue = pullParam.AsValueString(); if (!pullValue.Contains("Approach")) { MonitorMessage message = new MonitorMessage(doorInstance, pullParamName, "Incorrect parameter value has been set."); warningMessages.Add(message); } } #if RELEASE2013 || RELEASE2014 Parameter pushParam = doorInstance.get_Parameter(pushParamName); #elif RELEASE2015 || RELEASE2016 || RELEASE2017 Parameter pushParam = doorInstance.LookupParameter(pushParamName); #endif if (null != pushParam) { string pushValue = pushParam.AsValueString(); if (!pushValue.Contains("Approach")) { MonitorMessage message = new MonitorMessage(doorInstance, pushParamName, "Incorrect parameter value has been set."); warningMessages.Add(message); } } #if RELEASE2013 || RELEASE2014 Parameter caParam = doorInstance.get_Parameter(stateCAParamName); #elif RELEASE2015 || RELEASE2016 || RELEASE2017 Parameter caParam = doorInstance.LookupParameter(stateCAParamName); #endif if (null != caParam) { int caVal = caParam.AsInteger(); int projectVal = Convert.ToInt32(projectSetup.IsStateCA); if (caVal != projectVal) { using (Transaction trans = new Transaction(m_doc)) { trans.Start("Set State Param"); try { caParam.Set(projectVal); MonitorMessage message = new MonitorMessage(doorInstance, stateCAParamName, "Parameter Value has been changed. (solved) "); warningMessages.Add(message); trans.Commit(); } catch (Exception ex) { string message = ex.Message; trans.RollBack(); } } } } } transGroup.Assimilate(); } } catch (Exception ex) { MessageBox.Show("Failed to verify door parameters.\n" + ex.Message, "Verify Door Parameters", MessageBoxButton.OK, MessageBoxImage.Warning); } return(warningMessages); }
public void QTO_2_PlaceHoldersFromDWFMarkups( Document doc, string activityId) { View activeView = doc.ActiveView; if (!(activeView is ViewSheet)) { TaskDialog.Show("QTO", "The current view must be a Sheet View with DWF markups"); return; } ViewSheet vs = activeView as ViewSheet; Viewport vp = doc.GetElement( vs.GetAllViewports().First()) as Viewport; View plan = doc.GetElement(vp.ViewId) as View; int scale = vp.Parameters.Cast <Parameter>() .First(x => x.Id.IntegerValue.Equals( (int)BuiltInParameter.VIEW_SCALE)) .AsInteger(); IEnumerable <Element> dwfMarkups = new FilteredElementCollector(doc) .OfClass(typeof(ImportInstance)) .WhereElementIsNotElementType() .Where(x => x.Name.StartsWith("Markup") && x.OwnerViewId.IntegerValue.Equals( activeView.Id.IntegerValue)); using (TransactionGroup tg = new TransactionGroup(doc)) { tg.Start("DWF markups placeholders"); using (Transaction t = new Transaction(doc)) { t.Start("DWF Transfer"); plan.Parameters.Cast <Parameter>() .First(x => x.Id.IntegerValue.Equals( (int)BuiltInParameter.VIEWER_CROP_REGION)) .Set(1); XYZ VC = (plan.CropBox.Min + plan.CropBox.Max) / 2; XYZ BC = vp.GetBoxCenter(); t.RollBack(); foreach (Element e in dwfMarkups) { GeometryElement GeoElem = e.get_Geometry(new Options()); GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList <GeometryObject> gos = new List <GeometryObject>(); if (gei.Cast <GeometryObject>().Count(x => x is Arc) > 0) { continue; } foreach (GeometryObject go in gei) { XYZ med = new XYZ(); if (go is PolyLine) { PolyLine pl = go as PolyLine; XYZ min = new XYZ(pl.GetCoordinates().Min(p => p.X), pl.GetCoordinates().Min(p => p.Y), pl.GetCoordinates().Min(p => p.Z)); XYZ max = new XYZ(pl.GetCoordinates().Max(p => p.X), pl.GetCoordinates().Max(p => p.Y), pl.GetCoordinates().Max(p => p.Z)); med = (min + max) / 2; } med = med - BC; // Convert DWF sheet coordinates into model coordinates XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0); } } t.Start("DWF Transfer"); foreach (Element e in dwfMarkups) { GeometryElement GeoElem = e.get_Geometry(new Options()); GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList <GeometryObject> gos = new List <GeometryObject>(); if (gei.Cast <GeometryObject>().Count(x => x is Arc) == 0) { continue; } foreach (GeometryObject go in gei) { if (go is Arc) { Curve c = go as Curve; XYZ med = c.Evaluate(0.5, true); med = med - BC; XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0); // Warning CS0618: // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote( // View, XYZ, XYZ, XYZ, double, TextAlignFlags, string) // is obsolete: // This method is deprecated in Revit 2016. // Please use one of the TextNote.Create methods instead. //doc.Create.NewTextNote( plan, // a, // XYZ.BasisX, // XYZ.BasisY, // MMtoFeet( 5 ), // TextAlignFlags.TEF_ALIGN_CENTER, // activityId ); ElementId textTypeId = new FilteredElementCollector(doc) .OfClass(typeof(TextNoteType)) .FirstElementId(); TextNote.Create(doc, plan.Id, a, activityId, textTypeId); } } t.Commit(); } } tg.Assimilate(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; app = commandData.Application.Application; doc = uidoc.Document; //Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "Select a CAD Link"); //Element elem = doc.GetElement(refer); //GeometryElement geoElem = elem.get_Geometry(new Options()); Reference r = uidoc.Selection.PickObject(ObjectType.PointOnElement); string ss = r.ConvertToStableRepresentation(doc); Element elem = doc.GetElement(r); GeometryElement geoElem = elem.get_Geometry(new Options()); GeometryObject geoObj = elem.GetGeometryObjectFromReference(r); //获取选中的cad图层 Category targetCategory = null; ElementId graphicsStyleId = null; if (geoObj.GraphicsStyleId != ElementId.InvalidElementId) { graphicsStyleId = geoObj.GraphicsStyleId; GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle; if (gs != null) { targetCategory = gs.GraphicsStyleCategory; var name = gs.GraphicsStyleCategory.Name; } } //隐藏选中的cad图层 Transaction trans = new Transaction(doc, "隐藏图层"); trans.Start(); if (targetCategory != null) { doc.ActiveView.SetVisibility(targetCategory, false); } trans.Commit(); TransactionGroup transGroup = new TransactionGroup(doc, "绘制模型线"); transGroup.Start(); CurveArray curveArray = new CurveArray(); //判断元素类型 foreach (var gObj in geoElem) { GeometryInstance geomInstance = gObj as GeometryInstance; //坐标转换。如果选择的是“自动-中心到中心”,或者移动了importInstance,需要进行坐标转换 Transform transform = geomInstance.Transform; if (null != geomInstance) { foreach (var insObj in geomInstance.SymbolGeometry) { if (insObj.GraphicsStyleId.IntegerValue != graphicsStyleId.IntegerValue) { continue; } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.NurbSpline") { //未实现 } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Line") { Line line = insObj as Line; XYZ normal = XYZ.BasisZ; XYZ point = line.GetEndPoint(0); point = transform.OfPoint(point); curveArray.Append(TransformLine(transform, line)); CreateModelCurveArray(curveArray, normal, point); } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Arc") { //未实现 } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.PolyLine") { PolyLine polyLine = insObj as PolyLine; IList <XYZ> points = polyLine.GetCoordinates(); for (int i = 0; i < points.Count - 1; i++) { Line line = Line.CreateBound(points[i], points[i + 1]); line = TransformLine(transform, line); curveArray.Append(line); } XYZ normal = XYZ.BasisZ; XYZ point = points.First(); point = transform.OfPoint(point); CreateModelCurveArray(curveArray, normal, point); } } } } transGroup.Assimilate(); return(Result.Succeeded); }
/// <summary> /// Adds a new retaining pond. /// </summary> /// <param name="uiDoc">The document.</param> /// <param name="pondRadius">The radius of the pond.</param> private void AddNewRetainingPond(UIDocument uiDoc, double pondRadius) { Document doc = uiDoc.Document; // Find toposurfaces FilteredElementCollector tsCollector = new FilteredElementCollector(doc); tsCollector.OfClass(typeof(TopographySurface)); IEnumerable <TopographySurface> tsEnumerable = tsCollector.Cast <TopographySurface>().Where <TopographySurface>(ts => !ts.IsSiteSubRegion); int count = tsEnumerable.Count <TopographySurface>(); // If there is only on surface, use it. If there is more than one, let the user select the target. TopographySurface targetSurface = null; if (count > 1) // tmp { targetSurface = SiteUIUtils.PickTopographySurface(uiDoc); } else { targetSurface = tsEnumerable.First <TopographySurface>(); } // Pick point and project to plane at toposurface average elevation XYZ point = SiteUIUtils.PickPointNearToposurface(uiDoc, targetSurface, "Pick point for center of pond."); double elevation = point.Z; // Add subregion first, so that any previously existing points can be removed to avoid distorting the new region // Find material "Water" FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(Material)); Material mat = collector.Cast <Material>().FirstOrDefault <Material>(m => m.Name == "Water"); // Create subregion curves List <Curve> curves = new List <Curve>(); curves.Add(Arc.Create(point, pondRadius, 0, Math.PI, XYZ.BasisX, XYZ.BasisY)); curves.Add(Arc.Create(point, pondRadius, Math.PI, 2 * Math.PI, XYZ.BasisX, XYZ.BasisY)); CurveLoop curveLoop = CurveLoop.Create(curves); List <CurveLoop> curveLoops = new List <CurveLoop>(); curveLoops.Add(curveLoop); // All changes are added to one transaction group - will create one undo item using (TransactionGroup addGroup = new TransactionGroup(doc, "Add pond group")) { addGroup.Start(); IList <XYZ> existingPoints = null; // Transacton for adding subregion. using (Transaction t2 = new Transaction(doc, "Add subregion")) { t2.Start(); SiteSubRegion region = SiteSubRegion.Create(doc, curveLoops, targetSurface.Id); if (mat != null) { region.TopographySurface.MaterialId = mat.Id; } t2.Commit(); // The boundary points for the subregion cannot be deleted, since they are generated // to represent the subregion boundary rather than representing real points in the host. // Get non-boundary points only to be deleted. existingPoints = SiteEditingUtils.GetNonBoundaryPoints(region.TopographySurface); // Average elevation of all points in the subregion to use as base elevation for the pond topography elevation = SiteEditingUtils.GetAverageElevation(region.TopographySurface.GetPoints()); } // Add the topography points to the target surface via edit scope. using (TopographyEditScope editScope = new TopographyEditScope(doc, "Edit TS")) { editScope.Start(targetSurface.Id); // Transaction for points changes using (Transaction t = new Transaction(doc, "Add points")) { t.Start(); // Delete existing points first to avoid conflict if (existingPoints.Count > 0) { targetSurface.DeletePoints(existingPoints); } // Generate list of points to add IList <XYZ> points = SiteEditingUtils.GeneratePondPointsSurrounding(new XYZ(point.X, point.Y, elevation - 3), pondRadius); targetSurface.AddPoints(points); t.Commit(); } editScope.Commit(new TopographyEditFailuresPreprocessor()); } addGroup.Assimilate(); } }
public static Result Do(UIApplication uiapp, Dictionary <ElementId, double> level) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; List <XYZ> points = new List <XYZ>(); List <Curve> SplitCurves = new List <Curve>(); List <double> _elevations = RevitModel.LevelElevation.GetElevations(doc); foreach (ElementId e1 in GlobalVariables.SplitObjects) { Curve c1 = Elements.GetCurve(doc, level, e1); if (null != c1) { SplitCurves.Add(c1); foreach (ElementId e2 in GlobalVariables.CutObjects) { Curve c2 = Elements.GetCurve(doc, level, e2); if (null != c2) { XYZ intersection = GetIntersection(c1, c2); if (intersection != null && !PointAlreadyInList.Check(points, intersection)) { points.Add(intersection); } } } } } using (TransactionGroup transgroup = new TransactionGroup(doc, "Intersect Geometry")) { try { if (transgroup.Start() != TransactionStatus.Started) { return(Result.Failed); } foreach (ElementId e1 in GlobalVariables.SplitObjects) { Curve c = Elements.GetCurve(doc, level, e1); FamilyInstance f = Elements.GetFamilyInstance(doc, level, e1); List <Curve> newCurves = ElementSplitter.Do(c, points); ICollection <ElementId> newElements = null; for (int i = 0; i < newCurves.Count; i++) { if (i != 0) // First Element different - just change endpoint // All other make copy first { using (Transaction trans = new Transaction(doc, "Copy element.")) { try { if (trans.Start() != TransactionStatus.Started) { return(Result.Failed); } XYZ transform = newCurves[i].GetEndPoint(0) - c.GetEndPoint(0); newElements = Elements.Transform(doc, e1, transform); if (TransactionStatus.Committed != trans.Commit()) { trans.RollBack(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); trans.RollBack(); } } foreach (ElementId id in newElements) { // Change Curve using (Transaction trans = new Transaction(doc, "Transform element.")) { try { if (trans.Start() != TransactionStatus.Started) { return(Result.Failed); } FamilyInstance newf = Elements.GetFamilyInstance(doc, level, id); Elements.ChangeEndPoint(doc, newCurves[i], newf, level, _elevations); FailureHandlingOptions options = trans.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new WarningSwallower()); if (TransactionStatus.Committed != trans.Commit(options)) { trans.RollBack(); } } catch { trans.RollBack(); } } } } else { using (Transaction trans = new Transaction(doc, "Transform element.")) { try { if (trans.Start() != TransactionStatus.Started) { return(Result.Failed); } foreach (ElementId eId in JoinGeometryUtils.GetJoinedElements(doc, f)) { JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(e1), doc.GetElement(eId)); } FailureHandlingOptions options = trans.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new WarningSwallower()); if (TransactionStatus.Committed != trans.Commit(options)) { trans.RollBack(); } } catch { trans.RollBack(); } } using (Transaction trans = new Transaction(doc, "Transform element.")) { try { if (trans.Start() != TransactionStatus.Started) { return(Result.Failed); } LocationCurve orig_location = f.Location as LocationCurve; double orig_len = orig_location.Curve.Length; double up_len = newCurves[i].Length; Elements.ChangeEndPoint(doc, newCurves[i], f, level, _elevations); LocationCurve after_location = f.Location as LocationCurve; double after_len = after_location.Curve.Length; doc.Regenerate(); LocationCurve regen_location = f.Location as LocationCurve; double regen_len = regen_location.Curve.Length; uidoc.RefreshActiveView(); FailureHandlingOptions options = trans.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new WarningSwallower()); options.SetClearAfterRollback(true); if (TransactionStatus.Committed != trans.Commit(options)) { trans.RollBack(); return(Result.Failed); } } catch { trans.RollBack(); return(Result.Failed); } } } } } if (transgroup.Assimilate() == TransactionStatus.Committed) { return(Result.Succeeded); } else { return(Result.Failed); } } catch { transgroup.RollBack(); return(Result.Failed); } } }
public void QTO_2_PlaceHoldersFromDWFMarkups( Document doc, string activityId) { View activeView = doc.ActiveView; if( !( activeView is ViewSheet ) ) { TaskDialog.Show( "QTO", "The current view must be a Sheet View with DWF markups" ); return; } ViewSheet vs = activeView as ViewSheet; Viewport vp = doc.GetElement( vs.GetAllViewports().First() ) as Viewport; View plan = doc.GetElement( vp.ViewId ) as View; int scale = vp.Parameters.Cast<Parameter>() .First( x => x.Id.IntegerValue.Equals( (int) BuiltInParameter.VIEW_SCALE ) ) .AsInteger(); IEnumerable<Element> dwfMarkups = new FilteredElementCollector( doc ) .OfClass( typeof( ImportInstance ) ) .WhereElementIsNotElementType() .Where( x => x.Name.StartsWith( "Markup" ) && x.OwnerViewId.IntegerValue.Equals( activeView.Id.IntegerValue ) ); using( TransactionGroup tg = new TransactionGroup( doc ) ) { tg.Start( "DWF markups placeholders" ); using( Transaction t = new Transaction( doc ) ) { t.Start( "DWF Transfer" ); plan.Parameters.Cast<Parameter>() .First( x => x.Id.IntegerValue.Equals( (int) BuiltInParameter.VIEWER_CROP_REGION ) ) .Set( 1 ); XYZ VC = ( plan.CropBox.Min + plan.CropBox.Max ) / 2; XYZ BC = vp.GetBoxCenter(); t.RollBack(); foreach( Element e in dwfMarkups ) { GeometryElement GeoElem = e.get_Geometry( new Options() ); GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList<GeometryObject> gos = new List<GeometryObject>(); if( gei.Cast<GeometryObject>().Count( x => x is Arc ) > 0 ) { continue; } foreach( GeometryObject go in gei ) { XYZ med = new XYZ(); if( go is PolyLine ) { PolyLine pl = go as PolyLine; XYZ min = new XYZ( pl.GetCoordinates().Min( p => p.X ), pl.GetCoordinates().Min( p => p.Y ), pl.GetCoordinates().Min( p => p.Z ) ); XYZ max = new XYZ( pl.GetCoordinates().Max( p => p.X ), pl.GetCoordinates().Max( p => p.Y ), pl.GetCoordinates().Max( p => p.Z ) ); med = ( min + max ) / 2; } med = med - BC; // Convert DWF sheet coordinates into model coordinates XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 ); } } t.Start( "DWF Transfer" ); foreach( Element e in dwfMarkups ) { GeometryElement GeoElem = e.get_Geometry( new Options() ); GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList<GeometryObject> gos = new List<GeometryObject>(); if( gei.Cast<GeometryObject>().Count( x => x is Arc ) == 0 ) { continue; } foreach( GeometryObject go in gei ) { if( go is Arc ) { Curve c = go as Curve; XYZ med = c.Evaluate( 0.5, true ); med = med - BC; XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 ); // Warning CS0618: // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote( // View, XYZ, XYZ, XYZ, double, TextAlignFlags, string) // is obsolete: // This method is deprecated in Revit 2016. // Please use one of the TextNote.Create methods instead. //doc.Create.NewTextNote( plan, // a, // XYZ.BasisX, // XYZ.BasisY, // MMtoFeet( 5 ), // TextAlignFlags.TEF_ALIGN_CENTER, // activityId ); ElementId textTypeId = new FilteredElementCollector( doc ) .OfClass( typeof( TextNoteType ) ) .FirstElementId(); TextNote.Create( doc, plan.Id, a, activityId, textTypeId ); } } t.Commit(); } } tg.Assimilate(); } }
private static void CropView(View view, PickedBox pickedBox, Document doc, string trName) { var cropRegionShapeManager = view.GetCropRegionShapeManager(); var pt1 = pickedBox.Min; var pt3 = pickedBox.Max; var plane = CreatePlane(view.UpDirection, pt3); var pt2 = plane.ProjectOnto(pt1); plane = CreatePlane(view.UpDirection, pt1); var pt4 = plane.ProjectOnto(pt3); var line1 = TryCreateLine(pt1, pt2); var line2 = TryCreateLine(pt2, pt3); var line3 = TryCreateLine(pt3, pt4); var line4 = TryCreateLine(pt4, pt1); if (line1 == null || line2 == null || line3 == null || line4 == null) { // Не удалось получить валидную прямоугольную область. Попробуйте еще раз MessageBox.Show(Language.GetItem("h6")); return; } var curveLoop = CurveLoop.Create(new List <Curve> { line1, line2, line3, line4 }); if (curveLoop.IsRectangular(CreatePlane(view.ViewDirection, view.Origin))) { using (var transactionGroup = new TransactionGroup(doc)) { transactionGroup.Start(); using (var tr = new Transaction(doc, trName)) { tr.Start(); if (!view.CropBoxActive) { view.CropBoxActive = true; view.CropBoxVisible = false; } cropRegionShapeManager.SetCropShape(curveLoop); tr.Commit(); } // reset crop using (var tr = new Transaction(doc, trName)) { tr.Start(); cropRegionShapeManager.RemoveCropRegionShape(); tr.Commit(); } transactionGroup.Assimilate(); } } else { // Не удалось получить валидную прямоугольную область. Попробуйте еще раз MessageBox.Show(Language.GetItem("h6")); } }
/// <summary> /// Выполнить процедуру слияния выбранных размеров /// </summary> public void MergeExecute() { var selection = _application.ActiveUIDocument.Selection; var doc = _application.ActiveUIDocument.Document; var prompt = Language.GetItem(new ModPlusConnector().Name, "h1"); const double tol = 0.0001; var elementsIds = new FilteredElementCollector(doc, doc.ActiveView.Id) .WhereElementIsNotElementType() .Select(e => e.Id.IntegerValue) .ToList(); while (true) { try { var dimensions = selection .PickElementsByRectangle(new DimensionsFilter(), prompt) .OfType <Dimension>().ToList(); var byDimLineDictionary = new Dictionary <Line, List <Dimension> >(); foreach (var dimension in dimensions) { if (!(dimension.Curve is Line line)) { continue; } var isMatch = false; foreach (var pair in byDimLineDictionary) { if ((Math.Abs(pair.Key.Origin.DistanceTo(line.Origin)) < tol && Math.Abs(Math.Abs(pair.Key.Direction.DotProduct(line.Direction)) - 1) < tol) || Math.Abs(Math.Abs(pair.Key.Direction.DotProduct(Line.CreateBound(pair.Key.Origin, line.Origin).Direction)) - 1) < tol) { isMatch = true; pair.Value.Add(dimension); break; } } if (!isMatch) { byDimLineDictionary.Add(line, new List <Dimension> { dimension }); } } var transactionName = Language.GetFunctionLocalName(new ModPlusConnector()); if (string.IsNullOrEmpty(transactionName)) { transactionName = "Merge dimensions"; } using (var t = new TransactionGroup(doc, transactionName)) { t.Start(); foreach (var pair in byDimLineDictionary) { if (pair.Value.Count < 1) { continue; } try { using (var tr = new Transaction(doc, "Merge dims")) { tr.Start(); var referenceArray = new ReferenceArray(); var view = pair.Value.First().View; var type = pair.Value.First().DimensionType; var dimsData = new List <DimData>(); foreach (var d in pair.Value) { if (d.NumberOfSegments > 0) { dimsData.AddRange(from DimensionSegment segment in d.Segments select new DimData(segment)); } else { dimsData.Add(new DimData(d)); } foreach (Reference reference in d.References) { if (reference.ElementId != ElementId.InvalidElementId && !elementsIds.Contains(reference.ElementId.IntegerValue)) { continue; } if (reference.ElementId != ElementId.InvalidElementId && doc.GetElement(reference.ElementId) is Grid grid) { referenceArray.Append(new Reference(grid)); } else if (reference.ElementId != ElementId.InvalidElementId && doc.GetElement(reference.ElementId) is Level level) { referenceArray.Append(new Reference(level)); } else { referenceArray.Append(reference); } } } if (doc.Create.NewDimension(view, pair.Key, referenceArray, type) is Dimension createdDimension) { if (ModPlus_Revit.Utils.Dimensions.TryRemoveZeroes(createdDimension, out referenceArray)) { if (doc.Create.NewDimension(view, pair.Key, referenceArray, type) is Dimension reCreatedDimension) { doc.Delete(createdDimension.Id); RestoreTextFields(reCreatedDimension, dimsData); } } else { RestoreTextFields(createdDimension, dimsData); } doc.Delete(pair.Value.Select(d => d.Id).ToList()); } tr.Commit(); } } catch (Exception exception) { ExceptionBox.Show(exception); } } t.Assimilate(); } } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { break; } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; _uidoc = uiapp.ActiveUIDocument; _doc = _uidoc.Document; try { using (TransactionGroup transGroup = new TransactionGroup(_doc)) { transGroup.Start("Placing a void family"); using (var trans = new Transaction(_doc)) { trans.Start("Placing a void family"); FamilyInstance fi = CreateVoid(GetFamilySymbol()); fi.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(UnitUtils.ConvertToInternalUnits(100, DisplayUnitType.DUT_MILLIMETERS)); fi.LookupParameter("width")?.Set(UnitUtils.ConvertToInternalUnits(300, DisplayUnitType.DUT_MILLIMETERS)); fi.LookupParameter("length")?.Set(UnitUtils.ConvertToInternalUnits(300, DisplayUnitType.DUT_MILLIMETERS)); fi.LookupParameter("depth")?.Set(UnitUtils.ConvertToInternalUnits(700, DisplayUnitType.DUT_MILLIMETERS)); if (trans.Commit() != TransactionStatus.Committed) { return(Result.Failed); } IEnumerable <Element> intersects = GetIntersectsBoundingBox(fi); trans.Start("Adding cuts"); foreach (Element intersect in intersects) { if (InstanceVoidCutUtils.CanBeCutWithVoid(intersect)) { InstanceVoidCutUtils.AddInstanceVoidCut(_doc, intersect, fi); } } if (trans.Commit() != TransactionStatus.Committed) { return(Result.Failed); } } transGroup.Assimilate(); } } catch (OperationCanceledException) { return(Result.Failed); } catch (Exception e) { e.ShowRevitDialog(); return(Result.Failed); } return(Result.Succeeded); }
const double labelTextOffset = 0.005; // 5mm, defined in paper space #endregion #region InterfaceImplementation /// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document document = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.DB.View view = commandData.View; // find major and minor station arrow styles FilteredElementCollector fec = new FilteredElementCollector(document); Element majorStationLeaderArrowheadType = fec.OfClass(typeof(ElementType)) .Cast <ElementType>() .FirstOrDefault(x => x.Name.Contains(majorStationLeaderArrowheadName)); Element minorStationLeaderArrowheadType = fec.OfClass(typeof(ElementType)) .Cast <ElementType>() .FirstOrDefault(x => x.Name.Contains(minorStationLeaderArrowheadName)); if (majorStationLeaderArrowheadType == null || minorStationLeaderArrowheadType == null) { TaskDialog td = new TaskDialog("Missing arrowheads"); td.MainContent = "In Manage>Additional Settings>Arrowheads, create two styles of arrowheads, named\r\n" + "Major Station Arrowhead and Minor Station Arrowhead"; td.Show(); return(Result.Failed); } // find major and minor station label types; if not there, create them SpotDimensionType majorLabelType = fec.OfClass(typeof(SpotDimensionType)) .Cast <SpotDimensionType>() .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(majorStationSetLabelTypeName)); SpotDimensionType minorLabelType = fec.OfClass(typeof(SpotDimensionType)) .Cast <SpotDimensionType>() .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(minorStationSetLabelTypeName)); SpotDimensionType curvatureLabelType = fec.OfClass(typeof(SpotDimensionType)) .Cast <SpotDimensionType>() .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(horizontalCurvatureChangeLabelTypeName)); using (Transaction t = new Transaction(document, "Create major station labels")) { t.Start(); if (majorLabelType == null) { // create major station label type with the given arrowhead style majorLabelType = document.GetElement(AlignmentStationLabel.CreateRecommendedTypeForSet(document)) as SpotDimensionType; majorLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(majorStationLeaderArrowheadType.Id); majorLabelType.Name = majorStationSetLabelTypeName; } if (minorLabelType == null) { // create minor station label type with the given arrowhead style // exclude the station text, which leave only the arrowheads // make the minor station's color grey // make the text 60% of the original value, in case text is later turned on minorLabelType = document.GetElement(AlignmentStationLabel.CreateRecommendedTypeForSet(document)) as SpotDimensionType; minorLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(minorStationLeaderArrowheadType.Id); minorLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_INCLUDE_STATION).Set(0); minorLabelType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(8421504 /* 127*2^0 + 127*2^8 + 127*2^16: grey */); Parameter textSizeParam = minorLabelType.get_Parameter(BuiltInParameter.TEXT_SIZE); textSizeParam.Set(textSizeParam.AsDouble() * 0.6); minorLabelType.Name = minorStationSetLabelTypeName; } if (curvatureLabelType == null) { // create a new label type, based on the default alignment station label type, // but with some adjustments to the label contents, as described below ElementType defaultAlignmentLabelType = document.GetElement( document.GetDefaultElementTypeId(ElementTypeGroup.AlignmentStationLabelType)) as ElementType; curvatureLabelType = defaultAlignmentLabelType.Duplicate(horizontalCurvatureChangeLabelTypeName) as SpotDimensionType; curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_COORDINATE_BASE).Set(1); // "Shared" coordinate base // Label position and content curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_ROTATE_WITH_COMPONENT).Set(0); // do not rotate with component curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TEXT_ORIENTATION).Set(0); // horizontal text curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TEXT_LOCATION).Set(0); // text location above leader curvatureLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_INCLUDE_STATION).Set(1); // include station curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_COORDINATE_INCLUDE_ELEVATION).Set(0); // do not include elevation curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_BOT_VALUE).Set(0); // do not include bottom value curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TOP_VALUE).Set(0); // do not include top value curvatureLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_IND_STATION).Set(""); // empty station indicator // Text curvatureLabelType.get_Parameter(BuiltInParameter.DIM_TEXT_BACKGROUND).Set(0); // nontransparent text curvatureLabelType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(255 /* 255*2^0 + 0*2^8 + 0*2^16: red */); // text in red color Parameter textSizeParam = curvatureLabelType.get_Parameter(BuiltInParameter.TEXT_SIZE); textSizeParam.Set(textSizeParam.AsDouble() * 0.6); // text size 60% of default // Leader curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(ElementId.InvalidElementId); // no leader arrowhead } t.Commit(); } // create major and minor station label sets ElementId alignmentId = AlignmentSelectionFilter.SelectAlignment(document); Alignment alignment = Alignment.Get(document.GetElement(alignmentId)); // start placement from a multiple of the major station interval // make sure to compute the multiple in the proper unit system and then convert it back to internal units for further use double labelSetsPlacementStartStation = UnitUtils.ConvertFromInternalUnits(alignment.DisplayedStartStation, UnitTypeId.StationingMeters); labelSetsPlacementStartStation = Math.Ceiling(labelSetsPlacementStartStation / majorStationInterval) * majorStationInterval; labelSetsPlacementStartStation = UnitUtils.ConvertToInternalUnits(labelSetsPlacementStartStation, UnitTypeId.StationingMeters); var majorStations = new List <double>(); using (Transaction t = new Transaction(document, "Create major station labels")) { t.Start(); AlignmentStationLabelSetOptions options = new AlignmentStationLabelSetOptions(); options.Interval = UnitUtils.ConvertToInternalUnits(majorStationInterval, UnitTypeId.StationingMeters); options.Offset = UnitUtils.ConvertToInternalUnits(labelTextOffset, UnitTypeId.StationingMeters); options.StartStation = labelSetsPlacementStartStation; options.EndStation = alignment.DisplayedEndStation; options.TypeId = majorLabelType.Id; var labels = AlignmentStationLabel.CreateSet(alignment, view, options); foreach (var label in labels) { majorStations.Add(label.Station); } t.Commit(); } using (Transaction t = new Transaction(document, "Create minor station labels")) { t.Start(); AlignmentStationLabelSetOptions options = new AlignmentStationLabelSetOptions(); options.Interval = UnitUtils.ConvertToInternalUnits(minorStationInterval, UnitTypeId.StationingMeters); // setting text offset specification can be skipped, // as in this example the minor station labels do not include any label text, only leader arrowheads options.StartStation = labelSetsPlacementStartStation; options.EndStation = labelSetsPlacementStartStation + UnitUtils.ConvertToInternalUnits(majorStationInterval, UnitTypeId.StationingMeters); options.TypeId = minorLabelType.Id; // delete the minor station labels which overlap with the major ones var labels = AlignmentStationLabel.CreateSet(alignment, view, options); foreach (var label in labels) { foreach (var majorStation in majorStations) { if (MathComparisonUtils.IsAlmostEqual(label.Station, majorStation)) { label.Element.Pinned = false; document.Delete(label.Element.Id); break; } } } t.Commit(); } if (view.ViewType == ViewType.FloorPlan || view.ViewType == ViewType.CeilingPlan || view.ViewType == ViewType.EngineeringPlan) { IList <HorizontalCurveEndpoint> curveEndpoints = alignment.GetDisplayedHorizontalCurveEndpoints(); using (TransactionGroup tg = new TransactionGroup(document, "Create horizontal curvature changes labels")) { tg.Start(); double previousStation = alignment.DisplayedStartStation; foreach (var curveEndpoint in curveEndpoints) { using (Transaction t = new Transaction(document, "Create one horizontal curvature change label")) { double thisStation = curveEndpoint.Station; // skip placing curvature labels at the start and end points of the alignment if (MathComparisonUtils.IsAlmostEqual((alignment.DisplayedStartStation), thisStation) || MathComparisonUtils.IsAlmostEqual((alignment.DisplayedEndStation), thisStation)) { continue; } t.Start(); AlignmentStationLabelOptions options = new AlignmentStationLabelOptions(thisStation); options.HasLeader = false; options.TypeId = curvatureLabelType.Id; AlignmentStationLabel label = AlignmentStationLabel.Create(alignment, view, options); // regeneration is necessary before the label's positional properties (such as Origin)L can be properly evaluated document.Regenerate(); // set the shoulder and end to coincide, creating a leader pointing along the view's up direction SpotDimension dim = label.Element as SpotDimension; XYZ leaderDirection = view.UpDirection; // compute the distance to the previous label // if the previous label is too close, flip the placement direction { var dimBBox = dim.get_BoundingBox(view); double dimOffset = Math.Abs(dimBBox.Max.X - dimBBox.Min.X); if (MathComparisonUtils.IsGreaterThanOrAlmostEqual(dimOffset, thisStation - previousStation)) { leaderDirection = leaderDirection.Negate(); } } dim.HasLeader = true; dim.LeaderHasShoulder = true; dim.LeaderShoulderPosition = dim.Origin + leaderDirection * UnitUtils.ConvertToInternalUnits(labelTextOffset, UnitTypeId.StationingMeters) * view.Scale; dim.LeaderEndPosition = dim.LeaderShoulderPosition; dim.TextPosition = dim.LeaderShoulderPosition; previousStation = thisStation; t.Commit(); } } tg.Assimilate(); } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name); FamilyInstance myFamilyInstance_Departure = doc.GetElement(new ElementId(myWindow1.myIntUpDown_Middle2.Value.Value)) as FamilyInstance; FamilySymbol myFamilySymbol = doc.GetElement(myFamilyInstance_Departure.GetTypeId()) as FamilySymbol; IList <ElementId> placePointIds_1338 = AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(myFamilyInstance_Departure); ReferencePoint myReferencePoint_Departure = doc.GetElement(placePointIds_1338.First()) as ReferencePoint; Transform myTransform = myReferencePoint_Departure.GetCoordinateSystem(); int myIntTimeOut = 0; int myInt_ChangeCount = 0; double myDouble_ChangePosition = -1; /// TECHNIQUE 6 OF 19 ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ SET DEFAULT TYPE ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ///Demonstrates: ///SketchPlane ///PromptForFamilyInstancePlacement with the PromptForFamilyInstancePlacementOptions class ///DocumentChanged event that cancels the command and focuses the window using (TransactionGroup transGroup = new TransactionGroup(doc)) { transGroup.Start("Transform animation"); if (myBool_Cycle) { for (int i = 1; i <= myWindow1.myUpDown_CycleNumber.Value; i++) { for (int ii = 0; ii <= 24; ii++) { wait(100); if (true) //candidate for methodisation 202006141254 { if (myDouble_ChangePosition != ii) { myDouble_ChangePosition = ii; myWindow1.myLabel_ChangeCount.Content = myInt_ChangeCount++.ToString(); using (Transaction y = new Transaction(doc, "a Transform")) { y.Start(); myReferencePoint_Departure.SetCoordinateSystem(myWindow1.myListTransform_Interpolate[(int)myDouble_ChangePosition]); y.Commit(); } myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisZ, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisX, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisY, true); } } myWindow1.myLabel_Setting.Content = ii.ToString(); } } } if (!myBool_Cycle) { while (myWindow1.mySlideInProgress | myBool_RunOnce == true) { myBool_RunOnce = false; wait(100); myIntTimeOut++; if (true) //candidate for methodisation 202006141254 { if (myDouble_ChangePosition != myWindow1.mySlider_Interpolate.Value) { myDouble_ChangePosition = myWindow1.mySlider_Interpolate.Value; myWindow1.myLabel_ChangeCount.Content = myInt_ChangeCount++.ToString(); using (Transaction y = new Transaction(doc, "a Transform")) { y.Start(); myReferencePoint_Departure.SetCoordinateSystem(myWindow1.myListTransform_Interpolate[(int)myDouble_ChangePosition]); y.Commit(); } myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisZ, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisX, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisY, true); } } myWindow1.myLabel_Setting.Content = myWindow1.mySlider_Interpolate.Value.ToString(); if (myIntTimeOut == 400) { MessageBox.Show("Timeout"); break; } } } transGroup.Assimilate(); } } #region catch and finally catch (Exception ex) { _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE01_Part1_Interpolate" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } finally { } #endregion }
/// <summary> /// Shuffles all parameter values /// </summary> /// <param name="uiapp">The Revit application object</param> /// <param name="text">Caption of the transaction for the operation.</param> /// <param name="operation">A delegate to perform the operation on an instance of a door.</param> /// public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, double> > values) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; if (!doc.IsFamilyDocument) { Command.global_message = "Please run this command in a family document."; TaskDialog.Show("Message", Command.global_message); } int counter = 0; int max = values.Count(); string current = ""; if ((uidoc != null)) { using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change")) { tg.Start(); string s = "{0} of " + max.ToString() + String.Format(" elements processed. ", counter.ToString()) + "{1}"; string caption = "Processing .."; using (ProgressBarView pbv = new ProgressBarView(caption, s, max)) { foreach (var value in values) { current = value.Item1; if (pbv.getAbortFlag()) { break; } pbv.Increment(current); //Increment the ProgressBar using (Transaction trans = new Transaction(uidoc.Document)) { FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); failureHandlingOptions.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(failureHandlingOptions); FamilyManager mgr = doc.FamilyManager; FamilyParameter fp = mgr.get_Parameter(value.Item1); // Since we'll modify the document, we need a transaction // It's best if a transaction is scoped by a 'using' block // The name of the transaction was given as an argument if (trans.Start(text) == TransactionStatus.Started) { if (fp.IsDeterminedByFormula) { continue; //Cannot change parameters driven by formulas } if (fp.IsReporting) { continue; //Cannot change reporting parameters } mgr.Set(fp, value.Item2); doc.Regenerate(); trans.Commit(); uidoc.RefreshActiveView(); if (failureHandler.ErrorMessage != "") { RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage)); } else { RequestError.NotifyLog += $"{fp.Definition.Name} was shuffled.{Environment.NewLine}"; } } } } } tg.Assimilate(); if (!String.IsNullOrEmpty(RequestError.NotifyLog)) { var lines = RequestError.NotifyLog.Split('\n').Length - 1; RequestError.NotifyLog += $"{Environment.NewLine}{lines.ToString()} parameters have been processed sucessfully."; } } } }
/// <summary> /// Moves a subregion and the associated topography to a new user-selected location. /// </summary> /// <param name="uiDoc">The document.</param> private void MoveSubregionAndPoints(UIDocument uiDoc) { Document doc = uiDoc.Document; // Pick subregion TopographySurface subregion = SiteUIUtils.PickSubregion(uiDoc); TopographySurface toposurface = SiteEditingUtils.GetTopographySurfaceHost(subregion); IList <XYZ> points = SiteEditingUtils.GetPointsFromSubregionExact(subregion); XYZ sourceLocation = SiteEditingUtils.GetCenterOf(subregion); // Pick target location XYZ targetPoint = SiteUIUtils.PickPointNearToposurface(uiDoc, toposurface, "Pick point to move to"); // Delta for the move XYZ delta = targetPoint - sourceLocation; // All changes are added to one transaction group - will create one undo item using (TransactionGroup moveGroup = new TransactionGroup(doc, "Move subregion and points")) { moveGroup.Start(); // Get elevation of region in current location IList <XYZ> existingPointsInCurrentLocation = subregion.GetPoints(); double existingElevation = SiteEditingUtils.GetAverageElevation(existingPointsInCurrentLocation); // Move subregion first - allows the command delete existing points and adjust elevation to surroundings using (Transaction t2 = new Transaction(doc, "Move subregion")) { t2.Start(); ElementTransformUtils.MoveElement(doc, subregion.Id, delta); t2.Commit(); } // The boundary points for the subregion cannot be deleted, since they are generated // to represent the subregion boundary rather than representing real points in the host. // Get non-boundary points only to be deleted. IList <XYZ> existingPointsInNewLocation = SiteEditingUtils.GetNonBoundaryPoints(subregion); // Average elevation of all points in the subregion. double newElevation = SiteEditingUtils.GetAverageElevation(subregion.GetPoints()); // Adjust delta for elevation based on calculated values delta = SiteEditingUtils.MoveXYZToElevation(delta, newElevation - existingElevation); // Edit scope for points changes using (TopographyEditScope editScope = new TopographyEditScope(doc, "Edit TS")) { editScope.Start(toposurface.Id); using (Transaction t = new Transaction(doc, "Move points")) { t.Start(); // Delete existing points from target region if (existingPointsInNewLocation.Count > 0) { toposurface.DeletePoints(existingPointsInNewLocation); } // Move points from source region toposurface.MovePoints(points, delta); t.Commit(); } editScope.Commit(new TopographyEditFailuresPreprocessor()); } moveGroup.Assimilate(); } }
public static Result Execute ( UIApplication app, View view, IDictionary <string, string> JournalData, string filePath, ref string message ) { var result = Result.Failed; if ((result = ReadFromFile(filePath, out var definition)) == Result.Succeeded) { using (definition) { bool enableSolutions = GH_Document.EnableSolutions; var currentCulture = Thread.CurrentThread.CurrentCulture; try { using (var transGroup = new TransactionGroup(app.ActiveUIDocument.Document)) { transGroup.Start(Path.GetFileNameWithoutExtension(definition.Properties.ProjectFileName)); GH_Document.EnableSolutions = true; definition.Enabled = true; definition.ExpireSolution(); var inputs = GetInputParams(definition); result = PromptForInputs(app.ActiveUIDocument, inputs, out var values); if (result != Result.Succeeded) { return(result); } // Update input volatile data values foreach (var value in values) { value.Key.AddVolatileDataList(new Grasshopper.Kernel.Data.GH_Path(0), value.Value); } Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; using (var modal = new Rhinoceros.ModalScope()) { definition.NewSolution(false, GH_SolutionMode.Silent); do { if (modal.Run(false, false) == Result.Failed) { return(Result.Failed); } } while (definition.ScheduleDelay >= GH_Document.ScheduleRecursive); } Thread.CurrentThread.CurrentCulture = currentCulture; if (definition.SolutionState == GH_ProcessStep.Aborted) { message = $"Solution aborted by user after ~{ definition.SolutionSpan.TotalSeconds} seconds"; return(Result.Cancelled); } transGroup.Assimilate(); } } catch (Exception e) { message = e.Message; return(Result.Failed); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; GH_Document.EnableSolutions = enableSolutions; } } } return(result); }
/// <summary> /// 可以理解为简单工厂模式 /// </summary> /// <param name="uiapp"></param> public void Execute(UIApplication uiapp) { #region 与revit文档交互入口 UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; View acvtiView = doc.ActiveView; #endregion #region 将Revit窗口设置为前台窗口,鼠标焦点可即时捕捉 IntPtr activeMainWindow = Autodesk.Windows.ComponentManager.ApplicationWindow;// 获得当前窗口句柄 SetActiveWindow(activeMainWindow); #endregion TransactionGroup transGroupParkingPlace = new TransactionGroup(doc);//开启事务组 var window = APP.MainWindow; try { switch (Request.Take())//Request.Take()数据提取 只能有一次 { case RequestId.None: { break; } case RequestId.SelDieectionShpaesByRectangle: { transGroupParkingPlace.Start("框选DirectionShapes"); SelDieectionShpaesByRectangle selDieectionShpaesByRectangle = new SelDieectionShpaesByRectangle(uiapp); selDieectionShpaesByRectangle.Execute(); GC.Collect(); break; } case RequestId.SetSurfaceTransparency: { transGroupParkingPlace.Start("框选DirectionShapes"); SetSurfaceTransparency setSurfaceTransparency = new SetSurfaceTransparency(uiapp); setSurfaceTransparency.Execute(); GC.Collect(); break; } case RequestId.CommentElementId: { transGroupParkingPlace.Start("解锁所有已锁定元素"); CommentElementId commentElementId = new CommentElementId(uiapp); commentElementId.Execute(); GC.Collect(); break; } case RequestId.Test: { transGroupParkingPlace.Start("普通测试"); Test test = new Test(uiapp); test.Execute(); GC.Collect(); break; } default: { GC.Collect(); break; } } transGroupParkingPlace.Assimilate(); } catch (Exception ex) { GC.Collect(); TaskDialog.Show("error", ex.Message); transGroupParkingPlace.RollBack(); } finally { GC.Collect(); window.WakeUp(); window.Activate(); } } //execute
private void AlignTag(UIDocument UIDoc, AlignType alignType, TransactionGroup txg) { // Get the handle of current document. Document doc = UIDoc.Document; ICollection <ElementId> selectedIds = UIDoc.Selection.GetElementIds(); // 1. First Proposed Change // First check if there is something that's been seleted, and if so - operate on that // However, if the Uidoc.Slection is empty, prompt for selection. // This allows you to stay on the 'Add-ins' Tab and keep using the 'Align' tab without going back and forth to 'Modify' // TO-DO: Should we disselect after we are done? (delete the boolean stuff if you don't think it's worth disselecting) bool empty = false; using (Transaction tx = new Transaction(doc)) { txg.Start("Align Tag"); if (selectedIds.Count == 0) { empty = true; IList <Reference> selectedReferences = UIDoc.Selection.PickObjects(ObjectType.Element, "Pick elements to be aligned"); selectedIds = Tools.RevitReferencesToElementIds(doc, selectedReferences); UIDoc.Selection.SetElementIds(selectedIds); } List <AnnotationElement> annotationElements = RetriveAnnotationElementsFromSelection(UIDoc, tx); txg.RollBack(); txg.Start("Align Tag"); tx.Start("Align Tags"); if (annotationElements.Count > 1) { View currentView = doc.ActiveView; XYZ displacementDirection = currentView.UpDirection; switch (alignType) { case AlignType.Left: AnnotationElement farthestAnnotation = annotationElements.OrderBy(x => x.UpLeft.X).FirstOrDefault(); foreach (AnnotationElement annotationElement in annotationElements) { XYZ resultingPoint = new XYZ(farthestAnnotation.UpLeft.X, annotationElement.UpLeft.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Left); } break; case AlignType.Right: farthestAnnotation = annotationElements.OrderByDescending(x => x.UpRight.X).FirstOrDefault(); foreach (AnnotationElement annotationElement in annotationElements) { XYZ resultingPoint = new XYZ(farthestAnnotation.UpRight.X, annotationElement.UpRight.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Right); } break; case AlignType.Up: farthestAnnotation = annotationElements.OrderByDescending(x => x.UpRight.Y).FirstOrDefault(); foreach (AnnotationElement annotationElement in annotationElements) { XYZ resultingPoint = new XYZ(annotationElement.UpRight.X, farthestAnnotation.UpRight.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Up); } break; case AlignType.Down: farthestAnnotation = annotationElements.OrderBy(x => x.DownRight.Y).FirstOrDefault(); foreach (AnnotationElement annotationElement in annotationElements) { XYZ resultingPoint = new XYZ(annotationElement.DownRight.X, farthestAnnotation.DownRight.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Down); } break; case AlignType.Center: //On the same vertical axe List <AnnotationElement> sortedAnnotationElements = annotationElements.OrderBy(x => x.UpRight.X).ToList(); AnnotationElement rightAnnotation = sortedAnnotationElements.LastOrDefault(); AnnotationElement leftAnnotation = sortedAnnotationElements.FirstOrDefault(); double XCoord = (rightAnnotation.Center.X + leftAnnotation.Center.X) / 2; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(XCoord, annotationElement.Center.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Center); } break; case AlignType.Middle: //On the same horizontal axe sortedAnnotationElements = annotationElements.OrderBy(x => x.UpRight.Y).ToList(); AnnotationElement upperAnnotation = sortedAnnotationElements.LastOrDefault(); AnnotationElement lowerAnnotation = sortedAnnotationElements.FirstOrDefault(); double YCoord = (upperAnnotation.Center.Y + lowerAnnotation.Center.Y) / 2; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(annotationElement.Center.X, YCoord, 0); annotationElement.MoveTo(resultingPoint, AlignType.Middle); } break; case AlignType.Vertically: sortedAnnotationElements = annotationElements.OrderBy(x => x.UpRight.Y).ToList(); upperAnnotation = sortedAnnotationElements.LastOrDefault(); lowerAnnotation = sortedAnnotationElements.FirstOrDefault(); double spacing = (upperAnnotation.Center.Y - lowerAnnotation.Center.Y) / (annotationElements.Count - 1); int i = 0; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(annotationElement.Center.X, lowerAnnotation.Center.Y + i * spacing, 0); annotationElement.MoveTo(resultingPoint, AlignType.Vertically); i++; } break; case AlignType.Horizontally: sortedAnnotationElements = annotationElements.OrderBy(x => x.UpRight.X).ToList(); rightAnnotation = sortedAnnotationElements.LastOrDefault(); leftAnnotation = sortedAnnotationElements.FirstOrDefault(); spacing = (rightAnnotation.Center.X - leftAnnotation.Center.X) / (annotationElements.Count - 1); i = 0; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(leftAnnotation.Center.X + i * spacing, annotationElement.Center.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.Horizontally); i++; } break; case AlignType.UntangleVertically: sortedAnnotationElements = annotationElements.OrderBy(y => y.GetLeaderEnd().Y).ToList(); upperAnnotation = sortedAnnotationElements.FirstOrDefault(); spacing = 0; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(annotationElement.UpLeft.X, upperAnnotation.UpLeft.Y + spacing, 0); annotationElement.MoveTo(resultingPoint, AlignType.UntangleVertically); spacing = spacing + (annotationElement.UpLeft.Y - annotationElement.DownLeft.Y); } break; case AlignType.UntangleHorizontally: sortedAnnotationElements = annotationElements.OrderBy(x => x.GetLeaderEnd().X).ToList(); leftAnnotation = sortedAnnotationElements.FirstOrDefault(); spacing = 0; foreach (AnnotationElement annotationElement in sortedAnnotationElements) { XYZ resultingPoint = new XYZ(leftAnnotation.UpLeft.X + spacing, annotationElement.UpLeft.Y, 0); annotationElement.MoveTo(resultingPoint, AlignType.UntangleHorizontally); spacing = spacing + (annotationElement.UpRight.X - annotationElement.UpLeft.X); } break; default: break; } } tx.Commit(); txg.Assimilate(); } // Disselect if the selection was empty to begin with if (empty) { selectedIds = new List <ElementId> { ElementId.InvalidElementId } } ; UIDoc.Selection.SetElementIds(selectedIds); } }
/// <summary> /// This method implements the external command within /// Revit. /// </summary> /// <param name="commandData">An ExternalCommandData /// object which contains reference to Application and /// View needed by external command.</param> /// <param name="message">Error message can be returned /// by external command. This will be displayed only if /// the command status was "Failed". There is a limit /// of 1023 characters for this message; strings longer /// than this will be truncated.</param> /// <param name="elements">Element set indicating /// problem elements to display in the failure dialog. /// This will be used only if the command status was /// "Failed".</param> /// <returns>The result indicates if the execution /// fails, succeeds, or was canceled by user. If it /// does not succeed, Revit will undo any changes made /// by the external command.</returns> Result IExternalCommand.Execute( ExternalCommandData commandData, ref string message , ElementSet elements) { ResourceManager res_mng = new ResourceManager( GetType()); ResourceManager def_res_mng = new ResourceManager( typeof(Properties.Resources)); Result result = Result.Failed; try { UIApplication ui_app = commandData?.Application ; UIDocument ui_doc = ui_app?.ActiveUIDocument; Application app = ui_app?.Application; Document doc = ui_doc?.Document; /* Wrap all transactions into the transaction * group. At first we get the transaction group * localized name. */ var tr_gr_name = UIBuilder.GetResourceString( GetType(), typeof(Properties.Resources), "_transaction_group_name"); using (var tr_gr = new TransactionGroup(doc, tr_gr_name)) { if (TransactionStatus.Started == tr_gr .Start()) { /* Here do your work or the set of * works... */ if (DoWork(commandData, ref message, elements)) { if (TransactionStatus.Committed == tr_gr.Assimilate()) { result = Result.Succeeded; } } else { tr_gr.RollBack(); } } } } catch (Exception ex) { TaskDialog.Show(def_res_mng.GetString("_Error") , ex.Message); result = Result.Failed; } finally { res_mng.ReleaseAllResources(); def_res_mng.ReleaseAllResources(); } return(result); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // There is likely an easier way to do this using // an exclusion filter but this being my first foray // into filtering with Revit, I couldn't get that working. FilteredElementCollector filt = new FilteredElementCollector(doc); List <ElementId> refIDs = filt.OfClass(typeof(ReferencePlane)).ToElementIds().ToList(); using (TransactionGroup tg = new TransactionGroup(doc)) { tg.Start("Remove Un-Used Reference Planes"); foreach (ElementId id in refIDs) { var filt2 = new ElementClassFilter(typeof(FamilyInstance)); var filt3 = new ElementParameterFilter(new FilterElementIdRule(new ParameterValueProvider(new ElementId(BuiltInParameter.HOST_ID_PARAM)), new FilterNumericEquals(), id)); var filt4 = new LogicalAndFilter(filt2, filt3); var thing = new FilteredElementCollector(doc); using (Transaction t = new Transaction(doc)) { // Check for hosted elements on the plane if (thing.WherePasses(filt4).Count() == 0) { t.Start("Do The Thing"); #if Revit2018 if (doc.GetElement(id).GetDependentElements(new ElementClassFilter(typeof(FamilyInstance))).Count == 0) { doc.Delete(id); } t.Commit(); #else // Make sure there is nothing measuring to the plane if (doc.Delete(id).Count() > 1) { t.Dispose(); // Skipped } else { // Deleted t.Commit(); } #endif } else { // Skipped } } } tg.Assimilate(); } return(Result.Succeeded); }
private bool CopyRoomData(List <FamilyInstance> doorInstances) { bool result = true; try { StringBuilder strBuilder = new StringBuilder(); using (TransactionGroup tg = new TransactionGroup(m_doc, "Copy Room Data")) { tg.Start(); try { foreach (FamilyInstance door in doorInstances) { using (Transaction trans = new Transaction(m_doc, "Copy Room")) { trans.Start(); try { DoorProperties dp = AssignToFromRoom(door); if (null != dp.ToRoom) { string roomNumber = GetRoomNumber(dp.ToRoom); string roomName = GetRoomName(dp.ToRoom); Parameter toParam = door.LookupParameter(toRoomNumber); if (null != toParam) { toParam.Set(roomNumber); } toParam = door.LookupParameter(toRoomName); if (null != toParam) { toParam.Set(roomName); } } if (null != dp.FromRoom) { string roomNumber = GetRoomNumber(dp.FromRoom); string roomName = GetRoomName(dp.FromRoom); Parameter fromParam = door.LookupParameter(fromRoomNumber); if (null != fromParam) { fromParam.Set(roomNumber); } fromParam = door.LookupParameter(fromRoomName); if (null != fromParam) { fromParam.Set(roomName); } } trans.Commit(); } catch (Exception ex) { result = false; strBuilder.AppendLine(door.Id.IntegerValue + "\t" + door.Name + ": " + ex.Message); trans.RollBack(); } } } tg.Assimilate(); } catch (Exception ex) { string message = ex.Message; tg.RollBack(); } } if (strBuilder.Length > 0) { MessageBox.Show("The following doors have been skipped due to some issues.\n\n" + strBuilder.ToString(), "Skipped Door Elements", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { MessageBox.Show("Failed to copy system room data to shared parameters.\n" + ex.Message, "Copy Room Data", MessageBoxButtons.OK, MessageBoxIcon.Warning); result = false; } return(result); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; ICollection <ElementId> refplaneids = new FilteredElementCollector(doc) .OfClass(typeof(ReferencePlane)) .ToElementIds(); using (TransactionGroup tg = new TransactionGroup(doc)) { tg.Start("Remove unused reference planes"); FilteredElementCollector instances = new FilteredElementCollector(doc) .OfClass(typeof(FamilyInstance)); Dictionary <ElementId, int> toKeep = new Dictionary <ElementId, int>(); foreach (FamilyInstance i in instances) { // Ensure the element is hosted if (null != i.Host) { ElementId hostId = i.Host.Id; // Check list to see if we've already added this plane if (!toKeep.ContainsKey(hostId)) { toKeep.Add(hostId, 0); } ++toKeep[hostId]; } } // Loop through reference planes and // delete the ones not in the list toKeep. foreach (ElementId refid in refplaneids) { if (!toKeep.ContainsKey(refid)) { using (Transaction t = new Transaction(doc)) { t.Start("Removing plane " + doc.GetElement(refid).Name); // Ensure there are no dimensions measuring to the plane if (doc.Delete(refid).Count > 1) { t.Dispose(); } else { t.Commit(); } } } } tg.Assimilate(); } return(Result.Succeeded); }
private void button2DCreate_Click(object sender, RoutedEventArgs e) { try { var areaList = (List <AreaProperties>)dataGridArea.ItemsSource; var selectedAreas = areaList.Where(x => x.IsSelected).ToList(); if (selectedAreas.Any()) { statusLable.Text = "Creating 2D Masses .."; progressBar.Visibility = System.Windows.Visibility.Visible; progressBar.Value = 0; progressBar.Maximum = selectedAreas.Count(); var createdParamMaps = massConfig.UpdateType != ParameterUpdateType.None && massConfig.MassParameters.Count > 0; var updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue); using (var tg = new TransactionGroup(doc)) { tg.Start("Create 2D Masses"); try { double count = 0; foreach (var ap in selectedAreas) { using (var trans = new Transaction(doc)) { trans.Start("Create 2D Mass"); var options = trans.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new DuplicateWarningSwallower()); trans.SetFailureHandlingOptions(options); try { if (MassCreator.CreateAreaFace(doc, ap, out var createdMass)) { if (AreaDictionary.ContainsKey(ap.AreaUniqueId)) { var updatedArea = new AreaProperties(ap) { IsSelected = false, Linked2d = true, Linked2dMass = createdMass, ModifiedHost = false }; if (updatedArea.Linked3d && null != updatedArea.Linked3dMass) { updatedArea.ToolTip = "Mass 3D Id: " + updatedArea.Linked3dMass.MassId; updatedArea.ToolTip += "\nMass 2D Id: " + updatedArea.Linked2dMass.MassId; } else { updatedArea.ToolTip = "Mass 2D Id: " + updatedArea.Linked2dMass.MassId; } if (createdParamMaps) { var unused = UpdateParameter(ap.AreaElement, createdMass.MassElement); } AreaDictionary.Remove(ap.AreaUniqueId); AreaDictionary.Add(ap.AreaUniqueId, updatedArea); } } trans.Commit(); } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); trans.RollBack(); } } count++; Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, ProgressBar.ValueProperty, count); } DisplayAreaInfo(); tg.Assimilate(); } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); tg.RollBack(); MessageBox.Show("Failed to create 2d masses from the selected areas\n" + ex.Message, "Create 2D Masses from Areas", MessageBoxButton.OK, MessageBoxImage.Warning); } } progressBar.Visibility = System.Windows.Visibility.Hidden; statusLable.Text = "Ready"; } else { MessageBox.Show("Please select areas to update masses.", "Select Areas", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); MessageBox.Show("Failed to create 2d masses from the selected areas.\n" + ex.Message, "Create 2D Masses from Areas", MessageBoxButton.OK, MessageBoxImage.Warning); } }
/// <summary> /// Duplicates the input sheet a number of times. It allows for ViewDuplicateOption for dependent views. /// </summary> /// <param name="m_doc"></param> /// <param name="sourceSheet"></param> /// <param name="copies"></param> /// <param name="dependentOption"></param> private void DuplicateSheets(Document m_doc, ViewSheet sourceSheet, int copies, ViewDuplicateOption dependentOption) { // get Title Block FamilyInstance titleBlock = new FilteredElementCollector(m_doc) .OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks) .Cast <FamilyInstance>() .First(q => q.OwnerViewId == sourceSheet.Id); using (TransactionGroup tg = new TransactionGroup(m_doc, "Duplicate Sheet")) { tg.Start(); for (int i = 0; i < copies; i++) { // create unique sheet number string uniqueSheetNumber = Data.Helpers.CreateUniqueSheetNumber(m_doc, sourceSheet); using (Transaction t = new Transaction(m_doc, "Duplicate Sheet")) { t.Start(); // create new SHEET, new NUMBER and new NAME ViewSheet newSheet = ViewSheet.Create(m_doc, titleBlock.GetTypeId()); newSheet.SheetNumber = uniqueSheetNumber; newSheet.Name = sourceSheet.Name; #region Loop through viewports (except schedules) because GetAllPlacedViews() does not return Schedules foreach (ElementId eid in sourceSheet.GetAllPlacedViews()) { // get view element Autodesk.Revit.DB.View sourceView = m_doc.GetElement(eid) as Autodesk.Revit.DB.View; Autodesk.Revit.DB.View newView = null; // declare newView variable // DUPLICATE views // if view element is legend newView is equal to sourceView if (sourceView.ViewType == ViewType.Legend) { newView = sourceView; } else // for non-legend views { if (sourceView.GetPrimaryViewId() == ElementId.InvalidElementId) // if parent view { ElementId newViewId = sourceView.Duplicate(ViewDuplicateOption.WithDetailing); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } else // if dependent view { ElementId newViewId = sourceView.Duplicate(dependentOption); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } } // CREATE viewport and MOVE it foreach (Viewport vp in new FilteredElementCollector(m_doc).OfClass(typeof(Viewport))) { if (vp.SheetId == sourceSheet.Id && vp.ViewId == sourceView.Id) { XYZ sourceCenter = vp.GetBoxCenter(); ElementId sourceTypeId = vp.GetTypeId(); Viewport newViewport = Viewport.Create(m_doc, newSheet.Id, newView.Id, XYZ.Zero); newViewport.ChangeTypeId(sourceTypeId); Ana_NoOfViewports += 1; // add 1 to the viewport counter XYZ newCenter = newViewport.GetBoxCenter(); ElementTransformUtils.MoveElement(m_doc, newViewport.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } #endregion #region Loop through schedules foreach (ScheduleSheetInstance si in (new FilteredElementCollector(m_doc).OfClass(typeof(ScheduleSheetInstance)))) { if (si.OwnerViewId == sourceSheet.Id) { if (!si.IsTitleblockRevisionSchedule) { foreach (ViewSchedule viewSchedule in new FilteredElementCollector(m_doc).OfClass(typeof(ViewSchedule))) { if (si.ScheduleId == viewSchedule.Id) { XYZ sourceCenter = si.Point; ScheduleSheetInstance newSSheetInstance = ScheduleSheetInstance.Create(m_doc, newSheet.Id, viewSchedule.Id, XYZ.Zero); XYZ newCenter = newSSheetInstance.Point; ElementTransformUtils.MoveElement(m_doc, newSSheetInstance.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } } } #endregion t.Commit(); } } tg.Assimilate(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var doc = uidoc.Document; var sel = uidoc.Selection; var acview = uidoc.ActiveView; if (!(acview is ViewPlan)) { MessageBox.Show("请到平面视图执行此命令"); return(Result.Cancelled); } Category equipmentCategory = Category.GetCategory(doc, BuiltInCategory.OST_FireAlarmDevices); //电气设备集合 ElementCategoryFilter catefilter1 = new ElementCategoryFilter(BuiltInCategory.OST_FireAlarmDevices); ElementCategoryFilter catefilter2 = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures); ElementCategoryFilter catefilter3 = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalEquipment); var filterlist = new List <ElementFilter>() { catefilter3, catefilter2, catefilter1 }; LogicalOrFilter ElectricaldeviceOrfixturesFilter = new LogicalOrFilter(filterlist); var elecEquipCollector = new FilteredElementCollector(doc, acview.Id).WherePasses(ElectricaldeviceOrfixturesFilter).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList(); var fsInfoCol = new List <FsInfo>(); //LogHelper.LogWrite(); //MessageBox.Show("sec1:" + elecEquipCollector.Count); var namelist = elecEquipCollector.Select(m => m.Symbol.FamilyName); var namestring = string.Join("\n", namelist); //MessageBox.Show(namestring); foreach (FamilyInstance fs in elecEquipCollector) { var fsinfo = new FsInfo(fs); fsInfoCol.Add(fsinfo); } //电线折线集合 var wirecollector = new FilteredElementCollector(doc, acview.Id).OfClass(typeof(Wire)).Cast <Wire>().ToList(); var wirelineCol = new List <Line>(); foreach (Wire wire in wirecollector) { var lines = getwirelines(wire); wirelineCol.AddRange(lines); } //MessageBox.Show("sec2:" + wirecollector.Count); var wiretypes = doc.TCollector <WireType>(); string wiretypename = "DLcoverwiretype"; var coverwiretype = default(WireType); bool targetWireTypeexist = false; //var wiretypenames = wiretypes.Select(m => m.Name); coverwiretype = wiretypes.Where(m => m.Name == wiretypename)?.FirstOrDefault(); if (coverwiretype != null) { targetWireTypeexist = true; } var firswiretype = wiretypes.First(); TransactionGroup tsg = new TransactionGroup(doc, "创建电缆遮挡"); tsg.Start(); Transaction ts1 = new Transaction(doc, "创建电缆类型"); ts1.Start(); if (!targetWireTypeexist) { coverwiretype = firswiretype.Duplicate(wiretypename) as WireType; } ts1.Commit(); Transaction ts2 = new Transaction(doc, "覆盖"); ts2.Start(); //辅助计数 var count = default(long); foreach (var fsinfo in fsInfoCol) { foreach (Line line in wirelineCol) { #region fortest //var temins = (fsinfo.Id.GetElement(doc) as FamilyInstance); //if (temins.Symbol.FamilyName.Contains("单相空调插座")) //{ // MessageBox.Show(fsinfo.Outline1.Count.ToString()); // drawoutline(fsinfo.Outline1, doc); // //MessageBox.Show(fsinfo.Width.ToString() + Environment.NewLine + fsinfo.Height.ToString()); //} #endregion //添加遮挡导线 if (lineIntersecOutline(line, fsinfo.Outline1)) { CreateHideWire(doc, fsinfo, line, coverwiretype, WiringType.Chamfer, acview); //绘制外轮廓 //drawoutline(fsinfo.Outline1, doc); } } } //MessageBox.Show("inbox count:" + count.ToString()); ts2.Commit(); tsg.Assimilate(); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; using( TransactionGroup g = new TransactionGroup( doc ) ) { g.Start( "Cut Beam with Voids" ); // Retrieve or load cutting symbol FamilySymbol cuttingSymbol = RetrieveOrLoadCuttingSymbol( doc ); // Select beam to cut Selection sel = uidoc.Selection; FamilyInstance beam = null; try { Reference r = sel.PickObject( ObjectType.Element, new BeamSelectionFilter(), "Pick beam to cut" ); beam = doc.GetElement( r.ElementId ) as FamilyInstance; } catch( Autodesk.Revit.Exceptions .OperationCanceledException ) { return Result.Cancelled; } // Place cutting instances and apply cuts CutBeamWithVoid( beam, cuttingSymbol ); g.Assimilate(); // Calling Commit after Assimilate throws an // exception saying "The Transaction group has // not been started (its status is not // 'Started').." //g.Commit(); } return Result.Succeeded; }