Beispiel #1
0
        public void DivideFromPoint()
        {
            var grid = new Grid1d(new Line(new Vector3(-5, -5), new Vector3(5, 5)));

            grid.DivideByFixedLengthFromPoint(3, new Vector3(-4, 4));
            Assert.Equal(6, grid.Cells.Count);
        }
Beispiel #2
0
        public void GridFromCurves()
        {
            var a       = Vector3.Origin;
            var b       = new Vector3(5, 0, 1);
            var c       = new Vector3(5, 5, 2);
            var d       = new Vector3(0, 5, 3);
            var e       = new Vector3(0, 0, 4);
            var f       = new Vector3(5, 0, 5);
            var ctrlPts = new List <Vector3> {
                a, b, c, d, e, f
            };

            var bezier1 = new Bezier(ctrlPts);

            var grid = new Grid1d(bezier1);

            grid.DivideByApproximateLength(0.5, EvenDivisionMode.RoundUp);
            var cellGeometry = grid.GetCells().Select(cl => cl.GetCellGeometry());

            Assert.Equal(25, cellGeometry.Count());


            var r  = 2.0;
            var a1 = new Arc(new Vector3(5, 0), r, -90.0, 90.0);

            var arcGrid = new Grid1d(a1);

            arcGrid.DivideByApproximateLength(1, EvenDivisionMode.RoundDown);
            arcGrid.Cells[1].DivideByCount(4);
            var arcCellGeometry = arcGrid.GetCells().Select(cl => cl.GetCellGeometry());

            Assert.Equal(9, arcCellGeometry.Count());
        }
Beispiel #3
0
 private static void PanelGroundFloor(double bottomElevation,
                                      double topElevation,
                                      Line[] boundarySegments,
                                      double panelWidth,
                                      Model model)
 {
     foreach (var segment in boundarySegments)
     {
         var u      = new Grid1d(segment);
         var v      = new Grid1d(new Line(segment.Start, new Vector3(segment.Start.X, segment.Start.Y, segment.Start.Z + topElevation)));
         var grid2d = new Grid2d(u, v);
         grid2d.U.DivideByFixedLength(1.5);
         grid2d.V.DivideByCount(2);
         foreach (var sep in grid2d.GetCellSeparators(GridDirection.U))
         {
             var mullion = new Beam((Line)sep, Polygon.Rectangle(0.05, 0.05), BuiltInMaterials.Black);
             model.AddElement(mullion);
         }
         foreach (var sep in grid2d.GetCellSeparators(GridDirection.V))
         {
             var mullion = new Beam((Line)sep, Polygon.Rectangle(0.05, 0.05), BuiltInMaterials.Black);
             model.AddElement(mullion);
         }
         var panel = new Panel(new Polygon(new[] {
             segment.Start, segment.End, new Vector3(segment.End.X, segment.End.Y, segment.End.Z + topElevation), new Vector3(segment.Start.X, segment.Start.Y, segment.Start.Z + topElevation)
         }), BuiltInMaterials.Glass);
         model.AddElement(panel);
     }
 }
Beispiel #4
0
        public void Grid1dFixedDivisions()
        {
            var length      = 10;
            var panelTarget = 3;
            var sacrificial = 0;
            var inMiddle    = new Grid1d(new Line(new Vector3(0, 0, 0), new Vector3(length, 0, 0)));
            var atStart     = new Grid1d(new Line(new Vector3(0, 1, 0), new Vector3(length, 1, 0)));
            var atEnd       = new Grid1d(new Line(new Vector3(0, 2, 0), new Vector3(length, 2, 0)));
            var atBothEnds  = new Grid1d(new Line(new Vector3(0, 3, 0), new Vector3(length, 3, 0)));

            inMiddle.DivideByFixedLength(panelTarget, FixedDivisionMode.RemainderNearMiddle, sacrificial);
            atStart.DivideByFixedLength(panelTarget, FixedDivisionMode.RemainderAtStart, sacrificial);
            atEnd.DivideByFixedLength(panelTarget, FixedDivisionMode.RemainderAtEnd, sacrificial);
            atBothEnds.DivideByFixedLength(panelTarget, FixedDivisionMode.RemainderAtBothEnds, sacrificial);

            Assert.Equal(panelTarget, inMiddle.Cells.First().Domain.Length);
            Assert.Equal(panelTarget, inMiddle.Cells.Last().Domain.Length);

            Assert.NotEqual(panelTarget, atStart.Cells.First().Domain.Length);
            Assert.Equal(panelTarget, atStart.Cells.Last().Domain.Length);

            Assert.Equal(panelTarget, atEnd.Cells.First().Domain.Length);
            Assert.NotEqual(panelTarget, atEnd.Cells.Last().Domain.Length);

            Assert.NotEqual(panelTarget, atBothEnds.Cells.First().Domain.Length);
            Assert.NotEqual(panelTarget, atBothEnds.Cells.Last().Domain.Length);
        }
