Пример #1
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            if (doc.IsFamilyDocument)
            {
                TaskDialog.Show("Error", "This tool only works in Project environment.");

                return(Result.Cancelled);
            }

            Transaction t1 = new Transaction(doc, "Draw Insulation");

            try
            {
                Reference refinsulation = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterAnnotation(), "Select Insulation Batting");

                Reference refcurve = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterCurve(), "Select Curve");

                DetailCurve insulationdetailcurve = doc.GetElement(refinsulation) as DetailCurve;

                DetailCurve detailcurve = doc.GetElement(refcurve) as DetailCurve;

                double width = insulationdetailcurve.LookupParameter("Insulation Width").AsDouble();

                double ratio = insulationdetailcurve.LookupParameter("Insulation Bulge to Width Ratio (1/x)").AsDouble();

                Curve curve = detailcurve.GeometryCurve;

                t1.Start();

                if (curve is Arc && curve.IsBound)
                {
                    List <Line> lines = SplitArc(curve, width, ratio);

                    foreach (Line l in lines)
                    {
                        DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve;
                        newcurve.GeometryCurve = l;
                    }
                }
                if (curve is Line && curve.IsBound)
                {
                    Line        l        = curve as Line;
                    DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve;
                    newcurve.GeometryCurve = l;
                }

                t1.Commit();

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                t1.RollBack();
                return(Result.Cancelled);
            }
        }
Пример #2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var        uiapp = commandData.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            doc.Invoke(m =>
            {
                Element ele = sel.PickObject(ObjectType.Element, "请选择一个元素").GetElement(doc);
                ICollection <Element> eles = new List <Element>();
                eles.Add(ele);
                XYZ newTrans = new XYZ(1000d.MmToFeet(), 2000d.MmToFeet(), 0);
                var ele2     = ElementTransformUtils.CopyElement(doc, ele.Id, newTrans);
                string info  = "";
                int i        = 0;
                info        += "元素总个数:" + eles.Count;
                foreach (var elementId in ele2)
                {
                    i++;
                    info += i + ":\nNew:" + elementId + "\nOld:" + ele.Id;
                }
                TaskDialog.Show("tips", info);
            }
                       , "复制元素1");

            return(Result.Succeeded);
        }
Пример #3
0
        public void CopyElementByVectorClipBoard2()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;


            ElementId eIdHost = uiDoc.Selection.PickObject(ObjectType.Element, "pick Host").ElementId;

            Element eHost = doc.GetElement(eIdHost);

            LocationCurve cur     = eHost.Location as LocationCurve;
            Line          lineCur = cur.Curve as Line;

            XYZ    q           = lineCur.GetEndPoint(0);
            XYZ    p           = lineCur.GetEndPoint(1);
            XYZ    v           = p - q;
            double lengCurLine = v.GetLength();


            ElementId eIdRebar = uiDoc.Selection.PickObject(ObjectType.Element, "Pick rebar").ElementId;

            Element eRebar = doc.GetElement(eIdRebar);


            List <XYZ> myCoors = new List <XYZ>();

            string myTextClipBoard = Clipboard.GetText();

            //Split each line in
            string[] distances = myTextClipBoard.Split(';');
            foreach (string distance in distances)
            {
                XYZ myPointPlace = (Convert.ToDouble(distance) / lengCurLine) * v;
                myCoors.Add(myPointPlace);
            }

            if (myCoors.Count < 1)
            {
                TaskDialog.Show("Empty Data", "ClipBoard không có dữ liệu phù hợp...");
                return;
            }

            // using transcation (edit DB)
            using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

            {
                myTrans.Start();
                foreach (XYZ myXYZ in myCoors)
                {
                    ElementTransformUtils.CopyElement(doc, eIdRebar, myXYZ);
                }
                myTrans.Commit();
            }
        }
