Example #1
1
        /// <summary>
        /// Create Curves using Isolines of a Surface
        /// </summary>
        /// <param name="face">Surface</param>
        /// <param name="isoDirection">Iso Line Direction</param>
        /// <param name="parameters">Parameters to Evaluate</param>
        /// <returns>List of IsoCurves</returns>
        //public static List<Curve> FollowingIsoLineSurface(Surface face, int isoDirection, List<double> parameters)
        //{
        //    List<Curve> result = new List<Curve>();
        //
        //    foreach (double parameter in parameters)
        //        result.Add(face.GetIsoline(isoDirection, parameter));
        //
        //    return result;
        //}

        /// <summary>
        /// Cuts a set of Rebars by Plane
        /// </summary>
        /// <param name="plane">Plane to cut by</param>
        /// <param name="rebarContainerElement">Rebar Container</param>
        /// <param name="firstPart">Return the first or the last part of the splitted elements</param>
        public static void Cut(Surface plane, Revit.Elements.Element rebarContainerElement, bool firstPart)
        {
            // Get Rebar Container Element
            Autodesk.Revit.DB.Structure.RebarContainer rebarContainer = (Autodesk.Revit.DB.Structure.RebarContainer)rebarContainerElement.InternalElement;

            // Get the active Document
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;

            // Open a new Transaction
            TransactionManager.Instance.EnsureInTransaction(document);

            // Get all single Rebar elements from the container
            List<Autodesk.Revit.DB.Structure.RebarContainerItem> rebars = rebarContainer.ToList();

            // Walk through all rebar elements
            foreach (Autodesk.Revit.DB.Structure.RebarContainerItem rebar in rebars)
            {
                // Buffer Rebar properties for recreation
                RVT.Structure.RebarBarType barType = (RVT.Structure.RebarBarType)document.GetElement(rebar.BarTypeId);
                RVT.Structure.RebarHookType hookTypeStart = (RVT.Structure.RebarHookType)document.GetElement(rebar.GetHookTypeId(0));
                RVT.Structure.RebarHookType hookTypeEnd = (RVT.Structure.RebarHookType)document.GetElement(rebar.GetHookTypeId(1));
                RVT.Structure.RebarHookOrientation hookOrientationStart = rebar.GetHookOrientation(0);
                RVT.Structure.RebarHookOrientation hookOrientationEnd = rebar.GetHookOrientation(1);

                // create a list to store the remaining part of the curve after cutting it
                List<RVT.Curve> result = new List<RVT.Curve>();

                // get the center line curves of the rebar elements
                foreach (RVT.Curve curve in rebar.GetCenterlineCurves(false, true, true))
                {
                    // if the curve is a line or an arc consider it being valid
                    if (curve.GetType() == typeof(RVT.Line) || curve.GetType() == typeof(RVT.Arc))
                    {
                        // Get a DesignScript Curve from the Revit curve
                        Curve geocurve = curve.ToProtoType();

                        // Intersect the selected plane with the curve
                        foreach (Geometry geometry in plane.Intersect(geocurve))
                        {
                            // if the intersection is a point
                            if (geometry.GetType() == typeof(Point))
                            {
                                // Get the closest point to the intersection on the curve
                                Point p = geocurve.ClosestPointTo((Point)geometry);

                                // Split the curve at this point
                                Curve[] curves = geocurve.ParameterSplit(geocurve.ParameterAtPoint(p));

                                // If the curve has been split into two parts
                                if (curves.Length == 2)
                                {
                                    // return the first or the second part of the splitted curve
                                    if (firstPart)
                                        result.Add(curves[0].ToRevitType());
                                    else
                                        result.Add(curves[1].ToRevitType());
                                }
                            }
                        }
                    }
                }

                // If the result has some elements, create a new rebar container from those curves
                // using the same properties as the initial one.
                if (result.Count > 0)
                {
                    rebar.SetFromCurves(RVT.Structure.RebarStyle.Standard, barType, hookTypeStart, hookTypeEnd, rebar.Normal, result, hookOrientationStart, hookOrientationEnd, true, false);
                }
            }

            // Commit and Dispose the transaction
            TransactionManager.Instance.TransactionTaskDone();
        }
Example #2
0
        public BuildingSurface(Surface surface, Zone zone, string name = "default", string type = "Wall", string constructionName = "default", string boundaryCondition = "Outdoors")
        {
            FenestrationSurfacesNumber = 1;

            if (name == "default")
            {
                Name = zone.Name + " - Surface " + zone.SurfaceNumber;
            }
            else
            {
                Name = name;
            }

            Surface = surface;
            ZoneName = zone.Name;
            zone.BuildingSurfaces.Add(this);
            zone.SurfaceNumber++;

            Type = type;
            ConstructionName = constructionName == "default" ? GetDefault(type, boundaryCondition) : constructionName;
            BoundaryCondition = boundaryCondition;
            BoundaryObject = "";

            if (boundaryCondition == "Outdoors")
            {
                SunExposed = true;
                WindExposed = true;
            }
            else
            {
                SunExposed = false;
                WindExposed = false;
            }
        }
Example #3
0
        public static DSGeom.Surface FromPoint(
            List <DSGeom.Polygon> boundary,
            [DefaultArgument("[]")] List <DSGeom.Polygon> internals,
            DSGeom.Point point)
        {
            BaseGraph baseGraph = BaseGraph.ByBoundaryAndInternalPolygons(boundary, internals);

            if (baseGraph == null)
            {
                throw new ArgumentNullException("graph");
            }
            if (point == null)
            {
                throw new ArgumentNullException("point");
            }

            GTGeom.Vertex origin = GTGeom.Vertex.ByCoordinates(point.X, point.Y, point.Z);

            List <GTGeom.Vertex> vertices = VisibilityGraph.VertexVisibility(origin, baseGraph.graph);
            List <DSGeom.Point>  points   = vertices.Select(v => GTGeom.Points.ToPoint(v)).ToList();

            var polygon = DSGeom.Polygon.ByPoints(points);

            // if polygon is self intersecting, make new polygon
            if (polygon.SelfIntersections().Length > 0)
            {
                points.Add(point);
                polygon = DSGeom.Polygon.ByPoints(points);
            }
            DSGeom.Surface surface = DSGeom.Surface.ByPatch(polygon);
            polygon.Dispose();
            points.ForEach(p => p.Dispose());

            return(surface);
        }
Example #4
0
        /// <summary>
        /// Splits a surface by multiple curves.
        /// </summary>
        /// <param name="srf"></param>
        /// <param name="crvs"></param>
        /// <search></search>
        public static Autodesk.DesignScript.Geometry.Geometry[] SplitPlanarSurfaceByMultipleCurves(this Autodesk.DesignScript.Geometry.Surface srf, List <Autodesk.DesignScript.Geometry.Curve> crvs)
        {
            Autodesk.DesignScript.Geometry.Vector vec = srf.NormalAtParameter(0.5, 0.5);

            List <Autodesk.DesignScript.Geometry.Surface> srfLst = new List <Autodesk.DesignScript.Geometry.Surface>();

            foreach (Autodesk.DesignScript.Geometry.Curve crv in crvs)
            {
                Autodesk.DesignScript.Geometry.Surface splitSrf = crv.Extrude(vec, 5000);
                srfLst.Add(splitSrf);
            }

            Autodesk.DesignScript.Geometry.PolySurface polysrf = Autodesk.DesignScript.Geometry.PolySurface.ByJoinedSurfaces(srfLst);

            Autodesk.DesignScript.Geometry.Geometry[] geo = srf.Split(polysrf);

            vec.Dispose();
            polysrf.Dispose();
            foreach (Autodesk.DesignScript.Geometry.Surface s in srfLst)
            {
                s.Dispose();
            }

            return(geo);
        }