Beispiel #5
0
        /// <summary>
        /// Add graph section using polygon, extruded in given direction.
        /// Any vertices that already exist are not created but reused.
        /// This way new region is connected with the rest of the graph.
        /// </summary>
        /// <param name="boundingPolygon">Base polygon</param>
        /// <param name="extrusionAxis">Extrusion direction</param>
        /// <param name="distance">Height of polygon extrusion</param>
        /// <param name="keyPoints">Set of 3D points, region is split with.</param>
        public void AddFromExtrude(Polygon boundingPolygon, Vector3 extrusionAxis, double distance, List <Vector3> keyPoints)
        {
            var gridZ = new Grid1d(new Line(boundingPolygon.Start, boundingPolygon.Start + distance * extrusionAxis));

            gridZ.SplitAtPoints(keyPoints);
            var edgesBefore = GetEdges();

            var zCells = gridZ.GetCells();

            for (var i = 0; i < zCells.Count; i++)
            {
                var elevationVector          = zCells[i].Domain.Min * extrusionAxis;
                var transformedPolygonBottom = boundingPolygon.TransformedPolygon(new Transform(elevationVector));
                var grid = CreateGridFromPolygon(transformedPolygonBottom);
                SplitGrid(grid, keyPoints);
                SplitGridAtIntersectionPoints(boundingPolygon, grid, edgesBefore);
                var addedEdges = AddFromGrid(grid, edgesBefore);
                AddVerticalEdges(extrusionAxis, zCells[i].Domain.Length, addedEdges);
                if (i == zCells.Count - 1)
                {
                    var transformedPolygonTop = boundingPolygon.TransformedPolygon(
                        new Transform(zCells[i].Domain.Max * extrusionAxis));
                    grid = CreateGridFromPolygon(transformedPolygonTop);
                    SplitGrid(grid, keyPoints);
                    SplitGridAtIntersectionPoints(boundingPolygon, grid, edgesBefore);
                    AddFromGrid(grid, edgesBefore);
                }
            }
        }
Beispiel #6
0
        public void Grid2dSerializes()
        {
            Name = "grid2d serializes";
            var polyline = new Polyline(new[] {
                new Vector3(0, 0, 0),
                new Vector3(10, 2, 0),
                new Vector3(30, 4, 0),
            });
            var uGrid  = new Grid1d(polyline);
            var p2     = new Line(Vector3.Origin, new Vector3(0, 20, 0));
            var vGrid  = new Grid1d(p2);
            var grid2d = new Grid2d(uGrid, vGrid);

            grid2d.U.DivideByCount(10);
            grid2d.V.DivideByCount(3);
            grid2d[2, 2].U.DivideByCount(4);
            var json         = JsonConvert.SerializeObject(grid2d);
            var deserialized = JsonConvert.DeserializeObject <Grid2d>(json);

            Assert.Equal(grid2d.GetCells().Count, deserialized.GetCells().Count);

            var grid2dElem = new Grid2dElement(grid2d, Guid.NewGuid(), "Grid");

            Model.AddElement(grid2dElem);
        }
Beispiel #7
0
        public void DivideFromPosition()
        {
            var grid = new Grid1d(new Domain1d(-8, 8));

            Assert.Throws <ArgumentException>(() => grid.DivideByFixedLengthFromPosition(1, 10));
            grid.DivideByFixedLengthFromPosition(4, 0);
            Assert.Equal(4, grid.Cells.Count);
        }
Beispiel #8
0
        public void Grid1d()
        {
            this.Name = "Elements_Spatial_Grid1d";

            // <example>
            // Create a 1d Grid from a line
            var line = new Line(new Vector3(5, 0, 0), new Vector3(60, 0, 0));
            var grid = new Grid1d(line);

            // Divide the grid into sections of length 10, and leave remainders
            // at both ends
            grid.DivideByFixedLength(10, FixedDivisionMode.RemainderAtBothEnds);

            // Take the second grid segment and subdivide it
            // into 5 equal length segments
            grid[1].DivideByCount(5);

            // Take the third grid segment and subdivide it into
            // segments of approximate length 3
            grid[2].DivideByApproximateLength(3);

            // Take the fourth grid segment and subdivide it by a repeating pattern
            var pattern = new[] { 1.0, 1.5 };

            grid[3].DivideByPattern(pattern);

            // Retrieve all bottom-level cells.
            // Note that grid.Cells gets the top-level cells only, and
            // grid.GetCells() recursively gets the bottom-level individual cells.
            var cells = grid.GetCells();

            // Get lines representing each cell
            var lines = cells.Select(c => c.GetCellGeometry()).OfType <Line>();

            // Create walls from lines, and assign a random color material
            List <Wall> walls = new List <Wall>();
            var         rand  = new Random();

            foreach (var wallLine in lines)
            {
                var color = new Color(rand.NextDouble(), rand.NextDouble(), rand.NextDouble(), 1.0);
                walls.Add(new StandardWall(wallLine, 0.1, 3.0, new Material(color.ToString(), color, 0, 0, null, false, false)));
            }

            // Create rectangles from top-level grid cells
            var topLevelCells = grid.Cells.Select(c => c.GetCellGeometry()).OfType <Line>();
            var cellRects     = new List <ModelCurve>();

            foreach (var topLevelCell in topLevelCells)
            {
                var rect = Polygon.Rectangle(topLevelCell.Start - new Vector3(0, 2, 0), topLevelCell.End + new Vector3(0, 2, 0));
                cellRects.Add(new ModelCurve(rect));
            }
            // </example>

            this.Model.AddElements(cellRects);
            this.Model.AddElements(walls);
        }