Пример #4
0
        private List <Ceiling> CreateCeilings(Room room, List <Ceiling> ceilingsFound, CeilingType ceilingType, ref StringBuilder msgBuilder)
        {
            var copiedCeilings = new List <Ceiling>();

            try
            {
                foreach (var ceiling in ceilingsFound)
                {
                    using (var trans = new Transaction(Doc))
                    {
                        trans.Start("Copy Ceiling");
                        try
                        {
                            double finishThickness = 0;
                            var    param           = ceilingType.get_Parameter(BuiltInParameter.CEILING_THICKNESS);
                            if (null != param)
                            {
                                if (param.HasValue)
                                {
                                    finishThickness = param.AsDouble();
                                }
                            }

                            var copiedIds = ElementTransformUtils.CopyElement(Doc, ceiling.Id, new XYZ(0, 0, -finishThickness));
                            trans.Commit();

                            trans.Start("Change Ceiling Type");
                            if (copiedIds.Count > 0)
                            {
                                var copiedCeilingId = copiedIds.First();
                                var copiedCeiling   = Doc.GetElement(copiedCeilingId) as Ceiling;
                                if (null != copiedCeiling)
                                {
                                    var changedTypeId = copiedCeiling.ChangeTypeId(ceilingType.Id);
                                    copiedCeilings.Add(copiedCeiling);
                                }
                            }
                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            msgBuilder.AppendLine(ceiling.Name + " [" + ceiling.Id.IntegerValue + "]: cannot be copied\n" + ex.Message);
                            trans.RollBack();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot create ceilings from the selected rooms.\nRoom Id:" + room.Id.IntegerValue + "\n\n" + ex.Message, "Create Ceilings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(copiedCeilings);
        }
Пример #5
0
        /// <summary>
        /// Offsets an element a set amount in a specific direction set by the XYZDirection enum
        /// </summary>
        /// <param name="originalelement">element, the new element should be offset from</param>
        /// <param name="offsetamount">amount new element should be offset from original</param>
        /// <param name="offsetdirection">direction element should be offset</param>
        /// <returns></returns>
        public static ElementId Offset(this Element originalelement, double offsetamount, XYZDirection offsetdirection)
        {
            // variable for new offset element
            ElementId newelement = null;

            // the current document
            Document curdoc = originalelement.Document;

            // element's XYZ
            LocationPoint elp           = originalelement.Location as LocationPoint;
            XYZ           elem_location = null;


            // depending on user input offset direction should be incremented by the offsetamount
            switch (offsetdirection)
            {
            default:
                break;

            case XYZDirection.X:
                elem_location = new XYZ(offsetamount, 0.0, 0.0) + elp.Point;
                break;

            case XYZDirection.Y:
                elem_location = new XYZ(0.0, offsetamount, 0.0) + elp.Point;
                break;

            case XYZDirection.Z:
                elem_location = new XYZ(0.0, 0.0, offsetamount) + elp.Point;
                break;
            }

            try
            {
                // attempt to offset the element within the transaction
                using (Transaction tr_offset = new Transaction(curdoc, "Offsetting element"))
                {
                    tr_offset.Start();
                    newelement = ElementTransformUtils.CopyElement(curdoc, originalelement.Id, elem_location).FirstOrDefault();
                    tr_offset.Commit();
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("Command Failed. See below: \n" + e.StackTrace.ToString());
            }

            return(newelement);
        }
Пример #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;

            uidoc.Document.AutoTransaction(() =>
            {
                var reference = uidoc.Selection.PickObject(ObjectType.Element, "Please select a element.");

                // Copying element.
                ElementTransformUtils.CopyElement(uidoc.Document, uidoc.Document.GetElement(reference).Id, new XYZ(10, 10, 0));

                // Deleting element.
                uidoc.Document.Delete(uidoc.Document.GetElement(reference).Id);
            });

            return(Result.Succeeded);
        }
Пример #7
0
        public void CopyElementByVectorClipBoard()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;


            ElementId eId = uiDoc.Selection.PickObject(ObjectType.Element).ElementId;

            Element e = doc.GetElement(eId);

            List <XYZ> myCoors = new List <XYZ>();

            string myTextClipBoard = Clipboard.GetText();

            //Split each line in
            string[] lines = myTextClipBoard.Split(';');
            foreach (string line in lines)
            {
                string[] myItem = line.Split('|');
                if (myItem.Length - 1 == 2)
                {
                    if (myItem[0] != "0" || myItem[1] != "0")
                    {
                        myCoors.Add(new XYZ(Convert.ToDouble(myItem[0]) / 304.8, Convert.ToDouble(myItem[1]) / 304.8, Convert.ToDouble(myItem[2]) / 304.8));
                    }
                }
            }

            if (myCoors.Count < 1)
            {
                TaskDialog.Show("Empty Data", "ClipBoard không có dữ liệu phù hợp...");
                return;
            }

// using transcation (edit DB)
            using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

            {
                myTrans.Start();
                foreach (XYZ myXYZ in myCoors)
                {
                    ElementTransformUtils.CopyElement(doc, eId, myXYZ);
                }
                myTrans.Commit();
            }
        }
Пример #8
0
        public void editDimText()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;


            ElementId eId = uiDoc.Selection.PickObject(ObjectType.Element).ElementId;

            Element e = doc.GetElement(eId);

            List <XYZ> myCoors = new List <XYZ>();

//read textFile coordinate

            string textFile = @"C:\Users\NAMTRUNG205\Desktop\myFile.txt";

            if (File.Exists(textFile))
            {
//Split each line in



                string[] lines = File.ReadAllLines(textFile);
                foreach (string line in lines)
                {
                    string[] myItem = line.Split('|');
                    if (myItem.Length - 1 == 2)
                    {
                        myCoors.Add(new XYZ(Convert.ToInt32(myItem[0]), Convert.ToInt32(myItem[1]), Convert.ToInt32(myItem[2])));
                    }
                }
            }

// using transcation (edit DB)
            using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

            {
                myTrans.Start();
                foreach (XYZ myXYX in myCoors)
                {
                    ElementTransformUtils.CopyElement(doc, eId, myXYX);
                }
                myTrans.Commit();
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp  = commandData.Application;
            UIDocument    uidoc  = commandData.Application.ActiveUIDocument;
            Document      doc    = uidoc.Document;
            Selection     sel    = uidoc.Selection;
            View          acview = uidoc.ActiveView;
            //UIView acuivew = uidoc.Activeuiview();
            var eleref = sel.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is MEPCurve),
                                        "拾取管线打断点");
            var pickpoint    = eleref.GlobalPoint;
            var mep          = eleref.GetElement(doc) as MEPCurve;
            var locationline = (mep.Location as LocationCurve).Curve as Line;

            pickpoint = pickpoint.ProjectToXLine(locationline); //ProjectToXLine 方法作用是 获取点投影到直线上的点
            var startpo   = locationline.StartPoint();
            var endpo     = locationline.EndPoint();
            var newstart  = startpo;
            var newend    = pickpoint;
            var newstart1 = pickpoint;
            var newend1   = endpo;



            Transaction ts = new Transaction(doc, "***********");

            try
            {
                ts.Start();
                var newmep = ElementTransformUtils.CopyElement(doc, mep.Id, new XYZ()).First().GetElement(doc) as MEPCurve;
                chagnemeplen(mep, newstart, newend);
                chagnemeplen(newmep, newstart1, newend1);
                ts.Commit();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                if (ts.GetStatus() == TransactionStatus.Started)
                {
                    ts.RollBack();
                }
                //throw;
            }
            return(Result.Succeeded);
        }
Пример #10
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc     = commandData.Application.ActiveUIDocument;
            Document   doc       = uidoc.Document;
            Selection  selection = uidoc.Selection;

            while (true)
            {
                try
                {
                    using (Transaction ts = new Transaction(doc))
                    {
                        ts.Start("打断");
                        Reference     refElement = selection.PickObject(ObjectType.PointOnElement, "请选择需要打断的点");
                        XYZ           point      = refElement.GlobalPoint;
                        Element       elem       = doc.GetElement(refElement);
                        LocationCurve lc         = elem.Location as LocationCurve;
                        XYZ           newPoint   = lc.Curve.Project(point).XYZPoint;
                        if (lc == null)
                        {
                            TaskDialog.Show("Error", "您选择的构建不可以分割,请重新选择");
                            continue;
                        }
                        XYZ startPoint = lc.Curve.GetEndPoint(0);
                        XYZ endPoint   = lc.Curve.GetEndPoint(1);

                        Line    l1  = Line.CreateBound(startPoint, newPoint);
                        Line    l2  = Line.CreateBound(newPoint, endPoint);
                        Element el1 = doc.GetElement(ElementTransformUtils.CopyElement(doc, elem.Id, new XYZ(1, 0, 0)).First());
                        Element el2 = doc.GetElement(ElementTransformUtils.CopyElement(doc, elem.Id, new XYZ(1, 0, 0)).First());
                        (el1.Location as LocationCurve).Curve = l1;
                        (el2.Location as LocationCurve).Curve = l2;
                        doc.Delete(elem.Id);
                        ts.Commit();
                    }
                }
                catch
                {
                    break;
                }
            }


            return(Result.Succeeded);
        }
Пример #11
0
        public List <FamilyInstance> CutBeam(FamilyInstance beam, XYZ point)
        {
            var result = new List <FamilyInstance>();
            var doc    = beam.Document;

            var locationcurve = beam.Location as LocationCurve;
            var locationline  = locationcurve.Curve as Line;

            if (locationline == null)
            {
                return(result);
            }

            point = point.ProjectToXLine(locationline);
            if (point.IsOnLine(locationline))
            {
                var start = locationline.StartPoint();
                var end   = locationline.EndPoint();

                var line1 = Line.CreateBound(start, point);
                var line2 = Line.CreateBound(point, end);

                (beam.Location as LocationCurve).Curve = line1;

                var copiedBeams = ElementTransformUtils.CopyElement(beam.Document, beam.Id, new XYZ());
                var beam2Id     = copiedBeams.First();
                var beam2       = beam2Id.GetElement(doc) as FamilyInstance;

                (beam2.Location as LocationCurve).Curve = line2;

                result.Add(beam);
                result.Add(beam2);
            }
            else
            {
                throw new Exception("point is not on beam,can not cut beam!");
            }

            return(result);
        }
Пример #12
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);
        }
Пример #13
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);
                }
            });
        }
Пример #14
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);
        }
Пример #15
0
        public static ICollection <ElementId> Transform(Document doc, ElementId id, XYZ trans)
        {
            ICollection <ElementId> newElements = ElementTransformUtils.CopyElement(doc, id, trans);

            return(newElements);
        }
        private List <ElementId> copyRebarByDistance_Update_MaxSpace(Document doc, Rebar myRebar, Dictionary <double, double> myDicDisNum)
        {
            List <double> myDistances = myDicDisNum.Keys.ToList();

            myDistances.Sort();

            List <double> myListNum = new List <double>();

            foreach (double key in myDistances)
            {
                myListNum.Add(myDicDisNum[key]);
            }


            //Get Id rebar
            ElementId myIdRebar = myRebar.Id;


            //Get Id Beam
            ElementId myIdBeam = myRebar.GetHostId();

            Element myBeam = doc.GetElement(myIdBeam);


            if (myBeam.Category.Name != "Structural Framing")
            {
                TaskDialog.Show("Loi!", "Hay chon 1 rebar co host la 1 Structural Framing");
                return(null);
            }

            else
            {
                LocationCurve cur     = myBeam.Location as LocationCurve;
                Line          lineCur = cur.Curve as Line;


                XYZ    p1          = lineCur.GetEndPoint(0);
                XYZ    q           = lineCur.GetEndPoint(1);
                XYZ    v           = q - p1;
                double lengCurLine = v.GetLength();

                XYZ p = p1 - 0.1 * v;

                List <XYZ> myCoors = new List <XYZ>();

                // NOTE LAM TRON SO

                //Get diameter of rebar

                XYZ middlePoint = myRebar.get_BoundingBox(null).Max.Add(myRebar.get_BoundingBox(null).Min) / 2;

                List <Curve> centerLines = myRebar.GetCenterlineCurves(false, false, false,
                                                                       MultiplanarOption.IncludeOnlyPlanarCurves, 0)
                                           as List <Curve>;


                foreach (Curve myCurBar in centerLines)
                {
                    middlePoint = myCurBar.GetEndPoint(0);
                    break;
                }

                Plane myReBarPlane = Plane.CreateByNormalAndOrigin(v, middlePoint);


                // Distance from first rebar to
                RebarBarType myRbType        = doc.GetElement(myRebar.GetTypeId()) as RebarBarType;
                double       myRebarDiameter = myRbType.BarDiameter;


                XYZ v1 = p - myReBarPlane.Origin;

                double delta_0 = Math.Abs(myReBarPlane.Normal.DotProduct(v1));

                if (delta_0 == 10000000)
                {
                    return(null);
                }

                foreach (double distance in myDistances)
                {
                    XYZ myPointPlace = ((distance - delta_0) / lengCurLine) * v;
                    myCoors.Add(myPointPlace);
                }

                if (myCoors.Count < 1)
                {
                    TaskDialog.Show("Loi!", "Khong the copy...");
                    return(null);
                }

                ICollection <ElementId> myRebarIdCol;
                List <ElementId>        myListIdRebar = new List <ElementId>();

                // using transcation (edit DB)
                using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

                {
                    myTrans.Start();
                    foreach (XYZ myXYZ in myCoors)
                    {
                        myRebarIdCol = ElementTransformUtils.CopyElement(doc, myIdRebar, myXYZ);
                        foreach (ElementId elemRebarId in myRebarIdCol)
                        {
                            myListIdRebar.Add(elemRebarId);
                        }
                    }
                    myTrans.Commit();
                }
                return(myListIdRebar);
            }
        }
Пример #17
0
        public void copyAndPlaceFamilyAtDwgBlock(UIDocument uiDoc)
        {
            Document doc = uiDoc.Document;


            //Select ImportInstance

            //List<string> myListImportDwg = new List<string>() {"Import Symbol"};

            Reference myRefImportDWG = uiDoc.Selection.PickObject(ObjectType.Element,
                                                                  "Pick a Import DWG...");
            ImportInstance myImportInstance = doc.GetElement(myRefImportDWG) as ImportInstance;
            Element        dwgImportElement = doc.GetElement(myRefImportDWG);


            string myTextClipBoard = Clipboard.GetText();


            Dictionary <XYZ, double> myDicCoorAndRot = getOriginAndRotByBlock(dwgImportElement, myTextClipBoard);

            if (myDicCoorAndRot.Keys.Count < 1)
            {
                TaskDialog.Show("Error!!", "CLipboard không có dữ liệu, hoặc file .DWG không chứa block có tên như trong clipboard");
                return;
            }

            Reference myRefFamily = uiDoc.Selection.PickObject(ObjectType.Element, "Select Instance Family...");

            Element myFamilyElement = doc.GetElement(myRefFamily);


            XYZ originInstance = myImportInstance.GetTransform().Origin;

            LocationCurve locCurve = myFamilyElement.Location as LocationCurve;

            if (null == locCurve)
            {
                XYZ pointRef = ((LocationPoint)myFamilyElement.Location).Point;


                XYZ deltaXYZ = new XYZ();
                List <ElementId> myElemIdCopiedColTotal = new List <ElementId>();
                foreach (XYZ myXYZ in myDicCoorAndRot.Keys)
                {
                    List <ElementId> myElemIdCopiedCol = new List <ElementId>();

                    //Copy Element
                    using (Transaction myTrans = new Transaction(doc, "Copy Element"))
                    {
                        myTrans.Start();
                        deltaXYZ          = originInstance + myXYZ - pointRef;
                        myElemIdCopiedCol = ElementTransformUtils.CopyElement(doc, myFamilyElement.Id, deltaXYZ).ToList();
                        myTrans.Commit();
                    }

                    using (Transaction myTrans = new Transaction(doc, "RotateElement Location Point"))
                    {
                        myTrans.Start();
                        // Code here
                        //ElementTransformUtils.RotateElement(doc, myEle.Id, axis, DegreesToRadians(degrees));

                        foreach (ElementId myIdEleCopied in myElemIdCopiedCol)
                        {
                            Element myElemCopied = doc.GetElement(myIdEleCopied);
                            XYZ     point        = ((LocationPoint)myElemCopied.Location).Point;
                            XYZ     point2       = point.Add(XYZ.BasisZ);

                            Line axis = Line.CreateBound(point, point2);

                            ElementTransformUtils.RotateElement(doc, myIdEleCopied, axis, myDicCoorAndRot[myXYZ]);
                            myElemIdCopiedColTotal.Add(myIdEleCopied);
                        }
                        myTrans.Commit();
                    }
                }

                // Make group From element Cp=opied
                using (Transaction trans = new Transaction(doc, "Make group from Copied Element"))
                {
                    trans.Start();
                    if (myElemIdCopiedColTotal.Count > 0)
                    {
                        Group myGroupRebar = doc.Create.NewGroup(myElemIdCopiedColTotal);
                        //	myGroupRebar.GroupType.Name = rebarGroupName;
                    }
                    else
                    {
                        TaskDialog.Show("Warning!", "No rebar was hosted by this element, so no any group was created!");
                    }
                    trans.Commit();
                }
            }
        }
Пример #18
0
/// <summary>
/// Các nhóm hàm liên quan modify (copy, move, rotate ...Element)
/// </summary>
        public void CopyElementByVectorTextFile()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;


            ElementId eId = uiDoc.Selection.PickObject(ObjectType.Element).ElementId;

            Element e = doc.GetElement(eId);

            List <XYZ> myCoors = new List <XYZ>();


            var filePath = string.Empty;

            using (System.Windows.Forms.OpenFileDialog myOpenTxtPath = new System.Windows.Forms.OpenFileDialog())
            {
                myOpenTxtPath.InitialDirectory = "c:\\";
                myOpenTxtPath.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                myOpenTxtPath.FilterIndex      = 2;
                myOpenTxtPath.RestoreDirectory = true;

                if (myOpenTxtPath.ShowDialog() == DialogResult.OK)
                {
                    //Get the path of specified file
                    filePath = myOpenTxtPath.FileName;
                }

                //read textFile coordinate

                //	string textFile = @"C:\Users\NAMTRUNG205\Desktop\myFile.txt";

                string textFile = @filePath;

                if (File.Exists(textFile))
                {
                    //Split each line in
                    string[] lines = File.ReadAllLines(textFile);
                    foreach (string line in lines)
                    {
                        string[] myItem = line.Split('|');
                        if (myItem.Length - 1 == 2)
                        {
                            if (myItem[0] != "0" || myItem[1] != "0")
                            {
                                myCoors.Add(new XYZ(Convert.ToInt32(myItem[0]) / 304.8, Convert.ToInt32(myItem[1]) / 304.8, Convert.ToInt32(myItem[2]) / 304.8));
                            }
                        }
                    }
                }

// using transcation (edit DB)
                using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

                {
                    myTrans.Start();
                    foreach (XYZ myXYZ in myCoors)
                    {
                        ElementTransformUtils.CopyElement(doc, eId, myXYZ);
                    }
                    myTrans.Commit();
                }
            }
        }
Пример #19
0
        private List <ElementId> copyRebarByDistance(Document doc, Rebar myRebar, List <double> myDistances)
        {
            //UIDocument uiDoc = this.ActiveUIDocument;
            //Document doc = uiDoc.Document;

            //Get Id rebar
            ElementId myIdRebar = myRebar.Id;


            //Get Id Beam
            ElementId myIdBeam = myRebar.GetHostId();

            Element myBeam = doc.GetElement(myIdBeam);


            if (myBeam.Category.Name != "Structural Framing")
            {
                TaskDialog.Show("Loi!", "Hay chon 1 rebar co host la 1 Structural Framing");
                return(null);
            }

            else
            {
                LocationCurve cur     = myBeam.Location as LocationCurve;
                Line          lineCur = cur.Curve as Line;

                XYZ    q           = lineCur.GetEndPoint(0);
                XYZ    p           = lineCur.GetEndPoint(1);
                XYZ    v           = p - q;
                double lengCurLine = v.GetLength();


                List <XYZ> myCoors = new List <XYZ>();


                double delta0 = getDelta_0(doc, myRebar);

                if (delta0 == 10000000)
                {
                    return(null);
                }

                foreach (double distance in myDistances)
                {
                    XYZ myPointPlace = ((distance - delta0) / lengCurLine) * v;
                    myCoors.Add(myPointPlace);
                }

                if (myCoors.Count < 1)
                {
                    TaskDialog.Show("Loi!", "Khong the copy...");
                    return(null);
                }

                ICollection <ElementId> myRebarIdCol;
                List <ElementId>        myListIdRebar = new List <ElementId>();

                // using transcation (edit DB)
                using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate"))

                {
                    myTrans.Start();
                    foreach (XYZ myXYZ in myCoors)
                    {
                        myRebarIdCol = ElementTransformUtils.CopyElement(doc, myIdRebar, myXYZ);
                        foreach (ElementId elemRebarId in myRebarIdCol)
                        {
                            myListIdRebar.Add(elemRebarId);
                        }
                    }
                    myTrans.Commit();
                }
                return(myListIdRebar);
            }
        }
Пример #20
0
        /// <summary>
        /// Back-end facing method that displaces one element by the given displacement values with an option to copy
        /// </summary>
        /// <param name="element"></param>
        /// <param name="displacement"></param>
        /// <param name="location"></param>
        /// <param name="copy"></param>
        /// <returns></returns>
        private HashSet <ElementId> DisplaceElement(
            Element element,
            List <int> displacement,
            Location location,
            bool copy = false
            )
        {
            HashSet <ElementId> affected = new HashSet <ElementId>();

            // Get x, y, and z value (in feet and inches)
            double xValue = ConvertMM2FeetInch(displacement[0]);
            double yValue = ConvertMM2FeetInch(displacement[1]);
            double zValue = ConvertMM2FeetInch(displacement[2]);

            // Generate object to modify the x and y value
            XYZ newXY = new XYZ(xValue, yValue, 0);

            // Get z parameters to modify the z value
            List <string> zParams = this.GetZParamFromLoc(location);

            // if method is copying, then tranName = "Copy and Move Elements", else, "Move Elements"
            string tranName = copy ? "Copy and Move Elements" : "Move Elements";
            // set transSuccess to true, used to determine whether or not to roll back the changes made to this element
            bool tranSuccess = true;

            using (Transaction tran = new Transaction(this.doc, tranName))
            {
                tran.Start();

                if (copy)
                {
                    // If copied, then gather the elements that are newly created from the copy and add it into affected
                    ICollection <ElementId> elementsCopied = ElementTransformUtils.CopyElement(this.doc, element.Id, newXY);
                    affected.UnionWith(elementsCopied);
                }
                else
                {
                    // If not copied, then get the current element's id and add it into affected
                    ElementTransformUtils.MoveElement(this.doc, element.Id, newXY);
                    affected.Add(element.Id);
                }

                List <Parameter> parameters;
                foreach (ElementId id in affected)
                {
                    // Get the parameter for Z value
                    parameters = GetParameters(this.GetElement(id), zParams);

                    double elevationDouble;
                    string elevationString;
                    foreach (Parameter p in parameters)
                    {
                        // Get the the new elevation value for the given parameter
                        elevationDouble = ConvertStringToFeetInch(p.AsValueString()) + zValue;
                        elevationString = ConvertFeetInchToString(elevationDouble);
                        // Apply the elevation value into the parameter
                        p.SetValueString(elevationString);
                    }
                }

                // If the transation is a success, commit the changes, else, roll back (undo) the changes made
                if (tranSuccess)
                {
                    tran.Commit();
                }
                else
                {
                    tran.RollBack();
                }
            }

            return(affected);
        }
Пример #21
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            if (doc.IsFamilyDocument)
            {
                TaskDialog.Show("Error", "This tool only works in Project environment.");

                return(Result.Cancelled);
            }

            Transaction t1 = new Transaction(doc, "Draw Insulation");

            try
            {
                Reference refinsulation = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterAnnotation(), "Select Insulation Batting");

                Reference refcurve = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterCurve(), "Select Curve");

                DetailCurve insulationdetailcurve = doc.GetElement(refinsulation) as DetailCurve;

                DetailCurve detailcurve = doc.GetElement(refcurve) as DetailCurve;

                double width = insulationdetailcurve.get_Parameter(BuiltInParameter.INSULATION_WIDTH).AsDouble(); //swapped to built in parameter for cross-language compatibility

                double ratio = insulationdetailcurve.get_Parameter(BuiltInParameter.INSULATION_SCALE).AsDouble(); //swapped to built in parameter for cross-language compatibility

                Curve curve = detailcurve.GeometryCurve;

                t1.Start();

                if (curve is Arc && curve.IsBound)
                {
                    List <Line> lines = SplitArc(curve, width, ratio);

                    foreach (Line l in lines)
                    {
                        DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve;
                        newcurve.GeometryCurve = l;
                    }
                }
                if (curve is Line && curve.IsBound)
                {
                    Line        l        = curve as Line;
                    DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve;
                    newcurve.GeometryCurve = l;
                }

                t1.Commit();

                return(Result.Succeeded);
            }
            catch
            {
                if (t1.HasStarted()) // check to see if the transaction even started before trying to roll it back
                {
                    t1.RollBack();
                }
                return(Result.Cancelled);
            }
        }
Пример #22
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app = commandData.Application.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            bool SourceIsWallFoundation = false;
            Reference ref1 = null;
            IList<Reference> ref2List = new List<Reference>();

            try
            {
                ref1 = uidoc.Selection.PickObject(ObjectType.Element, new RebarHostSelectionFilter(), "Pick a rebar host to copy from");
                ref2List = uidoc.Selection.PickObjects(ObjectType.Element, new RebarHostSelectionFilter(), "Pick a rebar host to copy to");
            }
            catch(Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                TaskDialog.Show("Rebar Copy command cancelled", "Click finish in top left corner to complete the command");
                return Result.Cancelled;
            }

            using (Transaction t1 = new Transaction(doc, "Copy rebar"))
            {
                t1.Start();
                foreach (Reference ref2 in ref2List)
                {
                    Element sourceHost = doc.GetElement(ref1.ElementId);
                    Element targetHost = doc.GetElement(ref2.ElementId);
                    ICollection<ElementId> elementIdToBeDeleted = new List<ElementId>();
                    WallFoundation sourceWallFoundation = null;
                    WallFoundation targetWallFoundation = null;
                    //Workaround for wall foundations: They have no location lines, but are completely dependent on their walls. So by copiing the host wall, both the wall foundation and the rebars follows along
                    if (sourceHost is WallFoundation && targetHost is WallFoundation)
                    {
                        SourceIsWallFoundation = true;
                        sourceWallFoundation = (WallFoundation)sourceHost;
                        sourceHost = doc.GetElement(sourceWallFoundation.WallId);
                        targetWallFoundation = (WallFoundation)targetHost;
                        targetHost = doc.GetElement(targetWallFoundation.WallId);
                    }
                    //STEP 1: Copy element to random location
                    //5000 is a random chosen number, surprisingly it matters if its copied in Y or Z direction:
                    ICollection<ElementId> copiedElements = ElementTransformUtils.CopyElement(doc, sourceHost.Id, new XYZ(0, 5000, 0));
                    Element copiedElement = doc.GetElement(copiedElements.FirstOrDefault());
                    elementIdToBeDeleted.Add(copiedElement.Id);

                    //STEP 2: Relocate copy to match the target 
                    if (copiedElement.Location is LocationCurve && targetHost.Location is LocationCurve)
                    {
                        LocationCurve locationTo = targetHost.Location as LocationCurve;
                        LocationCurve locationCopied = copiedElement.Location as LocationCurve;
                        locationCopied.Curve = locationTo.Curve;
                    }
                    else if (copiedElement.Location is LocationPoint && targetHost.Location is LocationPoint)
                    {
                        LocationPoint locationTo = targetHost.Location as LocationPoint;
                        LocationPoint locationCopied = copiedElement.Location as LocationPoint;
                        locationCopied.Point = locationTo.Point;
                        if (locationCopied.Rotation != locationTo.Rotation)
                        {
                            Transform trans1 = Transform.CreateTranslation(new XYZ(0, 0, 1));
                            XYZ origin1 = locationTo.Point;
                            XYZ endAxis = trans1.OfPoint(origin1);
                            Line axis1 = Line.CreateBound(origin1, endAxis);
                            locationCopied.Rotate(axis1, locationTo.Rotation);
                        }
                    }
                    else
                    {
                        TaskDialog.Show("Warning", "Pick two Rebar Hosts with the same location type. Only elements with locatoion lines and location points are supported. Elements such as beams, walls and slanted columns do typically have location lines. Floors and slabs are not supported.");
                        t1.RollBack();
                        return Result.Cancelled;
                    }


                    //STEP 3: Change the type of the copied element to match the target element
                    //TODO: Change types for wall foundations and change heights/offsets for walls
                    try
                    {
                        if (targetHost.GetTypeId() != copiedElement.GetTypeId())
                        {
                            copiedElement.ChangeTypeId(targetHost.GetTypeId());
                        }

                        if (targetHost is Wall && sourceHost is Wall)
                        {
                            copiedElement.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).Set(targetHost.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble());
                            copiedElement.get_Parameter(BuiltInParameter.WALL_TOP_OFFSET).Set(targetHost.get_Parameter(BuiltInParameter.WALL_TOP_OFFSET).AsDouble());
                        }

                        if (IsNotSlantedColumn(targetHost) && IsNotSlantedColumn(sourceHost))
                        {
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble());
                        } 
                    }
                    catch { }

                    doc.Regenerate();

                    //Step 3: Change rebar host from copied element to target element
                    IList<Rebar> copiedRebars = new List<Rebar>();

                    if (SourceIsWallFoundation)
                    {
                        //Need to find the foundation that was created by copying the wall
                        WallFoundation wallFoundation = new FilteredElementCollector(doc)
                            .OfClass(typeof(WallFoundation))
                            .WhereElementIsNotElementType().Cast<WallFoundation>()
                            .FirstOrDefault(q => q.WallId == copiedElement.Id);
                        elementIdToBeDeleted.Add(wallFoundation.Id);
                        copiedRebars = RebarHostData.GetRebarHostData(wallFoundation).GetRebarsInHost();
                        if (targetWallFoundation != null)
                        {
                            foreach (Rebar r in copiedRebars)
                            {
                                r.SetHostId(doc, targetWallFoundation.Id);
                            }
                        }

                    }
                    else
                    {
                        copiedRebars = RebarHostData.GetRebarHostData(copiedElement).GetRebarsInHost();
                        foreach (Rebar r in copiedRebars)
                        {
                            r.SetHostId(doc, targetHost.Id);
                        }
                    }

                    //Step 4: Delete the copied element
                    doc.Delete(elementIdToBeDeleted);

                }

                t1.Commit();
            }
            return Result.Succeeded;
        }
Пример #23
0
        public void placeFamilyByBlockOneAngle()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;


            //Select ImportInstance
            Reference myRef            = uiDoc.Selection.PickObject(ObjectType.Element, "Select Import DWG...");
            Element   dwgImportElement = doc.GetElement(myRef);


            string myTextClipBoard = Clipboard.GetText();


            Dictionary <XYZ, double> myDicCoorAndRot = getOriginAndRotByBlock(dwgImportElement, myTextClipBoard);

            if (myDicCoorAndRot.Keys.Count < 1)
            {
                TaskDialog.Show("Error!!", "CLipboard không có dữ liệu, hoặc file .DWG không chứa block có tên như trong clipboard");
                return;
            }


            Reference      myRefFamily      = uiDoc.Selection.PickObject(ObjectType.Element, "Select Instance Family...");
            ImportInstance myImportInstance = doc.GetElement(myRef) as ImportInstance;
            Element        myFamilyElement  = doc.GetElement(myRefFamily);

            LocationPoint myLocPoint    = myFamilyElement.Location as LocationPoint;
            double        myAngleFamily = myLocPoint.Rotation;



            XYZ originInstance = myImportInstance.GetTransform().Origin;

            LocationCurve locCurve = myFamilyElement.Location as LocationCurve;

            if (null == locCurve)
            {
                XYZ pointRef = ((LocationPoint)myFamilyElement.Location).Point;


                XYZ deltaXYZ = new XYZ();
                List <ElementId> myElemIdCopiedColTotal = new List <ElementId>();

                foreach (XYZ myXYZ in myDicCoorAndRot.Keys)
                {
                    List <ElementId> myElemIdCopiedCol = new List <ElementId>();

                    //Copy Element

                    if (Math.Round(myAngleFamily, 3) == Math.Round(myDicCoorAndRot[myXYZ], 3))
                    {
                        using (Transaction myTrans = new Transaction(doc, "Copy Element"))
                        {
                            myTrans.Start();
                            deltaXYZ          = originInstance + myXYZ - pointRef;
                            myElemIdCopiedCol = ElementTransformUtils.CopyElement(doc, myFamilyElement.Id, deltaXYZ).ToList();
                            myTrans.Commit();
                        }
                    }

                    foreach (ElementId myIdEleCopied in myElemIdCopiedCol)
                    {
                        myElemIdCopiedColTotal.Add(myIdEleCopied);
                    }
                }


                // Make group From element Cp=opied
                using (Transaction trans = new Transaction(doc, "Make group from Copied Element"))
                {
                    trans.Start();
                    if (myElemIdCopiedColTotal.Count > 0)
                    {
                        Group myGroupRebar = doc.Create.NewGroup(myElemIdCopiedColTotal);
                        //	myGroupRebar.GroupType.Name = rebarGroupName;
                    }
                    else
                    {
                        TaskDialog.Show("Warning!", "No rebar was hosted by this element, so no any group was created!");
                    }
                    trans.Commit();
                }
            }
        }
Пример #24
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiapp  = commandData.Application;
            var uidoc  = uiapp.ActiveUIDocument;
            var doc    = uidoc.Document;
            var sel    = uidoc.Selection;
            var acview = doc.ActiveView;

            ValueSettingUI settingWin = new ValueSettingUI();

            n :;
            settingWin.ShowDialog();

            var valuestring = settingWin.settingValue.Text;
            var value       = default(double);

            var parseResult = double.TryParse(valuestring, out value);

            if (!parseResult)
            {
                MessageBox.Show("数值错误,请重新输入");
                settingWin.Hide();
                goto n;
            }

            while (true)
            {
                try
                {
                    var eleref = sel.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is Pipe));

                    var pipe = eleref.GetElement(doc) as Pipe;

                    var pipecons = pipe.ConnectorManager.Connectors.Cast <Connector>();

                    var validcons = pipecons.Where(m =>
                                                   m.IsConnected && (m.ConnectorType == ConnectorType.End || m.ConnectorType == ConnectorType.Curve))
                                    .ToList();

                    if (validcons.Count < 1)
                    {
                        return(Result.Cancelled);
                    }
                    var connectedPipeFittings = validcons.Select(m => m.GetConnectedCon().Owner).Cast <FamilyInstance>().Where(m => m != null);
                    //MessageBox.Show(connectedPipeFittings.Count().ToString());

                    var teeFitting = default(IEnumerable <FamilyInstance>);
                    teeFitting = connectedPipeFittings.Where(m => m.Symbol.Family.get_Parameter(BuiltInParameter.FAMILY_CONTENT_PART_TYPE).AsValueString().Contains("三通") && m.FacingOrientation.IsParallel(pipe.LocationLine().Direction));

                    if (teeFitting.Count() == 1)
                    {
                        var tee       = teeFitting.FirstOrDefault();
                        var location  = (tee.Location as LocationPoint).Point;
                        var facingdir = tee.FacingOrientation;
                        var handdir   = tee.HandOrientation;
                        var anxisline = Line.CreateUnbound(location, handdir);

                        var updir    = -facingdir.CrossProduct(handdir);
                        var newupdir = default(XYZ);
                        if (updir.AngleTo(XYZ.BasisZ) <= Math.PI / 2)
                        {
                            newupdir = updir;
                        }
                        else
                        {
                            newupdir = -updir;
                        }

                        var consOfTee = tee.MEPModel.ConnectorManager.Connectors.Cast <Connector>();
                        var branchCon = consOfTee.Where(m => m.CoordinateSystem.BasisZ.IsSameDirection(-facingdir)).FirstOrDefault();

                        var connectedconOfBranchCon = branchCon.GetConnectedCon();

                        Transaction ts = new Transaction(doc, "提升支管高度");
                        ts.Start();

                        branchCon.DisconnectFrom(connectedconOfBranchCon);
                        //改变支管高度
                        ElementTransformUtils.MoveElement(doc, pipe.Id, newupdir * value / 304.8);

                        //旋转Tee
                        ElementTransformUtils.RotateElement(doc, tee.Id, anxisline, facingdir.AngleOnPlaneTo(newupdir * (value) / Math.Abs(value), -handdir));
                        doc.Regenerate();

                        var branchConPosition = branchCon.Origin;
                        var distance          = branchConPosition.DistanceTo(pipe.LocationLine());

                        //新创建管道
                        var startpo = branchConPosition;
                        var endpo   = startpo + newupdir * (value) / Math.Abs(value) * distance;

                        var newline = Line.CreateBound(startpo, endpo);

                        var newpipeid = ElementTransformUtils.CopyElement(doc, pipe.Id, new XYZ()).FirstOrDefault();

                        var newpipe = newpipeid.GetElement(doc) as Pipe;

                        (newpipe.Location as LocationCurve).Curve = newline;

                        foreach (Connector con in newpipe.ConnectorManager.Connectors)
                        {
                            var conorigin = con?.Origin;
                            if (conorigin == null)
                            {
                                continue;
                            }
                            if (conorigin.IsAlmostEqualTo(branchConPosition))
                            {
                                con.ConnectTo(branchCon);
                            }
                        }
                        pipe.ElbowConnect(newpipe);

                        ts.Commit();
                    }
                    else if (teeFitting.Count() == 2)
                    {
                        //两端都是三通的情况 暂未处理
                    }
                }
                catch (Exception e)
                {
                    break;
                }
            }
            return(Result.Succeeded);
        }
Пример #25
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                IList <Reference> refColumn = uidoc.Selection.PickObjects(ObjectType.Element, "Select columns");

                int count = 0;

                foreach (Reference reference in refColumn)
                {
                    Element selectedColumn = doc.GetElement(reference);

                    //top and bottom elevation
                    ElementId columnTopLevel = selectedColumn.LookupParameter("Top Level").AsElementId();

                    double columnTopElevation = doc.GetElement(columnTopLevel).LookupParameter("Elevation").AsDouble();

                    ElementId columnBottomLevel = selectedColumn.LookupParameter("Base Level").AsElementId();

                    double columnBottomElevation = doc.GetElement(columnBottomLevel).LookupParameter("Elevation").AsDouble();

                    string markValue = selectedColumn.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() <= columnTopElevation &&

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

                                                                               ).ToList();

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

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

                                                                                  ).ToList();

                    using (var t = new Transaction(doc, "Split Column"))
                    {
                        t.Start();

                        // Set failure handler
                        var failureOptions = t.GetFailureHandlingOptions();
                        failureOptions.SetFailuresPreprocessor(new DuplicateMarkSwallower());
                        t.SetFailureHandlingOptions(failureOptions);

                        for (int i = 0; i < topConstraintList.Count(); i++)
                        {
                            ICollection <ElementId> newWallId = ElementTransformUtils.CopyElement(doc, selectedColumn.Id, new XYZ(0, 0, 0));

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

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

                            newColumn.LookupParameter("Top Level").Set(topLevelId);

                            newColumn.LookupParameter("Base Level").Set(bottomLevelId);

                            newColumn.LookupParameter("Mark").Set(markValue);
                        }



                        doc.Delete(selectedColumn.Id);

                        t.Commit();
                    }


                    string splittingLevels = "";

                    foreach (ElementId eid in topConstraintList)
                    {
                        splittingLevels += doc.GetElement(eid).Name + "\n";
                    }

                    count += 1;
                }

                TaskDialog.Show("Result", String.Format("{0} columns have been splitted", count));

                return(Result.Succeeded);
            }
            catch
            {
                return(Result.Failed);
            }
        }
Пример #26
0
        public ElementId ChangeTypeKeepParameter(Element elem_old, ElementType type)
        {
            Document  doc           = elem_old.Document;
            ElementId id_newelement = null;
            //复制图元(偏移一段距离,跳过警告窗口)=>参数转移=>偏移回原位=>删除原有图元.
            ICollection <ElementId> ids_newelement = ElementTransformUtils.CopyElement(doc, elem_old.Id, new XYZ(1, 0, 0));

            if (ids_newelement.Count != 1)
            {
                return(null);
            }
            id_newelement = ids_newelement.First();
            Element elem_new = doc.GetElement(id_newelement);

            elem_new.ChangeTypeId(type.Id);
            //parameter
            ParameterSet parameterSet = elem_old.Parameters;

            foreach (Parameter para_oldelem in parameterSet)
            {
                if (para_oldelem.IsReadOnly)
                {
                    continue;
                }
                if (!para_oldelem.HasValue)
                {
                    continue;
                }
                if (para_oldelem.StorageType == StorageType.None)
                {
                    continue;
                }
                if (para_oldelem.StorageType == StorageType.ElementId)
                {
                    continue;
                }

                Parameter para_newelem = elem_new.LookupParameter(para_oldelem.Definition.Name);
                if (para_newelem.IsReadOnly)
                {
                    continue;
                }
                if (!para_newelem.HasValue)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.None)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.ElementId)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.Double)
                {
                    para_newelem.Set(para_oldelem.AsDouble());
                }
                if (para_newelem.StorageType == StorageType.Integer)
                {
                    para_newelem.Set(para_oldelem.AsInteger());
                }
                if (para_newelem.StorageType == StorageType.String)
                {
                    para_newelem.Set(para_oldelem.AsValueString());
                }
            }
            doc.Delete(elem_old.Id);
            ElementTransformUtils.MoveElement(doc, id_newelement, new XYZ(-1, 0, 0));
            return(id_newelement);
        }
Пример #27
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            try
            {
                FamilyInstance selectedBeam = doc.GetElement(sel.PickObject(ObjectType.Element, new BeamSelectionFilter(), Properties.Messages.CopyBeamsToLevels_SelectBeam)) as FamilyInstance;

                ElementId levelID = selectedBeam.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM).AsElementId();

                IList <Element> beamInSourceLevel = Utils.FindElements.GetElementsInLevelBounds(doc, levelID, 3.00, BuiltInCategory.OST_StructuralFraming);

                beamInSourceLevel = beamInSourceLevel.Where(b => b.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM).AsElementId() == levelID).ToList();

                IList <LevelInfo> allLevelInfo = Utils.GetInformation.GetAllLevelsInfo(doc);

                ElementsCopyUI currentUI = new ElementsCopyUI(allLevelInfo);

                currentUI.ShowDialog();

                if (currentUI.DialogResult == false)
                {
                    return(Result.Cancelled);
                }


                var selectedLevelsInfo = currentUI.listLevels.SelectedItems;

                if (selectedLevelsInfo.Count == 0)
                {
                    return(Result.Cancelled);
                }

                using (Transaction t = new Transaction(doc, Properties.Messages.CopyBeamsToLevels_Transaction))
                {
                    t.Start();
                    foreach (LevelInfo currentLevelInfo in selectedLevelsInfo)
                    {
                        ElementId currentLevelID = new ElementId(currentLevelInfo.levelId);
                        Level     currentLevel   = doc.GetElement(currentLevelID) as Level;

                        if (currentUI.checkEraseBeamsOnTarget.IsChecked == true)
                        {
                            IList <Element> beamsTodelete = Utils.FindElements.GetElementsInLevelBounds(doc, currentLevelID, 3.00, BuiltInCategory.OST_StructuralFraming);

                            beamsTodelete = beamsTodelete.Where(b => b.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM).AsElementId() == currentLevelID).ToList();

                            foreach (Element currentBeamToDelete in beamsTodelete)
                            {
                                doc.Delete(currentBeamToDelete.Id);
                            }
                        }

                        foreach (Element currentBeam in beamInSourceLevel)
                        {
                            IList <ElementId> copiedElementsIDs = ElementTransformUtils.CopyElement(doc, currentBeam.Id, XYZ.Zero).ToList();

                            foreach (ElementId currentcopiedID in copiedElementsIDs)
                            {
                                Element currentCopiedElement = doc.GetElement(currentcopiedID);

                                if (currentCopiedElement is FamilyInstance)
                                {
                                    currentCopiedElement.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END0_ELEVATION).Set(1);
                                    currentCopiedElement.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END1_ELEVATION).Set(1);

                                    currentCopiedElement.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM).Set(currentLevelID);

                                    currentCopiedElement.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END0_ELEVATION).Set(0);
                                    currentCopiedElement.get_Parameter(BuiltInParameter.STRUCTURAL_BEAM_END1_ELEVATION).Set(0);

                                    if (currentUI.checkEraseBeamsOnTarget.IsChecked == false)
                                    {
                                        doc.Regenerate();
                                        Utils.CheckFamilyInstanceForIntersection.checkForDuplicates(currentCopiedElement as FamilyInstance, doc);
                                    }
                                }
                            }
                        }
                    }
                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
            }

            return(Result.Succeeded);
        }
Пример #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;
            }


        }
Пример #29
0
 /// <summary>
 /// 获得拷贝
 /// </summary>
 /// <param name="src"></param>
 /// <param name="doc"></param>
 /// <returns></returns>
 public static MEPCurve GetCopy(this MEPCurve src, Document doc)
 {
     return(doc.GetElement(ElementTransformUtils.CopyElement(doc, src.Id, new XYZ(0, 0, 0)).First()) as MEPCurve);
 }