예제 #1
0
 /// <summary>
 /// Create from an existing element
 /// </summary>
 /// <param name="existingSketchPlane"></param>
 /// <param name="isRevitOwned"></param>
 /// <returns></returns>
 internal static SketchPlane FromExisting(Autodesk.Revit.DB.SketchPlane existingSketchPlane, bool isRevitOwned)
 {
     return(new SketchPlane(existingSketchPlane)
     {
         IsRevitOwned = isRevitOwned
     });
 }
예제 #2
0
        void ReconstructModelLineByCurve
        (
            DB.Document doc,
            ref DB.Element element,

            Rhino.Geometry.Curve curve,
            DB.SketchPlane sketchPlane
        )
        {
            var plane = sketchPlane.GetPlane().ToPlane();

            if
            (
                ((curve = Rhino.Geometry.Curve.ProjectToPlane(curve, plane)) == null)
            )
            {
                ThrowArgumentException(nameof(curve), "Failed to project curve in the sketchPlane.");
            }

            var centerLine = curve.ToCurve();

            if (curve.IsClosed == centerLine.IsBound)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Unable to keep curve closed.");
            }

            if (element is DB.ModelCurve modelCurve && centerLine.IsSameKindAs(modelCurve.GeometryCurve))
            {
                modelCurve.SetSketchPlaneAndCurve(sketchPlane, centerLine);
            }
예제 #3
0
        void ReconstructModelLineByCurve
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Curve curve,
            Autodesk.Revit.DB.SketchPlane sketchPlane
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            var plane = sketchPlane.GetPlane().ToRhino().Scale(scaleFactor);

            if
            (
                !(scaleFactor != 1.0 ? curve.Scale(scaleFactor) : true) ||
                ((curve = Rhino.Geometry.Curve.ProjectToPlane(curve, plane)) != null)
            )
            {
                ThrowArgumentException(nameof(curve), "Failed to project curve in the sketchPlane.");
            }

            var curves = curve.ToHost().ToArray();

            Debug.Assert(curves.Length == 1);
            var centerLine = curves[0];

            if (element is ModelCurve modelCurve && centerLine.IsSameKindAs(modelCurve.GeometryCurve))
            {
                modelCurve.SetSketchPlaneAndCurve(sketchPlane, centerLine);
            }
예제 #4
0
파일: ModelText.cs 프로젝트: hipigod/Dynamo
        /// <summary>
        /// Internal constructor for the ModelText
        /// </summary>
        /// <param name="text"></param>
        /// <param name="sketchPlane"></param>
        /// <param name="xCoordinateInPlane"></param>
        /// <param name="yCoordinateInPlane"></param>
        /// <param name="textDepth"></param>
        /// <param name="modelTextType"></param>
        private ModelText(string text, Autodesk.Revit.DB.SketchPlane sketchPlane, double xCoordinateInPlane, double yCoordinateInPlane, double textDepth, Autodesk.Revit.DB.ModelTextType modelTextType)
        {
            //Phase 1 - Check to see if the object exists and should be rebound
            var oldEle =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.ModelText>(Document);


            // Note: not sure if there's a way to mutate the sketchPlane for a ModelText, so we need
            // to insure the Element hasn't changed position, otherwise, we destroy and rebuild the Element
            if (oldEle != null && PositionUnchanged(oldEle, sketchPlane, xCoordinateInPlane, yCoordinateInPlane))
            {
                // There was an element and it's position hasn't changed
                InternalSetModelText(oldEle);
                InternalSetText(text);
                InternalSetDepth(textDepth);
                InternalSetModelTextType(modelTextType);
                return;
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            // We have to clean up the old ModelText b/c we can't mutate it's position
            if (oldEle != null)
            {
                DocumentManager.Instance.DeleteElement(new ElementUUID(oldEle.UniqueId));
            }

            var mt = CreateModelText(text, sketchPlane, xCoordinateInPlane, yCoordinateInPlane, textDepth, modelTextType);

            InternalSetModelText(mt);

            TransactionManager.Instance.TransactionTaskDone();

            ElementBinder.SetElementForTrace(this.InternalElement);
        }
예제 #5
0
        void ReconstructModelLineByCurve
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Curve curve,
            Autodesk.Revit.DB.SketchPlane sketchPlane
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            var plane = sketchPlane.GetPlane().ToRhino().ChangeUnits(scaleFactor);

            if
            (
                ((curve = curve.ChangeUnits(scaleFactor)) is null) ||
                ((curve = Rhino.Geometry.Curve.ProjectToPlane(curve, plane)) == null)
            )
            {
                ThrowArgumentException(nameof(curve), "Failed to project curve in the sketchPlane.");
            }

            var centerLine = curve.ToHost();

            if (curve.IsClosed == centerLine.IsBound)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Unable to keep curve closed.");
            }

            if (element is ModelCurve modelCurve && centerLine.IsSameKindAs(modelCurve.GeometryCurve))
            {
                modelCurve.SetSketchPlaneAndCurve(sketchPlane, centerLine);
            }