Beispiel #9
0
        public void AlreadySplitGridsThrowsExceptionWhenDividedByN()
        {
            var grid = new Grid1d();

            grid.SplitAtParameter(0.25);
            var ex = Assert.Throws <Exception>(() => grid.DivideByCount(10));

            Assert.Equal("This grid already has subdivisions. Maybe you meant to select a subgrid to divide?", ex.Message);
        }
Beispiel #10
0
        public void DivideFromPosition()
        {
            var grid = new Grid1d(new Domain1d(-8, 8));

            grid.DivideByFixedLengthFromPosition(20, 10);
            Assert.Null(grid.Cells); // this should have been left undivided
            grid.DivideByFixedLengthFromPosition(4, 0);
            Assert.Equal(4, grid.Cells.Count);
        }
Beispiel #11
0
        public void SplitAtOffset()
        {
            var grid = new Grid1d(30);

            grid.SplitAtOffset(5);
            grid.SplitAtOffset(5, true);
            Assert.Equal(5, grid.Cells[0].Domain.Length);
            Assert.Equal(20, grid.Cells[1].Domain.Length);
            Assert.Equal(5, grid.Cells[2].Domain.Length);
        }
Beispiel #12
0
        public void ChildGridUpdatesParent()
        {
            var u      = new Grid1d(10);
            var v      = new Grid1d(5);
            var grid2d = new Grid2d(u, v);

            Assert.Single(grid2d.CellsFlat);
            grid2d.U.DivideByCount(10);
            grid2d.V.DivideByCount(5);
            Assert.Equal(50, grid2d.CellsFlat.Count);
        }
Beispiel #13
0
        public void SplitAtPositions()
        {
            var positions = new[] { 3.0, 8, 5, 4 };
            var grid      = new Grid1d(10);

            grid.SplitAtPositions(positions);
            Assert.Equal(5, grid.Cells.Count);
            Assert.Equal(1, grid[1].Domain.Length);
            grid.SplitAtPosition(8); // should do nothing but not throw an error
            Assert.Equal(5, grid.Cells.Count);
        }
Beispiel #14
0
        public void DivideGridFromOrigin()
        {
            var grid1 = new Grid1d(10);

            grid1.DivideByFixedLengthFromPosition(3, 5);
            var cellGeo = grid1.GetCells().Select(c => c.GetCellGeometry());

            Assert.Equal(4, cellGeo.Count());
            Assert.Equal(2, cellGeo.Last().Length());
            Assert.Equal(3, cellGeo.ToArray()[1].Length());
        }
Beispiel #15
0
        public void PatternTooLongThrowsException()
        {
            var grid    = new Grid1d(4);
            var pattern = new List <(string, double)>
            {
                ("Solid", 1),
                ("Glazing", 3),
                ("Fin", 0.2)
            };
            Exception ex = Assert.Throws <ArgumentException>(() => grid.DivideByPattern(pattern, PatternMode.None, FixedDivisionMode.RemainderAtBothEnds));

            Assert.Equal("The grid could not be constructed. Pattern length exceeds grid length.", ex.Message);
        }
Beispiel #16
0
        public void SplitGridAtParameters()
        {
            var grid = new Grid1d(new Domain1d(50, 100));

            grid.SplitAtParameter(0.25);
            var subCell = grid.Cells[1];

            subCell.DivideByCount(5);
            subCell.Cells[3].DivideByApproximateLength(1.2, EvenDivisionMode.Nearest);
            var allCells     = grid.GetCells();
            var cellGeometry = allCells.Select(c => c.GetCellGeometry());

            Assert.Equal(11, allCells.Count);
        }
Beispiel #17
0
        public void Grid1dApproximateLength()
        {
            var grid1 = new Grid1d(10.5);
            var grid2 = new Grid1d(10.5);
            var grid3 = new Grid1d(10.2);

            grid1.DivideByApproximateLength(6, EvenDivisionMode.Nearest);
            Assert.Equal(2, grid1.Cells.Count);

            grid2.DivideByApproximateLength(4, EvenDivisionMode.RoundUp);
            Assert.Equal(3, grid2.Cells.Count);

            grid3.DivideByApproximateLength(1, EvenDivisionMode.RoundDown);
            Assert.Equal(10, grid3.Cells.Count);
        }
Beispiel #18
0
        private void AddEdge(long key, long startVertexId, long endVertexId)
        {
            if (this.Points.TryGetValue(startVertexId, out var start) && this.Points.TryGetValue(endVertexId, out var end))
            {
                var dist = start.DistanceTo(end);
                var line = new Line(start, end);

                if (!SkipSubdivide && dist > DivisionLength && (start.X != end.X || start.Y != end.Y))
                {
                    var indices = new List <long>()
                    {
                        startVertexId
                    };

                    var grid = new Grid1d(line);
                    grid.DivideByFixedLength(DivisionLength, FixedDivisionMode.RemainderAtBothEnds);
                    var cells = grid.GetCells();

                    // Get lines representing each 10' cell
                    var cellLines = cells.Select(c => c.GetCellGeometry()).OfType <Line>().ToArray();

                    // Add end of each division except for last point
                    foreach (var cellLine in cellLines.SkipLast(1))
                    {
                        var index = this._maxVertexKey + 1;
                        var point = cellLine.PointAt(1.0);
                        this.Points.Add(index, point);
                        indices.Add(index);
                        this._maxVertexKey = index;
                    }

                    // Add right point
                    indices.Add(endVertexId);
                    this.Lines.Add(key, indices);
                }
                else
                {
                    this.Lines.Add(key, new List <long>()
                    {
                        startVertexId, endVertexId
                    });
                }
            }
            else
            {
                throw new Exception("Malformed geometry found: no vertex found at address for this edge.");
            }
        }