Example #5
0
        private Display(Surface surface, Color[][] colors)
        {
            geometry = surface;

            // Transpose the colors array. This is required
            // to correctly align the colors on the surface with
            // the UV space of the surface.

            var rows = colors.GetLength(0);
            var columns = colors[0].Count();

            colorMap = new Color[columns][];
            for (var c = 0; c < columns; c++)
            {
                colorMap[c] = new Color[rows];
            }

            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < columns; j++)
                {
                    colorMap[j][i] = colors[i][j];
                }
            } 
        }
Example #6
0
        /// <summary>
        /// Tessellate the surface by calling the ToRevitType function.
        /// If it fails, each edge of the surface will be tessellated instead by calling
        /// the correspoinding Tessellate method.
        /// </summary>
        /// <param name="surface"></param>
        /// <returns></returns>
        private List <GeometryObject> Tessellate(Surface surface)
        {
            List <GeometryObject> rtGeoms = new List <GeometryObject>();

            try
            {
                rtGeoms.AddRange(surface.ToRevitType());
            }
            catch (Exception)
            {
                // Add a red bounding box geometry to identify that some errors occur
                var bbox = surface.BoundingBox;
                rtGeoms.AddRange(ProtoToRevitMesh.CreateBoundingBoxMeshForErrors(bbox.MinPoint, bbox.MaxPoint));

                foreach (var edge in surface.Edges)
                {
                    if (edge != null)
                    {
                        var curveGeometry = edge.CurveGeometry;
                        rtGeoms.AddRange(Tessellate(curveGeometry));
                        curveGeometry.Dispose();
                        edge.Dispose();
                    }
                }
            }

            return(rtGeoms);
        }
Example #7
0
        /// <summary>
        ///     Creates a Delaunay triangulation of a surface with a given set of UV parameters.
        /// </summary>
        /// <param name="uvs">Set of UV parameters.</param>
        /// <param name="face">Surface to triangulate.</param>
        public static IEnumerable<Curve> ByParametersOnSurface(IEnumerable<UV> uvs, Surface face)
        {
            var verts = uvs.Select(Vertex2.FromUV).ToList();
            var triangulation = DelaunayTriangulation<Vertex2, Cell2>.Create(verts, new TriangulationComputationConfig());

            // there are three vertices per cell in 2D
            foreach (var cell in triangulation.Cells)
            {
                var v1 = cell.Vertices[0].AsVector();
                var v2 = cell.Vertices[1].AsVector();
                var v3 = cell.Vertices[2].AsVector();

                var xyz1 = face.PointAtParameter(v1.X, v1.Y);
                var xyz2 = face.PointAtParameter(v2.X, v2.Y);
                var xyz3 = face.PointAtParameter(v3.X, v3.Y);

                if (xyz1.DistanceTo(xyz2) > 0.1)
                {
                    var l1 = Line.ByStartPointEndPoint(xyz1, xyz2);
                    yield return l1;
                }

                if (xyz2.DistanceTo(xyz3) > 0.1)
                {
                    var l1 = Line.ByStartPointEndPoint(xyz3, xyz2);
                    yield return l1;
                }

                if (xyz3.DistanceTo(xyz1) > 0.1)
                {
                    var l1 = Line.ByStartPointEndPoint(xyz1, xyz3);
                    yield return l1;
                }
            }
        }
Example #8
0
 private static Autodesk.DesignScript.Geometry.Surface Transform(Autodesk.DesignScript.Geometry.Surface surface, CoordinateSystem coordinateSystem)
 {
     if (coordinateSystem == null)
     {
         return(surface);
     }
     return((surface as Autodesk.DesignScript.Geometry.Geometry).Transform(coordinateSystem) as Autodesk.DesignScript.Geometry.Surface);
 }
Example #9
0
        internal Shell(Surface surface, ShellProp shellprop)
        {
            BaseS = surface;
            shellProp = shellprop;
            this.Type = Structure.Type.Shell;

            //register for cache
            ID = TracedShellManager.GetNextUnusedID();
            TracedShellManager.RegisterShellforID(ID, this);
        }
Example #10
0
        /// <summary>
        /// Remove Curtain Grid
        /// </summary>
        /// <param name="face"></param>
        public void RemoveCurtainGrid(Autodesk.DesignScript.Geometry.Surface face)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);
            var reference = face.Tags.LookupTag("RevitFaceReference");

            if (reference != null)
            {
                this.InternalCurtainSystem.RemoveCurtainGrid((Autodesk.Revit.DB.Reference)reference);
            }
            TransactionManager.Instance.TransactionTaskDone();
        }
Example #11
0
 private SurfaceCurvature(Surface contextSurface, double u, double v, ICoordinateSystemEntity coordinateSystemEntity)
 {
     FirstPrincipleCurvature = new Vector(coordinateSystemEntity.XAxis);
     SecondPrincipleCurvature = new Vector(coordinateSystemEntity.YAxis);
     GaussianCurvature = FirstPrincipleCurvature.Length * SecondPrincipleCurvature.Length;
     mPointOnSurface = Point.ToGeometry(coordinateSystemEntity.Origin, false, contextSurface) as Point;
     U = u;
     V = v;
     ContextSurface = contextSurface;
     mCoordinateSystem = CoordinateSystem.ToCS(coordinateSystemEntity, false);
 }
Example #12
0
        /// <summary>
        /// Return the bounding surface of the input surface
        /// </summary>
        /// <param name="surface"></param>
        /// <search></search>
        public static Autodesk.DesignScript.Geometry.Surface BoundingSurface(this Autodesk.DesignScript.Geometry.Surface surface)
        {
            Autodesk.DesignScript.Geometry.BoundingBox bb = surface.BoundingBox;
            Cuboid c = bb.ToCuboid();

            Autodesk.DesignScript.Geometry.Surface srf = (c.Explode())[0] as Autodesk.DesignScript.Geometry.Surface;

            bb.Dispose();
            c.Dispose();

            return(srf);
        }
Example #13
0
        /// <summary>
        ///     Creates a Voronoi tessellation of a surface with a given set of UV parameters.
        /// </summary>
        /// <param name="uvs">Set of UV parameters.</param>
        /// <param name="face">Surface to tesselate.</param>
        public static IEnumerable<Curve> ByParametersOnSurface(IEnumerable<UV> uvs, Surface face)
        {
            var verts = uvs.Select(Vertex2.FromUV);
            var voronoiMesh = VoronoiMesh.Create<Vertex2, Cell2>(verts);

            return from edge in voronoiMesh.Edges
                   let _from = edge.Source.Circumcenter
                   let to = edge.Target.Circumcenter
                   let start = face.PointAtParameter(_from.X, _from.Y)
                   let end = face.PointAtParameter(to.X, to.Y)
                   where start.DistanceTo(end) > 0.1
                   select Line.ByStartPointEndPoint(start, end);
        }
