Esempio n. 1
0
        public void CopyElementsBetweenSheets(SheetCopierViewHost sheet)
        {
            IList <ElementId> list = new List <ElementId>();

            using (var collector = new FilteredElementCollector(doc))
            {
                collector.OwnedByView(sheet.SourceSheet.Id);
                foreach (Element e in collector)
                {
                    if (!(e is Viewport))
                    {
                        if (e is CurveElement)
                        {
                            continue;
                        }
                        if (e.IsValidObject && e.ViewSpecific)
                        {
                            list.Add(e.Id);
                        }
                    }
                }
            }
            if (list.Count > 0)
            {
                Transform        transform;
                CopyPasteOptions options;
                ElementTransformUtils.CopyElements(
                    sheet.SourceSheet,
                    list,
                    sheet.DestinationSheet,
                    transform = new Transform(ElementTransformUtils.GetTransformFromViewToView(sheet.SourceSheet, sheet.DestinationSheet)),
                    options   = new CopyPasteOptions());
                if (Settings.Default.DeleteRevisionClouds)
                {
                    DeleteRevisionClouds(sheet.DestinationSheet.Id, doc);
                }
                options.Dispose();
                transform.Dispose();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Copies all view-specific elements from a source view to a target view.
        /// </summary>
        /// <remarks>
        /// The source and target views do not have to be in the same document.
        /// </remarks>
        /// <param name="fromView">The source view.</param>
        /// <param name="toView">The target view.</param>
        /// <returns>The number of new elements created during the copy operation.</returns>
        private static int DuplicateDetailingAcrossViews(View fromView,
                                                         View toView)
        {
            // Collect view-specific elements in source view
            FilteredElementCollector collector = new FilteredElementCollector(fromView.Document, fromView.Id);

            // Skip elements which don't have a category.  In testing, this was
            // the revision table and the extents element, which should not be copied as they will
            // be automatically created for the copied view.
            collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true));

            // Get collection of elements to copy for CopyElements()
            ICollection <ElementId> toCopy = collector.ToElementIds();

            // Return value
            int numberOfCopiedElements = 0;

            if (toCopy.Count > 0)
            {
                using (Transaction t2 = new Transaction(toView.Document, "Duplicate view detailing"))
                {
                    t2.Start();
                    // Set handler to skip the duplicate types dialog
                    CopyPasteOptions options = new CopyPasteOptions();
                    options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                    // Copy the elements using no transformation
                    ICollection <ElementId> copiedElements =
                        ElementTransformUtils.CopyElements(fromView, toCopy, toView, Transform.Identity, options);
                    numberOfCopiedElements = copiedElements.Count;

                    // Set failure handler to skip any duplicate types warnings that are posted.
                    FailureHandlingOptions failureOptions = t2.GetFailureHandlingOptions();
                    failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor());
                    t2.Commit(failureOptions);
                }
            }

            return(numberOfCopiedElements);
        }
Esempio n. 3
0
        /// <summary>
        /// Attempt to set the plane of an existing SketchPlane
        /// </summary>
        /// <param name="p"></param>
        /// <returns>False if the new sketch plane is not parallel to the existing one</returns>
        private bool InternalSetPlane(Autodesk.Revit.DB.Plane p)
        {
            var sp = this.InternalSketchPlane;

            XYZ newOrigin = p.Origin;
            XYZ newNorm   = p.Normal;
            var oldP      = sp.GetPlane();
            XYZ oldOrigin = oldP.Origin;
            XYZ oldNorm   = oldP.Normal;

            if (oldNorm.IsAlmostEqualTo(newNorm))
            {
                XYZ moveVec = newOrigin - oldOrigin;
                if (moveVec.GetLength() > 0.000000001)
                {
                    ElementTransformUtils.MoveElement(Document, sp.Id, moveVec);
                }
                return(true);
            }

            return(false);
        }
Esempio n. 4
0
        /// <summary>
        /// Create one rectangular extrusion
        /// </summary>
        private void CreateExtrusion()
        {
            try
            {
                #region Create rectangle profile
                CurveArrArray curveArrArray = new CurveArrArray();
                CurveArray    curveArray1   = new CurveArray();

                Autodesk.Revit.DB.XYZ normal      = Autodesk.Revit.DB.XYZ.BasisZ;
                SketchPlane           sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero);

                // create one rectangular extrusion
                Autodesk.Revit.DB.XYZ p0 = Autodesk.Revit.DB.XYZ.Zero;
                Autodesk.Revit.DB.XYZ p1 = new Autodesk.Revit.DB.XYZ(10, 0, 0);
                Autodesk.Revit.DB.XYZ p2 = new Autodesk.Revit.DB.XYZ(10, 10, 0);
                Autodesk.Revit.DB.XYZ p3 = new Autodesk.Revit.DB.XYZ(0, 10, 0);
                Line line1 = Line.CreateBound(p0, p1);
                Line line2 = Line.CreateBound(p1, p2);
                Line line3 = Line.CreateBound(p2, p3);
                Line line4 = Line.CreateBound(p3, p0);
                curveArray1.Append(line1);
                curveArray1.Append(line2);
                curveArray1.Append(line3);
                curveArray1.Append(line4);

                curveArrArray.Append(curveArray1);
                #endregion
                // here create rectangular extrusion
                Extrusion rectExtrusion = m_creationFamily.NewExtrusion(true, curveArrArray, sketchPlane, 10);
                // move to proper place
                Autodesk.Revit.DB.XYZ transPoint1 = new Autodesk.Revit.DB.XYZ(-16, 0, 0);
                ElementTransformUtils.MoveElement(m_familyDocument, rectExtrusion.Id, transPoint1);
            }
            catch (Exception e)
            {
                m_errCount++;
                m_errorInfo += "Unexpected exceptions occur in CreateExtrusion: " + e.ToString() + "\r\n";
            }
        }
Esempio n. 5
0
        private static void MoveScheduleOrGroup(Document doc, ScheduleSheetInstance ssi, double distance)
        {
            if (ssi.GroupId == null || ssi.GroupId == ElementId.InvalidElementId)
            {
                ElementTransformUtils.MoveElement(doc, ssi.Id, new XYZ(distance, 0, 0));
            }
            else
            {
                Element group = doc.GetElement(ssi.GroupId);
                if (groupIds.Contains(ssi.GroupId.IntegerValue))
                {
                    return;
                }

                if (group.Pinned)
                {
                    group.Pinned = false;
                }
                ElementTransformUtils.MoveElement(doc, ssi.GroupId, new XYZ(distance, 0, 0));
                groupIds.Add(ssi.GroupId.IntegerValue);
            }
        }