예제 #6
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Curve curve,
            Autodesk.Revit.DB.SketchPlane plane
        )
        {
            var elements = PreviousElements(doc, Iteration).ToList();

            try
            {
                if (curve == null)
                {
                    throw new Exception(string.Format("Parameter '{0}' is null.", Params.Input[0].Name));
                }

                if (plane == null)
                {
                    throw new Exception(string.Format("Parameter '{0}' is null.", Params.Input[1].Name));
                }

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

                curve = Rhino.Geometry.Curve.ProjectToPlane(curve, plane.GetPlane().ToRhino());

                var newElements = new List <Element>();
                {
                    int index = 0;
                    foreach (var c in curve.ToHost() ?? Enumerable.Empty <Autodesk.Revit.DB.Curve>())
                    {
                        var element = index < elements.Count ? elements[index] : null;
                        index++;

                        if (element?.Pinned ?? true)
                        {
                            if (element is ModelCurve modelCurve && modelCurve.GeometryCurve.IsBound == c.IsBound)
                            {
                                modelCurve.SetSketchPlaneAndCurve(plane, c);
                            }
                            else if (doc.IsFamilyDocument)
                            {
                                element = CopyParametersFrom(doc.FamilyCreate.NewModelCurve(c, plane), element);
                            }
                            else
                            {
                                element = CopyParametersFrom(doc.Create.NewModelCurve(c, plane), element);
                            }
                        }

                        newElements.Add(element);
                    }
                }

                ReplaceElements(doc, DA, Iteration, newElements);
            }
예제 #7
0
        private static Autodesk.Revit.DB.SketchPlane GetSketchPlaneFromCurve(Curve c)
        {
            Plane plane = GetPlaneFromCurve(c, false);

            Autodesk.Revit.DB.SketchPlane sp = null;
            sp = Document.IsFamilyDocument ?
                 Document.FamilyCreate.NewSketchPlane(plane) :
                 Document.Create.NewSketchPlane(plane);

            return(sp);
        }
예제 #8
0
        public static SketchPlane GetSketchPlaneFromCurve(Curve c)
        {
            Plane       plane = GetPlaneFromCurve(c, false);
            SketchPlane sp    = null;

            sp = dynRevitSettings.Doc.Document.IsFamilyDocument ?
                 dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(plane) :
                 dynRevitSettings.Doc.Document.Create.NewSketchPlane(plane);

            return(sp);
        }
예제 #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve axis = null;
            DA.GetData("Curve", ref axis);

            Autodesk.Revit.DB.SketchPlane plane = null;
            DA.GetData("SketchPlane", ref plane);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, plane));
        }
예제 #10
0
        /// <summary>
        /// Create a ModelText element in the current Family Document
        /// </summary>
        /// <param name="text"></param>
        /// <param name="sketchPlane"></param>
        /// <param name="xCoordinateInPlane"></param>
        /// <param name="yCoordinateInPlane"></param>
        /// <param name="textDepth"></param>
        /// <param name="modelTextType"></param>
        /// <returns></returns>
        private static Autodesk.Revit.DB.ModelText CreateModelText(string text, Autodesk.Revit.DB.SketchPlane sketchPlane, double xCoordinateInPlane, double yCoordinateInPlane, double textDepth, Autodesk.Revit.DB.ModelTextType modelTextType)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // obtain the position of the ModelText element in the plane of the sketchPlane
            var plane = sketchPlane.GetPlane();
            var pos   = plane.Origin + plane.XVec * xCoordinateInPlane + plane.YVec * yCoordinateInPlane;

            // create the modeltext
            var mt = Document.FamilyCreate.NewModelText(text, modelTextType, sketchPlane, pos, HorizontalAlign.Left, textDepth);

            TransactionManager.Instance.TransactionTaskDone();

            return(mt);
        }
예제 #11
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(dynRevitSettings.Doc.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                Plane p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(p1);
                Curve       c1  = dynRevitSettings.Revit.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = dynRevitSettings.Doc.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }
예제 #12
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                var p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewSketchPlane(p1);
                Curve       c1  = DocumentManager.Instance.CurrentUIApplication.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }
예제 #13
0
        public override FScheme.Value Evaluate(FSharpList <FScheme.Value> args)
        {
            var pts = ((FScheme.Value.List)args[0]).Item.Select(
                x => ((ReferencePoint)((FScheme.Value.Container)x).Item).Position
                ).ToList();

            if (pts.Count <= 1)
            {
                throw new Exception("Not enough reference points to make a curve.");
            }

            var ns = UIDocument.Application.Application.Create.NewNurbSpline(
                pts, Enumerable.Repeat(1.0, pts.Count).ToList());

            ModelNurbSpline c;

            if (Elements.Any() && dynUtils.TryGetElement(Elements[0], out c))
            {
                ModelCurve.setCurveMethod(c, ns); //c.GeometryCurve = ns;
            }
            else
            {
                Elements.Clear();

                double    rawParam = ns.ComputeRawParameter(.5);
                Transform t        = ns.ComputeDerivatives(rawParam, false);

                XYZ norm = t.BasisZ;

                if (norm.GetLength() == 0)
                {
                    norm = XYZ.BasisZ;
                }

                Autodesk.Revit.DB.Plane       p  = new Autodesk.Revit.DB.Plane(norm, t.Origin);
                Autodesk.Revit.DB.SketchPlane sp = this.UIDocument.Document.FamilyCreate.NewSketchPlane(p);
                //sps.Add(sp);

                c = UIDocument.Document.FamilyCreate.NewModelCurve(ns, sp) as ModelNurbSpline;

                Elements.Add(c.Id);
            }

            return(FScheme.Value.NewContainer(c));
        }