Example #14
0
        /// <summary>
        /// Create Curtain System from face references
        /// </summary>
        /// <param name="face"></param>
        /// <param name="curtainSystemType"></param>
        /// <returns></returns>
        public static CurtainSystem ByFace(Autodesk.DesignScript.Geometry.Surface face, CurtainSystemType curtainSystemType)
        {
            ReferenceArray ca = new ReferenceArray();

            var reference = face.Tags.LookupTag("RevitFaceReference");

            if (reference == null)
            {
                throw new Exception(Properties.Resources.FaceReferenceFailure);
            }
            ca.Append((Autodesk.Revit.DB.Reference)reference);

            return(new CurtainSystem(ca, curtainSystemType.InternalCurtainSystemType));
        }
        public static IList <GeometryObject> ToRevitType(this Autodesk.DesignScript.Geometry.Surface srf,
                                                         TessellatedShapeBuilderTarget target     = TessellatedShapeBuilderTarget.Mesh,
                                                         TessellatedShapeBuilderFallback fallback = TessellatedShapeBuilderFallback.Salvage,
                                                         ElementId MaterialId           = null,
                                                         bool performHostUnitConversion = true)
        {
            var rp = new DefaultRenderPackage();

            if (performHostUnitConversion)
            {
                var newSrf = srf.InHostUnits();
                newSrf.Tessellate(rp, new TessellationParameters());
                newSrf.Dispose();
            }
            else
            {
                srf.Tessellate(rp, new TessellationParameters());
            }

            var tsb = new TessellatedShapeBuilder()
            {
                Fallback = fallback, Target = target, GraphicsStyleId = ElementId.InvalidElementId
            };

            tsb.OpenConnectedFaceSet(false);

            var v = rp.MeshVertices.ToList();

            for (int i = 0; i < v.Count; i += 9)
            {
                var a = new XYZ(v[i], v[i + 1], v[i + 2]);
                var b = new XYZ(v[i + 3], v[i + 4], v[i + 5]);
                var c = new XYZ(v[i + 6], v[i + 7], v[i + 8]);

                var face = new TessellatedFace(new List <XYZ>()
                {
                    a, b, c
                }, MaterialId != null ? MaterialId : MaterialsManager.Instance.DynamoMaterialId);
                tsb.AddFace(face);
            }

            tsb.CloseConnectedFaceSet();
            tsb.Build();
            var result = tsb.GetBuildResult();

            return(result.GetGeometricalObjects());
        }
        private FenestrationSurface(Surface surface, BuildingSurface buildingSurface, int multiplier, string constructionName = "default")
        {
            Name = buildingSurface.Name + " - Window " + buildingSurface.FenestrationSurfacesNumber;

            Type = "Window";

            ConstructionName = constructionName == "default"
                ? "000 Standard Window"
                : constructionName;

            SurfaceName = buildingSurface.Name;
            BuildingSurface = buildingSurface;
            Surface = surface;
            buildingSurface.FenestrationSurfacesNumber++;

            Multiplier = multiplier;
        }
Example #17
0
        /// <summary>
        /// Place a Revit family instance of the given the FamilyType (also known as the FamilySymbol in the Revit API)
        /// on a surface derived from a backing Revit face as reference and a line as reference for its position.
        ///
        /// Note: The FamilyPlacementType must be CurveBased and the input surface must be created from a Revit Face
        /// </summary>
        /// <param name="familyType">Family Type. Also called Family Symbol.</param>
        /// <param name="face">Surface geometry derived from a Revit face as reference element</param>
        /// <param name="line">A line on the face defining where the symbol is to be placed</param>
        /// <returns>FamilyInstance</returns>
        public static FamilyInstance ByFace(FamilyType familyType, Surface face, Autodesk.DesignScript.Geometry.Line line)
        {
            if (familyType == null)
            {
                throw new ArgumentNullException("familyType");
            }
            if (face == null)
            {
                throw new ArgumentNullException("face");
            }
            if (line == null)
            {
                throw new ArgumentNullException("line");
            }
            var reference = ElementFaceReference.TryGetFaceReference(face);

            return(new FamilyInstance(familyType.InternalFamilySymbol, reference.InternalReference, (Autodesk.Revit.DB.Line)line.ToRevitType()));
        }
