Example #1
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            IEnumerable <Rhino.Geometry.Point3d> points
        )
        {
            var element = PreviousElement(doc, Iteration);

            try
            {
                if (element?.Pinned ?? true)
                {
                    var scaleFactor = 1.0 / Revit.ModelUnits;
                    if (scaleFactor != 1.0)
                    {
                        points = points.Select(p => p * scaleFactor);
                    }

                    element = TopographySurface.Create(doc, points.ToHost().ToList());
                }
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
            }
            finally
            {
                ReplaceElement(doc, DA, Iteration, element);
            }
        }
Example #2
0
        private Topography(IList <XYZ> points)
        {
            //Phase 1 - Check to see if the object exists and should be rebound
            var oldSurf =
                ElementBinder.GetElementFromTrace <TopographySurface>(Document);

            var document = DocumentManager.Instance.CurrentDBDocument;

            //Phase 2- There was no existing point, create one
            TransactionManager.Instance.EnsureInTransaction(Document);

            var topo = TopographySurface.Create(document, points);

            InternalSetTopographySurface(topo);

            TransactionManager.Instance.TransactionTaskDone();

            if (oldSurf != null)
            {
                ElementBinder.CleanupAndSetElementForTrace(Document, this.InternalElement);
            }
            else
            {
                ElementBinder.SetElementForTrace(this.InternalElement);
            }
        }
Example #3
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user canceled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                Document document = commandData.Application.ActiveUIDocument.Document;

                TrianglesData trianglesData = TrianglesData.Load();

                using (Transaction tran = new Transaction(document, "CreateTrianglesTopography"))
                {
                    tran.Start();
                    // Creates a new topography surface element from facets and adds it to the document.
                    IList <PolymeshFacet> triangleFacets = new List <PolymeshFacet>();
                    foreach (List <int> facet in trianglesData.Facets)
                    {
                        triangleFacets.Add(new PolymeshFacet(facet[0], facet[1], facet[2]));
                    }
                    TopographySurface topoSurface = TopographySurface.Create(document, trianglesData.Points, triangleFacets);
                    Parameter         name        = topoSurface.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.ROOM_NAME);
                    if (name != null)
                    {
                        name.Set("CreateTrianglesTopography");
                    }
                    tran.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Example #4
0
        public ApplicationPlaceholderObject TopographyToNative(Topography speckleSurface)
        {
            var docObj = GetExistingElementByApplicationId(((Base)speckleSurface).applicationId);

            var pts = new List <XYZ>();

            for (int i = 0; i < speckleSurface.displayMesh.vertices.Count; i += 3)
            {
                var point = new Geometry.Point(speckleSurface.displayMesh.vertices[i], speckleSurface.displayMesh.vertices[i + 1], speckleSurface.displayMesh.vertices[i + 2], speckleSurface.displayMesh.units);
                pts.Add(PointToNative(point));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var revitSurface = TopographySurface.Create(Doc, pts);

            if (speckleSurface is RevitTopography rt)
            {
                SetInstanceParameters(revitSurface, rt);
            }
            //Report.Log($"Created Topography {revitSurface.Id}");
            return(new ApplicationPlaceholderObject {
                applicationId = ((Base)speckleSurface).applicationId, ApplicationGeneratedId = revitSurface.UniqueId, NativeObject = revitSurface
            });
        }
Example #5
0
        public static TopographySurface ToNative(this Topography mySurface)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(mySurface.ApplicationId, mySurface.Type);

            var pts = new List <XYZ>();

            for (int i = 0; i < mySurface.Vertices.Count; i += 3)
            {
                pts.Add(new XYZ(mySurface.Vertices[i] * Scale, mySurface.Vertices[i + 1] * Scale, mySurface.Vertices[i + 2] * Scale));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);

                // TODO: Can't start a transaction here as we have started a global transaction for the creation of all objects.
                // TODO: Let each individual ToNative method handle its own transactions. It's a big change, so will leave for later.

                //var srf = (TopographySurface) docObj;

                //using( TopographyEditScope e = new TopographyEditScope( Doc, "Speckle Topo Edit" ) )
                //{
                //  e.Start(srf.Id);
                //  srf.DeletePoints( srf.GetPoints() );
                //  srf.AddPoints( pts );
                //  e.Commit( null );
                //}
                //return srf;
            }

            return(TopographySurface.Create(Doc, pts));
        }
        public ApplicationPlaceholderObject TopographyToNative(Topography speckleSurface)
        {
            var docObj = GetExistingElementByApplicationId(((Base)speckleSurface).applicationId);

            var pts = new List <XYZ>();

            for (int i = 0; i < speckleSurface.baseGeometry.vertices.Count; i += 3)
            {
                pts.Add(new XYZ(
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i], speckleSurface.baseGeometry.units),
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i + 1], speckleSurface.baseGeometry.units),
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i + 2], speckleSurface.baseGeometry.units)));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var revitSurface = TopographySurface.Create(Doc, pts);

            if (speckleSurface is RevitTopography rt)
            {
                SetInstanceParameters(revitSurface, rt);
            }

            return(new ApplicationPlaceholderObject {
                applicationId = ((Base)speckleSurface).applicationId, ApplicationGeneratedId = revitSurface.UniqueId, NativeObject = revitSurface
            });
        }
Example #7
0
        void ReconstructTopographyByPoints
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            IList <Rhino.Geometry.Point3d> points,
            [Optional] IList <Rhino.Geometry.Curve> regions
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            if (scaleFactor != 1.0)
            {
                for (int p = 0; p < points.Count; ++p)
                {
                    points[p] = points[p] * scaleFactor;
                }

                if (regions != null)
                {
                    foreach (var region in regions)
                    {
                        region.Scale(scaleFactor);
                    }
                }
            }

            //if (element is TopographySurface topography)
            //{
            //  using (var editScope = new TopographyEditScope(doc, "TopographyByPoints"))
            //  {
            //    editScope.Start(element.Id);
            //    topography.DeletePoints(topography.GetPoints());
            //    topography.AddPoints(points.ToHost().ToList());

            //    foreach (var subRegionId in topography.GetHostedSubRegionIds())
            //      doc.Delete(subRegionId);

            //    editScope.Commit(new Revit.FailuresPreprocessor());
            //  }
            //}
            //else
            {
                ReplaceElement(ref element, TopographySurface.Create(doc, points.ToHost().ToList()));
            }

            if (element != null && regions != null && regions.Count > 0)
            {
                var curveLoops = regions.Select(region => CurveLoop.Create(region.ToHost().ToList())).ToList();
                SiteSubRegion.Create(doc, curveLoops, element.Id);
            }
        }
Example #8
0
        public TopographySurface Run(Document doc)
        {
            var bb0 = coordService.GetRevitCoords(osmStore.MapBottom, osmStore.MapLeft);
            var bb1 = coordService.GetRevitCoords(osmStore.MapTop, osmStore.MapLeft);
            var bb2 = coordService.GetRevitCoords(osmStore.MapTop, osmStore.MapRight);
            var bb3 = coordService.GetRevitCoords(osmStore.MapBottom, osmStore.MapRight);

            var points = new List <XYZ>()
            {
                bb0, bb1, bb2, bb3
            };

            var topography = TopographySurface.Create(doc, points);

            return(topography);
        }