Esempio n. 6
0
        /// <summary>
        ///     Creates a new CurtainSystem.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="profile"></param>
        /// <param name="lvl"></param>
        /// <param name="normal"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public static CurtainSystem CreateCurtainSystem(this Document doc, CurveArrArray profile, Level lvl, XYZ normal, string typeName = null)
        {
            if (normal is null)
            {
                throw new NullReferenceException(nameof(normal));
            }

            var pts = profile.ToCurveList().Select(s => s.GetEndPoint(0));

            pts = pts.OrderBy(o => o.Z).ThenBy(o => o.Y).ThenBy(o => o.X);

            var fdoc     = doc.CreateExtrusion(profile, normal.CreatePlane(XYZ.Zero), 100);
            var symbol   = doc.NewLoadFamily(fdoc);
            var location = pts.FirstOrDefault();
            var instance = doc.Create.NewFamilyInstance(location, symbol, lvl, NonStructural);

            doc.Regenerate();

            // The instance has thickness.
            var faces = instance.GetFaceList(6, -normal).ToFaceArray();

            var result = doc.CreateCurtainSystem(faces, typeName);

            doc.Delete(instance.Id);
            doc.Delete(symbol.Family.Id);

            var pnlTypeId = result.CurtainSystemType.get_Parameter(AUTO_PANEL).AsElementId();

            if (!(doc.GetElement(pnlTypeId) is PanelType pnlType))
            {
                return(result);
            }

            var thickness = pnlType.get_Parameter(CURTAIN_WALL_SYSPANEL_THICKNESS).AsDouble();

            ElementTransformUtils.MoveElement(doc, result.Id, normal * thickness / 2);

            return(result);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            try
            {
                Reference pickedObj = uidoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);

                if (pickedObj != null)
                {
                    ElementId elementId = pickedObj.ElementId;
                    Element   element   = doc.GetElement(elementId);

                    using (Transaction trans = new Transaction(doc, "Change Location"))
                    {
                        trans.Start();

                        XYZ movVec = new XYZ(3, 3, 0);
                        ElementTransformUtils.MoveElement(doc, elementId, movVec);

                        LocationPoint location = element.Location as LocationPoint;
                        XYZ           p1       = location.Point;
                        XYZ           p2       = new XYZ(p1.X, p1.Y, p1.Z + 10);
                        Line          axis     = Line.CreateBound(p1, p2);
                        double        angle    = 30 * Math.PI / 180;
                        ElementTransformUtils.RotateElement(doc, elementId, axis, angle);

                        trans.Commit();
                    }
                }
                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Execute method invoked by Revit via the
        /// external event as a reaction to a call
        /// to its Raise method.
        /// </summary>
        public void Execute(UIApplication a)
        {
            Debug.Assert(0 < _queue.Count,
                         "why are we here with nothing to do?");

            Document doc = a.ActiveUIDocument.Document;

            // Ensure that the unique id refers to a valid
            // element from the current doucument. If not,
            // no need to start a transaction.

            string  uid = _queue.Peek().Item1;
            Element e   = doc.GetElement(uid);

            if (null != e)
            {
                using (Transaction t = new Transaction(doc))
                {
                    t.Start(GetName());

                    while (0 < _queue.Count)
                    {
                        Tuple <string, XYZ> task = _queue.Dequeue();

                        Debug.Print("Translating {0} by {1}",
                                    task.Item1, Util.PointString(task.Item2));

                        e = doc.GetElement(task.Item1);

                        if (null != e)
                        {
                            ElementTransformUtils.MoveElement(
                                doc, e.Id, task.Item2);
                        }
                    }
                    t.Commit();
                }
            }
        }
Esempio n. 9
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            Transaction t1 = new Transaction(doc, "创建");

            t1.Start();
            Wall wall = Wall.Create(doc, Line.CreateBound(new XYZ(), new XYZ(0, 10, 0)), Level.Create(doc, 0).Id, false);

            t1.Commit();
            TaskDialog.Show("Tip", "结构墙已创建");

            Transaction t2 = new Transaction(doc, "复制");

            t2.Start();
            ElementTransformUtils.CopyElement(doc, wall.Id, new XYZ(30, 30, 30));
            t2.Commit();
            TaskDialog.Show("Tip", "结构墙已复制");

            Transaction t3 = new Transaction(doc, "移动");

            t3.Start();
            ElementTransformUtils.MoveElement(doc, wall.Id, new XYZ(10, 20, 10));
            t3.Commit();
            TaskDialog.Show("Tip", "移动");

            Transaction t4 = new Transaction(doc, "镜像");

            t4.Start();
            Plane p1 = new Plane(new XYZ(0, -1, 0), XYZ.Zero);

            ElementTransformUtils.MirrorElement(doc, wall.Id, p1);
            t4.Commit();
            TaskDialog.Show("tip", "结构墙已镜像");

            return(Result.Succeeded);
        }
Esempio n. 10
0
        private static void PutSeatList(Document doc, List <SeatInfo> seatInfos)
        {
            Doc.AutoTransaction(() =>
            {
                foreach (var seatInfo in seatInfos)
                {
                    var offset       = seatInfo.Location - (RefSeat.Location as LocationPoint)?.Point;
                    var cloneSeatIds = ElementTransformUtils.CopyElement(Doc, RefSeat.Id, offset).ToList();

                    if (cloneSeatIds.Count == 0)
                    {
                        MessageBox.Show("Copys the seat, but gets not a seat.");
                        return;
                    }

                    var seat = Doc.GetElement(cloneSeatIds[0]);

                    // Sets the seat some parameters.
                    seat.SetSeatParameters(FillPattern, doc, seatInfo);

                    // Sets the seat fill color.
                    seat.SetColorFill(FillPattern, doc, seatInfo.FillColor);

                    if (!seatInfo.IsRotation)
                    {
                        continue;
                    }

                    var location = seatInfo.Location;
                    var startPt  = new XYZ(location.X, location.Y + seatInfo.Length / 2, 0);
                    var endPt    = new XYZ(location.X, location.Y + seatInfo.Length / 2, 1);
                    var line     = Line.CreateBound(startPt, endPt);

                    // No use mirror, mirror element is very slow.
                    ElementTransformUtils.RotateElement(Doc, seat.Id, line, Math.PI);
                }
            });
        }
Esempio n. 11
0
        /// <summary>
        /// Create one sweep
        /// </summary>
        private void CreateSweep()
        {
            try
            {
                #region Create rectangular profile and path curve
                CurveArrArray arrarr = new CurveArrArray();
                CurveArray    arr    = new CurveArray();

                Autodesk.Revit.DB.XYZ normal      = Autodesk.Revit.DB.XYZ.BasisZ;
                SketchPlane           sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero);

                Autodesk.Revit.DB.XYZ pnt1 = new Autodesk.Revit.DB.XYZ(0, 0, 0);
                Autodesk.Revit.DB.XYZ pnt2 = new Autodesk.Revit.DB.XYZ(2, 0, 0);
                Autodesk.Revit.DB.XYZ pnt3 = new Autodesk.Revit.DB.XYZ(1, 1, 0);
                arr.Append(Arc.Create(pnt2, 1.0d, 0.0d, 180.0d, Autodesk.Revit.DB.XYZ.BasisX, Autodesk.Revit.DB.XYZ.BasisY));
                arr.Append(Arc.Create(pnt1, pnt3, pnt2));
                arrarr.Append(arr);
                SweepProfile profile = m_revit.Create.NewCurveLoopsProfile(arrarr);

                Autodesk.Revit.DB.XYZ pnt4 = new Autodesk.Revit.DB.XYZ(10, 0, 0);
                Autodesk.Revit.DB.XYZ pnt5 = new Autodesk.Revit.DB.XYZ(0, 10, 0);
                Curve curve = Line.CreateBound(pnt4, pnt5);

                CurveArray curves = new CurveArray();
                curves.Append(curve);
                #endregion
                // here create one sweep with two arcs formed the profile
                Sweep sweep1 = m_creationFamily.NewSweep(true, curves, sketchPlane, profile, 0, ProfilePlaneLocation.Start);
                // move to proper place
                Autodesk.Revit.DB.XYZ transPoint1 = new Autodesk.Revit.DB.XYZ(11, 0, 0);
                ElementTransformUtils.MoveElement(m_familyDocument, sweep1.Id, transPoint1);
            }
            catch (Exception e)
            {
                m_errCount++;
                m_errorInfo += "Unexpected exceptions occur in CreateSweep: " + e.ToString() + "\r\n";
            }
        }
Esempio n. 12
0
        public void CopyMaterial(ObservableCollection <DocModel> DocumentList, ObservableCollection <MaterialModel> curentMaterialList)
        {
            CopyPasteOptions copyPasteOptions = new CopyPasteOptions();

            foreach (var docModel in DocumentList)
            {
                if (docModel.ChangeMaterial)
                {
                    using (Transaction t = new Transaction(docModel.doc, "Копирование материалов"))
                    {
                        t.Start();

                        foreach (var KeyValuePair in GetElementIdCollection(curentMaterialList))
                        {
                            try
                            {
                                if (KeyValuePair.Value.Count > 0)
                                {
                                    ElementTransformUtils.CopyElements(KeyValuePair.Key, KeyValuePair.Value, docModel.doc, Transform.Identity, copyPasteOptions);
                                    foreach (var el in KeyValuePair.Value)
                                    {
                                        loger.AddLog("Скопирован материал " + KeyValuePair.Key.GetElement(el).Name + " из файла " + KeyValuePair.Key.Title + " в " + docModel.doc.Title);
                                    }
                                }
                            }
                            catch
                            {
                                loger.AddLog("Не удалось скопировать материалы из документа ", KeyValuePair.Key.Title);
                            }
                        }

                        t.Commit();
                    }
                }
            }
            loger.ShowTxtLog();
        }