Example #18
0
        public TrimmedSurface(Surface surface, double angleTolerance = 60)
        {
            this.internalSurface = surface;
            this.curvesByDirections = new Dictionary<Vector, TwoCurves>();
            this.tolerance = angleTolerance;

            // Walk through all perimeter curves
            foreach (Curve curve in internalSurface.PerimeterCurves())
            {
                // get the curves direction
                Vector direction = Vector.ByTwoPoints(curve.StartPoint, curve.EndPoint);

                // If there hasnt been any curve collected add this as the first one
                if (curvesByDirections.Count == 0)
                    curvesByDirections.Add(direction, new TwoCurves(curve));
                else
                {
                    // indicator to check if any curve matches its direction
                    bool matchingOrientation = false;

                    // Walk through all collected curves and check if the direction vectors are
                    // more or less parallel.
                    foreach (Vector vector in curvesByDirections.Keys.ToList())
                    {
                        if (direction.Parallel(vector, tolerance))
                        {
                            matchingOrientation = true;

                            // If there is a matching direction already in the dictionary,
                            // Add this curve to the existing curve
                            TwoCurves existingCurve = curvesByDirections[vector];
                            existingCurve.AddToMatchingCurve(curve);
                        }
                    }

                    // If there is no matching direction, this seems to be a new
                    // Side of the surface
                    if (!matchingOrientation)
                    {
                        curvesByDirections.Add(direction, new TwoCurves(curve));
                    }
                }
            }
        }
        public static AdaptiveComponent[] ByParametersOnFace(double[][][] uvs, Surface surface, FamilyType familyType)
        {
            if (uvs == null)
            {
                throw new ArgumentNullException("uvs");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (familyType == null)
            {
                throw new ArgumentNullException("familyType");
            }

            return(uvs.Select(x => ByParametersOnFace(x, surface, familyType)).ToArray());
        }
        /// <summary>
        /// Show a colored Face Analysis Display in the Revit view.
        /// </summary>
        /// <param name="view">The view into which you want to draw the analysis results.</param>
        /// <param name="sampleLocations">The locations at which you want to create analysis values.</param>
        /// <param name="samples">The analysis values at the given locations.</param>
        /// <param name="name">An optional analysis results name to show on the results legend.</param>
        /// <param name="description">An optional analysis results description to show on the results legend.</param>
        /// <param name="unitType">An optional Unit type to provide conversions in the analysis results.</param>
        /// <returns>A FaceAnalysisDisplay object.</returns>
        public static FaceAnalysisDisplay ByViewFacePointsAndValues(
            View view, Surface surface,
            Autodesk.DesignScript.Geometry.UV[] sampleLocations, double[] samples, string name = "", string description = "", Type unitType = null)
        {
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (sampleLocations == null)
            {
                throw new ArgumentNullException("sampleUvPoints");
            }

            if (samples == null)
            {
                throw new ArgumentNullException("samples");
            }

            if (sampleLocations.Length != samples.Length)
            {
                throw new Exception(Properties.Resources.Array_Count_Mismatch);
            }

            if (string.IsNullOrEmpty(name))
            {
                name = Properties.Resources.AnalysisResultsDefaultName;
            }

            if (string.IsNullOrEmpty(description))
            {
                description = Properties.Resources.AnalysisResultsDefaultDescription;
            }

            var data = SurfaceData.BySurfacePointsAndValues(surface, sampleLocations, samples);

            return(new FaceAnalysisDisplay(view.InternalView, data, name, description, unitType));
        }
Example #21
0
        public static AdaptiveComponent ByParametersOnFace(double[][] uvs, Surface surface, FamilyType familyType)
        {
            if (uvs == null)
            {
                throw new ArgumentNullException("uvs");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (familyType == null)
            {
                throw new ArgumentNullException("familyType");
            }

            return(new AdaptiveComponent(uvs, ElementFaceReference.TryGetFaceReference(surface), familyType));
        }
Example #22
0
        public static Dictionary <string, dynamic> MaximumArea(this List <Autodesk.DesignScript.Geometry.Surface> surfaces)
        {
            List <double> areas = new List <double>();

            for (int i = 0; i < surfaces.Count; i++)
            {
                areas.Add(surfaces[i].Area);
            }


            List <Autodesk.DesignScript.Geometry.Surface> otherSurfaces = new List <Autodesk.DesignScript.Geometry.Surface>();
            List <int> maxID = new List <int>();

            for (int i = 0; i < areas.Count; i++)
            {
                if (areas[i] == areas.Max())
                {
                    maxID.Add(i);
                }
                else
                {
                    otherSurfaces.Add(surfaces[i]);
                }
            }

            Autodesk.DesignScript.Geometry.Surface maxSurface = surfaces[maxID[0]];

            Dictionary <string, dynamic> newOutput;

            newOutput = new Dictionary <string, dynamic>
            {
                { "maxSrf", maxSurface },
                { "otherSrfs", otherSurfaces }
            };

            return(newOutput);
        }
Example #23
0
        /// <summary>
        /// Place a Revit family instance given the FamilyType (also known as the FamilySymbol in the Revit API)
        /// on a surface derived from a backing Revit face as reference, a reference direction and a point location where to place the family.
        ///
        /// Note: The FamilyType should be workplane based and the input surface must be created from a Revit Face. The reference direction defines the rotation of the instance on the reference, and thus cannot be perpendicular to the face.
        /// </summary>
        /// <param name="familyType">Family Type. Also called Family Symbol.</param>
        /// <param name="face">Surface geometry derived from a Revit face as reference element</param>
        /// <param name="location">Point on the face where the instance is to be placed</param>
        /// <param name="referenceDirection">A vector that defines the direction of placement of the family instance</param>
        /// <returns>FamilyInstance</returns>
        public static FamilyInstance ByFace(FamilyType familyType, Surface face, Point location,
                                            Vector referenceDirection)
        {
            if (familyType == null)
            {
                throw new ArgumentNullException("familyType");
            }
            if (face == null)
            {
                throw new ArgumentNullException("face");
            }
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }
            if (referenceDirection == null)
            {
                throw new ArgumentNullException("referenceDirection");
            }
            var reference = ElementFaceReference.TryGetFaceReference(face);

            return(new FamilyInstance(familyType.InternalFamilySymbol, reference.InternalReference,
                                      location.ToXyz(), referenceDirection.ToXyz()));
        }
Example #24
0
        /// <summary>
        /// Create an adaptive component by uv points on a face.
        /// </summary>
        /// <param name="uvs">An array of UV pairs</param>
        /// <param name="surface">The surface on which to place the AdaptiveComponent</param>
        /// <param name="familyType"></param>
        /// <returns></returns>
        public static AdaptiveComponent ByParametersOnFace(Autodesk.DesignScript.Geometry.UV[] uvs, Surface surface, FamilyType familyType)
        {
            if (uvs == null)
            {
                throw new ArgumentNullException("uvs");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (familyType == null)
            {
                throw new ArgumentNullException("familyType");
            }

            return(new AdaptiveComponent(uvs.Select(x => new[] { x.U, x.V }).ToArray(), ElementFaceReference.TryGetFaceReference(surface), familyType));
        }
Example #25
0
 /// <summary>
 /// Constructors a plane on a surface by given parameter. 
 /// </summary>
 /// <param name="contextSurface"></param>
 /// <param name="u"></param>
 /// <param name="v"></param>
 /// <returns></returns>
 public static Plane AtParameter(Surface contextSurface, double u, double v)
 {
     CoordinateSystem cs = CoordinateSystem.AtParameterCore(contextSurface, u, v, false);
     Plane plane = Plane.FromCoordinateSystem(cs);
     plane.Context = contextSurface;
     plane.U = u;
     plane.V = v;
     return plane;
 }
Example #26
0
        public static Dictionary <string, Autodesk.DesignScript.Geometry.Curve[]> OffsetPerimeterCurves(this Autodesk.DesignScript.Geometry.Surface surface, double offset)
        {
            List <Autodesk.DesignScript.Geometry.Curve> srfPerimCrvs = surface.PerimeterCurves().ToList();

            Autodesk.DesignScript.Geometry.PolyCurve plyCrv = Autodesk.DesignScript.Geometry.PolyCurve.ByJoinedCurves(srfPerimCrvs);

            double inOffset;
            double outOffset;

            if (offset < 0)
            {
                inOffset  = offset;
                outOffset = -offset;
            }
            else
            {
                inOffset  = -offset;
                outOffset = offset;
            }

            Autodesk.DesignScript.Geometry.Curve[] inPerimCrvs;
            try
            {
                List <Autodesk.DesignScript.Geometry.Curve> inOffsetCrv = new List <Autodesk.DesignScript.Geometry.Curve>()
                {
                    (plyCrv.Offset(inOffset))
                };
                Autodesk.DesignScript.Geometry.PolyCurve    inOffsetPolyCrv = Autodesk.DesignScript.Geometry.PolyCurve.ByJoinedCurves(inOffsetCrv);
                List <Autodesk.DesignScript.Geometry.Curve> inOffsetCrvList = inOffsetPolyCrv.Curves().ToList();
                List <Autodesk.DesignScript.Geometry.Point> inPts           = new List <Autodesk.DesignScript.Geometry.Point>();
                foreach (Autodesk.DesignScript.Geometry.Curve c in inOffsetCrvList)
                {
                    inPts.Add(c.StartPoint);
                }
                Autodesk.DesignScript.Geometry.PolyCurve inOffsetPolyCrv2 = PolyCurve.ByPoints(inPts, true);
                Autodesk.DesignScript.Geometry.Surface   inOffsetSrf      = Autodesk.DesignScript.Geometry.Surface.ByPatch(inOffsetPolyCrv2);
                inPerimCrvs = inOffsetSrf.PerimeterCurves();
                inOffsetSrf.Dispose();
                inOffsetPolyCrv.Dispose();
                inOffsetPolyCrv2.Dispose();
            }
            catch (Exception)
            {
                inPerimCrvs = null;
            }

            Autodesk.DesignScript.Geometry.Curve[] outPerimCrvs;
            try
            {
                List <Autodesk.DesignScript.Geometry.Curve> outOffsetCrv = new List <Autodesk.DesignScript.Geometry.Curve>()
                {
                    (plyCrv.Offset(outOffset))
                };
                Autodesk.DesignScript.Geometry.PolyCurve    outOffsetPolyCrv = Autodesk.DesignScript.Geometry.PolyCurve.ByJoinedCurves(outOffsetCrv);
                List <Autodesk.DesignScript.Geometry.Curve> outOffsetCrvList = outOffsetPolyCrv.Curves().ToList();
                List <Autodesk.DesignScript.Geometry.Point> outPts           = new List <Autodesk.DesignScript.Geometry.Point>();
                foreach (Autodesk.DesignScript.Geometry.Curve c in outOffsetCrvList)
                {
                    outPts.Add(c.StartPoint);
                }
                Autodesk.DesignScript.Geometry.PolyCurve outOffsetPolyCrv2 = PolyCurve.ByPoints(outPts, true);
                Autodesk.DesignScript.Geometry.Surface   outOffsetSrf      = Autodesk.DesignScript.Geometry.Surface.ByPatch(outOffsetPolyCrv2);
                outPerimCrvs = outOffsetSrf.PerimeterCurves();
                outOffsetSrf.Dispose();
                outOffsetPolyCrv.Dispose();
                outOffsetPolyCrv2.Dispose();
            }
            catch (Exception)
            {
                outPerimCrvs = null;
            }


            Dictionary <string, Autodesk.DesignScript.Geometry.Curve[]> newOutput;

            newOutput = new Dictionary <string, Autodesk.DesignScript.Geometry.Curve[]>
            {
                { "insetCrvs", inPerimCrvs },
                { "outsetCrvs", outPerimCrvs }
            };

            //Dispose all redundant geometry

            plyCrv.Dispose();
            foreach (Autodesk.DesignScript.Geometry.Curve c in srfPerimCrvs)
            {
                c.Dispose();
            }

            return(newOutput);
        }
Example #27
0
 /// <summary>
 /// Compute a set of color maps from a set of SurfaceData objects.
 /// </summary>
 /// <returns></returns>
 private static Color[][] ComputeColorMap(Surface surface, IEnumerable<UV> uvs, Color[] colors, int samplesU, int samplesV)
 {
     return Utils.CreateGradientColorMap(colors, uvs, samplesU, samplesV);
 }
Example #28
0
        /// <summary>
        /// Display color values on a surface.
        /// 
        /// The colors provided are converted internally to an image texture which is
        /// mapped to the surface. 
        /// </summary>
        /// <param name="surface">The surface on which to apply the colors.
        /// </param>
        /// <param name="colors">A two dimensional list of Colors.
        /// 
        /// The list of colors must be square. Attempting to pass a jagged array
        /// will result in an exception. </param>
        /// <returns>A Display object.</returns>
        public static Display BySurfaceColors(Surface surface, 
            [DefaultArgument("{{Color.ByARGB(255,255,0,0),Color.ByARGB(255,255,255,0)},{Color.ByARGB(255,0,255,255),Color.ByARGB(255,0,0,255)}};")] Color[][] colors)
        {
            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (colors == null)
            {
                throw new ArgumentNullException("colors");
            }

            if (!colors.Any())
            {
                throw new ArgumentException(Resources.NoColorsExceptionMessage);
            }

            if (colors.Length == 1)
            {
                throw new ArgumentException(Resources.TwoDimensionalListExceptionMessage);
            }

            var size = colors[0].Count();
            foreach (var list in colors)
            {
                if (list.Count() != size)
                {
                    throw new ArgumentException(Resources.JaggedListExceptionMessage);
                }
            }

            return new Display(surface, colors);
        }
Example #29
0
 /// <summary>
 /// Contructs a point on a given surface at given U, V parameter.
 /// </summary>
 /// <param name="contextSurface">Input Surface</param>
 /// <param name="u">U parameter value.</param>
 /// <param name="v">V parameter value.</param>
 /// <returns>Point</returns>
 public static Point AtParameter(Surface contextSurface, double u, double v)
 {
     return AtParameter(contextSurface, u, v, 0.0);
 }
Example #30
0
        /// <summary>
        /// Constructs a point by projecting a point on surface. It is equivalent 
        /// to finding the nearest point on the surface
        /// </summary>
        /// <param name="contextSurface">The surface on which the projection is to be made.</param>
        /// <returns>Projected point on surface</returns>
        public Point Project(Surface contextSurface)
        {
            if (null == contextSurface)
                throw new ArgumentNullException("contextSurface");

            Point pt = ProjectOnGeometry(contextSurface, null);
            if (null == pt)
                throw new InvalidOperationException(string.Format(Properties.Resources.OperationFailed, "Project on surface"));

            pt.Context = contextSurface;
            pt.ReferencePoint = this;
            double[] parameters = contextSurface.ParameterAtPoint(pt);
            if (null != parameters)
            {
                pt.U = parameters[0];
                pt.V = parameters[1];
            }
            return pt;
        }
Example #31
0
        public static Dictionary <string, Autodesk.DesignScript.Geometry.Surface> Create(
            Autodesk.DesignScript.Geometry.Surface surface,
            double offset,
            double depth)
        {
            // offset perimeter curves by the specified offset and create new surface.
            // makes sure there are space between outer perimeter and the amenity space
            List <Curve> inCrvs = surface.OffsetPerimeterCurves(offset)["insetCrvs"].ToList();
            Surface      inSrf  = Surface.ByPatch(PolyCurve.ByJoinedCurves(inCrvs));

            // get longest curve of the inSrf
            Curve        max;
            List <Curve> others;
            Dictionary <string, dynamic> dict = inCrvs.MaximumLength();

            if (dict["maxCrv"].Count < 1)
            {
                max = dict["otherCrvs"][0] as Curve;
                int          count = dict["otherCrvs"].Count;
                List <Curve> rest  = dict["otherCrvs"];
                others = rest.GetRange(1, (count - 1));
            }
            else
            {
                max    = dict["maxCrv"][0] as Curve;
                others = dict["otherCrvs"];
            }

            // get perimeter curves of input surface
            List <Curve> perimCrvs = surface.PerimeterCurves().ToList();
            List <Curve> matchCrvs = max.FindMatchingVectorCurves(perimCrvs);

            // get longest curve
            Curve max2;
            Dictionary <string, dynamic> dict2 = matchCrvs.MaximumLength();

            if (dict2["maxCrv"].Count < 1)
            {
                max2 = dict2["otherCrvs"][0] as Curve;
            }
            else
            {
                max2 = dict2["maxCrv"][0] as Curve;
            }

            Vector vec = max2.ByTwoCurves(max);

            Curve transLine  = max.Translate(vec, depth) as Curve;
            Line  extendLine = transLine.ExtendAtBothEnds(1);


            List <Curve> crvList = new List <Curve>()
            {
                max, extendLine
            };
            Surface loftSrf = Surface.ByLoft(crvList);

            List <bool> boolLst = new List <bool>();

            foreach (var crv in others)
            {
                bool b = max.DoesIntersect(crv);
                boolLst.Add(b);
            }

            List <Curve> intersectingCurves = others
                                              .Zip(boolLst, (name, filter) => new { name, filter, })
                                              .Where(item => item.filter == true)
                                              .Select(item => item.name)
                                              .ToList();
            List <Curve> extendCurves = new List <Curve>();

            foreach (Curve crv in intersectingCurves)
            {
                var l = crv.ExtendAtBothEnds(1);
                extendCurves.Add(l);
            }

            List <Surface> split = loftSrf
                                   .SplitPlanarSurfaceByMultipleCurves(extendCurves)
                                   .OfType <Surface>()
                                   .ToList();

            Surface amenitySurf = split.MaximumArea()["maxSrf"] as Surface;

            Surface remainSurf = inSrf.Split(amenitySurf)[0] as Surface;

            Dictionary <string, Surface> newOutput;

            newOutput = new Dictionary <string, Surface>
            {
                { amenitySurfaceOutputPort, amenitySurf },
                { remainingSurfaceOutputPort, remainSurf }
            };

            //Dispose redundant geometry
            inCrvs.ForEach(crv => crv.Dispose());
            inSrf.Dispose();
            max.Dispose();
            perimCrvs.ForEach(crv => crv.Dispose());
            matchCrvs.ForEach(crv => crv.Dispose());
            max2.Dispose();
            vec.Dispose();
            transLine.Dispose();
            extendLine.Dispose();
            crvList.ForEach(crv => crv.Dispose());
            loftSrf.Dispose();
            intersectingCurves.ForEach(crv => crv.Dispose());
            extendCurves.ForEach(crv => crv.Dispose());

            return(newOutput);
        }
Example #32
0
        /// <summary>
        /// Constructs a point by projecting a point on surface with given 
        /// project direction.
        /// </summary>
        /// <param name="contextSurface">The surface on which the projection is to be made.</param>
        /// <param name="direction">The direction vector of the projection</param>
        /// <returns>Projected point on surface</returns>
        public Point Project(Surface contextSurface, Vector direction)
        {
            if (null == contextSurface)
                throw new ArgumentNullException("contextSurface");
            if (null == direction || direction.IsZeroVector())
                throw new ArgumentException(string.Format(Properties.Resources.InvalidInput, direction, "Project on surface"), "direction");

            Point pt = ProjectOnGeometry(contextSurface, direction);
            pt.Context = contextSurface;
            pt.Direction = direction;
            pt.ReferencePoint = this;
            double[] parameters = contextSurface.ParameterAtPoint(pt);
            if (null != parameters)
            {
                pt.U = parameters[0];
                pt.V = parameters[1];
            }

            return pt;
        }
        public static IEnumerable <Surface> ToProtoType(this Autodesk.Revit.DB.Face revitFace,
                                                        bool performHostUnitConversion = true, Reference referenceOverride = null)
        {
            if (revitFace == null)
            {
                throw new ArgumentNullException("revitFace");
            }

            var revitEdgeLoops            = EdgeLoopPartition.GetAllEdgeLoopsFromRevitFace(revitFace);
            var partitionedRevitEdgeLoops = EdgeLoopPartition.ByEdgeLoopsAndFace(revitFace, revitEdgeLoops);

            var listSurface = new List <Surface>();

            foreach (var edgeloopPartition in partitionedRevitEdgeLoops)
            {
                // convert the trimming curves
                var edgeLoops = EdgeLoopsAsPolyCurves(revitFace, edgeloopPartition);

                // convert the underrlying surface
                var     dyFace       = (dynamic)revitFace;
                Surface untrimmedSrf = SurfaceExtractor.ExtractSurface(dyFace, edgeLoops);
                if (untrimmedSrf == null)
                {
                    edgeLoops.ForEach(x => x.Dispose());
                    edgeLoops.Clear();
                    throw new Exception("Failed to extract surface");
                }

                // trim the surface
                Surface converted;
                try
                {
                    converted = untrimmedSrf.TrimWithEdgeLoops(edgeLoops);
                }
                catch (Exception e)
                {
                    edgeLoops.ForEach(x => x.Dispose());
                    edgeLoops.Clear();
                    untrimmedSrf.Dispose();
                    throw e;
                }

                edgeLoops.ForEach(x => x.Dispose());
                edgeLoops.Clear();
                untrimmedSrf.Dispose();

                // perform unit conversion if necessary
                if (performHostUnitConversion)
                {
                    UnitConverter.ConvertToDynamoUnits(ref converted);
                }

                // if possible, apply revit reference
                var revitRef = referenceOverride ?? revitFace.Reference;
                if (revitRef != null)
                {
                    converted = ElementFaceReference.AddTag(converted, revitRef);
                }

                listSurface.Add(converted);
            }

            return(listSurface);
        }
Example #34
0
        /// <summary>
        /// Create curves perpendicular to Face
        /// </summary>
        /// <param name="face">Face to use</param>
        /// <param name="boundary">Boundary Faces</param>
        /// <param name="height">Location Parameter</param>
        /// <param name="numberOfCurves">Number of curves to create</param>
        /// <param name="flip">Flip orientation</param>
        /// <param name="offset">Offset</param>
        /// <returns>List of perpendicular curves</returns>
        public static List<Curve> Perpendicular(Surface face, List<Surface> boundary, double height, int numberOfCurves, bool flip = true, double offset = 0)
        {
            List<Curve> data = face.NormalCurves(boundary, numberOfCurves, offset, height, flip);

            return data;
        }
Example #35
0
        public static Surface CutWindows(Surface surface, List<Surface> windows)
        {
            foreach (var window in windows)
            {
                var sub = window.Thicken(5000.0, true);
                surface.SubtractFrom(sub);
            }

            return surface;
        }
Example #36
0
        /// <summary>
        /// Contructs a point on the normal of a given surface at a given offset
        /// </summary>
        /// <param name="contextSurface">Input surface</param>
        /// <param name="u">U parameter value</param>
        /// <param name="v">V parameter value</param>
        /// <param name="offset">Offset in the direction of normal</param>
        /// <returns>Point</returns>
        internal static Point AtParameter(Surface contextSurface, double u, double v, double offset)
        {
            if (contextSurface == null)
            return null;

              var pt = contextSurface.PointAtParametersCore(ref u, ref v, offset);
              if (null == pt)
            return null;

              pt.Context = contextSurface;
              pt.U = u;
              pt.V = v;
              pt.Distance = offset;
              pt.Persist();
              return pt;
        }
Example #37
0
 internal override IGeometryEntity[] IntersectWithSurface(Surface surf)
 {
     return surf.SurfaceEntity.IntersectWith(PlaneEntity);
 }
        private static int GetIntersection(Surface face, List<Surface> surfaces, Point point, double offset, ref List<Curve> curves, bool reverse)
        {
            Surface my = face;

            if (face.GetType() == typeof(PolySurface))
            {
                PolySurface poly = (PolySurface)face;
                foreach (Surface s in poly.Surfaces())
                {
                    UV coords = s.UVParameterAtPoint(point);
                    if (coords != null && coords.U >= 0 && coords.U <= 1 && coords.V >= 0 && coords.V <= 1)
                    {
                        my = s;
                    }
                }
            }

            // Get the Normal at that point
            Vector normal = my.NormalAtPoint(point);

            // Remove Z Value in order to create horizontal normals
            Vector optimizedNormal = (reverse) ? normal.Reverse() : normal;
            // Vector.ByCoordinates(normal.X, normal.Y, 0).Reverse() : Vector.ByCoordinates(normal.X, normal.Y, 0);

            // Get an startpoint offset if it applies
            Point startPoint = point;
            if (offset != 0)
            {
                Line offsetLine = Line.ByStartPointDirectionLength(point, optimizedNormal, offset);
                startPoint = offsetLine.EndPoint;
            }

            // Create an almost endless line
            Line line = Line.ByStartPointDirectionLength(startPoint, optimizedNormal, 100000000);

            // Get intersection points with boundary surfaces
            List<double> intersections = line.Insersection(surfaces);

            // If there are any intersections
            if (intersections.Count > 1)
            {
                // trim the curve into segments if there are gaps or holes
                Curve[] segments = line.ParameterTrimSegments(intersections.ToArray(), false);

                // Walk through trimmed curves and add only those to the return collection
                // which are of a reasonable length
                foreach (Curve segment in segments)
                    //if (segment.Length < 100000)
                    curves.Add(segment);
            }
            else if (intersections.Count == 1)
            {
                Curve[] segments = line.ParameterSplit(intersections[0]);
                curves.Add(segments[0]);
            }

            return intersections.Count;
        }
Example #39
0
        public static AdaptiveComponent ByParametersOnFace(double[][] uvs, Surface surface, FamilySymbol familySymbol)
        {
            if (uvs == null)
            {
                throw new ArgumentNullException("uvs");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (familySymbol == null)
            {
                throw new ArgumentNullException("familySymbol");
            }

            return new AdaptiveComponent(uvs, ElementFaceReference.TryGetFaceReference(surface), familySymbol);
        }
Example #40
0
        internal static CoordinateSystem AtParameterCore(Surface contextSurface, double u, double v, bool visible)
        {
            if (contextSurface == null)
                throw new System.ArgumentNullException("contextSurface");

            var cs = contextSurface.GetCSAtParameters(u, v);
            if (null == cs)
                throw new System.Exception(string.Format(Properties.Resources.OperationFailed, "CoordinateSystem.AtParameter"));

            cs.ContextSurface = contextSurface;
            cs.U = u;
            cs.V = v;
            cs.Visible = visible;
            return cs;
        }
Example #41
0
        /// <summary>
        /// Create an adaptive component by uv points on a face.
        /// </summary>
        /// <param name="uvs">An array of UV pairs</param>
        /// <param name="surface">The surface on which to place the AdaptiveComponent</param>
        /// <param name="familySymbol"></param>
        /// <returns></returns>
        public static AdaptiveComponent ByParametersOnFace( Autodesk.DesignScript.Geometry.UV[] uvs, Surface surface, FamilySymbol familySymbol)
        {
            if (uvs == null)
            {
                throw new ArgumentNullException("uvs");
            }

            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (familySymbol == null)
            {
                throw new ArgumentNullException("familySymbol");
            }

            return new AdaptiveComponent(uvs.Select(x => new []{x.U,x.V}).ToArray(), ElementFaceReference.TryGetFaceReference(surface), familySymbol);
        }
Example #42
0
        public static object AwareTributaryArea_ByPoints(Dyn.Surface boundarySrf, List <Dyn.Point> pointsForLoad, bool flipDirection)
        {
            sDynamoConverter dycon = new sDynamoConverter("Feet", "Meters");

            List <Dyn.UV> uvs = new List <Dyn.UV>();


            //double fac = 10;
            //if (flipDirection) fac *= -1;
            //foreach (Dyn.Curve seg in Dyn.PolyCurve.ByJoinedCurves(boundarySrf.PerimeterCurves()).Offset(fac).Explode())
            //{
            //    uvs.Add(boundarySrf.UVParameterAtPoint(seg.PointAtParameter(0.5)));
            //}
            foreach (Dyn.Point lp in pointsForLoad)
            {
                uvs.Add(boundarySrf.UVParameterAtPoint(lp));
            }
            List <Dyn.Surface> vorocut = new List <Dyn.Surface>();

            foreach (var vc in Voronoi.ByParametersOnSurface(uvs, boundarySrf))
            {
                Dyn.Curve vcc = vc as Dyn.Curve;

                Dyn.Geometry[] ints = boundarySrf.Intersect(vcc);
                if (ints != null && ints.Length > 0)
                {
                    for (int i = 0; i < ints.Length; ++i)
                    {
                        if (ints[i] is Dyn.Curve)
                        {
                            Dyn.Curve   ic   = ints[i] as Dyn.Curve;
                            Dyn.Surface isrf = ic.Extrude(Dyn.Vector.ZAxis().Scale(5));
                            vorocut.Add(isrf);
                        }
                        else
                        {
                            object t = ints[i];
                        }
                    }
                }
            }
            List <Dyn.Surface> voroPattern = new List <Dyn.Surface>();
            List <double>      voroArea    = new List <double>();
            List <Dyn.Point>   lpts        = new List <Dyn.Point>();

            Dyn.PolySurface vorocutPoly = Dyn.PolySurface.ByJoinedSurfaces(vorocut);
            Dyn.Geometry[]  splited     = boundarySrf.Split(vorocutPoly);
            for (int i = 0; i < splited.Length; ++i)
            {
                Dyn.Surface vsrf = splited[i] as Dyn.Surface;
                if (vsrf != null)
                {
                    //voroPattern.Add(Dyn.PolyCurve.ByJoinedCurves(vsrf.PerimeterCurves()));
                    voroPattern.Add(vsrf);
                    voroArea.Add(vsrf.Area);

                    foreach (Dyn.Point lp in pointsForLoad)
                    {
                        if (lp.DistanceTo(vsrf) < 0.005)
                        {
                            lpts.Add(lp);
                            break;
                        }
                    }
                }
            }


            //vorocutPoly.Dispose();

            return(new Dictionary <string, object>
            {
                { "LoadPoints", lpts },
                { "TributaryAreaSrfs", voroPattern },
                { "TributaryArea", voroArea }
            });
        }
Example #43
0
        /// <summary>
        /// Display color values on a surface.
        /// </summary>
        /// <param name="surface">The surface on which to apply the colors.</param>
        /// <param name="colors">A two dimensional list of Colors.</param>
        /// <returns>A Display object.</returns>
        public static Display BySurfaceColors(Surface surface, Color[][] colors)
        {
            if (surface == null)
            {
                throw new ArgumentNullException("surface");
            }

            if (colors == null)
            {
                throw new ArgumentNullException("colors");
            }

            if (!colors.Any())
            {
                throw new ArgumentException("You must supply some colors");
            }

            if (colors.Length == 1)
            {
                throw new ArgumentException("You must supply a two dimensional list of Colors.");
            }

            var size = colors[0].Count();
            foreach (var list in colors)
            {
                if (list.Count() != size)
                {
                    throw new ArgumentException("The list of colors must not be a jagged list.");
                }
            }

            return new Display(surface, colors);
        }
Example #44
0
        /// <summary>
        /// Creates Shell from Surface
        /// </summary>
        /// <param name="Surface">Dynamo Surface</param>
        /// <param name="ShellProp">Shell Property </param>
        /// <returns></returns>
        public static Shell FromSurface(Surface Surface, ShellProp ShellProp)
        {
            // TODO: IsPlanar logic should be added here! HANDLETHE ERROR.
            Shell tShell;
            ShellID tShellid = DynamoServices.TraceUtils.GetTraceData(TRACE_ID) as ShellID;

            if (tShellid == null)
            {
                // trace cache log didnoy return an objec, create new one !
                tShell = new Shell(Surface, ShellProp);
                // Set Label
                tShell.Label = String.Format("dyn_{0}", tShell.ID.ToString());
            }
            else
            {
                tShell = TracedShellManager.GetShellbyID(tShellid.IntID);

                tShell.BaseS = Surface;
                tShell.shellProp = ShellProp;
            }

            // Set the trace data on the return to be this Shell
            DynamoServices.TraceUtils.SetTraceData(TRACE_ID, new ShellID { IntID = tShell.ID });

            return tShell;
        }
Example #45
0
 private static Autodesk.DesignScript.Geometry.Surface Tag(Autodesk.DesignScript.Geometry.Surface srf,
                                                           Autodesk.Revit.DB.Reference reference)
 {
     return(reference != null?ElementFaceReference.AddTag(srf, reference) : srf);
 }
Example #46
0
        public static void CreateorUpdateArea(ref cSapModel Model, Surface s, ref string Id, bool update, double SF, ref string error)
        {
            Curve[] PerimeterCrvs = s.PerimeterCurves();
            List<Point> SurfPoints = new List<Point>();
            long ret = 0;
            int counter = 0;
            foreach (var crv in PerimeterCrvs)
            {
                SurfPoints.Add(crv.StartPoint);
            }

            if (!update) // Create new
            {
                List<string> ProfilePts = new List<string>();
                foreach (var v in SurfPoints)
                {
                    string dummy = null;
                    ret = Model.PointObj.AddCartesian(v.X * SF, v.Y * SF, v.Z * SF, ref dummy);
                    ProfilePts.Add(dummy);
                }

                string[] names = ProfilePts.ToArray();
                string dummyarea = string.Empty;
                ret = Model.AreaObj.AddByPoint(ProfilePts.Count(), ref names, ref dummyarea);
                if (ret == 1) counter++;
                Id = dummyarea;
            }
            else
            {  // TODO: Update Shell

                // Existing
                int eNumberofPts = 0;
                string[] ePtNames = null;
                ret = Model.AreaObj.GetPoints(Id, ref eNumberofPts, ref ePtNames);

                // Compare the number of points
                if (eNumberofPts == SurfPoints.Count())
                {
                    for (int i = 0; i < eNumberofPts; i++)
                    {
                        ret = Model.EditPoint.ChangeCoordinates_1(ePtNames[i], SurfPoints[i].X * SF, SurfPoints[i].Y * SF, SurfPoints[i].Z * SF);
                        if (ret == 1) counter++;
                    }
                }
                else if (eNumberofPts > SurfPoints.Count()) // remove Points
                {
                    for (int i = 0; i < eNumberofPts; i++)
                    {
                        if (i < SurfPoints.Count())
                        {
                            ret = Model.EditPoint.ChangeCoordinates_1(ePtNames[i], SurfPoints[i].X * SF, SurfPoints[i].Y * SF, SurfPoints[i].Z * SF);
                        }
                        else
                        {
                            ret = Model.SelectObj.ClearSelection();
                            ret = Model.AreaObj.SetSelected(Id, true);
                            ret = Model.PointObj.SetSelected(ePtNames[i], true);
                            ret = Model.EditArea.PointRemove();
                        }
                    }
                    if (ret == 1) counter++;
                }
                else if (eNumberofPts < SurfPoints.Count()) // add points
                {
                    for (int i = 0; i < SurfPoints.Count(); i++)
                    {
                        if (i < eNumberofPts)
                        {
                            ret = Model.EditPoint.ChangeCoordinates_1(ePtNames[i], SurfPoints[i].X * SF, SurfPoints[i].Y * SF, SurfPoints[i].Z * SF);
                        }
                        else
                        {
                            // add point to latest edge
                            ret = Model.SelectObj.ClearSelection();
                            int a = i - 1;
                            ret = Model.AreaObj.SetSelectedEdge(Id, a, true);

                            ret = Model.EditArea.PointAdd();

                            // the repeat the first step so # of name and has updated
                            int tempnumb = 0;
                            string[] TempPtNames = null;
                            ret = Model.AreaObj.GetPoints(Id, ref tempnumb, ref TempPtNames);

                            ret = Model.EditPoint.ChangeCoordinates_1(TempPtNames[i], SurfPoints[i].X * SF, SurfPoints[i].Y * SF, SurfPoints[i].Z * SF);
                        }
                    }
                    if (ret == 1) counter++;

                }

            }
            if (counter > 0) error = string.Format("Error creating Mesh{0}", Id);
        }
Example #47
0
 /// <summary>
 /// Constructs a CoordinateSystem at the given u, v parameters on the given surface. The x-axis of the CoordinateSystem 
 /// is aligned with the u-directional tangent, the y-axis with the v-directional tangent and the z-axis is mutually 
 /// perpendicular to the x and y axes.
 /// </summary>
 /// <param name="contextSurface"></param>
 /// <param name="u"></param>
 /// <param name="v"></param>
 /// <returns></returns>
 public static CoordinateSystem AtParameter(Surface contextSurface, double u, double v)
 {
     return AtParameterCore(contextSurface, u, v, true);//make sure it's visible
 }
Example #48
0
        //Length Scale Factor
        public static void GetShell(ref cSapModel Model, string areaid, ref Surface BaseS, double LSF, ref string PropName)
        {
            long ret = 0;

            int NumOfPts = 0;
            string[] PtsNames = null;
            ret = Model.AreaObj.GetPoints(areaid, ref NumOfPts, ref PtsNames);

            List<Point> dynPts = new List<Point>();
            List<IndexGroup> igs = new List<IndexGroup>();
            for (int i = 0; i < PtsNames.Count(); i++)
            {
                double x = 0;
                double y = 0;
                double z = 0;

                ret = Model.PointObj.GetCoordCartesian(PtsNames[i], ref x, ref y, ref z);

                Point p = Point.ByCoordinates(x * LSF, y * LSF, z * LSF);
                dynPts.Add(p);
            }

            //Mesh.ByPointsFaceIndices()
            BaseS = Surface.ByPerimeterPoints(dynPts);

            // Get assigned Property Name
            ret = Model.AreaObj.GetProperty(areaid, ref PropName);
        }
Example #49
0
        //**INTERNAL FUNCTIONS
        /// <summary>
        /// maps surfaces to XYplane: iterate over list of surface arrays
        /// and map each surface onto XY plane while maintaining index structure.
        /// </summary>
        /// <param name="surfacesInput">list of closed planar surfaces</param>
        /// <returns>list of closed surface arrays on XYplane</returns>
        private List<Surface[]> MapToXYPlane(List<Surface[]> surfacesInput)
        {
            List<Surface[]> surfacesResult = new List<Surface[]>();
            for (int i = 0; i < surfacesInput.Count; i++ )
            {
                Surface[] surfaces = new Surface[surfacesInput[i].Length];
                for (int j = 0; j < surfacesInput[i].Length; j++)
                {
                    surfaces[j] = (Surface) surfacesInput[i][j].Transform(surfacesInput[i][j].CoordinateSystemAtParameter(0.5, 0.5), CoordinateSystem.Identity());
                }
                surfacesResult.Add(surfaces);
            }

            return surfacesResult;
        }
Example #50
0
        /// <summary>
        /// Create Rebar following a selected surface
        /// </summary>
        /// <param name="face">Surface</param>
        /// <param name="numberOfCurves">Define number of curves or distance between bars</param>
        /// <param name="distanceBetweenCurves">Define distance between curves or number of bars</param>
        /// <param name="flip">Flip orientation</param>
        /// <param name="offset">Offset</param>
        /// <param name="idealize">Idealize surfaces to rectangles</param>
        /// <returns>List of rebar</returns>
        public static List<Curve> FollowingSurface(Surface face, int numberOfCurves, double distanceBetweenCurves = 0, bool flip = true, double offset = 0, bool idealize = true)
        {
            if (idealize)
            {
                return face.Follow(50, offset, distanceBetweenCurves, numberOfCurves, flip);
            }
            else
            {

                // Create return value collection
                List<Curve> curves = new List<Curve>();

                // Get a reference curve from the surface
                UV p1 = UV.ByCoordinates(0, 0);
                UV p2 = UV.ByCoordinates(1, 0);

                double length = (!flip) ? face.DistanceBetweenPoints(p1, p2) : face.DistanceBetweenPoints(p1.Flip(), p2.Flip());

                // If there is a distance applied use it to determine the number of lines to create
                if (distanceBetweenCurves > 0) numberOfCurves = (int)(length / (distanceBetweenCurves));

                numberOfCurves++;

                Surface surface = face;

                if (offset != 0) surface = (Surface)face.Offset(offset);
                

                TrimmedSurface trimmedSurface = new TrimmedSurface(surface);

                // Walk thru the amount of lines to create
                for (int j = 1; j < numberOfCurves; j++)
                {
                    // Create a set of points for createing a curve
                    List<Point> points = new List<Point>();

                    // Get the height parameter
                    double height = (double)j / (double)numberOfCurves;

                    curves.Add(trimmedSurface.GetCurveAtParameter(height, flip));
                }

                return curves;
            }
        }