I am new to C#, I am trying to simulating drainage path on mesh. but I keep getting same points. There is something wrong in the code. Can any one help me to have a look! Appreciate!
public class Script_Instance : GH_ScriptInstance
{
#region Notes
/*
Members:
RhinoDoc RhinoDocument
GH_Document GrasshopperDocument
IGH_Component Component
int Iteration
Methods (Virtual & overridable):
Print(string text)
Print(string format, params object[] args)
Reflect(object obj)
Reflect(object obj, string method_name)
*/
public List<Point3d> pts;
public List<GradientDescent> descents;
public class GradientDescent
{
// properties
// Positions
// NextDirection
public Mesh m {get;set;}
public Point3d Pos {get;set;}
public Vector3d Dir {get;set; } = new Vector3d(0,0,1);
public double MaxSpeed{get;set;} = 50;
public List<Point3d> PosList {get;set;} = new List<Point3d>();
public int Time {get;set;} = 50;
private int recursionDepth = 0;
// --------------------
// construcotr
public GradientDescent(Mesh myMesh, Point3d position, Vector3d gravityDirection, double maxSpeed, int runTimes)
{
this.m = myMesh;
MeshPoint mp = m.ClosestMeshPoint(position,10);
Vector3d mpNormal = m.NormalAt(mp);
this.Pos = mp.Point;
gravityDirection.Unitize();
this.Dir = Vector3d.CrossProduct(gravityDirection, mpNormal);
this.MaxSpeed = maxSpeed;
this.Time = runTimes;
}
// ---------------------
// methods
// Directions of NEXT Movement
public Vector3d NextDirection()
{
this.Dir.Unitize();
Vector3d NextDirection = this.Dir * MaxSpeed;
return NextDirection;
}
// RUN Movement
public void Move()
{
if (recursionDepth >= this.Time)
{
return;
}
Point3d posPrev = this.Pos;
Vector3d NextDir = NextDirection();
Point3d posNext = Point3d.Add(this.Pos, NextDir);
posNext = m.ClosestMeshPoint(posNext, 10).Point;
this.Pos = posNext;
if (posNext.Z < posPrev.Z && Math.Abs(posPrev.Z - posNext.Z) > (MaxSpeed / 100))
{
PosList.Add(this.Pos);
recursionDepth ++;
Move(); // Recursive call to continue moving
recursionDepth --;
}
}
}
#endregion
private void RunScript(
bool iRest,
Mesh iMesh,
List<Point3d> iPoints,
Vector3d gravityDir,
ref object a)
{
// Initilize Instance
// Initialize Instance only if needed
if (pts == null || iRest)
{
pts = new List<Point3d>();
}
if (descents == null || iRest)
{
descents = new List<GradientDescent>();
}
// Initialize Instance
// descents = new List<GradientDescent>();
// pts = new List<Point3d>(); // Initialize list to store updated points
foreach (Point3d pt in iPoints)
{
GradientDescent myDescent = new GradientDescent(iMesh,pt, gravityDir, 10,60);
descents.Add(myDescent);
myDescent.Move();
Console.Write($"Next direction is {myDescent.Dir}");
Console.Write($"Next direction is {myDescent.NextDirection()}");
}
foreach (GradientDescent descent in descents)
{
pts.Add(descent.Pos);
}
a = pts;
// Collect trail points
// add polyline
// colorize the ployline
}
}