The issue you're experiencing with the ExpandInstanceObjects method seems to be related to the way transformations are applied to nested instance references. When you expand an inner instance reference, you're applying the transformation from the outer instance directly to the geometry of the inner instances. However, if the inner instances themselves have their own transformation matrix, you need to ensure that the transformations accumulate correctly.
You should apply both the transformation from the outer instance and the transformation inherent to the inner instance reference. Here’s how you can modify your code to address this issue:
public static void ExpandInstanceObjects(InstanceObject instance, List<RhinoObject> output)
{
var definition = instance.InstanceDefinition;
if (definition == null) return;
var instanceXform = instance.InstanceXform;
var ddd = definition.GetObjects();
foreach (var objRef in ddd)
{
// Get the original RhinoObject
var rhinoObj = objRef as RhinoObject;
if (rhinoObj != null)
{
// Check if this RhinoObject is another instance reference
if (rhinoObj.ObjectType == ObjectType.InstanceReference && objRef is InstanceObject nestedInstance)
{
// Recursively expand nested instances
ExpandInstanceObjects(nestedInstance, output);
}
else
{
// Transform the outer instance's coordinates
var geom = rhinoObj.Geometry.Duplicate();
// Apply the transformation from the outer instance
geom.Transform(instanceXform);
// If rhinoObj is an instance, get its own transformation (if any)
if (rhinoObj is InstanceObject)
{
var innerInstanceXform = ((InstanceObject)rhinoObj).InstanceXform;
// Apply this inner transformation as well
geom.Transform(innerInstanceXform);
}
// Add the transformed geometry to output, reflecting the final transformation
output.Add(new RhinoObject(geom));
}
}
}
}
Key Changes:
-
Duplicating Geometry: The line that duplicates the geometry from the rhinoObj is uncommented. Duplicating the geometry helps ensure that you're applying transformations to a new instance rather than modifying the original.
-
Transforming Inner Instances: A check is added to see if the rhinoObj is also an InstanceObject. If it is, you retrieve its transformation and apply it after applying the transform from the outer instance.
Note:
- Ensure that you're correctly handling the specific types and retaining the original objects as needed. The above code assumes you're constructing new
RhinoObjects from transformed geometry; if your actual implementation is different, adjust accordingly.
- The logic assumes both the outer and inner instance transformations accumulate correctly. Make sure to test various configurations in Rhino to verify the output meets your expectations.
Feel free to adjust the geometry handling as per your requirements, especially how you create a new RhinoObject or handle any specific types of geometry or objects.