예제 #14
0
        public Autodesk.Revit.DB.ModelCurve MakeLine(Document doc, XYZ ptA, XYZ ptB)
        {
            Autodesk.Revit.ApplicationServices.Application app = doc.Application;
            // Create plane by the points
            Line   line   = app.Create.NewLine(ptA, ptB, true);
            XYZ    norm   = ptA.CrossProduct(ptB);
            double length = norm.GetLength();

            if (length == 0)
            {
                norm = XYZ.BasisZ;
            }
            Autodesk.Revit.DB.Plane       plane   = app.Create.NewPlane(norm, ptB);
            Autodesk.Revit.DB.SketchPlane skplane = doc.FamilyCreate.NewSketchPlane(plane);
            // Create line here
            Autodesk.Revit.DB.ModelCurve modelcurve = doc.FamilyCreate.NewModelCurve(line, skplane);
            return(modelcurve);
        }
예제 #15
0
파일: Plane.cs 프로젝트: l2obin/Dynamo
        bool resetPlaneofSketchPlaneElement(Autodesk.Revit.DB.SketchPlane sp, Autodesk.Revit.DB.Plane p)
        {
            XYZ newOrigin = p.Origin;
            XYZ newNorm   = p.Normal;
            var oldP      = sp.Plane;
            XYZ oldOrigin = oldP.Origin;
            XYZ oldNorm   = oldP.Normal;

            if (oldNorm.IsAlmostEqualTo(newNorm))
            {
                XYZ moveVec = newOrigin - oldOrigin;
                if (moveVec.GetLength() > 0.000000001)
                {
                    ElementTransformUtils.MoveElement(this.UIDocument.Document, sp.Id, moveVec);
                }
                return(true);
            }
            //rotation might not work for sketch planes
            return(false);
        }
