public RhinoList <Guid> CommitIntoRhinoDocument() { RhinoList <Guid> newGuids = new RhinoList <Guid>(Objects.Count); foreach (var content in this.Objects.AttributedGeometries) { var geom = content.Geometry; var attr = content.Attributes; if (geom is IGH_BakeAwareData) { Guid guid; (geom as IGH_BakeAwareData).BakeGeometry(RhinoDoc.ActiveDoc, attr, out guid); if (!guid.Equals(Guid.Empty)) { newGuids.Add(guid); } } else { throw new ApplicationException("UnexpectedObjectException. Please report this error to [email protected]"); } } return(newGuids); }
protected RhinoList <Rectangle3d> generateNetRects(Vector3d widthHeightDepthVect, out Point3d bottomRightmostPoint, double thickness = 0) { RhinoList <Rectangle3d> rectList = new RhinoList <Rectangle3d>(); double xDist = widthHeightDepthVect.X; double yDist = widthHeightDepthVect.Y; double zDist = widthHeightDepthVect.Z; // Add thickness for fingering gaps Point3d origin1 = ORIGIN + new Vector3d(xDist + thickness, 0, 0); Point3d origin2 = origin1 + new Vector3d(yDist + thickness, 0, 0); Point3d origin3 = origin2 + new Vector3d(xDist + thickness, 0, 0); // Line 4 rectangles X, Y, X, Y; all Z tall Rectangle3d rect0 = MakeRect(ORIGIN, xDist, zDist, margin: BIRCH_CM); Rectangle3d rect1 = MakeRect(origin1, yDist, zDist, margin: BIRCH_CM); Rectangle3d rect2 = MakeRect(origin2, xDist, zDist, margin: BIRCH_CM); Rectangle3d rect3 = MakeRect(origin3, yDist, zDist, margin: BIRCH_CM); rectList.Add(rect0); rectList.Add(rect1); rectList.Add(rect2); rectList.Add(rect3); // Set the bottomRightmost point so caller function can keep drawing // where we leave off bottomRightmostPoint = origin3 + new Vector3d(rect3.Width, 0, 0); return(rectList); }
/// <summary> /// This function selects breps /// </summary> /// /// public static bool XSelectBreps(string message, out RhinoList <Brep> breps) { breps = new RhinoList <Brep>(); int i; var gc = new GetObject(); gc.SetCommandPrompt("Select some Breps"); gc.EnablePreSelect(true, true); gc.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gc.GetMultiple(1, 0); //we do our double check to make sure the user selected something if (gc.CommandResult() != Result.Success) { return(false); } for (i = 0; i < gc.ObjectCount; i++) { var brep = gc.Object(i).Brep(); if (null != brep) { breps.Add(brep); } } return(true); }
protected override Result RunCommand(Rhino.RhinoDoc doc, RunMode mode) { const Rhino.DocObjects.ObjectType selFilter = Rhino.DocObjects.ObjectType.Point; Rhino.DocObjects.ObjRef[] pointObjRefs; Result getPointsResults = RhinoGet.GetMultipleObjects("Select circuit component endpoints", false, selFilter, out pointObjRefs); if (getPointsResults == Result.Success) { RhinoList <Point> circuitPoints = new RhinoList <Point>(); foreach (Rhino.DocObjects.ObjRef objRef in pointObjRefs) { circuitPoints.Add(objRef.Point()); } RhinoList <Line> conduitLines = autoroute(circuitPoints); foreach (Line conduitLine in conduitLines) { doc.Objects.AddLine(conduitLine); } doc.Views.Redraw(); return(Result.Success); } return(Result.Failure); }
public static List <Target> bestTarget(Target now, List <Target> targetList) { List <double> scores = targetList.Select(n => fitness(n, now, 10)).ToList(); RhinoList <Target> targetListCopy = new RhinoList <Target>(targetList); targetListCopy.Sort(scores.ToArray()); return(targetListCopy.ToList()); }
private void drawPolyNet(ObjRef objRef, RhinoDoc doc, double thickness, bool shrinkToDimensions = false) { // Get the section polyline Polyline sectionPolyline = getSectionPolyline(objRef); double polyDepth = getWidthHeigthDepthVect(objRef).Z; double effectiveNetThickness = shrinkToDimensions ? -thickness : thickness; //Generate rectangles + polygon based on the face dimensions Point3d bottomRightmostPoint; RhinoList <Rectangle3d> rectList = generatePolyRects(sectionPolyline, polyDepth, out bottomRightmostPoint, effectiveNetThickness); Polyline polyline; Polyline[] explodedLines; Line jointLine; Point3d rightEdgeBottom, rightEdgeTop; // Draw the first finger leftmost before iterating jointLine = new Line(rectList[0].Corner(0), rectList[0].Corner(3)); polyline = generateFingerJoint(jointLine, thickness); doc.Objects.AddPolyline(polyline); foreach (Rectangle3d rect in rectList) { // First draw fingers rightEdgeBottom = rect.Corner(1); rightEdgeTop = rect.Corner(2); jointLine = new Line(rightEdgeBottom, rightEdgeTop); // Draw on both sides of seam polyline = generateFingerJoint(jointLine, thickness); doc.Objects.AddPolyline(polyline); // Then draw rectangle itself, explode, and remove seams polyline = rect.ToPolyline(); explodedLines = polyline.BreakAtAngles(Math.PI / 2); doc.Objects.AddPolyline(explodedLines[0]); doc.Objects.AddPolyline(explodedLines[2]); } doc.Views.Redraw(); // Finally, draw bottom rectangle bottomRightmostPoint += new Vector3d(effectiveNetThickness / 2, 0, 0); Curve bottomCurve = generatePolyBottomCurve(objRef, bottomRightmostPoint, thickness, shrinkToDimensions); doc.Objects.AddCurve(bottomCurve); doc.Views.Redraw(); }
protected RhinoList <Line> autoroute(RhinoList <Point> points) { // TODO: define heuristics e.g. penalize length // TODO: define cost function for heuristics, do gradient descent // NOTE: currently we use a dumb greedy algorithm, but will change later RhinoList <Line> conduitLines = new RhinoList <Line>(); conduitLines = naiveGreedyRoute(points); return(conduitLines); }
public RhinoList <Guid> AddPoints(IEnumerable <Point3f> points, ObjectAttributes attributes) { RhinoList <Guid> list = new RhinoList <Guid>(InferLengthOrGuess(points)); foreach (var p in points) { var id = AddPoint(p, attributes); if (!id.Equals(Guid.Empty)) { list.Add(id); } } return(list); }
private void drawBoxNet(ObjRef boxObjRef, RhinoDoc doc, bool shrinkToDimensions = false) { Vector3d widthHeightDepthVect = getWidthHeigthDepthVect(boxObjRef); Point3d bottomRightmostPoint; double effectiveNetThickness = shrinkToDimensions ? 0 : BIRCH_CM; RhinoList <Rectangle3d> rectList = generateNetRects(widthHeightDepthVect, out bottomRightmostPoint, thickness: effectiveNetThickness); Polyline polyline; Polyline[] explodedLines; Line jointLine; Point3d rightEdgeBottom, rightEdgeTop; // Draw the first finger leftmost before iterating jointLine = new Line(rectList[0].Corner(0), rectList[0].Corner(3)); polyline = generateFingerJoint(jointLine, BIRCH_CM); doc.Objects.AddPolyline(polyline); foreach (Rectangle3d rect in rectList) { // First draw fingers rightEdgeBottom = rect.Corner(1); rightEdgeTop = rect.Corner(2); jointLine = new Line(rightEdgeBottom, rightEdgeTop); // Draw on both sides of seam polyline = generateFingerJoint(jointLine, BIRCH_CM); doc.Objects.AddPolyline(polyline); // Then draw rectangle itself, explode, and remove seams polyline = rect.ToPolyline(); explodedLines = polyline.BreakAtAngles(Math.PI / 2); doc.Objects.AddPolyline(explodedLines[0]); doc.Objects.AddPolyline(explodedLines[2]); } // Finally, draw bottom rectangle bottomRightmostPoint += new Vector3d(BIRCH_CM / 2, 0, 0); Rectangle3d bottomRect = generateBottomRect(widthHeightDepthVect, bottomRightmostPoint, thickness: BIRCH_CM); doc.Objects.AddPolyline(bottomRect.ToPolyline()); doc.Views.Redraw(); }
private RhinoList <Line> naiveGreedyRoute(RhinoList <Point> points) { RhinoList <Line> conduitLines = new RhinoList <Line>(); for (int i = 0; i < points.Count; i++) { for (int j = i + 1; j < points.Count; j++) { Point3d fromPoint, toPoint; fromPoint = points[i].Location; toPoint = points[j].Location; conduitLines.Add(new Line(fromPoint, toPoint)); } } return(conduitLines); }
protected RhinoList <Rectangle3d> generatePolyRects(Polyline charCurve, double depth, out Point3d bottomRightmostPoint, double thickness = 0) { RhinoList <double> sectionDistances = new RhinoList <double>(); Line[] sectionSegments = charCurve.GetSegments(); foreach (Line segment in sectionSegments) { sectionDistances.Add(segment.Length); } // Add origin points, accounting for thickness RhinoList <Point3d> origins = new RhinoList <Point3d>(); Point3d currOrigin = ORIGIN; // Loop invariant: CURR_ORIGIN be safely added and incremented foreach (double distance in sectionDistances) { origins.Add(currOrigin); currOrigin += new Vector3d(distance + thickness, 0, 0); } RhinoList <Rectangle3d> rectList = new RhinoList <Rectangle3d>(); Rectangle3d currRect; int i; for (i = 0; i < origins.Count; i++) { currRect = MakeRect(origins[i], sectionDistances[i], depth, margin: thickness); rectList.Add(currRect); } bottomRightmostPoint = origins.Last + new Vector3d(sectionDistances[i - 1], 0, 0); return(rectList); }
private static List <Text3d> GetRoadWidthFromPlot(Plot plot) { Curve[] segments = plot.Boundary.DuplicateSegments(); List <Text3d> output = new List <Text3d>(); for (int i = 0; i < plot.Surroundings.Count(); i++) { if (plot.Surroundings[i] > 0) { Curve tempCurve = segments[i].DuplicateCurve(); RhinoList <Curve> tempOffsettedCurve = new RhinoList <Curve>(tempCurve.Offset(Plane.WorldXY, -plot.Surroundings[i] * 1000, 0, CurveOffsetCornerStyle.None)); double[] offsettedCurveLength = (from curve in tempOffsettedCurve select curve.GetLength()).ToArray(); tempOffsettedCurve.Sort(offsettedCurveLength); Point3d tempPoint = tempOffsettedCurve[tempOffsettedCurve.Count - 1].PointAt(tempOffsettedCurve[tempOffsettedCurve.Count - 1].Domain.Mid); Vector3d tempCurveVector = new Vector3d(tempCurve.PointAt(tempCurve.Domain.T1) - tempCurve.PointAt(tempCurve.Domain.T0)); double angle = getAngle(tempCurveVector); if (angle > Math.PI / 2) { angle += Math.PI; } Plane tempPlane = new Plane(); tempPlane.Transform(Transform.Rotation(angle, Point3d.Origin)); tempPlane.Transform(Transform.Translation(new Vector3d(tempPoint))); output.Add(new Text3d(plot.Surroundings[i].ToString() + "m 도로", tempPlane, 1000)); } } return(output); }
private static double maxRectDirection(Plot plot) { Polyline x; plot.Boundary.TryGetPolyline(out x); //parameters int gridResolution = 23; int angleResolution = 23; int ratioResolution = 5; int binarySearchIteration = 7; double ratioMaximum = 100; int gridSubResolution = 4; int angleSubResolution = 3; int ratioSubResolution = 4; int subIter = 4; double convergenceFactor = 1.1; double maxR = ratioMaximum; int binaryIter = binarySearchIteration; int rRes = ratioResolution; double alpha = 0.01; int edgeAngleNum = 5; //sub constants double gridDom = 0.3; double angleDom = 0.3; double ratioDom = 0.3; //plot Polyline xcurve = x; Curve plotCurve = xcurve.ToNurbsCurve(); //loop start parameters double areaMax = 0; double solWidth = 0; Point3d solPoint = new Point3d(0, 0, 0); double solR = 15; double solAngle = 0; //output List <Point3d> coreOri = new List <Point3d>(); List <Rectangle3d> coreShape = new List <Rectangle3d>(); //search space List <double> angles = new List <double>(); for (int i = 0; i < angleResolution; i++) { angles.Add(Math.PI * 2 * i / angleResolution); } List <Line> outlineSegments = x.GetSegments().ToList(); RhinoList <Line> outSegRL = new RhinoList <Line>(outlineSegments); List <double> outlineSegLength = outlineSegments.Select(n => n.Length).ToList(); outSegRL.Sort(outlineSegLength.ToArray()); outlineSegments = outSegRL.ToList(); outlineSegments.Reverse(); for (int i = 0; i < Math.Min(edgeAngleNum, outlineSegments.Count); i++) { Vector3d vector = outlineSegments[i].UnitTangent; if (vector.Y < 0) { vector.Reverse(); } double angleTemp = -Math.Acos(Vector3d.Multiply(Vector3d.XAxis, vector)); angles.Add(angleTemp); angles.Add(angleTemp + Math.PI / 2); } //loop for (int ang = 0; ang < angles.Count; ang++) { Polyline xClone = new Polyline(x); xClone.Transform(Transform.Rotation(angles[ang], new Point3d(0, 0, 0))); //find bounding box, grid dimensions var bBox = xClone.BoundingBox; Point3d minP = bBox.Min; Point3d maxP = bBox.Max; List <double> ressG = new List <double>(); ressG.Add(maxP.X - minP.X - 2 * alpha); ressG.Add(maxP.Y - minP.Y - 2 * alpha); List <double> resG = new List <double>(ressG.Select(val => val / gridResolution)); //1st search for (int i = 0; i < gridResolution + 1; i++) { //create lines Line lineY = new Line(new Point3d(minP.X + alpha + i * resG[0], minP.Y, 0), new Point3d(minP.X + alpha + i * resG[0], maxP.Y, 0)); Line lineX = new Line(new Point3d(minP.X, minP.Y + i + alpha * resG[1], 0), new Point3d(maxP.X, minP.Y + alpha + i * resG[1], 0)); //create mid points of segments List <Point3d> midsX = new List <Point3d>(intersectionMids(lineX, xClone)); List <Point3d> midsY = new List <Point3d>(intersectionMids(lineY, xClone)); List <Point3d> mids = new List <Point3d>(); foreach (Point3d j in midsX) { mids.Add(j); } foreach (Point3d j in midsY) { mids.Add(j); } foreach (Point3d j in mids) { //get max height and max width Line midlineY = new Line(new Point3d(j.X, minP.Y, 0), new Point3d(j.X, maxP.Y, 0)); Line midlineX = new Line(new Point3d(minP.X, j.Y, 0), new Point3d(maxP.X, j.Y, 0)); List <Point3d> widthP = new List <Point3d>(intersectionPoints(midlineX, xClone)); List <Point3d> heightP = new List <Point3d>(intersectionPoints(midlineY, xClone)); List <double> widthV = new List <double>(); List <double> heightV = new List <double>(); foreach (Point3d k in widthP) { widthV.Add(k.DistanceTo(j)); } foreach (Point3d k in heightP) { heightV.Add(k.DistanceTo(j)); } double maxWidth; double maxHeight; if (widthV.Count == 0) { maxWidth = 0; } else { maxWidth = widthV.Min() * 2; } if (heightV.Count == 0) { maxHeight = 0; } else { maxHeight = heightV.Min() * 2; } //binary search double minRatio = Math.Max(areaMax / maxWidth / maxWidth, 1 / maxR); double maxRatio = Math.Min(maxHeight * maxHeight / areaMax, maxR); double r = 1; if (minRatio < maxRatio) { for (int a = -rRes; a < rRes + 1; a++) { if (a < 0) { r = 1 / (1 + (1 / minRatio - 1) / Math.Pow(2, -a)); } else if (a == 1) { r = 1; } else { r = 1 + (maxRatio - 1) / Math.Pow(2, a); } //solution boundary List <double> minWidths = new List <double>(); minWidths.Add(Math.Sqrt(areaMax / r)); double minSolWidth = minWidths.Max(); double maxSolWidth = Math.Min(maxWidth, maxHeight / r); double searchWidth = (minSolWidth + maxSolWidth) / 2; double binRes = searchWidth / 2; //binary if (minSolWidth < maxSolWidth) { for (int b = 0; b < binaryIter; b++) { if (inCheck(j, searchWidth, r, xClone) == 1) { if (areaMax < searchWidth * searchWidth * r && searchWidth * searchWidth * r * 4 < PolygonArea(xcurve)) { areaMax = searchWidth * searchWidth * r; solWidth = searchWidth; solPoint = j; solR = r; solAngle = angles[ang]; } searchWidth += binRes; } else { searchWidth -= binRes; } binRes /= 2; } } } } } } } Rectangle3d ohGod = new Rectangle3d(Plane.WorldXY, new Point3d(solPoint.X - solWidth, solPoint.Y - solWidth * solR, 0), new Point3d(solPoint.X + solWidth, solPoint.Y + solWidth * solR, 0)); ohGod.Transform(Transform.Rotation(-solAngle, new Point3d(0, 0, 0))); //2nd search double solWidthNew = solWidth; Point3d solPointNew = solPoint; double solRNew = solR; double solAngleNew = solAngle; int token = 0; while (token < subIter) { gridDom /= convergenceFactor; angleDom /= convergenceFactor; ratioDom /= convergenceFactor; for (int ang = -angleSubResolution; ang < angleSubResolution + 1; ang++) { double searchAngle = solAngle + ang * Math.PI / 2 * angleDom / 2 / angleSubResolution; Polyline xCloneNew = new Polyline(x); xCloneNew.Transform(Transform.Rotation(searchAngle, new Point3d(0, 0, 0))); Curve xCloneNewCurve = xCloneNew.ToNurbsCurve(); //find bounding box, grid dimensions var bBox = xCloneNew.BoundingBox; Point3d minP = bBox.Min; Point3d maxP = bBox.Max; List <double> ressG = new List <double>(); ressG.Add(maxP.X - minP.X); ressG.Add(maxP.Y - minP.Y); List <double> resG = new List <double>(ressG.Select(val => val / (2 * gridSubResolution) * gridDom)); List <Point3d> mids = new List <Point3d>(); for (int i = -gridSubResolution; i < gridSubResolution + 1; i++) { for (int ii = -gridSubResolution; ii < gridSubResolution + 1; ii++) { Point3d solPointTemp = solPoint; //solPointTemp.Transform(Transform.Rotation(searchAngle, new Point3d(0, 0, 0))); Point3d gridPoint = new Point3d(solPointTemp.X + i * resG[0], solPointTemp.Y + ii * resG[1], 0); if (xCloneNewCurve.Contains(gridPoint) == PointContainment.Inside) { mids.Add(gridPoint); } } } foreach (Point3d j in mids) { //get max height and max width Line midlineY = new Line(new Point3d(j.X, minP.Y, 0), new Point3d(j.X, maxP.Y, 0)); Line midlineX = new Line(new Point3d(minP.X, j.Y, 0), new Point3d(maxP.X, j.Y, 0)); List <Point3d> widthP = new List <Point3d>(intersectionPoints(midlineX, xCloneNew)); List <Point3d> heightP = new List <Point3d>(intersectionPoints(midlineY, xCloneNew)); List <double> widthV = new List <double>(); List <double> heightV = new List <double>(); foreach (Point3d k in widthP) { widthV.Add(k.DistanceTo(j)); } foreach (Point3d k in heightP) { heightV.Add(k.DistanceTo(j)); } double maxWidth = widthV.Min(); double maxHeight = heightV.Min(); //binary search double r; for (int a = -ratioSubResolution; a < ratioSubResolution + 1; a++) { r = solR * (1 + a * ratioDom / ratioSubResolution); //solution boundary List <double> minWidths = new List <double>(); minWidths.Add(Math.Sqrt(areaMax / r)); double minSolWidth = minWidths.Max(); double maxSolWidth = Math.Min(maxWidth, maxHeight / r); double searchWidth = (minSolWidth + maxSolWidth) / 2; double binRes = searchWidth / 2; //binary if (minSolWidth < maxSolWidth) { for (int b = 0; b < binaryIter; b++) { if (inCheck(j, searchWidth, r, xCloneNew) == 1) { if (areaMax < searchWidth * searchWidth * r && searchWidth * searchWidth * r * 4 < PolygonArea(xcurve)) { areaMax = searchWidth * searchWidth * r; solWidthNew = searchWidth; solPointNew = j; solRNew = r; solAngleNew = searchAngle; } searchWidth += binRes; } else { searchWidth -= binRes; } binRes /= 2; } } } } } solWidth = solWidthNew; solPoint = solPointNew; solR = solRNew; solAngle = solAngleNew; token += 1; } solPoint.Transform(Transform.Rotation(-solAngle, new Point3d(0, 0, 0))); Rectangle3d ohGoditsworkingNew = new Rectangle3d(Plane.WorldXY, new Point3d(solPointNew.X - solWidthNew, solPointNew.Y - solWidthNew * solRNew, 0), new Point3d(solPointNew.X + solWidthNew, solPointNew.Y + solWidthNew * solRNew, 0)); ohGoditsworkingNew.Transform(Transform.Rotation(-solAngleNew, new Point3d(0, 0, 0))); Rectangle3d outlineRectangle = ohGoditsworkingNew; List <Point3d> pts = new List <Point3d>(outlineRectangle.ToPolyline()); Vector3d vectorT = Vector3d.Subtract(new Vector3d(pts[0]), new Vector3d(pts[1])); if (vectorT.Y < 0) { vectorT.Reverse(); } double outAngleTemp = -Math.Acos(Vector3d.Multiply(Vector3d.XAxis, Vector3d.Multiply(vectorT, 1 / vectorT.Length))); return(outAngleTemp); }
private RhinoList <Line> iteratedOneSteiner(RhinoList <Point> points) { // TODO return(new RhinoList <Line>()); }
/// <summary> /// Adds a Mesh to the ModelObjects List /// </summary> protected virtual void AddModelMesh (Mesh mesh, ObjectAttributes attr) { //Add this to the list of all the meshes if (AllMeshes == null) AllMeshes = new RhinoList<Mesh> (); AllMeshes.Add (mesh); Material material = new Material (); int materialIndex = -1; switch (attr.MaterialSource) { case (ObjectMaterialSource.MaterialFromLayer): if (attr.LayerIndex >= 0 && attr.LayerIndex < ModelFile.Layers.Count) materialIndex = ModelFile.Layers [attr.LayerIndex].RenderMaterialIndex; break; case (ObjectMaterialSource.MaterialFromObject): materialIndex = attr.MaterialIndex; break; case (ObjectMaterialSource.MaterialFromParent): materialIndex = attr.MaterialIndex; break; } if (materialIndex < 0 || materialIndex >= ModelFile.Materials.Count) { materialIndex = -1; material.Default (); } else { material = ModelFile.Materials [materialIndex]; } object[] displayMeshes = DisplayMesh.CreateWithMesh (mesh, attr, material, materialIndex); if (displayMeshes != null) { var modelMesh = new ModelMesh (displayMeshes, attr.ObjectId); AddModelObject (modelMesh, attr); } }
/// <summary> /// Prepare the Bounding Boxes in the ModelFile /// </summary> protected virtual void PrepareBoundingBoxes() { if (ModelFile != null) { // Prepare BBoxes // Get the entire model's bounding box BBox = ModelFile.Objects.GetBoundingBox (); if (!BBox.IsValid) BBox.MakeValid (); // Calculate the layerBBoxes LayerBBoxes = new RhinoList<Rhino.Geometry.BoundingBox> (); for (int layerIndex = 0; layerIndex < Layers.Count; layerIndex++) { File3dmObject[] objsByLayer = ModelFile.Objects.FindByLayer (LayerAtIndex (layerIndex).Name); BoundingBox bbox = new BoundingBox (); foreach (File3dmObject obj in objsByLayer) { bbox.Union (obj.Geometry.GetBoundingBox (false)); } LayerBBoxes.Insert (layerIndex, bbox); } } }
/// <summary> /// Copy all the numbers from an existing RhinoList. /// </summary> /// <param name="list">List to mimic.</param> /// <since>5.0</since> public Interpolator(RhinoList <double> list) : base(list) { }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { int i, j; var gc = new GetObject(); gc.SetCommandPrompt("Select some Breps"); gc.EnablePreSelect(true, true); gc.GeometryFilter = ObjectType.Brep; gc.GetMultiple(1, 0); if (gc.CommandResult() != Result.Success) { return(gc.CommandResult()); } RhinoList <Brep> breps = new RhinoList <Brep>(); for (i = 0; i < gc.ObjectCount; i++) { var brep = gc.Object(i).Brep(); if (null != brep) { breps.Add(brep); } var format = string.Format("F{0}", doc.DistanceDisplayPrecision); var brepinfo = string.Format("Brep {0} has {1} face(s) and total surface of {2} square {3}", i.ToString(), brep.Faces.Count, brep.GetArea().ToString(format), doc.ModelUnitSystem.ToString() ); for (j = 0; j < brep.Faces.Count; j++) { AreaMassProperties brepfacemass = AreaMassProperties.Compute(brep.Faces[j]); double brepfaceearea = brepfacemass.Area; var brepfaceinfo = string.Format("Brepface {0} belongs to brep {1} and has a surface of {2} square {3}", j.ToString(), i.ToString(), brepfaceearea.ToString(format), doc.ModelUnitSystem.ToString() ); var brepfacedomain = string.Format(" and its Domain is U:{0} to {1} and V: {2} to {3}", brep.Faces[j].Domain(0).T0.ToString(format), brep.Faces[j].Domain(0).T1.ToString(format), // Domain(0) means U, start at T0, end at T1 brep.Faces[j].Domain(1).T0.ToString(format), brep.Faces[j].Domain(1).T1.ToString(format) // Domain(1) means V ); RhinoApp.WriteLine(brepfaceinfo + brepfacedomain); } RhinoApp.WriteLine(brepinfo); } //if the breps are not joined, they will be joined with the function below. Brep[] joinedbreps = Brep.JoinBreps(breps, doc.ModelAbsoluteTolerance); for (i = 0; i < joinedbreps.Length; i++) // we use the .Length instead of .Count because we have a <Standard> array from Rhino. { doc.Objects.AddBrep(joinedbreps[i]); } doc.Views.Redraw(); RhinoApp.WriteLine("The user selected {0} brep(s) successfully, and they have been joined.", breps.Count.ToString()); return(Result.Success); }
public static List <Apartment> giantAnteater(Plot plot, ApartmentGeneratorBase ag, Target target, bool previewOn) { double mutationProbability = ag.GAParameterSet[0]; double elitismPercentage = ag.GAParameterSet[1]; double initialBoost = ag.GAParameterSet[2]; int population = (int)ag.GAParameterSet[3]; int maxGen = (int)ag.GAParameterSet[4]; double fitnessFactor = ag.GAParameterSet[5]; double mutationFactor = ag.GAParameterSet[6]; //Initialize Minimum and Maximum value double[] tempMaxInput = ag.MaxInput.Clone() as double[]; double[] tempMinInput = ag.MinInput.Clone() as double[]; //create initial genes Random myRandom = new Random((int)DateTime.Now.Ticks); double goodAngle = maxRectDirection(plot); //double goodAngle = Math.PI * 152 / 180; List <ParameterSet> offspringGenes = new List <ParameterSet>(); //for (int i = 0; i < initialBoost; i++) //{ // CoreType tempCoreType = ag.GetRandomCoreType(); // double[] oneGene = new double[ag.MinInput.Length]; // //if (ag.IsCoreProtrude) // // tempMaxInput[2] = tempCoreType.GetDepth(); // for (int j = 0; j < ag.MinInput.Length; j++) // { // if (i % 2 == 0 && j == 3 && ag.GetType() == typeof(AG1)) // { // oneGene[j] = goodAngle; // } // else // { // double parameterForGene = (tempMaxInput[j] - tempMinInput[j]) * myRandom.NextDouble() + tempMinInput[j]; // oneGene[j] = parameterForGene; // } // oneGene[0] = Math.Floor(oneGene[0]); // oneGene[1] = Math.Floor(oneGene[1]); // } // ParameterSet a = new ParameterSet(oneGene, ag.GetType().ToString(), tempCoreType); // offspringGenes.Add(a); //} double otherAngles = population * initialBoost;//(population - 1) * initialBoost; for (int i = 0; i < (int)otherAngles; i++) { CoreType tempCoreType = ag.GetRandomCoreType(); double[] oneGene = new double[ag.MinInput.Length]; //if (ag.IsCoreProtrude) // tempMaxInput[2] = tempCoreType.GetDepth(); for (int j = 0; j < ag.MinInput.Length; j++) { if (/*i % 2 == 0 &&*/ j == 3 && ag.GetType() == typeof(AG1)) { double parameterForGene = ((goodAngle + Math.PI / 2 * (i % 4) / 2) % (Math.PI * 2) + Math.PI * ((int)(i / 4) % 2) % (Math.PI * 2)); //oneGene[j] = parameterForGene; //double mainAngle = Math.PI * i / otherAngles; //oneGene[j] = mainAngle; oneGene[j] = parameterForGene; } else { double parameterForGene = (tempMaxInput[j] - tempMinInput[j]) * myRandom.NextDouble() + tempMinInput[j]; //width - 100씩 if (j == 2) { parameterForGene = Math.Round(parameterForGene / 100) * 100; } oneGene[j] = parameterForGene; } oneGene[0] = Math.Floor(oneGene[0]); oneGene[1] = Math.Floor(oneGene[1]); } ParameterSet a = new ParameterSet(oneGene); offspringGenes.Add(a); } //initializing end condition bool endCondition = true; //start genetic algorithm int genCount = 0; ParameterSet bestGene = offspringGenes[0]; while (endCondition) { //evaluate fitness` List <List <double> > evaluation = new List <List <double> >(evaluateFitness(plot, ag, target, offspringGenes, fitnessFactor, previewOn)); List <double> fitnessValues = new List <double>(evaluation[0]); //sort genes and fitness values RhinoList <ParameterSet> myRhinoList = new RhinoList <ParameterSet>(offspringGenes); myRhinoList.Sort(fitnessValues.ToArray()); myRhinoList.Reverse(); fitnessValues.Sort(); fitnessValues.Reverse(); offspringGenes = myRhinoList.ToList(); var radcheck = offspringGenes.Select(n => n.Parameters[3]); /* * //write * Rhino.RhinoApp.WriteLine(genCount.ToString()); * Rhino.RhinoApp.WriteLine(evaluation[1][0].ToString()); * Rhino.RhinoApp.WriteLine(evaluation[1][offspringGenes.Count-1].ToString()); * ParameterSet geneToShow = offspringGenes[0]; * * for (int i = 0; i < geneToShow.Parameters.Length; i++) * { * Rhino.RhinoApp.WriteLine(geneToShow.Parameters[i].ToString()); * } */ //create new generation List <ParameterSet> tempGenes = new List <ParameterSet>(); //Add elites to new generation int eliteNum = (int)(population * elitismPercentage); for (int i = 0; i < eliteNum; i++) { tempGenes.Add(offspringGenes[i]); } //crossover & mutation for (int i = 0; i < population - eliteNum; i++) { ParameterSet newOffspring = crossover(offspringGenes, fitnessValues, (int)myRandom.Next(0, int.MaxValue), ag.GetType().ToString()); if (myRandom.NextDouble() < mutationProbability) { newOffspring = mutation(newOffspring, ag, mutationFactor, (int)myRandom.Next(0, int.MaxValue)); } tempGenes.Add(newOffspring); } offspringGenes = tempGenes; genCount += 1; if (genCount == maxGen) { endCondition = false; } GC.Collect(); //Rhino.RhinoApp.Wait(); //finalize before end if (endCondition == false) { //evaluate fitness evaluation = new List <List <double> >(evaluateFitness(plot, ag, target, offspringGenes, fitnessFactor, previewOn)); fitnessValues = new List <double>(evaluation[0]); //sort genes and fitness values myRhinoList = new RhinoList <ParameterSet>(offspringGenes); myRhinoList.Sort(fitnessValues.ToArray()); myRhinoList.Reverse(); fitnessValues.Sort(); fitnessValues.Reverse(); offspringGenes = myRhinoList.ToList(); bestGene = offspringGenes[0]; } Rhino.RhinoApp.Wait(); } //best 1 Apartment bestOutput = ag.generator(plot, bestGene, target); return(new Apartment[] { bestOutput }.ToList()); //best 5 //var uniqueGenes = offspringGenes.Distinct(); //Apartment[] bestOutputs = offspringGenes.Take(5).Select(n => ag.generator(plot, n, target)).ToArray(); //return bestOutputs.ToList(); //best 10 //var uniqueGenes = offspringGenes.Distinct(); //Apartment[] bestOutputs = offspringGenes.Take(10).Select(n=>ag.generator(plot, n, target)).ToArray(); //return new Apartment[] { bestOutput }.ToList(); //return bestOutputs.ToList(); //all Apartment[] bestOutputs = offspringGenes.Select(n => ag.generator(plot, n, target)).ToArray(); return(bestOutputs.ToList()); if (bestOutput.ParameterSet == null) { return(FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false)); } if (bestOutput.ParameterSet.Parameters != null) { List <Apartment> output = FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false); bool IsSatisfyingLegalParking = false; List <Apartment> satisFyingLegalParkingOutput = new List <Apartment>(); foreach (Apartment i in output) { if (i.GetLegalParkingLotOfCommercial() + i.GetLegalParkingLotofHousing() < i.ParkingLotOnEarth.GetCount() + i.ParkingLotUnderGround.Count) { satisFyingLegalParkingOutput.Add(i); IsSatisfyingLegalParking = true; } } if (IsSatisfyingLegalParking == false) { targetError tempErrorMessage = new targetError(); List <Apartment> tempNewOutput = tempErrorMessage.showDialogAndReturnValue(ag, plot, bestGene, target, output); bool tempSatisfyingLegalParking = false; List <Apartment> tempSatisFyingLegalParkingOutput = new List <Apartment>(); foreach (Apartment i in tempNewOutput) { if (i.GetLegalParkingLotOfCommercial() + i.GetLegalParkingLotofHousing() < i.ParkingLotOnEarth.GetCount() + i.ParkingLotUnderGround.Count) { tempSatisfyingLegalParking = true; tempSatisFyingLegalParkingOutput.Add(i); } } if (tempSatisfyingLegalParking == false) { System.Windows.MessageBox.Show("선택한 설계로 법정 주차대수를 만족하기 어려운 대지입니다."); return(output); } else { return(tempSatisFyingLegalParkingOutput); } } else { return(output); } } else { System.Windows.MessageBox.Show(CommonFunc.GetApartmentType(ag.GetAGType) + " 타입 설계에 적합하지 않은 대지입니다."); } return(FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false)); }
/// <summary> /// Gets a collection of perpendicular frames along the curve. Perpendicular frames /// are also known as 'Zero-twisting frames' and they minimize rotation from one frame to the next. /// </summary> /// <param name="parameters">A collection of <i>strictly increasing</i> curve parameters to place perpendicular frames on.</param> /// <returns>An array of perpendicular frames on success or null on failure.</returns> /// <exception cref="InvalidOperationException">Thrown when the curve parameters are not increasing.</exception> public Plane[] GetPerpendicularFrames(IEnumerable<double> parameters) { RhinoList<double> ts = new RhinoList<double>(); double t0 = double.MinValue; foreach (double t in parameters) { if (t <= t0) throw new InvalidOperationException("Curve parameters must be strictly increasing"); ts.Add(t); t0 = t; } // looks like we need at least two parameters to have this function make sense if (ts.Count < 2) return null; double[] _parameters = ts.ToArray(); int count = _parameters.Length; Plane[] frames = new Plane[count]; IntPtr pConstCurve = ConstPointer(); int rc_count = UnsafeNativeMethods.RHC_RhinoGet1RailFrames(pConstCurve, count, _parameters, frames); if (rc_count == count) return frames; if (rc_count > 0) { Plane[] rc = new Plane[rc_count]; Array.Copy(frames, rc, rc_count); return rc; } return null; }
private static List <List <double> > evaluateFitness(Plot plot, ApartmentGeneratorBase ag, Target target, List <ParameterSet> gene, double fitnessFactor, bool previewOn) { List <List <double> > result = new List <List <double> >(); List <double> grossAreaRatio = new List <double>(); List <double> parkinglotRatio = new List <double>(); List <double> targetAccuracy = new List <double>(); List <double> axisAccuracy = new List <double>(); bool drawSomeThing = false; int i = 0; var timer = new System.Threading.Timer((e) => { drawSomeThing = true; } , drawSomeThing, TimeSpan.Zero, TimeSpan.FromMilliseconds(1000)); List <Apartment> agOutToDrawList = new List <Apartment>(); List <double> agOutToDrawGrossAreaList = new List <double>(); for (i = 0; i < gene.Count(); i++) { Apartment tempOutput = ag.generator(plot, gene[i], target); grossAreaRatio.Add(tempOutput.GetGrossAreaRatio()); //targetAccuracy.Add(tempOutput.GetTargetAccuracy()); parkinglotRatio.Add(tempOutput.GetParkingScore()); axisAccuracy.Add(tempOutput.GetAxisAccuracy()); TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor += 1; TuringAndCorbusierPlugIn.InstanceClass.page3.updateProGressBar(TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor.ToString() + "/" + TuringAndCorbusierPlugIn.InstanceClass.page3.currentWorkQuantity.ToString() + " 진행중"); if (previewOn) { agOutToDrawList.Add(tempOutput); //agOutToDrawGrossAreaList.Add(tempOutput.GetGrossAreaRatio()); if (drawSomeThing) { TuringAndCorbusierPlugIn.InstanceClass.page3.preview(agOutToDrawList.Last()); Rhino.RhinoDoc.ActiveDoc.Views.Redraw(); Rhino.RhinoApp.Wait(); agOutToDrawList.Clear(); agOutToDrawGrossAreaList.Clear(); drawSomeThing = false; } } } double MaxFAR = TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio; //법정 용적률에 근접한 유전자가 가장 높은 값 받음, // -0 ~ -5 최대값 받음 //넘어가면 * 0.01 포인트 마이너스 //낮으면 *0.1포인트 마이너스 List <double> points = new List <double>(); for (int r = 0; r < grossAreaRatio.Count; r++) { double point = 0; if (grossAreaRatio[r] < MaxFAR && grossAreaRatio[r] > MaxFAR - 5) { point = 1 + (5 - (MaxFAR - grossAreaRatio[r])) / MaxFAR; } else if (grossAreaRatio[r] > MaxFAR) { point = 1 - (grossAreaRatio[r] - MaxFAR) / MaxFAR / 10; } else { point = 1 - (MaxFAR - grossAreaRatio[r]) / MaxFAR; } points.Add(point); } List <double> tempGAR = new List <double>(grossAreaRatio); RhinoList <double> FARList = new RhinoList <double>(tempGAR); //FARList.Sort(points.ToArray()); //points.Sort(); double Cworst = FARList.First; double Cbest = FARList.Last; double k = fitnessFactor; List <double> fitness = new List <double>(); //double Cworst = tempGAR[0]; //double Cbest = tempGAR[gene.Count - 1]; //double k = fitnessFactor; //List<double> fitness = new List<double>(); double parkingWeight = 0.3; double CworstR = parkinglotRatio.Min(); double CbestR = parkinglotRatio.Max(); double targetWeight = 0.4; //double CworstT = targetAccuracy.Min(); //double CbestT = targetAccuracy.Max(); //fitnessvalue rate //연면적 1 : 주차율(?) 0.3 : 유닛정확도 : 0.4 //for test //string url = @"C://Users//user//Desktop//test"; //System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(url); //string filename = "//garojutacklogV2" + (dinfo.GetFiles().Length + 1).ToString() + ".csv"; //System.IO.FileStream fs = new System.IO.FileStream(url + filename, System.IO.FileMode.CreateNew); //fs.Close(); //fs.Dispose(); //System.IO.StreamWriter w = new System.IO.StreamWriter(fs.Name); //string column = "FAR" + "," + "Floors" + "," + "FARPoint" + "," + "ParkingPoint" + "," + "AxisPoint" + "," + "Sum" + "," + "Use1F" + ",UseSetback"; //w.WriteLine(column); for (int j = 0; j < gene.Count; j++) { double farfitnessVal = points[j] * 10; double parkkingfitnessVal = parkinglotRatio[j]; double axisfitnessVal = axisAccuracy[j]; //double farfitnessVal = ((grossAreaRatio[j] - Cbest) * (k - 1) / k + (Cbest - Cworst) + 0.01) / (Cbest - Cworst + 0.01); //double parkingval = ((parkinglotRatio[j] - CbestR) * (k - 1) / k + (CbestR - CworstR) + 0.01) / (CbestR - CworstR + 0.01) * parkingWeight; //double targetval = ((targetAccuracy[j] - CbestT) * (k - 1) / k + (CbestT - CworstT) + 0.01) / (CbestT - CworstT + 0.01) * targetWeight; //firstfloor test double firstfloorBonus = 0; //if (gene[j].using1F) // firstfloorBonus = 1000; //setback test double setbackBonus = 0; //if (gene[j].setback) // setbackBonus = 1000; fitness.Add(farfitnessVal + parkkingfitnessVal + axisfitnessVal + setbackBonus + firstfloorBonus); //for test //string format = grossAreaRatio[j].ToString() + "," + gene[j].Stories + "," + farfitnessVal + "," + parkkingfitnessVal + "," + axisfitnessVal + "," + (farfitnessVal + parkkingfitnessVal + axisfitnessVal).ToString() + "," + gene[j].using1F.ToString() + "," + gene[j].setback.ToString(); //w.WriteLine(format); } //for test //w.Close(); //w.Dispose(); //tempGAR.Reverse(); //fitness.Reverse(); //FARList.Reverse(); result.Add(fitness); result.Add(FARList.Select(n => n).ToList()); double maxfar = FARList.Max(); double maxfitness = fitness.Max(); TuringAndCorbusierPlugIn.InstanceClass.page3.updateProGressBar(TuringAndCorbusierPlugIn.InstanceClass.page3.currentProgressFactor.ToString() + "/" + TuringAndCorbusierPlugIn.InstanceClass.page3.currentWorkQuantity.ToString() + " 완료"); return(result); //or, return nested list, containing gross area ratio. }
/// <summary> /// Splits (divides) the curve at a series of specified parameters. /// The parameter must be in the interior of the curve's domain. /// </summary> /// <param name="t"> /// Parameters to split the curve at in the interval returned by Domain(). /// </param> /// <returns> /// Multiple curves on success, null on failure. /// </returns> public Curve[] Split(IEnumerable<double> t) { Interval domain = Domain; RhinoList<double> parameters = new RhinoList<double>(t); parameters.Add(domain.Min); parameters.Add(domain.Max); parameters.Sort(); RhinoList<Curve> rc = new RhinoList<Curve>(); for (int i = 0; i < parameters.Count - 1; i++) { double start = parameters[i]; double end = parameters[i + 1]; if ((end - start) > RhinoMath.ZeroTolerance) { Curve trimcurve = Trim(start, end); if (trimcurve != null) rc.Add(trimcurve); } } return rc.Count == 0 ? null : rc.ToArray(); }
private static List <double> getUniqueParameter(List <Curve> baseCurve, Plot plot, out Curve perpendicularCurve, out List <int> indexOfTheParameter) { List <double> output = new List <double>(); ////////////////////////////////////////// BoundingBox boundaryBox = plot.Boundary.GetBoundingBox(false); double extendLength = boundaryBox.Corner(true, true, true).DistanceTo(boundaryBox.Corner(false, false, true)); Curve tempCurve = baseCurve[(int)(baseCurve.Count() / 2)]; Point3d centerPoint = tempCurve.PointAt(tempCurve.Domain.Mid); Vector3d centerPointPerpVector = tempCurve.TangentAt(tempCurve.Domain.Mid); centerPointPerpVector.Transform(Transform.Rotation(Math.PI / 2, Point3d.Origin)); perpendicularCurve = new LineCurve(centerPoint, centerPoint + centerPointPerpVector); double perpCurveStart = -extendLength; double perpCurveEnd = extendLength; perpendicularCurve = new LineCurve(perpendicularCurve.PointAt(perpCurveStart), perpendicularCurve.PointAt(perpCurveEnd)); List <Point3d> pointOnPerpCurve = new List <Point3d>(); foreach (Curve i in baseCurve) { double tempParameter; perpendicularCurve.ClosestPoint(i.PointAt(i.Domain.Mid), out tempParameter); pointOnPerpCurve.Add(perpendicularCurve.PointAt(tempParameter)); } List <Point3d> uniquePointOnPerpCurve = Point3d.CullDuplicates(pointOnPerpCurve, 1000).ToList(); List <double> uniquePointParameter = new List <double>(); foreach (Point3d i in uniquePointOnPerpCurve) { double tempParameter; perpendicularCurve.ClosestPoint(i, out tempParameter); uniquePointParameter.Add(tempParameter); } RhinoList <Point3d> rhinoUniquePointOnPerpCurve = new RhinoList <Point3d>(uniquePointOnPerpCurve); rhinoUniquePointOnPerpCurve.Sort(uniquePointParameter.ToArray()); uniquePointParameter.Sort(); List <int> tempIndexOfParameter = new List <int>(); foreach (Point3d i in rhinoUniquePointOnPerpCurve) { int index = pointOnPerpCurve.IndexOf(i); tempIndexOfParameter.Add(index); } /// indexOfTheParameter = tempIndexOfParameter; return(uniquePointParameter); }