Esempio n. 13
0
        public void CopyElements(Document doc, FamilyInstance familyInstance, List <FamilyInstance> listinstance, ICollection <ElementId> elementIds)
        {
            ICollection <ElementId> newlist         = new List <ElementId>();
            CopyPasteOptions        option          = new CopyPasteOptions();
            ProgressBarform         progressBarform = new ProgressBarform(listinstance.Count, "Loading...");

            progressBarform.Show();
            foreach (FamilyInstance source in listinstance)
            {
                progressBarform.giatri();
                if (progressBarform.iscontinue == false)
                {
                    break;
                }
                Transform transform  = TransformToCopy(source, familyInstance);
                Transform transform1 = Transform.CreateTranslation(transform.Origin);
                using (Transaction tran = new Transaction(doc, "copy"))
                {
                    tran.Start();
                    FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                    IgnoreProcess          ignoreProcess = new IgnoreProcess();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(ignoreProcess);
                    tran.SetFailureHandlingOptions(options);
                    try
                    {
                        newlist = ElementTransformUtils.CopyElements(doc, elementIds, doc, transform, option);
                        Remove_product(doc, newlist);
                    }
                    catch (Exception)
                    {
                    }
                    tran.Commit();
                }
            }
            progressBarform.Close();
        }
Esempio n. 14
0
        //*****************************MoveDoors()*****************************
        public void MoveDoors(Document doc, ObjDoors linkedDoor, ObjDoors localDoor)
        {
            Element linkedElement = linkedDoor.doorElement;
            Element localElement  = localDoor.doorElement;
            // get the column current location
            LocationPoint New_InstanceLocation = linkedElement.Location as LocationPoint;
            LocationPoint Old_InstanceLocation = localElement.Location as LocationPoint;

            XYZ oldPlace = Old_InstanceLocation.Point;

            // XY
            double New_x = linkedDoor.X;
            double New_y = linkedDoor.Y;
            //Get Level
            Level New_level = findLevel(doc, linkedDoor);

            XYZ New_xyz = new XYZ(New_x, New_y, New_level.Elevation);

            double Move_X = New_x - oldPlace.X;
            double Move_Y = New_y - oldPlace.Y;
            //Get Level
            Level  Old_level = findLevel(doc, linkedDoor);
            double Move_Z    = New_level.Elevation - Old_level.Elevation;

            // Move the element to new location.
            XYZ new_xyz = new XYZ(Move_X, Move_Y, Move_Z);

            //Start move using a transaction.
            Transaction t = new Transaction(doc);

            t.Start("Move Element");

            ElementTransformUtils.MoveElement(doc, localElement.Id, new_xyz);
            //ElementTransformUtils.RotateElement(doc, element.Id, New_Axis, Rotate);

            t.Commit();
        }
Esempio n. 15
0
        public static List <string> TransferViewTemplateAndFilter(Document LinkDocument, bool IsIncludeFilters = true)
        {
            var TemplateNames = new List <string>();
            var doc           = DocumentManager.Instance.CurrentDBDocument;
            var views         = new FilteredElementCollector(LinkDocument).OfClass(typeof(View)).Cast <View>().Where(x => x.IsTemplate).ToList();
            var ids           = new List <ElementId>();

            foreach (var view in views)
            {
                ids.Add(view.Id);
            }
            TransactionManager.Instance.EnsureInTransaction(doc);

            var templates = ElementTransformUtils.CopyElements(LinkDocument, ids, doc, Transform.Identity,
                                                               new CopyPasteOptions());

            foreach (var i in templates)
            {
                TemplateNames.Add(doc.GetElement(i).Name);
            }

            if (!IsIncludeFilters)
            {
                foreach (ElementId v in templates)
                {
                    View view    = doc.GetElement(v) as View;
                    var  filters = view.GetFilters();
                    foreach (ElementId f in filters)
                    {
                        view.RemoveFilter(f);
                    }
                }
            }

            TransactionManager.Instance.TransactionTaskDone();
            return(TemplateNames);
        }
Esempio n. 16
0
        /// <summary>
        /// Set the Euler angle of the family instance around its local Z-axis.
        /// </summary>
        /// <param name="degree">The Euler angle around Z-axis.</param>
        /// <returns>The result family instance.</returns>
        public FamilyInstance SetRotation(double degree)
        {
            if (this == null)
            {
                throw new ArgumentNullException("familyInstance");
            }

            var oldTransform = InternalGetTransform();

            double[] oldRotationAngles;
            TransformUtils.ExtractEularAnglesFromTransform(oldTransform, out oldRotationAngles);
            double newRotationAngle = degree * Math.PI / 180;

            if (!oldRotationAngles[0].AlmostEquals(newRotationAngle, 1.0e-6))
            {
                double rotateAngle = newRotationAngle - oldRotationAngles[0];
                var    axis        = Line.CreateUnbound(oldTransform.Origin, oldTransform.BasisZ);
                ElementTransformUtils.RotateElement(Document, new ElementId(Id), axis, -rotateAngle);
            }

            TransactionManager.Instance.TransactionTaskDone();

            return(this);
        }
Esempio n. 17
0
        protected void checkFSDoc()
        {
            if (this.Context == null ||
                this.RefDocId == this.TarDocId)
            {
                return;
            }
            //try find a symbol of same name
            var tarFS = new FilteredElementCollector(this.TarDoc)
                        .OfClass(typeof(FamilySymbol))
                        .OfCategoryId(this.fs.Category.Id)
                        .Where(x => x.Name == this.fs.Name)
                        .Cast <FamilySymbol>()
                        .FirstOrDefault(x => x.Family.Name == this.fs.Family.Name);

            if (tarFS != null)
            {
                this.fs = tarFS as FamilySymbol;
                return;
            }
            else
            {
                //if not found, copy from ref doc
                var newIds = ElementTransformUtils.CopyElements
                                 (this.fs.Document,
                                 new List <ElementId>()
                {
                    this.fs.Id
                },
                                 this.TarDoc,
                                 null,
                                 new CopyPasteOptions());
                this.TarDoc.Regenerate();
                this.fs = TarDoc.GetElement(newIds.First()) as FamilySymbol;
            }
        }
Esempio n. 18
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument  uiDoc = commandData.Application.ActiveUIDocument;
            Document    doc   = uiDoc.Document;
            Transaction t1    = new Transaction(doc, "T1");

            t1.Start();
            Wall wall = Wall.Create(doc, Line.CreateBound(new XYZ(), new XYZ(0, 10, 0)), Level.Create(doc, 0).Id,
                                    false);//注意这里需要返回Id,而不是LevelId

            t1.Commit();
            TaskDialog.Show("T1", wall.Id.ToString());
            Transaction t2 = new Transaction(doc, "copy");

            t2.Start();
            ElementTransformUtils.CopyElement(doc, wall.Id, new XYZ(10, 0, 0));
            t2.Commit();
            TaskDialog.Show("T2", "Copy Successed!");
            Transaction t3 = new Transaction(doc, "Move");

            t3.Start();
            ElementTransformUtils.MoveElement(doc, wall.Id, new XYZ(10, 20, 0));
            t3.Commit();
            TaskDialog.Show("T3", "移动完成");
            Transaction t4 = new Transaction(doc, "Mirror");

            t4.Start();
            if (ElementTransformUtils.CanMirrorElement(doc, wall.Id))
            {
                Plane pl = Plane.CreateByNormalAndOrigin(new XYZ(0, -1, 0), XYZ.Zero);
                ElementTransformUtils.MirrorElement(doc, wall.Id, pl);
            }
            t4.Commit();
            TaskDialog.Show("T4", "Mirror !");
            return(Result.Succeeded);
        }