Example #9
0
        public DataToTopography(Document document, List <List <XYZ> > contours, double interpolationLength = 10, double proximityTolerance = 5)
        {
            Dictionary <string, XYZ> dict = new Dictionary <string, XYZ>();
            int counter = 0;

            foreach (List <XYZ> cntr in contours)
            {
                ProcessPolygon processedContour = new ProcessPolygon(cntr);
                processedContour.LoadEdgeLengths();
                processedContour.RemoveClosePoints(proximityTolerance);
                processedContour.Interpolate(interpolationLength);
                processedContour.LoadEdgeLengths();
                foreach (XYZ item in processedContour.ProcessedPolygon)
                {
                    string key = item.X.ToString() + item.Y.ToString();
                    try
                    {
                        dict.Add(key, item);
                    }
                    catch (Exception)
                    {
                        //MessageBox.Show(er.Message);
                        counter++;
                    }
                }
            }
            this.NumberOfFailedPoints = counter;
            List <XYZ> pnts = new List <XYZ>();

            foreach (var item in dict.Keys)
            {
                XYZ pn;
                if (dict.TryGetValue(item, out pn))
                {
                    pnts.Add(pn);
                }
            }
            using (Transaction createTopography = new Transaction(document))
            {
                createTopography.Start("Create Topography");
                this.Topography = TopographySurface.Create(document, pnts);
                createTopography.Commit();
            }
        }
Example #10
0
        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            // Get the lat and long domain
            latMin = Convert.ToDouble(minLatTextBox.Text);
            latMax = Convert.ToDouble(maxLatTextBox.Text);
            lonMin = Convert.ToDouble(minLonTextBox.Text);
            lonMax = Convert.ToDouble(maxLonTextBox.Text);

            LINE.Geometry.Interval2d topoDomain = new LINE.Geometry.Interval2d(lonMin, lonMax, latMin, latMax);

            // output parameters

            string filePath = fileTextBox.Text;


            if (filePath != null && System.IO.File.Exists(filePath))
            {
                List <List <LINE.Geometry.Point3d> > pts = ElkLib.ProcessTopoFile(filePath, unitScale, topoDomain);

                List <XYZ> points = new List <XYZ>();
                for (int i = 0; i < pts.Count; i++)
                {
                    List <LINE.Geometry.Point3d> rowPoints = pts[i];

                    for (int j = 0; j < rowPoints.Count; j++)
                    {
                        XYZ revPoint = new XYZ(rowPoints[j].X, rowPoints[j].Y, rowPoints[j].Z);
                        points.Add(revPoint);
                    }
                }
                using (Transaction trans = new Transaction(doc, "Elk Create Topography"))
                {
                    trans.Start();

                    if (points.Count > 2)
                    {
                        TopographySurface topo = TopographySurface.Create(doc, points);
                    }
                    trans.Commit();
                }
            }
            Close();
        }
        void ReconstructTopographyByPoints
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            IList <Rhino.Geometry.Point3d> points,
            [Optional] IList <Rhino.Geometry.Curve> regions
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;
            var xyz         = points.Select(x => x.ChangeUnits(scaleFactor).ToHost()).ToArray();

            //if (element is TopographySurface topography)
            //{
            //  using (var editScope = new TopographyEditScope(doc, "TopographyByPoints"))
            //  {
            //    editScope.Start(element.Id);
            //    topography.DeletePoints(topography.GetPoints());
            //    topography.AddPoints(points.ToHost().ToList());

            //    foreach (var subRegionId in topography.GetHostedSubRegionIds())
            //      doc.Delete(subRegionId);

            //    editScope.Commit(new Revit.FailuresPreprocessor());
            //  }
            //}
            //else
            {
                ReplaceElement(ref element, TopographySurface.Create(doc, xyz));
            }

            if (element is object && regions?.Count > 0)
            {
                var curveLoops = regions.Select(region => CurveLoop.Create(region.ChangeUnits(scaleFactor).ToHostMultiple().ToArray())).ToArray();
                SiteSubRegion.Create(doc, curveLoops, element.Id);
            }
        }
