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

            if (doc.IsFamilyDocument)
            {
                Util.ErrorMsg(
                    "This command requires an active document.");

                return(Result.Failed);
            }

            int nDeleted = RemoveDwfLinkUsingDelete(doc);

            int nDeleted2 = RemoveDwfLinkUsingExternalFileUtils(doc);

            return(Result.Succeeded);
        }
        /// <summary>
        /// Create three new spot elevations on the top
        /// surface of a beam, at its midpoint and both
        /// endpoints.
        /// </summary>
        bool NewSpotElevation(Document doc)
        {
            //Document doc = ActiveDocument; // for VSTA macro version

            View westView = FindView(doc, "West");

            if (null == westView)
            {
                Util.ErrorMsg("No view found named 'West'.");
                return(false);
            }

            // define the hard-coded beam element id:

            //ElementId instanceId = Create.NewElementId();
            //instanceId.IntegerValue = 230298;

            ElementId instanceId = new ElementId(230298);

            FamilyInstance beam = doc.GetElement(
                instanceId) as FamilyInstance;

            if (null == beam)
            {
                Util.ErrorMsg("Beam 230298 not found.");
                return(false);
            }

            //doc.BeginTransaction(); // for VSTA macro version

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Spot Elevation");

                Reference topReference
                    = FindTopMostReference(beam);

                LocationCurve lCurve = beam.Location
                                       as LocationCurve;

                for (int i = 0; i < 3; ++i)
                {
                    XYZ lCurvePnt = lCurve.Curve.Evaluate(
                        0.5 * i, true);

                    XYZ bendPnt = lCurvePnt.Add(
                        Create.NewXYZ(0, 1, 4));

                    XYZ endPnt = lCurvePnt.Add(
                        Create.NewXYZ(0, 2, 4));

                    // NewSpotElevation arguments:
                    // View view, Reference reference,
                    // XYZ origin, XYZ bend, XYZ end, XYZ refPt,
                    // bool hasLeader

                    SpotDimension d = doc.Create.NewSpotElevation(
                        westView, topReference, lCurvePnt, bendPnt,
                        endPnt, lCurvePnt, true);
                }

                //doc.EndTransaction(); // for VSTA macro version

                t.Commit();
            }
            return(true);
        }