Esempio n. 19
0
        /// <summary>
        /// Mutate the two end points of the ReferencePlane
        /// </summary>
        /// <param name="bubbleEnd"></param>
        /// <param name="freeEnd"></param>
        /// <returns>False if the operation failed</returns>
        private bool InternalSetEndpoints(XYZ bubbleEnd, XYZ freeEnd)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            var refPlane = InternalReferencePlane;

            XYZ oldBubbleEnd = refPlane.BubbleEnd;
            XYZ oldFreeEnd   = refPlane.FreeEnd;

            var success = true;

            if (!refPlane.FreeEnd.IsAlmostEqualTo(oldFreeEnd) ||
                !refPlane.BubbleEnd.IsAlmostEqualTo(oldBubbleEnd))
            {
                XYZ midPointOld = 0.5 * (oldBubbleEnd + oldFreeEnd);

                XYZ midPoint = 0.5 * (bubbleEnd + freeEnd);
                XYZ moveVec  = XYZ.BasisZ.DotProduct(midPoint - midPointOld) * XYZ.BasisZ;

                // (sic) From Dynamo Legacy
                try
                {
                    ElementTransformUtils.MoveElement(Document, refPlane.Id, moveVec);
                    refPlane.BubbleEnd = bubbleEnd;
                    refPlane.FreeEnd   = freeEnd;
                }
                catch
                {
                    success = false;
                }
            }

            TransactionManager.Instance.TransactionTaskDone();

            return(success);
        }