Example #12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            Autodesk.Revit.DB.Document doc = uidoc.Document;
            Transaction trans = new Transaction(doc);

            trans.Start("交易開始");

            //訂定土體範圍
            List <XYZ> topxyz = new List <XYZ>();
            XYZ        t1     = new XYZ(-200, -200, 0);
            XYZ        t2     = new XYZ(200, -200, 0);
            XYZ        t3     = new XYZ(200, 200, 0);
            XYZ        t4     = new XYZ(-200, 200, 0);

            topxyz.Add(t1 * 1000 / 304.8);
            topxyz.Add(t2 * 1000 / 304.8);
            topxyz.Add(t3 * 1000 / 304.8);
            topxyz.Add(t4 * 1000 / 304.8);
            TopographySurface.Create(doc, topxyz);

            //開挖深度所需參數
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfClass(typeof(BuildingPadType));
            BuildingPadType bdtp = collector.FirstElement() as BuildingPadType;

            csv_read csv = new csv_read();

            csv.Main();

            //開挖各階之深度輸入
            List <double> height = new List <double>();

            foreach (var data in csv.excaLevel)
            {
                height.Add(data.Item2 * -1);
            }

            //建立開挖階數
            Level[] levlist = new Level[height.Count()];
            for (int i = 0; i != height.Count(); i++)
            {
                levlist[i]      = Level.Create(doc, height[i] * 1000 / 304.8);
                levlist[i].Name = "開挖階數" + (i + 1).ToString();
            }

            double wallLength = csv.Wall_length;
            Level  DW_level   = Level.Create(doc, wallLength * -1 * 1000 / 304.8);

            //建立回築樓層
            Level[] re_levlist = new Level[csv.back.Count()];
            for (int i = 0; i != csv.back.Count(); i++)
            {
                re_levlist[i]      = Level.Create(doc, (csv.back[i].Item2 * -1 + csv.back[i].Item3 / (2)) * 1000 / 304.8);
                re_levlist[i].Name = (csv.back[i].Item1).ToString();
            }
            Level[] all_level_list = new Level[levlist.Count() + re_levlist.Count()];
            all_level_list = levlist.Concat(re_levlist).ToArray();

            //訂定開挖範圍
            IList <CurveLoop> profileloops      = new List <CurveLoop>();
            IList <Curve>     wall_profileloops = new List <Curve>();

            //須回到原點

            XYZ[] points = new XYZ[csv.excaRange.Count()];

            for (int i = 0; i != csv.excaRange.Count(); i++)
            {
                points[i] = new XYZ(csv.excaRange[i].Item1, csv.excaRange[i].Item2, 0) * 1000 / 304.8;
            }

            CurveLoop profileloop = new CurveLoop();

            for (int i = 0; i < points.Count() - 1; i++)
            {
                Line line = Line.CreateBound(points[i], points[i + 1]);
                wall_profileloops.Add(line);
                profileloop.Append(line);
            }
            profileloops.Add(profileloop);
            Level levdeep = null;

            //建立開挖深度
            ICollection <Level> level_familyinstance = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast <Level>().ToList();

            foreach (Level lev in level_familyinstance)
            {
                if (lev.Name == levlist[levlist.Count() - 1].Name)
                {
                    BuildingPad b = BuildingPad.Create(doc, bdtp.Id, lev.Id, profileloops);
                    levdeep = lev;
                }
            }

            //建立連續壁
            IList <Curve>          inner_wall_curves       = new List <Curve>();
            double                 wall_W                  = csv.Wall_width * 1000; //連續壁厚度
            List <Wall>            inner_wall              = new List <Wall>();
            ICollection <WallType> walltype_familyinstance = new FilteredElementCollector(doc).OfClass(typeof(WallType)).Cast <WallType>().ToList();

            foreach (WallType walltype in walltype_familyinstance)
            {
                if (walltype.Name == "連續壁")
                {
                    for (int i = 0; i < points.Count <XYZ>() - 1; i++)
                    {
                        Curve c = wall_profileloops[i].CreateOffset(wall_W / 2 / 304.8, new XYZ(0, 0, -1)); //偏移連續壁厚度1/2的距離,做為建置參考線
                        Wall  w = Wall.Create(doc, c, walltype.Id, DW_level.Id, wallLength * 1000 / 304.8, 0, false, false);
                        w.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set("連續壁");
                        inner_wall.Add(w);
                    }
                }
            }

            trans.Commit();

            //取得連續壁內座標點
            XYZ[] innerwall_points           = new XYZ[points.Count <XYZ>()];
            XYZ[] for_check_innerwall_points = new XYZ[points.Count <XYZ>()]; //計算支撐中間樁之擺放界線
            for (int i = 0; i < (inner_wall.Count <Wall>()); i++)
            {
                //inner
                XYZ wall_curve_point = (inner_wall[i].Location as LocationCurve).Curve.Tessellate()[0];
                wall_curve_point              = new XYZ(wall_curve_point.X, wall_curve_point.Y, 0);
                innerwall_points[i]           = points[i] - (points[i] - wall_curve_point) * 2;
                for_check_innerwall_points[i] = points[i] - (points[i] - wall_curve_point) * 1.4; //計算支撐中間樁之擺放界線
            }
            innerwall_points[points.Count <XYZ>() - 1]           = innerwall_points[0];
            for_check_innerwall_points[points.Count <XYZ>() - 1] = for_check_innerwall_points[0];

            //取得側牆profile
            IList <CurveLoop> bdtpCurve = new List <CurveLoop>();
            IList <Curve>     side_wall_profileloops = new List <Curve>();
            CurveLoop         bdtploop = new CurveLoop();

            for (int i = 0; i < innerwall_points.Count() - 1; i++)
            {
                Line line = Line.CreateBound(innerwall_points[i], innerwall_points[i + 1]);
                side_wall_profileloops.Add(line);
                bdtploop.Append(line);
            }

            //trans.commit();

            trans.Start("inner_buildingpad");
            // /*
            bdtpCurve.Add(bdtploop);
            //建立開挖深度
            ICollection <Level> level_family = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast <Level>().ToList();

            foreach (Level lev in level_family)
            {
                if (lev.Name == levlist[levlist.Count() - 1].Name)
                {
                    BuildingPad b = BuildingPad.Create(doc, bdtp.Id, lev.Id, bdtpCurve);
                    //b.get_Parameter(BuiltInParameter.)
                    //b.LookupParameter("厚度").SetValueString("1");
                    levdeep = lev;
                }
            }
            // */
            trans.Commit();

            trans.Start("side_wall");
            //建立側牆
            List <Wall> side_wall = new List <Wall>();

            foreach (WallType walltype in walltype_familyinstance)
            {
                if (walltype.Name == "側牆")
                {
                    for (int i = 0; i < csv.sidewall.Count; i++)
                    {
                        double floor_width  = csv.back[i].Item3 * 1000 / 304.8;                                   //set the width to a new value
                        double floor_deep   = -csv.back[i].Item2 * 1000 / 304.8;
                        double floor_bottom = (floor_deep + floor_width / 2);                                     //側牆底部高程點(考慮厚度做offset後-往上半個厚度)
                        double floor_top    = (csv.back[i + 1].Item2 + csv.back[i + 1].Item3 / 2) * 1000 / 304.8; //側牆頂部高程點(考慮厚度做offset後-往下半個厚度)
                        for (int j = 0; j < points.Count <XYZ>() - 1; j++)
                        {
                            Curve side_c = side_wall_profileloops[j].CreateOffset((csv.sidewall[i].Item2 * 1000 / 2) / 304.8, new XYZ(0, 0, -1)); //此步驟為偏移擋土牆厚度1/2距離,作為建置參考線
                            Wall  side_w = Wall.Create(doc, side_c, walltype.Id, re_levlist[i].Id, (floor_bottom * (-1) - floor_top), 0, false, false);
                            side_w.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set(csv.sidewall[i].Item1 + "側牆");
                            side_wall.Add(side_w);
                        }
                    }
                }
            }
            trans.Commit();

            //取得側牆牆點座標
            CurveArray profileloops_array = new CurveArray();

            XYZ[] sidewall_points = new XYZ[points.Count <XYZ>()];
            for (int i = 0; i < (inner_wall.Count <Wall>()); i++)
            {
                //side
                XYZ side_wall_curve_point = (side_wall[i].Location as LocationCurve).Curve.Tessellate()[0];
                side_wall_curve_point = new XYZ(side_wall_curve_point.X, side_wall_curve_point.Y, 0);
                sidewall_points[i]    = innerwall_points[i] - (innerwall_points[i] - side_wall_curve_point) * 2;
            }
            sidewall_points[points.Count <XYZ>() - 1] = sidewall_points[0];

            //建立底板範圍
            for (int i = 0; i < points.Count() - 1; i++)
            {
                Line line = Line.CreateBound(innerwall_points[i], innerwall_points[i + 1]);
                profileloops_array.Append(line);
            }

            trans.Start("建立底板");

            //建立底板類型及實作元件
            ICollection <FloorType> family = new FilteredElementCollector(doc).OfClass(typeof(FloorType)).Cast <FloorType>().ToList();
            FloorType floor_type           = family.Where(x => x.Name == "通用 300mm").First();
            int       base_control         = 0;

            foreach (Tuple <string, double, double, double> base_tuple in csv.back)
            {
                FloorType newFamSym = null;
                try { newFamSym = floor_type.Duplicate(base_tuple.Item1) as FloorType; } catch { newFamSym = family.Where(x => x.Name == base_tuple.Item1).First(); }
                double floor_width  = base_tuple.Item3 * 1000 / 304.8; //set the width to a new value
                double floor_deep   = base_tuple.Item2 * -1 * 1000 / 304.8;
                double floor_offset = (floor_deep + floor_width / 2) * 304.8;
                newFamSym.GetCompoundStructure().GetLayers()[0].Width = floor_width;
                CompoundStructure ly = newFamSym.GetCompoundStructure();
                ly.SetLayerWidth(0, floor_width);
                newFamSym.SetCompoundStructure(ly);
                Floor floor = doc.Create.NewFloor(profileloops_array, newFamSym as FloorType, re_levlist[base_control], false);
                floor.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set(base_tuple.Item1);
                floor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).SetValueString("0");
                base_control += 1;
            }
            trans.Commit();

            //取得所有XY數值
            List <double> Xs = new List <double>();
            List <double> Ys = new List <double>();

            double[] slope = new double[inner_wall.Count <Wall>()];
            double[] bias  = new double[inner_wall.Count <Wall>()];
            for (int i = 0; i < (innerwall_points.Count <XYZ>()); i++)
            {
                Xs.Add(innerwall_points[i].X);
                Ys.Add(innerwall_points[i].Y);
                if (i < slope.Count())
                {
                    if (innerwall_points[i + 1].X - innerwall_points[i].X == 0)
                    {
                        slope[i] = 20172018;
                        bias[i]  = innerwall_points[i + 1].X;
                    }
                    else
                    {
                        slope[i] = (innerwall_points[i + 1].Y - innerwall_points[i].Y) / (innerwall_points[i + 1].X - innerwall_points[i].X);
                        if (slope[i] == 0 || Math.Abs(slope[i]) < 0.0000001)
                        {
                            bias[i] = innerwall_points[i + 1].Y;
                        }
                        else
                        {
                            bias[i] = innerwall_points[i + 1].Y - slope[i] * innerwall_points[i + 1].X;
                        }
                    }
                }
            }

            Transaction trans_2 = new Transaction(doc);

            trans_2.Start("交易開始");
            //開始建立中間樁
            double columns_dis = csv.centralCol[0].Item1 * 1000 / 304.8; //中間樁間距
            ICollection <FamilySymbol> columns_familyinstance = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();

            foreach (FamilySymbol column_type in columns_familyinstance)
            {
                if (column_type.Name == "中間樁")
                {
                    for (int j = 0; j < (Math.Abs(Ys.Max() - Ys.Min()) / columns_dis - 1); j++)
                    {
                        for (int i = 0; i < (Math.Abs(Xs.Max() - Xs.Min()) / columns_dis - 1); j++)
                        {
                            XYZ column_location = new XYZ(Xs.Min() + (i + 1) * columns_dis, Ys.Min() + (j + 1) * columns_dis, 0);
                            if (IsInPolygon(column_location, innerwall_points) == true)
                            {
                                //TaskDialog.Show("asd", "asd");
                                FamilyInstance column_instance = doc.Create.NewFamilyInstance(column_location, column_type, levdeep, Autodesk.Revit.DB.Structure.StructuralType.Column);
                                column_instance.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).SetValueString("0"); //中間樁長度
                                column_instance.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set("中間樁");
                            }
                        }
                    }
                }
            }

            //迴圈起始點
            for (int lev = 0; lev != csv.supLevel.Count(); lev++)
            {
                //建立圍囹
                //開始建立圍囹
                ICollection <FamilySymbol> beam_familyinstance = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();
                foreach (FamilySymbol beam_type in beam_familyinstance)
                {
                    if (beam_type.Name == "H100x100")
                    {
                        double beam_H = double.Parse(beam_type.LookupParameter("H").AsValueString());
                        double beam_B = double.Parse(beam_type.LookupParameter("B").AsValueString());
                        for (int i = 0; i < innerwall_points.Count <XYZ>() - 1; i++)
                        {
                            Curve c = null;
                            if (i == points.Count <XYZ>())
                            {
                                try { int.Parse(csv.supLevel[lev].Item1.ToString()); c = Line.CreateBound(innerwall_points[i], innerwall_points[0]).CreateOffset((beam_H) / 304.8, new XYZ(0, 0, -1)); }
                                catch { c = Line.CreateBound(sidewall_points[i], sidewall_points[0]).CreateOffset((beam_H) / 304.8, new XYZ(0, 0, -1)); }
                            }
                            else
                            {
                                try { int.Parse(csv.supLevel[lev].Item1.ToString()); c = Line.CreateBound(innerwall_points[i], innerwall_points[i + 1]).CreateOffset((beam_H) / 304.8, new XYZ(0, 0, -1)); }
                                catch { c = Line.CreateBound(sidewall_points[i], sidewall_points[i + 1]).CreateOffset((beam_H) / 304.8, new XYZ(0, 0, -1)); }
                            }
                            FamilyInstance beam = doc.Create.NewFamilyInstance(c, beam_type, levlist[0], Autodesk.Revit.DB.Structure.StructuralType.Beam);
                            beam.LookupParameter("斷面旋轉").SetValueString("90");
                            StructuralFramingUtils.DisallowJoinAtEnd(beam, 0);
                            StructuralFramingUtils.DisallowJoinAtEnd(beam, 1);
                            beam.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-圍囹");

                            //判斷圍囹之垂直深度,斜率零為負,反之為正

                            if ((i % 2 == 0))
                            {
                                beam.get_Parameter(BuiltInParameter.Y_OFFSET_VALUE).SetValueString((csv.supLevel[lev].Item2 * 1000 - beam_B / 2).ToString()); //2000為支撐階數深度,表1中
                            }
                            else
                            {
                                beam.get_Parameter(BuiltInParameter.Y_OFFSET_VALUE).SetValueString((csv.supLevel[lev].Item2 * 1000 + beam_B / 2).ToString());
                            }
                        }
                    }
                }

                //開始建立支撐
                //建立支撐

                XYZ frame_startpoint = null;
                XYZ frame_endpoint   = null;

                ICollection <FamilySymbol> frame_familyinstance = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();

                foreach (FamilySymbol frame_type in frame_familyinstance)
                {
                    if (frame_type.Name == "H100x100")
                    {
                        double frame_H = double.Parse(frame_type.LookupParameter("H").AsValueString());

                        //X向支撐
                        for (int j = 0; j < Math.Abs(Ys.Max() - Ys.Min()) / columns_dis - 1; j++)
                        {
                            for (int i = 0; i < Math.Abs(Xs.Max() - Xs.Min()) / columns_dis - 1; i++)
                            {
                                XYZ frame_location = new XYZ(Xs.Min() + (i + 1) * columns_dis, Ys.Min() + (j + 1) * columns_dis, 0);
                                frame_startpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, true)[0];
                                if (IsInPolygon(frame_location, innerwall_points) == true)
                                {
                                    try
                                    {
                                        frame_endpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, true)[1];
                                        Line           line           = Line.CreateBound(frame_startpoint, frame_endpoint);
                                        FamilyInstance frame_instance = doc.Create.NewFamilyInstance(line, frame_type, levdeep, Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                        frame_instance.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-支撐");
                                        //處理偏移與延伸問題
                                        frame_instance.get_Parameter(BuiltInParameter.Z_OFFSET_VALUE).SetValueString((csv.supLevel[lev].Item2 * -1000).ToString());
                                        frame_instance.get_Parameter(BuiltInParameter.Y_OFFSET_VALUE).SetValueString((-frame_H).ToString());
                                        try
                                        {
                                            int.Parse(csv.supLevel[lev].Item1.ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.START_EXTENSION).SetValueString((-frame_H).ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.END_EXTENSION).SetValueString((-frame_H).ToString());
                                        }
                                        catch
                                        {
                                            frame_instance.get_Parameter(BuiltInParameter.START_EXTENSION).SetValueString((-frame_H - csv.sidewall[0].Item2 * 1000).ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.END_EXTENSION).SetValueString((-frame_H - csv.sidewall[0].Item2 * 1000).ToString());
                                        }
                                        //取消接合
                                        StructuralFramingUtils.DisallowJoinAtEnd(frame_instance, 0);
                                        StructuralFramingUtils.DisallowJoinAtEnd(frame_instance, 1);

                                        //若為雙向支撐,則鏡射支撐
                                        if (csv.supLevel[lev].Item3 == 2)
                                        {
                                            ElementTransformUtils.MirrorElement(doc, frame_instance.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisY, frame_startpoint));
                                        }
                                        break;
                                    }
                                    catch { }
                                }
                            }
                        }

                        //Y向支撐
                        for (int i = 0; i < (Math.Abs(Xs.Max() - Xs.Min()) / columns_dis - 1); i++)
                        {
                            for (int j = 0; j < (Math.Abs(Ys.Max() - Ys.Min()) / columns_dis - 1); j++)
                            {
                                XYZ frame_location = new XYZ(Xs.Min() + (i + 1) * columns_dis, Ys.Min() + (1 + j) * columns_dis, 0);
                                frame_startpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, false)[0];
                                if (IsInPolygon(frame_location, innerwall_points) == true)
                                {
                                    try
                                    {
                                        frame_endpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, false)[1];
                                        Line           line           = Line.CreateBound(frame_startpoint, frame_endpoint);
                                        FamilyInstance frame_instance = doc.Create.NewFamilyInstance(line, frame_type, levdeep, Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                        frame_instance.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-支撐");

                                        //處理偏移與延伸問題

                                        frame_instance.get_Parameter(BuiltInParameter.Z_OFFSET_VALUE).SetValueString((csv.supLevel[lev].Item2 * -1000 + frame_H).ToString());//2000為支撐階數深度,表1中
                                        frame_instance.get_Parameter(BuiltInParameter.Y_OFFSET_VALUE).SetValueString((-frame_H).ToString());
                                        try
                                        {
                                            int.Parse(csv.supLevel[lev].Item1.ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.START_EXTENSION).SetValueString((-frame_H).ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.END_EXTENSION).SetValueString((-frame_H).ToString());
                                        }
                                        catch
                                        {
                                            frame_instance.get_Parameter(BuiltInParameter.START_EXTENSION).SetValueString((-frame_H - csv.sidewall[0].Item2 * 1000).ToString());
                                            frame_instance.get_Parameter(BuiltInParameter.END_EXTENSION).SetValueString((-frame_H - csv.sidewall[0].Item2 * 1000).ToString());
                                        }
                                        //取消接合
                                        StructuralFramingUtils.DisallowJoinAtEnd(frame_instance, 0);
                                        StructuralFramingUtils.DisallowJoinAtEnd(frame_instance, 1);

                                        //若為雙向支撐,則鏡射支撐
                                        if (csv.supLevel[lev].Item3 == 2)
                                        {
                                            ElementTransformUtils.MirrorElement(doc, frame_instance.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisX, frame_startpoint));
                                        }
                                        break;
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                }

                //建立斜撐
                ICollection <FamilySymbol> slopframe_symbol = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();
                foreach (FamilySymbol slopframe_type in slopframe_symbol)
                {
                    if (slopframe_type.Name == "斜撐")
                    {
                        //X向斜撐
                        for (int j = 0; j < (Math.Abs(Ys.Max() - Ys.Min()) / columns_dis - 1); j++)
                        {
                            for (int i = 0; i < (Math.Abs(Xs.Max() - Xs.Min()) / columns_dis - 1); i++)
                            {
                                XYZ frame_location = new XYZ(Xs.Min() + (i + 1) * columns_dis, Ys.Min() + (j + 1) * columns_dis, 0);
                                frame_startpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, true)[0];
                                if (IsInPolygon(frame_location, innerwall_points) == true)
                                {
                                    frame_endpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, true)[1];
                                    FamilyInstance slopframe_1 = doc.Create.NewFamilyInstance(frame_startpoint, slopframe_type, all_level_list[lev], Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                    FamilyInstance slopframe_2 = doc.Create.NewFamilyInstance(frame_endpoint, slopframe_type, all_level_list[lev], Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                    slopframe_1.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-斜撐");
                                    slopframe_2.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-斜撐");
                                    slopframe_1.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(Math.Abs(all_level_list[lev].Elevation - csv.supLevel[lev].Item2 * -1000 / 304.8 + slopframe_1.LookupParameter("支撐厚度").AsDouble() / 2));

                                    slopframe_2.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(Math.Abs(all_level_list[lev].Elevation - csv.supLevel[lev].Item2 * -1000 / 304.8 + slopframe_1.LookupParameter("支撐厚度").AsDouble() / 2));
                                    int o;
                                    if (int.TryParse(csv.supLevel[lev].Item1, out o) == false)//305為圍囹寬度,應該要查表而非指定。
                                    {
                                        slopframe_1.LookupParameter("圍囹寬度").SetValueString((305 + csv.sidewall[0].Item2 * 1000).ToString());
                                        slopframe_2.LookupParameter("圍囹寬度").SetValueString((305 + csv.sidewall[0].Item2 * 1000).ToString());
                                    }
                                    else
                                    {
                                        slopframe_1.LookupParameter("圍囹寬度").SetValueString((305).ToString());
                                        slopframe_2.LookupParameter("圍囹寬度").SetValueString((305).ToString());
                                    }
                                    //旋轉斜撐元件
                                    Line rotate_line_s = Line.CreateBound(frame_startpoint, frame_startpoint + new XYZ(0, 0, 1));
                                    Line rotate_line_e = Line.CreateBound(frame_endpoint, frame_endpoint + new XYZ(0, 0, 1));
                                    slopframe_1.Location.Rotate(rotate_line_s, 1.5 * Math.PI);
                                    slopframe_2.Location.Rotate(rotate_line_e, 0.5 * Math.PI);

                                    //鏡射斜撐元件
                                    if (csv.supLevel[lev].Item3 == 2)//雙排
                                    {
                                        ElementTransformUtils.MirrorElement(doc, slopframe_1.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisY, frame_startpoint));
                                        ElementTransformUtils.MirrorElement(doc, slopframe_2.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisY, frame_endpoint));
                                    }
                                    else//單排
                                    {
                                        ElementTransformUtils.MirrorElement(doc, slopframe_1.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisY, frame_startpoint.Add(new XYZ(0, -(slopframe_1.LookupParameter("支撐厚度").AsDouble() / 2 + slopframe_1.LookupParameter("中間樁直徑").AsDouble() / 2), 0))));
                                        ElementTransformUtils.MirrorElement(doc, slopframe_2.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisY, frame_endpoint));
                                        slopframe_2.Location.Move((new XYZ(0, -(slopframe_1.LookupParameter("支撐厚度").AsDouble() + slopframe_1.LookupParameter("中間樁直徑").AsDouble()), 0)));
                                    }

                                    break;
                                }
                            }
                        }

                        //Y向斜撐
                        for (int i = 0; i < (Math.Abs(Xs.Max() - Xs.Min()) / columns_dis - 1); i++)
                        {
                            for (int j = 0; j < (Math.Abs(Ys.Max() - Ys.Min()) / columns_dis - 1); j++)
                            {
                                XYZ frame_location = new XYZ(Xs.Min() + (i + 1) * columns_dis, Ys.Min() + (1 + j) * columns_dis, 0);
                                frame_startpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, false)[0];
                                if (IsInPolygon(frame_location, innerwall_points) == true)
                                {
                                    frame_endpoint = intersection(frame_location, for_check_innerwall_points, slope, bias, false)[1];
                                    FamilyInstance slopframe_1 = doc.Create.NewFamilyInstance(frame_startpoint, slopframe_type, all_level_list[lev], Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                    FamilyInstance slopframe_2 = doc.Create.NewFamilyInstance(frame_endpoint, slopframe_type, all_level_list[lev], Autodesk.Revit.DB.Structure.StructuralType.Beam);
                                    slopframe_1.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-斜撐");
                                    slopframe_2.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set((csv.supLevel[lev].Item1).ToString() + "-斜撐");
                                    slopframe_1.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(Math.Abs(all_level_list[lev].Elevation - csv.supLevel[lev].Item2 * -1000 / 304.8 - slopframe_1.LookupParameter("支撐厚度").AsDouble() / 2));

                                    slopframe_2.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(Math.Abs(all_level_list[lev].Elevation - csv.supLevel[lev].Item2 * -1000 / 304.8 - slopframe_2.LookupParameter("支撐厚度").AsDouble() / 2));
                                    int o;
                                    if (int.TryParse(csv.supLevel[lev].Item1, out o) == false)//305為圍囹寬度,應該要查表而非指定。
                                    {
                                        slopframe_1.LookupParameter("圍囹寬度").SetValueString((305 + csv.sidewall[0].Item2 * 1000).ToString());
                                        slopframe_2.LookupParameter("圍囹寬度").SetValueString((305 + csv.sidewall[0].Item2 * 1000).ToString());
                                    }
                                    else
                                    {
                                        slopframe_1.LookupParameter("圍囹寬度").SetValueString((305).ToString());
                                        slopframe_2.LookupParameter("圍囹寬度").SetValueString((305).ToString());
                                    }
                                    //旋轉斜撐元件
                                    Line rotate_line = Line.CreateBound(frame_endpoint, frame_endpoint + new XYZ(0, 0, 1));
                                    slopframe_2.Location.Rotate(rotate_line, Math.PI);

                                    //鏡射斜撐元件
                                    if (csv.supLevel[lev].Item3 == 2)//雙排
                                    {
                                        ElementTransformUtils.MirrorElement(doc, slopframe_1.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisX, frame_startpoint));
                                        ElementTransformUtils.MirrorElement(doc, slopframe_2.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisX, frame_endpoint));
                                    }
                                    else//單排
                                    {
                                        ElementTransformUtils.MirrorElement(doc, slopframe_1.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisX, frame_startpoint.Add(new XYZ(slopframe_1.LookupParameter("支撐厚度").AsDouble() / 2 + slopframe_1.LookupParameter("中間樁直徑").AsDouble() / 2, 0, 0))));
                                        ElementTransformUtils.MirrorElement(doc, slopframe_2.Id, Plane.CreateByNormalAndOrigin(XYZ.BasisX, frame_endpoint));
                                        slopframe_2.Location.Move((new XYZ((slopframe_1.LookupParameter("支撐厚度").AsDouble() + slopframe_1.LookupParameter("中間樁直徑").AsDouble()), 0, 0)));
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            trans_2.Commit();
            return(Result.Succeeded);
        }
