public class Detail2DGH : BaseGhComponent
{
private PaftalamaDetayAlmaFrm frm = new PaftalamaDetayAlmaFrm();
private List rectangle = new List();
private readonly List previewCurvesList = new List();
private bool showGeometry = true;
private bool bake = false;
private bool closeForm = false;
private string blockName;
private Guid guid;
private Make2dResult hiddenAndVisibleCurves;
private List cuttedBlockGeo = new List();
List insideCurves = new List();
List overlappingCurves = new List();
public Detail2DGH()
: base("2DDETAY", "P", "DETAY ALMA", "PARDUS", "3D'DEN 2D'YE")
{
InitializeEventHandlers();
}
code
Assistant
protected override string CodeName => "DETAY_ALMA";
protected override GH_Exposure? ValidExposure => GH_Exposure.primary;
protected override Bitmap Icon => Resources.DETAY_ALMA;
private void InitializeEventHandlers()
{
frm.btnBlock.Click += AddBlock;
frm.btnRec.Click += RecSel;
frm.txtName.TextChanged += ControlValueChanged;
frm.cmbScaleText.TextChanged += ControlValueChanged;
frm.cmbScaleDraw.TextChanged += ControlValueChanged;
frm.cmbLayer.TextChanged += ControlValueChanged;
frm.chbHidden.CheckedChanged += ControlValueChanged;
frm.radTurkey.CheckedChanged += ControlValueChanged;
frm.radEnglish.CheckedChanged += ControlValueChanged;
frm.radRussian.CheckedChanged += ControlValueChanged;
frm.btnBake.Click += Bake;
frm.Closed += Frm_Closed;
}
private void ControlValueChanged(object sender, EventArgs e)
{
ExpireSolution(true);
}
private void RecSel(object sender, EventArgs e)
{
rectangle.Clear();
rectangle = EIGetRihnoTl.GetPolylineCurve("Select region.", false, false, false, false, out guid);
ExpireSolution(true);
}
private void Frm_Closed(object sender, EventArgs e)
{
if (closeForm) bake = true;
showGeometry = false;
ExpireSolution(true);
}
private void Bake(object sender, EventArgs e)
{
closeForm = true;
frm.Close();
}
private void AddBlock(object sender, EventArgs e)
{
blockName = EIGetRihnoTl.GetNameBlock("Block Seç", false, true)[0];
ExpireSolution(true);
}
protected override void RegisterInputParams(GH_InputParamManager pManager) { }
protected override void RegisterOutputParams(GH_OutputParamManager pManager)
{
pManager.AddGenericParameter("C", "c", "c", GH_ParamAccess.list);
pManager.AddGenericParameter("C", "c", "c", GH_ParamAccess.list);
}
/// <summary>
/// Authenticated Solve Instance method where the main functionality is executed.
/// </summary>
protected override void AuthenticatedSolveInstance(IGH_DataAccess DA)
{
frm.Show();
previewCurvesList.Clear();
var rectangleGeometries = new List<GeometryBase>();
var make2dGeometries = new List<GeometryBase>();
var doc = RhinoDoc.ActiveDoc;
var currentDocPlane = doc.Views.ActiveView.ActiveViewport.ConstructionPlane();
if (rectangle.Count > 0)
{
List<Curve> ttt = new List<Curve>();
bool is2D;
List<GeometryWithAttributes> blockGeoWithAttributes = GetBlockGeometries(doc, blockName, out var boundingBoxGeo1, out List<Curve> ggg, out is2D);
ttt.AddRange(ggg);
ProcessBlockCurves(ttt, rectangle[0],out List<Curve>_in,out List<Curve>_out);
// Section 9: Bake Geometries
if (bake)
{
//BakeGeometries(doc, rectangleGeometries, make2dGeometries, _Hiddenss, _Visibles, _Verticals);
}
// Show Geometry
EIShowGeomatryTl.ShowGeomatry(previewCurvesList, showGeometry);
DA.SetDataList(0, ttt);
DA.SetDataList(1, rectangle);
//doc.Objects.Delete(guid, true);
}
}
private List<GeometryWithAttributes> GetBlockGeometries(RhinoDoc doc, string blockName, out BoundingBox boundingBoxGeo, out List<Curve> outputCurvves, out bool is2D)
{
var blockGeometriesWithAttributes = new List<GeometryWithAttributes>();
List<GeometryBase> BlockObjs = new List<GeometryBase>();
List<Curve> Outputss = new List<Curve>();
var definition = doc.InstanceDefinitions.Find(blockName, true);
if (definition != null)
{
// Retrieve objects from the block definition
var geometryObjects = definition.GetObjects();
if (geometryObjects != null)
{
foreach (var obj in geometryObjects)
{
BlockObjs.Add(obj.Geometry);
blockGeometriesWithAttributes.Add(new GeometryWithAttributes
{
Geometry = obj.Geometry,
Attributes = obj.Attributes
});
}
}
}
// Compute the bounding box of these geometries
boundingBoxGeo = BoundigboxGeometry(BlockObjs);
var bbox = BoundingBox.Empty;
foreach (var obj in BlockObjs)
{
if (obj is Curve ddd)
{
var fff = (Curve)ddd;
Curve.ProjectToPlane(fff, Plane.WorldXY);
var objBbox = fff.GetBoundingBox(true);
bbox.Union(objBbox);
Outputss.Add(fff);
}
}
var box = new Box(bbox);
is2D = Math.Abs(box.Z.Max - box.Z.Min) < 1;
outputCurvves = Outputss;
// Check if the geometry is 2D
//is2D = Math.Abs(boundingBoxGeo.Max.Z - boundingBoxGeo.Min.Z) < 1;
return blockGeometriesWithAttributes;
}
private void ProcessBlockCurves(List<Curve> blockCurves, Curve region, out List<Curve>r1, out List<Curve>r2)
{
List<Curve> In = new List<Curve>();
List<Curve> Out = new List<Curve>();
List<Curve> AllSSegments = new List<Curve>();
foreach (var curve in blockCurves)
{
AllSSegments.AddRange(blockCurves[0].DuplicateSegments());
}
foreach (var curve in AllSSegments)
{
// Project the curve onto the region's plane if necessary
Curve projectedCurve = curve.DuplicateCurve();
projectedCurve = Curve.ProjectToPlane(projectedCurve, Plane.WorldXY);
// Check if the curve is completely inside the region
if (IsCurveInsideRegion(projectedCurve, region))
{
insideCurves.Add(projectedCurve);
}
else
{
List<double> passs = new List<double>();
// Check for intersection with the region
var intersectionEvents = Rhino.Geometry.Intersect.Intersection.CurveCurve(projectedCurve, region, 0.001, 0.001);
var InterectPoints = CurvveCurveIntersection(projectedCurve, region,out passs);
if (InterectPoints.Count > 0)
{
// Shatter the curve at the intersection points
var segments = projectedCurve.DuplicateSegments();
var shatteredCurves = projectedCurve.Split(passs);
// Check each segment to see if it's inside the region
foreach (var segment in shatteredCurves)
{
// Use the midpoint of the segment to test if it's inside
var midpoint = segment.PointAtNormalizedLength(0.5);
if (region.Contains(midpoint) == PointContainment.Inside)
{
In.Add(segment);
}
else
{
Out.Add(segment);
}
}
}
else
{
Out.Add(projectedCurve);
}
}
}
r1 = In;
r2 = Out;
}
private List<Point3d> CurvveCurveIntersection(Curve A, Curve B,out List<double>prams)
{
var doc = RhinoDoc.ActiveDoc;
//Component written by @bava-kumaravel
//Solves intersections between two curves A and B and returns the
//points of intersection P and the parameters on the curves tA and tB
//Define lists to hold the intersection points and parameters
List<Point3d> points = new List<Point3d>();
List<double> paramA = new List<double>();
List<double> paramB = new List<double>();
//Define tolerance as the Model Space Absolute Tolerance
double tol = doc.ModelAbsoluteTolerance;
//Perform intersection
Rhino.Geometry.Intersect.CurveIntersections intersections =
Rhino.Geometry.Intersect.Intersection.CurveCurve(A, B, tol, tol);
if (intersections != null)
{
//If there are intersections, go through the list of intersection events
for (int i = 0; i < intersections.Count; i++)
{
Rhino.Geometry.Intersect.IntersectionEvent inter = intersections[i];
//Check if the intersection event is an intersection or an overlap
if (inter.IsOverlap)
{
//If it is an overlap, there will be two points and parameters as
//outputs, one at the start of the overlap and one at the end
Point3d startingPt = inter.PointA;
Point3d endingPt = inter.PointA2;
//Add the two points to the points list
points.Add(startingPt);
points.Add(endingPt);
//Get the overlapping interval in Curve A and B
Interval overlapA = inter.OverlapA;
Interval overlapB = inter.OverlapB;
//Get the starting and ending parameters from the overlapping intervals
double startingParamA = overlapA.Min;
double endingParamA = overlapA.Max;
double startingParamB = overlapB.Min;
double endingParamB = overlapB.Max;
//Add the parameters to the respective lists
paramA.Add(startingParamA);
paramA.Add(endingParamA);
paramB.Add(startingParamB);
paramB.Add(endingParamB);
}
else if (inter.IsPoint)
{
//If it is an intersection, there will be one point and one parameter
//for each curve
Point3d point = inter.PointA;
//Add intersection point to the points list
points.Add(point);
//Get the parameters at curve A and B
double parameterA = inter.ParameterA;
double parameterB = inter.ParameterB;
//Add the parameters to their respective lists
paramA.Add(parameterA);
paramB.Add(parameterB);
}
}
}
prams = paramA;
return points;
}
private bool IsCurveInsideRegion(Curve curve, Curve region)
{
// Use a point on the curve to test if it's inside the region
var testPoint = curve.PointAtNormalizedLength(0.5);
var testPoint2 = curve.PointAtNormalizedLength(0.2);
var testPoint3 = curve.PointAtNormalizedLength(0.8);
var tt1 = region.Contains(testPoint, Plane.WorldXY, 0.001) == PointContainment.Inside;
var tt12 = region.Contains(testPoint2, Plane.WorldXY, 0.001) == PointContainment.Inside;
var tt13 = region.Contains(testPoint3, Plane.WorldXY, 0.001) == PointContainment.Inside;
return (tt1 && tt12 && tt13);
}
this has a problem which is the bloc curves are always at the origine but the real block is not there
The issue you're encountering arises because the code retrieves geometries directly from the block definition, which are defined relative to the origin (0,0,0). This means that, regardless of where the block instances are placed in your document, the geometries you get are always at the origin, not at the actual location of the blocks in your model.
To fix this, you need to:
Select the specific block instance in your document (not just the block name or definition).
Retrieve the transformation (InstanceXform) associated with that block instance.
Apply this transformation to the geometries obtained from the block definition, which will position them correctly in your model.
Here's how you can modify your code to implement these steps:
Step 1: Modify the Block Selection Method
Change your AddBlock method to allow the user to select a block instance instead of just getting the block name. Store the ObjectId of the selected instance for later use.
csharp
private Guid selectedInstanceId;
private void AddBlock(object sender, EventArgs e)
{
RhinoDoc doc = RhinoDoc.ActiveDoc;
// Prompt user to select a block instance
var go = new GetObject();
go.SetCommandPrompt("Select a block instance");
go.GeometryFilter = ObjectType.InstanceReference;
go.Get();
if (go.CommandResult() != Rhino.Commands.Result.Success)
{
return;
}
var objRef = go.Object(0);
if (objRef != null)
{
var instanceObj = objRef.Object() as InstanceObject;
if (instanceObj != null)
{
// Save the instance for later use
selectedInstanceId = instanceObj.Id;
blockName = instanceObj.InstanceDefinition.Name;
}
}
ExpireSolution(true);
}
Step 2: Modify the Geometry Retrieval Method
Update your GetBlockGeometries method to retrieve the block instance using the stored selectedInstanceId, get its transformation (InstanceXform), and apply it to the geometries from the definition.
csharp
private List<GeometryWithAttributes> GetBlockGeometries(RhinoDoc doc, string blockName, out BoundingBox boundingBoxGeo, out List<Curve> outputCurves, out bool is2D)
{
var blockGeometriesWithAttributes = new List<GeometryWithAttributes>();
List<GeometryBase> BlockObjs = new List<GeometryBase>();
List<Curve> OutputCurves = new List<Curve>();
var definition = doc.InstanceDefinitions.Find(blockName, true);
boundingBoxGeo = BoundingBox.Empty;
if (definition != null)
{
// Get the instance object using selectedInstanceId
var instanceObj = doc.Objects.FindId(selectedInstanceId) as InstanceObject;
if (instanceObj != null)
{
// Get the instance's transformation
var xform = instanceObj.InstanceXform;
// Retrieve objects from the block definition
var geometryObjects = definition.GetObjects();
if (geometryObjects != null)
{
foreach (var obj in geometryObjects)
{
// Duplicate the geometry
var geom = obj.Geometry.Duplicate();
// Transform it using the instance's transformation
geom.Transform(xform);
BlockObjs.Add(geom);
blockGeometriesWithAttributes.Add(new GeometryWithAttributes
{
Geometry = geom,
Attributes = obj.Attributes
});
// If geometry is a curve, add to output curves
if (geom is Curve curve)
{
OutputCurves.Add(curve);
// Update the bounding box
var objBbox = curve.GetBoundingBox(true);
boundingBoxGeo = BoundingBox.Combine(boundingBoxGeo, objBbox);
}
}
}
}
else
{
// Handle case where the instance is not found
throw new Exception("Block instance not found.");
}
// Now, check if the geometry is 2D
is2D = Math.Abs(boundingBoxGeo.Max.Z - boundingBoxGeo.Min.Z) < 1;
outputCurves = OutputCurves;
}
else
{
boundingBoxGeo = BoundingBox.Empty;
outputCurves = new List<Curve>();
is2D = true;
}
return blockGeometriesWithAttributes;
}
Explanation
Selecting the Block Instance: By prompting the user to select a block instance and storing its ObjectId, you ensure that you're working with the exact block placement in the document.
Applying the Transformation: When you retrieve geometries from the block definition, they are in the local coordinate space of the block (origin-based). By transforming these geometries using the block instance's InstanceXform, you place them correctly in the world coordinate space of your document.
Updating Geometries and Curves: After applying the transformation, you proceed to process the geometries (e.g., extracting curves, computing bounding boxes) as intended.
Additional Adjustments
Handle Multiple Instances: If you need to process multiple block instances, you can modify the code to iterate over all selected instances, applying each one's transformation to the definition geometries.
Error Handling: Ensure you add error handling for cases where the block instance might not be found or other unexpected situations.
Conclusion
By adjusting your code to work with block instances and their transformations, the geometries you retrieve and process will correspond to the actual placements of the blocks in your document, thus resolving the issue of the block curves always being at the origin.
This approach leverages the inherent structure of blocks in Rhino, where definitions are templates and instances are their placements in the model space, each potentially having its own transformation.