public void Execute(UpdaterData data)
{
try
{
Document doc = data.GetDocument();
FamilyInstance window = doc.get_Element(m_windowId) as FamilyInstance;
Element section = doc.get_Element(m_sectionId);
// iterate through modified elements to find the one we want the section to follow
foreach (ElementId id in data.GetModifiedElementIds())
{
if (id == m_windowId)
{
//Let's take this out temporarily.
bool enableLookup = false;
if (enableLookup)
m_schema = Schema.Lookup(m_schemaId); // (new Guid("{4DE4BE80-0857-4785-A7DF-8A8918851CB2}"));
Entity storedEntity = null;
storedEntity = window.GetEntity(m_schema);
//
// first we look-up X-Y-Z parameters, which we know are set on our windows
// and the values are set to the current coordinates of the window instance
Field fieldPosition = m_schema.GetField("Position");
XYZ oldPosition = storedEntity.Get<XYZ>(fieldPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
TaskDialog.Show("Old position", oldPosition.ToString());
LocationPoint lp = window.Location as LocationPoint;
XYZ newPosition = lp.Point;
// XYZ has operator overloads
XYZ translationVec = newPosition - oldPosition;
// move the section by the same vector
if (!translationVec.IsZeroLength())
{
ElementTransformUtils.MoveElement(doc, section.Id, translationVec);
}
TaskDialog.Show("Moving", "Moving");
// Lookup the normal vector (i,j,we assume k=0)
Field fieldOrientation = m_schema.GetField("Orientation");
// Establish the old and new orientation vectors
XYZ oldNormal = storedEntity.Get<XYZ>(fieldOrientation, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
XYZ newNormal = window.FacingOrientation;
// If different, rotate the section by the angle around the location point of the window
double angle = oldNormal.AngleTo(newNormal);
// Need to adjust the rotation angle based on the direction of rotation (not covered by AngleTo)
XYZ cross = oldNormal.CrossProduct(newNormal).Normalize();
double sign = 1.0;
if (!cross.IsAlmostEqualTo(XYZ.BasisZ))
{
sign = -1.0;
}
angle *= sign;
if (Math.Abs(angle) > 0)
{
Line axis = doc.Application.Create.NewLineBound(newPosition, newPosition + XYZ.BasisZ);
ElementTransformUtils.RotateElement(doc, section.Id, axis, angle);
}
// update the parameters on the window instance (to be the current position and orientation)
storedEntity.Set<XYZ>(fieldPosition, newPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
storedEntity.Set<XYZ>(fieldOrientation, newNormal, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
window.SetEntity(storedEntity);
}
}
}
catch (System.Exception ex)
{
TaskDialog.Show("Exception", ex.ToString());
}
return;
}