Below C# Journal walks thru the assembly structure and update the weight. It also exports CG points in to information window.
In case if the part file is not having solid body , it gives a message saying part has no valid bodies.
using System;
using NXOpen;
using NXOpenUI;
using NXOpen.Assemblies;
public class WgtCg
{
public static void Main(string[] args)
{
Session theSession = Session.GetSession();
UI theUi = UI.GetUI();
Part workPart = theSession.Parts.Work;
Part displayPart = theSession.Parts.Display;
try
{
AssyRun(workPart);
}
catch (NXOpen.NXException ex)
{
theUi.NXMessageBox.Show("Cathced", NXMessageBox.DialogType.Information, ex.ToString());
}
}
public static void AssyRun(Part a)
{
WgtandCG(a);
if (a.ComponentAssembly.RootComponent != null)
{
Component[] a1 = a.ComponentAssembly.RootComponent.GetChildren();
foreach (Component a2 in a1)
{
//msg("Owning Part: " + a2.Prototype.OwningPart.Leaf.ToString());
AssyRun((Part)a2.Prototype.OwningPart);
}
// msg("Reached : " + a.OwningPart.Leaf.ToString());
}
}
public static void msg (string x)
{
Session theSession = Session.GetSession();
ListingWindow lw = theSession.ListingWindow;
if (lw.IsOpen != true)
{
lw.Open();
lw.WriteFullline(x);
}
else
{
lw.WriteFullline(x);
}
}
public static void WgtUpdate(Part p)
{
NXObject[] nxobj = new NXObject[1];
nxobj[0] = p;
MassPropertiesBuilder mbd = p.PropertiesManager.CreateMassPropertiesBuilder(nxobj);
mbd.UpdateNow();
mbd.Destroy();
msg(p.Leaf.ToString()+" Weight is updated.");
}
public static void WgtandCG(Part w)
{
WgtUpdate(w);
Body[] bds = w.Bodies.ToArray();
if (bds.Length > 0)
{
int body = 0;
foreach (Body b in bds)
{
if (b.IsSolidBody)
{
//NXOpen.GeometricAnalysis.SolidDensity den = w.AnalysisManager.CreateSolidDensityObject();
//den.Units = NXOpen.GeometricAnalysis.SolidDensity.UnitsType.PoundsPerCubicInches;
// den.Density = .289;
//bool assign = den.Solids.Add(b);
//den.Commit();
//den.Destroy();
//NXOpen.MeasureBodies mbdy = w.MeasureManager.NewMassProperties()
body++;
Unit[] myunts = w.UnitCollection.ToArray();
Body[] b1 = new Body[1];
b1[0] = b;
NXOpen.MeasureBodies mbdy = w.MeasureManager.NewMassProperties(myunts, .001, b1);
Point3d cg = new Point3d(mbdy.Centroid.X, mbdy.Centroid.Y, mbdy.Centroid.Z);
msg(w.Leaf.ToString()+": Solid body number:"+body.ToString()+ " weight and CG details. ");
msg("Weight:"+mbdy.Weight.ToString());
msg(" CG X:" + cg.X.ToString() + " CG Y:" + cg.Y.ToString() + " CG Z:" + cg.Z.ToString());
}
}
}
else
{
msg(w.Leaf.ToString() + " has no valid bodies");
}
}
public static int GetUnloadOption(string dummy) { return (int)Session.LibraryUnloadOption.Immediately; }
}