Beispiel #19
0
        public void SplitAtPositionsInRightPlace()
        {
            var simpleLine    = new Line(Vector3.Origin, new Vector3(10, 0, 0));
            var lineGrid      = new Grid1d(simpleLine);
            var splitLocation = new Vector3(3, 0, 0);

            lineGrid.SplitAtPoint(splitLocation);
            Assert.True(lineGrid[0].GetCellGeometry().PointAt(1.0).DistanceTo(splitLocation) < 0.01);

            var polyline              = new Polyline(new[] { Vector3.Origin, new Vector3(3, 5), new Vector3(6, 2), new Vector3(10, -3) });
            var polylineGrid          = new Grid1d(polyline);
            var polylineSplitLocation = new Vector3(3, 5);

            polylineGrid.SplitAtPoint(polylineSplitLocation);
            Assert.True(polylineGrid[0].GetCellGeometry().PointAt(1.0).DistanceTo(polylineSplitLocation) < 0.01);
        }
Beispiel #20
0
        public void GetSeparators()
        {
            var grid = new Grid1d(100);

            grid.DivideByCount(5);
            var pts = grid.GetCellSeparators();

            Assert.Equal(6, pts.Count);
            Assert.Equal(pts[0], new Vector3(0, 0, 0));
            Assert.Equal(pts[1], new Vector3(20, 0, 0));
            Assert.Equal(pts[5], new Vector3(100, 0, 0));

            grid[1].DivideByCount(3);
            var pts2 = grid.GetCellSeparators(true);

            Assert.Equal(8, pts2.Count);
        }
Beispiel #21
0
        public void Grid1dSerializes()
        {
            var polyline = new Polyline(new[] {
                new Vector3(0, 0, 0),
                new Vector3(10, 2, 0),
                new Vector3(30, 4, 0),
            });
            var grid = new Grid1d(polyline);

            grid.DivideByCount(4);
            grid[3].DivideByFixedLength(0.4);
            var json         = JsonConvert.SerializeObject(grid);
            var deserialized = JsonConvert.DeserializeObject <Grid1d>(json);

            Assert.Equal(grid.GetCells().Count, deserialized.GetCells().Count);
            Assert.Equal(0, (grid.Curve as Polyline).Start.DistanceTo((deserialized.Curve as Polyline).Start));
        }
Beispiel #22
0
        public void DivideByPatternWithoutRemainder()
        {
            var grid    = new Grid1d(6);
            var pattern = new List <(string typename, double length)>
            {
                ("A", 2),
                ("B", 1)
            };

            grid.DivideByPattern(pattern, PatternMode.Cycle, FixedDivisionMode.RemainderAtEnd);
            var cells = grid.GetCells();

            for (int i = 0; i < cells.Count; i++)
            {
                Assert.Equal(pattern[i % pattern.Count].typename, cells[i].Type);
                Assert.Equal(pattern[i % pattern.Count].length, cells[i].Domain.Length, 3);
            }
        }
Beispiel #23
0
        public void DivideByPattern()
        {
            var grid    = new Grid1d(new Domain1d(60, 150));
            var pattern = new List <(string typename, double length)>
            {
                ("Solid", 1),
                ("Glazing", 3),
                ("Fin", 0.2)
            };

            grid.DivideByPattern(pattern, PatternMode.Cycle, FixedDivisionMode.RemainderAtBothEnds);
            var cells = grid.GetCells();
            var types = cells.Select(c => c.Type);

            for (int i = 0; i < 10; i++)
            {
                Assert.Equal(pattern[i % pattern.Count].length, cells[i + 1].Domain.Length, 3);
                Assert.Equal(pattern[i % pattern.Count].typename, cells[i + 1].Type);
            }
        }
Beispiel #24
0
        /// <summary>
        /// The BallonaBridge function.
        /// </summary>
        /// <param name="model">The input model.</param>
        /// <param name="input">The arguments to the execution.</param>
        /// <returns>A BallonaBridgeOutputs instance containing computed results and the model with any new elements.</returns>
        public static BallonaBridgeOutputs Execute(Dictionary <string, Model> inputModels, BallonaBridgeInputs input)
        {
            /// Your code here.
            var output = new BallonaBridgeOutputs(1.0);

            Elements.Material brdigeMaterial = null;
            switch (input.Material)
            {
            case Material.Red:
                brdigeMaterial = new Elements.Material("Red", Colors.Red, 0.0f, 0.0f);
                break;

            case Material.Steel:
                brdigeMaterial = BuiltInMaterials.Steel;
                break;

            case Material.Wood:
                brdigeMaterial = BuiltInMaterials.Wood;
                break;
            }
            var beam = new Beam(input.CenterLine, Polygon.Rectangle(input.BridgeWidth, input.BridgeHeight), brdigeMaterial);

            var offsetCrv = input.CenterLine.Offset(5, EndType.Square);

            // output.model.AddElement(offsetCrv);


            var grid = new Grid1d(offsetCrv[0]);

            grid.DivideByApproximateLength(1.0);
            foreach (var pt in grid.GetCellSeparators())
            {
                var column = new Column(pt, 5, Polygon.Rectangle(0.05, 0.05));
                output.model.AddElement(column);
            }

            output.model.AddElement(beam);
            return(output);
        }
