please optimize this code and make it faster and more professional and solve potential bugs: private void RunScript(Brep srf, List start, List end, int count, double dist, double angle, int towards, ref object A, ref object B)
{
var surf = srf.Surfaces[0];
code
Point3d origin = surf.PointAt(start[0], start[1]);
Vector3d xAxis = surf.PointAt(end[0], end[1]) - origin;
Vector3d yAxis = surf.NormalAt(start[0], start[1]);
// Create a plane at the start point
Plane plane;
surf.FrameAt(start[0], start[1], out plane);
Vector3d adjustedXAxis = plane.ClosestPoint(origin + xAxis) - origin;
// Rotate the yAxis if angle is provided
if (angle != 0.0)
yAxis.Rotate(RhinoMath.ToRadians(angle), adjustedXAxis);
plane = new Plane(origin, adjustedXAxis, yAxis);
// Adjust plane if angle is 90 degrees
if (angle == 90)
plane.Origin += surf.NormalAt(start[0], start[1]) * 0.001;
// Define curves and points outside the function
Curve[] initialCurves;
Point3d[] points;
// Perform intersection of Brep with the plane
if (!Rhino.Geometry.Intersect.Intersection.BrepPlane(srf, plane, 0.0001, out initialCurves, out points) || initialCurves.Length == 0)
return;
List<Curve> crvList = new List<Curve>(initialCurves); // Start with initial intersection curves
// Handle different 'towards' directions
switch (towards)
{
case 1:
if (initialCurves[0].IsValid)
{
crvList.AddRange(GenerateCurvesParallel(initialCurves, srf, dist, count));
}
break;
case 2:
plane.Flip();
Rhino.Geometry.Intersect.Intersection.BrepPlane(srf, plane, 0.0001, out initialCurves, out points);
if (initialCurves.Length > 0 && initialCurves[0].IsValid)
{
crvList.AddRange(GenerateCurvesParallel(initialCurves, srf, dist, count));
}
break;
case 3:
if (initialCurves[0].IsValid)
{
crvList.AddRange(GenerateCurvesParallel(initialCurves, srf, dist, count));
plane.Flip();
Rhino.Geometry.Intersect.Intersection.BrepPlane(srf, plane, 0.0001, out initialCurves, out points);
if (initialCurves.Length > 0 && initialCurves[0].IsValid)
{
crvList.AddRange(GenerateCurvesParallel(initialCurves, srf, dist, count));
}
}
break;
}
A = crvList;
B = plane; // Optionally return the plane
Assistant
}
//
private List GenerateCurvesParallel(Curve[] initialCurves, Brep srf, double dist, int count)
{
List crvList = new List();
List currentCurves = new List(initialCurves); // Use all initial curves
code
for (int i = 0; i < count; i++)
{
List<Curve> nextCurves = new List<Curve>();
// Parallelize offset processing for all current curves
System.Threading.Tasks.Parallel.ForEach(currentCurves, (curve) =>
{
var offsetCurves = curve.OffsetOnSurface(srf.Faces[0], dist, 0.00001);
if (offsetCurves == null || offsetCurves.Length == 0)
return;
foreach (var offsetCurve in offsetCurves)
{
if (!offsetCurve.IsValid)
continue;
// Self-intersection check (for both open and closed curves)
if (Rhino.Geometry.Intersect.Intersection.CurveSelf(offsetCurve, 0.1).Count > 0)
continue;
// If the curve is open, extend it on the surface
Curve extendedCurve = offsetCurve;
if (!extendedCurve.IsClosed)
{
CurveEnd side = CurveEnd.Both;
extendedCurve = extendedCurve.ExtendOnSurface(side, srf.Faces[0]);
}
// Add to the next curve list in a thread-safe manner
lock (nextCurves)
{
nextCurves.Add(extendedCurve);
}
}
});
// If no new valid curves were generated, break early
if (nextCurves.Count == 0)
break;
crvList.AddRange(nextCurves); // Add all the new curves
currentCurves = nextCurves; // Update the current curves for the next iteration
}
return crvList;
}
Certainly! I've reviewed your code and made several optimizations to improve its performance, professionalism, and robustness. Below is the optimized version of your code with detailed explanations of the changes made:
csharp
private void RunScript(
Brep srf,
List<double> start,
List<double> end,
int count,
double dist,
double angle,
int towards,
ref object A,
ref object B)
{
// Validate input surface
if (srf == null || srf.Surfaces.Count == 0 || srf.Faces.Count == 0)
{
A = null;
B = null;
return;
}
// Validate start and end parameters
if (start == null || start.Count < 2 || end == null || end.Count < 2)
{
A = null;
B = null;
return;
}
// Access the first surface and face
Surface surface = srf.Surfaces[0];
BrepFace face = srf.Faces[0];
// Compute the origin point on the surface
Point3d origin = surface.PointAt(start[0], start[1]);
// Compute the x-axis vector
Vector3d xAxis = surface.PointAt(end[0], end[1]) - origin;
xAxis.Unitize();
// Compute the normal at the start point (y-axis)
Vector3d yAxis = surface.NormalAt(start[0], start[1]);
yAxis.Unitize();
// Create a plane at the start point
Plane plane;
if (!surface.FrameAt(start[0], start[1], out plane))
{
A = null;
B = null;
return;
}
// Adjust the x-axis based on the plane's coordinate system
Vector3d adjustedXAxis = plane.ClosestPoint(origin + xAxis) - origin;
adjustedXAxis.Unitize();
// Rotate the y-axis if angle is provided
if (angle != 0.0)
{
yAxis.Rotate(RhinoMath.ToRadians(angle), adjustedXAxis);
}
// Reconstruct the plane with adjusted axes
plane = new Plane(origin, adjustedXAxis, yAxis);
// Adjust plane origin slightly if angle is exactly 90 degrees (to avoid numerical issues)
if (Math.Abs(angle - 90.0) < RhinoMath.ZeroTolerance)
{
Vector3d normal = surface.NormalAt(start[0], start[1]);
normal.Unitize();
plane.Origin += normal * 0.001;
}
// Perform intersection of the Brep with the plane
Curve[] initialCurves;
Point3d[] intersectionPoints;
bool intersectSuccess = Rhino.Geometry.Intersect.Intersection.BrepPlane(
srf, plane, RhinoMath.ZeroTolerance, out initialCurves, out intersectionPoints);
// Check if the intersection was successful
if (!intersectSuccess || initialCurves == null || initialCurves.Length == 0)
{
A = null;
B = null;
return;
}
// Initialize the list of curves with the initial intersection curves
List<Curve> curveList = new List<Curve>(initialCurves);
// Handle different 'towards' directions
switch (towards)
{
case 1:
// Generate curves in the initial direction
if (initialCurves[0].IsValid)
{
var generatedCurves = GenerateCurvesParallel(initialCurves, srf, dist, count);
curveList.AddRange(generatedCurves);
}
break;
case 2:
// Flip the plane and generate curves in the opposite direction
plane.Flip();
intersectSuccess = Rhino.Geometry.Intersect.Intersection.BrepPlane(
srf, plane, RhinoMath.ZeroTolerance, out initialCurves, out intersectionPoints);
if (intersectSuccess && initialCurves != null && initialCurves.Length > 0 && initialCurves[0].IsValid)
{
var generatedCurves = GenerateCurvesParallel(initialCurves, srf, dist, count);
curveList.AddRange(generatedCurves);
}
break;
case 3:
// Generate curves in both directions
if (initialCurves[0].IsValid)
{
var generatedCurves = GenerateCurvesParallel(initialCurves, srf, dist, count);
curveList.AddRange(generatedCurves);
// Flip the plane for the opposite direction
plane.Flip();
intersectSuccess = Rhino.Geometry.Intersect.Intersection.BrepPlane(
srf, plane, RhinoMath.ZeroTolerance, out initialCurves, out intersectionPoints);
if (intersectSuccess && initialCurves != null && initialCurves.Length > 0 && initialCurves[0].IsValid)
{
generatedCurves = GenerateCurvesParallel(initialCurves, srf, dist, count);
curveList.AddRange(generatedCurves);
}
}
break;
default:
// If 'towards' parameter is not recognized, do nothing or throw an exception
break;
}
// Assign output parameters
A = curveList;
B = plane; // Optionally return the plane for debugging or further processing
}
// Generate curves by offsetting the initial curves on the surface
private List<Curve> GenerateCurvesParallel(
Curve[] initialCurves,
Brep srf,
double dist,
int count)
{
// Validate input surface
if (srf == null || srf.Faces.Count == 0)
{
return new List<Curve>();
}
BrepFace face = srf.Faces[0];
var curveList = new List<Curve>();
var currentCurves = new List<Curve>(initialCurves);
for (int i = 0; i < count; i++)
{
var nextCurves = new ConcurrentBag<Curve>();
System.Threading.Tasks.Parallel.ForEach(currentCurves, curve =>
{
// Offset the curve on the surface
var offsetCurves = curve.OffsetOnSurface(face, dist, RhinoMath.ZeroTolerance);
if (offsetCurves == null || offsetCurves.Length == 0)
return;
foreach (var offsetCurve in offsetCurves)
{
if (!offsetCurve.IsValid)
continue;
// Check for self-intersections
var selfIntersections = Rhino.Geometry.Intersect.Intersection.CurveSelf(offsetCurve, 0.1);
if (selfIntersections != null && selfIntersections.Count > 0)
continue;
// Extend the curve on the surface if it's open
if (!offsetCurve.IsClosed)
{
offsetCurve = offsetCurve.ExtendOnSurface(CurveEnd.Both, face);
}
nextCurves.Add(offsetCurve);
}
});
if (nextCurves.Count == 0)
break;
curveList.AddRange(nextCurves);
currentCurves = nextCurves.ToList(); // Prepare for next iteration
}
return curveList;
}
Changes and Optimizations:
Input Validation:
Surface Checks: Added checks to ensure srf is not null, and that it contains at least one surface and face before proceeding.
Parameter Checks: Ensured start and end lists contain at least two elements each.
These checks prevent potential NullReferenceException and IndexOutOfRangeException errors.
Variable Naming and Consistency:
Improved variable names for clarity (e.g., changed surf to surface, crvList to curveList).
Consistent variable naming makes the code more readable and professional.
Vector Normalization:
Normalized vectors (xAxis, yAxis, adjustedXAxis) to ensure they are unit vectors before use.
This is crucial when these vectors are used for rotations or as axes in plane construction.
Using RhinoMath.ZeroTolerance:
Replaced hard-coded small numbers like 0.0001 with RhinoMath.ZeroTolerance for better precision control.
This makes the code more robust to numerical precision issues.
Error Handling:
Added checks after operations like Intersection.BrepPlane to ensure they succeeded before proceeding.
Used early returns to exit the function when an error is detected, preventing further execution of dependent code.
Thread-Safe Collections:
Replaced List<Curve> with ConcurrentBag<Curve> in the Parallel.ForEach loop to allow thread-safe additions without locking.
This improves performance by reducing the overhead caused by locks in a multithreaded environment.
Avoiding Unnecessary Locks:
Eliminated the explicit lock statement by using ConcurrentBag, which is designed for concurrent operations.
This enhances the efficiency of the parallel offsetting process.
:
Potential Bug Fixes:
Index Access Checks: Ensured that any access to an array or list element is preceded by a check that confirms the existence of that element.
Null Reference Checks: After operations that can return null, such as OffsetOnSurface, checks are added to handle null results gracefully.
Plane Construction: Adjusted the plane construction to handle cases where angle is exactly 90 degrees to prevent issues with plane orientation and intersection.
Performance Improvements:
Parallel Processing: Utilized Parallel.ForEach along with a ConcurrentBag to process curve offsets in parallel, leveraging multi-core CPUs for performance gains.
Early Exit Conditions: Incorporated early exits in loops and functions when no further valid data is available to process, reducing unnecessary computations.
This optimized code should perform faster due to multithreading and improved checks. It is more professional with better naming conventions, error handling, and documentation. Potential bugs related to input validation, null references, and index out-of-range exceptions have been addressed.
Note: It's important to test this code within your specific environment to ensure that all edge cases are handled correctly and that performance improvements are realized as expected.