Esempio n. 20
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // Retrieve selected floors, or all floors, if nothing is selected:

            List <Element> floors = new List <Element>();

            if (!Util.GetSelectedElementsOrAll(
                    floors, uidoc, typeof(Floor)))
            {
                Selection sel = uidoc.Selection;
                message = (0 < sel.GetElementIds().Count)
          ? "Please select some floor elements."
          : "No floor elements found.";
                return(Result.Failed);
            }

            // Determine top face of each selected floor:

            int         nNullFaces = 0;
            List <Face> topFaces   = new List <Face>();
            Options     opt        = app.Application.Create.NewGeometryOptions();

            foreach (Floor floor in floors)
            {
                GeometryElement geo = floor.get_Geometry(opt);

                //GeometryObjectArray objects = geo.Objects; // 2012

                foreach (GeometryObject obj in geo)
                {
                    Solid solid = obj as Solid;
                    if (solid != null)
                    {
                        PlanarFace f = GetTopFace(solid);
                        if (null == f)
                        {
                            Debug.WriteLine(
                                Util.ElementDescription(floor)
                                + " has no top face.");
                            ++nNullFaces;
                        }
                        topFaces.Add(f);
                    }
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Model Lines and Floor");

                // Create new floors from the top faces found.
                // Before creating the new floor, we would obviously
                // apply whatever modifications are required to the
                // new floor profile:

                Autodesk.Revit.Creation.Application creApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    creDoc = doc.Create;

                int i = 0;
                int n = topFaces.Count - nNullFaces;

                Debug.Print(
                    "{0} top face{1} found.",
                    n, Util.PluralSuffix(n));

                foreach (Face f in topFaces)
                {
                    Floor floor = floors[i++] as Floor;

                    if (null != f)
                    {
                        EdgeArrayArray eaa = f.EdgeLoops;
                        CurveArray     profile;

                        #region Attempt to include inner loops
#if ATTEMPT_TO_INCLUDE_INNER_LOOPS
                        bool use_original_loops = true;
                        if (use_original_loops)
                        {
                            profile = Convert(eaa);
                        }
                        else
#endif // ATTEMPT_TO_INCLUDE_INNER_LOOPS
                        #endregion // Attempt to include inner loops

                        {
                            profile = new CurveArray();

                            // Only use first edge array,
                            // the outer boundary loop,
                            // skip the further items
                            // representing holes:

                            EdgeArray ea = eaa.get_Item(0);
                            foreach (Edge e in ea)
                            {
                                IList <XYZ> pts  = e.Tessellate();
                                int         m    = pts.Count;
                                XYZ         p    = pts[0];
                                XYZ         q    = pts[m - 1];
                                Line        line = Line.CreateBound(p, q);
                                profile.Append(line);
                            }
                        }
                        //Level level = floor.Level; // 2013

                        Level level = doc.GetElement(floor.LevelId)
                                      as Level; // 2014

                        // In this case we have a valid floor type given.
                        // In general, not that NewFloor will only accept
                        // floor types whose IsFoundationSlab predicate
                        // is false.

                        floor = creDoc.NewFloor(profile,
                                                floor.FloorType, level, true);

                        XYZ v = new XYZ(5, 5, 0);

                        //doc.Move( floor, v ); // 2011
                        ElementTransformUtils.MoveElement(doc, floor.Id, v); // 2012
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            //获取CW 102-50-100p类型的墙体
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            Element ele = collector.OfCategory(BuiltInCategory.OST_Columns).OfClass(typeof(FamilySymbol))
                          .FirstOrDefault(x => x.Name == "457 x 475mm");
            FamilySymbol columnType = ele as FamilySymbol;

            columnType.Activate();

            //获取标高
            //通过链式编程,一句话搞定
            Level level = new FilteredElementCollector(doc).
                          OfClass(typeof(Level)).FirstOrDefault(x => x.Name == "标高 1") as Level;
            //创建放置点
            int        countcircle = 72;
            List <XYZ> xyzlist     = new List <XYZ>();

            for (int i = 0; i < countcircle; i++)
            {
                double x     = 10 * (2 * Math.Cos(2 * Math.PI / countcircle * i) - Math.Cos(2 * 2 * Math.PI / countcircle * i));
                double y     = 10 * (2 * Math.Sin(2 * Math.PI / countcircle * i) - Math.Sin(2 * 2 * Math.PI / countcircle * i));
                XYZ    start = new XYZ(x, y, 0);
                xyzlist.Add(start);
            }

            double height = 15 / 0.3048;
            double offset = 0;
            //创建事务
            List <FamilyInstance> familyInstance = new List <FamilyInstance>();
            Transaction           trans          = new Transaction(doc, "创建柱子");

            foreach (XYZ item in xyzlist)
            {
                trans.Start();
                FamilyInstance colum = doc.Create.NewFamilyInstance(item, columnType, level, StructuralType.NonStructural);
                trans.Commit();
                //刷新界面,出现动画效果
                System.Windows.Forms.Application.DoEvents(); //动画步骤一
                //使用线程来控制实践
                Thread.Sleep(100);                           //动画步骤二
                familyInstance.Add(colum);
            }

            //旋转柱子
            Transaction transRotate = new Transaction(doc, "旋转柱子");

            for (int i = 0; i < 100; i++)
            {
                transRotate.Start();
                for (int j = 0; j < xyzlist.Count; j++)
                {
                    Line line = Line.CreateBound(xyzlist[j], new XYZ(xyzlist[j].X, xyzlist[j].Y, 10));
                    ElementTransformUtils.RotateElement(doc, familyInstance[j].Id, line, Math.PI / 6);//旋转对象的方法
                }
                transRotate.Commit();
                System.Windows.Forms.Application.DoEvents();
            }



            return(Result.Succeeded);
        }
Esempio n. 22
0
        // The Execute method for the updater
        public void Execute(UpdaterData data)
        {
            try
            {
                Document       doc     = data.GetDocument();
                FamilyInstance window  = doc.get_Element(m_windowId) as FamilyInstance;
                Element        section = doc.get_Element(m_sectionId);

                // iterate through modified elements to find the one we want the section to follow
                foreach (ElementId id in data.GetModifiedElementIds())
                {
                    if (id == m_windowId)
                    {
                        //Let's take this out temporarily.
                        bool enableLookup = false;
                        if (enableLookup)
                        {
                            m_schema = Schema.Lookup(m_schemaId); // (new Guid("{4DE4BE80-0857-4785-A7DF-8A8918851CB2}"));
                        }
                        Entity storedEntity = null;
                        storedEntity = window.GetEntity(m_schema);

                        //
                        // first we look-up X-Y-Z parameters, which we know are set on our windows
                        // and the values are set to the current coordinates of the window instance
                        Field fieldPosition = m_schema.GetField("Position");
                        XYZ   oldPosition   = storedEntity.Get <XYZ>(fieldPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);

                        TaskDialog.Show("Old position", oldPosition.ToString());

                        LocationPoint lp          = window.Location as LocationPoint;
                        XYZ           newPosition = lp.Point;

                        // XYZ has operator overloads
                        XYZ translationVec = newPosition - oldPosition;

                        // move the section by the same vector
                        if (!translationVec.IsZeroLength())
                        {
                            ElementTransformUtils.MoveElement(doc, section.Id, translationVec);
                        }
                        TaskDialog.Show("Moving", "Moving");

                        // Lookup the normal vector (i,j,we assume k=0)
                        Field fieldOrientation = m_schema.GetField("Orientation");
                        // Establish the old and new orientation vectors
                        XYZ oldNormal = storedEntity.Get <XYZ>(fieldOrientation, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);


                        XYZ newNormal = window.FacingOrientation;

                        // If different, rotate the section by the angle around the location point of the window

                        double angle = oldNormal.AngleTo(newNormal);

                        // Need to adjust the rotation angle based on the direction of rotation (not covered by AngleTo)
                        XYZ    cross = oldNormal.CrossProduct(newNormal).Normalize();
                        double sign  = 1.0;
                        if (!cross.IsAlmostEqualTo(XYZ.BasisZ))
                        {
                            sign = -1.0;
                        }
                        angle *= sign;
                        if (Math.Abs(angle) > 0)
                        {
                            Line axis = doc.Application.Create.NewLineBound(newPosition, newPosition + XYZ.BasisZ);
                            ElementTransformUtils.RotateElement(doc, section.Id, axis, angle);
                        }

                        // update the parameters on the window instance (to be the current position and orientation)
                        storedEntity.Set <XYZ>(fieldPosition, newPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);


                        storedEntity.Set <XYZ>(fieldOrientation, newNormal, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
                        window.SetEntity(storedEntity);
                    }
                }
            }
            catch (System.Exception ex)
            {
                TaskDialog.Show("Exception", ex.ToString());
            }


            return;
        }
        public DataToBuilding(Document doc, List <Building> buildings, ElementId topographyID, string documentFileAddress = "")
        {
            this.DocumentFileAddress       = documentFileAddress;
            this.opt.OverwriteExistingFile = true;
            List <double> bldgHeight = new List <double>();

            _doc = doc; this.TopographyID = topographyID;
            using (Transaction createBuildingPadType = new Transaction(_doc))
            {
                createBuildingPadType.Start("Create Building Pad Type");
                this.buildingPadType = BuildingPadType.CreateDefault(_doc);
                createBuildingPadType.Commit();
            }
            this.FailedAttemptsToCreateBuildingPads = 0;
            this.FailedAttemptsToCreateBuildings    = 0;

            #region pre-process the contour lines
            List <ProcessPolygon> ProcessedFootPrints = new List <ProcessPolygon>();
            this.RayTracerView = this.createView3d();
            foreach (Building building in buildings)
            {
                ProcessPolygon processedContour = new ProcessPolygon(building.vertices);
                processedContour.Flatten();
                processedContour.RemoveIdenticalPoints();
                processedContour.RemoveClosePoints(.5);
                processedContour.RemoveCollinearity();
                processedContour.ForceToFixList();

                bldgHeight.Add(building.height);
                ProcessedFootPrints.Add(processedContour);
            }
            this.BuildingFootPrints = ProcessedFootPrints;
            #endregion

            #region Create building Masses ad independent families

            this.FamilyTemplateAddress = this.familyTemplateAddress();
            List <double> elevations = new List <double>();
            for (int i = 0; i < this.BuildingFootPrints.Count; i++)
            {
                elevations.Add(this.FindBuildingElevation(this.BuildingFootPrints[i]));
            }
            //Finding a folder to save the buildings
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            DialogResult        result        = folderBrowser.ShowDialog();
            string folder = "";
            if (result == DialogResult.OK)
            {
                folder = folderBrowser.SelectedPath;
            }
            //creating extrusions and saving them
            List <XYZ>          translations     = new List <XYZ>();
            List <FamilySymbol> symbols          = new List <FamilySymbol>();
            List <int>          footPrintIndices = new List <int>();

            for (int i = 0; i < 5; i++)
            {
                if (elevations[i] != double.NaN && elevations[i] != -1)
                {
                    string path        = folder + @"\" + i.ToString() + ".rfa";
                    XYZ    translation = XYZ.Zero;
                    foreach (XYZ item in this.BuildingFootPrints[i].ProcessedPolygon)
                    {
                        translation += item;
                    }
                    translation /= this.BuildingFootPrints[i].ProcessedPolygon.Count;

                    bool formCreated = CreateFamilyFile(this.BuildingFootPrints[i], bldgHeight[i], path, translation);
                    if (formCreated)
                    {
                        using (Transaction placeFamily = new Transaction(_doc))
                        {
                            FailureHandlingOptions failOpt = placeFamily.GetFailureHandlingOptions();
                            failOpt.SetFailuresPreprocessor(new WarningSwallower());
                            placeFamily.SetFailureHandlingOptions(failOpt);
                            placeFamily.Start("Place a Mass");
                            Family family = null;
                            _doc.LoadFamily(path, out family);
                            FamilySymbol symbol = null;
                            //foreach( FamilySymbol s in family.Symbols ) // 2014
                            foreach (ElementId id in family.GetFamilySymbolIds()) // 2015
                            {
                                symbol = _doc.GetElement(id) as FamilySymbol;
                                break;
                            }
                            symbols.Add(symbol);
                            XYZ displacement = new XYZ(translation.X, translation.Y, elevations[i]);
                            translations.Add(displacement);
                            footPrintIndices.Add(i);
                            placeFamily.Commit();
                        }
                    }
                    else
                    {
                        this.BuildingFootPrints[i].Visualize(_doc);
                    }
                }
            }
            #endregion

            #region inserting a mass file
            for (int i = 0; i < translations.Count; i++)
            {
                using (Transaction placeMass = new Transaction(_doc))
                {
                    FailureHandlingOptions failOpt = placeMass.GetFailureHandlingOptions();
                    failOpt.SetFailuresPreprocessor(new WarningSwallower());
                    placeMass.SetFailureHandlingOptions(failOpt);
                    placeMass.Start("Insert Mass");
                    try
                    {
                        FamilyInstance building = _doc.Create.NewFamilyInstance(XYZ.Zero, symbols[i], StructuralType.NonStructural);
                        ElementTransformUtils.MoveElement(_doc, building.Id, translations[i]);
                        this.BuildingMasses.Add(building);
                    }
                    catch (Exception)
                    {
                        this.FailedAttemptsToCreateBuildings++;
                    }
                    placeMass.Commit();
                }
            }
            #endregion

            if (this.DocumentFileAddress != "")
            {
                _doc.SaveAs(this.DocumentFileAddress, this.opt);
            }

            #region creating building pads
            //for (int i = 0; i < footPrintIndices.Count; i++)
            //{
            //    Transaction CreatePads = new Transaction(_doc, "Create Building Pad");
            //    FailureHandlingOptions failOpt = CreatePads.GetFailureHandlingOptions();
            //    failOpt.SetFailuresPreprocessor(new WarningSwallower());
            //    CreatePads.SetFailureHandlingOptions(failOpt);
            //    CreatePads.Start();
            //    try
            //    {
            //        Autodesk.Revit.DB.Architecture.BuildingPad pad = this.CreateBuildingPad(this.BuildingFootPrints[footPrintIndices[i]], elevations[footPrintIndices[i]]);
            //        this.BuildingPads.Add(pad);
            //        if (this.DocumentFileAddress != "")
            //        {
            //            _doc.SaveAs(this.DocumentFileAddress, this.opt);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        this.FailedAttemptsToCreateBuildingPads++;
            //    }

            //    CreatePads.Commit();
            //}
            #endregion
        }
Esempio n. 24
0
 public void MoveElement(ElementId id, XYZ translation) =>
 ElementTransformUtils.MoveElement(doc, id, translation);
Esempio n. 25
0
        /// <summary>
        /// move the selected grid line to the location of the mouse cursor
        /// </summary>
        /// <param name="mousePosition">
        /// indicates the destination position of the grid line
        /// </param>
        /// <returns>
        /// return whether the grid line be moved successfully
        /// </returns>
        public bool MoveGridLine(System.Drawing.Point mousePosition)
        {
            // verify that the mouse location is valid: it's inside the curtain grid area
            // & it doesn't lap over another grid line (it's not allowed to move a grid line to lap over another one)
            if (false == m_drawing.MouseLocationValid)
            {
                return(false);
            }

            if (null == m_lineToBeMoved)
            {
                return(false);
            }

            // move a U line along the V direction
            if (-1 != m_drawing.SelectedUIndex)
            {
                // convert the 2D data to 3D
                Autodesk.Revit.DB.XYZ xyz = new Autodesk.Revit.DB.XYZ(mousePosition.X, mousePosition.Y, 0);
                Vector4 vec = new Vector4(xyz);
                vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec);
                double offset = vec.Z - m_lineToBeMoved.FullCurve.GetEndPoint(0).Z;
                xyz = new Autodesk.Revit.DB.XYZ(0, 0, offset);
                Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString());
                act.Start();
                try
                {
                    ElementTransformUtils.MoveElement(m_activeDocument, m_lineToBeMoved.Id, xyz);
                }
                catch (System.Exception e)
                {
                    TaskDialog.Show("Exception", e.Message);
                    return(false);
                }
                act.Commit();

                // update the grid line 2d
                GridLine2D line = m_drawing.UGridLines2D[m_drawing.SelectedUIndex];
                line.StartPoint = new System.Drawing.Point(line.StartPoint.X, line.StartPoint.Y + m_moveOffset);
                line.EndPoint   = new System.Drawing.Point(line.EndPoint.X, line.EndPoint.Y + m_moveOffset);

                // update the mapped grid line graphics path
                GraphicsPath path = new GraphicsPath();
                path.AddLine(line.StartPoint, line.EndPoint);
                m_drawing.ULinePathList[m_drawing.SelectedUIndex] = path;

                // update the mapped segment line and its graphics path
                List <GraphicsPath>  pathList    = m_drawing.USegLinePathListList[m_drawing.SelectedUIndex];
                List <SegmentLine2D> segLineList = line.Segments;
                for (int i = 0; i < segLineList.Count; i++)
                {
                    // update the segment
                    SegmentLine2D segLine2D = segLineList[i];
                    segLine2D.StartPoint = new System.Drawing.Point(segLine2D.StartPoint.X, segLine2D.StartPoint.Y + m_moveOffset);
                    segLine2D.EndPoint   = new System.Drawing.Point(segLine2D.EndPoint.X, segLine2D.EndPoint.Y + m_moveOffset);

                    // update the segment's graphics path
                    GraphicsPath gpath = new GraphicsPath();
                    path.AddLine(segLine2D.StartPoint, segLine2D.EndPoint);
                    pathList[i] = gpath;
                }
            }
            // move a V line along the U direction
            else if (-1 != m_drawing.SelectedVIndex)
            {
                // convert the 2D data to 3D
                Autodesk.Revit.DB.XYZ xyz = new Autodesk.Revit.DB.XYZ(mousePosition.X, mousePosition.Y, 0);
                Vector4 vec = new Vector4(xyz);
                vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec);
                double offset = vec.X - m_lineToBeMoved.FullCurve.GetEndPoint(0).X;
                xyz = new Autodesk.Revit.DB.XYZ(offset, 0, 0);

                Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString());
                act.Start();
                try
                {
                    ElementTransformUtils.MoveElement(m_activeDocument, m_lineToBeMoved.Id, xyz);
                }
                catch (System.Exception e)
                {
                    TaskDialog.Show("Exception", e.Message);
                    return(false);
                }
                act.Commit();

                // update the grid line 2d
                GridLine2D line = m_drawing.VGridLines2D[m_drawing.SelectedVIndex];
                line.StartPoint = new System.Drawing.Point(line.StartPoint.X + m_moveOffset, line.StartPoint.Y);
                line.EndPoint   = new System.Drawing.Point(line.EndPoint.X + m_moveOffset, line.EndPoint.Y);

                // update the mapped grid line graphics path
                GraphicsPath path = new GraphicsPath();
                path.AddLine(line.StartPoint, line.EndPoint);
                m_drawing.VLinePathList[m_drawing.SelectedVIndex] = path;

                // update the mapped segment line and its graphics path
                List <GraphicsPath>  pathList    = m_drawing.VSegLinePathListList[m_drawing.SelectedVIndex];
                List <SegmentLine2D> segLineList = line.Segments;
                for (int i = 0; i < segLineList.Count; i++)
                {
                    // update the segment
                    SegmentLine2D segLine2D = segLineList[i];
                    segLine2D.StartPoint = new System.Drawing.Point(segLine2D.StartPoint.X + m_moveOffset, segLine2D.StartPoint.Y);
                    segLine2D.EndPoint   = new System.Drawing.Point(segLine2D.EndPoint.X + m_moveOffset, segLine2D.EndPoint.Y);

                    // update the segment's graphics path
                    GraphicsPath gpath = new GraphicsPath();
                    path.AddLine(segLine2D.StartPoint, segLine2D.EndPoint);
                    pathList[i] = gpath;
                }
            }
            // line moved, the segment information changed, so reload all the geometry data
            this.ReloadGeometryData();

            m_drawing.DrawObject.Clear();
            return(true);
        }