Beispiel #25
0
        public void TryToSplitButAlreadySplitAtLowerLevel()
        {
            //var grid = new Grid1d(100);
            //grid.DivideByCount(2); //now split at 50
            //grid[1].SplitAtParameter(0.5); // splitting child cell at halfway mark = 75 on the parent
            //grid.SplitAtPosition(75); // should silently do nothing.
            //Assert.Equal(3, grid.GetCells().Count);

            var grid2 = new Grid1d(256);

            grid2.DivideByCount(2);          //split at 128
            grid2[0].DivideByCount(2);       // split at 64
            grid2[0][0].DivideByCount(2);    // split at 32
            grid2[0][0][0].DivideByCount(2); // split at 16
            grid2.SplitAtPosition(32);
            Assert.Equal(5, grid2.GetCells().Count);
            Assert.Equal(3, grid2.Cells.Count);
            Assert.Single(grid2[0].Cells);
            Assert.Equal(2, grid2[1].Cells.Count);
            Assert.Single(grid2[0][0].Cells);
            Assert.Equal(2, grid2[0][0][0].Cells.Count);
        }
Beispiel #26
0
        /// <summary>
        /// Construct a set of elements from this rule for a given definition.
        /// </summary>
        /// <param name="definition">The definition to instantiate.</param>
        public List <Element> Instantiate(ComponentDefinition definition)
        {
            var arrayElements = new List <Element>();
            var newVertices   = PolylinePlacementRule.TransformPolyline(this, definition);

            var path = IsClosed ? new Polygon(newVertices) : new Polyline(newVertices);

            var grid1d = new Grid1d(path);

            switch (SpacingRule.SpacingMode)
            {
            case SpacingMode.ByLength:
                grid1d.DivideByFixedLength(SpacingRule.Value);
                break;

            case SpacingMode.ByApproximateLength:
                grid1d.DivideByApproximateLength(SpacingRule.Value);
                break;

            case SpacingMode.ByCount:
                grid1d.DivideByCount((int)SpacingRule.Value);
                break;
            }

            var separators = grid1d.GetCellSeparators();

            foreach (var sep in separators)
            {
                ElementDefinition.IsElementDefinition = true;
                var transform = new Transform(definition.OrientationGuide);
                transform.Concatenate(new Transform(sep));
                var instance = ElementDefinition.CreateInstance(transform, Guid.NewGuid().ToString());
                arrayElements.Add(instance);
            }
            return(arrayElements);
        }