예제 #16
0
        /// <summary>
        /// Set the plane and the curve internally.
        /// </summary>
        private void InternalSetSketchPlaneFromCurve(Curve newCurve)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            Plane newPlane = CurveUtils.GetPlaneFromCurve(newCurve, false);
            Plane oldPlane = InternalCurveElement.SketchPlane.GetPlane();

            var angleBetweenPlanes     = newPlane.Normal.AngleTo(oldPlane.Normal);
            var distanceBetweenOrigins = newPlane.Origin.DistanceTo(oldPlane.Origin);

            Autodesk.Revit.DB.SketchPlane sp = null;

            // Planes are different.
            if (angleBetweenPlanes > tolerance || distanceBetweenOrigins > tolerance)
            {
                sp = GetSketchPlaneFromCurve(newCurve);
                InternalCurveElement.SetSketchPlaneAndCurve(sp, newCurve);
            }
            // Planes are the same.
            else
            {
                InternalSetCurve(newCurve);
            }

            string idSpUnused = String.Empty;

            if (sp != null && InternalCurveElement.SketchPlane.Id != sp.Id)
            {
                idSpUnused = sp.UniqueId;
            }

            // if we got a valid id, delete the old sketch plane
            if (idSpUnused != String.Empty)
            {
                DocumentManager.Instance.DeleteElement(new ElementUUID(idSpUnused));
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
예제 #17
0
 /// <summary>
 /// Initialize a SketchPlane element
 /// </summary>
 /// <param name="existingSketchPlane"></param>
 private void InitSketchPlane(Autodesk.Revit.DB.SketchPlane existingSketchPlane)
 {
     InternalSetSketchPlane(existingSketchPlane);
 }
예제 #18
0
 public SketchPlane(DB.SketchPlane sketchPlane) : base(sketchPlane)
 {
 }
예제 #19
0
 public static SketchPlane Wrap(Autodesk.Revit.DB.SketchPlane ele, bool isRevitOwned)
 {
     return(SketchPlane.FromExisting(ele, isRevitOwned));
 }
예제 #20
0
 public RefPlane(Autodesk.Revit.DB.SketchPlane sp)
 {
     Id           = sp.Id.IntegerValue;
     RefPlaneName = sp.Name;
 }
예제 #21
0
        public override FScheme.Value Evaluate(FSharpList <FScheme.Value> args)
        {
            Autodesk.Revit.DB.CurveLoop cl = (Autodesk.Revit.DB.CurveLoop)((FScheme.Value.Container)args[0]).Item;

            if (cl == null)
            {
                throw new InvalidOperationException("No curve loop");
            }

            Autodesk.Revit.DB.Plane plane = cl.GetPlane();
            if (plane == null)
            {
                throw new InvalidOperationException("Curve loop is not planar");
            }

            var mcs = new System.Collections.Generic.List <Autodesk.Revit.DB.ModelCurve>();

            var listCurves           = new System.Collections.Generic.List <Curve> ();
            CurveLoopIterator CLiter = cl.GetCurveLoopIterator();

            for (; CLiter.MoveNext();)
            {
                listCurves.Add(CLiter.Current.Clone());
            }

            int numCurves = listCurves.Count;

            Autodesk.Revit.DB.SketchPlane sp = null;
            for (int index = 0; index < numCurves; index++)
            {
                //instead of changing Revit curve keep it "as is"
                //user might have trouble modifying curve in Revit if it is off the sketch plane
                Autodesk.Revit.DB.ModelCurve mc = null;
                if (this.Elements.Any() && index < this.Elements.Count)
                {
                    bool needsRemake = false;
                    if (dynUtils.TryGetElement(this.Elements[index], out mc))
                    {
                        ElementId idSpUnused = ModelCurve.resetSketchPlaneMethod(mc, listCurves[index], plane, out needsRemake);

                        if (idSpUnused != ElementId.InvalidElementId && index == numCurves - 1)
                        {
                            this.DeleteElement(idSpUnused);
                        }
                        if (!needsRemake)
                        {
                            if (!mc.GeometryCurve.IsBound && listCurves[index].IsBound)
                            {
                                listCurves[index] = listCurves[index].Clone();
                                listCurves[index].MakeUnbound();
                            }
                            ModelCurve.setCurveMethod(mc, listCurves[index]); // mc.GeometryCurve = c;
                        }
                        else
                        {
                            this.DeleteElement(this.Elements[index]);
                        }
                    }
                    else
                    {
                        needsRemake = true;
                    }
                    if (needsRemake)
                    {
                        if (sp == null)
                        {
                            sp = dynRevitSettings.Doc.Document.IsFamilyDocument ?
                                 dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(plane) :
                                 dynRevitSettings.Doc.Document.Create.NewSketchPlane(plane);
                        }
                        if (dynRevitUtils.GetPlaneFromCurve(listCurves[index], true) == null)
                        {
                            mc = this.UIDocument.Document.IsFamilyDocument
                                ? this.UIDocument.Document.FamilyCreate.NewModelCurve(listCurves[index], sp)
                                : this.UIDocument.Document.Create.NewModelCurve(listCurves[index], sp);

                            ModelCurve.setCurveMethod(mc, listCurves[index]);
                        }
                        else
                        {
                            mc = this.UIDocument.Document.IsFamilyDocument
                                ? this.UIDocument.Document.FamilyCreate.NewModelCurve(listCurves[index], sp)
                                : this.UIDocument.Document.Create.NewModelCurve(listCurves[index], sp);
                        }
                        if (index < this.Elements.Count)
                        {
                            this.Elements[index] = mc.Id;
                        }
                        else
                        {
                            this.Elements.Add(mc.Id);
                        }
                        if (mc.SketchPlane.Id != sp.Id && index == numCurves - 1)
                        {
                            //THIS BIZARRE as Revit could use different existing SP, so if Revit had found better plane  this sketch plane has no use
                            this.DeleteElement(sp.Id);
                        }
                    }
                }
                else
                {
                    if (sp == null)
                    {
                        sp = dynRevitSettings.Doc.Document.IsFamilyDocument ?
                             dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(plane) :
                             dynRevitSettings.Doc.Document.Create.NewSketchPlane(plane);
                    }

                    if (dynRevitUtils.GetPlaneFromCurve(listCurves[index], true) == null)
                    {
                        mc = this.UIDocument.Document.IsFamilyDocument
                            ? this.UIDocument.Document.FamilyCreate.NewModelCurve(listCurves[index], sp)
                            : this.UIDocument.Document.Create.NewModelCurve(listCurves[index], sp);

                        ModelCurve.setCurveMethod(mc, listCurves[index]);
                    }
                    else
                    {
                        mc = this.UIDocument.Document.IsFamilyDocument
                            ? this.UIDocument.Document.FamilyCreate.NewModelCurve(listCurves[index], sp)
                            : this.UIDocument.Document.Create.NewModelCurve(listCurves[index], sp);
                    }
                    this.Elements.Add(mc.Id);
                    if (mc.SketchPlane.Id != sp.Id && index == numCurves - 1)
                    {
                        //found better plane
                        this.DeleteElement(sp.Id);
                    }
                }
                if (mc != null)
                {
                    mcs.Add(mc);
                }
            }
            FSharpList <FScheme.Value> results = FSharpList <FScheme.Value> .Empty;

            foreach (var mc in mcs)
            {
                results = FSharpList <FScheme.Value> .Cons(FScheme.Value.NewContainer(mc), results);
            }
            return(FScheme.Value.NewList(Utils.SequenceToFSharpList(results.Reverse())));
        }
예제 #22
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Curve curve,
            Autodesk.Revit.DB.SketchPlane plane
        )
        {
            var elements = PreviousElements(doc, Iteration).ToList();

            try
            {
                var newElements = new List <Element>();

                if (curve == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is null.", Params.Input[0].Name));
                }
                else if (plane == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is null.", Params.Input[1].Name));
                }
                else
                {
                    curve = Rhino.Geometry.Curve.ProjectToPlane(curve, plane.GetPlane().ToRhino());

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

                    if (curve.IsShort(Revit.ShortCurveTolerance))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' is too short.", Params.Input[0].Name));
                    }
                    else
                    {
                        int index = 0;
                        foreach (var c in curve.ToHost() ?? Enumerable.Empty <Autodesk.Revit.DB.Curve>())
                        {
                            var element = index < elements.Count ? elements[index] : null;
                            index++;

                            if (element?.Pinned ?? true)
                            {
                                element = doc.Create.NewModelCurve(c, plane);
                            }

                            newElements.Add(element);
                        }
                    }
                }

                elements = newElements;
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
            }
            finally
            {
                ReplaceElements(doc, DA, Iteration, elements);
            }
        }
예제 #23
0
 public SketchPlane(Autodesk.Revit.DB.SketchPlane sketchPlane) : base(sketchPlane)
 {
 }
예제 #24
0
        private static string resetSketchPlaneMethod(Autodesk.Revit.DB.CurveElement mc, Curve c, Autodesk.Revit.DB.Plane flattenedOnPlane, out bool needsSketchPlaneReset)
        {
            //do we need to reset?
            needsSketchPlaneReset = false;
            Autodesk.Revit.DB.Plane newPlane = flattenedOnPlane != null ? flattenedOnPlane : CurveUtils.GetPlaneFromCurve(c, false);

            Autodesk.Revit.DB.Plane curPlane = mc.SketchPlane.GetPlane();

            bool resetPlane = false;

            {
                double llSqCur         = curPlane.Normal.DotProduct(curPlane.Normal);
                double llSqNew         = newPlane.Normal.DotProduct(newPlane.Normal);
                double dotP            = newPlane.Normal.DotProduct(curPlane.Normal);
                double dotSqNormalized = (dotP / llSqCur) * (dotP / llSqNew);
                double angleTol        = System.Math.PI / 1800.0;
                if (dotSqNormalized < 1.0 - angleTol * angleTol)
                {
                    resetPlane = true;
                }
            }
            Autodesk.Revit.DB.SketchPlane sp = null;

            if (!resetPlane)
            {
                double originDiff = curPlane.Normal.DotProduct(curPlane.Origin - newPlane.Origin);
                double tolerance  = 0.000001;
                if (originDiff > tolerance || originDiff < -tolerance)
                {
                    sp             = GetSketchPlaneFromCurve(c);
                    mc.SketchPlane = GetSketchPlaneFromCurve(c);
                }
                return((sp == null || mc.SketchPlane.Id == sp.Id) ? "" : sp.UniqueId);
            }

            //do reset if method is available

            bool foundMethod = false;

            if (hasMethodResetSketchPlane)
            {
                Type          CurveElementType        = typeof(Autodesk.Revit.DB.CurveElement);
                MethodInfo[]  curveElementMethods     = CurveElementType.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                System.String nameOfMethodSetCurve    = "ResetSketchPlaneAndCurve";
                System.String nameOfMethodSetCurveAlt = "SetSketchPlaneAndCurve";

                foreach (MethodInfo m in curveElementMethods)
                {
                    if (m.Name == nameOfMethodSetCurve || m.Name == nameOfMethodSetCurveAlt)
                    {
                        object[] argsM = new object[2];
                        sp       = GetSketchPlaneFromCurve(c);
                        argsM[0] = sp;
                        argsM[1] = null;

                        foundMethod = true;
                        m.Invoke(mc, argsM);
                        break;
                    }
                }
            }
            if (!foundMethod)
            {
                //sp = dynRevitUtils.GetSketchPlaneFromCurve(c);
                hasMethodResetSketchPlane = false;
                needsSketchPlaneReset     = true;
                //expect exception, so try to keep old plane?
                //mc.SketchPlane = sp;
                return("");
            }

            if (sp != null && mc.SketchPlane.Id != sp.Id)
            {
                return(sp.UniqueId);
            }

            return("");
        }
예제 #25
0
 /// <summary>
 /// Set the Element, ElementId, and UniqueId
 /// </summary>
 /// <param name="existingSketchPlane"></param>
 private void InternalSetSketchPlane(Autodesk.Revit.DB.SketchPlane existingSketchPlane)
 {
     this.InternalSketchPlane = existingSketchPlane;
     this.InternalElementId = existingSketchPlane.Id;
     this.InternalUniqueId = existingSketchPlane.UniqueId;
 }