Esempio n. 26
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Hello World
            //TaskDialog.Show("VL title", "VL says Hello Revit");

            var uiApp = commandData.Application;
            var app   = commandData.Application.Application;
            var uiDoc = commandData.Application.ActiveUIDocument;
            var doc   = commandData.Application.ActiveUIDocument.Document;


            #region 放置类型为"0762*2032 mm"的门
            //首先通过类型过滤出 类型为门的族类型,找到名称相同的
            string       doorTypeName = "0762*2032 mm";
            FamilySymbol doorType     = null;
            var          filter       = new LogicalAndFilter(
                new ElementCategoryFilter(BuiltInCategory.OST_Doors),
                new ElementClassFilter(typeof(FamilySymbol))
                );
            var  collector   = new FilteredElementCollector(doc).WherePasses(filter);
            bool symbolFound = collector.FirstOrDefault(c => c.Name == doorTypeName) != null;
            //如果没有则通过文件加载族
            if (symbolFound)
            {
                doorType = collector.FirstOrDefault(c => c.Name == doorTypeName) as FamilySymbol;
            }
            else
            {
                string file = @"familyFilePath";
                Family family;
                if (doc.LoadFamily(file, out family))
                {
                    var validType = family.GetValidTypes().FirstOrDefault(c =>
                    {
                        var symbol = (doc.GetElement(c) as FamilySymbol);
                        if (symbol != null && symbol.Name == doorTypeName)
                        {
                            return(true);
                        }
                        return(false);
                    });
                    if (validType != null)
                    {
                        doorType    = doc.GetElement(validType) as FamilySymbol;
                        symbolFound = true;
                    }
                }
            }
            //使用族类型创建门 线性的门是有着LocationCurve的且LocationCurve.Curve为Line的元素
            Wall wall = null;
            if (doorType != null)
            {
                Element element = new FilteredElementCollector(doc)
                                  .WherePasses(new ElementClassFilter(typeof(Wall)))
                                  .FirstOrDefault(c =>
                {
                    var locationCurve = c.Location as LocationCurve;
                    if (locationCurve != null)
                    {
                        var line = locationCurve.Curve as Line;
                        if (line != null)
                        {
                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                });
                if (element != null)
                {
                    wall = element as Wall;
                }
            }
            //在墙的中心创建一个门
            if (wall != null)
            {
                var            line          = (wall.Location as LocationCurve).Curve as Line;
                var            wallLevel     = doc.GetElement(wall.LevelId) as Level;
                XYZ            midPoint      = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2;
                var            structureType = Autodesk.Revit.DB.Structure.StructuralType.NonStructural;
                FamilyInstance door          = doc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, structureType);
            }
            #endregion

            #region  制墙类型
            var wallElementId = 1111;
            wall = doc.GetElement(new ElementId(wallElementId)) as Wall;
            if (wall != null)
            {
                var         wallType       = wall.WallType;
                ElementType duplicatedType = wallType.Duplicate(wall.Name + "duplicated");
            }
            #endregion

            #region 元素移动
            VLTransactionHelper.DelegateTransaction(doc, "创建一根柱子", () =>
            {
                //Revit文档的创建句柄
                Autodesk.Revit.Creation.Document creator = doc.Create;
                XYZ origin              = new XYZ(0, 0, 0);
                Level level             = doc.GetElement(new ElementId(12122)) as Level;
                FamilySymbol columnType = doc.GetElement(new ElementId(12123)) as FamilySymbol;
                var structureType       = Autodesk.Revit.DB.Structure.StructuralType.Column;
                FamilyInstance column   = creator.NewFamilyInstance(origin, columnType, level, structureType);
                XYZ newPlace            = new XYZ(10, 20, 30);
                ElementTransformUtils.MoveElement(doc, column.Id, newPlace);
                return(true);
            });
            #endregion

            #region ElementTransformUtils
            //ElementTransformUtils.CopyElement();
            //ElementTransformUtils.CopyElements();
            //ElementTransformUtils.MirrorElement();
            //ElementTransformUtils.MirrorElements();
            //ElementTransformUtils.MoveElement();
            //ElementTransformUtils.MoveElements();
            //ElementTransformUtils.RotateElement();
            //ElementTransformUtils.RotateElements();
            #endregion

            #region 元素旋转
            VLTransactionHelper.DelegateTransaction(doc, "ElementTransformUtils旋转方法", () =>
            {
                LocationCurve wallLine = wall.Location as LocationCurve;
                XYZ p1    = wallLine.Curve.GetEndPoint(0);
                XYZ p2    = new XYZ(p1.X, p1.Y, 30);
                Line axis = Line.CreateBound(p1, p2);
                ElementTransformUtils.RotateElement(doc, wall.Id, axis, Math.PI / 3);//逆时针60°
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "LocationCurve,LocationPoint,自带的旋转方法", () =>
            {
                LocationCurve locationCurve = wall.Location as LocationCurve;//线性坐标自带线
                if (locationCurve != null)
                {
                    Curve curve = locationCurve.Curve;
                    var start   = curve.GetEndPoint(0);
                    Line axis   = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationCurve.Rotate(axis, Math.PI);//PI=180°
                }
                LocationPoint locationPoint = wall.Location as LocationPoint;
                if (locationPoint != null)
                {
                    var start = locationPoint.Point;
                    Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationPoint.Rotate(axis, Math.PI);
                }
                return(true);
            });
            #endregion

            #region 元素镜像
            VLTransactionHelper.DelegateTransaction(doc, "元素镜像", () =>
            {
                Plane plane = new Plane(XYZ.BasisX, XYZ.Zero);
                if (ElementTransformUtils.CanMirrorElement(doc, wall.Id))
                {
                    ElementTransformUtils.MirrorElement(doc, wall.Id, plane);
                }
                return(true);
            });
            #endregion

            #region 元素删除
            //var deleteElements = Document.Delete(@ElementIds);
            #endregion

            #region 元素组合
            VLTransactionHelper.DelegateTransaction(doc, "元素组合", () =>
            {
                List <ElementId> elementIds = new List <ElementId>()
                {
                    new ElementId(1000),
                    new ElementId(1001),
                    new ElementId(1002),
                };
                Group group = doc.Create.NewGroup(elementIds);
                return(true);
            });
            #endregion

            #region 元素编辑
            VLTransactionHelper.DelegateTransaction(doc, "创建参照平面", () =>
            {
                XYZ bubbleEnd = new XYZ(0, 5, 5);
                XYZ freeEnd   = new XYZ(5, 5, 5);
                XYZ cutVector = XYZ.BasisY;
                View view     = doc.ActiveView;
                ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view);
                referencePlane.Name           = "MyReferencePlane";
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "创建参照线,由模型线-转>参照线", () =>
            {
                ModelCurve modelCurve = doc.GetElement(new ElementId(1000)) as ModelCurve;//ModelCurve模型线
                modelCurve.ChangeToReferenceLine();
                //modelCurve.IsReferenceLine;
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "通过标高创建草图平面,然后在草图平面创建模型线", () =>
            {
                Level level             = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).FirstOrDefault() as Level;
                Line line               = Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 0));
                SketchPlane sketchPlane = SketchPlane.Create(doc, level.Id);
                ModelCurve modelLine    = doc.FamilyCreate.NewModelCurve(line, sketchPlane);
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "使用拉身体获取相应的草图平面", () =>
            {
                Extrusion extrusion         = doc.GetElement(new ElementId(11212)) as Extrusion;
                SketchPlane sketchPlane     = extrusion.Sketch.SketchPlane;
                CurveArrArray sketchProfile = extrusion.Sketch.Profile;
                return(true);
            });
            #endregion

            #region 族
            string       tagName   = "梁平法_集中标_左对齐";
            FamilySymbol tagSymbol = null;
            //查找族类型
            var symbols = new FilteredElementCollector(doc)
                          .WherePasses(new ElementClassFilter(typeof(FamilySymbol)))
                          .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_StructuralFramingTags));
            var targetSymbol = symbols.FirstOrDefault(c => c.Name == tagName);
            if (targetSymbol != null)
            {
                tagSymbol = targetSymbol as FamilySymbol;
            }
            //空时加载族类型
            if (tagSymbol == null)
            {
                var    symbolFile = @"E:\WorkingSpace\Tasks\0526标注\梁平法_集中标_左对齐.rfa";
                Family family;
                if (doc.LoadFamily(symbolFile, out family))
                {
                    foreach (ElementId typeId in family.GetValidTypes())
                    {
                        var validType = doc.GetElement(typeId) as FamilySymbol;
                        if (validType != null && validType.Name == tagName)
                        {
                            tagSymbol = validType;
                            break;
                        }
                    }
                }
                else
                {
                    TaskDialogShow("加载族文件失败");
                }
            }
            //如果上述两者获取到了对应的族
            if (tagSymbol != null)
            {
                //doc.Create.NewFamilyInstance(, tagSymbol);
            }
            #endregion

            #region 建筑建模

            VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () =>
            {
                var levelId         = 111;
                Level level         = doc.GetElement(new ElementId(levelId)) as Level;
                LevelType levelType = doc.GetElement(level.GetTypeId()) as LevelType;


                return(true);
            });


            #endregion

            return(Result.Succeeded);
        }