Example #13
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            IEnumerable <Rhino.Geometry.Point3d> points,
            IEnumerable <Rhino.Geometry.Curve> regions
        )
        {
            var element = PreviousElement(doc, Iteration);

            if (!element?.Pinned ?? false)
            {
                ReplaceElement(doc, DA, Iteration, element);
            }
            else
            {
                try
                {
                    var scaleFactor = 1.0 / Revit.ModelUnits;
                    if (scaleFactor != 1.0)
                    {
                        points = points.Select(p => p * scaleFactor);

                        foreach (var region in regions)
                        {
                            region.Scale(scaleFactor);
                        }
                    }

                    TopographySurface topography = null;
                    //if (element is TopographySurface topography)
                    //{
                    //  using (var editScope = new TopographyEditScope(doc, "TopographyByPoints"))
                    //  {
                    //    editScope.Start(element.Id);
                    //    topography.DeletePoints(topography.GetPoints());
                    //    topography.AddPoints(points.ToHost().ToList());

                    //    foreach (var subRegionId in topography.GetHostedSubRegionIds())
                    //      doc.Delete(subRegionId);

                    //    editScope.Commit(new Revit.FailuresPreprocessor());
                    //  }
                    //}
                    //else
                    {
                        topography = CopyParametersFrom(TopographySurface.Create(doc, points.ToHost().ToList()), element);
                        element    = topography;
                    }

                    if (topography != null && regions.Any())
                    {
                        var curveLoops = regions.Select(region => CurveLoop.Create(region.ToHost().ToList())).ToList();
                        SiteSubRegion.Create(doc, curveLoops, topography.Id);
                    }

                    ReplaceElement(doc, DA, Iteration, element);
                }
                catch (Exception e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                    ReplaceElement(doc, DA, Iteration, null);
                }
            }
        }