예제 #26
0
        /// <summary>
        /// Convert an input Value into and expected type if possible.
        /// Ex. If a node expects an XYZ, a user can pass in a ReferencePoint object
        /// and the position (XYZ) of that object will be returned.
        /// </summary>
        /// <param name="input">The value of the input.</param>
        /// <param name="output">The desired output type.</param>
        /// <returns></returns>
        public static object ConvertInput(Value input, Type output)
        {
            if (input.IsContainer)
            {
                object item = ((Value.Container)input).Item;

                #region ModelCurve
                if (item.GetType() == typeof(ModelCurve))
                {
                    ModelCurve a = (ModelCurve)item;

                    if (output == typeof(Curve))
                    {
                        return(((ModelCurve)item).GeometryCurve);
                    }
                }
                #endregion

                #region SketchPlane
                else if (item.GetType() == typeof(SketchPlane))
                {
                    SketchPlane a = (SketchPlane)item;

                    if (output == typeof(Plane))
                    {
                        return(a.Plane);
                    }
                    else if (output == typeof(ReferencePlane))
                    {
                        return(a.Plane);
                    }
                    else if (output == typeof(string))
                    {
                        return(string.Format("{0},{1},{2},{3},{4},{5}", a.Plane.Origin.X, a.Plane.Origin.Y, a.Plane.Origin.Z,
                                             a.Plane.Normal.X, a.Plane.Normal.Y, a.Plane.Normal.Z));
                    }
                }
                #endregion

                #region Point
                else if (item.GetType() == typeof(Point))
                {
                    Point a = (Point)item;

                    if (output == typeof(XYZ))
                    {
                        return(a.Coord);
                    }
                    else if (output == typeof(string))
                    {
                        return(string.Format("{0},{1},{2}", a.Coord.X, a.Coord.Y, a.Coord.Z));
                    }
                }
                #endregion

                #region ReferencePoint
                else if (item.GetType() == typeof(ReferencePoint))
                {
                    ReferencePoint a = (ReferencePoint)item;

                    if (output == typeof(XYZ))
                    {
                        return(a.Position);
                    }
                    else if (output == typeof(Reference))
                    {
                        return(a.GetCoordinatePlaneReferenceXY());
                    }
                    else if (output == typeof(Transform))
                    {
                        return(a.GetCoordinateSystem());
                    }
                    else if (output == typeof(string))
                    {
                        return(string.Format("{0},{1},{2}", a.Position.X, a.Position.Y, a.Position.Z));
                    }
                    else if (output == typeof(ElementId))
                    {
                        return(a.Id);
                    }
                }
                #endregion

                #region ElementId
                else if (item.GetType() == typeof(ElementId))
                {
                    if (output == typeof(ReferencePoint))
                    {
                        ElementId      a  = (ElementId)item;
                        Element        el = dynRevitSettings.Doc.Document.GetElement(a);
                        ReferencePoint rp = (ReferencePoint)el;
                        return(rp);
                    }
                }
                #endregion

                #region Reference
                else if (item.GetType() == typeof(Reference))
                {
                    Reference a = (Reference)item;
                    if (output.IsAssignableFrom(typeof(Element)))
                    {
                        Element e = dynRevitSettings.Doc.Document.GetElement(a);
                    }
                    else if (output == typeof(Face))
                    {
                        Face f = (Face)dynRevitSettings.Doc.Document.GetElement(a.ElementId).GetGeometryObjectFromReference(a);
                        return(f);
                    }
                }
                #endregion

                #region XYZ
                if (item.GetType() == typeof(XYZ))
                {
                    XYZ a = (XYZ)item;
                    if (output == typeof(Transform))
                    {
                        Transform t = Transform.get_Translation(a);
                        return(t);
                    }
                }
                #endregion

                return(item);
            }
            else if (input.IsNumber)
            {
                double a = (double)((Value.Number)input).Item;

                if (output == typeof(bool))
                {
                    return(Convert.ToBoolean(a));
                }
                else if (output == typeof(Int32))
                {
                    return(Convert.ToInt32(a));
                }

                return(a);
            }
            else if (input.IsString)
            {
                string a = ((Value.String)input).Item.ToString();
                return(a);
            }
            else if (input.IsList)
            {
                FSharpList <Value> a = ((Value.List)input).Item;

                if (output == typeof(ReferenceArrayArray))
                {
                    return(DynamoTypeConverter.ConvertFSharpListListToReferenceArrayArray(a));
                }
                else if (output == typeof(ReferenceArray))
                {
                    return(DynamoTypeConverter.ConvertFSharpListListToReferenceArray(a));
                }
                else if (output == typeof(CurveArrArray))
                {
                    return(DynamoTypeConverter.ConvertFSharpListListToCurveArray(a));
                }
                else if (output == typeof(CurveArray))
                {
                    return(DynamoTypeConverter.ConvertFSharpListListToCurveArray(a));
                }

                return(a);
            }

            //return the input by default
            return(input);
        }
예제 #27
0
 /// <summary>
 /// Set the Element, ElementId, and UniqueId
 /// </summary>
 /// <param name="existingSketchPlane"></param>
 private void InternalSetSketchPlane(Autodesk.Revit.DB.SketchPlane existingSketchPlane)
 {
     this.InternalSketchPlane = existingSketchPlane;
     this.InternalElementId   = existingSketchPlane.Id;
     this.InternalUniqueId    = existingSketchPlane.UniqueId;
 }
예제 #28
0
 /// <summary>
 /// Internal constructor for the ModelText
 /// </summary>
 /// <param name="text"></param>
 /// <param name="sketchPlane"></param>
 /// <param name="xCoordinateInPlane"></param>
 /// <param name="yCoordinateInPlane"></param>
 /// <param name="textDepth"></param>
 /// <param name="modelTextType"></param>
 private ModelText(string text, Autodesk.Revit.DB.SketchPlane sketchPlane, double xCoordinateInPlane,
                   double yCoordinateInPlane, double textDepth, Autodesk.Revit.DB.ModelTextType modelTextType)
 {
     SafeInit(() => InitModelText(text, sketchPlane, xCoordinateInPlane, yCoordinateInPlane, textDepth, modelTextType));
 }
예제 #29
0
 /// <summary>
 /// Set the Sketch plane from an existing one
 /// </summary>
 /// <param name="existingSketchPlane"></param>
 private SketchPlane(Autodesk.Revit.DB.SketchPlane existingSketchPlane)
 {
     SafeInit(() => InitSketchPlane(existingSketchPlane));
 }
예제 #30
0
        /// <summary>
        /// Check if the position of a ModelText has changed, given the original ModelText Element
        /// and the new position in the SketchPlane
        /// </summary>
        /// <param name="oldModelText"></param>
        /// <param name="newSketchPlane"></param>
        /// <param name="xCoordinateInPlane"></param>
        /// <param name="yCoordinateInPlane"></param>
        /// <returns></returns>
        private static bool PositionUnchanged(Autodesk.Revit.DB.ModelText oldModelText, Autodesk.Revit.DB.SketchPlane newSketchPlane, double xCoordinateInPlane, double yCoordinateInPlane)
        {
            var oldPosition = ((LocationPoint)oldModelText.Location).Point;

            var plane       = newSketchPlane.GetPlane();
            var newPosition = plane.Origin + plane.XVec * xCoordinateInPlane + plane.YVec * yCoordinateInPlane;

            return(oldPosition.IsAlmostEqualTo(newPosition));
        }
예제 #31
0
        public static Dictionary <string, object> ByRoom(string familyTemplatePath, global::Revit.Elements.Room room, string materialName, global::Revit.Elements.Category category, string subcategory = "")
        {
            //variables
            global::Revit.Elements.Element   famInstance = null;
            Autodesk.Revit.DB.FamilyInstance internalFam = null;
            bool fileFound = false;

            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            UIApplication uiapp            = new UIApplication(doc.Application);

            //convert the room to an Autodesk.Revit.DB representation
            Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement;
            string name = internalRoom.Name;

            //we close all of the families because we need to swap documents
            foreach (Document d in uiapp.Application.Documents)
            {
                if (d.IsFamilyDocument)
                {
                    d.Close(false);
                }
            }
            //create the new family document in the background and store it in memory
            Document familyDocument = uiapp.Application.NewFamilyDocument(familyTemplatePath);
            //instantiate a material element id and try to get the material that was specified
            ElementId material = null;
            FilteredElementCollector materialCollector = new FilteredElementCollector(familyDocument).OfClass(typeof(Autodesk.Revit.DB.Material));

            foreach (var m in materialCollector)
            {
                if (m.Name.ToLower().Replace(" ", "") == materialName.ToLower().Replace(" ", ""))
                {
                    material = m.Id;
                }
            }
            //close Dynamo's open transaction, we need to do this because we open a new Revit API transaction in the family document (This is document switching)
            TransactionManager.Instance.ForceCloseTransaction();
            //start creating the families.
            Transaction trans = new Transaction(familyDocument, "Generate Families Ya'll");

            trans.Start();
            //set the family category
            Autodesk.Revit.DB.Category familyCategory = familyDocument.Settings.Categories.get_Item(category.Name);
            familyDocument.OwnerFamily.FamilyCategory = familyCategory;
            //get the subcategory for the solids
            Autodesk.Revit.DB.Category subCategory = null;
            foreach (Autodesk.Revit.DB.Category c in familyCategory.SubCategories)
            {
                if (c.Name.ToLower() == subcategory.ToLower())
                {
                    subCategory = c;
                }
            }
            //get the height of the thing
            double height = room.Height;
            //get the curves
            IList <IList <BoundarySegment> > boundary = internalRoom.GetBoundarySegments(new SpatialElementBoundaryOptions());

            //generate a plane
            Autodesk.Revit.DB.Plane       revitPlane  = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(Vector.ZAxis().ToXyz(), new XYZ(0, 0, 0));
            Autodesk.Revit.DB.SketchPlane sketchPlane = SketchPlane.Create(familyDocument, revitPlane);
            //the curve arrays to generate solids and voids in family
            CurveArray    curveArray        = new CurveArray();
            CurveArrArray curveArrArray     = new CurveArrArray();
            CurveArray    curveArrayVoid    = new CurveArray();
            CurveArrArray curveArrArrayVoid = new CurveArrArray();
            //to perform  the cut action on the solid with the voids
            CombinableElementArray ceArray = new CombinableElementArray();
            //transform bizness
            Point            roomCentroid  = room.BoundingBox.ToCuboid().Centroid();
            Point            locationPoint = Point.ByCoordinates(roomCentroid.X, roomCentroid.Y, 0);
            CoordinateSystem oldCS         = CoordinateSystem.ByOrigin(locationPoint);
            CoordinateSystem newCS         = CoordinateSystem.ByOrigin(0, 0, 0);

            //flag to step through the boundaries.
            int flag = 0;

            while (flag < boundary.Count)
            {
                //the first set of curves is the solid's boundary
                if (flag == 0)
                {
                    //generate the solid form which is the first item in the boundary segments.
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArray.Append(movedCurve.ToRevitType());
                    }
                    curveArrArray.Append(curveArray);
                    Extrusion solidExtrusion = familyDocument.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height);
                    if (material != null)
                    {
                        //Set the material
                        Autodesk.Revit.DB.Parameter matParam = solidExtrusion.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);
                        matParam.Set(material);
                    }
                    //try to set the subcategory
                    if (subCategory != null)
                    {
                        solidExtrusion.Subcategory = subCategory;
                    }
                }
                //subsequent lists of curves are representative of the voids
                else
                {
                    //clear the curves from the collection for all items after the second one. (index 2+)
                    if (!curveArrayVoid.IsEmpty)
                    {
                        curveArrayVoid.Clear();
                        curveArrArrayVoid.Clear();
                        ceArray.Clear();
                    }
                    //generate the void form
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArrayVoid.Append(movedCurve.ToRevitType());
                    }
                    curveArrArrayVoid.Append(curveArrayVoid);
                    Extrusion voidExtrusion = familyDocument.FamilyCreate.NewExtrusion(false, curveArrArrayVoid, sketchPlane, height);

                    //try to combine things
                    foreach (Extrusion genericForm in new FilteredElementCollector(familyDocument).OfClass(typeof(Extrusion))
                             .Cast <Extrusion>())
                    {
                        ceArray.Append(genericForm);
                    }
                    //to add the void to the solid
                    familyDocument.CombineElements(ceArray);
                }
                flag++;
            }
            familyDocument.Regenerate();
            trans.Commit();

            Autodesk.Revit.DB.Family fam = null;
            //build the temporary path
            string familyFilePath = Path.GetTempPath() + name + ".rfa";

            SaveAsOptions opt = new SaveAsOptions();

            opt.OverwriteExistingFile = true;
            familyDocument.SaveAs(familyFilePath, opt);
            familyDocument.Close(false);

            TransactionManager.Instance.ForceCloseTransaction();
            Transaction trans2 = new Transaction(doc, "Attempting to place or update Room family instances.");

            trans2.Start();
            IFamilyLoadOptions loadOptions = new FamilyImportOptions();
            bool variable = true;

            loadOptions.OnFamilyFound(true, out variable);
            doc.LoadFamily(familyFilePath, loadOptions, out fam);

            FamilySymbol familySymbol = (FamilySymbol)doc.GetElement(fam.GetFamilySymbolIds().First());
            //try to find if it is placed already
            FilteredElementCollector col = new FilteredElementCollector(doc);
            //get built in category from user viewable category
            BuiltInCategory myCatEnum =
                (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            foreach (Autodesk.Revit.DB.Element e in col.WhereElementIsNotElementType().OfCategory(myCatEnum).ToElements())
            {
                Autodesk.Revit.DB.FamilySymbol type = (FamilySymbol)doc.GetElement(e.GetTypeId());
                if (type.FamilyName.Equals(name))
                {
                    fileFound   = true;
                    internalFam = e as Autodesk.Revit.DB.FamilyInstance;
                }
            }
            //place families that are not placed
            if (fileFound == false)
            {
                if (!familySymbol.IsActive)
                {
                    familySymbol.Activate();
                }

                internalFam = doc.Create.NewFamilyInstance(new XYZ(roomCentroid.X, roomCentroid.Y, 0), familySymbol, internalRoom.Level,
                                                           StructuralType.NonStructural);
            }
            trans2.Commit();
            //delete the temp file
            File.Delete(familyFilePath);
            //cast to Dynamo type for output and location updating (if necessary)
            famInstance = internalFam.ToDSType(true);
            if (fileFound)
            {
                famInstance.SetLocation(locationPoint);
            }
            //returns the outputs
            var outInfo = new Dictionary <string, object>
            {
                { "familyInstance", famInstance }
            };

            return(outInfo);
        }