示例#3
0
        /// <summary>
        /// Create a new swept blend form.
        /// The NewSweptBlend method requires the
        /// input profile to be in the XY plane.
        /// </summary>
        public void CreateNewSweptBlend(Document doc)
        {
            Debug.Assert(doc.IsFamilyDocument,
                         "this method will only work in a family document");

            Application app = doc.Application;

            Autodesk.Revit.Creation.Application creapp
                = app.Create;

            CurveArrArray curvess0
                = creapp.NewCurveArrArray();

            CurveArray curves0 = new CurveArray();

            XYZ p00 = creapp.NewXYZ(0, 7.5, 0);
            XYZ p01 = creapp.NewXYZ(0, 15, 0);

            // changing Z to 1 in the following line fails:

            XYZ p02 = creapp.NewXYZ(-1, 10, 0);

            //curves0.Append( creapp.NewLineBound( p00, p01 ) ); // 2013

            curves0.Append(Line.CreateBound(p00, p01)); // 2014
            curves0.Append(Line.CreateBound(p01, p02));
            curves0.Append(Line.CreateBound(p02, p00));
            curvess0.Append(curves0);

            CurveArrArray curvess1 = creapp.NewCurveArrArray();
            CurveArray    curves1  = new CurveArray();

            XYZ p10 = creapp.NewXYZ(7.5, 0, 0);
            XYZ p11 = creapp.NewXYZ(15, 0, 0);

            // changing the Z value in the following line fails:

            XYZ p12 = creapp.NewXYZ(10, -1, 0);

            curves1.Append(Line.CreateBound(p10, p11));
            curves1.Append(Line.CreateBound(p11, p12));
            curves1.Append(Line.CreateBound(p12, p10));
            curvess1.Append(curves1);

            SweepProfile sweepProfile0
                = creapp.NewCurveLoopsProfile(curvess0);

            SweepProfile sweepProfile1
                = creapp.NewCurveLoopsProfile(curvess1);

            XYZ   pnt10 = new XYZ(5, 0, 0);
            XYZ   pnt11 = new XYZ(0, 20, 0);
            Curve curve = Line.CreateBound(pnt10, pnt11);

            XYZ normal = XYZ.BasisZ;

            SketchPlane splane = CreateSketchPlane(
                doc, normal, XYZ.Zero);

            try
            {
                SweptBlend sweptBlend = doc.FamilyCreate.NewSweptBlend(
                    true, curve, splane, sweepProfile0, sweepProfile1);
            }
            catch (Exception ex)
            {
                Util.ErrorMsg("NewSweptBlend exception: " + ex.Message);
            }
        }
        /// <summary>
        /// Create a new shared parameter
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="cat">Category to bind the parameter definition</param>
        /// <param name="nameSuffix">Parameter name suffix</param>
        /// <param name="typeParameter">Create a type parameter? If not, it is an instance parameter.</param>
        /// <returns></returns>
        bool CreateSharedParameter(
            Document doc,
            Category cat,
            int nameSuffix,
            bool typeParameter)
        {
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca
                = app.Create;

            // get or set the current shared params filename:

            string filename
                = app.SharedParametersFilename;

            if (0 == filename.Length)
            {
                string       path = _filename;
                StreamWriter stream;
                stream = new StreamWriter(path);
                stream.Close();
                app.SharedParametersFilename = path;
                filename = app.SharedParametersFilename;
            }

            // get the current shared params file object:

            DefinitionFile file
                = app.OpenSharedParameterFile();

            if (null == file)
            {
                Util.ErrorMsg(
                    "Error getting the shared params file.");

                return(false);
            }

            // get or create the shared params group:

            DefinitionGroup group
                = file.Groups.get_Item(_groupname);

            if (null == group)
            {
                group = file.Groups.Create(_groupname);
            }

            if (null == group)
            {
                Util.ErrorMsg(
                    "Error getting the shared params group.");

                return(false);
            }

            // set visibility of the new parameter:

            // Category.AllowsBoundParameters property
            // indicates if a category can have user-visible
            // shared or project parameters. If it is false,
            // it may not be bound to visible shared params
            // using the BindingMap. Please note that
            // non-user-visible parameters can still be
            // bound to these categories.

            bool visible = cat.AllowsBoundParameters;

            // get or create the shared params definition:

            string defname = _defname + nameSuffix.ToString();

            Definition definition = group.Definitions.get_Item(
                defname);

            if (null == definition)
            {
                //definition = group.Definitions.Create( defname, _deftype, visible ); // 2014

                ExternalDefinitionCreationOptions opt
                    = new ExternalDefinitionCreationOptions(
                          defname, _deftype);

                opt.Visible = visible;

                definition = group.Definitions.Create(opt); // 2015
            }
            if (null == definition)
            {
                Util.ErrorMsg(
                    "Error creating shared parameter.");

                return(false);
            }

            // create the category set containing our category for binding:

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(cat);

            // bind the param:

            try
            {
                Binding binding = typeParameter
          ? ca.NewTypeBinding(catSet) as Binding
          : ca.NewInstanceBinding(catSet) as Binding;

                // we could check if it is already bound,
                // but it looks like insert will just ignore
                // it in that case:

                doc.ParameterBindings.Insert(definition, binding);

                // we can also specify the parameter group here:

                //doc.ParameterBindings.Insert( definition, binding,
                //  BuiltInParameterGroup.PG_GEOMETRY );

                Debug.Print(
                    "Created a shared {0} parameter '{1}' for the {2} category.",
                    (typeParameter ? "type" : "instance"),
                    defname, cat.Name);
            }
            catch (Exception ex)
            {
                Util.ErrorMsg(string.Format(
                                  "Error binding shared parameter to category {0}: {1}",
                                  cat.Name, ex.Message));
                return(false);
            }
            return(true);
        }
        Result IExternalCommand.Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // cache admin data
            _appUI = commandData.Application;
            _app   = _appUI.Application;
            _docUI = commandData.Application.ActiveUIDocument;
            _doc   = _docUI.Document;

            try // generic
            {
                // Current View must be Sheet
                ViewSheet sheet = _doc.ActiveView as ViewSheet;
                if (null == sheet)
                {
                    Util.ErrorMsg("Current View is NOT a Sheet!");
                    return(Result.Cancelled);
                }

                // There must be a Floor Plan named "Level 0"
                // which is the "master" to align to
                Viewport vpMaster = null;
                // There must be at least one more Floor Plan
                // View to align (move)
                List <Viewport> vpsSlave = new List <Viewport>();
                // Find them:
                foreach (ElementId idVp in sheet.GetAllViewports())
                {
                    Viewport vp = _doc.GetElement(idVp) as Viewport;
                    ViewRvt  v  = _doc.GetElement(vp.ViewId) as ViewRvt;
                    if (v.ViewType == ViewType.FloorPlan)
                    {
                        if (v.Name.Equals("Level 0", StringComparison
                                          .CurrentCultureIgnoreCase))
                        {
                            vpMaster = vp;
                        }
                        else
                        {
                            vpsSlave.Add(vp);
                        }
                    } //if FloorPlan
                }     //foreeach idVp

                // Check if got them all
                if (null == vpMaster)
                {
                    Util.ErrorMsg("NO 'Level 0' Floor Plan on the Sheet!");
                    return(Result.Cancelled);
                }
                else if (vpsSlave.Count == 0)
                {
                    Util.ErrorMsg("NO other Floor Plans to adjust on the Sheet!");
                    return(Result.Cancelled);
                }

                // Process Master
                // --------------

                XYZ     ptMasterVpCenter = vpMaster.GetBoxCenter();
                ViewRvt viewMaster       = _doc.GetElement(
                    vpMaster.ViewId) as ViewRvt;
                double scaleMaster = viewMaster.Scale;

                // Process Slaves
                // --------------

                using (Transaction t = new Transaction(_doc))
                {
                    t.Start("Set Box Centres");

                    foreach (Viewport vpSlave in vpsSlave)
                    {
                        XYZ     ptSlaveVpCenter = vpSlave.GetBoxCenter();
                        ViewRvt viewSlave       = _doc.GetElement(
                            vpSlave.ViewId) as ViewRvt;
                        double scaleSlave = viewSlave.Scale;
                        // MUST be the same scale, otherwise can't really overlap
                        if (scaleSlave != scaleMaster)
                        {
                            continue;
                        }

                        // Work out how to move the center of Slave
                        // Viewport to coincide model-wise with Master
                        // (must use center as only Viewport.SetBoxCenter
                        // is provided in API)
                        // We can ignore View.Outline as Viewport.GetBoxOutline
                        // is ALWAYS the same dimensions enlarged by
                        // 0.01 ft in each direction.
                        // This guarantees that the center of View is
                        // also center of Viewport, BUT there is a
                        // problem when any Elevation Symbols outside
                        // the crop box are visible (can't work out why
                        // - BUG?, or how to calculate it all if BY-DESIGN)

                        BoundingBoxXYZ bbm = viewMaster.CropBox;
                        BoundingBoxXYZ bbs = viewSlave.CropBox;

                        // 0) Center points in WCS
                        XYZ wcsCenterMaster = 0.5 * bbm.Min.Add(bbm.Max);
                        XYZ wcsCenterSlave  = 0.5 * bbs.Min.Add(bbs.Max);

                        // 1) Delta (in model's feet) of the slave center w.r.t master center
                        double deltaX = wcsCenterSlave.X - wcsCenterMaster.X;
                        double deltaY = wcsCenterSlave.Y - wcsCenterMaster.Y;

                        // 1a) Scale to Delta in Sheet's paper-space feet
                        deltaX *= 1.0 / (double)scaleMaster;
                        deltaY *= 1.0 / (double)scaleMaster;

                        // 2) New center point for the slave viewport, so *models* "overlap":
                        XYZ newCenter = new XYZ(
                            ptMasterVpCenter.X + deltaX,
                            ptMasterVpCenter.Y + deltaY,
                            ptSlaveVpCenter.Z);
                        vpSlave.SetBoxCenter(newCenter);
                    }
                    t.Commit();
                }
            }
            catch (Exception ex)
            {
                Util.ErrorMsg("Generic exception: " + ex.Message);
                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
        // This has been mentioned in this post from 2016 but maybe it's worth bringing up again as 2018 hasn't resolved the issue yet.
        // As far as I can tell, the Face.Intersect( face) method always returns FaceIntersectionFaceResult.Intersecting - or I am not implementing it correctly.When I run the code below in a view with a single wall and single floor, each face to face test returns an intersection. Can someone please verify (maybe 2019)?
        // https://forums.autodesk.com/t5/revit-api-forum/get-conection-type-and-geometry-between-two-elements-from-the/m-p/6465671
        // https://forums.autodesk.com/t5/revit-api-forum/surprising-results-from-face-intersect-face-method/m-p/8079881
        // /a/doc/revit/tbc/git/a/img/intersect_strange_result.png
        // /a/doc/revit/tbc/git/a/img/floor_wall_disjunct.png
        void TestIntersect(Document doc)
        {
            View view = doc.ActiveView;

            var list = new FilteredElementCollector(doc, view.Id)
                       .WhereElementIsNotElementType()
                       .Where(e => e is Wall || e is Floor);

            int n = list.Count();

            Element floor = null;
            Element wall  = null;

            if (2 == n)
            {
                floor = list.First() as Floor;
                if (null == floor)
                {
                    floor = list.Last() as Floor;
                    wall  = list.First() as Wall;
                }
                else
                {
                    wall = list.Last() as Wall;
                }
            }

            if (null == floor || null == wall)
            {
                Util.ErrorMsg("Please run this command in a "
                              + "document with just one floor and one wall "
                              + "with no mutual intersection");
            }
            else
            {
                Options            opt        = new Options();
                IEnumerable <Face> floorFaces = GetFaces(floor);
                IEnumerable <Face> wallFaces  = GetFaces(wall);
                n = 0;
                foreach (var f1 in floorFaces)
                {
                    foreach (var f2 in wallFaces)
                    {
                        if (f1.Intersect(f2)
                            == FaceIntersectionFaceResult.Intersecting)
                        {
                            ++n;

                            if (System.Windows.Forms.MessageBox.Show(
                                    "Intersects", "Continue",
                                    System.Windows.Forms.MessageBoxButtons.OKCancel,
                                    System.Windows.Forms.MessageBoxIcon.Exclamation)
                                == System.Windows.Forms.DialogResult.Cancel)
                            {
                                return;
                            }
                        }
                    }
                }
                Debug.Print("{0} face-face intersection{1}.",
                            n, Util.PluralSuffix(n));
            }
        }