Skip to content

Instantly share code, notes, and snippets.

@giobel
Last active April 3, 2024 23:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save giobel/a90eb49a0c322bb2f0c3adfbd1acc794 to your computer and use it in GitHub Desktop.
Save giobel/a90eb49a0c322bb2f0c3adfbd1acc794 to your computer and use it in GitHub Desktop.
# collection of C# macro functions.
# credits: boostyourbim, archilizer, archsmarter, don rudden
# ADN-DevTech/RevitTrainingMaterial
public void AssociateFamilyParameter(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference sel = uidoc.Selection.PickObject(ObjectType.Element, "Select element");
Element ele = doc.GetElement(sel);
Parameter eleMatParam = ele.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);
FamilyManager fm = doc.FamilyManager;
ICollection<ElementId> materials = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Materials).ToElementIds();
FamilyParameter famparam = fm.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);
using (Transaction t = new Transaction(doc, "Add Param")){
t.Start();
FamilyParameter p = fm.AddParameter("My Structural Material", BuiltInParameterGroup.PG_GENERAL, ParameterType.Material,true);
doc.FamilyManager.Set(p, materials.First());
fm.AssociateElementParameterToFamilyParameter(eleMatParam, p);
t.Commit();
}
}
// For a macro in Revit Zero State don't use the Document or the UIDocument, just the application
Application app = this.Application;
string[] filePath = System.IO.Directory.GetFiles(@"C:\Users\giovanni.brogiolo\Documents\Animation");
ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath[0]);
OpenOptions optionDetach = new OpenOptions();
optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
Document openDoc = app.OpenDocumentFile(modelP, optionDetach);
openDoc.Close(false);
// Find the closest UV point (on the centerline of the face) to a beam start or end point
private static void BeamStartUVPoint(Element beam, Face myFace, out XYZ choosenLocation, out XYZ beamDirection){
BoundingBoxUV bbox = myFace.GetBoundingBox();
double halfDepthU = (bbox.Min.U + bbox.Max.U)*0.5;
double halfDepthV = (bbox.Min.V + bbox.Max.V)*0.5;
//double length = Math.Abs(bbox.Min.U - bbox.Max.U);
UV start = bbox.Min;
UV end = bbox.Max;
//XYZ beamDirection = myFace.IsInside()
LocationCurve beamLine = beam.Location as LocationCurve;
XYZ stPt = beamLine.Curve.GetEndPoint(0);
XYZ endPt = beamLine.Curve.GetEndPoint(1);
List<UV> UVpoints = new List<UV>();
UVpoints.Add(new UV(bbox.Max.U, halfDepthV));
UVpoints.Add(new UV(bbox.Min.U, halfDepthV));
UVpoints.Add(new UV(halfDepthU, bbox.Max.V));
UVpoints.Add(new UV(halfDepthU, bbox.Min.V));
Dictionary<double, XYZ> ptOnSurfaces = new Dictionary<double,XYZ>();
foreach (UV pt in UVpoints) {
XYZ point = myFace.Evaluate(pt);
ptOnSurfaces.Add(stPt.DistanceTo(point), point); //if replaced with the beam end point change the beam direction
}
double closestDistanceToStart = ptOnSurfaces.Keys.Min();
choosenLocation = ptOnSurfaces[closestDistanceToStart];
beamDirection = beamLine.Curve.GetEndPoint(0) - beamLine.Curve.GetEndPoint(1); //invert if beam End Point is chosen
}//close method
# Export a Sheet from revit. xref the view exported by shared coordinates. rotate the layout viewport to match the revit view
# (set the cad viewport center to revit viewport center (by survey point coordinates => WCS))
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
[assembly: CommandClass(typeof(AutoCAD_2018_Plugin1.Commands))]
namespace AutoCAD_2018_Plugin1
{
public class Commands
{
[CommandMethod("TEST")]
public void Test()
{
var doc = AcAp.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
ed.WriteMessage("ciao bnello");
//var peo = new PromptEntityOptions("\nSelect the viewport");
//peo.SetRejectMessage("\nMust be a viewport.");
//peo.AddAllowedClass(typeof(Viewport), false);
//var viewportSelected = ed.GetEntity(peo);
//if (viewportSelected.Status != PromptStatus.OK)
// return;
//var brId = viewportSelected.ObjectId;
PromptPointResult pPtRes;
PromptPointOptions pPtOpts = new PromptPointOptions("");
// Prompt for the start point
pPtOpts.Message = "\nEnter the Revit viewport center: ";
pPtRes = doc.Editor.GetPoint(pPtOpts);
Point3d ptCenter = pPtRes.Value;
PromptDoubleOptions pdo1 = new PromptDoubleOptions("\nEnter angle in XY plane from X axis (deg): ");
PromptDoubleResult angleXY = ed.GetDouble(pdo1);
if (angleXY.Status != PromptStatus.OK)
return;
//Zoom(new Point3d(), new Point3d(), new Point3d(2987, 3072, 0), 1);
//Zoom(new Point3d(), new Point3d(), ptCenter, 1);
//Rotate(pdr1.Value, ptCenter);
ObjectId vpId = PickViewport(ed);
if (!vpId.IsNull)
{
//Twist the viewport
TwistViewport(vpId, ptCenter, DegToRad(angleXY.Value));
}
//using (Transaction Tx = db.TransactionManager.StartTransaction())
//{
// Orbit(doc, vtr, Vector3d.ZAxis, 17, ptCenter);
// Tx.Commit();
//}
}
static void Rotate(double pdr1, Point3d origin)
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database db = acDoc.Database;
var ed = acDoc.Editor;
using (Transaction Tx = db.TransactionManager.StartTransaction())
{
ViewTable vt = Tx.GetObject(db.ViewTableId, OpenMode.ForRead)
as ViewTable;
ViewTableRecord newView = ed.GetCurrentView();
newView.ViewDirection = ComputeViewDirection(
DegToRad(17), //DegToRad(pdr1),
DegToRad(0) //DegToRad(pdr2)
);
//newView.ViewTwist = DegToRad(pdr1);
//newView.ViewDirection.TransformBy(Matrix3d.Rotation(DegToRad(pdr2), Vector3d.ZAxis, origin));
//Matrix3d rotationMat = Matrix3d.Rotation(Math.PI / 10, Vector3d.ZAxis, Point3d.Origin);
//newView.ViewDirection.RotateBy(DegToRad(17), curUCS.Zaxis);
newView.Name = "VPNetView";
if (!vt.Has(newView.Name))
{
vt.UpgradeOpen();
vt.Add(newView);
Tx.AddNewlyCreatedDBObject(newView, true);
}
using (ViewTableRecord vtr = new ViewTableRecord())
{
vtr.CopyFrom(newView);
ed.SetCurrentView(vtr);
}
Tx.Commit();
}
}
static void Orbit(Document _doc, ViewTableRecord _vtr, Vector3d axis, double angle, Point3d origin)
{
// Adjust the ViewTableRecord
_vtr.ViewDirection = _vtr.ViewDirection.TransformBy(Matrix3d.Rotation(angle, axis, origin));
// Set it as the current view
_doc.Editor.SetCurrentView(_vtr);
}
static double DegToRad(double deg)
{
return deg * Math.PI / 180.0;
}
private static ObjectId PickViewport(Editor ed)
{
ObjectId id = ObjectId.Null;
PromptEntityOptions opt =
new PromptEntityOptions("\nPlease pick an viewport:");
opt.SetRejectMessage("\nInvalid pick: not a viewport.");
opt.AddAllowedClass(typeof(Viewport), true);
PromptEntityResult res = ed.GetEntity(opt);
if (res.Status == PromptStatus.OK)
{
id = res.ObjectId;
}
return id;
}
private static void TwistViewport(ObjectId vpId, Point3d target, double angle)
{
using (Transaction tran = vpId.Database.TransactionManager.StartTransaction())
{
Viewport vport = (Viewport)tran.GetObject(vpId, OpenMode.ForWrite);
vport.Locked = false;
vport.ViewDirection = Vector3d.ZAxis;
vport.ViewTarget = target;
vport.ViewCenter = Point2d.Origin;
vport.TwistAngle = Math.PI * 2 - angle;
//vport.Locked = true;
tran.Commit();
}
}
static Vector3d ComputeViewDirection(double angleInXyPlane, double angleFromXyPlane)
{
//Vector3d v1 = Vector3d.XAxis.RotateBy(angleInXyPlane, Vector3d.ZAxis);
Vector3d v1 = Vector3d.ZAxis.RotateBy(angleInXyPlane, Vector3d.ZAxis);
Vector3d v2 = v1.CrossProduct(Vector3d.ZAxis);
Vector3d viewDir = v1.RotateBy(angleFromXyPlane, v2);
return viewDir;
}
static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));
// Get the extents of the current space when no points
// or only a center point is provided
// Check to see if Model space is current
if (acCurDb.TileMode == true)
{
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Extmin;
pMax = acCurDb.Extmax;
}
}
else
{
// Check to see if Paper space is current
if (nCurVport == 1)
{
// Get the extents of Paper space
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Pextmin;
pMax = acCurDb.Pextmax;
}
}
else
{
// Get the extents of Model space
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Extmin;
pMax = acCurDb.Extmax;
}
}
}
// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Get the current view
using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
{
Extents3d eExtents;
// Translate WCS coordinates to DCS
Matrix3d matWCS2DCS;
matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
acView.ViewDirection,
acView.Target) * matWCS2DCS;
// If a center point is specified, define the min and max
// point of the extents
// for Center and Scale modes
if (pCenter.DistanceTo(Point3d.Origin) != 0)
{
pMin = new Point3d(pCenter.X - (acView.Width / 2),
pCenter.Y - (acView.Height / 2), 0);
pMax = new Point3d((acView.Width / 2) + pCenter.X,
(acView.Height / 2) + pCenter.Y, 0);
}
// Create an extents object using a line
using (Line acLine = new Line(pMin, pMax))
{
eExtents = new Extents3d(acLine.Bounds.Value.MinPoint,
acLine.Bounds.Value.MaxPoint);
}
// Calculate the ratio between the width and height of the current view
double dViewRatio;
dViewRatio = (acView.Width / acView.Height);
// Tranform the extents of the view
matWCS2DCS = matWCS2DCS.Inverse();
eExtents.TransformBy(matWCS2DCS);
double dWidth;
double dHeight;
Point2d pNewCentPt;
// Check to see if a center point was provided (Center and Scale modes)
if (pCenter.DistanceTo(Point3d.Origin) != 0)
{
dWidth = acView.Width;
dHeight = acView.Height;
if (dFactor == 0)
{
pCenter = pCenter.TransformBy(matWCS2DCS);
}
pNewCentPt = new Point2d(pCenter.X, pCenter.Y);
}
else // Working in Window, Extents and Limits mode
{
// Calculate the new width and height of the current view
dWidth = eExtents.MaxPoint.X - eExtents.MinPoint.X;
dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;
// Get the center of the view
pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5),
((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5));
}
// Check to see if the new width fits in current window
if (dWidth > (dHeight * dViewRatio)) dHeight = dWidth / dViewRatio;
// Resize and scale the view
if (dFactor != 0)
{
acView.Height = dHeight * dFactor;
acView.Width = dWidth * dFactor;
}
// Set the center of the view
acView.CenterPoint = pNewCentPt;
// Set the current view
acDoc.Editor.SetCurrentView(acView);
}
// Commit the changes
acTrans.Commit();
}
}
}
}
public void ChangeColumnLocation(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
DTPickFilter filterLines = new DTPickFilter();
Reference selLine = uidoc.Selection.PickObject(ObjectType.Element,filterLines, "Select Line");
Reference selColumn = uidoc.Selection.PickObject(ObjectType.Element, "Select Element");
Element eleCrv = doc.GetElement(selLine.ElementId);
Element eleColumn = doc.GetElement(selColumn.ElementId);
//line location curve
LocationCurve locCrv = eleCrv.Location as LocationCurve;
Curve crv = locCrv.Curve;
XYZ lineStart = crv.GetEndPoint(0);
XYZ lineEnd = crv.GetEndPoint(1);
//column Location curve
LocationCurve colLocCrv = eleColumn.Location as LocationCurve;
Curve colCrv = colLocCrv.Curve;
double dist1 = colCrv.GetEndPoint(0).DistanceTo(lineStart);
double dist2 = colCrv.GetEndPoint(0).DistanceTo(lineEnd);
using (Transaction t = new Transaction(doc)){
t.Start("Move column");
if (lineStart.Z <lineEnd.Z){
Line newColumnLine = Line.CreateBound(lineStart, lineEnd);
colLocCrv.Curve = newColumnLine;
}
else {
Line reverseLine = Line.CreateBound(lineEnd,lineStart);
colLocCrv.Curve = reverseLine;
}
t.Commit();
}//close using
}
// Change an existing directshape to a new geometry without recreating it
public void ChangeDS(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
List<Curve> profile = new List<Curve>();
// first create sphere with 2' radius
XYZ center = XYZ.Zero;
double radius = 5.0;
XYZ profile00 = center;
XYZ profilePlus = center + new XYZ(0, radius, 0);
XYZ profileMinus = center - new XYZ(0, radius, 0);
profile.Add(Autodesk.Revit.DB.Line.CreateBound(profilePlus, profileMinus));
profile.Add(Arc.Create(profileMinus, profilePlus, center + new XYZ(radius, 0, 0)));
CurveLoop curveLoop = CurveLoop.Create(profile);
SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);
options.MaterialId = new ElementId(39301);
Frame frame = new Frame(center, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY);
Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curveLoop }, 0, 2 * Math.PI, options);
IList<Reference> s = uidoc.Selection.PickObjects(ObjectType.Element,"select");
DirectShape ds = doc.GetElement(s.First()) as DirectShape;
using (Transaction t = new Transaction(doc, "isolate view")){
t.Start();
ds.SetShape(new GeometryObject[] { sphere });
t.Commit();
}
}
public void CheckedListTest(){
//access the default UIDocument and Document
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
//let's test everything is working
//TaskDialog.Show("Result", "Hello World");
//let's create a list to feed the Checked List
List<string> sheetNumberList = new List<string>(){"S101","S102","S103"};
//let's store the selected items in another list
List<string> selectedSheets = new List<string>();
StringBuilder sb = new StringBuilder(); //namespace System.Text
//add the windows form. Createa an instance on the form and display it.
using (var form = new CheckedListForm()){
//let's link the checked list form to the newly created list
form.checkedListSource = sheetNumberList;
form.ShowDialog();
//if the user hits cancel just drop out of macro
if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
foreach (string s in form.checkedItems) {
selectedSheets.Add(s);
sb.AppendLine(s);
}
}//close using
//to display the content of a list we can use StringBuilder
TaskDialog.Show("Selected", sb.ToString());
}//close macro
public ViewSheet GetElementViewSheet(Document doc, View elementView){
ViewSheet viewSh = null;
Parameter sheetNumber = elementView.LookupParameter("Sheet Number");
IList<Element> sheets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet)).ToElements();
for (int i = 0; i < sheets.Count(); i++) {
ViewSheet sht = sheets[i] as ViewSheet;
if (sht.SheetNumber.ToString() == sheetNumber.AsString()){
viewSh = sht;
break;
}
}
return viewSh;
}
public void CloudElement()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<ElementId> rev = Revision.GetAllRevisionIds(doc);
// get elements from user selection
List<Element> elements = new List<Element>();
foreach (Reference r in uidoc.Selection.PickObjects(ObjectType.Element))
{
Element e = doc.GetElement(r);
elements.Add(e);
//TaskDialog.Show("r", GetElementViewSheet(doc, e).Name);
}
using( TransactionGroup transGroup = new TransactionGroup( doc ) ){
using (Transaction t = new Transaction(doc)){
try{
transGroup.Start("Transaction Group");
List<Curve> curvesSheet = new List<Curve>();
//THIS ONLY WORKS BY ACTIVATING THE VIEWPORT AND SELECTING THE ELEMENTS. AUTOMATICALLY FIND THE SELECTED ELEMENT VIEW -> TBC
ViewSheet selectedViewSheet = GetElementViewSheet(doc, doc.ActiveView);
foreach (Element e in elements)
{
View elementView = doc.GetElement(e.OwnerViewId) as View;
if (elementView == null)
{
elementView = doc.ActiveView;
}
//MOVED OUT THE FOREACH LOOP -> ALL CLOUDS ARE GROUPED. WHAT IF WE HAVE MULTIPLE SHEETS?
//ViewSheet selectedViewSheet = GetElementViewSheet(doc, elementView);
//AUTOMATICALLY FIND THE SELECTED ELEMENT VIEW -> TBC
//View elementView = doc.GetElement(e.OwnerViewId) as View;
//FIND VIEWPORT
ICollection<ElementId> viewportIds = selectedViewSheet.GetAllViewports();
Viewport viewport = null;
foreach (ElementId eid in viewportIds) {
Viewport vp = doc.GetElement(eid) as Viewport;
//TaskDialog.Show("Check", String.Format("{0} : {1}", vp.ViewId.ToString(), elementView.Id.ToString()));
if (vp.ViewId.ToString() == elementView.Id.ToString()){
viewport = vp;
}
}
//TaskDialog.Show("Viewport Name",String.Format("Viewport name: {0}",viewport.Name));
ICollection<ElementId> categoryToIsolate = new List<ElementId>();
Categories groups = doc.Settings.Categories;
categoryToIsolate.Add(groups.get_Item(BuiltInCategory.OST_Loads).Id);
XYZ viewCenter = null;
XYZ changedVPcenter = null;
t.Start("Hide Categories");
elementView.IsolateCategoriesTemporary(categoryToIsolate);
//Use the annotation crop region to find the view centroid
ViewCropRegionShapeManager vcr = elementView.GetCropRegionShapeManager();
//Set the annotation offset to the minimum (3mm)
vcr.BottomAnnotationCropOffset = 3 / 304.8;
vcr.TopAnnotationCropOffset = 3 / 304.8;
vcr.LeftAnnotationCropOffset = 3 / 304.8;
vcr.RightAnnotationCropOffset = 3 / 304.8;
//Get the Viewport Center. This will match the View centroid
changedVPcenter = viewport.GetBoxCenter();
//Find the view centroid using the annotation crop shape (it should always be a rectangle, while the cropbox shape can be a polygon).
CurveLoop cloop = vcr.GetAnnotationCropShape();
List<XYZ> pts = new List<XYZ>();
foreach (Curve crv in cloop)
{
pts.Add(crv.GetEndPoint(0));
pts.Add(crv.GetEndPoint(1));
}
//View centroid with elements hidden
viewCenter = GetCentroid(pts, pts.Count);
t.RollBack();
int scale = elementView.Scale;
t.Start("Add rev cloud");
//VIEWPORT CENTER
//XYZ vpMax = viewport.GetBoxOutline().MaximumPoint;
//XYZ vpMin = viewport.GetBoxOutline().MinimumPoint;
//XYZ vpCen = (vpMax + vpMin)/2;
XYZ vpCen = changedVPcenter;
//DrawRectangle(doc, selectedViewSheet, vpMax, vpMin);
//FIND ELEMENT BBOX FOR REVISION CLOUDS
BoundingBoxXYZ bbox = e.get_BoundingBox(doc.ActiveView);
XYZ pt1 = bbox.Min;
XYZ pt3 = bbox.Max;
XYZ pt2 = new XYZ(pt3.X, pt1.Y,0);
XYZ pt4 = new XYZ(pt1.X, pt3.Y,0);
//bbox center
XYZ bboxCenter = (pt3 + pt1)/2;
//OFFSETS
double xOffset = (viewCenter.X - bboxCenter.X)/scale;
double yOffset = (viewCenter.Y - bboxCenter.Y)/scale;
// TaskDialog.Show("Offsets", String.Format("x: {0} y: {1}", xOffset*304.8, yOffset*304.8));
XYZ pt1Sheet = bbox.Min/scale;
XYZ pt3Sheet = bbox.Max/scale;
XYZ pt2Sheet = new XYZ(pt3Sheet.X, pt1Sheet.Y,0);
XYZ pt4Sheet = new XYZ(pt1Sheet.X, pt3Sheet.Y,0);
XYZ ptSheetMid = (pt3Sheet + pt1Sheet)/2;
//MOVE POINTS
XYZ moveToVPCenter = vpCen-ptSheetMid;
pt1Sheet = pt1Sheet.Add(moveToVPCenter);
pt3Sheet = pt3Sheet.Add(moveToVPCenter);
pt2Sheet = pt2Sheet.Add(moveToVPCenter);
pt4Sheet = pt4Sheet.Add(moveToVPCenter);
XYZ moveToViewLocation = new XYZ(-xOffset, -yOffset,0);
pt1Sheet = pt1Sheet.Add(moveToViewLocation);
pt3Sheet = pt3Sheet.Add(moveToViewLocation);
pt2Sheet = pt2Sheet.Add(moveToViewLocation);
pt4Sheet = pt4Sheet.Add(moveToViewLocation);
//ElementTransformUtils.MoveElement(doc, cloudSheet.Id, vpCen - ptSheetMid);
//ElementTransformUtils.MoveElement(doc, cloudSheet.Id, new XYZ(-xOffset, -yOffset,0));
//doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(FlattenPoint(pt1), FlattenPoint(pt3)));
//Line l = Line.CreateBound(pts[0], pts[3]);
//doc.Create.NewDetailCurve(doc.ActiveView, l);
//doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(viewCenter, FlattenPoint(bboxCenter)));
//VIEWPORT CENTRE
//viewport.GetBoxCenter()
//doc.Create.NewDetailCurve(selectedViewSheet, Line.CreateBound(new XYZ(0,0,0), FlattenPoint(vpCen)));
//doc.Create.NewDetailCurve(selectedViewSheet, Line.CreateBound(new XYZ(0,0,0), FlattenPoint(viewport.GetBoxCenter())));
//INSIDE VIEW
List<Curve> curves = new List<Curve>();
curves.Add(Line.CreateBound(pt1, pt4));
curves.Add(Line.CreateBound(pt4, pt3));
curves.Add(Line.CreateBound(pt3, pt2));
curves.Add(Line.CreateBound(pt2, pt1));
RevisionCloud cloud = RevisionCloud.Create(doc, doc.ActiveView, rev[0], curves);
//ON SHEET
//MOVED OUTSIDE THE FOREACH LOOP SO COULDS WILL BE GROUPED TOGETHER
//List<Curve> curvesSheet = new List<Curve>();
curvesSheet.Add(Line.CreateBound(pt1Sheet, pt4Sheet));
curvesSheet.Add(Line.CreateBound(pt4Sheet, pt3Sheet));
curvesSheet.Add(Line.CreateBound(pt3Sheet, pt2Sheet));
curvesSheet.Add(Line.CreateBound(pt2Sheet, pt1Sheet));
//RevisionCloud cloudSheet = RevisionCloud.Create(doc, selectedViewSheet, rev[0], curvesSheet);
//MOVE THE SINGLE CLOUD AFTER CREATION
//ElementTransformUtils.MoveElement(doc, cloudSheet.Id, vpCen - ptSheetMid);
//ElementTransformUtils.MoveElement(doc, cloudSheet.Id, new XYZ(-xOffset, -yOffset,0));
t.Commit();
}
t.Start("Draw Clouds on Sheet");
RevisionCloud cloudSheet = RevisionCloud.Create(doc, selectedViewSheet, rev[0], curvesSheet);
t.Commit();
}
catch(Exception ex){
TaskDialog.Show("Error", ex.Message);
}
finally{
}
transGroup.Assimilate();
}
}
}
public void CreateRevisionsClouds(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<ElementId> rev = Revision.GetAllRevisionIds(doc);
using (Transaction t = new Transaction(doc, "aaa")){
t.Start();
List<Curve> curvesSheet = new List<Curve>(){
Line.CreateBound(new XYZ(0,0,0), new XYZ(10,0,0)),
Line.CreateBound(new XYZ(10,0,0), new XYZ(10,10,0)),
Line.CreateBound(new XYZ(10,10,0), new XYZ(0,10,0)),
Line.CreateBound(new XYZ(0,10,0), new XYZ(0,0,0)),
Line.CreateBound(new XYZ(20,20,0), new XYZ(40,20,0)),
Line.CreateBound(new XYZ(40,40,0), new XYZ(20,40,0)),
Line.CreateBound(new XYZ(20,40,0), new XYZ(20,20,0))
};
RevisionCloud cloudSheet = RevisionCloud.Create(doc, doc.ActiveView, rev[0], curvesSheet);
t.Commit();
}
}
public XYZ FlattenPoint(XYZ point){
XYZ newPoint = new XYZ(point.X, point.Y, 0);
return newPoint;
}
public void FindViewportCenterOnSheet()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference viewportRef = uidoc.Selection.PickObject(ObjectType.Element,"Select a Viewport");
Element viewportElement = doc.GetElement(viewportRef);
Viewport viewport = viewportElement as Viewport;
//Find the Viewport center
XYZ vpMax = viewport.GetBoxOutline().MaximumPoint;
XYZ vpMin = viewport.GetBoxOutline().MinimumPoint;
XYZ vpCen = vpMax - vpMin;
double vpX = Convert.ToInt16(viewport.GetBoxCenter().X * 304.8);
double vpY = Convert.ToInt16(viewport.GetBoxCenter().Y * 304.8);
double vpZ = Convert.ToInt16(viewport.GetBoxCenter().Z * 304.8);
//TaskDialog.Show("Viewport Center", String.Format("{0}, {1}, {2}", vpX, vpY, vpZ ));
using (Transaction t = new Transaction(doc, "Draw Rectangle")){
t.Start();
//DrawRectangle(doc, doc.ActiveView, vpMax,vpMin);
t.Commit();
}
View plan = doc.GetElement(viewport.ViewId) as View;
ViewCropRegionShapeManager vcr = plan.GetCropRegionShapeManager();
CurveLoop cloop = vcr.GetAnnotationCropShape();
List<XYZ> pts = new List<XYZ>();
foreach (Curve crv in cloop)
{
pts.Add(crv.GetEndPoint(0));
pts.Add(crv.GetEndPoint(1));
}
//View centroid
XYZ center = GetCentroid(pts, pts.Count);
//See the difference
BoundingBoxXYZ bbox = plan.get_BoundingBox(plan);
XYZ centroid = bbox.Max - bbox.Min;
double centerX = (center.X * 304.8);
double centerY = (center.Y * 304.8);
double centerZ = (center.Z * 304.8);
using (Transaction t = new Transaction(doc, "tes")){
t.Start();
Line l = Line.CreateBound(pts[0], pts[3]);
//Line l = Line.CreateBound(new XYZ(0,0,0),new XYZ(center.X, center.Y,0));
doc.Create.NewDetailCurve(plan, l);
t.Commit();
}
TaskDialog.Show("Viewport Center", String.Format("{0}, {1}, {2}", centerX, centerY, centerZ));
}
public static XYZ GetCentroid(List<XYZ> nodes, int count)
{
double x = 0, y = 0, area = 0, k;
XYZ a, b = nodes[count - 1];
for (int i = 0; i < count; i++)
{
a = nodes[i];
k = a.Y * b.X - a.X * b.Y;
area += k;
x += (a.X + b.X) * k;
y += (a.Y + b.Y) * k;
b = a;
}
area *= 3;
//return (area == 0) ? XYZ.Zero : new XYZ(x /= area, y /= area, nodes.First().Z);
return (area == 0) ? XYZ.Zero : new XYZ(x /= area, y /= area, 0);
}
public void DrawRectangle(Document doc, View vpPlan, XYZ _max, XYZ _min){
XYZ min = new XYZ(_min.X, _min.Y,0);
XYZ max = new XYZ(_max.X, _max.Y,0);
Line l1 = Line.CreateBound(min, new XYZ(max.X, min.Y,0));
Line l2 = Line.CreateBound(min, new XYZ(min.X, max.Y,0));
Line l3 = Line.CreateBound(new XYZ(min.X,max.Y,0), max);
Line l4 = Line.CreateBound(max,new XYZ(max.X,min.Y,0));
Line l5 = Line.CreateBound(min,max);
doc.Create.NewDetailCurve(vpPlan,l1);
doc.Create.NewDetailCurve(vpPlan,l2);
doc.Create.NewDetailCurve(vpPlan,l3);
doc.Create.NewDetailCurve(vpPlan,l4);
doc.Create.NewDetailCurve(vpPlan,l5);
}
public static List<View> collectTemplates(Document doc){
IEnumerable<View> fec = new FilteredElementCollector(doc).OfClass(typeof(View)).Cast<View>();
List<View> myVT = new List<View>();
foreach (View v in fec) {
if (v.IsTemplate){
myVT.Add(v);
}
}
return myVT;
}
public void SelectLinkedElements()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> linkModelElements = uidoc.Selection.PickObjects(ObjectType.LinkedElement,"Select Elements");
using (Transaction t = new Transaction(doc,"Copy Linked Elements")){
t.Start();
try{
ICollection<ElementId> elementsToCopy = new List<ElementId>();
Document linkedDoc = null;
RevitLinkInstance revitLinkInst = null;
Transform transf = revitLinkInst.GetTotalTransform();
CopyPasteOptions copyPasteOption = new CopyPasteOptions();
copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandler());
foreach (Reference elementRef in linkModelElements) {
Element e = doc.GetElement(elementRef.ElementId);
revitLinkInst = e as RevitLinkInstance;
linkedDoc = (e as RevitLinkInstance).GetLinkDocument();
Element eLinked =linkedDoc.GetElement(elementRef.LinkedElementId);
elementsToCopy.Add(eLinked.Id);
}
ElementTransformUtils.CopyElements(revitLinkInst.GetLinkDocument(),elementsToCopy,doc,null, copyPasteOption);
TaskDialog.Show("elements to copy", String.Format("{0} elements have been copied",elementsToCopy.Count));
}
catch(Exception ex){
TaskDialog.Show("e", ex.Message);
}
t.Commit();
}
}
#credits: https://forums.autodesk.com/t5/revit-api-forum/how-to-retrieve-the-final-graphics-style-of-an-element/td-p/7505002
public void CopyOverrideSettings()
{
Document doc = this.ActiveUIDocument.Document;
UIDocument uidoc = this.ActiveUIDocument;
ElementId sourceId = uidoc.Selection.PickObject(ObjectType.Element,"Select source").ElementId;
IList<Reference> destinationId = uidoc.Selection.PickObjects(ObjectType.Element,"Select destination");
OverrideGraphicSettings ogs = doc.ActiveView.GetElementOverrides(sourceId);
using (Transaction t = new Transaction(doc,"Set Element Override"))
{
t.Start();
destinationId.ToList().ForEach(r => doc.ActiveView.SetElementOverrides(r.ElementId, ogs));
t.Commit();
}
}
public void CountByDrawing()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
FilteredElementCollector allViews = new FilteredElementCollector(doc).OfClass(typeof(View));
//List<string> viewNames = new List<string>{"BASEMENT - WET FIRE SHEET 1","BASEMENT - WET FIRE SHEET 2","BASEMENT - WET FIRE SHEET 4","OFFICE - GROUND - WET FIRE SHEET 1","OFFICE - GROUND - WET FIRE SHEET 2","OFFICE - GROUND - WET FIRE SHEET 3","OFFICE - GROUND - WET FIRE SHEET 4","FP-EXISTING STORAGE AREA","SALOON LEVEL - MEZZANINE ROOM 1- LOW LEVEL VIEW","SALOON LEVEL - MEZZANINE ROOM 2- LOW LEVEL VIEW","OFFICE - LEVEL 1 - WET FIRE SHEET 1","OFFICE - LEVEL 1 - WET FIRE SHEET 2","OFFICE - LEVEL 2 - WET FIRE SHEET 1","OFFICE - LEVEL 2 - WET FIRE SHEET 2"};
List<string> viewNames = new List<string>{"FP-AMENITIES 1ST FLOOR LEVEL","FP-BASEMENT LEVEL","FP-BASEMENT LEVEL SOUTH","FP-EQUIPMENT 2ND FLOOR LEVEL","FP-EXISTING STORAGE AREA"};
StringBuilder sb = new StringBuilder();
List<ElementId> ids = new List<ElementId>();
foreach (View view in allViews) {
if (viewNames.Contains(view.Name)){
IList<Element> sprinklers = new FilteredElementCollector(doc, view.Id).OfCategory(BuiltInCategory.OST_Sprinklers).ToElements();
Dictionary<string, int> items = new Dictionary<string, int>();
foreach (Element element in sprinklers) {
if (!ids.Contains(element.Id)){
if (!element.Name.Contains("Symbol")){
if (!items.ContainsKey(element.Name)){
items[element.Name] = 1;
}
else{
items[element.Name] += 1;
}
}
ids.Add(element.Id);
}
}
//doc.Delete(ids);
//ids.Clear();
foreach (var item in items.Keys) {
sb.AppendLine(String.Format("{0},{1},{2},{3}",view.LookupParameter("Sheet Number").AsString(), view.Name, item, items[item]));
}
sb.AppendLine();
}
}//CLOSE FOREACH
string outputFile = @"C:\Temp\Counted.csv";
string headers = "Drawing Number,Drawing Name, Type, Count";
File.WriteAllText(outputFile, headers + "\n");
File.AppendAllText(outputFile, sb.ToString());
//TaskDialog.Show("r", s);
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = outputFile;
process.Start();
}
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
namespace ViewEditing
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("025A053A-569B-4C5E-BD22-ABFA8781D433")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void CreateDraftingView()
{
//Access the UI of the currently Revit project opened
UIDocument uidoc = this.ActiveUIDocument;
//The active or top most view of the project
Document doc = uidoc.Document;
// Select all the ViewFamilyType in the project
FilteredElementCollector viewTypes = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType));
ViewFamilyType vft = null;
foreach (ViewFamilyType vt in viewTypes) {
if (vt.Name == "Detail View 1"){
vft = vt;
}
}
TaskDialog.Show("title", vft.Name);
//Start Transaction
using (Transaction t = new Transaction(doc))
{
try
{
t.Start("Create Drafting View");
ViewDrafting newDraftingView = ViewDrafting.Create(doc, vft.Id);
//newDraftingView.Name = "My New Drafting View";
t.Commit();
TaskDialog.Show("Result", "Success");
}
catch {
TaskDialog.Show("Result", "Error");
}
}//close using
} //close method
}//close class
}//close namespace
/*
* Created by SharpDevelop.
* User: Giovanni.Brogiolo
* Date: 08/10/2018
* Time: 11:46
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
namespace ViewEditing
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("025A053A-569B-4C5E-BD22-ABFA8781D433")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void CreateDraftingView()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
using(var form = new CreateDraftingViewForm())
{
string interrupt = "False";
while(interrupt == "False")
{
form.ShowDialog();
//if the user hits cancel just drop out of macro
if(form.DialogResult == System.Windows.Forms.DialogResult.Cancel) return;
if (form.usertext.Length >2)
{
Helpers.AddDraftingView(doc, form.usertext);
interrupt = "True";
}
else if (form.usertext == "") {
TaskDialog.Show("Error", "Please specify the view name");
}
else if (form.usertext.Length <2) { //use <=
TaskDialog.Show("Error", "The view name is too short");
}
else
{
TaskDialog.Show("Error", "I don't know what went wrong");
}
}//close while
}//close using
} //close method
}//close class
}//close namespace
//knots
//revit -> control points + degree + 1
//rhino -> control points + degree - 1
//in revit re-add the first and the last knot
public void CreateRhinoSpline()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
double scale = 0.3048;
List<XYZ> controlPoints = new List<XYZ>();
controlPoints.Add(new XYZ(0/scale, 0/scale, 0/scale));
controlPoints.Add(new XYZ(5/scale, 5/scale, 2/scale));
controlPoints.Add(new XYZ(10/scale, 10/scale, 5/scale));
controlPoints.Add(new XYZ(15/scale, 10/scale, 5/scale));
controlPoints.Add(new XYZ(20/scale, 5/scale, 4/scale));
controlPoints.Add(new XYZ(25/scale, 5/scale, 3/scale));
List<double> weights = new List<double>();
weights.Add(1.0);
weights.Add(1.0);
weights.Add(1.0);
weights.Add(1.0);
weights.Add(1.0);
weights.Add(1.0);
List<double> knots = new List<double>();
knots.Add(0); //1
knots.Add(0); //2
knots.Add(0); //3
knots.Add(0); //4
knots.Add(10.76); //5
knots.Add(21.51); //6
knots.Add(32.27); //7
knots.Add(32.27);
knots.Add(32.27); //9
knots.Add(32.27);//revit
HermiteSpline hermspline = HermiteSpline.Create(controlPoints, false);
//Curve nurbSpline = NurbSpline.Create(hermspline);
Curve nurbSpline = NurbSpline.CreateCurve(3,knots, controlPoints, weights);
WireframeBuilder builder = new WireframeBuilder();
builder.AddCurve(nurbSpline);
using (Transaction t = new Transaction(doc, "create spline"))
{
t.Start();
ElementId categoryId = new ElementId(BuiltInCategory.OST_GenericModel);
DirectShape ds = DirectShape.CreateElement(doc, categoryId);
ds.SetShape(builder);
ds.Name = "RhinoSpline";
t.Commit();
}
}
public void CreateSchedule()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ElementId cat = new ElementId(BuiltInCategory.OST_Walls);
Transaction t = new Transaction(doc, "Add schedule");
t.Start();
ViewSchedule vs = ViewSchedule.CreateSchedule(doc, cat);
vs.Name = System.DateTime.Now.ToShortDateString() + '-' + "LR Automated Walls Schedule";
string sb = "";
foreach (SchedulableField column in vs.Definition.GetSchedulableFields()) {
string columnName = column.GetName(doc);
if ( columnName== "Family and Type" || columnName == "Volume" || columnName == "Phase Created" || columnName == "Workset_TX"){
vs.Definition.AddField(column);
}
}
t.Commit();
TaskDialog.Show("r", sb);
}
public void currentSelection() {
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ICollection<ElementId> refe = uidoc.Selection.GetElementIds();
string output = "";
foreach (ElementId e in refe) {
output += e.ToString() + "\n" ;
}
TaskDialog.Show("View Selected",output);
}
//Credits https://github.com/mcneel/rhino.inside-revit/blob/5701bd32fabfdc24c7dd4248c1ab9339f7c36148/src/RhinoInside.Revit.GH/Components/Element/DirectShape/ByCurve.cs
public void CurveDirectShape()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
XYZ pt0 = new XYZ(0,0,0);
XYZ pt1 = new XYZ(10,10,0);
XYZ pt2 = new XYZ(20,0,0);
XYZ pt3 = new XYZ(40,10,0);
List<Curve> profile = new List<Curve>();
profile.Add(Line.CreateBound(pt0, pt1));
profile.Add(Line.CreateBound(pt1, pt2));
profile.Add(Line.CreateBound(pt2, pt3));
WireframeBuilder builder = new WireframeBuilder();
builder.AddCurve(Line.CreateBound(pt0, pt1));
builder.AddCurve(Line.CreateBound(pt1, pt2));
builder.AddCurve(Line.CreateBound(pt2, pt3));
using (Transaction t = new Transaction(doc, "a")){
t.Start();
DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
ds.SetShape(profile.ToArray().OfType<GeometryObject>().ToList());
DirectShape dsWireframe = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
ds.SetShape(builder);
t.Commit();
TaskDialog.Show("r", ds.Id.ToString());
}
}
public void DeleteTextFont(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> textToDelete = uidoc.Selection.PickObjects(ObjectType.Element, "Select text to delete");
ICollection<ElementId> textNoteTypes = new FilteredElementCollector(doc).OfClass( typeof( TextNoteType ) ).ToElementIds();
using (Transaction t = new Transaction(doc, "Place text")){
t.Start();
foreach (Reference textReference in textToDelete) {
TextNote textNoteElement = doc.GetElement(textReference) as TextNote;
ElementId eid = textNoteTypes.Where(x => x == textNoteElement.GetTypeId()).First();
doc.Delete(eid);
}
t.Commit();
}
// TaskDialog.Show("r", doc.GetElement(eid).Name);
}
"""NOTE: KEYS IN DICTIONARY MUST BE UNIQUE!!!"""
public static Dictionary<ViewSheet, string> collectSheets(Document doc){
FilteredElementCollector fec = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets);
Dictionary<ViewSheet, string> mySheets = new Dictionary<ViewSheet, string> ();
foreach (ViewSheet f in fec) {
mySheets.Add(f,f.Name);
}
return mySheets;
}
public void DisableOpeningWarning()
{
UIApplication uiapp = new UIApplication(Application);
Application app = uiapp.Application;
try{
uiapp.DialogBoxShowing += new EventHandler<DialogBoxShowingEventArgs>(DialogBoxShowing);
string[] filePath = System.IO.Directory.GetFiles(@"C:\Users\giovanni.brogiolo\Documents\Animation");
ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath[0]);
OpenOptions optionDetach = new OpenOptions();
optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
Document openDoc = app.OpenDocumentFile(modelP, optionDetach);
FilteredElementCollector fec = new FilteredElementCollector(openDoc).OfClass(typeof(FamilyInstance));
forms.MessageBox.Show(fec.Count().ToString());
openDoc.Close(false);
}
catch(Exception ex){
TaskDialog.Show("result", ex.Message);
}
finally{
uiapp.DialogBoxShowing -= DialogBoxShowing;
TaskDialog.Show("Result", "Done");
}
}
void DialogBoxShowing(object sender, DialogBoxShowingEventArgs e)
{
TaskDialogShowingEventArgs e2 = e as TaskDialogShowingEventArgs;
string s = string.Empty;
bool isConfirm = false;
int dialogResult = 0;
if (e2.DialogId.Equals("TaskDialog_Missing_Third_Party_Updaters"))
{
isConfirm = true;
dialogResult = (int)TaskDialogResult.CommandLink1;
}
if (isConfirm)
{
e2.OverrideResult(dialogResult);
s += ", auto-confirmed.";
}
else
{
s = string.Format(
", dialog id {0}, message '{1}'",
e2.DialogId, e2.Message);
forms.MessageBox.Show(s);
}
}
/* Create 3 model lines aligned with the object axis from a point on a face. To be used with the Family Instance Total Transform
property. Note: the face transform may not be in global coordinates! it refers to the family environment.
Reference r = uidoc.Selection.PickObject(ObjectType.Face, "Please pick a point on a face");
Element e = doc.GetElement( r.ElementId );
FamilyInstance fi = e as FamilyInstance;
//GeometryObject obj = e.GetGeometryObjectFromReference( r ); not needed
Transform transf = fi.GetTotalTransform();
XYZ pntCenter = r.GlobalPoint;
*/
private void DrawAxisPerpendicularToDirections(Document doc, XYZ origin, XYZ dir1, XYZ dir2, double length, Color color){
XYZ pntCenter = origin;
XYZ cross = dir2.CrossProduct(dir1);
XYZ pntEnd = pntCenter + cross.Multiply(length/304.8);
Plane perpPlane = Plane.CreateByThreePoints(pntCenter, pntEnd, dir1);
SketchPlane perpSplane = SketchPlane.Create(doc, perpPlane);
Line line2 = Autodesk.Revit.DB.Line.CreateBound(pntCenter, pntEnd);
ModelLine perpLine = doc.Create.NewModelCurve(line2, perpSplane) as ModelLine;
OverrideGraphicSettings ogs= new OverrideGraphicSettings();
ogs.SetProjectionLineColor(color);
doc.ActiveView.SetElementOverrides(perpLine.Id, ogs);
}
private bool ExportDWG(Document document, Autodesk.Revit.DB.View view, string setupName)
{
bool exported = false;
// Get the predefined setups and use the one with the given name.
IList<string> setupNames = BaseExportOptions.GetPredefinedSetupNames(document);
foreach (string name in setupNames)
{
if (name.CompareTo(setupName) == 0)
{
// Export using the predefined options
DWGExportOptions dwgOptions = DWGExportOptions.GetPredefinedOptions(document, name);
// Export the active view
ICollection<ElementId> views = new List<ElementId>();
views.Add(view.Id);
// The document has to be saved already, therefore it has a valid PathName.
exported = document.Export(Path.GetDirectoryName(document.PathName),
Path.GetFileNameWithoutExtension(document.PathName), views, dwgOptions);
break;
}
}
return exported;
}
public void ExportSchedule()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = this.ActiveUIDocument.Document;
FilteredElementCollector collection = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule));
ViewScheduleExportOptions opt = new ViewScheduleExportOptions();
string folderName = @"05-Excel\240304 Wheel Lathe FD";
foreach( ViewSchedule vs in collection ){
if(vs.Name.StartsWith("LR")){
try
{
vs.Export(folderName, vs.Name + ".csv", opt );
}
catch
{
TaskDialog.Show("Error", vs.Name);
}
}
}
TaskDialog.Show("r", "Done");
}
#https://github.com/jeremytammik/the_building_coder_samples/blob/master/BuildingCoder/BuildingCoder/CmdPreprocessFailure.cs#L44-L67
#region Header
//
// CmdPreprocessFailure.cs - suppress warning message by implementing the IFailuresPreprocessor interface
//
// Copyright (C) 2010-2019 by Jeremy Tammik, Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
/// <summary>
/// Here is some code that is in the RevitAPI.chm
/// as a snippet for IFailuresPreprocessor Interface).
/// It creates an unbounded room and suppresses the
/// warning ("Room is not in a properly enclosed region")
/// that would otherwise be given.
///
/// The duration for this implementation is only for
/// the transaction in the external command, so after
/// the command is executed manually placed unbounded
/// rooms do result in the warning.
///
/// However, it is also possible with the new failure
/// API to suppress warnings for the entire Revit session.
///
/// By Harry Mattison.
/// </summary>
[Transaction( TransactionMode.Manual )]
class CmdPreprocessFailure : IExternalCommand
{
#region General Warning Swallower
FailureProcessingResult PreprocessFailures(
FailuresAccessor a )
{
IList<FailureMessageAccessor> failures
= a.GetFailureMessages();
foreach( FailureMessageAccessor f in failures )
{
FailureSeverity fseverity = a.GetSeverity();
if( fseverity == FailureSeverity.Warning )
{
a.DeleteWarning( f );
}
else
{
a.ResolveFailure( f );
return FailureProcessingResult.ProceedWithCommit;
}
}
return FailureProcessingResult.Continue;
}
#endregion // General Warning Swallower
public class RoomWarningSwallower : IFailuresPreprocessor
{
public FailureProcessingResult PreprocessFailures(
FailuresAccessor a )
{
// inside event handler, get all warnings
IList<FailureMessageAccessor> failures
= a.GetFailureMessages();
foreach( FailureMessageAccessor f in failures )
{
// check failure definition ids
// against ones to dismiss:
FailureDefinitionId id
= f.GetFailureDefinitionId();
if( BuiltInFailures.RoomFailures.RoomNotEnclosed
== id )
{
a.DeleteWarning( f );
}
}
return FailureProcessingResult.Continue;
}
}
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
Document doc = commandData.Application
.ActiveUIDocument.Document;
using( Transaction t = new Transaction( doc ) )
{
FilteredElementCollector collector
= new FilteredElementCollector( doc );
collector.OfClass( typeof( Level ) );
Level level = collector.FirstElement() as Level;
t.Start( "Create unbounded room" );
FailureHandlingOptions failOpt
= t.GetFailureHandlingOptions();
failOpt.SetFailuresPreprocessor(
new RoomWarningSwallower() );
t.SetFailureHandlingOptions( failOpt );
doc.Create.NewRoom( level, new UV( 0, 0 ) );
t.Commit();
}
return Result.Succeeded;
}
}
}
public void Oversized()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference vpRef = uidoc.Selection.PickObject(ObjectType.Element, "Select VP");
Viewport vp = doc.GetElement(vpRef) as Viewport;
//
double scale = 304.8;
XYZ center = new XYZ(432/scale,305/scale,0);
double width = 864/scale;
double height = 482/scale;
XYZ minPt = new XYZ(center.X-width/2, center.Y-height/2,0);
XYZ maxPt = new XYZ(center.X+width/2, center.Y+height/2,0);
Outline sheetOutline = new Outline(minPt, maxPt); //assumed titleblock size 823x532
DrawRectangle(doc, doc.ActiveView, maxPt, minPt);
//
// List<Outline> vpOutline = new List<Outline>();
// vpOutline.Add(vp.GetBoxOutline());
//
// Outline viewportOutline = vp.GetBoxOutline();
//
//
View pView = doc.GetElement(vp.ViewId) as View;
try{
//BoundingBoxXYZ bbox = vp.GetBoxOutline();
//Outline viewportOutline = new Outline(bbox.Min, bbox.Max);
Outline viewportOutline = vp.GetBoxOutline();
DrawRectangle(doc, doc.ActiveView, viewportOutline.MinimumPoint, viewportOutline.MaximumPoint);
XYZ vpMinPoint = viewportOutline.MinimumPoint;
XYZ vpMaxPoint = viewportOutline.MaximumPoint;
XYZ newMin = new XYZ(vpMinPoint.X, vpMinPoint.Y, 0);
XYZ newMax = new XYZ(vpMaxPoint.X, vpMinPoint.Y, 0);
StringBuilder sb = new StringBuilder();
if (sheetOutline.Contains(newMin,0) && sheetOutline.Contains(newMax,0)){
TaskDialog.Show("re", "Not intersect");
}
else{
TaskDialog.Show("re", "Intersect");
}
}
catch(Exception ex){
TaskDialog.Show("R", ex.Message);
}
// XYZ vpMinPoint = viewportOutline.MinimumPoint;
// XYZ vpMaxPoint = viewportOutline.MaximumPoint;
//
// XYZ newMin = new XYZ(vpMinPoint.X, vpMinPoint.Y, 0);
// XYZ newMax = new XYZ(vpMaxPoint.X, vpMinPoint.Y, 0);
//
// StringBuilder sb = new StringBuilder();
//
// if (sheetOutline.Contains(newMin,0) && sheetOutline.Contains(newMax11,0)){
// TaskDialog.Show("re", "Not intersect");
// }
// else{
// TaskDialog.Show("re", "Intersect");
// }
//TaskDialog.Show("re", Points(sheetOutline)+"\n"+Points(vp.GetBoxOutline()));
}
public void FindViewPortAdjustedCenter(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference viewport = uidoc.Selection.PickObject(ObjectType.Element, "select a viewport");
Viewport vp = doc.GetElement(viewport) as Viewport;
View view = doc.GetElement(vp.ViewId) as View;
XYZ unchangedVPcenter = vp.GetBoxCenter();
XYZ flattenVPcenter = new XYZ(unchangedVPcenter.X, unchangedVPcenter.Y,0);
TaskDialog.Show("r", PointToString(flattenVPcenter));
ICollection<ElementId> categoryToIsolate = new List<ElementId>();
Categories groups = doc.Settings.Categories;
categoryToIsolate.Add(groups.get_Item(BuiltInCategory.OST_Loads).Id);
XYZ changedVPcenter = null;
ViewCropRegionShapeManager vcr = null;
double scale = 304.8;
using (Transaction t = new Transaction(doc, "Hide categories")){
t.Start();
view.IsolateCategoriesTemporary(categoryToIsolate);
vcr = view.GetCropRegionShapeManager();
vcr.BottomAnnotationCropOffset = 3/scale;
vcr.TopAnnotationCropOffset = 3/scale;
vcr.LeftAnnotationCropOffset = 3/scale;
vcr.RightAnnotationCropOffset = 3/scale;
changedVPcenter = vp.GetBoxCenter();
t.RollBack();
}
TaskDialog.Show("Changed VP center", PointToString(changedVPcenter));
XYZ viewPointsVector = (flattenVPcenter - changedVPcenter)*view.Scale;
TaskDialog.Show("Viewpoints vector", PointToString(viewPointsVector));
CurveLoop cloop = vcr.GetAnnotationCropShape();
List<XYZ> pts = new List<XYZ>();
foreach (Curve crv in cloop)
{
pts.Add(crv.GetEndPoint(0));
}
XYZ centroid = GetCentroid(pts, pts.Count);
//From PBP coordinates to SP coordinates
ProjectLocation pl = doc.ActiveProjectLocation;
Transform ttr = pl.GetTotalTransform().Inverse;
ProjectPosition projPosition = doc.ActiveProjectLocation.GetProjectPosition(new XYZ(0, 0, 0));
XYZ newCentroid = centroid + viewPointsVector;
//XYZ point = ttr.OfPoint(center);
XYZ point = ttr.OfPoint(newCentroid);
StringBuilder sb = new StringBuilder();
PointConverter(point, ref sb);
TaskDialog.Show("a", sb.ToString());
}
public void FlipBeam(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
UIApplication uiapp = new UIApplication(Application);
Element e = Util.SelectSingleElement(uidoc, "an element" );
FamilyInstance fa = e as FamilyInstance;
IList<Element> openingCuts = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFramingOpening).ToElements();
List<ElementId> openingsPerBeam = new List<ElementId>();
foreach (Opening o in openingCuts) {
if (o.Host.Id == e.Id){
try{
openingsPerBeam.Add(o.Id);
}
catch{
}
}
}
uidoc.Selection.SetElementIds(openingsPerBeam);
Press.Keys("CB");
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Cut Openings" );
StructuralFramingUtils.FlipEnds(fa);
doc.Delete(openingsPerBeam);
tx.Commit();
}
Press.Keys("PA");
}
public static void GetInstanceGeometry(GeometryObject obj, Dictionary<int,Face> areas){
GeometryInstance instance = obj as GeometryInstance;
if (null != instance)
{
GeometryElement instanceGeometryElement = instance.GetInstanceGeometry();
foreach (GeometryObject instanceObj in instanceGeometryElement){
Solid instanceGeomSolid = instanceObj as Solid;
if (null != instanceGeomSolid){
foreach (Face geomFace in instanceGeomSolid.Faces) {
try{
areas.Add((int)geomFace.Area, geomFace);
}
catch{
// TaskDialog.Show("Result", "Solid geometry not found");
}
}
}
}
}//close object array
}//close method
// Filter a selection of elements by category
public void GetSelectedElements()
{
UIDocument uidoc = this.ActiveUIDocument;
ICollection<ElementId> selectedIds = uidoc.Selection.GetElementIds();
// Go through the selected items and filter out
ICollection<ElementId> selectedElemCategory = new List<ElementId>();
foreach (ElementId id in selectedIds)
{
Element elements = uidoc.Document.GetElement(id);
if (elements.Category.Name == "Structural Foundations")
{
selectedElemCategory.Add(id);
}
}
uidoc.Selection.SetElementIds(selectedElemCategory);
}
public static void GetSymbolGeometry(GeometryObject obj, Dictionary<int,Face> areas,out Transform instanceTransform){
GeometryInstance instance = obj as GeometryInstance;
instanceTransform = instance.Transform;
if (null != instance)
{
GeometryElement symbolGeometryElement = instance.GetSymbolGeometry();
foreach (GeometryObject instanceObj in symbolGeometryElement){
Solid instanceGeomSolid = instanceObj as Solid;
if (null != instanceGeomSolid){
foreach (Face geomFace in instanceGeomSolid.Faces) {
try{
areas.Add((int)geomFace.Area, geomFace);
}
catch{
// TaskDialog.Show("Result", "Solid geometry not found");
}
}
}
}
}//close object array
}//close method
// GetSymbolGeometry() returns the geometry represented in the coordinate system of the family without regards
// to the orientation and placement location within the project. The bounding box of this element can be used to
// calculate the width of the beam
public void GetInstanceBBox(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Element e = Util.SelectSingleElement(uidoc, "an element" );
Options opt = new Options();
opt.ComputeReferences = true;
opt.IncludeNonVisibleObjects = false;
opt.View = doc.ActiveView;
GeometryElement obj = e.get_Geometry(opt);
BoundingBoxXYZ bbox = null;
double width = 0;
double length = 0;
Transform instaTransform = null;
Transform transformInverse = null;
foreach (var o in obj) {
GeometryInstance gi = o as GeometryInstance;
try{
gi.GetSymbolGeometry();
bbox = gi.GetSymbolGeometry().GetBoundingBox();
width = (bbox.Max.Y - bbox.Min.Y);
length = (bbox.Max.X - bbox.Min.X);
instaTransform = gi.Transform;
transformInverse = gi.Transform.Inverse;
}
catch{
}
}
/*
XYZ transformedMinPoint = instaTransform.OfPoint(bbox.Min);
XYZ transformedMaxPoint = instaTransform.OfPoint(bbox.Max);
bbox.Min = transformedMinPoint;
bbox.Max = transformedMaxPoint;
*/
//bbox = Helpers.RotateBoundingBox(bbox, instaTransform);
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Draw Model Line Bounding Box Outline" );
Creator creator = new Creator( doc );
//bbox.Min = transformInverse.OfPoint(bbox.Min);
//bbox.Max = transformInverse.OfPoint(bbox.Max);
creator.DrawPolygon( new List<XYZ>(Util.GetBottomCorners( bbox ) ) );
//Transform rotation = Transform.CreateRotation(XYZ.BasisZ, 28 * Math.PI / 180.0 );
//bbox = Helpers.RotateBoundingBox( bbox, rotation );
//creator.DrawPolygon( new List<XYZ>(Util.GetBottomCorners( bbox ) ) );
//beam direction
LocationCurve beamLine = e.Location as LocationCurve;
Line bl = beamLine.Curve as Line;
XYZ beamDirection = beamLine.Curve.GetEndPoint(0) - beamLine.Curve.GetEndPoint(1);
XYZ normal = beamDirection.CrossProduct(XYZ.BasisZ);
XYZ nn = Util.Normal(bl);
FamilyInstance fi = e as FamilyInstance;
XYZ hand = fi.HandOrientation;
double angle = nn.AngleTo(XYZ.BasisX)*180/Math.PI;
double angle2 = hand.AngleTo(XYZ.BasisX)*180/Math.PI;
XYZ newMin = instaTransform.OfPoint(bbox.Min);
XYZ newMax = instaTransform.OfPoint(bbox.Max);
BoundingBoxXYZ newBBox = new BoundingBoxXYZ();
newBBox.Transform = transformInverse;
newBBox.Min = newMin;
newBBox.Max = newMax;
creator.DrawPolygon( new List<XYZ>(Util.GetBottomCorners( newBBox ) ) );
Line newLine = Line.CreateBound(newMax, newMin);
creator.CreateModelCurve(newLine);
tx.Commit();
TaskDialog.Show("result", (width*304.8).ToString()+"\n"+(length*304.8).ToString()+"\n"+angle+"\n"+angle2);
}
}//close mehtod
// Get the viewport's view centerpoint and transform it to SP coordinates.
public void ViewCenterSP()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference viewport = uidoc.Selection.PickObject(ObjectType.Element, "select a viewport");
Viewport vp = doc.GetElement(viewport) as Viewport;
Autodesk.Revit.DB.View vpPlan = doc.GetElement(vp.ViewId) as Autodesk.Revit.DB.View;
BoundingBoxXYZ bounding = vpPlan.get_BoundingBox( vpPlan);
StringBuilder sb = new StringBuilder();
XYZ min = bounding.Min;
XYZ max = bounding.Max;
XYZ center = (min+max)/2;
//PointConverter(center, ref sb);
XYZ min0 = PointFlatten(min);
XYZ max0 = PointFlatten(max);
XYZ center0 = (min0+max0)/2;
using(Transaction t = new Transaction(doc, "test")){
t.Start();
Line L1 = Line.CreateBound(min0, center0);
Line L2 = Line.CreateBound(max0, center0);
doc.Create.NewDetailCurve(vpPlan,L1);
doc.Create.NewDetailCurve(vpPlan,L2);
t.Commit();
}
//From PBP coordinates to SP coordinates
ProjectLocation pl = doc.ActiveProjectLocation;
Transform ttr = pl.GetTotalTransform().Inverse;
ProjectPosition projPosition = doc.ActiveProjectLocation.GetProjectPosition(new XYZ(0, 0, 0));
XYZ point = ttr.OfPoint(center);
PointConverter(point, ref sb);
TaskDialog.Show("a", sb.ToString());
}
private void PointConverter(XYZ point, ref StringBuilder sb){
sb.AppendLine (UnitUtils.ConvertFromInternalUnits(point.X, DisplayUnitType.DUT_MILLIMETERS).ToString());
sb.AppendLine (UnitUtils.ConvertFromInternalUnits(point.Y, DisplayUnitType.DUT_MILLIMETERS).ToString());
sb.AppendLine (UnitUtils.ConvertFromInternalUnits(point.Z, DisplayUnitType.DUT_MILLIMETERS).ToString());
}
private XYZ PointFlatten(XYZ point){
return new XYZ (point.X,point.Y,0);
}
public static ViewFamilyType getViewFamilyTypeByName(Document doc, string familyName){
// Select all the ViewFamilyType in the project
FilteredElementCollector viewTypes = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType));
ViewFamilyType vft = null;
foreach (ViewFamilyType vt in viewTypes) {
if (vt.FamilyName == familyName){
vft = vt;
}
}
return vft;
}
FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(ElementType)).WhereElementIsElementType();
Dictionary<string, ElementId> viewTypes = new Dictionary<string, ElementId>();
StringBuilder sb = new StringBuilder();
foreach( ElementType e in fec )
{
if (e.FamilyName == "Viewport"){
try{
viewTypes.Add(e.Name, e.Id);
sb.AppendLine(e.Name + " " + e.Id);
}
catch{}
}
}
TaskDialog.Show("r", sb.ToString());
//https://adndevblog.typepad.com/aec/2015/09/revitapi-how-to-get-location-of-keynote-file.html
public void Keynotes()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
KeynoteTable kt = KeynoteTable.GetKeynoteTable(doc);
IDictionary<ExternalResourceType, ExternalResourceReference> dict = kt.GetExternalResourceReferences();
StringBuilder sb = new StringBuilder();
foreach (var item in dict.Keys) {
sb.AppendLine(item.ToString() + " " + dict[item].InSessionPath);
}
TaskDialog.Show("r", sb.ToString());
}
public class GenericSelectionFilter : ISelectionFilter
{
public string catNameChosen { get; set; }
public GenericSelectionFilter(string catName)
{
this.catNameChosen = catName;
}
public bool AllowElement(Element e)
{
if (e.Category.Name == catNameChosen)
{
return true;
}
return false;
}
public bool AllowReference(Reference refer, XYZ point)
{
return false;
}
}//close class
public void JoinRevClouds(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
List<RevisionCloud> elements = new List<RevisionCloud>();
IList<ElementId> rev = Revision.GetAllRevisionIds(doc);
List<Curve> curvesSheet = new List<Curve>();
using (Transaction t = new Transaction(doc, "Merge clouds")) {
t.Start("Draw Clouds on Sheet");
foreach (Reference r in uidoc.Selection.PickObjects(ObjectType.Element))
{
RevisionCloud rc = doc.GetElement(r) as RevisionCloud;
foreach (Curve crv in rc.GetSketchCurves()) {
curvesSheet.Add(crv);
}
doc.Delete(doc.GetElement(r).Id);
}
RevisionCloud cloudSheet = RevisionCloud.Create(doc, doc.ActiveView, rev[0], curvesSheet);
t.Commit();
}
}
public static XYZ lineDirection(Curve crv){
XYZ startPoint = crv.GetEndPoint(0);
XYZ endPoint = crv.GetEndPoint(1);
XYZ direction = (endPoint - startPoint);
return direction;
}
public void LineStyles()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
XYZ origin = uidoc.Selection.PickPoint("Select insertion point");
double width = 0.2; //feet
Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
CategoryNameMap subcats = c.SubCategories;
double offset = 0;
TextNoteOptions options = new TextNoteOptions();
options.HorizontalAlignment = HorizontalTextAlignment.Left;
options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
var dict = new SortedDictionary<string, GraphicsStyle>();
foreach( Category lineStyle in subcats ) {
GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);
dict.Add(gs.Name, gs);
}
var output = dict.OrderBy(e => e.Key).Select(e => new {graphicStyle = e.Value, linestyleName = e.Key}).ToList();
using (Transaction t = new Transaction(doc, "Place Lines")){
t.Start();
//foreach( Line item in ordered) {
foreach(var item in output) {
// GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);
XYZ newOrigin = new XYZ (origin.X, origin.Y + offset, 0);
XYZ offsetPoint = new XYZ(origin.X + width, origin.Y + offset, 0);
Line L1 = Line.CreateBound(newOrigin,offsetPoint);
try{
TextNote note = TextNote.Create(doc, doc.ActiveView.Id, new XYZ(origin.X - 0.2, origin.Y + offset + 0.01, 0), 0.2, item.linestyleName, options);
DetailCurve e = doc.Create.NewDetailCurve(doc.ActiveView, L1);
Parameter p = e.LookupParameter("Line Style");
p.Set(item.graphicStyle.Id);
}
catch{
}
offset -= 0.03;
}
t.Commit();
}
//TaskDialog.Show("r", sb.ToString());
}
// Create a new list C = A-B
// A = All schedules; B = Schedules on Sheets; C = Schedule not on sheet
public void ListContains()
{
List<string> ls = new List<string> ();
ls.Add("a");
ls.Add("b");
ls.Add("c");
ls.Add("d");
List<string> onSheet = new List<string>();
onSheet.Add("b");
onSheet.Add("d");
string notOnSheet = "";
foreach (var element in ls) {
if (onSheet.Contains(element)){
}
else{
notOnSheet += element + Environment.NewLine;
}
}
TaskDialog.Show("result", notOnSheet);
}
//works in sections only
public void MirrorElements()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> selectedElementRefList = uidoc.Selection.PickObjects(ObjectType.Element, "Select a detail Item");
using (Transaction t = new Transaction(doc, "Mirror Element")){
t.Start();
foreach (Reference eleRef in selectedElementRefList) {
Element selectedElement = doc.GetElement(eleRef);
LocationPoint lp = selectedElement.Location as LocationPoint;
Plane plane = Plane.CreateByNormalAndOrigin(new XYZ(0, 1, 0), lp.Point);
ElementTransformUtils.MirrorElement(doc, eleRef.ElementId, plane);
doc.Delete(eleRef.ElementId);
}
t.Commit();
}
}
public void PickEndPoint(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ObjectSnapTypes snapTypes = ObjectSnapTypes.Endpoints;
Reference selColumn = uidoc.Selection.PickObject(ObjectType.Element, "Select Element");
XYZ point = uidoc.Selection.PickPoint(snapTypes, "Select the destination point");
Element eleColumn = doc.GetElement(selColumn.ElementId);
//Element location curve
LocationCurve locCrv = eleColumn.Location as LocationCurve;
Curve crv = locCrv.Curve;
XYZ lineStart = crv.GetEndPoint(0);
XYZ lineEnd = crv.GetEndPoint(1);
string stPt = lineStart.X.ToString() + "," + lineStart.Y.ToString() + "," + lineStart.Z.ToString();
string endPt = lineEnd.X.ToString() +"," + lineEnd.Y.ToString() + "," + lineEnd.Z.ToString() ;
string pt = point.X.ToString() +"," + point.Y.ToString() + "," + point.Z.ToString() ;
double dist1 = lineStart.DistanceTo(point);
double dist2 = lineEnd.DistanceTo(point);
using (Transaction t = new Transaction(doc)){
t.Start("Move column");
if (dist1<dist2){
Line newColumnLine = Line.CreateBound(lineStart, point);
locCrv.Curve = newColumnLine;
}
else {
Line reverseLine = Line.CreateBound(point,lineEnd);
locCrv.Curve = reverseLine;
}
t.Commit();
}//close using
TaskDialog.Show("Coord", stPt + Environment.NewLine + endPt + Environment.NewLine + pt + Environment.NewLine + dist1.ToString() + Environment.NewLine + dist2.ToString());
}
public void PileBreakLineViewports()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> refe = uidoc.Selection.PickObjects(ObjectType.Element, "Select Viewports");
//get the view from each viewport
IList<ElementId> viewportViewIds = new List<ElementId>();
foreach (Reference r in refe)
{
Viewport vp = doc.GetElement(r) as Viewport;
viewportViewIds.Add(vp.ViewId);
}
Element fecBrakLine = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(x => x.Name == "Arup_Detail_BreakLineCircular").First();
FamilySymbol studSymbol = fecBrakLine as FamilySymbol;
using (Transaction t = new Transaction(doc, "Insert breakline in each viewport")){
t.Start();
//foreach (Reference pileref in pilerefs) {
foreach (ElementId viewId in viewportViewIds)
{
View currentView = doc.GetElement(viewId) as View;
//TaskDialog.Show("r", currentView.Name);
ICollection<ElementId> pileIds = new FilteredElementCollector(doc, currentView.Id).OfCategory(BuiltInCategory.OST_StructuralFoundation).WhereElementIsNotElementType().ToElementIds();
foreach (ElementId pileId in pileIds) {
Element pile = doc.GetElement(pileId);
Location lc = pile.Location as Location;
LocationPoint pilePoint = lc as LocationPoint;
XYZ pileTranslatedPoint = new XYZ(pilePoint.Point.X, pilePoint.Point.Y, pilePoint.Point.Z - 2550/304.8);
FamilyInstance fi = doc.Create.NewFamilyInstance(pileTranslatedPoint, studSymbol, currentView);
fi.LookupParameter("left").Set(310/304.8);
}
}
t.Commit();
}
}
public void NumberPickedPiles() {
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
List<ElementId> elementIds = new List<ElementId>();
int counter = 1;
bool flag = true;
while (flag)
{
try
{
using (Transaction tran = new Transaction(doc, "Pile mark updated"))
{
tran.Start();
Reference reference = uidoc.Selection.PickObject(ObjectType.Element, "Pick elements in the desired order and hit ESC to stop picking.");
Element pile = doc.GetElement(reference);
pile.LookupParameter("Mark").Set("Pile " + counter.ToString());
counter ++;
tran.Commit();
}
}
catch
{
flag = false;
}
}
}
public void placeActiveView()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
View activeView = doc.ActiveView;
using(var form = new Form1())
{
//use ShowDialog to show the form as a modal dialog box.
form.ShowDialog();
//if the user hits cancel just drop out of macro
if(form.DialogResult == forms.DialogResult.Cancel) return;
//create a new variable to store the user input text
string sheetNumber = form.textString.ToString();
ViewSheet viewSh = null;
FilteredElementCollector sheets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet));
foreach (ViewSheet sht in sheets)
{
if (sht.SheetNumber.ToString() == sheetNumber) //find the sheet that matches the user input text
viewSh = sht;
}
//TaskDialog.Show("out","Selected sheet Id: " + viewSh.Id.ToString());
using (Transaction t = new Transaction(doc))
{
t.Start("Add view to sheet");
try
{
Viewport vp = Viewport.Create(doc, viewSh.Id, activeView.Id, new XYZ(0,0,0));
t.Commit();
}
/*
catch (System.NullReferenceException ex)
{
TaskDialog.Show("Exception Caught", "The Sheet Number does not exists");
t.RollBack();
placeActiveView();
}
*/ catch
{
if (sheetNumber == ""){
TaskDialog.Show("Warning","Please enter a sheet number");
//t.RollBack();
placeActiveView();
}
else if (viewSh == null){
TaskDialog.Show("Warning","The sheet number does not exist");
t.RollBack();
placeActiveView();
}
else {
TaskDialog.Show("Warning","The view is already placed on another sheet");
t.RollBack();
placeActiveView();
}
}
//close using
}
//close Form1
}
//close placeActiveView
}
//Revit Macro
public void PlaceBeams()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id);
//first method
IList<Element> WallsInView = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
IList<Level> lvl = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast<Level>().Where(X => X.Name.Equals("02")).ToList();
Level level = lvl.First();
Line curve = Line.CreateBound(new XYZ(0,0,0), new XYZ(10,0,0));
List<FamilySymbol> Fs = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol))
.OfCategory(BuiltInCategory.OST_StructuralFraming).Cast<FamilySymbol>()
.ToList();
FamilySymbol symb = Fs.First();
using (Transaction t = new Transaction(doc, "strip")){
t.Start();
Element newBeam = doc.Create.NewFamilyInstance(curve, symb, level, Autodesk.Revit.DB.Structure.StructuralType.Beam);
newBeam.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM).Set(level.Id);
newBeam.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END0_ELEVATION).Set(0);
newBeam.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END1_ELEVATION).Set(0);
t.Commit();
}
}
private void DrawDimension(Document doc, Reference refPlaneLine, FamilyInstance fi1, double offset){
ReferencePlane refP = doc.GetElement(refPlaneLine) as ReferencePlane;
//FamilyInstance fi1 = doc.GetElement(opening1) as FamilyInstance;
IList<Reference> fir1 = fi1.GetReferences(FamilyInstanceReferenceType.WeakReference);
XYZ refPlanePoint = refP.FreeEnd;//end point of reference plane
LocationPoint lp = fi1.Location as LocationPoint;
XYZ direction = refP.Normal;//perpendicular direction to reference plane
Plane p = Plane.CreateByNormalAndOrigin(direction, refP.FreeEnd);
XYZ startPoint = ProjectOnto(p, lp.Point) + offset * refP.Direction;
double distance = 1000;
//direction = direction / direction.GetLength();
XYZ endPoint = startPoint + distance * direction;
Line dimensionLine= Line.CreateBound(startPoint, endPoint);
ReferenceArray references = new ReferenceArray();
references.Append(fir1.First());
references.Append(refPlaneLine);
// lockedAlign = doc.Create.NewAlignment(view, r1, r2)
Dimension d = doc.Create.NewDimension(doc.ActiveView, dimensionLine, references);
d.IsLocked = true;
}
public void PlaceDimension(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> openings = uidoc.Selection.PickObjects(ObjectType.Element, "Select openings");
List<FamilyInstance> fa = new List<FamilyInstance>();
foreach (Reference refe in openings) {
fa.Add(doc.GetElement(refe) as FamilyInstance);
}
var grouped = fa.GroupBy(x => x.Host);
double offset = 500/304.8;
Reference refPlaneLine = uidoc.Selection.PickObjects(ObjectType.Element, "Select a ref plane").First();
using (Transaction t = new Transaction(doc, "Lock dim")){
t.Start();
foreach (var element in grouped) {
foreach (FamilyInstance item in element) {
offset += 500/304.8;
DrawDimension(doc, refPlaneLine, item, offset);
}
// offset = 500/304.8;
}
t.Commit();
}
}
public void PopulateDropDown()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
List<View> allViewTemplates = Helpers.collectTemplates(doc);
using(var forma = new Form2(doc)){
//use ShowDialog to show the form as a modal dialog box.
forma.ShowDialog();
TaskDialog.Show("result",allViewTemplates[forma.chosenView].Name);
}
copy "$(ProjectDir)*.addin" "$(AppData)\Autodesk\Revit\Addins\2019"
copy "$(ProjectDir)bin\debug\*.dll" "$(AppData)\Autodesk\Revit\Addins\2019\ReviTab"
copy "$(ProjectDir)*.addin" "$(AppData)\Autodesk\Revit\Addins\2018"
copy "$(ProjectDir)bin\debug\*.dll" "$(AppData)\Autodesk\Revit\Addins\2018\ReviTab"
copy "$(ProjectDir)*.addin" "$(AppData)\Autodesk\Revit\Addins\2017"
copy "$(ProjectDir)bin\debug\*.dll" "$(AppData)\Autodesk\Revit\Addins\2017\ReviTab"
public void RebarToSolid()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ICollection<Element> rebers = new FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_Rebar).ToElements();
List<Rebar> List_Rebar = new List<Rebar>();
if(rebers==null)
{
TaskDialog.Show("REBAR", "NO REBAR EXISTS IN THE DRAWINGS");
}
Transaction trans = new Transaction(doc);
trans.Start("ACTRAN");
IEnumerable<ViewFamilyType> VFT = from Element in new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)) let type = Element as ViewFamilyType where type.ViewFamily == ViewFamily.ThreeDimensional select type;
View3D v3d = doc.ActiveView as View3D;
foreach(Rebar r in rebers)
{
r.SetSolidInView(v3d, true);
List_Rebar.Add(r);
}
trans.Commit();
}
#credits https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2016/ENU/Revit-API/files/GUID-B3EE488D-2287-49A2-A772-C7164B84A648-htm.html
public void RoomHeight()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
//Collect all the floors in the model
ICollection<ElementId> selectedIds = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors).ToElementIds();
//Select a Room to evaluate
Element roomElement = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element,new RoomSelectionFilter(), "Select a Room").ElementId);
//Get the room location point
LocationPoint roomCenter = roomElement.Location as LocationPoint;
//Convert the location point to XYZ point
XYZ roomXYZ = roomCenter.Point;
//Move the point up by 1 feet or the ReferenceIntersector will return that floor
roomXYZ = new XYZ(roomXYZ.X,roomXYZ.Y,roomXYZ.Z+1);
//Get a 3d View to perform the intersection (any 3d view but not a View Template)
Func<View3D, bool> isNotTemplate = v3 => !(v3.IsTemplate);
View3D view3D = new FilteredElementCollector(doc).OfClass(typeof(View3D)).WhereElementIsNotElementType().Cast<View3D>().FirstOrDefault(isNotTemplate);
//Ray direction (vertical up)
XYZ rayDirection = new XYZ(0, 0, 1);
//Set the filter for the ReferenceIntersector to the tpye we want (Floor or Ceiling or Roof)
ElementClassFilter filter = new ElementClassFilter(typeof(Floor));
//Create the ReferenceIntersector
ReferenceIntersector refIntersector = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);
//Shoot the ray
ReferenceWithContext referenceWithContext = refIntersector.FindNearest(roomXYZ, rayDirection);
//Retrieve the reference found
Reference reference = referenceWithContext.GetReference();
//Retrieve the intersection point
XYZ intersection = reference.GlobalPoint;
//Calculate the height of the room (remember we moved the room XYZ point up by 1)
TaskDialog.Show("RoomLocation", ((intersection.Z-roomXYZ.Z+1)*304.8).ToString());
}
}//close class
public class RoomSelectionFilter : ISelectionFilter
{
public bool AllowElement(Element element)
{
if (element.Category.Name == "Rooms")
{
return true;
}
return false;
}
public bool AllowReference(Reference refer, XYZ point)
{
return false;
}
public void RotateInPlace()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ICollection<ElementId> selectedElementsId = uidoc.Selection.GetElementIds();
using (Transaction t = new Transaction(doc, "Rotate")){
t.Start();
foreach (ElementId eid in selectedElementsId) {
TextElement e = doc.GetElement(eid) as TextElement;
//XYZ center = e.get_BoundingBox(doc.ActiveView).Max - e.get_BoundingBox(doc.ActiveView).Min;
XYZ baseVector = e.BaseDirection;
XYZ upVector = e.UpDirection;
XYZ center = e.Coord + new XYZ(0,0,e.Width*100/2) - upVector.Normalize()*e.Height*100/2; //100 is the view scale
XYZ sec = center + 3 * upVector.Normalize();
//doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(center,sec));
XYZ normalVector = baseVector.CrossProduct(upVector);
Line axis = Line.CreateUnbound(center, normalVector);
ElementTransformUtils.RotateElement(doc, eid, axis, Math.PI);
}
t.Commit();
}
}
public void RevitLinksInfo()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
//select all the link instances
FilteredElementCollector collector = new FilteredElementCollector(doc);
collector.OfClass(typeof(RevitLinkInstance));
//create a string to store the results
System.Text.StringBuilder linkedDocs = new System.Text.StringBuilder();
foreach (Element elem in collector)
{
try{
//link instance
RevitLinkInstance instance = elem as RevitLinkInstance;
//link type
ElementId rvtLinkTypeId = instance.GetTypeId();
RevitLinkType rvtLinkType = doc.GetElement(rvtLinkTypeId) as RevitLinkType;
//Loaded/Unloaded/Locally Unloaded
string linkStatus = rvtLinkType.GetExternalFileReference().GetLinkedFileStatus().ToString();
//Overlay or Attachment
Parameter referenceType = rvtLinkType.get_Parameter(BuiltInParameter.RVT_LINK_REFERENCE_TYPE);
//Get File Path
ExternalFileReference externalLink = rvtLinkType.GetExternalFileReference();
string path = ModelPathUtils.ConvertModelPathToUserVisiblePath(externalLink.GetAbsolutePath());
linkedDocs.AppendLine(String.Format("{0},{1},{2},{3},{4} ",rvtLinkType.Name,linkStatus,referenceType.AsValueString(),rvtLinkType.PathType.ToString(), path));
}
catch(Exception ex){
TaskDialog.Show("error", ex.Message);
}
}
// TaskDialog.Show("Revit Links in Document", linkedDocs.ToString());
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\Temp\RevitLinks.txt"))
{
sw.WriteLine(linkedDocs);
}
TaskDialog.Show("Done", "The file has been saved to C:\\Temp\\RevitLinks.txt");
}
public void Flatten()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
List<Element> col = new List<Element>();
Reference r = uidoc.Selection.PickObject(ObjectType.Element, "Select Element");
col.Add(doc.GetElement(r));
Options geometryOptions = new Options();
ElementId cat1Id = new ElementId(BuiltInCategory.OST_Walls);
DirectShapeLibrary dsLib = DirectShapeLibrary.GetDirectShapeLibrary(doc);
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Convert elements to DirectShapes" );
foreach( Element e in col )
{
GeometryElement gelt = e.get_Geometry(
geometryOptions );
if( null != gelt )
{
string appDataGUID = e.Id.ToString();
try
{
string familyName = "MyFamily";
DirectShapeType dsType1 = DirectShapeType.Create(doc, familyName, cat1Id);
dsType1.SetShape(new List<GeometryObject>( gelt ) );
dsLib.AddDefinitionType(familyName, dsType1.Id);
Transform trs = Transform.Identity;
DirectShape ds1 = DirectShape.CreateElementInstance(doc, dsType1.Id, cat1Id, familyName, trs);
// Delete original element
doc.Delete( e.Id );
TaskDialog.Show("Result", "Element Flattened");
}
catch( Exception ex )
{
TaskDialog.Show("Error", ex.Message);
}
}
}
tx.Commit();
}
}
public void SectionMark()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Element> sectionsList = new FilteredElementCollector(doc).WhereElementIsNotElementType().OfClass(typeof(ViewSection)).Where(x=>x.Name.StartsWith("304")).ToList();
TextNoteOptions options = new TextNoteOptions();
options.HorizontalAlignment = HorizontalTextAlignment.Center;
options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
using (Transaction t = new Transaction(doc,"Add view names")){
t.Start();
foreach (View ele in sectionsList) {
View view = ele as View;
try{
ViewCropRegionShapeManager vcr = view.GetCropRegionShapeManager();
CurveLoop cloop = vcr.GetAnnotationCropShape();
List<XYZ> pts = new List<XYZ>();
foreach (Curve crv in cloop)
{
pts.Add(crv.GetEndPoint(0));
pts.Add(crv.GetEndPoint(1));
}
//View centroid with elements hidden
XYZ viewCropCenter = GetCentroid(pts, pts.Count);
XYZ viewCenter = view.Origin;
XYZ stPt = new XYZ(view.Origin.X, 0, view.Origin.Y);
XYZ endPt = new XYZ(stPt.X + 20, 0, stPt.Y + 0);
//TaskDialog.Show("r", String.Format("{0},{1},{2}", viewCenter.X, viewCenter.Y, viewCenter.Z));
Plane plane = Plane.CreateByNormalAndOrigin(view.ViewDirection, view.Origin);
//SketchPlane sp = SketchPlane.Create(doc, plane);
BoundingBoxXYZ bbox = view.CropBox;
Line li = Line.CreateBound(view.Origin, endPt);
//doc.Create.NewDetailCurve(view, li);
XYZ centroid = bbox.Max - bbox.Min;
//XYZ noteOffset = new XYZ(view.Origin.X, 0, 0);
//XYZ noteOffset = view.Origin + plane.XVec.Normalize()*(-300);
XYZ noteOffset = view.Origin + plane.XVec.Normalize()*(-50) +plane.YVec.Normalize()*(-90);
//noteOffset = noteOffset + plane.YVec.Normalize()*10;
TextNote.Create(doc, view.Id, noteOffset , 1, "" + view.Name, options);
}
catch{
//TaskDialog.Show("R", view.Name);
}
}
t.Commit();
}
TaskDialog.Show("result","done");
}
public void SelectInViewports()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> refe = uidoc.Selection.PickObjects(ObjectType.Element, "Select Viewports");
IList<ElementId> viewportViewIds = new List<ElementId>();
foreach (Reference r in refe)
{
Viewport vp = doc.GetElement(r) as Viewport;
viewportViewIds.Add(vp.ViewId);
}
ICollection<ElementId> toBeSelected = new List<ElementId>();
foreach (ElementId viewId in viewportViewIds)
{
//element to select
ICollection<ElementId> fec = new FilteredElementCollector(doc, viewId).OfCategory(BuiltInCategory.OST_StructuralColumnTags).WhereElementIsNotElementType().ToElementIds();
foreach (ElementId item in fec)
{
toBeSelected.Add(item);
}
}
uidoc.Selection.SetElementIds(toBeSelected);
}
public void ChangeMaterial(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference s = uidoc.Selection.PickObject(ObjectType.Element,"select");
ElementId materialId = new ElementId(509467);
DirectShape ds = doc.GetElement(s) as DirectShape;
Autodesk.Revit.DB.Options opt = new Options();
Autodesk.Revit.DB.GeometryElement geomElem = doc.GetElement(s).get_Geometry(opt);
Solid geomSolid = null;
foreach (GeometryObject geomObj in geomElem)
{
geomSolid = geomObj as Solid;
}
using (Transaction t = new Transaction(doc, "isolate view")){
t.Start();
foreach (Face geomFace in geomSolid.Faces) {
doc.Paint(s.ElementId, geomFace, materialId);
}
t.Commit();
}
}
public void SetScalebarScale()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ViewSheet sheet = doc.ActiveView as ViewSheet;
FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id);
collector.OfCategory(BuiltInCategory.OST_TitleBlocks);
Element sheetTitleblock = collector.ToElements().FirstOrDefault();
//TaskDialog.Show("result", sheetTitleblock.Name);
List<int> scaleValues = new List<int>();
foreach( ElementId idVp in sheet.GetAllViewports() )
{
try
{
View view = doc.GetElement(vp.ViewId) as View;
if (view.ViewType != ViewType.Legend && view.ViewType != ViewType.ThreeD)
{
Parameter scale = vp.get_Parameter(BuiltInParameter.VIEW_SCALE);
scaleValues.Add(scale.AsInteger());
}
}
catch
{
}
}
//int scaleBarValue = scaleValues.GroupBy(x => x).First().First();
var scaleBarValue = scaleValues.GroupBy(x => x)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
int longestArray = scaleBarValue.OrderBy(x => x.Counter).Last().Element;
using (Transaction t = new Transaction(doc, "Set scalebar")){
t.Start();
//TaskDialog.Show("result", scaleBarValue.ToString());
Parameter tbScalebar = sheetTitleblock.LookupParameter("Scalebar scale");
tbScalebar.Set(longestArray);
t.Commit();
}
}
public void SheetManager()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
ICollection<ElementId> selectedSheetsId = uidoc.Selection.GetElementIds();
ICollection<ViewSheet> selectedSheets = new List<ViewSheet>();
foreach (var eid in selectedSheetsId) {
selectedSheets.Add(doc.GetElement(eid) as ViewSheet);
}
uidoc.ActiveView = uidoc.ActiveGraphicalView;
XYZ origin = uidoc.Selection.PickPoint("Select insertion point");
double Yoffset = origin.Y;
double width = 0.5; //feet
TextNoteOptions options = new TextNoteOptions();
options.HorizontalAlignment = HorizontalTextAlignment.Left;
options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
ICollection<Element> allLegends = new FilteredElementCollector(doc).OfClass(typeof(View)).ToList();
List<Tuple<string, string>> result = new List<Tuple<string, string>>();
var sortedList = selectedSheets.OrderBy(pd => pd.SheetNumber);
string headers = "Sheet Numbers; LegendIds; Legend Positions; LegendNames";
string sheetNumbers = "";
string legendIds = "";
string legendName = "";
string legendPosition = "";
foreach (ViewSheet vs in sortedList) {
ICollection<ElementId> viewports = vs.GetAllViewports();
foreach (var vpid in viewports) {
Viewport vport = doc.GetElement(vpid) as Viewport;
View view = doc.GetElement(vport.ViewId) as View;
if (view.ViewType == ViewType.Legend){
result.Add (new Tuple<string, string>(vs.SheetNumber.ToString(), vpid.ToString()));
sheetNumbers += vs.SheetNumber.ToString() +"; \n";
legendIds += vpid.ToString() +";\n";
legendName += view.Name+";\n";
legendPosition += vport.GetBoxCenter()+";\n";
}
}
}
using (Transaction t = new Transaction(doc, "Place text"))
{
t.Start();
XYZ headersPos = new XYZ(origin.X, Yoffset+0.02, 0);
XYZ col1 = new XYZ(origin.X, Yoffset, 0);
XYZ col2 = new XYZ(origin.X+0.05, Yoffset, 0);
XYZ col3 = new XYZ(origin.X+0.10, Yoffset, 0);
XYZ col4 = new XYZ(origin.X+0.35, Yoffset, 0);
TextNote noteHeader = TextNote.Create(doc, doc.ActiveView.Id, headersPos, width, headers, options);
TextNote note1 = TextNote.Create(doc, doc.ActiveView.Id, col1, 0.05, sheetNumbers, options);
TextNote note2 = TextNote.Create(doc, doc.ActiveView.Id, col2, 0.05, legendIds, options);
TextNote note3 = TextNote.Create(doc, doc.ActiveView.Id, col3, width, legendPosition, options);
TextNote note4 = TextNote.Create(doc, doc.ActiveView.Id, col4, width, legendName, options);
t.Commit();
}
}
// Display the content of a list in a Task Dialog
string s = "";
foreach (var element in vs)
{
s += element.Name + Environment.NewLine;
}
TaskDialog.Show("Schedules", s);
public void SourceEndPoint(){
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference refToMove = uidoc.Selection.PickObject(ObjectType.Element, "Select Element to be moved");
Reference refSource = uidoc.Selection.PickObject(ObjectType.Element, "Select Source Element");
Element eleToMove = doc.GetElement(refToMove.ElementId);
//Element location curve
LocationCurve locCrv = eleToMove.Location as LocationCurve;
Curve crv = locCrv.Curve;
XYZ lineStart = crv.GetEndPoint(0);
XYZ lineEnd = crv.GetEndPoint(1);
Element eleSource = doc.GetElement(refSource.ElementId);
LocationCurve sourceCurve = eleSource.Location as LocationCurve;
Curve sourceCrv = sourceCurve.Curve;
XYZ sourceStart = sourceCrv.GetEndPoint(0);
XYZ sourceEnd = sourceCrv.GetEndPoint(1);
double dist1 = lineStart.DistanceTo(sourceEnd);
double dist2 = lineEnd.DistanceTo(sourceEnd);
double dist3 = lineStart.DistanceTo(sourceStart);
double dist4 = lineEnd.DistanceTo(sourceStart);
Dictionary<string, double> dict = new Dictionary<string, double>();
dict.Add("d1", dist1);
dict.Add("d2", dist2);
dict.Add("d3", dist3);
dict.Add("d4", dist4);
var val = dict.OrderBy(k => k.Value).FirstOrDefault();
string keyR = val.Key;
using (Transaction t = new Transaction(doc)){
t.Start("Move column");
if (keyR == "d1"){
Line newColumnLine = Line.CreateBound(sourceEnd, lineEnd);
locCrv.Curve = newColumnLine;
}
else if (keyR == "d2"){
Line newColumnLine = Line.CreateBound(lineStart, sourceEnd);
locCrv.Curve = newColumnLine;
}
else if (keyR == "d3"){
Line newColumnLine = Line.CreateBound(sourceStart, lineEnd);
locCrv.Curve = newColumnLine;
}
else if (keyR == "d4"){
Line newColumnLine = Line.CreateBound(lineStart, sourceStart);
locCrv.Curve = newColumnLine;
}
else{
TaskDialog.Show("Error", "Error");
}
t.Commit();
}//close using
//TaskDialog.Show("result", keyR + Environment.NewLine + dist1.ToString() + "\n" + dist2.ToString() + "\n" + dist3.ToString() + "\n" + dist4.ToString());
}
public void SplitColumn(){
Application app = this.Application;
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
Reference refColumn = uidoc.Selection.PickObject(ObjectType.Element,"Select a column");
Element eleColumn = uidoc.Document.GetElement(refColumn);
Reference refLevel = uidoc.Selection.PickObject(ObjectType.Element,"Select a Level");
Element eleLevel = uidoc.Document.GetElement(refLevel);
TaskDialog.Show("title", eleColumn.Name);
}
public void SplitCells()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
IList<Reference> lineToSplitRef = uidoc.Selection.PickObjects(ObjectType.Element, "select line to split");
ObjectSnapTypes snapTypes = ObjectSnapTypes.Intersections;
XYZ ptOne = uidoc.Selection.PickPoint(snapTypes, "Select Point1");
XYZ ptTwo = uidoc.Selection.PickPoint(snapTypes, "Select Point2");
using (Transaction t = new Transaction(doc, "Split Line")){
t.Start();
foreach (Reference refe in lineToSplitRef) {
SplitLines(doc, refe, ptOne, ptTwo);
}
t.Commit();
}
// CurveElement lineToSplit = doc.GetElement(lineToSplitRef) as CurveElement;
//
// LocationCurve lc = lineToSplit.Location as LocationCurve;
//
// Line line = lc.Curve as Line;
//
// foreach (var splitter in splitLines) {
// CurveElement split = doc.GetElement(splitter) as CurveElement;
// LocationCurve splitLc = split.Location as LocationCurve;
// Line splitLine = splitLc.Curve as Line;
// XYZ point = GetIntersection(line, splitLine);
// }
//
// IntersectionResultArray ira = null;
// XYZ intersectionPoint = null;
//
// if(curve1.Intersect(curve2, out ira) == SetComparisonResult.Overlap)
// {
// intersectionPoint = ira.get_Item(0).XYZPoint;
// }
//
// double paraIntersection1 = curve1.Project(intersectionPoint).Parameter;
// double paraIntersection2 = curve2.Project(intersectionPoint).Parameter;
//
//
//
// Curve c11 = curve1.Clone();
// c11.MakeBound(curve1.GetEndParameter(0), paraIntersection1);
// Curve c12 = curve1.Clone();
// c12.MakeBound(paraIntersection1, curve1.GetEndParameter(1));
//
// Curve c21 = curve2.Clone();
// c21.MakeBound(curve2.GetEndParameter(0), paraIntersection2);
// Curve c22 = curve2.Clone();
// c22.MakeBound(paraIntersection2, curve2.GetEndParameter(1));
}
private bool SplitLines(Document doc, Reference lineToSplitRef, XYZ ptOne, XYZ ptTwo){
try{
LocationCurve locLineCrv = doc.GetElement(lineToSplitRef).Location as LocationCurve;
Curve crv = locLineCrv.Curve;
XYZ pt1 = crv.Project(ptOne).XYZPoint;
Line l1 = Line.CreateBound(ClosestPoint(pt1, crv), pt1);
doc.Create.NewDetailCurve(doc.ActiveView, l1);
XYZ pt2 = crv.Project(ptTwo).XYZPoint;
Line l2 = Line.CreateBound(ClosestPoint(pt2, crv), pt2);
doc.Create.NewDetailCurve(doc.ActiveView, l2);
doc.Delete(lineToSplitRef.ElementId);
return true;
}
catch{
return false;
}
}
private XYZ ClosestPoint(XYZ pt1, Curve crv){
double d1 = crv.GetEndPoint(0).DistanceTo(pt1);
double d2 = crv.GetEndPoint(1).DistanceTo(pt1);
if (d1<d2){
return crv.GetEndPoint(0);
}
else{
return crv.GetEndPoint(1);
}
}
public void DisableWarnings()
{
Application app = this.Application;
app.FailuresProcessing += Application_FailuresProcessing;
string[] filePath = System.IO.Directory.GetFiles(@"C:\Users\giovanni.brogiolo\Documents\Animation");
ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath[0]);
OpenOptions optionDetach = new OpenOptions();
optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
Document openDoc = app.OpenDocumentFile(modelP, optionDetach);
openDoc.Close(false);
TaskDialog.Show("Result", filePath[0]);
}
void Application_FailuresProcessing(object sender, Autodesk.Revit.DB.Events.FailuresProcessingEventArgs e)
{
FailuresAccessor fa = e.GetFailuresAccessor();
IList<FailureMessageAccessor> failList = new List<FailureMessageAccessor>();
failList = fa.GetFailureMessages(); // Inside event handler, get all warnings
foreach (FailureMessageAccessor failure in failList)
{
fa.DeleteWarning(failure);
// check FailureDefinitionIds against ones that you want to dismiss, FailureDefinitionId failID = failure.GetFailureDefinitionId();
// prevent Revit from showing Unenclosed room warnings
FailureDefinitionId failID = failure.GetFailureDefinitionId();
if (failID == BuiltInFailures.WorksharingFailures.DuplicateNamesChanged)
{
fa.DeleteWarning(failure);
}
}
public void TextFonts()
{
UIDocument uidoc = this.ActiveUIDocument;
Document doc = uidoc.Document;
XYZ origin = uidoc.Selection.PickPoint("Select insertion point");
double Yoffset = origin.Y;
double width = 0.5; //feet
TextNoteOptions options = new TextNoteOptions();
options.HorizontalAlignment = HorizontalTextAlignment.Left;
options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
ICollection<Element> textNoteTypes = new FilteredElementCollector(doc).OfClass( typeof( TextNoteType ) ).OrderBy(x => x.Name).ToList();
using (Transaction t = new Transaction(doc, "Place text")){
t.Start();
foreach (Element e in textNoteTypes) {
TextNoteType textNoteElement = doc.GetElement(e.Id) as TextNoteType;
double fontSize = Convert.ToDouble(textNoteElement.LookupParameter("Text Size").AsValueString().Replace("mm",""))/304.8;
double borderOffset = textNoteElement.LookupParameter("Leader/Border Offset").AsDouble();
XYZ offsetPoint = new XYZ(origin.X, Yoffset, 0);
TextNote note = TextNote.Create(doc, doc.ActiveView.Id, offsetPoint, width, textNoteElement.Name, options);
note.ChangeTypeId(e.Id);
Yoffset -= (fontSize + borderOffset*2 + 0.03);
}
t.Commit();
}
}
private void InitializeComponent()
{
this.ok_btn = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.comboBoxCategory = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.btn_cancel = new System.Windows.Forms.Button();
this.textBoxWidth = new System.Windows.Forms.TextBox();
this.textBoxHeight = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.checkBoxStart = new System.Windows.Forms.CheckBox();
this.checkBoxEnd = new System.Windows.Forms.CheckBox();
this.checkBoxMidPoint = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// ok_btn
//
this.ok_btn.DialogResult = System.Windows.Forms.DialogResult.OK;
this.ok_btn.Location = new System.Drawing.Point(38, 207);
this.ok_btn.Name = "ok_btn";
this.ok_btn.Size = new System.Drawing.Size(90, 29);
this.ok_btn.TabIndex = 0;
this.ok_btn.Text = "OK";
this.ok_btn.UseCompatibleTextRendering = true;
this.ok_btn.UseVisualStyleBackColor = true;
this.ok_btn.Click += new System.EventHandler(this.Ok_btnClick);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 161);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(261, 20);
this.textBox1.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(12, 141);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(249, 15);
this.label1.TabIndex = 2;
this.label1.Text = "Offset";
this.label1.UseCompatibleTextRendering = true;
//
// comboBoxCategory
//
this.comboBoxCategory.FormattingEnabled = true;
this.comboBoxCategory.Location = new System.Drawing.Point(13, 29);
this.comboBoxCategory.Name = "comboBoxCategory";
this.comboBoxCategory.Size = new System.Drawing.Size(261, 21);
this.comboBoxCategory.Sorted = true;
this.comboBoxCategory.TabIndex = 3;
this.comboBoxCategory.SelectedIndexChanged += new System.EventHandler(this.ComboBoxCategorySelectedIndexChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(13, 11);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(155, 15);
this.label2.TabIndex = 5;
this.label2.Text = "Select Opening Family";
this.label2.UseCompatibleTextRendering = true;
//
// btn_cancel
//
this.btn_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btn_cancel.Location = new System.Drawing.Point(157, 207);
this.btn_cancel.Name = "btn_cancel";
this.btn_cancel.Size = new System.Drawing.Size(86, 29);
this.btn_cancel.TabIndex = 6;
this.btn_cancel.Text = "Cancel";
this.btn_cancel.UseCompatibleTextRendering = true;
this.btn_cancel.UseVisualStyleBackColor = true;
//
// textBoxWidth
//
this.textBoxWidth.Location = new System.Drawing.Point(12, 74);
this.textBoxWidth.Name = "textBoxWidth";
this.textBoxWidth.Size = new System.Drawing.Size(100, 20);
this.textBoxWidth.TabIndex = 7;
//
// textBoxHeight
//
this.textBoxHeight.Location = new System.Drawing.Point(173, 74);
this.textBoxHeight.Name = "textBoxHeight";
this.textBoxHeight.Size = new System.Drawing.Size(100, 20);
this.textBoxHeight.TabIndex = 8;
//
// label3
//
this.label3.Location = new System.Drawing.Point(13, 56);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 15);
this.label3.TabIndex = 9;
this.label3.Text = "Width";
this.label3.UseCompatibleTextRendering = true;
//
// label4
//
this.label4.Location = new System.Drawing.Point(173, 56);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(100, 15);
this.label4.TabIndex = 10;
this.label4.Text = "Height";
this.label4.UseCompatibleTextRendering = true;
//
// checkBoxStart
//
this.checkBoxStart.Location = new System.Drawing.Point(12, 105);
this.checkBoxStart.Name = "checkBoxStart";
this.checkBoxStart.Size = new System.Drawing.Size(104, 24);
this.checkBoxStart.TabIndex = 11;
this.checkBoxStart.Text = "Start Point";
this.checkBoxStart.UseCompatibleTextRendering = true;
this.checkBoxStart.UseVisualStyleBackColor = true;
this.checkBoxStart.Click += new System.EventHandler(this.CheckBoxStart_Click);
//
// checkBoxEnd
//
this.checkBoxEnd.Location = new System.Drawing.Point(205, 105);
this.checkBoxEnd.Name = "checkBoxEnd";
this.checkBoxEnd.Size = new System.Drawing.Size(104, 24);
this.checkBoxEnd.TabIndex = 12;
this.checkBoxEnd.Text = "End Point";
this.checkBoxEnd.UseCompatibleTextRendering = true;
this.checkBoxEnd.UseVisualStyleBackColor = true;
this.checkBoxEnd.Click += new System.EventHandler(this.CheckBoxEnd_Click);
//
// checkBoxMidPoint
//
this.checkBoxMidPoint.Checked = true;
this.checkBoxMidPoint.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxMidPoint.Location = new System.Drawing.Point(105, 105);
this.checkBoxMidPoint.Name = "checkBoxMidPoint";
this.checkBoxMidPoint.Size = new System.Drawing.Size(73, 24);
this.checkBoxMidPoint.TabIndex = 13;
this.checkBoxMidPoint.Text = "Mid Point";
this.checkBoxMidPoint.UseCompatibleTextRendering = true;
this.checkBoxMidPoint.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(289, 248);
this.Controls.Add(this.checkBoxMidPoint);
this.Controls.Add(this.checkBoxEnd);
this.Controls.Add(this.checkBoxStart);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBoxHeight);
this.Controls.Add(this.textBoxWidth);
this.Controls.Add(this.btn_cancel);
this.Controls.Add(this.label2);
this.Controls.Add(this.comboBoxCategory);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.ok_btn);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Place Instance By Face";
this.Load += new System.EventHandler(this.Form1Load);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.CheckBox checkBoxMidPoint;
private System.Windows.Forms.CheckBox checkBoxEnd;
private System.Windows.Forms.CheckBox checkBoxStart;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxHeight;
private System.Windows.Forms.TextBox textBoxWidth;
private System.Windows.Forms.Button btn_cancel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox comboBoxCategory;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button ok_btn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment