示例#1
0
        private static bool MyCreateGuizheng(ElementId gId, Document doc, IList <Curve> curs, ElementId leveId)
        {
            if (gId != null)
            {
                DateTime     oTimeStart          = DateTime.Now;
                FamilySymbol guiZhenFamilySymbol = doc.GetElement(gId) as FamilySymbol;
                Level        level        = doc.GetElement(leveId) as Level;
                int          numOfGuiZhen = 0;
                Transaction  tr           = new Transaction(doc); //创建对象必须添加事务
                tr.Start("轨枕");
                foreach (Curve c in curs)
                {
                    SubTransaction str = new SubTransaction(doc);
                    str.Start();
                    double l   = c.Length * 304.8;
                    int    n   = (int)Math.Floor(l / 650);
                    double ang = 0;
                    if (c is Line)
                    {
                        Line   line = c as Line;
                        double lAng = line.Direction.AngleTo(XYZ.BasisX);
                        ang = line.Direction.Y >= 0 ? lAng + Math.PI / 2 : Math.PI / 2 - lAng;
                        for (double i = 0.5; i < n; i += 1)
                        {
                            XYZ            pt         = c.Evaluate(i / n, true);
                            Transform      t          = c.ComputeDerivatives(i / n, true);
                            FamilyInstance gzInstance = doc.Create.NewFamilyInstance(pt, guiZhenFamilySymbol, level, StructuralType.NonStructural);
                            ElementTransformUtils.RotateElement(doc, gzInstance.Id, Line.CreateBound(pt, new XYZ(pt.X, pt.Y, pt.Z + 1)), ang);
                            numOfGuiZhen++;
                        }
                    }
                    else
                    {
                        for (double i = 0.5; i < n; i += 1)
                        {
                            Transform t    = c.ComputeDerivatives(i / n, true);
                            XYZ       pt   = t.Origin;
                            double    lAng = t.BasisY.AngleTo(new XYZ(1, 0, 0));
                            ang = t.BasisY.Y >= 0 ? lAng : -lAng;
                            FamilyInstance gzInstance = doc.Create.NewFamilyInstance(pt, guiZhenFamilySymbol, level,
                                                                                     StructuralType.NonStructural);
                            ElementTransformUtils.RotateElement(doc, gzInstance.Id,
                                                                Line.CreateBound(pt, new XYZ(pt.X, pt.Y, pt.Z + 1)), ang);
                            numOfGuiZhen++;
                        }
                    }

                    str.Commit();
                }

                tr.Commit();
                DateTime oTimeEnd = DateTime.Now;
                TimeSpan time     = oTimeEnd.Subtract(oTimeStart);
                TaskDialog.Show("轨枕创建成功", $"本次共创建了{numOfGuiZhen}根轨枕!" +
                                $"\n\t共耗时{time.Seconds}秒!");
                return(true);
            }
            else
            {
                TaskDialog.Show("ERR", "对象为空");
                return(false);
            }
        }
示例#2
0
        /// <summary>
        /// Update a piece of furniture.
        /// Return true if anything was changed.
        /// </summary>
        bool UpdateBimFurniture(
            DbFurniture f)
        {
            Document doc = _uiapp.ActiveUIDocument.Document;

            bool rc = false;

            if (!_roomUniqueIdDict.ContainsKey(f.RoomId))
            {
                Debug.Print("Furniture instance '{0}' '{1}'"
                            + " with UniqueId {2} belong to a room from"
                            + " a different model, so ignore it.",
                            f.Name, f.Description, f.Id);

                return(rc);
            }

            Element e = doc.GetElement(f.Id);

            if (null == e)
            {
                Util.ErrorMsg(string.Format(
                                  "Unable to retrieve element '{0}' '{1}' "
                                  + "with UniqueId {2}. Are you in the right "
                                  + "Revit model?", f.Name,
                                  f.Description, f.Id));

                return(rc);
            }

            if (!(e is FamilyInstance))
            {
                Debug.Print("Strange, we received an "
                            + "updated '{0}' '{1}' with UniqueId {2}, "
                            + "which we ignore.", f.Name,
                            f.Description, f.Id);

                return(rc);
            }

            // Convert SVG transform from string to int
            // to XYZ point and rotation in radians
            // including flipping of Y coordinates.

            string svgTransform = f.Transform;

            char[]   separators = new char[] { ',', 'R', 'T' };
            string[] a          = svgTransform.Substring(1).Split(separators);
            int[]    trxy       = a.Select <string, int>(s => int.Parse(s)).ToArray();

            double r = Util.ConvertDegreesToRadians(
                Util.SvgFlipY(trxy[0]));

            XYZ p = new XYZ(
                Util.ConvertMillimetresToFeet(trxy[1]),
                Util.ConvertMillimetresToFeet(Util.SvgFlipY(trxy[2])),
                0.0);

            // Check for modified transform

            LocationPoint lp = e.Location as LocationPoint;

            XYZ    translation = p - lp.Point;
            double rotation    = r - lp.Rotation;

            bool modifiedTransform = (0.01 < translation.GetLength()) ||
                                     (0.01 < Math.Abs(rotation));

            // Check for modified properties

            List <string> modifiedPropertyKeys = new List <string>();

            Dictionary <string, string> dbdict
                = f.Properties;

            Dictionary <string, string> eldict
                = Util.GetElementProperties(e);

            Debug.Assert(dbdict.Count == eldict.Count,
                         "expected equal dictionary length");

            string key_db; // JavaScript lowercases first char
            string val_db; // remove prepended "r " or "w "
            string val_el;

            foreach (string key in eldict.Keys)
            {
                Parameter pa = e.LookupParameter(key);

                Debug.Assert(null != pa, "expected valid parameter");

                if (Util.IsModifiable(pa))
                {
                    key_db = Util.Uncapitalise(key);

                    Debug.Assert(dbdict.ContainsKey(key_db),
                                 "expected same keys in Revit model and cloud database");

                    val_db = dbdict[key_db].Substring(2);

                    if (StorageType.String == pa.StorageType)
                    {
                        val_el = pa.AsString() ?? string.Empty;
                    }
                    else
                    {
                        Debug.Assert(StorageType.Integer == pa.StorageType,
                                     "expected only string and integer parameters");

                        val_el = pa.AsInteger().ToString();
                    }

                    if (!val_el.Equals(val_db))
                    {
                        modifiedPropertyKeys.Add(key);
                    }
                }
            }

            if (modifiedTransform || 0 < modifiedPropertyKeys.Count)
            {
                using (Transaction tx = new Transaction(
                           doc))
                {
                    tx.Start("Update Furniture and "
                             + "Equipmant Instance Placement");

                    if (.01 < translation.GetLength())
                    {
                        ElementTransformUtils.MoveElement(
                            doc, e.Id, translation);
                    }
                    if (.01 < Math.Abs(rotation))
                    {
                        Line axis = Line.CreateBound(lp.Point,
                                                     lp.Point + XYZ.BasisZ);

                        ElementTransformUtils.RotateElement(
                            doc, e.Id, axis, rotation);
                    }
                    foreach (string key in modifiedPropertyKeys)
                    {
                        Parameter pa = e.LookupParameter(key);

                        key_db = Util.Uncapitalise(key);
                        val_db = dbdict[key_db].Substring(2);

                        if (StorageType.String == pa.StorageType)
                        {
                            pa.Set(val_db);
                        }
                        else
                        {
                            try
                            {
                                int i = int.Parse(val_db);
                                pa.Set(i);
                            }
                            catch (System.FormatException)
                            {
                            }
                        }
                    }
                    tx.Commit();
                    rc = true;
                }
            }
            return(rc);
        }
示例#3
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static Duct ToRevitDuct(this oM.MEP.System.Duct duct, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null)
        {
            if (document == null)
            {
                return(null);
            }

            // Check valid duct object
            if (duct == null)
            {
                return(null);
            }

            // Construct Revit Duct
            Duct revitDuct = refObjects.GetValue <Duct>(document, duct.BHoM_Guid);

            if (revitDuct != null)
            {
                return(revitDuct);
            }

            // Settings
            settings = settings.DefaultIfNull();

            // Duct type
            DuctType ductType = duct.SectionProperty.ToRevitElementType(document, new List <BuiltInCategory> {
                BuiltInCategory.OST_DuctSystem
            }, settings, refObjects) as DuctType;

            if (ductType == null)
            {
                BH.Engine.Reflection.Compute.RecordError("No valid family has been found in the Revit model. Duct creation requires the presence of the default Duct Family Type.");
                return(null);
            }

            // End points
            XYZ start = duct.StartPoint.ToRevit();
            XYZ end   = duct.EndPoint.ToRevit();

            // Level
            Level level = document.LevelBelow(Math.Min(start.Z, end.Z), settings);

            if (level == null)
            {
                return(null);
            }

            // Default system used for now
            // TODO: in the future you could look for the existing connectors and check if any of them overlaps with start/end of this duct - if so, use it in Duct.Create.
            // hacky/heavy way of getting all connectors in the link below - however, i would rather filter the connecting elements out by type/bounding box first for performance reasons
            // https://thebuildingcoder.typepad.com/blog/2010/06/retrieve-mep-elements-and-connectors.html

            MechanicalSystemType mst = new FilteredElementCollector(document).OfClass(typeof(MechanicalSystemType)).OfType <MechanicalSystemType>().FirstOrDefault();

            if (mst == null)
            {
                BH.Engine.Reflection.Compute.RecordError("No valid MechanicalSystemType can be found in the Revit model. Creating a revit Duct requires a MechanicalSystemType.");
                return(null);
            }

            BH.Engine.Reflection.Compute.RecordWarning("Duct creation will utilise the first available MechanicalSystemType from the Revit model.");

            SectionProfile sectionProfile = duct.SectionProperty?.SectionProfile;

            if (sectionProfile == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Duct creation requires a valid SectionProfile.");
                return(null);
            }

            DuctSectionProperty ductSectionProperty = duct.SectionProperty;

            // Create Revit Duct
            revitDuct = Duct.Create(document, mst.Id, ductType.Id, level.Id, start, end);
            if (revitDuct == null)
            {
                BH.Engine.Reflection.Compute.RecordError("No Revit Duct has been created. Please check inputs prior to push attempt.");
                return(null);
            }

            // Copy parameters from BHoM object to Revit element
            revitDuct.CopyParameters(duct, settings);

            double orientationAngle = duct.OrientationAngle;

            if (Math.Abs(orientationAngle) > settings.AngleTolerance)
            {
                ElementTransformUtils.RotateElement(document, revitDuct.Id, Line.CreateBound(start, end), orientationAngle);
            }

            double flowRate = duct.FlowRate;

            revitDuct.SetParameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM, flowRate);

            double hydraulicDiameter = ductSectionProperty.HydraulicDiameter;

            revitDuct.SetParameter(BuiltInParameter.RBS_HYDRAULIC_DIAMETER_PARAM, hydraulicDiameter);

            DuctLiningType dlt = null;

            if (sectionProfile.LiningProfile != null)
            {
                // Get first available ductLiningType from document
                dlt = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Mechanical.DuctLiningType)).FirstOrDefault() as Autodesk.Revit.DB.Mechanical.DuctLiningType;
                if (dlt == null)
                {
                    BH.Engine.Reflection.Compute.RecordError("Any duct lining type needs to be present in the Revit model in order to push ducts with lining.\n" +
                                                             "Duct has been created but no lining has been applied.");
                }
            }

            DuctInsulationType dit = null;

            if (sectionProfile.InsulationProfile != null)
            {
                dit = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Mechanical.DuctInsulationType)).FirstOrDefault() as Autodesk.Revit.DB.Mechanical.DuctInsulationType;
                if (dit == null)
                {
                    BH.Engine.Reflection.Compute.RecordError("Any duct insulation type needs to be present in the Revit model in order to push ducts with lining.\n" +
                                                             "Duct has been created but no insulation has been applied.");
                }
            }

            // Rectangular Duct
            if (sectionProfile.ElementProfile is BoxProfile)
            {
                BoxProfile elementProfile = sectionProfile.ElementProfile as BoxProfile;

                // Set Height
                double profileHeight = elementProfile.Height;
                revitDuct.SetParameter(BuiltInParameter.RBS_CURVE_HEIGHT_PARAM, profileHeight);

                // Set Width
                double profileWidth = elementProfile.Width;
                revitDuct.SetParameter(BuiltInParameter.RBS_CURVE_WIDTH_PARAM, profileWidth);

                // Set LiningProfile
                if (dlt != null)
                {
                    BoxProfile liningProfile   = sectionProfile.LiningProfile as BoxProfile;
                    double     liningThickness = liningProfile.Thickness;
                    // Create ductLining
                    Autodesk.Revit.DB.Mechanical.DuctLining dl = Autodesk.Revit.DB.Mechanical.DuctLining.Create(document, revitDuct.Id, dlt.Id, liningThickness);
                }

                // Set InsulationProfile
                if (dit != null)
                {
                    BoxProfile insulationProfile   = sectionProfile.InsulationProfile as BoxProfile;
                    double     insulationThickness = insulationProfile.Thickness;
                    // Create ductInsulation
                    Autodesk.Revit.DB.Mechanical.DuctInsulation di = Autodesk.Revit.DB.Mechanical.DuctInsulation.Create(document, revitDuct.Id, dit.Id, insulationThickness);
                }

                // Set EquivalentDiameter
                double circularEquivalentDiameter = ductSectionProperty.CircularEquivalentDiameter;
                revitDuct.SetParameter(BuiltInParameter.RBS_EQ_DIAMETER_PARAM, circularEquivalentDiameter);
            }
            else if (sectionProfile.ElementProfile is TubeProfile)
            {
                TubeProfile elementProfile = sectionProfile.ElementProfile as TubeProfile;

                double diameter = elementProfile.Diameter;
                revitDuct.SetParameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM, diameter);

                // Set LiningProfile
                if (dlt != null)
                {
                    TubeProfile liningProfile   = sectionProfile.LiningProfile as TubeProfile;
                    double      liningThickness = liningProfile.Thickness;
                    //Create ductLining
                    Autodesk.Revit.DB.Mechanical.DuctLining dl = Autodesk.Revit.DB.Mechanical.DuctLining.Create(document, revitDuct.Id, dlt.Id, liningThickness);
                }

                // Set InsulationProfile
                if (dit != null)
                {
                    TubeProfile insulationProfile   = sectionProfile.InsulationProfile as TubeProfile;
                    double      insulationThickness = insulationProfile.Thickness;
                    // Create ductInsulation
                    Autodesk.Revit.DB.Mechanical.DuctInsulation di = Autodesk.Revit.DB.Mechanical.DuctInsulation.Create(document, revitDuct.Id, dit.Id, insulationThickness);
                }
            }

            refObjects.AddOrReplace(duct, revitDuct);
            return(revitDuct);
        }
        //method to align created element
        public static bool AdjustElement(Document m_document, Element createdInstance,
                                         XYZ instancePoint, Pipe pipeElement, double rodLength, Curve pipeCurve)
        {
            bool rod = false, radius = false;

            try
            {
                if (pipeCurve is Line)
                {
                    Line pipeLine = (Line)pipeCurve;

                    //axis to find the y angle
                    Line yAngleAxis = Line.CreateBound(pipeLine.GetEndPoint(0), new XYZ(pipeLine.GetEndPoint(1).X, pipeLine.GetEndPoint(1).Y, pipeLine.GetEndPoint(0).Z));

                    double yAngle = XYZ.BasisY.AngleTo(yAngleAxis.Direction);

                    //axis of rotation
                    Line axis = Line.CreateBound(instancePoint, new XYZ(instancePoint.X, instancePoint.Y, instancePoint.Z + 10));

                    if (pipeCurve.GetEndPoint(0).Y > pipeCurve.GetEndPoint(1).Y)
                    {
                        if (pipeCurve.GetEndPoint(0).X > pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, Math.PI + yAngle);
                        }
                        else if (pipeCurve.GetEndPoint(0).X < pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, 2 * Math.PI - yAngle);
                        }
                    }
                    else if (pipeCurve.GetEndPoint(0).Y < pipeCurve.GetEndPoint(1).Y)
                    {
                        if (pipeCurve.GetEndPoint(0).X > pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, Math.PI + yAngle);
                        }
                        else if (pipeCurve.GetEndPoint(0).X < pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, 2 * Math.PI - yAngle);
                        }
                    }
                    else
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, yAngle);
                    }

                    ParameterSet parameters = createdInstance.Parameters;

                    //set the Nominal radius and Rod height parameters
                    foreach (Parameter para in parameters)
                    {
                        if (para.Definition.Name == "PIPE RADIUS")
                        {
                            para.Set(pipeElement.get_Parameter("Outside Diameter").AsDouble() / 2.0);
                            radius = true;
                        }
                        else if (para.Definition.Name == "ROD LENGTH")
                        {
                            para.Set(rodLength);
                            rod = true;
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (rod == true && radius == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#5
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();
                }
            }
        }