Esempio n. 27
0
        public List <ApplicationPlaceholderObject> GridLineToNative(GridLine speckleGridline)
        {
            var revitGrid = GetExistingElementByApplicationId(speckleGridline.applicationId) as Grid;
            var curve     = CurveToNative(speckleGridline.baseLine).get_Item(0);

            //delete and re-create line
            //TODO: check if can be modified
            if (revitGrid != null)
            {
                if (revitGrid.IsCurved)
                {
                    Doc.Delete(revitGrid.Id); //not sure how to modify arc grids
                }
                else
                {
                    //dim's magic from 1.0
                    var oldStart = revitGrid.Curve.GetEndPoint(0);
                    var oldEnd   = revitGrid.Curve.GetEndPoint(1);

                    var newStart = curve.GetEndPoint(0);
                    var newEnd   = curve.GetEndPoint(1);

                    var translate = newStart.Subtract(oldStart);
                    ElementTransformUtils.MoveElement(Doc, revitGrid.Id, translate);

                    var currentDirection = revitGrid.Curve.GetEndPoint(0).Subtract(revitGrid.Curve.GetEndPoint(1)).Normalize();
                    var newDirection     = newStart.Subtract(newEnd).Normalize();

                    var angle = newDirection.AngleTo(currentDirection);

                    if (angle > 0.00001)
                    {
                        var crossProd = newDirection.CrossProduct(currentDirection).Z;
                        ElementTransformUtils.RotateElement(Doc, revitGrid.Id, Autodesk.Revit.DB.Line.CreateUnbound(newStart, XYZ.BasisZ), crossProd < 0 ? angle : -angle);
                    }

                    try
                    {
                        revitGrid.SetCurveInView(DatumExtentType.Model, Doc.ActiveView, Line.CreateBound(newStart, newEnd));
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to set grid endpoints.");
                    }
                }
            }

            //create the grid
            if (revitGrid == null)
            {
                if (curve is Arc a)
                {
                    revitGrid = Grid.Create(Doc, a);
                }
                else if (curve is Line l)
                {
                    revitGrid = Grid.Create(Doc, l);
                }
                else
                {
                    throw new Speckle.Core.Logging.SpeckleException("Curve type not supported for Grid: " + curve.GetType().FullName);
                }
            }

            //name must be unique, too much faff
            //revitGrid.Name = speckleGridline.label;

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject
                {
                    applicationId          = speckleGridline.applicationId,
                    ApplicationGeneratedId = revitGrid.UniqueId,
                    NativeObject           = revitGrid
                }
            };


            return(placeholders);
        }
Esempio n. 28
0
        public Result Execute(
          ExternalCommandData commandData,
          ref string message,
          ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            try
            {
                
                Reference refWall = uidoc.Selection.PickObject(ObjectType.Element, "Select a wall");

                Element selectedWall = doc.GetElement(refWall);

                //top and bottom elevation
                ElementId wallTopLevel = selectedWall.LookupParameter("Top Constraint").AsElementId();

                double wallTopElevation = doc.GetElement(wallTopLevel).LookupParameter("Elevation").AsDouble();

                ElementId wallBottomLevel = selectedWall.LookupParameter("Base Constraint").AsElementId();

                double wallBottomElevation = doc.GetElement(wallBottomLevel).LookupParameter("Elevation").AsDouble();

                string wallMark = selectedWall.LookupParameter("Mark").AsString();
                //

                List<ElementId> allLevelsList = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElementIds().ToList();

                IOrderedEnumerable<ElementId> levelByZ = from ElementId l in allLevelsList orderby doc.GetElement(l).LookupParameter("Elevation").AsDouble() ascending select l;

                IEnumerable<ElementId> topConstraintList = levelByZ.Where(eid => doc.GetElement(eid).LookupParameter("Elevation").AsDouble() <= wallTopElevation &&

                                                                          doc.GetElement(eid).LookupParameter("Elevation").AsDouble() > wallBottomElevation

                                                                         ).ToList();

                IEnumerable<ElementId> bottomConstraintList = levelByZ.Where(eid => doc.GetElement(eid).LookupParameter("Elevation").AsDouble() >= wallBottomElevation &&

                                                              doc.GetElement(eid).LookupParameter("Elevation").AsDouble() < wallTopElevation

                                                             ).ToList();

                using (var t = new Transaction(doc, "Split Wall"))
                {

                    t.Start();

                    FailureHandlingOptions failOpt = t.GetFailureHandlingOptions();

                    failOpt.SetFailuresPreprocessor(new DuplicateMarksSwallower());

                    t.SetFailureHandlingOptions(failOpt);

                    for (int i = 0; i < topConstraintList.Count(); i++)
                    {

                        ICollection<ElementId> newWallId = ElementTransformUtils.CopyElement(doc, selectedWall.Id, new XYZ(0, 0, 0));

                        Element newWall = doc.GetElement(newWallId.First());

                        ElementId topLevelId = topConstraintList.ElementAt(i);
                        ElementId bottomLevelId = bottomConstraintList.ElementAt(i);

                        newWall.LookupParameter("Top Constraint").Set(topLevelId);

                        newWall.LookupParameter("Base Constraint").Set(bottomLevelId);

                        newWall.LookupParameter("Mark").Set(wallMark);
                    }



                    doc.Delete(selectedWall.Id);

                    t.Commit();

                }


                string splittingLevels = "";

                foreach (ElementId eid in topConstraintList)
                {

                    splittingLevels += doc.GetElement(eid).Name + "\n";
                }

                TaskDialog.Show("Result", String.Format("The wall has been splitted in {0} parts at: \n{1}", topConstraintList.Count(), splittingLevels));

                return Result.Succeeded;
            }
            catch
            {
                return Result.Failed;
            }


        }
Esempio n. 29
0
 public void RotateElement(ElementId id, double angle, XYZ axis0, XYZ axis1) =>
 ElementTransformUtils.RotateElement(doc, id, Line.CreateBound(axis0, axis1), angle);
Esempio n. 30
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("CopyTemplates"));

            Application app     = commandData.Application.Application;
            Document    mainDoc = commandData.Application.ActiveUIDocument.Document;

            DocumentSet       docSet  = app.Documents;
            List <MyDocument> allDocs = new List <MyDocument>();

            foreach (Document doc in app.Documents)
            {
                if (doc.Title == mainDoc.Title)
                {
                    continue;
                }
                if (doc.IsValidObject)
                {
                    MyDocument myDoc = new MyDocument(doc);
                    allDocs.Add(myDoc);
                }
            }
            Debug.Write("Docs count: " + allDocs.Count);
            if (allDocs.Count == 0)
            {
                message = "Нет открытых документов для копирования!";
                return(Result.Failed);
            }

            FormSelectDocument form1 = new FormSelectDocument(allDocs);

            form1.ShowDialog();
            if (form1.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Debug.WriteLine("Cancelled by user");
                return(Result.Cancelled);
            }

            Document selectedDoc = form1.selectedDocument.doc;

            Debug.WriteLine("Selected doc: " + selectedDoc.Title);

            List <View> templates = new FilteredElementCollector(selectedDoc)
                                    .OfClass(typeof(View))
                                    .Cast <View>()
                                    .Where(v => v.IsTemplate == true)
                                    .ToList();

            Debug.WriteLine("Templates found: " + templates.Count);
            List <MyView> myViews = templates
                                    .OrderBy(i => i.Name)
                                    .Select(i => new MyView(i))
                                    .ToList();

            FormSelectTemplates form2 = new FormSelectTemplates(myViews);

            form2.ShowDialog();
            if (form2.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Debug.WriteLine("Cancelled by user");
                return(Result.Cancelled);
            }

            List <ElementId> templateIds = form2.selectedTemplates.Select(i => i.view.Id).ToList();

            Debug.WriteLine("Selected templates: " + templateIds.Count);
            CopyPasteOptions cpo = new CopyPasteOptions();

            cpo.SetDuplicateTypeNamesHandler(new DuplicateNamesHandler());

            using (Transaction t = new Transaction(mainDoc))
            {
                t.Start("Копирование шаблонов видов");

                ElementTransformUtils.CopyElements(selectedDoc, templateIds, mainDoc, Transform.Identity, cpo);

                t.Commit();
            }

            string msg = "Успешно скопировано шаблонов: " + templateIds.Count.ToString();

            if (DuplicateTypes.types.Count > 0)
            {
                msg += "\nПродублированы: " + DuplicateTypes.ReturnAsString();
            }

            Debug.WriteLine(msg);
            TaskDialog.Show("Отчет", msg);

            return(Result.Succeeded);
        }