Beispiel #27
0
        /**
         * Does the computation
         */
        protected override void SolveRabbitInstance(IGH_DataAccess DA)
        {
            List <GH_Point> pointsList = new List <GH_Point>();

            DA.GetDataList(1, pointsList);

            int XDimension = pointsList.Count;

            IList <Point3d> genericPoints = GH_PointUtils.ConvertToOnPoints(pointsList);


            //Get the cell prototype------------------------------------------------------------
            GH_ObjectWrapper cellPrototypeWrapper = null;

            DA.GetData <GH_ObjectWrapper>(0, ref cellPrototypeWrapper);
            ICell cellPrototype = (ICell)cellPrototypeWrapper.Value;

            //----------------------------------------------------------------------------------
            List <GH_ObjectWrapper> stateConfigurations = new List <GH_ObjectWrapper>();

            DA.GetDataList(2, stateConfigurations);

            GH_ObjectWrapper stateConfigWrapper1;
            OnStateConfig    stateConfig = null;

            foreach (GH_ObjectWrapper stateConfigWrapper in stateConfigurations)
            {
                if (stateConfigWrapper != null)// Custom configuration defined
                {
                    if (stateConfigWrapper.Value.GetType() == typeof(OnStateConfig))
                    {
                        stateConfig = (OnStateConfig)stateConfigWrapper.Value;
                        //get the user-defined points that define custom Cell State
                        IList <Point3d> userConfigurationGHPoints = stateConfig.GetPoints();
                        //get the real configuration points, by finding the points that are closer to the user defined configuration points
                        IList <Point3d> realConfigurationPoints = PointUtils.GetClosestPoints(userConfigurationGHPoints, genericPoints);
                        stateConfig.SetPoints(realConfigurationPoints);
                    }
                }
            }
            //----------------------------------------------------------------------------------

            //build the grid
            Grid1d <ICell> space1d = new Grid1d <ICell>(XDimension);

            CellState ghAliveState = new GH_CellState(new GH_Boolean(true));
            CellState ghDeadState  = new GH_CellState(new GH_Boolean(false));

            //populate the grid
            for (int i = 0; i < XDimension; i++)
            {
                ICell cell = cellPrototype.Clone();
                cell.SetId(i);//very important as this identifies the cell
                if (stateConfig != null)
                {
                    foreach (Point3d configurationPoint in stateConfig.GetPoints())
                    {
                        if (pointsList[i].Value.X == configurationPoint.X && pointsList[i].Value.Y == configurationPoint.Y && pointsList[i].Value.Z == configurationPoint.Z)
                        {
                            cell.SetState(stateConfig.GetState());
                        }
                    }
                }

                cell.SetAttachedObject(pointsList[i]);
                space1d.Add(cell, i);
            }

            //build neighborhood
            for (int i = 0; i < XDimension; i++)
            {
                ElementaryCell cell = (ElementaryCell)space1d.GetObjectAt(i);
                //IList<ICell> neighbors = new List<ICell>(2);
                if (i > 0)
                {
                    cell.SetLeftNeighbor((ElementaryCell)space1d.GetObjectAt(i - 1));//neighbors.Add(cells[(i - 1)%XDimension]);
                }
                else if (i == 0)
                {
                    cell.SetLeftNeighbor((ElementaryCell)space1d.GetObjectAt(XDimension - 1));//neighbors.Add(cells[(i - 1)%XDimension]);
                }
                if (i < XDimension - 1)
                {
                    cell.SetRightNeighbor((ElementaryCell)space1d.GetObjectAt(i + 1));//neighbors.Add(cells[(i + 1)%XDimension]);
                }
                else if (i == XDimension - 1)
                {
                    cell.SetRightNeighbor((ElementaryCell)space1d.GetObjectAt(0));
                }
            }


            CA ca = new CA(space1d);

            //set the output parameters
            DA.SetData(0, ca);
        }
        /// <summary>
        /// The Testfunction1 function.
        /// </summary>
        /// <param name="model">The input model.</param>
        /// <param name="input">The arguments to the execution.</param>
        /// <returns>A Testfunction1Outputs instance containing computed results and the model with any new elements.</returns>
        public static Testfunction1Outputs Execute(Dictionary <string, Model> inputModels, Testfunction1Inputs input)
        {
            /// Your code here.
            var output = new Testfunction1Outputs(1.0);
            List <ModelCurve> modelCurves = new List <ModelCurve>();
            List <Curve>      Curves      = new List <Curve>();

            Elements.Material brdigeMaterial = null;
            switch (input.Material)
            {
            case Material.Red:
                brdigeMaterial = new Elements.Material("Red", Colors.Red, 0.0f, 0.0f);
                break;

            case Material.Steel:
                brdigeMaterial = BuiltInMaterials.Steel;
                break;

            case Material.Wood:
                brdigeMaterial = BuiltInMaterials.Wood;
                break;
            }
            var            profile          = WideFlangeProfileServer.Instance.GetProfileByType(WideFlangeProfileType.W10x100);
            var            pts              = new List <Vector3>();
            var            centerCrv        = input.CenterLine;
            var            offsetCrv        = input.CenterLine.Offset(input.OffsetWidth, EndType.Square)[0];
            var            offsetCrv2       = input.CenterLine.Offset(input.OffsetWidth / 2, EndType.Square)[0];
            var            rebuildOffsetCrv = new Polygon(offsetCrv.Vertices);
            var            LGon             = Polygon.L(15, 15, 5);
            var            ltransform       = new Transform(15, 0, 0);
            List <Polygon> testPoly         = new List <Polygon>();

            testPoly.AddRange(new[] { rebuildOffsetCrv, Polygon.Rectangle(15, 15), ltransform.OfPolygon(LGon) });

            foreach (var poly in testPoly)
            {
                var beam = new Beam(poly, Polygon.Rectangle(input.BridgeWidth, input.BridgeHeight), brdigeMaterial);
                // var beam = new Beam(poly, profile, brdigeMaterial);
                output.Model.AddElement(beam);
                var grid = new Grid1d(poly);

                grid.DivideByApproximateLength(3);

                foreach (var pt in grid.GetCellSeparators())
                {
                    var column = new Column(pt, 5, Polygon.Rectangle(0.1, 0.1));
                    output.Model.AddElement(column);
                }
            }
            var secLine = new Line(new Vector3(-input.OffsetWidth * 2, 0, 0), new Vector3(input.OffsetWidth * 2, 0, 0));
            // List<Plane> planes = new List<Plane>();
            List <Line> secLines = new List <Line>();


            var crvSegments = centerCrv.Segments();

            foreach (var crv in crvSegments)
            {
                var grid = new Grid1d(crv);

                grid.DivideByApproximateLength(3);

                foreach (var pt in grid.GetCellSeparators())
                {
                    // planes.Add(new Plane(pt, Vector3.XAxis(pt)))
                    // pts.Add(pt);
                    var transform = new Transform(pt, crv.Direction());
                    secLines.Add(transform.OfLine(secLine));
                    // planes.Add(new Plane(pt, crv.Direction()));
                    var column = new Column(pt, 5, Polygon.Rectangle(0.1, 0.1));
                    output.Model.AddElement(column);
                }
            }

            Curves.AddRange(new[] { centerCrv, offsetCrv, (Curve)secLine });
            Curves.AddRange(secLines);
            foreach (var crv in Curves)
            {
                modelCurves.Add(new ModelCurve(crv));
            }
            // var pink = new Elements.Material("pink", Colors.Pink);
            // var modelPoints = new ModelPoints(pts, pink);


            // var crvs = new List<Curve>{Polygon.Rectangle(10,10), offsetCrv[0]};

            // foreach(var crv in crvs) {
            //   modelCurves.Add(new ModelCurve(crv));
            //   var grid = new Grid1d(crv);
            //   grid.DivideByApproximateLength(1.0);
            //   foreach(var pt in grid.GetCellSeparators())
            //   {
            //     var column = new Column(pt, 5, Polygon.Rectangle(0.05, 0.05));
            //     output.Model.AddElement(column);
            //   }

            // }
            // output.Model.AddElements(modelPoints);
            output.Model.AddElements(modelCurves);
            // output.Model.AddElement(beam);
            return(output);
        }