示例#6
0
        /***************************************************/

        public static bool SetLocation(this FamilyInstance element, IInstance instance, RevitSettings settings)
        {
            if (instance.Location == null)
            {
                return(false);
            }

            bool success = false;

            if (instance.Location is BH.oM.Geometry.Point)
            {
                LocationPoint location = element.Location as LocationPoint;
                if (location == null)
                {
                    return(false);
                }

                XYZ newLocation = ((BH.oM.Geometry.Point)instance.Location).ToRevit();

                if (location.Point.DistanceTo(newLocation) > settings.DistanceTolerance)
                {
                    if (element.Host != null)
                    {
                        if (element.HostFace == null)
                        {
                            List <Solid> hostSolids = element.Host.Solids(new Options());
                            if (hostSolids != null && hostSolids.All(x => !newLocation.IsInside(x, settings.DistanceTolerance)))
                            {
                                BH.Engine.Reflection.Compute.RecordWarning($"The new location point used to update the location of a family instance was outside of the host solid, the point has been snapped to the host. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                            }
                        }
                        else
                        {
                            if (element.Host is ReferencePlane)
                            {
                                Autodesk.Revit.DB.Plane p = ((ReferencePlane)element.Host).GetPlane();
                                if (p.Origin.DistanceTo(newLocation) > settings.DistanceTolerance && Math.Abs((p.Origin - newLocation).Normalize().DotProduct(p.Normal)) > settings.AngleTolerance)
                                {
                                    BH.Engine.Reflection.Compute.RecordError($"Location update failed: the new location point used on update of a family instance does not lie in plane with its reference plane. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                                    return(false);
                                }
                            }
                            else
                            {
                                Autodesk.Revit.DB.Face face = element.Host.GetGeometryObjectFromReference(element.HostFace) as Autodesk.Revit.DB.Face;

                                XYZ       toProject         = newLocation;
                                Transform instanceTransform = null;
                                if (element.Host is FamilyInstance && !((FamilyInstance)element.Host).HasModifiedGeometry())
                                {
                                    instanceTransform = ((FamilyInstance)element.Host).GetTotalTransform();
                                    toProject         = (instanceTransform.Inverse.OfPoint(newLocation));
                                }

                                IntersectionResult ir = face?.Project(toProject);
                                if (ir == null)
                                {
                                    BH.Engine.Reflection.Compute.RecordError($"Location update failed: the new location point used on update of a family instance could not be placed on its host face. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                                    return(false);
                                }

                                newLocation = ir.XYZPoint;
                                if (instanceTransform != null)
                                {
                                    newLocation = (instanceTransform.OfPoint(newLocation));
                                }

                                if (ir.Distance > settings.DistanceTolerance)
                                {
                                    BH.Engine.Reflection.Compute.RecordWarning($"The location point used on update of a family instance has been snapped to its host face. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                                }
                            }
                        }
                    }

                    location.Point = newLocation;
                    success        = true;
                }

                if (instance.Orientation?.X != null)
                {
                    Transform transform = element.GetTotalTransform();
                    XYZ       newX      = instance.Orientation.X.ToRevit().Normalize();
                    if (1 - Math.Abs(transform.BasisX.DotProduct(newX)) > settings.AngleTolerance)
                    {
                        XYZ          revitNormal;
                        XYZ          bHoMNormal;
                        FamilySymbol fs = element.Document.GetElement(element.GetTypeId()) as FamilySymbol;
                        if (fs != null && fs.Family.FamilyPlacementType == FamilyPlacementType.OneLevelBasedHosted)
                        {
                            revitNormal = transform.BasisY;
                            bHoMNormal  = instance.Orientation.Y.ToRevit().Normalize();
                        }
                        else
                        {
                            revitNormal = transform.BasisZ;
                            bHoMNormal  = instance.Orientation.Z.ToRevit().Normalize();
                        }

                        if (1 - Math.Abs(revitNormal.DotProduct(bHoMNormal)) > settings.AngleTolerance)
                        {
                            BH.Engine.Reflection.Compute.RecordWarning($"The orientation applied to the family instance on update has different normal than the original one. Only in-plane rotation has been applied, the orientation out of plane has been ignored. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                        }

                        double angle = transform.BasisX.AngleOnPlaneTo(newX, revitNormal);
                        if (Math.Abs(angle) > settings.AngleTolerance)
                        {
                            ElementTransformUtils.RotateElement(element.Document, element.Id, Autodesk.Revit.DB.Line.CreateBound(newLocation, newLocation + transform.BasisZ), angle);
                            success = true;
                        }
                    }
                }
            }
            else if (instance.Location is ICurve && element.Host != null)
            {
                LocationCurve       location = element.Location as LocationCurve;
                BH.oM.Geometry.Line l        = instance.Location as BH.oM.Geometry.Line;
                if (location == null || l == null)
                {
                    return(false);
                }

                XYZ       start             = l.Start.ToRevit();
                XYZ       end               = l.End.ToRevit();
                Transform instanceTransform = null;
                if (element.Host is FamilyInstance && !((FamilyInstance)element.Host).HasModifiedGeometry())
                {
                    instanceTransform = ((FamilyInstance)element.Host).GetTotalTransform();
                    start             = (instanceTransform.Inverse.OfPoint(start));
                    end = (instanceTransform.Inverse.OfPoint(end));
                }

                Autodesk.Revit.DB.Face face = element.Host.GetGeometryObjectFromReference(element.HostFace) as Autodesk.Revit.DB.Face;
                IntersectionResult     ir1  = face?.Project(start);
                IntersectionResult     ir2  = face?.Project(end);
                if (ir1 == null || ir2 == null)
                {
                    BH.Engine.Reflection.Compute.RecordError($"Location update failed: the new location line used on update of a family instance could not be placed on its host face. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                    return(false);
                }

                if (ir1.Distance > settings.DistanceTolerance || ir2.Distance > settings.DistanceTolerance)
                {
                    BH.Engine.Reflection.Compute.RecordWarning($"The location line used on update of a family instance has been snapped to its host face. BHoM_Guid: {instance.BHoM_Guid} ElementId: {element.Id.IntegerValue}");
                }

                start = ir1.XYZPoint;
                end   = ir2.XYZPoint;
                if (instanceTransform != null)
                {
                    start = instanceTransform.OfPoint(start);
                    end   = instanceTransform.OfPoint(end);
                }

                Autodesk.Revit.DB.Line newLocation = Autodesk.Revit.DB.Line.CreateBound(start, end);
                if (!newLocation.IsSimilar(location.Curve, settings))
                {
                    location.Curve = newLocation;
                    success        = true;
                }
            }
            else
            {
                success = SetLocation(element, instance.Location as dynamic, settings);
            }

            return(success);
        }
示例#7
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //【1】获取当前文档
            Document doc = commandData.Application.ActiveUIDocument.Document;

            //【2】获取族类型
            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();

            //【3】获取标高
            //通过链式编程,一句话搞定
            Level level = new FilteredElementCollector(doc).OfClass(typeof(Level)).FirstOrDefault(x => x.Name == "标高 1") as Level;

            //【4】创建放置点

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

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



            //无连接高度 英尺进入 然后15/0.3048,变为实际的米4.572
            double height = 15 / 0.3048;
            double offset = 0;

            //【5】创建事务
            List <FamilyInstance> familyInstances = new List <FamilyInstance>();
            Transaction           trans           = new Transaction(doc, "创建柱子");

            foreach (XYZ item in xyzList)
            {
                trans.Start();
                FamilyInstance column = doc.Create.NewFamilyInstance(item, columnType, level, StructuralType.NonStructural);
                trans.Commit();
                //刷新界面,出现动态效果
                //System.Windows.Forms.Application.DoEvents();
                ////如果想控制时间,可以使用线程来控制
                //Thread.Sleep(100);
                familyInstances.Add(column);
            }

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

            for (int k = 0; k < 100; k++)
            {
                transRotate.Start();
                for (int i = 0; i < xyzList.Count; i++)
                {
                    Line line = Line.CreateBound(xyzList[i], new XYZ(xyzList[i].X, xyzList[i].Y, 10));
                    ElementTransformUtils.RotateElement(doc, familyInstances[i].Id, line, Math.PI / 6.0);
                }
                transRotate.Commit();

                System.Windows.Forms.Application.DoEvents();
            }



            return(Result.Succeeded);
        }
示例#8
0
        //*****************************RejustSectionView()*****************************
        public void RejustSectionView(Document doc, UIDocument uidoc)
        {
            //My library
            LibraryGetItems lib    = new LibraryGetItems();
            LibraryGeometry libGeo = new LibraryGeometry();
            // Select wall or object.
            Element wallElement = lib.SelectElement(uidoc, doc);

            // collect all ViewSections
            FilteredElementCollector SectionCollector = new FilteredElementCollector(doc);

            SectionCollector.OfClass(typeof(ViewSection)).WhereElementIsNotElementType();
            List <ViewSection> sections = SectionCollector.Cast <ViewSection>().Where(sh => sh.ViewType == ViewType.Section).ToList();
            // Select section from active view.
            Element sectionelem = lib.SelectElement(uidoc, doc);
            // Compare element by name to find the SectionView.
            ViewSection section = sections.Find(t => t.ViewName == sectionelem.Name);

            // OFFSET
            // element to wall.
            Wall          wall          = wallElement as Wall;
            LocationCurve locationCurve = wall.Location as LocationCurve;
            // Move the section element
            Line  origWallLine   = locationCurve.Curve as Line;
            Curve offsetWallLine = origWallLine.CreateOffset(3, XYZ.BasisZ);
            // Midpoint of the offset wall line.
            XYZ offsetWallMid = libGeo.Midpoint(offsetWallLine as Line);
            // selected section orign point.
            XYZ sectionOrigin = new XYZ(section.Origin.X, section.Origin.Y, 0);
            // Move distance between selected and offset.
            XYZ transaction = offsetWallMid - sectionOrigin;

            //ANGLE
            XYZ s       = origWallLine.GetEndPoint(0);
            XYZ e       = origWallLine.GetEndPoint(1);
            XYZ v       = e - s;
            int compare = libGeo.Compare(s, e);

            if (e.X > s.X && compare < 1)
            {
                if (e.Y < s.Y)
                {
                    v = s - e;

                    offsetWallLine = origWallLine.CreateOffset(-3, XYZ.BasisZ);
                    // Midpoint of the offset wall line.
                    offsetWallMid = libGeo.Midpoint(offsetWallLine as Line);
                    // selected section orign point.
                    sectionOrigin = new XYZ(section.Origin.X, section.Origin.Y, 0);
                    // Move distance between selected and offset.
                    transaction = offsetWallMid - sectionOrigin;
                }
            }

            if (e.Y < s.Y && compare == 1)
            {
                if (e.X < s.X)
                {
                    v = s - e;

                    offsetWallLine = origWallLine.CreateOffset(-3, XYZ.BasisZ);
                    // Midpoint of the offset wall line.
                    offsetWallMid = libGeo.Midpoint(offsetWallLine as Line);
                    // selected section orign point.
                    sectionOrigin = new XYZ(section.Origin.X, section.Origin.Y, 0);
                    // Move distance between selected and offset.
                    transaction = offsetWallMid - sectionOrigin;
                }
            }

            double radians = XYZ.BasisX.AngleTo(v);     // Angle is using radians.
            double Angle   = radians * (180 / Math.PI); // Convert Radians to degrees.

            // ROTATE SECTION FIRST
            using (Transaction tr = new Transaction(doc, "Rotate"))
            {
                tr.Start("rotate");
                try
                {
                    if (Angle > 0)
                    {
                        Line axis = Line.CreateBound(sectionOrigin, sectionOrigin + XYZ.BasisZ);
                        doc.Regenerate(); // Document regenerate to refresh document.
                        ElementTransformUtils.RotateElement(doc, sectionelem.Id, axis, radians);
                    }
                }
                catch { }
                tr.Commit();
            }

            // MOVE SECTION
            using (Transaction t = new Transaction(doc, "Update Section"))
            {
                t.Start("Update Section");
                try
                {
                    ElementTransformUtils.MoveElement(doc, sectionelem.Id, transaction);
                }
                catch { }
                t.Commit();
            }
        }
示例#9
0
        private void Setsymbol(Document doc, Dimension ele1, Dimension ele2, string family, string type, string family1, string type1, Plane plane)
        {
            Line curve1 = ele1.Curve as Line;

            curve1.MakeBound(0, 1);
            Line line1  = Support.ProjectLineOnPlane(plane, curve1);
            Line curve2 = ele2.Curve as Line;

            curve2.MakeBound(0, 1);
            Line         line2   = Support.ProjectLineOnPlane(plane, curve2);
            FamilySymbol symbol  = Support.GetSymbol(doc, family, type);
            FamilySymbol symbol1 = Support.GetSymbol(doc, family1, type1);

            //SUPPORT.PARAMETER.PARAMETER para = new SUPPORT.PARAMETER.PARAMETER();

            if (ele1.Id != ele2.Id)
            {
                //giao diem:
                XYZ giaodiem = Support.ExtendLineIntersection(line1, line2);

                ////Getendpoint:
                List <XYZ> listendpoint1  = Support.GetStartEndDimensio(ele1);
                List <XYZ> listendpoint2  = Support.GetStartEndDimensio(ele2);
                List <XYZ> TwoPointEndDim = Support.GetDimensionPointsEnd(doc, ele1);

                XYZ test1 = TwoPointEndDim[0];
                test1 = Support.ProjectOnto(plane, test1);
                XYZ test2 = TwoPointEndDim[1];
                test2 = Support.ProjectOnto(plane, test2);
                XYZ tp = new XYZ(2, 0, 0);

                Plane plane1 = Plane.CreateByNormalAndOrigin(line1.Direction.Normalize(), test2 - tp);
                #region Create line:
                var min1   = double.MaxValue;
                XYZ Point1 = XYZ.Zero;
                XYZ Point2 = XYZ.Zero;

                foreach (var point in listendpoint1)
                {
                    var distance = giaodiem.DistanceTo(point);
                    if (distance < min1)
                    {
                        Point1 = point;
                        min1   = distance;
                    }
                }
                var min2 = double.MaxValue;
                foreach (var point in listendpoint2)
                {
                    var distance = giaodiem.DistanceTo(point);
                    if (distance < min2)
                    {
                        Point2 = point;
                        min2   = distance;
                    }
                }
                Point1 = Support.ProjectOnto(plane, Point1);
                Point2 = Support.ProjectOnto(plane, Point2);

                XYZ ep21  = Support.ProjectOnto(plane, listendpoint2[0]);
                XYZ ep222 = Support.ProjectOnto(plane, listendpoint2[1]);

                DetailCurve cur1 = Support.createdetailcurve(doc, Point1, giaodiem, plane);
                DetailCurve cur3 = Support.createdetailcurve(doc, Point2, giaodiem, plane);
                #endregion

                #region : Create text
                List <Element> list1 = new List <Element>();
                List <Element> list2 = new List <Element>();

                for (int aa = 1; aa < ele1.Segments.Size; aa++)
                {
                    Reference ref1     = ele1.References.get_Item(aa);
                    Element   element1 = doc.GetElement(ref1);
                    if (element1.Name != null && element1.Category.Name == "Specialty Equipment")
                    {
                        list1.Add(element1);
                    }
                }

                for (int bb = 1; bb < ele2.Segments.Size; bb++)
                {
                    Reference ref2     = ele2.References.get_Item(bb);
                    Element   element2 = doc.GetElement(ref2);
                    if (element2.Name != null && element2.Category.Name == "Specialty Equipment")
                    {
                        list2.Add(element2);
                    }
                }

                XYZ             kc  = new XYZ(0, 0, 0);
                XYZ             pos = new XYZ(0, 0, 0);
                ElementId       defaultTextTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                TextNoteOptions opts = new TextNoteOptions(defaultTextTypeId);
                opts.HorizontalAlignment = HorizontalTextAlignment.Left;
                string s1 = list1.First().Name;

                #region : Create location
                FilteredElementCollector filter  = new FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_MultiCategoryTags);
                List <Element>           listtag = filter.OfCategory(BuiltInCategory.OST_MultiCategoryTags).WhereElementIsNotElementType().ToElements().ToList();
                List <Element>           sametag = new List <Element>();

                foreach (var item in listtag)
                {
                    IndependentTag el   = doc.GetElement(item.Id) as IndependentTag;
                    Element        tag1 = el.GetTaggedLocalElement();
                    string         tag  = tag1.Name;
                    if (tag == list1.First().Name)
                    {
                        sametag.Add(item);
                    }
                }

                string lastname = "";
                if (sametag.Count > 0)
                {
                    Element elem1     = doc.GetElement(sametag.First().Id) as Element;
                    string  samename  = elem1.Name;
                    int     gachngang = samename.LastIndexOf("-");
                    lastname = samename.Substring(gachngang + 1);
                    string s11 = s1 + "\n" + "(" + lastname + ")";
                }
                if (sametag.Count == 0)
                {
                    lastname = " ";
                }

                #endregion

                if (giaodiem.DistanceTo(test1) < giaodiem.DistanceTo(test2))
                {
                    FamilyInstance newinstance = null;;
                    XYZ            kt          = new XYZ(0, 0, 0);
                    if (line1.Direction.DotProduct(XYZ.BasisX) == -1)
                    {
                        kt = new XYZ(-3.3, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) == 1)
                    {
                        kt = new XYZ(3.3, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == -1)
                    {
                        kt = new XYZ(0, 0, -3.3);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == 1)
                    {
                        kt = new XYZ(0, 0, 3.3);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == 1)
                    {
                        kt = new XYZ(0, 4, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == -1)
                    {
                        kt = new XYZ(0, -4, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisY) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1)
                    {
                        kt = new XYZ(0, 0, 0);
                    }
                    newinstance = doc.Create.NewFamilyInstance(test1 - kt, symbol, doc.ActiveView);
                    #region : Create symbol
                    newinstance.LookupParameter("Part No.").Set(s1);
                    newinstance.LookupParameter("TEXT 3").Set("CL" + " (" + list1.Count * list2.Count + ")");
                    newinstance.LookupParameter("TEXT 2").Set(lastname);
                    #endregion
                }

                else
                {
                    FamilyInstance newinstance = null;
                    #region : Create symbol
                    if (line1.Direction.DotProduct(XYZ.BasisX) == -1)
                    {
                        XYZ kt = new XYZ(0.7, 0, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) == 1)
                    {
                        XYZ kt = new XYZ(0, 0, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == 1)
                    {
                        XYZ kt = new XYZ(0, 0, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == 1)
                    {
                        XYZ kt = new XYZ(0, 3.2, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == -1)
                    {
                        XYZ kt = new XYZ(0, 0, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisY) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1)
                    {
                        XYZ kt = new XYZ(0, 0, 0);
                        newinstance = doc.Create.NewFamilyInstance(test2 - kt, symbol, doc.ActiveView);
                    }

                    ICollection <ElementId> result    = new List <ElementId>();
                    ICollection <ElementId> newresult = new List <ElementId>();
                    result.Add(newinstance.Id);
                    ElementTransformUtils.RotateElement(doc, newinstance.Id, line2, Math.PI * 0.5);
                    newresult = ElementTransformUtils.MirrorElements(doc, result, plane1, true);
                    doc.Delete(newinstance.Id);
                    FamilyInstance famiin = doc.GetElement(newresult.First()) as FamilyInstance;
                    famiin.LookupParameter("Part No.").Set(s1);
                    famiin.LookupParameter("TEXT 3").Set("CL" + " (" + list1.Count * list2.Count + ")");
                    famiin.LookupParameter("TEXT 2").Set(lastname);
                    #endregion
                }
                #endregion
            }

            else
            {
                List <XYZ> listendpoint1 = Support.GetStartEndDimensio(ele1);

                List <XYZ> TwoPointEndDim = Support.GetDimensionPointsEnd(doc, ele1);

                XYZ test1 = TwoPointEndDim[0];
                test1 = Support.ProjectOnto(plane, test1);
                XYZ test2 = TwoPointEndDim[1];
                test2 = Support.ProjectOnto(plane, test2);
                XYZ Point2 = XYZ.Zero;
                #region
                //if (line1.Direction.DotProduct(XYZ.BasisY) == -1)
                //{
                //    Point2 = test1 + kc1;
                //    Point2 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point2);
                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test1, Point2, plane);
                //}

                //if (Math.Round(line1.Direction.DotProduct(XYZ.BasisY), 2) == 1)
                //{
                //    Point2 = test1 + kc11;
                //    Point2 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point2);

                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test1, Point2, plane);
                //}

                //if (line1.Direction.DotProduct(XYZ.BasisZ) == 1)
                //{
                //    Point2 = test2 + kc2;
                //    Point2 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point2);
                //    test1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, test1);
                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test2, Point2, plane);
                //}

                //if (line1.Direction.DotProduct(XYZ.BasisZ) == -1)
                //{
                //    Point2 = test1 + kc22;
                //    Point2 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point2);
                //    test1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, test1);
                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test1, Point2, plane);
                //}

                //if (line1.Direction.DotProduct(XYZ.BasisX) == 1)
                //{
                //    Point1 = test2 - kc23;
                //    Point1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point1);
                //    test1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, test1);
                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test2, Point1, plane);
                //}

                //if (line1.Direction.DotProduct(XYZ.BasisX) == -1)
                //{
                //    Point1 = test1 + kc23;
                //    Point1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, Point1);
                //    test1 = SUPPORT.PLANE.PlaneHelper.ProjectOnto(plane, test1);
                //    DetailCurve cur1 = SUPPORT.LINE.LINE.createdetailcurve(doc, test1, Point1, plane);
                //}
                ////if (line1.Direction.DotProduct(XYZ.BasisX) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisY) != -1 && line1.Direction.DotProduct(XYZ.BasisY) != 1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1 && line1.Direction.DotProduct(XYZ.BasisZ) != 1)
                ////{
                ////    CreateExtenline(doc, plane, ele1, 3.5);
                ////}

                //foreach (var point in listendpoint1)
                //{
                //    var distance = kc1.DistanceTo(point);
                //    if (distance < min1)
                //    {
                //        Point1 = point;
                //        min1 = distance;
                //    }
                //}
                #endregion

                #region : Create text
                List <Element> list1 = new List <Element>();

                for (int aa = 1; aa < ele1.Segments.Size; aa++)
                {
                    Reference ref1     = ele1.References.get_Item(aa);
                    Element   element1 = doc.GetElement(ref1);
                    if (element1.Name != null && element1.Category.Name == "Specialty Equipment")
                    {
                        list1.Add(element1);
                    }
                }

                //XYZ pos = null;
                ElementId       defaultTextTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                TextNoteOptions opts = new TextNoteOptions(defaultTextTypeId);
                string          s1   = list1.First().Name;

                XYZ    vector = test1 - test2;
                Double x      = vector.DotProduct(XYZ.BasisX);
                Double y      = vector.DotProduct(XYZ.BasisY);
                Double z      = vector.DotProduct(XYZ.BasisZ);

                FamilyInstance newinstance = null;

                if (Support.IsHorizontal(vector, doc.ActiveView) == true)
                {
                    XYZ kt = new XYZ(0, 0, 0);
                    if (line1.Direction.DotProduct(XYZ.BasisX) == -1)
                    {
                        kt = new XYZ(-3.2, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) == 1)
                    {
                        kt = new XYZ(3.2, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == -1)
                    {
                        kt = new XYZ(0, 0, -3.2);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == 1)
                    {
                        kt = new XYZ(0, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == 1)
                    {
                        kt = new XYZ(0, 3.2, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == -1)
                    {
                        kt = new XYZ(0, (3.2 + Support.Totaldim(ele1)), 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisY) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1)
                    {
                        kt = new XYZ(0, (3.2 + Support.Totaldim(ele1)), 0);
                    }
                    newinstance = doc.Create.NewFamilyInstance(test1, symbol, doc.ActiveView);
                }

                if (Support.IsVertical(vector, doc.ActiveView) == true)
                {
                    XYZ kt = new XYZ(0, 0, 0);
                    if (line1.Direction.DotProduct(XYZ.BasisX) == 1)
                    {
                        kt = new XYZ(-(Support.Totaldim(ele1) + 3.2), 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) == -1)
                    {
                        kt = new XYZ(-3.2, 0, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == 1)
                    {
                        kt = new XYZ(0, 0, -(Support.Totaldim(ele1) + 3.2));
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisZ) == -1)
                    {
                        kt = new XYZ(0, 0, -3.2);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == -1)
                    {
                        kt = new XYZ(0, 3.2, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisY) == 1)
                    {
                        kt = new XYZ(0, 3.2, 0);
                    }
                    if (line1.Direction.DotProduct(XYZ.BasisX) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisY) != -1 && line1.Direction.DotProduct(XYZ.BasisX) != 1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1 && line1.Direction.DotProduct(XYZ.BasisZ) != -1)
                    {
                        kt = new XYZ(0, 0, 0);
                    }
                    newinstance = doc.Create.NewFamilyInstance(test1, symbol1, doc.ActiveView);
                }

                if (Support.IsHorizontal(vector, doc.ActiveView) == false && Support.IsVertical(vector, doc.ActiveView) == false)
                {
                    newinstance = doc.Create.NewFamilyInstance(test1, symbol, doc.ActiveView);
                }
                #endregion
                #region : Create location
                FilteredElementCollector filter  = new FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_MultiCategoryTags);
                List <Element>           listtag = filter.OfCategory(BuiltInCategory.OST_MultiCategoryTags).WhereElementIsNotElementType().ToElements().ToList();
                List <Element>           sametag = new List <Element>();
                foreach (var item in listtag)
                {
                    IndependentTag el   = doc.GetElement(item.Id) as IndependentTag;
                    Element        tag1 = el.GetTaggedLocalElement();
                    string         tag  = tag1.Name;

                    if (tag == list1.First().Name)
                    {
                        sametag.Add(item);
                    }
                }
                try
                {
                    if (sametag.Count > 0)
                    {
                        Element elem1     = doc.GetElement(sametag.First().Id) as Element;
                        string  samename  = elem1.Name;
                        int     gachngang = samename.LastIndexOf("-");
                        string  lastname  = samename.Substring(gachngang + 1);
                        string  s11       = s1 + "\n" + "(" + lastname + ")";
                        #region : Create symbol
                        newinstance.LookupParameter("Part No.").Set(s1);
                        newinstance.LookupParameter("TEXT 3").Set("CL" + " (" + list1.Count + ")");
                        newinstance.LookupParameter("TEXT 2").Set(lastname);
                        #endregion
                    }
                    else
                    {
                        newinstance.LookupParameter("Part No.").Set(s1);
                        newinstance.LookupParameter("TEXT 3").Set("CL" + " (" + list1.Count + ")");
                        newinstance.LookupParameter("TEXT 2").Set(" ");
                    }
                }
                catch { };

                #endregion
            }
        }
示例#10
0
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        //Get process ids before running the excel codes
        CheckExcelProcesses();

        //Get application and document objects
        UIApplication uiApp = commandData.Application;
        UIDocument    uidoc = uiApp.ActiveUIDocument;
        Document      doc   = uidoc.Document;
        Application   app   = uiApp.Application;


        /////////////////////AXE POLYLINE FROM AUTOCAD
        ////SELECTION
        Selection sel = uidoc.Selection;
        Reference r   = sel.PickObject(ObjectType.Element, "Please pick an element");

        Element e = uidoc.Document.GetElement(r.ElementId);

        int polylineCounter = 0;

        ////GET GEOMETRY
        PolyLine axe = null;

        GeometryElement geoElement = e.get_Geometry(new Options());

        foreach (GeometryObject geoObject in geoElement)
        {
            GeometryInstance instance = geoObject as GeometryInstance;

            if (null != instance)
            {
                foreach (GeometryObject instObj in instance.SymbolGeometry)
                {
                    if (instObj is PolyLine)
                    {
                        ++polylineCounter;
                        axe = instObj as PolyLine;
                    }
                }
            }
        }

        ////ERRORS
        if (polylineCounter > 1)
        {
            // More than one axe
            TaskDialog.Show("Revit", "More than one alignment");
            return(Result.Failed);
        }

        ////UI
        ObjectsInsertion.BIOC formui = new ObjectsInsertion.BIOC();
        WinForms.Application.Run(formui);

        //Inputs
        string Excel_filename     = formui.Excel_filename;
        bool   Excel_fail         = formui.Excel_fail;
        int    colonne_PK         = ExcelColumnNameToNumber(formui.colonne_PK);
        int    colonne_Family     = ExcelColumnNameToNumber(formui.colonne_Family);
        bool   AsParameters       = formui.AsParameters;
        int    colonne_Parametres = 0;

        if (AsParameters)
        {
            colonne_Parametres = ExcelColumnNameToNumber(formui.colonne_Parametres);
        }

        bool vertical = formui.vertical;
        bool buttonOK = formui.buttonOK;

        //ERREURS
        if (Excel_fail)
        {
            return(Result.Failed);
        }

        //QUITTER
        if (buttonOK == false)
        {
            return(Result.Cancelled);
        }

        /////////////////OBJECTS CREATION
        if (axe != null)
        {
            //Excel infos
            X.Application excel = formui.excel;
            if (null == excel)
            {
                return(Result.Failed);
            }
            excel.Visible = false;
            X.Workbook  workbook  = formui.workbook;
            X.Worksheet worksheet = formui.worksheet;

            //Polylines Points
            IList <XYZ> list_pts = axe.GetCoordinates();

            //Number of PK
            int nb_pk = 0;
            while ((worksheet.Cells[nb_pk + 2, colonne_PK] as X.Range).Value != null)
            {
                nb_pk++;
            }

            //Number of Parameters
            int nb_params = 0;
            if (AsParameters)
            {
                while ((worksheet.Cells[1, colonne_Parametres + nb_params] as X.Range).Value != null)
                {
                    nb_params++;
                }
            }


            for (int i = 2; i < nb_pk + 2; i++)
            {
                ////Point on Polyline
                double PK       = Convert.ToDouble((worksheet.Cells[i, colonne_PK] as X.Range).Value2) / 0.3048;
                XYZ    location = point_PKsurPolyLines(PK, list_pts);

                ////FIND FAMILY
                string family_input = (worksheet.Cells[i, colonne_Family] as X.Range).Value;

                string familyName = "";
                string symbolName = "";

                //Search for Symbol type (.i.e type name in the family)
                //Bracket will contain the symbol name in the Excel file
                if (family_input.Contains("(") && family_input.Contains(")"))
                {
                    string   str     = family_input.Replace(" ", "").Replace(")", "");
                    string[] cut_str = str.Split('(');
                    familyName = cut_str[0];
                    symbolName = cut_str[1];
                }
                else
                {
                    familyName = family_input.Replace(" ", "");
                }

                Family       family = null;
                FamilySymbol symbol = null;

                //Filter Elment Collector
                FilteredElementCollector FamiliesCollector = new FilteredElementCollector(doc);
                FamiliesCollector.OfClass(typeof(Family));

                var families = from m_family in FamiliesCollector
                               where m_family.Name.ToLower() == familyName.ToLower()
                               select m_family;
                family = families.Cast <Family>().FirstOrDefault <Family>();

                //If the family is not found in the document
                if (family == null)
                {
                    WinForms.MessageBox.Show("The family " + familyName + " have not been found in the working document !");
                    workbook.Close(0);
                    excel.Quit();
                    KillExcel();
                    return(Result.Cancelled);
                }


                //choose the familysymbol
                if (symbolName != "")
                {
                    //Symbol requested by the user
                    foreach (ElementId id in family.GetFamilySymbolIds())
                    {
                        FamilySymbol tmp_symbol = doc.GetElement(id) as FamilySymbol;
                        if (tmp_symbol.Name == symbolName)
                        {
                            symbol = tmp_symbol;
                            break;
                        }
                    }
                }
                else
                {
                    //No symbol requested by the user so pick the first one
                    foreach (ElementId id in family.GetFamilySymbolIds())
                    {
                        symbol = doc.GetElement(id) as FamilySymbol;
                        break;
                    }
                }

                //Check if the symbol have been found
                if (symbol == null)
                {
                    WinForms.MessageBox.Show("The symbol (.i.e. family type) " + symbolName + " have not been found in the family " + familyName);
                    workbook.Close(0);
                    excel.Quit();
                    KillExcel();
                    return(Result.Cancelled);
                }

                ////OBJECTS CREATION AND ROTATION
                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("start");

                    //Activate the symbol
                    if (!symbol.IsActive)
                    {
                        symbol.Activate(); doc.Regenerate();
                    }

                    //place the familyinstance
                    Element elt_create = doc.Create.NewFamilyInstance(location, symbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                    //Plan rotation
                    double plan_rotation  = angleplan_anglevert(PK, list_pts)[0];
                    XYZ    axis_plan      = Axis_angleplan_anglevert(PK, list_pts)[0];
                    XYZ    deb_plan       = location;
                    XYZ    fin_plan       = deb_plan + axis_plan;
                    Line   axis_plan_line = Line.CreateBound(deb_plan, fin_plan);
                    ElementTransformUtils.RotateElement(doc, elt_create.Id, axis_plan_line, -plan_rotation);


                    //VERIF FAMILLE AND ROTATE
                    IList <Parameter> parameters_inclinaison = elt_create.GetParameters("Inclinaison");
                    if (parameters_inclinaison.Count() == 0)
                    {
                        if (vertical == false)
                        {
                            WinForms.MessageBox.Show("La famille ne peut pas supporter l'option orientation normale");
                            return(Result.Failed);
                        }
                    }
                    else
                    {
                        if (vertical == false)
                        {
                            //Vertical rotation
                            double vert_rotation = Math.PI / 2 + angleplan_anglevert(PK, list_pts)[1];
                            parameters_inclinaison[0].Set(vert_rotation);
                        }
                        else
                        {
                            //Vertical rotation
                            double vert_rotation = Math.PI / 2;
                            parameters_inclinaison[0].Set(vert_rotation);
                        }
                    }

                    //SET THE PARAMETER (FAIRE LES VERIFS)
                    if (AsParameters)
                    {
                        for (int j = colonne_Parametres; j < colonne_Parametres + nb_params; j++)
                        {
                            IList <Parameter> parameter = elt_create.GetParameters((worksheet.Cells[1, j] as X.Range).Value);
                            if ((worksheet.Cells[i, j] as X.Range).Value != null && parameter.Count() != 0)
                            {
                                if (parameter[0].Definition.UnitType == UnitType.UT_Length)
                                {
                                    parameter[0].Set((worksheet.Cells[i, j] as X.Range).Value / 0.3048);
                                }
                                else if (parameter[0].Definition.UnitType == UnitType.UT_Angle)
                                {
                                    parameter[0].Set((worksheet.Cells[i, j] as X.Range).Value * Math.PI / 180);
                                }
                                else
                                {
                                    parameter[0].Set((worksheet.Cells[i, j] as X.Range).Value);
                                }
                            }
                        }
                    }

                    trans.Commit();
                }
            }

            workbook.Close(0);
            excel.Quit();
            KillExcel();
        }

        return(Result.Succeeded);
    }
示例#11
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Get application and document objects
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp?.ActiveUIDocument;
            Document      doc   = uidoc?.Document;
            Document      docAR = null;

            string accPointName = "СКУД_Точка доступа_[ТД]";
            var    accessPoint  = Util.GetFamilySymbolByFamilyName(doc, accPointName);

            if (accessPoint == null)
            {
                Util.InfoMsg2("В модели не загружено семейство:", accPointName);
                return(Result.Cancelled);
            }



            var levels = Util.GetElementsOfCategory(doc, BuiltInCategory.OST_Levels);

            XYZ yVect = new XYZ(0, 1, 0);

            ICollection <ElementId> selectedIds = uidoc.Selection.GetElementIds();

            if (0 == selectedIds.Count)
            {
                TaskDialog.Show("Предупреждение", "Выделите модель в АР");
                return(Result.Cancelled);
            }
            else
            {
                foreach (ElementId id in selectedIds)
                {
                    var link = doc.GetElement(id);
                    if (link.Category.Id.IntegerValue == (int)BuiltInCategory.OST_RvtLinks)
                    {
                        docAR = ((RevitLinkInstance)link).GetLinkDocument();
                    }
                }
            }

            while (true)
            {
                try {
                    using (Transaction t = new Transaction(doc, "Создание ТД")) {
                        t.Start();

                        if (!accessPoint.IsActive)
                        {
                            accessPoint.Activate();
                        }

                        Reference refElemLinked = uidoc.Selection.PickObject(ObjectType.LinkedElement, "Выберите дверь в связанной модели АР");
                        Element   door          = docAR.GetElement(refElemLinked.LinkedElementId);
                        if (door.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors |
                            door.Category.Id.IntegerValue == (int)BuiltInCategory.OST_CurtainWallPanels)
                        {
                            var elev          = Math.Round(((Level)docAR.GetElement(door.LevelId)).Elevation, 2);
                            var currentLevels = levels.Where(i => Math.Round(((Level)i).Elevation, 2) == elev);
                            if (currentLevels.Count() > 0)
                            {
                                Level level   = (Level)currentLevels.First();
                                XYZ   loc     = ((FamilyInstance)door).GetTotalTransform().Origin;
                                var   rotAxis = Line.CreateBound(loc, new XYZ(loc.X, loc.Y, loc.Z + 1.0));
                                var   orient  = ((FamilyInstance)door).FacingOrientation;
                                var   angle   = orient.AngleTo(yVect);

                                var doorHost  = (Wall)((FamilyInstance)door).Host;
                                var wallDepth = doorHost.Width;

                                double doorW     = 0.0;
                                double doorH     = 0.0;
                                double doorShift = 0.0;

                                if (doorHost.WallType.Kind == WallKind.Curtain)
                                {
                                    if (door.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors)
                                    {
                                        doorW = door.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble();
                                        doorH = door.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble();
                                    }
                                    else if (door.Category.Id.IntegerValue == (int)BuiltInCategory.OST_CurtainWallPanels)
                                    {
                                        doorW = door.get_Parameter(BuiltInParameter.CURTAIN_WALL_PANELS_WIDTH).AsDouble();
                                        doorH = door.get_Parameter(BuiltInParameter.CURTAIN_WALL_PANELS_HEIGHT).AsDouble();
                                    }
                                }
                                else
                                {
                                    var doorSymbol = ((FamilyInstance)door).Symbol;
                                    doorW     = doorSymbol.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble();
                                    doorH     = doorSymbol.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble();
                                    doorShift = door.get_Parameter(BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM).AsDouble();
                                }

                                var accPoint = doc.Create.NewFamilyInstance(loc, accessPoint, level, StructuralType.NonStructural);
                                ElementTransformUtils.RotateElement(doc, accPoint.Id, rotAxis, angle);

                                accPoint.LookupParameter("Ширина двери").Set(doorW);
                                accPoint.LookupParameter("Высота двери").Set(doorH);
                                accPoint.LookupParameter("Толщина стены").Set(wallDepth);
                                accPoint.LookupParameter("Смещение").Set(doorShift);
                            }
                        }

                        t.Commit();
                    }
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                    break;
                }
                catch (Exception ex) {
                    message = ex.Message;
                    return(Result.Failed);
                }
            }



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

            // Variables to store user input
            List <int>     selectedIntIds;
            Element        titleBlock;
            View           viewTemplate;
            ViewFamilyType viewFamilyType;
            double         sheetDrawingHeight;
            double         sheetDrawingWidth;

            // Prompt window to collect user input
            using (InteriorElevationsWindow customWindow = new InteriorElevationsWindow(commandData))
            {
                customWindow.ShowDialog();
                selectedIntIds = customWindow.IntegerIds;
                titleBlock     = customWindow.SelectedComboItemTitleBlock.Tag as Element;
                viewTemplate   = customWindow.SelectedComboItemViewTemplate.Tag as View;
                viewFamilyType = customWindow.SelectedComboItemViewType.Tag as ViewFamilyType;

                #region Required elements for this tool

                // No required elements loaded
                if (titleBlock == null && viewTemplate == null && viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load a Elevation, a Title Block and create a View Template");
                    return(Result.Cancelled);
                }
                // No title block and elevation loaded
                else if (titleBlock == null && viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load a Elevation and a Title Block");
                    return(Result.Cancelled);
                }
                // No title block and view template
                else if (titleBlock == null && viewTemplate == null)
                {
                    TaskDialog.Show("Warning", "Please load a Title Block and create a View Template");
                    return(Result.Cancelled);
                }
                // No elevation and view template
                else if (viewFamilyType == null && viewTemplate == null)
                {
                    TaskDialog.Show("Warning", "Please load an Elevation and create a View Template");
                    return(Result.Cancelled);
                }
                // No elevation
                else if (viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load an Elevation");
                    return(Result.Cancelled);
                }
                // No title block
                else if (titleBlock == null)
                {
                    TaskDialog.Show("Warning", "Please load a Title Block");
                    return(Result.Cancelled);
                }
                // No view template
                else if (titleBlock == null)
                {
                    TaskDialog.Show("Warning", "Please create a view template");
                    return(Result.Cancelled);
                }
                #endregion

                // Room selected
                else if (selectedIntIds != null)
                {
                    // Select first plan view
                    FilteredElementCollector floorPlansCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views);
                    View floorPlan = floorPlansCollector.Cast <View>().Where(v =>
                                                                             v.ViewType == ViewType.FloorPlan).Where(v => v.IsTemplate == false).FirstOrDefault();

                    if (floorPlan == null)
                    {
                        TaskDialog.Show("Warning", "Please create a floor plan");
                        return(Result.Cancelled);
                    }

                    // Store rooms with elevations created
                    List <string> roomsSucceeded = new List <string>();

                    // Collect rooms
                    foreach (int id in selectedIntIds)
                    {
                        Room room = doc.GetElement(new ElementId(id)) as Room;

                        // Retrieve boundaries
                        IList <IList <BoundarySegment> > boundaries = Helpers.Helpers.SpatialBoundaries(room);

                        // Check boundaries list is not empty
                        if (boundaries != null)
                        {
                            // Retrieve doc annotation categories
                            var annoCategories = Helpers.Helpers.AnnoCatIds(doc);

                            #region Rectangular rooms without interior boundaries
                            if (boundaries[0].Count == 4 && boundaries.Count == 1 && Helpers.Helpers.IsRectangle(boundaries[0]))
                            {
                                // Transaction
                                Transaction t = new Transaction(doc, "Create Single Marker Interior Elevations");
                                t.Start();

                                List <XYZ> points   = Helpers.Helpers.BoundaPoints(boundaries);
                                XYZ        centroid = Helpers.Helpers.Centroid(points);

                                // Create sheet
                                ViewSheet sheet = Helpers.HelpersView.CreateSheet(doc,
                                                                                  titleBlock.Id,
                                                                                  room.Number + "-" + "INTERIOR ELEVATIONS");

                                // Retrieve title block
                                FamilyInstance tBlock = new FilteredElementCollector(doc, sheet.Id)
                                                        .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                        .FirstElement() as FamilyInstance;

                                // Retrieve title block size
                                double sheetHeight = tBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble();
                                double sheetWidth  = tBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble();

                                // Center of title block
                                XYZ centerTitleBlock = new XYZ(sheetWidth / 2, sheetHeight / 2, 0);

                                // Create elevation marker
                                ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, viewFamilyType.Id, centroid, viewTemplate.Scale);

                                // Place views on sheet
                                var viewports = new List <Viewport>();

                                for (int i = 0; i < 4; i++)
                                {
                                    // Create elevation
                                    View view = Helpers.HelpersView.CreateViewElevation(doc, marker, floorPlan, i, viewTemplate,
                                                                                        annoCategories);
                                    Helpers.HelpersView.CreateViewport(doc, sheet, ref viewports, view);
                                }

                                // Dictionary to store viewport dimensions
                                var viewportDims = Helpers.HelpersView.ViewportDimensions(viewports);

                                // Retrieve overall dimensions
                                List <double> firstRowX = new List <double>();
                                List <double> firstRowY = new List <double>();

                                List <double> secondRowX = new List <double>();
                                List <double> secondRowY = new List <double>();

                                foreach (KeyValuePair <Viewport, double[]> entry in viewportDims)
                                {
                                    Viewport vp           = entry.Key;
                                    string   detailNumber = vp.get_Parameter(BuiltInParameter.VIEWER_DETAIL_NUMBER).AsString();

                                    if (detailNumber == "1" || detailNumber == "2")
                                    {
                                        firstRowX.Add(entry.Value[0]);
                                        firstRowY.Add(entry.Value[1]);
                                    }
                                    else
                                    {
                                        secondRowX.Add(entry.Value[0]);
                                        secondRowY.Add(entry.Value[1]);
                                    }
                                }

                                // Calculate X spacing
                                double spacingViewX = Helpers.Helpers.MillimetersToFeet(30);
                                double overallX     = spacingViewX;

                                if (firstRowX.Sum() > secondRowX.Sum())
                                {
                                    overallX += firstRowX.Sum();
                                }
                                else
                                {
                                    overallX += secondRowX.Sum();
                                }

                                // Calculate Y spacing
                                double spacingViewY = Helpers.Helpers.MillimetersToFeet(30);
                                double overallY     = spacingViewY;

                                if (firstRowY.Sum() > secondRowY.Sum())
                                {
                                    overallY += firstRowY.Sum();
                                }
                                else
                                {
                                    overallY += secondRowY.Sum();
                                }

                                // Closest and furthest X points
                                double centerTitleBlockX = centerTitleBlock.X;
                                double furthestX         = overallX / 2 + centerTitleBlockX;
                                double closestX          = centerTitleBlockX - overallX / 2;

                                // Closest and furthest Y points
                                double centerTitleBlockY = centerTitleBlock.Y;
                                double furthestY         = overallY / 2 + centerTitleBlockY;
                                double closestY          = centerTitleBlockY - overallY / 2;

                                // Points boundary
                                XYZ lowestRight    = new XYZ(furthestX, closestY, 0);
                                XYZ lowestLeft     = new XYZ(closestX, closestY, 0);
                                XYZ heightestLeft  = new XYZ(closestX, furthestY, 0);
                                XYZ heightestRight = new XYZ(furthestX, furthestY, 0);

                                // Move viewports
                                foreach (Viewport vp in viewports)
                                {
                                    Outline vpOut    = vp.GetBoxOutline();
                                    Outline labelOut = vp.GetLabelOutline();

                                    // Viewport dimensions
                                    XYZ maxPoint = vpOut.MaximumPoint;
                                    XYZ minPoint = vpOut.MinimumPoint;

                                    string detailNumber = vp.get_Parameter(BuiltInParameter.VIEWER_DETAIL_NUMBER).AsString();

                                    if (detailNumber == "4")
                                    {
                                        XYZ lowRightPoint = new XYZ(maxPoint.X, minPoint.Y, 0);
                                        XYZ moveVec       = lowestRight - lowRightPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "3")
                                    {
                                        XYZ lowLeftPoint = new XYZ(minPoint.X, minPoint.Y, 0);
                                        XYZ moveVec      = lowestLeft - lowLeftPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "2")
                                    {
                                        XYZ highRightPoint = new XYZ(maxPoint.X, maxPoint.Y, 0);
                                        XYZ moveVec        = heightestRight - highRightPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "1")
                                    {
                                        XYZ highLeftPoint = new XYZ(minPoint.X, maxPoint.Y, 0);
                                        XYZ moveVec       = heightestLeft - highLeftPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                }

                                // Append room number to success list
                                roomsSucceeded.Add(room.Number);

                                // Commit transaction
                                t.Commit();
                            }
                            #endregion

                            #region Rest of rooms
                            // When room has more or less than 4 sides
                            else
                            {
                                // Offset distanceof the elevation marker
                                double offsetElevation = Helpers.Helpers.MillimetersToFeet(-1000);
                                // Vector Z
                                XYZ zAxis = new XYZ(0, 0, 1);

                                // Transaction to create single elevations
                                Transaction t2 = new Transaction(doc, "Create single elevations");
                                t2.Start();

                                // Create sheet
                                ViewSheet sheet = Helpers.HelpersView.CreateSheet(doc,
                                                                                  titleBlock.Id,
                                                                                  room.Number + "-" + "INTERIOR ELEVATIONS");

                                // Retrieve title block
                                FamilyInstance tBlock = new FilteredElementCollector(doc, sheet.Id)
                                                        .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                        .FirstElement() as FamilyInstance;

                                // Retrieve title block size
                                double sheetHeight = tBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble();
                                double sheetWidth  = tBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble();

                                // Store viewports on sheet
                                var viewports = new List <Viewport>();

                                // Loop through each boundary
                                foreach (var boundary in boundaries[0])
                                {
                                    Curve originalCurve = boundary.GetCurve();
                                    Curve offsetCurve   = originalCurve.CreateOffset(offsetElevation, zAxis);

                                    // Curve centers
                                    XYZ origCenter   = (originalCurve.GetEndPoint(0) + originalCurve.GetEndPoint(1)) / 2;
                                    XYZ offsetCenter = (offsetCurve.GetEndPoint(0) + offsetCurve.GetEndPoint(1)) / 2;

                                    // Vector marker to center of original boundary
                                    XYZ vec = origCenter - offsetCenter;

                                    // Create elevation marker
                                    ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, viewFamilyType.Id, offsetCenter, viewTemplate.Scale);

                                    // Calculate rotation angle
                                    double angle = Helpers.Helpers.AngleTwoVectors(new XYZ(0, 100, 0), vec);

                                    // Check the component X of the translated vector to new origin is positive
                                    // this means angle to rotate clockwise
                                    if (angle != 0 && vec.X > 0)
                                    {
                                        angle = angle * -1;
                                    }
                                    else if (angle != 0 && origCenter.X < offsetCenter.X && origCenter.X > 0)
                                    {
                                        // Angle remains the same
                                    }
                                    // Check if rotation needs to be 180 degrees
                                    else if (angle == 0 && origCenter.Y < offsetCenter.Y)
                                    {
                                        angle = Math.PI;
                                    }
                                    // Line along z axis
                                    Line zLine = Line.CreateBound(new XYZ(offsetCenter.X, offsetCenter.Y, offsetCenter.Z), new XYZ(offsetCenter.X, offsetCenter.Y, offsetCenter.Z + 10));

                                    // Create Elevation View as marker needs to have at least one elevation to rotate
                                    View view = Helpers.HelpersView.CreateViewElevation(doc, marker, floorPlan, 1, viewTemplate, annoCategories);

                                    // Rotate in increments as Revit API adds 180 degrees to certain positive angles
                                    if (angle > 0)
                                    {
                                        double angleRemainder = angle;
                                        while (angleRemainder > 0)
                                        {
                                            double rotAngle = 0;
                                            if (angleRemainder > 0.6)
                                            {
                                                rotAngle = 0.6;
                                            }
                                            else
                                            {
                                                rotAngle = angleRemainder;
                                            }

                                            ElementTransformUtils.RotateElement(doc, marker.Id, zLine, rotAngle);

                                            angleRemainder -= rotAngle;
                                        }
                                    }
                                    // Rotate normally
                                    else
                                    {
                                        ElementTransformUtils.RotateElement(doc, marker.Id, zLine, angle);
                                    }

                                    // Retrieve crop shape
                                    ViewCropRegionShapeManager cropShapeManag = view.GetCropRegionShapeManager();
                                    IList <CurveLoop>          cropCurves     = cropShapeManag.GetCropShape();

                                    // Retrieve max and min height
                                    double minHeight = 0;
                                    double maxHeight = 0;

                                    foreach (Curve curve in cropCurves[0])
                                    {
                                        XYZ    point  = curve.GetEndPoint(0);
                                        double height = point.Z;

                                        if (height > maxHeight)
                                        {
                                            maxHeight = height;
                                        }
                                        else if (height < minHeight)
                                        {
                                            minHeight = height;
                                        }
                                    }

                                    // Crop region offset
                                    double topOffset = Helpers.Helpers.MillimetersToFeet(25);

                                    // Create curves for crop region
                                    XYZ bottomStartPoint = offsetCurve.GetEndPoint(0);
                                    XYZ bottomEndPoint   = offsetCurve.GetEndPoint(1);

                                    XYZ startBase = new XYZ(bottomStartPoint.X, bottomStartPoint.Y, bottomStartPoint.Z + minHeight);
                                    XYZ endBase   = new XYZ(bottomEndPoint.X, bottomEndPoint.Y, bottomEndPoint.Z + minHeight);

                                    XYZ startTop = new XYZ(bottomStartPoint.X, bottomStartPoint.Y, bottomStartPoint.Z + maxHeight + topOffset);
                                    XYZ endTop   = new XYZ(bottomEndPoint.X, bottomEndPoint.Y, bottomEndPoint.Z + maxHeight + topOffset);

                                    // Create CurveLoop for new crop shape
                                    List <Curve> curvesNewCrop = new List <Curve>();

                                    // Create contiguous lines
                                    Line sideOne  = Line.CreateBound(startBase, startTop);
                                    Line sideTwo  = Line.CreateBound(endTop, endBase);
                                    Line top      = Line.CreateBound(startTop, endTop);
                                    Line baseLine = Line.CreateBound(endBase, startBase);

                                    // Add the curves in order to the CurveLoop list
                                    curvesNewCrop.Add(baseLine);
                                    curvesNewCrop.Add(sideOne);
                                    curvesNewCrop.Add(top);
                                    curvesNewCrop.Add(sideTwo);

                                    // Apply new crop shape
                                    cropShapeManag.SetCropShape(CurveLoop.Create(curvesNewCrop));
                                    // Update document to reflect new crop shape when placing viewports
                                    doc.Regenerate();

                                    // Create viewports
                                    Helpers.HelpersView.CreateViewport(doc, sheet, ref viewports, view);
                                }

                                // Final viewport translation coordinates
                                sheetDrawingHeight = Helpers.Helpers.MillimetersToFeet(customWindow.SheetDrawingHeight);
                                sheetDrawingWidth  = Helpers.Helpers.MillimetersToFeet(customWindow.SheetDrawingWidth);

                                var viewportDims = Helpers.HelpersView.ViewportDimensions(viewports);
                                var coordinates  = Helpers.HelpersView.ViewportRowsColumns(viewportDims, sheetDrawingWidth, sheetDrawingHeight);

                                for (int i = 0; i < viewports.Count; i++)
                                {
                                    ElementTransformUtils.MoveElement(doc, viewports[i].Id, coordinates[i]);
                                }

                                // Append room number to success list
                                roomsSucceeded.Add(room.Number);

                                // Commit transaction
                                t2.Commit();
                            }
                            #endregion
                        }
                    }

                    #region Display results to user
                    // Display results to user
                    if (roomsSucceeded.Count > 0)
                    {
                        string messageSuccess = string.Join("\n", roomsSucceeded.ToArray());
                        TaskDialog.Show("Success", "The following room elevations have been created: " + "\n" + messageSuccess);
                    }
                    else
                    {
                        TaskDialog.Show("Error", "No room elevations have been created");
                    }
                    #endregion
                }
            }

            return(Result.Succeeded);
        }
示例#13
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Plane plane
        )
        {
            var element = PreviousElement(doc, Iteration);

            try
            {
                if (!plane.IsValid)
                {
                    throw new Exception(string.Format("Parameter '{0}' is not valid.", Params.Input[0].Name));
                }

                var scaleFactor = 1.0 / Revit.ModelUnits;
                if (scaleFactor != 1.0)
                {
                    plane = plane.Scale(scaleFactor);
                }

                if (element is SketchPlane sketchPlane)
                {
                    bool pinned = element.Pinned;
                    element.Pinned = false;

                    var plane0 = sketchPlane.GetPlane();
                    using (var plane1 = plane.ToHost())
                    {
                        if (!plane0.Normal.IsParallelTo(plane1.Normal))
                        {
                            var    axisDirection = plane0.Normal.CrossProduct(plane1.Normal);
                            double angle         = plane0.Normal.AngleTo(plane1.Normal);

                            using (var axis = Line.CreateUnbound(plane0.Origin, axisDirection))
                                ElementTransformUtils.RotateElement(Revit.ActiveDBDocument, element.Id, axis, angle);

                            plane0 = sketchPlane.GetPlane();
                        }

                        {
                            double angle = plane0.XVec.AngleOnPlaneTo(plane1.XVec, plane1.Normal);
                            if (angle != 0.0)
                            {
                                using (var axis = Line.CreateUnbound(plane0.Origin, plane1.Normal))
                                    ElementTransformUtils.RotateElement(Revit.ActiveDBDocument, element.Id, axis, angle);
                            }
                        }

                        var trans = plane1.Origin - plane0.Origin;
                        if (!trans.IsZeroLength())
                        {
                            ElementTransformUtils.MoveElement(Revit.ActiveDBDocument, element.Id, trans);
                        }
                    }

                    element.Pinned = pinned;
                }
                else
                {
                    element = CopyParametersFrom(SketchPlane.Create(doc, plane.ToHost()), element);
                }

                ReplaceElement(doc, DA, Iteration, element);
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                ReplaceElement(doc, DA, Iteration, null);
            }
        }
示例#14
0
        //adjust the angle of the placed instance
        private static void AdjustAngle()
        {
            try
            {
                //axis of rotation
                Line axis = Line.CreateBound(instancePoint, new XYZ(instancePoint.X, instancePoint.Y, instancePoint.Z + 10));

                if (line.GetEndPoint(0).Y > line.GetEndPoint(1).Y)
                {
                    if (line.GetEndPoint(0).X > line.GetEndPoint(1).X)
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI + yAngle);
                    }
                    else if (line.GetEndPoint(0).X < line.GetEndPoint(1).X)
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(doc, instance.Id, axis, 2 * Math.PI - yAngle);
                    }
                }
                else if (line.GetEndPoint(0).Y < line.GetEndPoint(1).Y)
                {
                    if (line.GetEndPoint(0).X > line.GetEndPoint(1).X)
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI + yAngle);
                    }
                    else if (line.GetEndPoint(0).X < line.GetEndPoint(1).X)
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(doc, instance.Id, axis, 2 * Math.PI - yAngle);
                    }
                }
                else
                {
                    //rotate the created family instance to align with the pipe
                    ElementTransformUtils.RotateElement(doc, instance.Id, axis, yAngle);
                }


                if (Math.Round(zAngle, 5) < Math.Round(Math.PI / 2, 5) &&
                    Math.Round(line.GetEndPoint(0).Y, 5) < Math.Round(line.GetEndPoint(1).Y, 5))
                {
                    //rotate the created family instance to align with the pipe
                    ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI);
                }
                else if (Math.Round(zAngle, 5) > Math.Round(Math.PI / 2, 5) &&
                         Math.Round(line.GetEndPoint(0).Y, 5) > Math.Round(line.GetEndPoint(1).Y, 5))
                {
                    //rotate the created family instance to align with the pipe
                    ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI);
                }
                else if (Math.Round(zAngle, 5) < Math.Round(Math.PI / 2, 5) &&
                         Math.Round(line.GetEndPoint(0).X, 5) < Math.Round(line.GetEndPoint(1).X, 5))
                {
                    //rotate the created family instance to align with the pipe
                    ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI);
                }
                else if (Math.Round(zAngle, 5) > Math.Round(Math.PI / 2, 5) &&
                         Math.Round(line.GetEndPoint(0).X, 5) > Math.Round(line.GetEndPoint(1).X, 5))
                {
                    //rotate the created family instance to align with the pipe
                    ElementTransformUtils.RotateElement(doc, instance.Id, axis, Math.PI);
                }
            }
            catch
            {
                throw new Exception();
            }
        }
示例#15
0
        // The Execute method for the updater
        public void Execute(UpdaterData data)
        {
            try
            {
                Document       doc     = data.GetDocument();
                FamilyInstance window  = doc.GetElement(m_windowId) as FamilyInstance;
                Element        section = doc.GetElement(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 = Line.CreateBound(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;
        }
示例#16
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            //// Select all pipes in the entire model.

            //List<Pipe> pipes = new List<Pipe>(
            //  new FilteredElementCollector( doc )
            //    .OfClass( typeof( Pipe ) )
            //    .ToElements()
            //    .Cast<Pipe>() );

            //int n = pipes.Count;

            //// If there are less than two,
            //// there is nothing we can do.

            //if( 2 > n )
            //{
            //  message = _prompt;
            //  return Result.Failed;
            //}

            //// If there are exactly two, pick those.

            //if( 2 < n )
            //{
            //  // Else, check for a pre-selection.

            //  pipes.Clear();

            //  Selection sel = uidoc.Selection;

            //  //n = sel.Elements.Size; // 2014

            //  ICollection<ElementId> ids
            //    = sel.GetElementIds(); // 2015

            //  n = ids.Count; // 2015

            //  Debug.Print( "{0} pre-selected elements.",
            //    n );

            //  // If two or more model pipes were pre-
            //  // selected, use the first two encountered.

            //  if( 1 < n )
            //  {
            //    //foreach( Element e in sel.Elements ) // 2014

            //    foreach( ElementId id in ids ) // 2015
            //    {
            //      Pipe c = doc.GetElement( id ) as Pipe;

            //      if( null != c )
            //      {
            //        pipes.Add( c );

            //        if( 2 == pipes.Count )
            //        {
            //          Debug.Print( "Found two model pipes, "
            //            + "ignoring everything else." );

            //          break;
            //        }
            //      }
            //    }
            //  }

            //  // Else, prompt for an
            //  // interactive post-selection.

            //  if( 2 != pipes.Count )
            //  {
            //    pipes.Clear();

            //    try
            //    {
            //      Reference r = sel.PickObject(
            //        ObjectType.Element,
            //        new PipeElementSelectionFilter(),
            //        "Please pick first pipe." );

            //      pipes.Add( doc.GetElement( r.ElementId )
            //        as Pipe );
            //    }
            //    catch( Autodesk.Revit.Exceptions
            //      .OperationCanceledException )
            //    {
            //      return Result.Cancelled;
            //    }

            //    try
            //    {
            //      Reference r = sel.PickObject(
            //        ObjectType.Element,
            //        new PipeElementSelectionFilter(),
            //        "Please pick second pipe." );

            //      pipes.Add( doc.GetElement( r.ElementId )
            //        as Pipe );
            //    }
            //    catch( Autodesk.Revit.Exceptions
            //      .OperationCanceledException )
            //    {
            //      return Result.Cancelled;
            //    }
            //  }
            //}

            JtPairPicker <Pipe> picker
                = new JtPairPicker <Pipe>(uidoc);

            Result rc = picker.Pick();

            if (Result.Failed == rc)
            {
                message = _prompt;
            }

            if (Result.Succeeded != rc)
            {
                return(rc);
            }

            IList <Pipe> pipes = picker.Selected;

            // Check for same pipe system type.

            ElementId systemTypeId
                = pipes[0].MEPSystem.GetTypeId();

            Debug.Assert(pipes[1].MEPSystem.GetTypeId()
                         .IntegerValue.Equals(
                             systemTypeId.IntegerValue),
                         "expected two similar pipes");

            // Check for same pipe level.

            ElementId levelId = pipes[0].LevelId;

            Debug.Assert(
                pipes[1].LevelId.IntegerValue.Equals(
                    levelId.IntegerValue),
                "expected two pipes on same level");

            // Extract data from the two selected pipes.

            double wall_thickness = GetWallThickness(pipes[0]);

            Debug.Print("{0} has wall thickness {1}",
                        Util.ElementDescription(pipes[0]),
                        Util.RealString(wall_thickness));

            Curve c0 = pipes[0].GetCurve();
            Curve c1 = pipes[1].GetCurve();

            if (!(c0 is Line) || !(c1 is Line))
            {
                message = _prompt
                          + " Expected straight pipes.";

                return(Result.Failed);
            }

            XYZ p00 = c0.GetEndPoint(0);
            XYZ p01 = c0.GetEndPoint(1);

            XYZ p10 = c1.GetEndPoint(0);
            XYZ p11 = c1.GetEndPoint(1);

            XYZ v0 = p01 - p00;
            XYZ v1 = p11 - p10;

            if (!Util.IsParallel(v0, v1))
            {
                message = _prompt
                          + " Expected parallel pipes.";

                return(Result.Failed);
            }

            // Select the two pipe endpoints
            // that are farthest apart.

            XYZ p0 = p00.DistanceTo(p10) > p01.DistanceTo(p10)
        ? p00
        : p01;

            XYZ p1 = p10.DistanceTo(p0) > p11.DistanceTo(p0)
        ? p10
        : p11;

            XYZ pm = 0.5 * (p0 + p1);

            XYZ v = p1 - p0;

            if (Util.IsParallel(v, v0))
            {
                message = "The selected pipes are colinear.";
                return(Result.Failed);
            }

            // Normal vector of the plane defined by the
            // two parallel and offset pipes, which is
            // the plane hosting the rolling offset

            XYZ z = v.CrossProduct(v1);

            // Vector perpendicular to v0 and v0 and
            // z, i.e. vector pointing from the first pipe
            // to the second in the cross sectional view.

            XYZ w = z.CrossProduct(v1).Normalize();

            // Offset distance perpendicular to pipe direction

            double distanceAcross = Math.Abs(
                v.DotProduct(w));

            // Distance between endpoints parallel
            // to pipe direction

            double distanceAlong = Math.Abs(
                v.DotProduct(v1.Normalize()));

            Debug.Assert(Util.IsEqual(v.GetLength(),
                                      Math.Sqrt(distanceAcross * distanceAcross
                                                + distanceAlong * distanceAlong)),
                         "expected Pythagorean equality here");

            // The required offset pipe angle.

            double angle = 45 * Math.PI / 180.0;

            // The angle on the other side.

            double angle2 = 0.5 * Math.PI - angle;

            double length = distanceAcross * Math.Tan(angle2);

            double halfLength = 0.5 * length;

            // How long should the pipe stubs become?

            double remainingPipeLength
                = 0.5 * (distanceAlong - length);

            if (0 > v1.DotProduct(v))
            {
                v1.Negate();
            }

            v1 = v1.Normalize();

            XYZ q0 = p0 + remainingPipeLength * v1;

            XYZ q1 = p1 - remainingPipeLength * v1;

            using (Transaction tx = new Transaction(doc))
            {
                // Determine pipe diameter for creating
                // matching pipes and fittings

                Pipe pipe = pipes[0];

                double diameter = pipe
                                  .get_Parameter(bipDiameter) // "Diameter"
                                  .AsDouble();

                // Pipe type for calls to doc.Create.NewPipe

                PipeType pipe_type_standard
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(PipeType))
                      .Cast <PipeType>()
                      .Where <PipeType>(e
                                        => e.Name.Equals("Standard"))
                      .FirstOrDefault <PipeType>();

                Debug.Assert(
                    pipe_type_standard.Id.IntegerValue.Equals(
                        pipe.PipeType.Id.IntegerValue),
                    "expected all pipes in this simple "
                    + "model to use the same pipe type");

                tx.Start("Rolling Offset");

                if (_place_model_line)
                {
                    // Trim or extend existing pipes

                    (pipes[0].Location as LocationCurve).Curve
                        = Line.CreateBound(p0, q0);

                    (pipes[1].Location as LocationCurve).Curve
                        = Line.CreateBound(p1, q1);

                    // Add a model line for the rolling offset pipe

                    Creator creator = new Creator(doc);

                    Line line = Line.CreateBound(q0, q1);

                    creator.CreateModelCurve(line);

                    pipe = null;
                }
                else if (_place_fittings)
                {
                    // Set active work plane to the rolling
                    // offset plane... removed again, since
                    // this has no effect at all on the
                    // fitting placement or rotation.
                    //
                    //Plane plane = new Plane( z, q0 );
                    //
                    //SketchPlane sp = SketchPlane.Create(
                    //  doc, plane );
                    //
                    //uidoc.ActiveView.SketchPlane = sp;
                    //uidoc.ActiveView.ShowActiveWorkPlane();

                    FamilySymbol symbol
                        = new FilteredElementCollector(doc)
                          .OfClass(typeof(FamilySymbol))
                          .OfCategory(BuiltInCategory.OST_PipeFitting)
                          .Cast <FamilySymbol>()
                          .Where <FamilySymbol>(e
                                                => e.Family.Name.Contains("Elbow - Generic"))
                          .FirstOrDefault <FamilySymbol>();

                    // Set up first 45 degree elbow fitting

                    FamilyInstance fitting0 = doc.Create
                                              .NewFamilyInstance(q0, symbol,
                                                                 StructuralType.NonStructural);

                    fitting0.LookupParameter("Angle").Set(
                        45.0 * Math.PI / 180.0);

                    //fitting0.get_Parameter( bipDiameter ) // does not exist
                    //  .Set( diameter );

                    fitting0.LookupParameter("Nominal Radius")
                    .Set(0.5 * diameter);

                    Line axis = Line.CreateBound(p0, q0);
                    angle = z.AngleTo(XYZ.BasisZ);

                    ElementTransformUtils.RotateElement(
                        doc, fitting0.Id, axis, Math.PI - angle);

                    Connector con0 = Util.GetConnectorClosestTo(
                        fitting0, p0);

                    // Trim or extend existing pipe

                    (pipes[0].Location as LocationCurve).Curve
                        = Line.CreateBound(p0, con0.Origin);

                    // Connect pipe to fitting

                    Util.Connect(con0.Origin, pipe, fitting0);

                    // Set up second 45 degree elbow fitting

                    FamilyInstance fitting1 = doc.Create
                                              .NewFamilyInstance(q1, symbol,
                                                                 StructuralType.NonStructural);

                    //fitting1.get_Parameter( "Angle" ).Set( 45.0 * Math.PI / 180.0 ); // 2014
                    //fitting1.get_Parameter( "Nominal Radius" ).Set( 0.5 * diameter ); // 2014

                    fitting1.LookupParameter("Angle").Set(45.0 * Math.PI / 180.0);  // 2015
                    fitting1.LookupParameter("Nominal Radius").Set(0.5 * diameter); // 2015

                    axis = Line.CreateBound(
                        q1, q1 + XYZ.BasisZ);

                    ElementTransformUtils.RotateElement(
                        doc, fitting1.Id, axis, Math.PI);

                    axis = Line.CreateBound(q1, p1);

                    ElementTransformUtils.RotateElement(
                        doc, fitting1.Id, axis, Math.PI - angle);

                    Connector con1 = Util.GetConnectorClosestTo(
                        fitting1, p1);

                    (pipes[1].Location as LocationCurve).Curve
                        = Line.CreateBound(con1.Origin, p1);

                    Util.Connect(con1.Origin, fitting1, pipes[1]);

                    con0 = Util.GetConnectorClosestTo(
                        fitting0, pm);

                    con1 = Util.GetConnectorClosestTo(
                        fitting1, pm);

                    // Connecting one fitting to the other does
                    // not insert a pipe in between. If the
                    // system is edited later, however, the two
                    // fittings snap together.
                    //
                    //con0.ConnectTo( con1 );

                    // Create rolling offset pipe segment

                    //pipe = doc.Create.NewPipe( con0.Origin, // 2014
                    //  con1.Origin, pipe_type_standard );

                    pipe = Pipe.Create(doc,
                                       pipe_type_standard.Id, levelId, con0, con1); // 2015

                    pipe.get_Parameter(bipDiameter)
                    .Set(diameter);

                    // Connect rolling offset pipe segment
                    // with elbow fittings at each end

                    Util.Connect(con0.Origin, fitting0, pipe);
                    Util.Connect(con1.Origin, pipe, fitting1);
                }
                else
                {
                    if (_use_static_pipe_create)
                    {
                        // Element id arguments to Pipe.Create.

                        ElementId idSystem;
                        ElementId idType;
                        ElementId idLevel;

                        // All these values are invalid for idSystem:

                        ElementId idSystem1 = pipe.MEPSystem.Id;
                        ElementId idSystem2 = ElementId.InvalidElementId;
                        ElementId idSystem3 = PipingSystem.Create(
                            doc, pipe.MEPSystem.GetTypeId(), "Tbc")
                                              .Id;

                        // This throws an argument exception saying
                        // The systemTypeId is not valid piping system type.
                        // Parameter name: systemTypeId

                        //pipe = Pipe.Create( doc, idSystem,
                        //  idType, idLevel, q0, q1 );

                        // Retrieve pipe system type, e.g.
                        // hydronic supply.

                        PipingSystemType pipingSystemType
                            = new FilteredElementCollector(doc)
                              .OfClass(typeof(PipingSystemType))
                              .OfType <PipingSystemType>()
                              .FirstOrDefault(st
                                              => st.SystemClassification
                                              == MEPSystemClassification
                                              .SupplyHydronic);

                        if (null == pipingSystemType)
                        {
                            message = "Could not find hydronic supply piping system type";
                            return(Result.Failed);
                        }

                        idSystem = pipingSystemType.Id;

                        Debug.Assert(pipe.get_Parameter(
                                         BuiltInParameter.RBS_PIPING_SYSTEM_TYPE_PARAM)
                                     .AsElementId().IntegerValue.Equals(
                                         idSystem.IntegerValue),
                                     "expected same piping system element id");

                        // Retrieve the PipeType.

                        PipeType pipeType =
                            new FilteredElementCollector(doc)
                            .OfClass(typeof(PipeType))
                            .OfType <PipeType>()
                            .FirstOrDefault();

                        if (null == pipeType)
                        {
                            message = "Could not find pipe type";
                            return(Result.Failed);
                        }

                        idType = pipeType.Id;

                        Debug.Assert(pipe.get_Parameter(
                                         BuiltInParameter.ELEM_TYPE_PARAM)
                                     .AsElementId().IntegerValue.Equals(
                                         idType.IntegerValue),
                                     "expected same pipe type element id");

                        Debug.Assert(pipe.PipeType.Id.IntegerValue
                                     .Equals(idType.IntegerValue),
                                     "expected same pipe type element id");

                        // Retrieve the reference level.
                        // pipe.LevelId is not the correct source!

                        idLevel = pipe.get_Parameter(
                            BuiltInParameter.RBS_START_LEVEL_PARAM)
                                  .AsElementId();

                        // Create the rolling offset pipe.

                        pipe = Pipe.Create(doc,
                                           idSystem, idType, idLevel, q0, q1);
                    }
                    else
                    {
                        //pipe = doc.Create.NewPipe( q0, q1, pipe_type_standard ); // 2014

                        pipe = Pipe.Create(doc, systemTypeId,
                                           pipe_type_standard.Id, levelId, q0, q1); // 2015
                    }

                    pipe.get_Parameter(bipDiameter)
                    .Set(diameter);

                    // Connect rolling offset pipe segment
                    // directly with the neighbouring original
                    // pipes
                    //
                    //Util.Connect( q0, pipes[0], pipe );
                    //Util.Connect( q1, pipe, pipes[1] );

                    // NewElbowFitting performs the following:
                    // - select appropriate fitting family and type
                    // - place and orient a family instance
                    // - set its parameters appropriately
                    // - connect it with its neighbours

                    Connector con0 = Util.GetConnectorClosestTo(
                        pipes[0], q0);

                    Connector con = Util.GetConnectorClosestTo(
                        pipe, q0);

                    doc.Create.NewElbowFitting(con0, con);

                    Connector con1 = Util.GetConnectorClosestTo(
                        pipes[1], q1);

                    con = Util.GetConnectorClosestTo(
                        pipe, q1);

                    doc.Create.NewElbowFitting(con, con1);
                }

                tx.Commit();
            }
            return(Result.Succeeded);
        }
示例#17
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Получение элементов приложения и документа
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Transaction   trans;

            string       typeName = "BFC_102.82_FB_S Hlinikovy fabion";
            FamilySymbol famSym   = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(q => q.Name == typeName).First() as FamilySymbol;

            List <Element> fabions = Utils.GetAllFamilyTypeInstances(doc, typeName);

            string   komaxitMatName = "BFC_KX9016";
            Material komaxitMat     = new FilteredElementCollector(doc).OfClass(typeof(Material)).Cast <Material>().Where(q => q.Name == komaxitMatName).First();

            try
            {
                List <Room> cleanRooms          = Utils.GetAllCleanRooms(doc);
                IDictionary cornersOrientations = new Dictionary <Room, IList <string> >();

                // Удалим все ранее созданные фабионы, если они были размещены в проекте
                if (fabions.Count != 0)
                {
                    trans = new Transaction(doc);
                    trans.Start("Удаление фабиона");

                    Utils.DeleteElements(doc, fabions);

                    trans.Commit();
                }

                string s = null;

                if (cleanRooms != null)
                {
                    foreach (Room r in cleanRooms)
                    {
                        s += r.Name + " " + r.LookupParameter("BL_Класс чистоты").AsString() + "\n";

                        // Определение границ помещений
                        List <Line> roomBoundary = Utils.GetRoomBoundary(r);

                        // Определение ориентации углов помещений
                        List <string> roomCornerOrient = Utils.GetRoomCornerOrientation(roomBoundary);

                        // Количество внутренних углов помещения
                        int innerCornerCount = Utils.GetInnerCornerCount(roomCornerOrient);

                        // Количество внешних углов помещения
                        int outerCornerCount = Utils.GetOutterCornerCount(roomCornerOrient);

                        // Определение коорректирующих углов поворота для размещения фабионов
                        List <int> fabionRotations = Utils.RoomAnglesOrientations(roomCornerOrient, roomBoundary);

                        // Определение координат внутренних углов помещения
                        List <Point> startPoints = Utils.GetInnerCornerList(roomBoundary, roomCornerOrient);

                        // Базовый уровень помещения
                        Level level = r.Level;

                        using (Transaction t = new Transaction(doc, "Place fabions"))
                        {
                            t.Start();

                            // Расстановка фабионов в углах чистых помещений
                            for (int i = 0; i < startPoints.Count; i++)
                            {
                                XYZ            location = startPoints[i].Coord;
                                Line           axis     = Line.CreateBound(location, new XYZ(location.X, location.Y, location.Z + 10));
                                FamilyInstance fabion   = doc.Create.NewFamilyInstance(location, famSym, level, StructuralType.Column);
                                ElementTransformUtils.RotateElement(doc, fabion.Id, axis, fabionRotations[i] * Math.PI / 180);

                                // Установить расчет количества "0" - подсчет по длине заказа
                                fabion.LookupParameter("BFC_Pocet_prvku").Set(0);

                                // Установить размер для заказа
                                fabion.LookupParameter("BFC_Rozmer").Set(UnitUtils.ConvertToInternalUnits(3500, UnitTypeId.Millimeters));

                                // Установить высоту фабиона по полной высоте помещения
                                fabion.LookupParameter("BFC_Delka_prvku").Set(r.UnboundedHeight);

                                // Установить смещение снизу для фабиона
                                fabion.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).Set(r.BaseOffset);
                            }

                            // Заполнение параметра потолочных фабионов
                            Parameter paramDM1 = r.LookupParameter("BFC_DM1_Polozka");
                            paramDM1.Set("FB");
                            Parameter paramDM1pocet = r.LookupParameter("BFC_DM1_Pocet_prvku");
                            paramDM1pocet.Set(0);
                            Parameter paramDM1rozmer = r.LookupParameter("BFC_DM1_Rozmer");
                            paramDM1rozmer.Set(0);
                            Parameter paramDM1material = r.LookupParameter("BFC_DM1_Material");
                            paramDM1material.Set(komaxitMat.Id);

                            // Заполнение параметров угловых внутренних скруглений
                            Parameter paramDM2poloz = r.LookupParameter("BFC_DM2_Polozka");
                            paramDM2poloz.Set("3F");
                            Parameter paramDM2pocet = r.LookupParameter("BFC_DM2_Pocet_prvku");
                            paramDM2pocet.Set(innerCornerCount);
                            Parameter paramDM2rozmer = r.LookupParameter("BFC_DM2_Rozmer");
                            paramDM2rozmer.Set(1);
                            Parameter paramDM2material = r.LookupParameter("BFC_DM2_Material");
                            paramDM2material.Set(komaxitMat.Id);

                            // Заполнение параметров угловных наружных скруглений
                            if (outerCornerCount > 0)
                            {
                                Parameter paramDM3 = r.LookupParameter("BFC_DM3_Polozka");
                                paramDM3.Set("2FV");
                                Parameter paramDM3pocet = r.LookupParameter("BFC_DM3_Pocet_prvku");
                                paramDM3pocet.Set(outerCornerCount);
                                Parameter paramDM3rozmer = r.LookupParameter("BFC_DM3_Rozmer");
                                paramDM3rozmer.Set(1);
                                Parameter paramDM3material = r.LookupParameter("BFC_DM3_Material");
                                paramDM3material.Set(komaxitMat.Id);
                            }

                            t.Commit();
                        }



                        /***
                         * using (Transaction transaction = new Transaction(doc))
                         * {
                         *
                         *  if (transaction.Start("Заполнение параметров фабионов и угловых элементов в помещении") == TransactionStatus.Started)
                         *  {
                         *      r.LookupParameter("BFC_DM1_Polozka").SetValueString("FB");
                         *      transaction.Commit();
                         *  }
                         * }
                         ***/
                    }

                    TaskDialog.Show("Чистые помещения", s);
                }
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
示例#18
0
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name);


                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Show Arrangement");

                    KeyValuePair <string, Entity> myKeyValuePair = (KeyValuePair <string, Entity>)myWindow1.myWindow4.myListViewEE.SelectedItem;

                    IDictionary <ElementId, XYZ> dict_Child = myKeyValuePair.Value.Get <IDictionary <ElementId, XYZ> >("FurnLocations", DisplayUnitType.DUT_MILLIMETERS);

                    string myStringAggregate_Location = "";

                    foreach (KeyValuePair <ElementId, XYZ> myKP in dict_Child)
                    {
                        Element Searchelem = doc.GetElement(myKP.Key);
                        if (Searchelem == null)
                        {
                            continue;
                        }

                        ElementTransformUtils.MoveElement(doc, myKP.Key, myKP.Value - ((LocationPoint)Searchelem.Location).Point);

                        myStringAggregate_Location = myStringAggregate_Location + Environment.NewLine + ((FamilyInstance)doc.GetElement(myKP.Key)).get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString() + "," + Math.Round(myKP.Value.X, 2) + "," + Math.Round(myKP.Value.Y, 2) + "," + Math.Round(myKP.Value.Z, 2);
                    }


                    IDictionary <ElementId, double> dict_Child_Angle = myKeyValuePair.Value.Get <IDictionary <ElementId, double> >("FurnLocations_Angle", DisplayUnitType.DUT_MILLIMETERS);

                    string myStringAggregate_Angle = "";

                    foreach (KeyValuePair <ElementId, double> myKP in dict_Child_Angle)
                    {
                        FamilyInstance Searchelem = doc.GetElement(myKP.Key) as FamilyInstance;
                        if (Searchelem == null)
                        {
                            continue;
                        }

                        Line line = Line.CreateBound(((LocationPoint)Searchelem.Location).Point, ((LocationPoint)Searchelem.Location).Point + XYZ.BasisZ);

                        double myDouble = Searchelem.GetTransform().BasisX.AngleOnPlaneTo(XYZ.BasisY, XYZ.BasisZ) - myKP.Value;

                        ElementTransformUtils.RotateElement(doc, myKP.Key, line, myDouble);

                        myStringAggregate_Angle = myStringAggregate_Angle + Environment.NewLine + (IsZero(myKP.Value, _eps) ? 0 : Math.Round(myKP.Value, 2));
                    }



                    IDictionary <ElementId, ElementId> dict_Child_Pattern = myKeyValuePair.Value.Get <IDictionary <ElementId, ElementId> >("FurnLocations_Pattern", DisplayUnitType.DUT_MILLIMETERS);
                    IDictionary <ElementId, int>       dict_Child_Red     = myKeyValuePair.Value.Get <IDictionary <ElementId, int> >("FurnLocations_ColorRed", DisplayUnitType.DUT_MILLIMETERS);
                    IDictionary <ElementId, int>       dict_Child_Green   = myKeyValuePair.Value.Get <IDictionary <ElementId, int> >("FurnLocations_ColorGreen", DisplayUnitType.DUT_MILLIMETERS);
                    IDictionary <ElementId, int>       dict_Child_Blue    = myKeyValuePair.Value.Get <IDictionary <ElementId, int> >("FurnLocations_ColorBlue", DisplayUnitType.DUT_MILLIMETERS);



                    int myInt = -1;
                    foreach (KeyValuePair <ElementId, ElementId> myKP in dict_Child_Pattern)
                    {
                        myInt++;
                        FamilyInstance Searchelem = doc.GetElement(myKP.Key) as FamilyInstance;
                        if (Searchelem == null)
                        {
                            continue;
                        }
                        if (Searchelem.Category.Name != "Furniture")
                        {
                            continue;
                        }

                        OverrideGraphicSettings ogs       = new OverrideGraphicSettings();
                        OverrideGraphicSettings ogsCheeck = doc.ActiveView.GetElementOverrides(myKP.Key);

                        Color myColor         = new Autodesk.Revit.DB.Color((byte)dict_Child_Red[myKP.Key], (byte)dict_Child_Green[myKP.Key], (byte)dict_Child_Blue[myKP.Key]);
                        Color myColorBrighter = ChangeColorBrightness(myColor, (float)0.5);


                        ogs.SetSurfaceForegroundPatternId(myKP.Value);
                        ogs.SetSurfaceForegroundPatternColor(myColor);
                        ogs.SetProjectionLineWeight(5);
                        ogs.SetProjectionLineColor(myColor);


                        FillPatternElement myFillPattern_SolidFill = new FilteredElementCollector(doc).OfClass(typeof(FillPatternElement)).Cast <FillPatternElement>().First(a => a.Name.Contains("Solid fill"));
                        ogs.SetSurfaceBackgroundPatternId(myFillPattern_SolidFill.Id);
                        ogs.SetSurfaceBackgroundPatternColor(myColorBrighter);


                        doc.ActiveView.SetElementOverrides(myKP.Key, ogs);
                    }


                    tx.Commit();
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE13_ExtensibleStorage_Rearrange" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
示例#19
0
        protected void PlaceOpeningFamilies(IEnumerable <Intersection> intersections)
        {
            var log_param = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров размеров");
            var log_id    = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров id");
            var log_level = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров уровня");
            var log_cut   = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка вырезания");

            foreach (Intersection i in intersections)
            {
                Element holeElement;
                if (IsExisted(i))
                {
                    holeElement = ExistingOpenings.Where(x => x.LookupParameter("ТеррНИИ_Идентификатор").AsString() == i.Id.ToString()).First();
                    LocationPoint loc = holeElement.Location as LocationPoint;
                    XYZ           vec = new XYZ(i.InsertionPoint.X,
                                                i.InsertionPoint.Y,
                                                i.Level.ProjectElevation) - loc.Point;
                    ElementTransformUtils.MoveElement(doc, holeElement.Id, vec);
                }
                else
                {
                    holeElement = doc.Create.NewFamilyInstance(
                        new XYZ(
                            i.InsertionPoint.X,
                            i.InsertionPoint.Y,
                            i.Level.Elevation),
                        openingFamilySymbol,
                        i.Level,
                        StructuralType.NonStructural);
                    // поворачиваем на нужную позицию
                    Line axe = Line.CreateUnbound(i.InsertionPoint, XYZ.BasisZ);
                    ElementTransformUtils.RotateElement(doc, holeElement.Id, axe, i.Angle);

                    //делаем вырез в хосте
                    try
                    {
                        if (i.HasHosts)
                        {
                            foreach (var host in i.Hosts)
                            {
                                InstanceVoidCutUtils.AddInstanceVoidCut(doc, host, holeElement);
                            }
                        }
                    }
                    catch
                    {
                        log_cut.AddError(i.Id);
                    }
                }
                try
                {
                    //идентификация
                    holeElement.LookupParameter("ТеррНИИ_Идентификатор")?.Set(i.Id.ToString());
                    holeElement.LookupParameter("Связанный файл")?.Set(i.Name);
                }
                catch { log_id.AddError(i.Id); }


                try
                {
                    // задаем параметры
                    holeElement.LookupParameter("ADSK_Отверстие_Ширина").Set(i.HoleWidth);
                    holeElement.LookupParameter("ADSK_Отверстие_Высота").Set(i.HoleHeight);
                    holeElement.LookupParameter("ADSK_Толщина стены").Set(i.HoleDepth);
                    // (временно) работа с отверстиями в кирпиче
                    holeElement.LookupParameter("ТеррНИИ_Отверстие_В кирпиче")?.Set(1);
                }
                catch { log_param.AddError(i.Id); }

                try
                {
                    // назначаем отметки
                    holeElement.LookupParameter("ADSK_Отверстие_Отметка от этажа").Set(i.LevelOffset);
                    if (i.Level.Elevation == 0)
                    {
                        holeElement.LookupParameter("ADSK_Отверстие_Отметка этажа").Set(0);
                    }
                    else
                    {
                        holeElement.LookupParameter("ADSK_Отверстие_Отметка этажа").Set(i.Level.Elevation);
                    }
                    // обнуляем смещение
                    holeElement.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(0);
                }
                catch { log_level.AddError(i.Id); }
            }
        }
示例#20
0
        /***************************************************/

        public static bool SetLocation(this FamilyInstance element, Column column, RevitSettings settings)
        {
            if (!(typeof(Column).BuiltInCategories().Contains((BuiltInCategory)element.Category.Id.IntegerValue)))
            {
                return(false);
            }

            oM.Geometry.Line columnLine = column.Location as oM.Geometry.Line;
            if (columnLine == null)
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Location has not been updated, only linear columns are allowed in Revit. Revit ElementId: {0} BHoM_Guid: {1}", element.Id, column.BHoM_Guid));
                return(false);
            }

            if (columnLine.Start.Z >= columnLine.End.Z)
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Location of the column has not been updated because BHoM column has start above end. Revit ElementId: {0} BHoM_Guid: {1}", element.Id, column.BHoM_Guid));
                return(false);
            }

            if (1 - columnLine.Direction().DotProduct(Vector.ZAxis) > settings.AngleTolerance && element.LookupParameterInteger(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM) == 0)
            {
                BH.Engine.Reflection.Compute.RecordWarning(String.Format("Column style has been set to Vertical, but its driving curve is slanted. Column style changed to Slanted. Revit ElementId: {0} BHoM_Guid: {1}", element.Id, column.BHoM_Guid));
                element.SetParameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM, 2);
                element.Document.Regenerate();
            }

            bool updated = false;

            if (element.IsSlantedColumn)
            {
                updated |= element.SetLocation(columnLine, settings);
                Output <double, double> extensions = element.ColumnExtensions(settings);
                double startExtension = -extensions.Item1;
                double endExtension   = -extensions.Item2;

                if (Math.Abs(startExtension) > settings.DistanceTolerance || Math.Abs(endExtension) > settings.DistanceTolerance)
                {
                    element.SetLocation(columnLine.Extend(startExtension, endExtension), settings);
                    updated = true;
                }
            }
            else
            {
                double locationZ = ((LocationPoint)element.Location).Point.Z.ToSI(UnitType.UT_Length);
                updated |= element.SetLocation(new oM.Geometry.Point {
                    X = columnLine.Start.X, Y = columnLine.Start.Y, Z = locationZ
                }, settings);

                Parameter baseLevelParam  = element.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM);
                Parameter topLevelParam   = element.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM);
                Parameter baseOffsetParam = element.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);
                Parameter topOffsetParam  = element.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM);
                Level     baseLevel       = element.Document.GetElement(baseLevelParam.AsElementId()) as Level;
                Level     topLevel        = element.Document.GetElement(topLevelParam.AsElementId()) as Level;
                double    baseElevation   = (baseLevel.ProjectElevation + baseOffsetParam.AsDouble()).ToSI(UnitType.UT_Length);
                double    topElevation    = (topLevel.ProjectElevation + topOffsetParam.AsDouble()).ToSI(UnitType.UT_Length);

                if (Math.Abs(baseElevation - columnLine.Start.Z) > settings.DistanceTolerance)
                {
                    element.SetParameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM, columnLine.Start.Z.FromSI(UnitType.UT_Length) - baseLevel.ProjectElevation, false);
                    updated = true;
                }

                if (Math.Abs(topElevation - columnLine.End.Z) > settings.DistanceTolerance)
                {
                    element.SetParameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM, columnLine.End.Z.FromSI(UnitType.UT_Length) - topLevel.ProjectElevation, false);
                    updated = true;
                }
            }

            double rotation = 0;
            ConstantFramingProperty framingProperty = column.Property as ConstantFramingProperty;

            if (framingProperty == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning(String.Format("BHoM object's property is not a ConstantFramingProperty, therefore its orientation angle could not be retrieved. BHoM_Guid: {0}", column.BHoM_Guid));
            }
            else
            {
                rotation = ((ConstantFramingProperty)column.Property).OrientationAngle;
            }

            double rotationDifference = element.OrientationAngleColumn(settings) - rotation;

            if (Math.Abs(rotationDifference) > settings.AngleTolerance)
            {
                double rotationParamValue = element.LookupParameterDouble(BuiltInParameter.STRUCTURAL_BEND_DIR_ANGLE);
                if (double.IsNaN(rotationParamValue))
                {
                    ElementTransformUtils.RotateElement(element.Document, element.Id, columnLine.ToRevit(), -rotationDifference.NormalizeAngleDomain());
                    updated = true;
                }
                else
                {
                    double newRotation = (rotationParamValue + rotationDifference).NormalizeAngleDomain();
                    updated |= element.SetParameter(BuiltInParameter.STRUCTURAL_BEND_DIR_ANGLE, newRotation);
                }
            }

            return(updated);
        }
示例#21
0
        internal void RejustSectionView(Document doc, Element elem, ViewSection section)
        {
            XYZ position     = XYZ.Zero;
            XYZ fOrientation = XYZ.Zero;

            if (elem is FamilyInstance)
            {
                FamilyInstance familyInstance = elem as FamilyInstance;
                if (familyInstance.Location != null && familyInstance.Location is LocationPoint)
                {
                    LocationPoint locationPoint = familyInstance.Location as LocationPoint;
                    position = locationPoint.Point;
                }
                fOrientation = familyInstance.FacingOrientation;
            }

            XYZ sOrigin    = section.Origin;
            XYZ sDirection = section.ViewDirection;

            XYZ fRectOrientation = fOrientation.CrossProduct(XYZ.BasisZ);

            // Rotate the section element
            double angle = fOrientation.AngleTo(sDirection);
            // Need to adjust the rotation angle based on the direction of rotation (not covered by AngleTo)
            XYZ    cross = fRectOrientation.CrossProduct(sDirection).Normalize();
            double sign  = 1.0;

            if (!cross.IsAlmostEqualTo(XYZ.BasisZ))
            {
                sign = -1.0;
            }

            double rotateAngle = 0;

            if (Math.Abs(angle) > 0 && Math.Abs(angle) <= Math.PI / 2.0)
            {
                if (angle < 0)
                {
                    rotateAngle = Math.PI / 2.0 + angle;
                }
                else
                {
                    rotateAngle = Math.PI / 2.0 - angle;
                }
            }
            else if (Math.Abs(angle) > Math.PI / 2.0)
            {
                if (angle < 0)
                {
                    rotateAngle = angle + Math.PI / 2.0;
                }
                else
                {
                    rotateAngle = angle - Math.PI / 2.0;
                }
            }

            rotateAngle *= sign;

            if (Math.Abs(rotateAngle) > 0)
            {
                Line axis = Line.CreateBound(sOrigin, sOrigin + XYZ.BasisZ);
                ElementTransformUtils.RotateElement(doc, m_sectionElement.Id, axis, rotateAngle);
            }

            // Regenerate the document
            doc.Regenerate();

            // Move the section element
            double dotF           = position.DotProduct(fRectOrientation);
            double dotS           = sOrigin.DotProduct(fRectOrientation);
            double moveDot        = dotF - dotS;
            XYZ    sNewDirection  = section.ViewDirection; // Get the new direction after rotation.
            double correction     = fRectOrientation.DotProduct(sNewDirection);
            XYZ    translationVec = sNewDirection * correction * moveDot;

            if (!translationVec.IsZeroLength())
            {
                ElementTransformUtils.MoveElement(doc, m_sectionElement.Id, translationVec);
            }
        }
示例#22
0
        public static void RotateElementInPosition(XYZ placementPoint, Connector conOnFamilyToConnect, Connector start, Element element)
        {
            #region Geometric manipulation

            //http://thebuildingcoder.typepad.com/blog/2012/05/create-a-pipe-cap.html

            //Select the OTHER connector
            MEPCurve hostPipe = start.Owner as MEPCurve;

            Connector end = (from Connector c in hostPipe.ConnectorManager.Connectors //End of the host/dummy pipe
                             where c.Id != start.Id && (int)c.ConnectorType == 1
                             select c).FirstOrDefault();

            XYZ dir = (start.Origin - end.Origin);

            // rotate the cap if necessary
            // rotate about Z first

            XYZ pipeHorizontalDirection = new XYZ(dir.X, dir.Y, 0.0).Normalize();
            //XYZ pipeHorizontalDirection = new XYZ(dir.X, dir.Y, 0.0);

            XYZ connectorDirection = -conOnFamilyToConnect.CoordinateSystem.BasisZ;

            double zRotationAngle = pipeHorizontalDirection.AngleTo(connectorDirection);

            Transform trf = Transform.CreateRotationAtPoint(XYZ.BasisZ, zRotationAngle, placementPoint);

            XYZ testRotation = trf.OfVector(connectorDirection).Normalize();

            if (Math.Abs(testRotation.DotProduct(pipeHorizontalDirection) - 1) > 0.00001)
            {
                zRotationAngle = -zRotationAngle;
            }

            Line axis = Line.CreateBound(placementPoint, placementPoint + XYZ.BasisZ);

            ElementTransformUtils.RotateElement(element.Document, element.Id, axis, zRotationAngle);

            //Parameter comments = element.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
            //comments.Set("Horizontal only");

            // Need to rotate vertically?

            if (Math.Abs(dir.DotProduct(XYZ.BasisZ)) > 0.000001)
            {
                // if pipe is straight up and down,
                // kludge it my way else

                if (dir.X.Round3() == 0 && dir.Y.Round3() == 0 && dir.Z.Round3() != 0)
                {
                    XYZ yaxis = new XYZ(0.0, 1.0, 0.0);
                    //XYZ yaxis = dir.CrossProduct(connectorDirection);

                    double rotationAngle = dir.AngleTo(yaxis);
                    //double rotationAngle = 90;

                    if (dir.Z.Equals(1))
                    {
                        rotationAngle = -rotationAngle;
                    }

                    axis = Line.CreateBound(placementPoint,
                                            new XYZ(placementPoint.X, placementPoint.Y + 5, placementPoint.Z));

                    ElementTransformUtils.RotateElement(element.Document, element.Id, axis, rotationAngle);

                    //comments.Set("Vertical!");
                }
                else
                {
                    #region sloped pipes

                    double rotationAngle = dir.AngleTo(pipeHorizontalDirection);

                    XYZ normal = pipeHorizontalDirection.CrossProduct(XYZ.BasisZ);

                    trf = Transform.CreateRotationAtPoint(normal, rotationAngle, placementPoint);

                    testRotation = trf.OfVector(dir).Normalize();

                    if (Math.Abs(testRotation.DotProduct(pipeHorizontalDirection) - 1) < 0.00001)
                    {
                        rotationAngle = -rotationAngle;
                    }

                    axis = Line.CreateBound(placementPoint, placementPoint + normal);

                    ElementTransformUtils.RotateElement(element.Document, element.Id, axis, rotationAngle);

                    //comments.Set("Sloped");

                    #endregion
                }
            }

            #endregion
        }
示例#23
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;


            //1.find all ductEnds which needs ratate

            var collector       = new FilteredElementCollector(doc);
            var familyinstances = collector.OfClass(typeof(FamilyInstance)).WhereElementIsNotElementType().Cast <FamilyInstance>();

            var ductEnds = familyinstances.Where(m => m.Symbol.FamilyName.Contains("单层百叶风口"));


            MessageBox.Show(ductEnds.Count().ToString());

            Transaction ts = new Transaction(doc, "旋转风口");

            ts.Start();


            foreach (FamilyInstance fi in ductEnds)
            {
                var rotateAnxis       = Line.CreateUnbound((fi.Location as LocationPoint).Point, XYZ.BasisZ);
                var facingOrientation = fi.FacingOrientation;

                var mepmodel = fi.MEPModel;
                if (mepmodel == null)
                {
                    MessageBox.Show("mepmodel is null");

                    continue;
                }

                var conman     = mepmodel.ConnectorManager;
                var connectors = conman.Connectors;
                //MessageBox.Show(connectors.Size.ToString());

                var firstcon = connectors.Cast <Connector>().Where(m => m.ConnectorType == ConnectorType.End).First();
                if (firstcon == null)
                {
                    MessageBox.Show("firstcon is null");
                }

                var connectedcon = firstcon.GetConnectedCon();
                //var allrefs = firstcon.AllRefs;

                //foreach (Connector con in allrefs)
                //{
                //    MessageBox.Show(con.ConnectorType.ToString());

                //    if (con.ConnectorType == ConnectorType.Curve)
                //        MessageBox.Show("conMessage:" + con.Origin.ToString() + Environment.NewLine +
                //                        "firstconMsg:" + firstcon.Origin.ToString());
                //}

                //MessageBox.Show("allrefs::" + allrefs.Size.ToString());


                var ownerDuct = firstcon.GetConnectedCon().Owner as Duct;
                //if (ownerDuct == null)
                //{
                //    MessageBox.Show("Owner duct is null");

                //    continue;
                //}

                var ownerDuctDir = ownerDuct.LocationLine().Direction;
                if (!ownerDuctDir.Z.IsEqual(0))
                {
                    continue;
                }
                LogHelper.LogWrite(facingOrientation.ToString(), @"c:\abc.txt", true);
                LogHelper.LogWrite(ownerDuctDir.ToString(), @"c:\abc.txt", true);
                LogHelper.LogWrite("\n", @"c:\abc.txt", true);
                if (!facingOrientation.IsParallel(ownerDuctDir))
                {
                    //LogHelper.LogWrite(facingOrientation.ToString(), @"c:\abc.txt",true);
                    ElementTransformUtils.RotateElement(doc, fi.Id, rotateAnxis, Math.PI / 2);
                }
            }

            ts.Commit();



            return(Result.Succeeded);
        }
示例#24
0
        public static Autodesk.Revit.DB.FamilyInstance ToNative(this SpeckleElementsClasses.FamilyInstance myFamInst)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myFamInst.ApplicationId, myFamInst.Type);


            // get family symbol; it's used throughout
            FamilySymbol familySymbol = GetFamilySymbolByFamilyNameAndType(myFamInst.familyName, myFamInst.familyType);

            // Freak out if we don't have a symbol.
            if (familySymbol == null)
            {
                ConversionErrors.Add(new SpeckleConversionError {
                    Message = $"Missing family: {myFamInst.familyName} {myFamInst.familyType}"
                });
                throw new RevitFamilyNotFoundException($"No such family found in the project");
            }

            if (myFamInst.basePoint == null)
            {
                ConversionErrors.Add(new SpeckleConversionError {
                    Message = $"Could not create: {myFamInst.familyName} {myFamInst.familyType}"
                });
                throw new RevitFamilyNotFoundException($"Missing base point");
            }

            // Activate the symbol yo!
            if (!familySymbol.IsActive)
            {
                familySymbol.Activate();
            }

            XYZ xyz = (XYZ)SpeckleCore.Converter.Deserialise(obj: myFamInst.basePoint, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" });


            if (docObj != null) // we have a document object already, so check if we can edit it.
            {
                var type = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                // if family changed, tough luck - delete and rewind
                if (myFamInst.familyName != type.FamilyName)
                {
                    //delete and continue crating it
                    Doc.Delete(docObj.Id);
                }
                // edit element
                else
                {
                    var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj;

                    // check if type changed, and try and change it
                    if (myFamInst.familyType != null && (myFamInst.familyType != type.Name))
                    {
                        existingFamilyInstance.ChangeTypeId(familySymbol.Id);
                    }

                    //update location
                    var existingLocationPoint = existingFamilyInstance.Location as LocationPoint;
                    existingLocationPoint.Point = xyz;

                    var existingRotation = existingLocationPoint.Rotation * 180 / Math.PI;

                    if (existingRotation != myFamInst.rotation)
                    {
                        var r      = (double)myFamInst.rotation;
                        XYZ point1 = new XYZ(xyz.X, xyz.Y, 0);
                        XYZ point2 = new XYZ(xyz.X, xyz.Y, 10);

                        if (existingRotation != 0)
                        {
                            r -= existingRotation;
                        }

                        Autodesk.Revit.DB.Line axis = Autodesk.Revit.DB.Line.CreateBound(point1, point2);
                        ElementTransformUtils.RotateElement(Doc, existingFamilyInstance.Id, axis, Math.PI * r / 180);
                    }



                    SetElementParams(existingFamilyInstance, myFamInst.parameters);
                    return(existingFamilyInstance);
                }
            }

            else
            {
                var myTypeBasedFamInst = Doc.Create.NewFamilyInstance(xyz, familySymbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                SetElementParams(myTypeBasedFamInst, myFamInst.parameters);

                if (myFamInst.rotation != null && myFamInst.rotation != 0)
                {
                    var r      = (double)myFamInst.rotation;
                    XYZ point1 = new XYZ(xyz.X, xyz.Y, 0);
                    XYZ point2 = new XYZ(xyz.X, xyz.Y, 10);
                    Autodesk.Revit.DB.Line axis = Autodesk.Revit.DB.Line.CreateBound(point1, point2);

                    ElementTransformUtils.RotateElement(Doc, myTypeBasedFamInst.Id, axis, Math.PI * r / 180);
                }

                return(myTypeBasedFamInst);
            }
            return(null);
        }
示例#25
0
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name);


                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Show Arrangement");

                    KeyValuePair <string, Entity> myKeyValuePair = (KeyValuePair <string, Entity>)myWindow1.myWindow4.myListViewEE.SelectedItem;

                    IDictionary <ElementId, XYZ> dict_Child = myKeyValuePair.Value.Get <IDictionary <ElementId, XYZ> >("FurnLocations", DisplayUnitType.DUT_MILLIMETERS);

                    string myStringAggregate_Location = "";

                    foreach (KeyValuePair <ElementId, XYZ> myKP in dict_Child)
                    {
                        Element Searchelem = doc.GetElement(myKP.Key);
                        if (Searchelem == null)
                        {
                            continue;
                        }

                        ElementTransformUtils.MoveElement(doc, myKP.Key, myKP.Value - ((LocationPoint)Searchelem.Location).Point);

                        myStringAggregate_Location = myStringAggregate_Location + Environment.NewLine + ((FamilyInstance)doc.GetElement(myKP.Key)).get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString() + "," + Math.Round(myKP.Value.X, 2) + "," + Math.Round(myKP.Value.Y, 2) + "," + Math.Round(myKP.Value.Z, 2);
                    }


                    IDictionary <ElementId, double> dict_Child_Angle = myKeyValuePair.Value.Get <IDictionary <ElementId, double> >("FurnLocations_Angle", DisplayUnitType.DUT_MILLIMETERS);

                    string myStringAggregate_Angle = "";

                    foreach (KeyValuePair <ElementId, double> myKP in dict_Child_Angle)
                    {
                        FamilyInstance Searchelem = doc.GetElement(myKP.Key) as FamilyInstance;
                        if (Searchelem == null)
                        {
                            continue;
                        }

                        Line line = Line.CreateBound(((LocationPoint)Searchelem.Location).Point, ((LocationPoint)Searchelem.Location).Point + XYZ.BasisZ);

                        double myDouble = Searchelem.GetTransform().BasisX.AngleOnPlaneTo(XYZ.BasisY, XYZ.BasisZ) - myKP.Value;

                        ElementTransformUtils.RotateElement(doc, myKP.Key, line, myDouble);

                        myStringAggregate_Angle = myStringAggregate_Angle + Environment.NewLine + (IsZero(myKP.Value, _eps) ? 0 : Math.Round(myKP.Value, 2));
                    }

                    tx.Commit();
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE13_ExtensibleStorage_Rearrange" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
示例#26
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);
        }
示例#27
0
        void ReconstructSketchPlaneByPlane
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Plane plane
        )
        {
            if (!plane.IsValid)
            {
                ThrowArgumentException(nameof(plane), "Plane is not valid.");
            }

            var scaleFactor = 1.0 / Revit.ModelUnits;

            if (scaleFactor != 1.0)
            {
                plane = plane.Scale(scaleFactor);
            }

            if (element is SketchPlane sketchPlane)
            {
                bool pinned = element.Pinned;
                element.Pinned = false;

                var plane0 = sketchPlane.GetPlane();
                using (var plane1 = plane.ToHost())
                {
                    if (!plane0.Normal.IsParallelTo(plane1.Normal))
                    {
                        var    axisDirection = plane0.Normal.CrossProduct(plane1.Normal);
                        double angle         = plane0.Normal.AngleTo(plane1.Normal);

                        using (var axis = Line.CreateUnbound(plane0.Origin, axisDirection))
                            ElementTransformUtils.RotateElement(doc, element.Id, axis, angle);

                        plane0 = sketchPlane.GetPlane();
                    }

                    {
                        double angle = plane0.XVec.AngleOnPlaneTo(plane1.XVec, plane1.Normal);
                        if (angle != 0.0)
                        {
                            using (var axis = Line.CreateUnbound(plane0.Origin, plane1.Normal))
                                ElementTransformUtils.RotateElement(doc, element.Id, axis, angle);
                        }
                    }

                    var trans = plane1.Origin - plane0.Origin;
                    if (!trans.IsZeroLength())
                    {
                        ElementTransformUtils.MoveElement(doc, element.Id, trans);
                    }
                }

                element.Pinned = pinned;
            }
            else
            {
                ReplaceElement(ref element, SketchPlane.Create(doc, plane.ToHost()));
            }
        }