Example #14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            try
            {
                //normalPoint = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsElementType().Where(t => t.Name.Contains("DebugPoint")).FirstOrDefault() as FamilySymbol;

                if (uidoc.ActiveView is View3D == false)
                {
                    message = Properties.Messages.BeamsFromColumns_Not3dView;
                    return(Result.Failed);
                }

                PointCloudInstance pcInstance = doc.GetElement(sel.PickObject(ObjectType.Element, new PointCloundSelectionFilter(), Properties.Messages.TopoFromPointCloud_SelectPointCloudInstance)) as PointCloudInstance;

                //Element pcInstance = doc.GetElement(sel.PickObject(ObjectType.Element));

                if (pcInstance == null)
                {
                    message = Properties.Messages.TopoFromPointCloud_InvalidPointCloud;
                    return(Result.Failed);
                }



                View3D         this3dView  = uidoc.ActiveView as View3D;
                BoundingBoxXYZ boundingBox = null;

                //Use CropBox if there is one to use
                if (this3dView.CropBoxActive == true)
                {
                    boundingBox = this3dView.CropBox;
                }
                else
                {
                    boundingBox = pcInstance.get_BoundingBox(uidoc.ActiveView);
                }

                boundingBox.Enabled = true;
                Line l1 = Line.CreateBound(boundingBox.Min, boundingBox.Max);

                double crossAngle = XYZ.BasisX.AngleOnPlaneTo(l1.Direction, XYZ.BasisZ);
                double hypotenuse = boundingBox.Min.PlaneDistanceTo(boundingBox.Max);

                double xDirDistance = hypotenuse * Math.Cos(crossAngle);
                double yDirDistance = hypotenuse * Math.Sin(crossAngle);

                double xIncrAmount = 1;
                double yIncrAmount = 1;

                EstabilishIteractionPoints(xDirDistance, ref xNumberOfDivisions, ref xIncrAmount);
                EstabilishIteractionPoints(yDirDistance, ref yNumberOfDivisions, ref yIncrAmount);

                double axIncrAmount = xIncrAmount;
                double ayIncrAmount = yIncrAmount;

                TopoPointCloudUIAdvanced currentUI = new TopoPointCloudUIAdvanced(
                    Math.Round(Utils.ConvertM.feetToM(xDirDistance), 2), Math.Round(Utils.ConvertM.feetToM(yDirDistance), 2), xNumberOfDivisions,
                    yNumberOfDivisions, Math.Round(Utils.ConvertM.feetToM(xIncrAmount), 2), Math.Round(Utils.ConvertM.feetToM(yIncrAmount), 2),
                    pointMaxQuantity);


                currentUI.ShowDialog();

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

                xNumberOfDivisions = currentUI.xNumberOfDivisions;
                yNumberOfDivisions = currentUI.yNumberOfDivisions;
                xIncrAmount        = Utils.ConvertM.mToFeet(currentUI.xIncrAmount);
                yIncrAmount        = Utils.ConvertM.mToFeet(currentUI.yIncrAmount);
                pointMaxQuantity   = currentUI.pointMaxQuantity;

                pointDist = pcInstance.GetTotalTransform().Scale *pointDist;
                IList <XYZ> topographyPointList = new List <XYZ>();

                using (Transaction t = new Transaction(doc, Properties.Messages.TopoFromPointCloud_Transaction))
                {
                    t.Start();
                    for (int i = 0; i < xNumberOfDivisions; i++)
                    {
                        for (int j = 0; j < yNumberOfDivisions; j++)
                        {
                            IList <Plane> xPlanes = CreatePlaneBound(doc, boundingBox.Min.FlattenZ(), i, j, xIncrAmount, yIncrAmount, XYZ.BasisX, XYZ.BasisY);
                            IList <Plane> yPlanes = CreatePlaneBound2(doc, boundingBox.Min.FlattenZ(), j, i, yIncrAmount, xIncrAmount, XYZ.BasisY, XYZ.BasisX);
#if R2016
                            Plane planeZ1 = new Plane(XYZ.BasisZ, new XYZ(0, 0, -9999));
                            Plane planeZ2 = new Plane(-XYZ.BasisZ, new XYZ(0, 0, 9999));
#else
                            Plane planeZ1 = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, new XYZ(0, 0, -9999));
                            Plane planeZ2 = Plane.CreateByNormalAndOrigin(-XYZ.BasisZ, new XYZ(0, 0, 9999));
#endif

                            //doc.Create.NewFamilyInstance(planeZ1.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                            //doc.Create.NewFamilyInstance(planeZ2.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                            IList <Plane> currentPlanes = xPlanes.Union(yPlanes).ToList();
                            currentPlanes.Add(planeZ1);
                            currentPlanes.Add(planeZ2);

                            PointCloudFilter ptFilter        = PointCloudFilterFactory.CreateMultiPlaneFilter(currentPlanes);
                            PointCollection  pointCollection = pcInstance.GetPoints(ptFilter, pointDist, pointMaxQuantity);

                            IList <XYZ> currentBoxPoints = new List <XYZ>();
                            foreach (CloudPoint currentCloudPoint in pointCollection)
                            {
                                XYZ currentXYZ = new XYZ(currentCloudPoint.X, currentCloudPoint.Y, currentCloudPoint.Z);
                                currentXYZ = pcInstance.GetTotalTransform().OfPoint(currentXYZ);
                                if (!ListContainsPoint(currentBoxPoints, currentXYZ))
                                {
                                    currentBoxPoints.Add(currentXYZ);
                                }
                            }

                            topographyPointList = topographyPointList.Union(currentBoxPoints).ToList();
                        }
                    }

                    if (topographyPointList.Count < 3)
                    {
                        message = Properties.Messages.TopoFromPointCloud_NotEnoughPoints;
                        return(Result.Failed);
                    }

                    TopographySurface topoSurface = TopographySurface.Create(doc, topographyPointList);

                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
                return(Result.Cancelled);
            }

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

            Selection sel = uidoc.Selection;

            try
            {
                ImportInstance currentDwg = doc.GetElement(sel.PickObject(ObjectType.Element, new CADSelectionFilter(), "Selecione um elemento DWG para criacao do terreno")) as ImportInstance;

                IList <XYZ> currentDwgPoints = Utils.GetDwgGeometryInformation.GetDwgGeometryMidPoints(Utils.DwgGeometryType.Circle, currentDwg, null);

                if (currentDwgPoints.Count < 3)
                {
                    message = "Não foram encontrados pontos suficientes para a criação da topografia";
                    return(Result.Failed);
                }

                IList <XYZ>     currentDwgPointsWithHeight = new List <XYZ>();
                IList <Element> textElements = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TextNotes).WhereElementIsNotElementType().ToList();

                foreach (XYZ currentPoint in currentDwgPoints)
                {
                    double minDist = double.PositiveInfinity;

                    TextElement nearestText = null;

                    foreach (Element currentTextElement in textElements)
                    {
                        XYZ    currentTextPosition   = (currentTextElement as TextElement).Coord;
                        XYZ    currentTextPositionZ0 = new XYZ(currentTextPosition.X, currentTextPosition.Y, 0);
                        XYZ    currentPointZ0        = new XYZ(currentPoint.X, currentPoint.Y, 0);
                        double currentDist           = currentPointZ0.DistanceTo(currentTextPositionZ0);

                        if (currentDist < minDist)
                        {
                            minDist     = currentDist;
                            nearestText = currentTextElement as TextElement;
                        }
                    }

                    if (nearestText != null)
                    {
                        string textValue = nearestText.Text;
                        double zValue    = 0;

                        if (double.TryParse(textValue, out zValue))
                        {
                            //zValue = zValue * 1000;
                            zValue = Utils.ConvertM.mToFeet(zValue);
                            XYZ currentPointWithHeight = new XYZ(currentPoint.X, currentPoint.Y, zValue);
                            currentDwgPointsWithHeight.Add(currentPointWithHeight);
                        }
                        else
                        {
                            currentDwgPointsWithHeight.Add(currentPoint);
                        }
                    }
                    else
                    {
                        currentDwgPointsWithHeight.Add(currentPoint);
                    }
                }


                using (Transaction t = new Transaction(doc, "Criar Terreno"))
                {
                    t.Start();

                    TopographySurface currentTopo = TopographySurface.Create(doc, currentDwgPointsWithHeight);

                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
Example #16
0
 private TopographySurface CreateTopographySurface(List <XYZ> points)
 {
     return(TopographySurface.Create(dynRevitSettings.Doc.Document, points));
 }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get UIDocument
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            //Get Document
            Document doc = uidoc.Document;

            //Use active view for generation
            View view = doc.ActiveView;

            try
            {
                //Pick referenceline
                Reference refTopo = uidoc.Selection.PickObject(ObjectType.Element);

                //Retrieve Element
                ElementId         topoId  = refTopo.ElementId;
                Element           topo    = doc.GetElement(topoId);
                TopographySurface surface = topo as TopographySurface;

                BoundingBoxXYZ box = surface.get_BoundingBox(view);

                XYZ max = box.Max;
                XYZ min = box.Min;

                double maxx = max.X;
                double maxy = max.Y;
                double minx = min.X;
                double miny = min.Y;

                XYZ topleft     = new XYZ(minx, maxy, 0);
                XYZ bottomright = new XYZ(maxx, miny, 0);

                double domainx = max.DistanceTo(topleft);       //Math.Abs(maxx - minx);
                double domainy = min.DistanceTo(topleft);       //Math.Abs(maxy - miny);

                int nsquaresA = Convert.ToInt32(Math.Ceiling(domainx * 10 / (GlobVars.density / 30)));
                int nsquaresB = Convert.ToInt32(Math.Ceiling(domainy * 10 / (GlobVars.density / 30)));

                double distA = domainx / nsquaresA;
                double distB = domainy / nsquaresB;

                int[] permutations;

                //Generate noise
                //double permutation to avoid overflow
                if (GlobVars.randomvals == 0)
                {
                    permutations = GlobVars.permutation;
                }
                else
                {
                    var rand = new Random();
                    IEnumerable <int> numbers = Enumerable.Range(0, 256);
                    permutations = numbers.OrderBy(x => rand.Next()).ToArray();
                }


                int[] p = new int[512];

                for (int x = 0; x < 256; x++)
                {
                    p[x]       = permutations[x];
                    p[256 + x] = permutations[x];
                }

                //List<double> zvals = new List<double>();
                double[]   zvals      = new double[(nsquaresA + 1) * (nsquaresB + 1)];
                List <XYZ> topography = new List <XYZ>();

                for (double octave = 1.0; octave < (GlobVars.nOctaves + 1); octave++)
                {
                    for (double yy = 1.0; yy < (nsquaresB + 2); yy++)
                    {
                        for (double xx = 1.0; xx < (nsquaresA + 2); xx++)
                        {
                            double noise = perlin_noise((xx / (GlobVars.speed / (2.0 * octave))), (yy / (GlobVars.speed / (2.0 * octave))), p);
                            int    indx  = (((int)yy - 1) * (nsquaresA + 1) + (int)xx - 1);

                            zvals[indx] += (noise * ((GlobVars.amplitude / 330.0) / (2.0 * octave)));

                            if ((int)octave == GlobVars.nOctaves)
                            {
                                double xval = minx + (distA * ((int)xx - 1));
                                double yval = miny + (distB * ((int)yy - 1));

                                XYZ point = new XYZ(xval, yval, zvals[indx]);

                                topography.Add(point);
                            }
                        }
                    }
                }

                IList <XYZ> toDelete = surface.GetPoints();

                //Place generated lines in Revit
                using (Transaction trans = new Transaction(doc, "Place Tree"))
                {
                    trans.Start();

                    Plane       plane       = Plane.CreateByNormalAndOrigin(min.CrossProduct(max), max);
                    SketchPlane sketchPlane = SketchPlane.Create(doc, plane);

                    TopographySurface       toposurface  = TopographySurface.Create(doc, topography);
                    ICollection <ElementId> deletedIdSet = doc.Delete(topoId);

                    trans.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Example #18
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            W.OpenFileDialog dlg = new W.OpenFileDialog();

            // select file to open

            dlg.Filter = "LandXML files (*.xml)|*.xml";

            dlg.Title = "Import LandXML and "
                        + "Create TopographySurface";

            if (dlg.ShowDialog() != W.DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(dlg.FileName);

            XmlNodeList pnts
                = xmlDoc.GetElementsByTagName("Pnts");

            char[] separator = new char[] { ' ' };
            double x = 0, y = 0, z = 0;

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

            for (int k = 0; k < pnts.Count; ++k)
            {
                for (int i = 0;
                     i < pnts[k].ChildNodes.Count; ++i)
                {
                    int j = 1;

                    string   text   = pnts[k].ChildNodes[i].InnerText;
                    string[] coords = text.Split(separator);

                    foreach (string coord in coords)
                    {
                        switch (j)
                        {
                        case 1:
                            x = Double.Parse(coord);
                            break;

                        case 2:
                            y = Double.Parse(coord);
                            break;

                        case 3:
                            z = Double.Parse(coord);
                            break;

                        default:
                            break;
                        }
                        j++;
                    }
                    pts.Add(new XYZ(x, y, z));
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Topography Surface");

                //TopographySurface surface = doc.Create.NewTopographySurface( pntList );

                //TopographySurface surface = doc.Create.NewTopographySurface( pts ); // 2013

                TopographySurface surface = TopographySurface.Create(doc, pts); // 2014

                t.Commit();
            }
            return(Result.Succeeded);
        }
Example #19
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            Selection sel = uidoc.Selection;

            try
            {
                if (uidoc.ActiveView is View3D == false)
                {
                    message = "Você deve estar em uma vista 3d para utilizar este comando. Por favor, entre em uma vista compatível e rode o comando novamente.";
                    return(Result.Failed);
                }

                PointCloudInstance pcInstance = doc.GetElement(sel.PickObject(ObjectType.Element, new PointCloundSelectionFilter(), "Por favor, selecione uma nuvem de pontos")) as PointCloudInstance;

                if (pcInstance == null)
                {
                    message = "Objeto inválido selecionado. Este comando funciona somente com instancias de nuvem de pontos, por favor, rode o comando novamente e selecione uma nuvem de pontos.";
                    return(Result.Failed);
                }

                View3D this3dView = uidoc.ActiveView as View3D;

                BoundingBoxXYZ boundingBox = null;

                //Use CropBox if there is one to use
                if (this3dView.CropBoxActive == true)
                {
                    boundingBox = this3dView.CropBox;
                }
                else
                {
                    boundingBox = pcInstance.get_BoundingBox(uidoc.ActiveView);
                }

                List <Plane> planes   = new List <Plane>();
                XYZ          midpoint = (boundingBox.Min + boundingBox.Max) / 2.0;

#if R2016
                // X boundaries
                planes.Add(new Plane(XYZ.BasisX, boundingBox.Min));
                planes.Add(new Plane(-XYZ.BasisX, boundingBox.Max));

                // Y boundaries
                planes.Add(new Plane(XYZ.BasisY, boundingBox.Min));
                planes.Add(new Plane(-XYZ.BasisY, boundingBox.Max));

                // Z boundaries
                planes.Add(new Plane(XYZ.BasisZ, boundingBox.Min));
                planes.Add(new Plane(-XYZ.BasisZ, boundingBox.Max));
#else
                // X boundaries
                planes.Add(Plane.CreateByNormalAndOrigin(XYZ.BasisX, boundingBox.Min));
                planes.Add(Plane.CreateByNormalAndOrigin(-XYZ.BasisX, boundingBox.Max));

                // Y boundaries
                planes.Add(Plane.CreateByNormalAndOrigin(XYZ.BasisY, boundingBox.Min));
                planes.Add(Plane.CreateByNormalAndOrigin(-XYZ.BasisY, boundingBox.Max));

                // Z boundaries
                planes.Add(Plane.CreateByNormalAndOrigin(XYZ.BasisZ, boundingBox.Min));
                planes.Add(Plane.CreateByNormalAndOrigin(-XYZ.BasisZ, boundingBox.Max));
#endif

                using (Transaction t = new Transaction(doc, "Criar Topografia"))
                {
                    t.Start();
                    // Create filter
                    PointCloudFilter pcFilter = PointCloudFilterFactory.CreateMultiPlaneFilter(planes);
                    pcInstance.FilterAction = SelectionFilterAction.Highlight;

                    PointCollection pcColection = pcInstance.GetPoints(pcFilter, pointDistance, pointMaxQuantity);
                    IList <XYZ>     pcPoints    = new List <XYZ>();
                    XYZ             origin      = pcInstance.GetTotalTransform().Origin;

                    if (pcColection.Count < 3)
                    {
                        t.RollBack();
                        message = "Número de pontos insuficiente para criar a topografia. Por favor utilize outra nuvem de pontos.";
                        return(Result.Failed);
                    }

                    foreach (XYZ currentPoint in pcColection)
                    {
                        XYZ pointCopy = new XYZ(currentPoint.X, currentPoint.Y, currentPoint.Z);
                        pointCopy = pcInstance.GetTotalTransform().OfPoint(pointCopy);

                        if (!ListContainsPoint(pcPoints, pointCopy))
                        {
                            pcPoints.Add(pointCopy);
                        }
                    }

                    TopographySurface topoSurface = TopographySurface.Create(doc, pcPoints);
                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
                return(Result.Cancelled);
            }

            return(Result.Succeeded);
        }