Beispiel #29
0
        /// <summary>
        /// The BigBoxFacade function.
        /// </summary>
        /// <param name="model">The input model.</param>
        /// <param name="input">The arguments to the execution.</param>
        /// <returns>A BigBoxFacadeOutputs instance containing computed results and the model with any new elements.</returns>
        public static BigBoxFacadeOutputs Execute(Dictionary <string, Model> inputModels, BigBoxFacadeInputs input)
        {
            Envelope envelope = null;

            inputModels.TryGetValue("Envelope", out var envelopeModel);
            if (envelopeModel != null)
            {
                var envelopes = new List <Envelope>();
                envelopes.AddRange(envelopeModel.AllElementsOfType <Envelope>());
                var aboveGradeEnvelopes = envelopes.Where(e => e.Elevation >= 0.0).ToList();
                if (aboveGradeEnvelopes.Count() > 0)
                {
                    envelope = aboveGradeEnvelopes.First();
                }
            }
            if (envelope == null)
            {
                var envMatl   = new Material("envelope", new Color(1.0, 1.0, 1.0, 0.2), 0.0f, 0.0f);
                var height    = 15.0;
                var footprint = Polygon.Rectangle(60, 40);
                var extrude   = new Elements.Geometry.Solids.Extrude(footprint, height, Vector3.ZAxis, false);
                var geomRep   = new Representation(new List <Elements.Geometry.Solids.SolidOperation>()
                {
                    extrude
                });
                envelope = new Envelope(footprint, 0.0, height, Vector3.ZAxis, 0.0,
                                        new Transform(), envMatl, geomRep, false, Guid.NewGuid(), "");
            }

            var output           = new BigBoxFacadeOutputs(envelope.Profile.Perimeter.Area());
            var boundarySegments = envelope.Profile.Perimeter.Segments();
            var panelMat         = new Material("envelope", new Color(1.0, 1.0, 1.0, 1), 0.5f, 0.5f);

            var lowestSegment = boundarySegments.OrderBy((s) => s.Start.Average(s.End).Y).First();

            foreach (var s in boundarySegments)
            {
                var d = s.Direction();

                try {
                    var t = new Transform(s.Start + new Vector3(0, 0, 0), d, d.Cross(Vector3.ZAxis));
                    var l = s.Length();

                    if (lowestSegment == s)
                    {
                        var grid             = new Grid1d(s);
                        var doorWidth        = 4;
                        var backwardsLine    = s.Start.X > s.End.X;
                        var reverseDirection = backwardsLine != input.EntranceOnRight;

                        var leftDoor       = 0.0;
                        var rightDoor      = 0.0;
                        var leftDoorWidth  = 0.0;
                        var rightDoorWidth = 0.9;
                        if (reverseDirection)
                        {
                            leftDoor       = l / 10 * 2;
                            rightDoor      = l / 10 * 6;
                            leftDoorWidth  = doorWidth;
                            rightDoorWidth = doorWidth * 2.0;
                        }
                        else
                        {
                            leftDoor       = l / 10 * 4;
                            rightDoor      = l / 10 * 8;
                            leftDoorWidth  = doorWidth * 2.0;
                            rightDoorWidth = doorWidth;
                        }
                        grid.SplitAtPositions(new [] { leftDoor - leftDoorWidth / 2.0, leftDoor + leftDoorWidth / 2.0, rightDoor - rightDoorWidth / 2.0, rightDoor + rightDoorWidth / 2.0 });
                        var lines = grid.GetCells().Select(c => c.GetCellGeometry()).OfType <Line>();
                        if (reverseDirection)
                        {
                            lines = lines.Reverse();
                        }
                        var wallIdx = 0;
                        foreach (var wallLine in lines)
                        {
                            var segmentLength    = wallLine.Length();
                            var segmentTransform = new Transform(wallLine.Start + new Vector3(0, 0, 0), d, d.Cross(Vector3.ZAxis));
                            if (wallIdx == 1)
                            {
                                CreateStandardPanel(segmentLength, 6, envelope.Height - 6, 0.1, segmentTransform, panelMat, out FacadePanel panel);
                                output.model.AddElement(panel);
                                CreateBranding(envelope.Height, 10, 28, true, new Transform(wallLine.Start.Average(wallLine.End), Vector3.ZAxis, 0), output.model);
                            }
                            else if (wallIdx == 3)
                            {
                                CreateStandardPanel(segmentLength, 6, envelope.Height - 6, 0.1, segmentTransform, panelMat, out FacadePanel panel);
                                output.model.AddElement(panel);
                                CreateBranding(envelope.Height * 0.7, 5.5, 6, false, new Transform(wallLine.Start.Average(wallLine.End), Vector3.ZAxis, 0), output.model);
                            }
                            else
                            {
                                CreateStandardPanel(segmentLength, 0, envelope.Height, 0.1, segmentTransform, panelMat, out FacadePanel panel);
                                output.model.AddElement(panel);
                            }
                            wallIdx++;
                        }
                    }
                    else
                    {
                        CreateStandardPanel(l,
                                            0,
                                            envelope.Height,
                                            0.1,
                                            t,
                                            panelMat,
                                            out FacadePanel panel);
                        output.model.AddElement(panel);
                    }

                    var parapetLine = new Line(new Vector3(s.Start.X, s.Start.Y, envelope.Height), new Vector3(s.End.X, s.End.Y, envelope.Height));
                    var parapet     = new StandardWall(parapetLine, 0.4, 0.9, panelMat);
                    output.model.AddElement(parapet);
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(ex);
                }
            }

            return(output);
        }
        private static List <WallPanel> ProcessWallsAndStandardWalls(PanelsFromWallsInputs input, List <Wall> allWalls, out int totalCount, out int uniqueCount, out int nonStandardCount)
        {
            var wallCenterlines = allWalls.Select(TryGetCenterlineFromWall).Where(s => s != null);
            var endPoints       = wallCenterlines.SelectMany(l => new[] { l.Start, l.End });
            var network         = new Network(wallCenterlines);
            Dictionary <Elements.Spatial.Edge, Grid1d> edgeGrids = new Dictionary <Elements.Spatial.Edge, Grid1d>();

            foreach (var edge in network.Edges)
            {
                var edgeLine = network.GetEdgeLine(edge);
                var grid     = new Grid1d(edgeLine);
                edgeGrids.Add(edge, grid);

                var cornerAtStart = network[edge.From].Valence > 1;
                var cornerAtEnd   = network[edge.To].Valence > 1;

                var cornerCount = (cornerAtStart ? 1 : 0) + (cornerAtEnd ? 1 : 0);

                var cornerLength = input.CornerLength;
                if (cornerLength * cornerCount > edgeLine.Length())
                {
                    cornerLength = edgeLine.Length() / cornerCount;
                }
                if (cornerAtStart)
                {
                    grid.SplitAtOffset(cornerLength);
                }

                if (cornerAtEnd)
                {
                    grid.SplitAtOffset(cornerLength, true);
                }
                Grid1d gridToSubdivide = null;
                if (!grid.IsSingleCell)
                {
                    switch (grid.Cells.Count)
                    {
                    case 3:
                        gridToSubdivide = grid[1];
                        break;

                    case 2:
                        if (cornerCount == 1)
                        {
                            if (cornerAtStart)
                            {
                                gridToSubdivide = grid[1];
                            }
                            if (cornerAtEnd)
                            {
                                gridToSubdivide = grid[0];
                            }
                        }
                        break;

                    default:
                        gridToSubdivide = grid;
                        break;
                    }
                    if (gridToSubdivide != null)
                    {
                        gridToSubdivide.DivideByFixedLength(input.PanelLength, FixedDivisionMode.RemainderAtEnd);
                    }
                }
            }
            List <Line> lines = new List <Line>();

            foreach (var edgeGrid in edgeGrids)
            {
                if (edgeGrid.Value == null)
                {
                    continue;
                }
                var cells = edgeGrid.Value.IsSingleCell ? new List <Grid1d> {
                    edgeGrid.Value
                } : edgeGrid.Value.GetCells();
                var cellGeometry = cells.Select(c => c.GetCellGeometry()).OfType <Line>();
                lines.AddRange(cellGeometry);
            }

            // Create walls from lines, and assign a random color material
            var walls    = new List <WallPanel>();
            var rand     = new Random();
            var colorMap = new Dictionary <int, Color>();

            colorMap.Add(KeyFromLength(input.CornerLength), Colors.Red);
            if (input.CornerLength != input.PanelLength)
            {
                colorMap.Add(KeyFromLength(input.PanelLength), Colors.Blue);
            }
            foreach (var wallLine in lines)
            {
                var color     = default(Color);
                var lengthKey = KeyFromLength(wallLine.Length());
                if (colorMap.ContainsKey(lengthKey))
                {
                    color = colorMap[lengthKey];
                }
                else
                {
                    color = new Color(rand.NextDouble(), rand.NextDouble(), rand.NextDouble(), 1.0);
                    colorMap.Add(lengthKey, color);
                }
                var mat = input.ColorCodeByLength ? new Material(color, 0, 0, false, null, true, Guid.NewGuid(), color.ToString()) : BuiltInMaterials.Concrete;
                walls.Add(CreateSimpleWallPanel(wallLine, 0.1, 3.0, mat));
            }

            nonStandardCount = lines.Where(l => KeyFromLength(l.Length()) != KeyFromLength(input.PanelLength) && KeyFromLength(l.Length()) != KeyFromLength(input.CornerLength)).Count();
            totalCount       = walls.Count;
            uniqueCount      = Math.Min(totalCount, colorMap.Count());
            return(walls);
        }