/// <summary> /// 递归创建装配树 /// </summary> /// <param name="component"></param> /// <param name="swComponet"></param> private static void CreateTree(Component2 component, ref SWComponent swComponent) { if (component == null) { return; } /////////复制组件相关信息/////////// //名称 swComponent.Name = component.Name2; //是否根组件 swComponent.IsRoot = component.IsRoot(); //提取配合,存放在RootComponent节点 //if (swComponent.IsRoot) { swComponent.Mates = GetSWMatesOfRootComponent(component); //} //包围盒 double[] box = null; try { box = component.GetBox(false, false); } catch (Exception e) { //发生异常,说明该组件(根组件)没有包围盒 box = null; } if (box == null) { swComponent.BoundingBox = CreateSWBoundingBox(box); } else { swComponent.BoundingBox = new SWBoundingBox(); } //提取Body object bodyInfo; object[] bodies = component.GetBodies3((int)swBodyType_e.swSolidBody, out bodyInfo); if (bodies != null) { foreach (object objBody in bodies) { swComponent.Bodies.Add(CreateSWBody((Body2)objBody)); } } //继续遍历 object[] subComponents = component.GetChildren(); if (subComponents != null) { foreach (object obj in subComponents) { SWComponent newComponent = new SWComponent(); CreateTree((Component2)obj, ref newComponent); swComponent.SubComponents.Add(newComponent); } } }
/// <summary> /// Возвращает экземпляр класса, представляющего кухонный компонент /// </summary> public static KitchenComponent GetKitchenComponent(Component2 component) { ModelDoc2 model = component.GetModelDoc2(); CustomPropertyManager propertyManager = model.Extension.get_CustomPropertyManager(string.Empty); string kitchenType = string.Empty; string resolvedKitchenType = string.Empty; propertyManager.Get4("KitchenType", false, out kitchenType, out resolvedKitchenType); KitchenComponentTypes.Type kitchentype = KitchenComponentTypes.GetType(kitchenType); switch (kitchentype) { case KitchenComponentTypes.Type.BottomStand: return new BottomStand(component); case KitchenComponentTypes.Type.AngleBottomStand: return null; case KitchenComponentTypes.Type.TopStand: return null; case KitchenComponentTypes.Type.AngleTopStand: return null; case KitchenComponentTypes.Type.Column: return null; case KitchenComponentTypes.Type.Tabletop: return new Tabletop(component); case KitchenComponentTypes.Type.AngleTabletop: return null; case KitchenComponentTypes.Type.Plinth: return new Plinth(component); default: return null; } }
/// <summary> /// lodas an exisiting modelcomponent at the given path /// </summary> /// <param name="path">path to store this component at</param> public modelComponent(string path) { this.swData = RobotInfo.SwData; this.path = path; comp = null; comp = Component; //ConfigType = 0; //default to physical model }
internal DimensionConfiguration(int inNumber, Component2 inComponent, string caption, string idSlave, int id) { Number = inNumber; Component = inComponent; Caption = caption; IdSlave = idSlave; Id = id; }
/// <summary> /// Creates a new modelComponent /// </summary> /// <param name="path">path to stoer this component at</param> /// <param name="configname">Configuration that this compoent is in</param> /// <param name="configtype">The type of the configuration this component is in</param> /// <param name="component">The component that is being stored</param> /// <param name="pid">The persistant ID of the component</param> public modelComponent( string path, String configname, int configtype, Component2 component, String pid) { this.swData = RobotInfo.SwData; this.path = path; comp = component; ConfigType = configtype; ConfigName = configname; ComponentPID = pid; }
public KitchenModule(ModelDoc2 _rootModel, Component2 _swRootComponent, SwAddin _swAddin, ModelDoc2 _swModel) { RootModel = _rootModel; swRootComponent = _swRootComponent; measure = RootModel.Extension.CreateMeasure(); swAddin = _swAddin; swModel = _swModel; rootName = Path.GetFileNameWithoutExtension(RootModel.GetPathName()); }
public FrmReplaceComponents(SwAddin swAddin, Component2[] selComps) { InitializeComponent(); _mSwAddin = swAddin; _mSelComps = selComps; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; Show(); }
public void GetFirstBasic() { // Create and add a component var component = new Component1(); _componentCollection.Add(component); // Component1 qualifies as both of these types, so both should return the object. Assert.Same(component, _componentCollection.GetFirst <Component1>()); Assert.Same(component, _componentCollection.GetFirst <ComponentBase>()); // Component1 is NOT this type, so this should throw Assert.Throws <ArgumentException>(() => _componentCollection.GetFirst <Component2>()); // Create and add a component of a different type var component2 = new Component2(); _componentCollection.Add(component2); // Component1 should return the same instance as before Assert.Same(component, _componentCollection.GetFirst <Component1>()); var retrievedComponent = _componentCollection.GetFirst <ComponentBase>(); // Should be one of the two, since both are the proper type. Order is not enforced since we don't have priorities set to the components Assert.True(ReferenceEquals(retrievedComponent, component) || ReferenceEquals(retrievedComponent, component2)); // Should now return component2 Assert.Same(component2, _componentCollection.GetFirst <Component2>()); // Remove the original component _componentCollection.Remove(component); // Now component1 should throw because there's no more component1 instances in the container, // but the others should return component2 Assert.Throws <ArgumentException>(() => _componentCollection.GetFirst <Component1>()); Assert.Same(component2, _componentCollection.GetFirst <ComponentBase>()); // Component2 qualifies Assert.Same(component2, _componentCollection.GetFirst <Component2>()); }
public static void AddMate(SldWorks swApp, ModelDoc2 Doc, string newpartpath) { #region 添加部件 swApp.OpenDoc(newpartpath, 1); ((AssemblyDoc)Doc).AddComponent5(newpartpath, 0, "", false, "", 0, 0.3, 0); swApp.CloseDoc(newpartpath); #endregion Component2 BaseComp = ((AssemblyDoc)Doc).GetComponentByName("底座-1"); Component2 RoateComp = ((AssemblyDoc)Doc).GetComponentByName("转轴-1"); int err = 0; #region 轴装配 Feature BaseAxi = BaseComp.FeatureByName("基准轴1"); Feature RoateAxi = RoateComp.FeatureByName("转轴中心轴"); BaseAxi.Select(false); RoateAxi.Select(true); ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out err); #endregion #region 底面装配距离 Feature BaseBp = BaseComp.FeatureByName("Top"); Feature RoateBp = RoateComp.FeatureByName("Top"); BaseBp.Select(false); RoateBp.Select(true); ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignALIGNED, false, 10 / 1000.0, 10 / 1000.0, 10 / 1000.0, 0, 0, 0, 0, 0, false, false, 0, out err); #endregion #region 方位装配 Feature BaseOir = BaseComp.FeatureByName("Right"); Feature RoateOir = RoateComp.FeatureByName("Right"); BaseOir.Select(false); RoateOir.Select(true); ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateANGLE, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, (30 / 180.0) * Math.PI, (30 / 180.0) * Math.PI, (30 / 180.0) * Math.PI, false, false, 0, out err); #endregion Doc.EditRebuild3(); }
private void btnGetIntersectionPoint_Click(object sender, EventArgs e) { AllBodies.Clear(); ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc; if (swModel == null) { MessageBox.Show("请先打开装配体"); return; } if (swModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY) { MessageBox.Show("请先打开装配体"); return; } swApp.CommandInProgress = true; if (swApp != null) { Configuration swConf = (Configuration)swModel.GetActiveConfiguration(); Component2 swRootComp = (Component2)swConf.GetRootComponent(); //遍历 TraverseCompXform(swRootComp, 0); } //if (AllBodies.Count > 0) //{ // MessageBox.Show(AllBodies.Count.ToString()); //} CreatePoints(); swApp.CommandInProgress = false; }
public static void TestBridgeFields() { var c = new Component(); Assert.NotNull(c.InstanceField); Assert.NotNull(c.InstanceProperty); Assert.NotNull(Component.StaticField); Assert.NotNull(Component.StaticProperty); c.ctor = 6; c.config = 1; c.events = 2; c.inherits = 3; c.properties = 4; c.statics = 5; Assert.AreEqual(6, c.ctor); Assert.AreEqual(1, c.config); Assert.AreEqual(2, c.events); Assert.AreEqual(3, c.inherits); Assert.AreEqual(4, c.properties); Assert.AreEqual(5, c.statics); Assert.AreEqual(1, c.InstanceEventResult); Assert.AreEqual(2, Component.StaticEventResult); var c1 = new Component1(); Assert.NotNull(c1.any); var c2 = new Component2(); Assert.NotNull(c2.any); var c3 = new Component3(); Assert.NotNull(c3.any); }
public string Change(ModelDoc2 model) { if (string.IsNullOrEmpty(Name)) { return(string.Empty); } try { Log(string.Format("设置部件\"{0}\"的配置为\"{1}\"", Name, Value), 1); AssemblyDoc assm = (AssemblyDoc)model; Component2 com = assm.GetComponentByName(Name); com.ReferencedConfiguration = Value; return(string.Empty); } catch (Exception ex) { string err = string.Format("设置部件\"{0}\"的配置为\"{1}\"时失败", Name, Value); ex = new Exception(err + "---" + ex.ToString()); throw ex; } }
private Boolean SupprimerConfigs(Component2 Cp) { try { if ((Cp.TypeDoc() == eTypeDoc.Piece) && !Cp.IsHidden(true) && !_Dic.ContainsKey(Cp.eKeySansConfig()) && Cp.eEstDansLeDossier(MdlBase)) { _Dic.Add(Cp.eKeySansConfig(), ""); WindowLog.Ecrire(Cp.eNomAvecExt()); foreach (Configuration Cf in Cp.eModelDoc2().eListeConfigs(eTypeConfig.Depliee)) { String IsSup = Cf.eSupprimerConfigAvecEtatAff(Cp.eModelDoc2()) ? "Ok" : "Erreur"; WindowLog.EcrireF(" {0} : {1}", Cf.Name, IsSup); } } } catch (Exception e) { this.LogErreur(new Object[] { e }); } return(false); }
/// <summary> /// 获取根组件的配合(MATE) /// </summary> /// <param name="rootComponent"></param> /// <returns></returns> private static List <Mate2> GetMatesOfRootComponent(Component2 rootComponent) { if (rootComponent == null) { return(null); } Feature feature = null; ModelDoc2 doc = rootComponent.GetModelDoc2(); List <Mate2> mates = new List <Mate2>(); Mate2 pMate = null; //获得配合组(MateGroup) feature = doc.FirstFeature(); while (feature != null) { if (feature.GetTypeName2() == "MateGroup") { break; } feature = feature.GetNextFeature(); } // 从配合组的子特征中提取配合 if (feature != null) { feature = feature.GetFirstSubFeature(); while (feature != null) { pMate = feature.GetSpecificFeature2(); mates.Add(pMate); feature = feature.GetNextSubFeature(); } } return(mates); }
protected void PreSelection() { try { MdlBase.ClearSelection2(true); Component2 Marche = MdlBase.eRecChercherComposant(c => { return(Regex.IsMatch(c.Name2, _pMarche.GetValeur <String>()) && !c.IsSuppressed()); }, c => { return(false); } ); if (Marche.IsRef()) { MdlBase.eSelectMulti(Marche, _Select_Marche.Marque); } Component2 PieceRepet = MdlBase.eRecChercherComposant(c => { return(Regex.IsMatch(c.Name2, _pPieceRepet.GetValeur <String>()) && !c.IsSuppressed()); }); if (PieceRepet.IsRef()) { Feature F = PieceRepet.eChercherFonction(f => { return(Regex.IsMatch(f.Name, _pFonctionRepet.GetValeur <String>())); }, false); if (F.IsRef()) { SelectFonctionRepetition(_Select_FonctionRepet, F); } } } catch (Exception e) { this.LogMethode(new Object[] { e }); } }
public ComponentIdentifier(Component2 component) { this.component = component; OSC_string = ""; if (component.Name2.Contains("button")) { this.OSC_string = "/button/" + buttonCount; buttonCount++; } else if (component.Name2.Contains("slider")) { this.OSC_string = "/slider/" + sliderCount; sliderCount++; } else if (component.Name2.Contains("dial")) { this.OSC_string = "/dial/" + dialCount; dialCount++; } else if (component.Name2.Contains("joystick")) { this.OSC_string = "/joystick/" + joystickCount; joystickCount++; } else if (component.Name2.Contains("scroll-wheel")) { this.OSC_string = "/scrollwheel/" + scrollwheelCount; scrollwheelCount++; } else if (component.Name2.Contains("dpad")) { this.OSC_string = "/dpad/" + dpadCount; dpadCount++; } }
private List <ComponentIdentifier> getAllOurComponents() { List <ComponentIdentifier> found = new List <ComponentIdentifier>(); Component2 swComp = swConf.GetRootComponent3(true); object[] vChildComp; Component2 swChildComp; int i; vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; foreach (String compName in ourComponentNames) { if (swChildComp.Name2.StartsWith(compName) && !swChildComp.Equals(mainBody) && !swChildComp.IsSuppressed()) { ComponentIdentifier ci = new ComponentIdentifier(swChildComp); found.Add(ci); } } } return(found); }
private Boolean AppartientAuCorps(Component2 cp, Body2 corps, MateEntity2 m) { if (cp.Name2 != m.ReferenceComponent.Name2) { return(false); } Edge e; if (m.ReferenceType2 == (int)swSelectType_e.swSelVERTICES) { Vertex v = m.Reference; e = v.GetEdges()[0]; } else if (m.ReferenceType2 == (int)swSelectType_e.swSelEDGES) { e = m.Reference; } else if (m.ReferenceType2 == (int)swSelectType_e.swSelFACES) { e = m.Reference; } else { return(false); } Body2 b = e.GetBody(); if (b.Name == corps.Name) { return(true); } return(false); }
public void SetSWComponents(Link externalLink) { if (externalLink.SWComponents != null) { SWComponents = new List <Component2>(externalLink.SWComponents); } else { SWComponents = new List <Component2>(); } if (externalLink.SWComponentPIDs != null) { SWComponentPIDs = new List <byte[]>(externalLink.SWComponentPIDs); } else { SWComponentPIDs = new List <byte[]>(); } SWMainComponent = externalLink.SWMainComponent; SWMainComponentPID = externalLink.SWMainComponentPID; isFixedFrame = externalLink.isFixedFrame; }
public void ReadMat(ModelDoc2 swDoc) { AssemblyDoc swADoc; object[] varComp; double[] varMatProp; swADoc = (AssemblyDoc)swDoc; varComp = (object[])swADoc.GetComponents(true); int I = 0; for (I = 0; I < varComp.Length; I++) { Component2 swComp = default(Component2); swComp = (Component2)varComp[I]; varMatProp = (double[])swComp.GetModelMaterialPropertyValues(swComp.ReferencedConfiguration); if (!((varMatProp == null))) { Debug.Print(swComp.Name2 + "(" + I + ")" + "ConfigName : " + swComp.ReferencedConfiguration + "MatProp : "); Debug.Print("Red: " + (varMatProp[0]) * 255.0); Debug.Print("Green: " + (varMatProp[1]) * 255.0); Debug.Print("Blue: " + (varMatProp[2]) * 255.0); Debug.Print("Ambient: " + (varMatProp[3]) * 100.0 + "%"); Debug.Print("Diffuse: " + (varMatProp[4]) * 100.0 + "%"); Debug.Print("Specularity: " + (varMatProp[5]) * 100.0 + "%"); Debug.Print("Shininess: " + (varMatProp[6]) * 100.0 + "%"); Debug.Print("Transparency: " + (varMatProp[7]) * 100.0 + "%"); Debug.Print("Emission: " + (varMatProp[8]) * 100.0 + "%"); } Debug.Print(""); } }
/// <summary> /// Returns Lists of Custom_parts and Standard_Parts /// </summary> /// <param name="swModel"></param> /// <param name="swTableAnn"></param> /// <param name="ConfigName"></param> /// <param name="Standard_Parts"></param> /// <param name="Custom_Parts"></param> public static void Get_Sorted_Part_Data(ModelDoc2 swModel, BomFeature swBomFeat, List <BOM_Part_Informations> Standard_Parts, List <BOM_Part_Informations> Custom_Parts, string projectpath) { try { int nNumRow = 0; int J = 0; int I = 0; int numStandard_Part = 1; int numCustom_Part = 1; int quantity = 0; int index_description = 0; int index_article_number = 0; int index_supplier = 0; BOM_Part_Informations part_informations; string ItemNumber = null; string PartNumber = null; // Debug.Print(" Table Title " + swTableAnn.Title); Feature swFeat = default(Feature); object[] vTableArr = null; object vTable = null; string[] vConfigArray = null; object vConfig = null; string ConfigName = null; string partconfig = null; TableAnnotation swTable = default(TableAnnotation); Annotation swAnnotation = default(Annotation); object visibility = null; swFeat = swBomFeat.GetFeature(); vTableArr = (object[])swBomFeat.GetTableAnnotations(); foreach (TableAnnotation vTable_loopVariable in vTableArr) { vTable = vTable_loopVariable; swTable = (TableAnnotation)vTable; vConfigArray = (string[])swBomFeat.GetConfigurations(true, ref visibility); foreach (object vConfig_loopVariable in vConfigArray) { vConfig = vConfig_loopVariable; ConfigName = (string)vConfig; // MessageBox.Show(ConfigName); // swTable.SaveAsPDF(@"C:\Users\alex\Desktop\test.pdf"); nNumRow = swTable.RowCount; BomTableAnnotation swBOMTableAnn = default(BomTableAnnotation); swBOMTableAnn = (BomTableAnnotation)swTable; //swTable.GetColumnTitle for (int h = 0; h < swTable.ColumnCount; h++) { switch (swTable.GetColumnTitle(h)) { case "Benennung": index_description = h; break; case "Artikelnummer": index_article_number = h; break; case "Lieferant": index_supplier = h; break; default: break; } } if (index_supplier != 0 || index_supplier != 0 || index_article_number != 0) //Standard BOM Template { for (int n = 0; n <= nNumRow - 1; n++) { // Debug.Print(" Row Number " + J + " Component Count : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber)); // Debug.Print(" Item Number : " + ItemNumber); // Debug.Print(" Part Number : " + PartNumber); // MessageBox.Show("bubu"); object[] vPtArr = null; Component2 swComp = null; object pt = null; quantity = swBOMTableAnn.GetComponentsCount2(n, ConfigName, out ItemNumber, out PartNumber); vPtArr = (object[])swBOMTableAnn.GetComponents2(n, ConfigName); if (((vPtArr != null))) { for (I = 0; I <= vPtArr.GetUpperBound(0); I++) { pt = vPtArr[I]; swComp = (Component2)pt; if ((swComp != null)) { part_informations = new BOM_Part_Informations(); part_informations.manufacturer = swTable.get_Text(n, index_supplier); part_informations.order_number = swTable.get_Text(n, index_article_number); part_informations.IsAssembly = false; part_informations.part_number = PartNumber.TrimStart(); part_informations.quantity = quantity.ToString(); //Custom part if (swComp.GetPathName().Contains(projectpath)) { if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM")) { // MessageBox.Show(swComp.GetPathName()); part_informations.IsAssembly = true; } part_informations.description = swComp.ReferencedConfiguration; part_informations.item_number = numCustom_Part.ToString(); numCustom_Part++; Custom_Parts.Add(part_informations); break; } part_informations.description = swTable.get_Text(n, index_description); part_informations.item_number = numStandard_Part.ToString(); numStandard_Part++; Standard_Parts.Add(part_informations); break; } else { Debug.Print(" Could not get component."); } } } } } else //No Standard BOM Template { for (J = 0; J <= nNumRow - 1; J++) { // Debug.Print(" Row Number " + J + " Component Count : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber)); // Debug.Print(" Item Number : " + ItemNumber); // Debug.Print(" Part Number : " + PartNumber); object[] vPtArr = null; Component2 swComp = null; object pt = null; quantity = swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber); vPtArr = (object[])swBOMTableAnn.GetComponents2(J, ConfigName); if (((vPtArr != null))) { for (I = 0; I <= vPtArr.GetUpperBound(0); I++) { pt = vPtArr[I]; swComp = (Component2)pt; if ((swComp != null)) { part_informations = new BOM_Part_Informations(); part_informations.description = swComp.ReferencedConfiguration; part_informations.part_number = PartNumber; part_informations.quantity = quantity.ToString(); //Custom part if (swComp.GetPathName().Contains(projectpath)) { if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM")) { break; } else { part_informations.item_number = numCustom_Part.ToString(); numCustom_Part++; Custom_Parts.Add(part_informations); break; } } part_informations.item_number = numStandard_Part.ToString(); numStandard_Part++; Standard_Parts.Add(part_informations); break; } else { Debug.Print(" Could not get component."); } } } } } break; } } swAnnotation = swTable.GetAnnotation(); swAnnotation.Select3(false, null); swModel.EditDelete(); } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } }
public static bool ConvertMateToPython( ref Feature swMateFeature, ref string asciitext, ref ISldWorks mSWApplication, ref Hashtable saved_parts, ref int num_link, ref MathTransform roottrasf, ref Component2 assemblyofmates ) { if (swMateFeature == null) { return(false); } Mate2 swMate = (Mate2)swMateFeature.GetSpecificFeature2(); if (swMate == null) { return(false); } object foo = null; bool[] suppressedflags; suppressedflags = (bool[])swMateFeature.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, foo); if (suppressedflags[0] == true) { return(false); } if (swMate.GetMateEntityCount() >= 2) { // Get the mated parts MateEntity2 swEntityA = swMate.MateEntity(0); MateEntity2 swEntityB = swMate.MateEntity(1); Component2 swCompA = swEntityA.ReferenceComponent; Component2 swCompB = swEntityB.ReferenceComponent; double[] paramsA = (double[])swEntityA.EntityParams; double[] paramsB = (double[])swEntityB.EntityParams; // this is needed because parts might reside in subassemblies, and mate params are expressed in parent subassembly MathTransform invroottrasf = (MathTransform)roottrasf.Inverse(); MathTransform trA = roottrasf; MathTransform trB = roottrasf; if (assemblyofmates != null) { MathTransform partrasfA = assemblyofmates.GetTotalTransform(true); if (partrasfA != null) { trA = partrasfA.IMultiply(invroottrasf); // row-ordered transf. -> reverse mult.order! } MathTransform partrasfB = assemblyofmates.GetTotalTransform(true); if (partrasfB != null) { trB = partrasfB.IMultiply(invroottrasf); // row-ordered transf. -> reverse mult.order! } } // Fetch the python names using hash map (python names added when scanning parts) ModelDocExtension swModelDocExt = default(ModelDocExtension); ModelDoc2 swModel = (ModelDoc2)mSWApplication.ActiveDoc; swModelDocExt = swModel.Extension; String name1 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompA)]; String name2 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompB)]; // Only constraints between two parts or part & layout can be created if (((name1 != null) || (name2 != null)) && (name1 != name2)) { CultureInfo bz = new CultureInfo("en-BZ"); if (name1 == null) { name1 = "body_0"; } if (name2 == null) { name2 = "body_0"; } // Add some comment in Python, to list the referenced SW items asciitext += "\n# Mate constraint: " + swMateFeature.Name + " [" + swMateFeature.GetTypeName2() + "]" + " type:" + swMate.Type + " align:" + swMate.Alignment + " flip:" + swMate.Flipped + "\n"; for (int e = 0; e < swMate.GetMateEntityCount(); e++) { MateEntity2 swEntityN = swMate.MateEntity(e); Component2 swCompN = swEntityN.ReferenceComponent; String ce_nameN = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompN)]; if (ce_nameN == "") { ce_nameN = "body_0"; // reference assembly } asciitext += "# Entity " + e + ": C::E name: " + ce_nameN + " , SW name: " + swCompN.Name2 + " , SW ref.type:" + swEntityN.Reference.GetType() + " (" + swEntityN.ReferenceType2 + ")\n"; } asciitext += "\n"; // // For each type of SW mate, see which C::E mate constraint(s) // must be created. Some SW mates correspond to more than one C::E constraints. // bool swapAB_1 = false; bool do_CHmate_Xdistance = false; double do_distance_val = 0.0; bool do_CHmate_parallel = false; bool do_parallel_flip = false; bool do_CHmate_orthogonal = false; bool do_CHmate_spherical = false; bool do_CHmate_pointline = false; // to simplify things later... // NOTE: swMate.MateEntity(0).Reference.GetType() seems equivalent to swMate.MateEntity(0).ReferenceType2 // but in some cases the latter fails. /* * bool entity_0_as_FACE = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelFACES); * bool entity_0_as_EDGE = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelEDGES) || * (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelSKETCHSEGS) || * (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelDATUMAXES); * bool entity_0_as_VERTEX = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || * (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || * (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); * * bool entity_1_as_FACE = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelFACES); * bool entity_1_as_EDGE = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelEDGES) || * (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelSKETCHSEGS) || * (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelDATUMAXES); * bool entity_1_as_VERTEX = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || * (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || * (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); */ // NOTE: swMate.MateEntity(0).Reference.GetType() seems equivalent to swMate.MateEntity(0).ReferenceType2 // but in some cases the latter fails. However, sometimes swMate.MateEntity(0).Reference.GetType() is null ReferenceType2 is ok, // so do the following trick: int entity0_ref = swMate.MateEntity(0).Reference.GetType(); if (entity0_ref == (int)swSelectType_e.swSelNOTHING) { entity0_ref = swMate.MateEntity(0).ReferenceType2; } int entity1_ref = swMate.MateEntity(1).Reference.GetType(); if (entity1_ref == (int)swSelectType_e.swSelNOTHING) { entity1_ref = swMate.MateEntity(1).ReferenceType2; } bool entity_0_as_FACE = (entity0_ref == (int)swSelectType_e.swSelFACES) || (entity0_ref == (int)swSelectType_e.swSelDATUMPLANES); bool entity_0_as_EDGE = (entity0_ref == (int)swSelectType_e.swSelEDGES) || (entity0_ref == (int)swSelectType_e.swSelSKETCHSEGS) || (entity0_ref == (int)swSelectType_e.swSelDATUMAXES); bool entity_0_as_VERTEX = (entity0_ref == (int)swSelectType_e.swSelVERTICES) || (entity0_ref == (int)swSelectType_e.swSelSKETCHPOINTS) || (entity0_ref == (int)swSelectType_e.swSelDATUMPOINTS); bool entity_1_as_FACE = (entity1_ref == (int)swSelectType_e.swSelFACES) || (entity1_ref == (int)swSelectType_e.swSelDATUMPLANES); bool entity_1_as_EDGE = (entity1_ref == (int)swSelectType_e.swSelEDGES) || (entity1_ref == (int)swSelectType_e.swSelSKETCHSEGS) || (entity1_ref == (int)swSelectType_e.swSelDATUMAXES); bool entity_1_as_VERTEX = (entity1_ref == (int)swSelectType_e.swSelVERTICES) || (entity1_ref == (int)swSelectType_e.swSelSKETCHPOINTS) || (entity1_ref == (int)swSelectType_e.swSelDATUMPOINTS); Point3D cA = new Point3D(0, 0, 0); Point3D cB = new Point3D(0, 0, 0); Vector3D dA = new Vector3D(1, 0, 0); Vector3D dB = new Vector3D(1, 0, 0); Point3D cAloc = new Point3D(paramsA[0], paramsA[1], paramsA[2]); cA = SWTaskpaneHost.PointTransform(cAloc, ref trA); Point3D cBloc = new Point3D(paramsB[0], paramsB[1], paramsB[2]); cB = SWTaskpaneHost.PointTransform(cBloc, ref trB); if (!entity_0_as_VERTEX) { Vector3D dAloc = new Vector3D(paramsA[3], paramsA[4], paramsA[5]); dA = SWTaskpaneHost.DirTransform(dAloc, ref trA); } if (!entity_1_as_VERTEX) { Vector3D dBloc = new Vector3D(paramsB[3], paramsB[4], paramsB[5]); dB = SWTaskpaneHost.DirTransform(dBloc, ref trB); } if (swMateFeature.GetTypeName2() == "MateCoincident") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_VERTEX)) { do_CHmate_spherical = true; } if ((entity_0_as_VERTEX) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; } if ((entity_0_as_EDGE) && (entity_1_as_VERTEX)) { do_CHmate_pointline = true; swapAB_1 = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_Xdistance = true; swapAB_1 = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_orthogonal = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_Xdistance = true; do_CHmate_orthogonal = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) { do_parallel_flip = true; } } if (swMateFeature.GetTypeName2() == "MateConcentric") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_pointline = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_pointline = true; swapAB_1 = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) { do_parallel_flip = true; } } if (swMateFeature.GetTypeName2() == "MateParallel") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_orthogonal = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) { do_parallel_flip = true; } } if (swMateFeature.GetTypeName2() == "MatePerpendicular") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_parallel = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_parallel = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) { do_parallel_flip = true; } } if (swMateFeature.GetTypeName2() == "MateDistanceDim") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_Xdistance = true; swapAB_1 = true; } //***TO DO*** cases of distance line-vs-line and line-vs-vertex and vert-vert. // Those will require another .cpp ChLinkMate specialized class(es). if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) { do_parallel_flip = true; } // Get the imposed distance value, in SI units string confnames = ""; do_distance_val = swMate.DisplayDimension.GetDimension2(0).IGetSystemValue3((int)swInConfigurationOpts_e.swThisConfiguration, 0, ref confnames); if (swMate.Flipped) { do_distance_val = -do_distance_val; } } //// //// WRITE PYHTON CODE CORRESPONDING TO CONSTRAINTS //// if (do_CHmate_Xdistance) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateXdistance()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); if (!entity_0_as_VERTEX) { asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); } if (!entity_1_as_VERTEX) { asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); } // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dB)\n", linkname, name1, name2); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dA)\n", linkname, name2, name1); } //if (do_distance_val!=0) asciitext += String.Format(bz, "{0}.SetDistance({1})\n", linkname, do_distance_val * ChScale.L * -1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } if (do_CHmate_parallel) { if (Math.Abs(Vector3D.DotProduct(dA, dB)) > 0.98) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateParallel()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); if (do_parallel_flip) { asciitext += String.Format(bz, "{0}.SetFlipped(True)\n", linkname); } // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); } asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } else { asciitext += "\n# ChLinkMateParallel skipped because directions not parallel! \n"; } } if (do_CHmate_orthogonal) { if (Math.Abs(Vector3D.DotProduct(dA, dB)) < 0.02) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateOrthogonal()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); } asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } else { asciitext += "\n# ChLinkMateOrthogonal skipped because directions not orthogonal! \n"; } } if (do_CHmate_spherical) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateSpherical()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB)\n", linkname, name1, name2); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA)\n", linkname, name2, name1); } asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } if (do_CHmate_pointline) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateGeneric()\n", linkname); asciitext += String.Format(bz, "{0}.SetConstrainedCoords(False, True, True, False, False, False)\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); if (!entity_0_as_VERTEX) { asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); } else { asciitext += String.Format(bz, "dA = chrono.VNULL\n"); } if (!entity_1_as_VERTEX) { asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); } else { asciitext += String.Format(bz, "dB = chrono.VNULL\n"); } // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); } asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } // Now, do some other special mate type that did not fall in combinations // of do_CHmate_pointline, do_CHmate_spherical, etc etc if (swMateFeature.GetTypeName2() == "MateHinge") { // auto flip direction if anti aligned (seems that this is assumed automatically in MateHinge in SW) if (Vector3D.DotProduct(dA, dB) < 0) { dB.Negate(); } // Hinge constraint must be splitted in two C::E constraints: a coaxial and a point-vs-plane num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateCoaxial()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Initialize link, by setting the two csys, in absolute space, asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n", linkname); // NOTE!!! The 'hinge' mate uses 4 references: fetch the two others remaining // and build another C::E link, for point-vs-face mating MateEntity2 swEntityC = swMate.MateEntity(2); MateEntity2 swEntityD = swMate.MateEntity(3); Component2 swCompC = swEntityC.ReferenceComponent; Component2 swCompD = swEntityD.ReferenceComponent; double[] paramsC = (double[])swEntityC.EntityParams; double[] paramsD = (double[])swEntityD.EntityParams; String name3 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompC)]; String name4 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompD)]; MathTransform trC = roottrasf; MathTransform trD = roottrasf; if (assemblyofmates != null) { MathTransform partrasfC = assemblyofmates.GetTotalTransform(true); if (partrasfC != null) { trC = partrasfC.IMultiply(invroottrasf); } MathTransform partrasfD = assemblyofmates.GetTotalTransform(true); if (partrasfD != null) { trD = partrasfD.IMultiply(invroottrasf); } } // NOTE: swMate.MateEntity(0).Reference.GetType() seems equivalent to swMate.MateEntity(0).ReferenceType2 // but in some cases the latter fails. However, sometimes swMate.MateEntity(0).Reference.GetType() is null ReferenceType2 is ok, // so do the following trick: int entity2_ref = swMate.MateEntity(2).Reference.GetType(); if (entity2_ref == (int)swSelectType_e.swSelNOTHING) { entity2_ref = swMate.MateEntity(2).ReferenceType2; } int entity3_ref = swMate.MateEntity(3).Reference.GetType(); if (entity3_ref == (int)swSelectType_e.swSelNOTHING) { entity3_ref = swMate.MateEntity(3).ReferenceType2; } bool entity_2_as_VERTEX = (entity2_ref == (int)swSelectType_e.swSelVERTICES) || (entity2_ref == (int)swSelectType_e.swSelSKETCHPOINTS) || (entity2_ref == (int)swSelectType_e.swSelDATUMPOINTS); bool entity_3_as_VERTEX = (entity3_ref == (int)swSelectType_e.swSelVERTICES) || (entity3_ref == (int)swSelectType_e.swSelSKETCHPOINTS) || (entity3_ref == (int)swSelectType_e.swSelDATUMPOINTS); Point3D cC = new Point3D(0, 0, 0); Point3D cD = new Point3D(0, 0, 0); Vector3D dC = new Vector3D(1, 0, 0); Vector3D dD = new Vector3D(1, 0, 0); Point3D cCloc = new Point3D(paramsC[0], paramsC[1], paramsC[2]); cC = SWTaskpaneHost.PointTransform(cCloc, ref trC); Point3D cDloc = new Point3D(paramsD[0], paramsD[1], paramsD[2]); cD = SWTaskpaneHost.PointTransform(cDloc, ref trD); if (!entity_2_as_VERTEX) { Vector3D dCloc = new Vector3D(paramsC[3], paramsC[4], paramsC[5]); dC = SWTaskpaneHost.DirTransform(dCloc, ref trC); } if (!entity_3_as_VERTEX) { Vector3D dDloc = new Vector3D(paramsD[3], paramsD[4], paramsD[5]); dD = SWTaskpaneHost.DirTransform(dDloc, ref trD); } num_link++; linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateXdistance()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cC.X * ChScale.L, cC.Y * ChScale.L, cC.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dC.X, dC.Y, dC.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cD.X * ChScale.L, cD.Y * ChScale.L, cD.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dD.X, dD.Y, dD.Z); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Initialize link, by setting the two csys, in absolute space, if (entity_2_as_VERTEX) { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA)\n", linkname, name3, name4); } else { asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dB)\n", linkname, name3, name4); } // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n", linkname); return(true); } } } return(false); }
public void StoreToSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor) { System.Windows.Forms.MessageBox.Show("StoreToSelection()"); // If user pressed OK, apply settings to all selected parts (i.e. ChBody in C::E): for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) { if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc(); // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPart, "Chrono ChBody data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); swPartModel.ForceRebuild3(false); // needed? if (myattr == null) { System.Windows.Forms.MessageBox.Show("myattr null in setting!!"); } } ((Parameter)myattr.GetParameter("collision_on")).SetDoubleValue2( Convert.ToDouble(m_collide), (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("friction")).SetDoubleValue2( m_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("rolling_friction")).SetDoubleValue2( m_rolling_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("spinning_friction")).SetDoubleValue2( m_spinning_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("restitution")).SetDoubleValue2( m_restitution, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_margin")).SetDoubleValue2( m_collision_margin, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_envelope")).SetDoubleValue2( m_collision_envelope, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_family")).SetDoubleValue2( (double)m_collision_family, (int)swInConfigurationOpts_e.swThisConfiguration, ""); /* * // fetch SW attribute with Chrono parameters for ChConveyor * SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); * if (myattr_conveyor == null) * { * // if not already added to part, create and attach it * myattr_conveyor = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono ChConveyor data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); * if (myattr_conveyor == null) * System.Windows.Forms.MessageBox.Show("myattr null in setting!!"); * } * * ((Parameter)myattr_conveyor.GetParameter("conveyor_speed")).SetDoubleValue2( * m_conveyor_speed, (int)swInConfigurationOpts_e.swThisConfiguration, ""); */ } } }
public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor) { // Fetch current properties from the selected part(s) (i.e. ChBody in C::E) for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) { if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { //Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); Component2 swPart = swSelMgr.GetSelectedObjectsComponent3(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc2(); Component2 swPartcorr = swPartModel.Extension.GetCorresponding(swPart); // ***TODO*** for instanced parts? does not work... swPartcorr = swPart; // ***TODO*** if (swPartModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentFlexibleSolving) { System.Windows.Forms.MessageBox.Show("Fexible assemblies not supported as ChBody (set as Rigid?)"); return; } if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentRigidSolving) { System.Windows.Forms.MessageBox.Show("Setting props to rigid assembly as ChBody"); AssemblyDoc swAssemblyDoc = (AssemblyDoc)swPartModel; swPart.Select(false); swAssemblyDoc.EditAssembly(); swAssemblyDoc.EditRebuild(); //return; } } // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = null; if (swPartcorr != null) { myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); } if (myattr == null) { // if not already added to part, create and attach it //System.Windows.Forms.MessageBox.Show("Create data"); myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration); swPartModel.ForceRebuild3(false); // needed, but does not work... //swPartModel.Rebuild((int)swRebuildOptions_e.swRebuildAll); // needed but does not work... if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid)) { System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed)) { System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous)) { System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted)) { System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!"); } } Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter( "collision_on")).GetDoubleValue())); Set_friction(((Parameter)myattr.GetParameter( "friction")).GetDoubleValue()); Set_rolling_friction(((Parameter)myattr.GetParameter( "rolling_friction")).GetDoubleValue()); Set_spinning_friction(((Parameter)myattr.GetParameter( "spinning_friction")).GetDoubleValue()); Set_restitution(((Parameter)myattr.GetParameter( "restitution")).GetDoubleValue()); Set_collision_envelope(((Parameter)myattr.GetParameter( "collision_envelope")).GetDoubleValue()); Set_collision_margin(((Parameter)myattr.GetParameter( "collision_margin")).GetDoubleValue()); Set_collision_family((int)((Parameter)myattr.GetParameter( "collision_family")).GetDoubleValue()); // fetch SW attribute with Chrono parameters for ChConveyor /* * SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); * if (myattr_conv == null) * { * // if not already added to part, create and attach it * //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); * } */ /* * // fetch SW attribute with Chrono parameters for ChConveyor (if any!) * SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); * if (myattr_conveyor != null) * { * show_conveyor_params = true; * * Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter( * "conveyor_speed")).GetDoubleValue()); * } */ } } }
public App() { Component1 c1 = new Component1(); Component1 c2 = new Component2(); }
public void PythonTraverseFeatures_for_links(Feature swFeat, long nLevel, ref string asciitext, ref MathTransform roottrasf, ref Component2 assemblyofmates) { Feature swSubFeat; int num_link = 0; while ((swFeat != null)) { // Export mates as constraints if ((swFeat.GetTypeName2() == "MateGroup") && (this.checkBox_constraints.Checked)) { swSubFeat = (Feature)swFeat.GetFirstSubFeature(); while ((swSubFeat != null)) { ConvertMates.ConvertMateToPython(ref swSubFeat, ref asciitext, ref mSWApplication, ref saved_parts, ref num_link, ref roottrasf, ref assemblyofmates); swSubFeat = (Feature)swSubFeat.GetNextSubFeature(); } // end while loop on subfeatures mates } // end if mate group swFeat = (Feature)swFeat.GetNextFeature(); } // end while loop on features }
/// <summary> /// adds the given component to the list of link components if it not in the list already /// and adds the PID to LinkComponentPIDs /// </summary> /// <param name="component">component to add to this model configuration</param> public void insertModelComp(Component2 component) { if (component == null) return; //check that component not already in the list for (int i = 0; i < LinkComponents.Count; i++) { if (component == LinkComponents[i].Component) return; } //make new component String newPath = path + "/component" + nextComponentNumber; String newconfigname = modelDoc.ConfigurationManager.ActiveConfiguration.Name; byte[] pid = modelDoc.Extension.GetPersistReference3(component); String newpid = Convert.ToBase64String(pid); modelComponent newComponent = new modelComponent(newPath,newconfigname,Type,component,newpid); nextComponentNumber++; //insert in order: Collision, Visual, Physical //assume that LinkComponents already ordered as so for (int i = 0; i < LinkComponents.Count; i++) { if (newComponent.ConfigType < LinkComponents[i].ConfigType) { LinkComponents.Insert(i, newComponent); LinkComponentPIDs.AddItem(newpid); break; } } if (!LinkComponents.Contains(newComponent)) // insert newComponent at end { LinkComponents.Add(newComponent); LinkComponentPIDs.AddItem(newpid); } }
/// <summary> /// Method that process an assembly document and check if every subpart and subassembly has been sent to the server and if it is updated. /// <param name="currentAssembly">The current assembly been processing</param> /// <param name="worker">The worker in charge of doing this task</param> /// </summary> public ProcessStatus ProcessAssemblyRecursively(Assembly currentAssembly, BackgroundWorker worker) { // If the current assembly is already been processed in the current session, skip this iteration ProcessStatus possibleResult; if (m_ProcessedAssemblies.TryGetValue(currentAssembly.Guid, out possibleResult)) { return(possibleResult); } var allSubOccurrencesValid = true; var waitingForId = false; if (!currentAssembly.IsPart) { // Access to the colection of occurrences object[] allComponents = (object[])currentAssembly.AssemblyDocument.GetComponents(true); // True if all the suboccurrences are already in the server // Verify that all the subassemblies and subparts have an id for (int i = 0; i < allComponents.Length; i++) { // Access to the occurrence Component2 component = (Component2)allComponents[i]; object modelDoc = component.GetModelDoc2(); var componentAssembly = new Assembly(new Model((ModelDoc2)modelDoc)); // Analize each occurrence ProcessStatus result = ProcessAssemblyRecursively(componentAssembly, worker); switch (result) { case ProcessStatus.UPDATE: { // Get the occurrence transform. MatrixTransform transform = new MatrixTransform(component.Transform2); // Create the relation between this assembly and it subassembly or subpart Relation relation = new Relation(component.Name, componentAssembly.IdAssembly, new Position(transform.Translation(), transform.EulerAngles())); currentAssembly.ListOfRelations.Add(relation); } break; case ProcessStatus.FAIL: { allSubOccurrencesValid = false; } break; case ProcessStatus.WAITING_FOR_ID: case ProcessStatus.NEW: { waitingForId = true; // Get the occurrence transform. MatrixTransform transform = new MatrixTransform(component.Transform2); // Create the relation between this assembly and it subassembly or subpart Relation relation = new Relation(component.Name, componentAssembly.IdAssembly, new Position(transform.Translation(), transform.EulerAngles())); if (currentAssembly.WaitingChildIds.ContainsKey(componentAssembly.Guid)) { currentAssembly.WaitingChildIds[componentAssembly.Guid].Add(relation); } else { var relationsList = new List <Relation>(); relationsList.Add(relation); currentAssembly.WaitingChildIds.Add(componentAssembly.Guid, relationsList); } } break; } } } // If at leat one of the childs can not be sent to the server, neither the current assembly if (!allSubOccurrencesValid) { worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "On of the assembly childs cannot be sent")); Add(currentAssembly, ProcessStatus.FAIL); return(ProcessStatus.FAIL); } // If some of the child are waiting for id, mark as waiting if (waitingForId && (currentAssembly.CanBeUpdated || currentAssembly.CanBeSent)) { worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Waiting for child id")); Add(currentAssembly, ProcessStatus.WAITING_FOR_ID); return(ProcessStatus.WAITING_FOR_ID); } // If it can be updated, mark for update if (currentAssembly.CanBeUpdated) { worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Ready for update")); Add(currentAssembly, ProcessStatus.UPDATE); return(ProcessStatus.UPDATE); } // If it can be sent, mark for send if (currentAssembly.CanBeSent) { worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Ready to be sent")); Add(currentAssembly, ProcessStatus.NEW); return(ProcessStatus.NEW); } // If the current assembly cant be sent or updated, mark as failed worker.ReportProgress(0, new StatusMessage(currentAssembly.DocumentName, "Cannot be sent")); Add(currentAssembly, ProcessStatus.FAIL); return(ProcessStatus.FAIL); }
private void Run(Face2 dessus, Face2 devant, Feature gPlan, Feature dPlan, Component2 pltG, Component2 pltD) { if ((dessus == null) || (devant == null)) { this.LogMethode(new String[] { "Une reference à un objet a été perdue" }); return; } try { Edge E_Face = dessus.eListeDesArretesCommunes(devant)[0]; List <Edge> ListeArrete = dessus.eListeDesArretesContigues(E_Face); // On assigne les cotes de façon arbitraire pour eviter une assignation suplémentaire Edge E_Gauche = ListeArrete[0]; Edge E_Droit = ListeArrete[1]; // Création des segements gSegment S1 = new gSegment(E_Gauche); gSegment Sf = new gSegment(E_Face); // Orientation des segements S1.OrienterDe(Sf); Sf.OrienterVers(S1); gVecteur Normal = new gVecteur((Double[])dessus.Normal); // Verification du sens de rotation et modification des cotes si nécessaire if (Sf.Vecteur.RotationTrigo(S1.Vecteur, Normal)) { E_Gauche = ListeArrete[1]; E_Droit = ListeArrete[0]; } List <Face2> L = null; L = E_Gauche.eDeuxFacesAdjacentes(); L.Remove(dessus); Face2 FaceGauche = L[0]; L = E_Droit.eDeuxFacesAdjacentes(); L.Remove(dessus); Face2 FaceDroite = L[0]; if (pltG.IsRef()) { if (pltG.GetConstrainedStatus() == (int)swConstrainedStatus_e.swUnderConstrained) { Contraindre(gPlan, FaceGauche); } } if (pltD.IsRef()) { if (pltD.GetConstrainedStatus() == (int)swConstrainedStatus_e.swUnderConstrained) { Contraindre(dPlan, FaceDroite); } } } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
private void ChangeConfigurationForReferenceModel(Component2 comp, string nameConfiguration) { int err = 0, wrn = 0; var mod = _mSwAddin.SwApp.OpenDoc6( comp.IGetModelDoc(). GetPathName(), (int)swDocumentTypes_e.swDocPART, 0, "", ref err, ref wrn); if (mod != null) { mod.ShowConfiguration2(nameConfiguration); mod.Save(); _mSwAddin.SwApp.CloseDoc(mod.GetPathName()); } }
internal Target(DimensionRecorder dimRec, Object targetObject) { //string[] possibleNames = ijbGeneral.COMInfoProvider.isAsignableToNames(targetObject,typeof(Dimension)); if (!(targetObject is Dimension || targetObject is SketchPoint || targetObject is Feature)) { throw new Exception("Invalid trace object type"); } this.dimRec = dimRec; values = new List<TargetValue>(); this.targetObject = targetObject; //model name string modelName = this.dimRec.iSwApp.IActiveDoc.GetTitle(); modelName = Path.GetFileNameWithoutExtension(modelName);//!!!SW adds '.Part' or '.Assembly' to the full name! //Unit of this value (User units) this.angUnit = (UserUnit)this.dimRec.iSwApp.IActiveDoc.GetUserUnit((int)swUserUnitsType_e.swAngleUnit); this.lengthUnit = (UserUnit)this.dimRec.iSwApp.IActiveDoc.GetUserUnit((int)swUserUnitsType_e.swLengthUnit); //string angUnitName = angUnit.GetFullUnitName(false); //This returns eg. 'Grad' string angUnitName = this.angUnit.GetUnitsString(false); //This returns eg. 'Grad' //string lengthUnitName = lengthUnit.GetFullUnitName(false); //This returns eg. Millimeter' string lengthUnitName = this.lengthUnit.GetUnitsString(false); //This returns eg. 'mm' this.targetComponent = null; if (this.targetObject is Dimension) { Dimension dimension = (Dimension)targetObject; //Unit unitName = (dimension.GetType() == (int)swDimensionParamType_e.swDimensionParamTypeDoubleAngular) ? angUnitName : lengthUnitName; //Name targetName = dimension.FullName; } else if (this.targetObject is SketchPoint) { //Unit //Name SketchPoint sketchPoint = (SketchPoint)targetObject; int[] id = (int[])sketchPoint.GetID(); Sketch sketch = sketchPoint.GetSketch(); string sketchName = this.dimRec.iSwApp.IActiveDoc2.GetEntityName(sketch); targetName = string.Format("{0}{1}@{2}@{3}", Lang.POINT, id[1], sketchName, modelName); } else if (this.targetObject is Feature) { Feature feature = (Feature)targetObject; if (this.dimRec.iSwApp.IActiveDoc is AssemblyDoc) { AssemblyDoc assy = (AssemblyDoc) this.dimRec.iSwApp.IActiveDoc; Entity entity = (Entity)feature; this.targetComponent = entity.IGetComponent2(); } Object specificFeature = feature.GetSpecificFeature2(); if (specificFeature != null && specificFeature is RefPoint) { this.targetObject = specificFeature; RefPoint refPoint = (RefPoint)this.targetObject; string refPointName = this.dimRec.iSwApp.IActiveDoc2.GetEntityName(refPoint); targetName = string.Format("{0}@{1}", refPointName, modelName); } else { throw new Exception("Invalid trace object type"); } //Unit unitName = lengthUnitName; } }
/// <summary> /// gets all subComponents if a component is a subassembly /// </summary> /// <param name="comp">The component to find its subComponents of</param> /// <param name="comps">A List to store the subComponents in</param> private void GetSubComponents(Component2 comp, List<Component2> comps) { object[] childrenComps = (object[])comp.GetChildren(); if (childrenComps.Length>0) { foreach (Component2 c in childrenComps) { if (((object[])c.GetChildren()).Length > 0) { GetSubComponents(c, comps); } else { comps.Add(c); } } } }
/// <summary> /// unhides all components in the assembly /// </summary> /// <param name="excludeds">Components that should remain hidden</param> public void UnhideComponents(Component2[] excludeds) { object[] obs = asm.GetComponents(false); SelectionMgr manager = ((ModelDoc2)asm).SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = -1; DispatchWrapper[] dispComps = Array.ConvertAll(obs, e => new DispatchWrapper(e)); manager.AddSelectionListObjects(dispComps, data); ((ModelDoc2)asm).ShowComponent2(); ((ModelDoc2)asm).ClearSelection2(true); ((ModelDoc2)asm).Extension.MultiSelect2(excludeds, false, data); ((ModelDoc2)asm).HideComponent2(); ((ModelDoc2)asm).ClearSelection2(true); }
/// <summary> /// Gets the first component thatwould work as a display reference /// </summary> /// <param name="comp">component to work from</param> /// <returns>A component that would be valid for display</returns> private static Component2 getComponentForDisplay(Component2 comp) { object[] Comps; if (comp == null) Comps = ModelDoc.ConfigurationManager.ActiveConfiguration.GetRootComponent3(false).GetChildren(); else Comps = comp.GetChildren(); foreach (Component2 c in Comps) { if (c.GetChildren().Length <= 0 && c.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) { return c; } } foreach (Component2 c in Comps) { object[] subComps = c.GetChildren(); if(c.GetChildren().Length > 0 && c.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) { Component2 newComp = getComponentForDisplay(c); if (newComp != null) return newComp; } } return null; }
public void OnSelectionboxFocusChanged(int Id) { lock (page) { switch (PrevSelectId) { case linkComponentsSelectionboxID: Component2[] selectedComponents = new Component2[((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(2)]; Component2 temp; for (int l = 1; l <= selectedComponents.Length; l++) { temp = (Component2)((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectsComponent4(l, 2); selectedComponents[l - 1] = temp; } currentLink.LinkComponents = selectedComponents; break; case jointAxis1SelectionboxID: if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(4) > 0) //currentLink.ParentConnection.Axis1 = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 4); DrawJointPreview(); SelectLimits(); jointLinkLowerEdgeSelectionbox.SetSelectionFocus(); break; case jointUpperLimitStopSelectionboxID: //if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(64) > 0) //currentLink.ParentConnection.UpperLimitStop = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 64); break; case jointLinkUpperEdgeSelectionboxID: //if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(32) > 0) //currentLink.ParentConnection.UpperLimitEdge = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 32); break; case jointLowerLimitStopSelectionboxID: //if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(16) > 0) //currentLink.ParentConnection.LowerLimitStop = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 16); break; case jointLinkLowerEdgeSelectionboxID: //if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(8) > 0) //currentLink.ParentConnection.LowerLimitEdge = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 8); break; } PrevSelectId = Id; } }
public Component1(Component2 component2) { this.component2 = component2; }
/// <summary> /// Saves the currently selected link's information back into the robot model /// </summary> private void SaveCurrentLinkSelection() { Component2[] selectedComponents = new Component2[((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(2)]; Component2 temp; for (int l = 1; l <= selectedComponents.Length; l++) { temp = (Component2)((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectsComponent4(l, 2); selectedComponents[l-1] = temp; } currentLink.LinkComponents = selectedComponents; /*if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(8) > 0) currentLink.ParentConnection.LowerLimitEdge = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 8); if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(16) > 0) currentLink.ParentConnection.LowerLimitStop = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 16); if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(32) > 0) currentLink.ParentConnection.UpperLimitEdge = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 32); if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(64) > 0) currentLink.ParentConnection.UpperLimitStop = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 64); if (((SelectionMgr)modelDoc.SelectionManager).GetSelectedObjectCount2(4) > 0) currentLink.ParentConnection.Axis1 = ((SelectionMgr)modelDoc.SelectionManager).GetSelectedObject6(1, 4); if (currentLink.ParentConnection != null) { currentLink.ParentConnection.CalcLimits(null); }*/ swManips = null; DragArrows = null; GC.Collect(); }
public static ExternalFileReferences Get(SldWorks swApp) { try { var obj = new ExternalFileReferences(); ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModDocExt = default(ModelDocExtension); SelectionMgr swSelMgr = default(SelectionMgr); Feature swFeat = default(Feature); Component2 swComp = default(Component2); object vModelPathName = null; object vComponentPathName = null; object vFeature = null; object vDataType = null; object vStatus = null; object vRefEntity = null; object vFeatComp = null; int nConfigOpt = 0; string sConfigName = null; int nRefCount = 0; int nSelType = 0; int i = 0; swModel = (ModelDoc2)swApp.ActiveDoc; swSelMgr = (SelectionMgr)swModel.SelectionManager; swModDocExt = (ModelDocExtension)swModel.Extension; nSelType = swSelMgr.GetSelectedObjectType3(1, -1); switch (nSelType) { // Selected component in an assembly document case (int)swSelectType_e.swSelCOMPONENTS: swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, -1); nRefCount = swComp.ListExternalFileReferencesCount(); swComp.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName); swModel = (ModelDoc2)swComp.GetModelDoc2(); break; // Selected feature in a part or assembly document case (int)swSelectType_e.swSelBODYFEATURES: case (int)swSelectType_e.swSelSKETCHES: swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1); nRefCount = swFeat.ListExternalFileReferencesCount(); swFeat.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName); break; // Part document only default: nRefCount = swModDocExt.ListExternalFileReferencesCount(); swModDocExt.ListExternalFileReferences(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName); break; } //Debug.Print("Model name = " + swModel.GetPathName()); if (nRefCount >= 1) { object[] ModelPathName = new object[nRefCount - 1]; object[] ComponentPathName = new object[nRefCount - 1]; object[] Feature = new object[nRefCount - 1]; object[] DataType = new object[nRefCount - 1]; int[] Status = new int[nRefCount - 1]; object[] RefEntity = new object[nRefCount - 1]; object[] FeatComp = new object[nRefCount - 1]; ModelPathName = (object[])vModelPathName; ComponentPathName = (object[])vComponentPathName; Feature = (object[])vFeature; DataType = (object[])vDataType; Status = (int[])vStatus; RefEntity = (object[])vRefEntity; FeatComp = (object[])vFeatComp; for (i = 0; i <= nRefCount - 1; i++) { obj.ModelPathName = ModelPathName[i].ToString(); obj.ComponentPathName = ComponentPathName[i].ToString(); obj.Feature = Feature[i].ToString(); obj.DataType = DataType[i].ToString(); obj.Status = Status[i].ToString(); obj.ReferenceEntity = RefEntity[i].ToString(); obj.FeatureComponent = FeatComp[i].ToString(); obj.ConfigOption = nConfigOpt.ToString(); obj.ConfigName = sConfigName?.ToString(); } } return(obj); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); return(null); } }
public ComponentWrap(Component2 component2) { this.component2 = component2; }
internal static bool processModel(SldWorks swApp, string file, string targetFile, string calcFile, CancellationToken cancellationToken) { // Initiate variables Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); StreamWriter toFile = new StreamWriter(targetFile); toFile.AutoFlush = true; StreamWriter toCalc = new StreamWriter(calcFile); toCalc.AutoFlush = true; MathUtility swMathUtil = default(MathUtility); ModelDoc2 swModel = default(ModelDoc2); Feature swFeat = default(Feature); Feature swMateFeat = null; Feature swSubFeat = default(Feature); Mate2 swMate = default(Mate2); Component2 swComp = default(Component2); MateEntity2[] swMateEnt = new MateEntity2[3]; MathTransform swTrans = default(MathTransform); MathPoint swOrig = default(MathPoint); AssemblyDoc swAssembly = default(AssemblyDoc); double[] corners = new double[6]; int[] swAssyDir = new int[6]; double[] nPt = new double[3]; object vPt = null; double height = 0; double width = 0; double depth = 0; int Warning = 0; int Error = 0; int i = 0; double[] entityParameters = new double[8]; // Start function try { if (cancellationToken.IsCancellationRequested) { return(false); } string extention = Path.GetExtension(file); int type = 0; if (extention.ToLower().Contains("sldprt")) { type = (int)swDocumentTypes_e.swDocPART; } else { type = (int)swDocumentTypes_e.swDocASSEMBLY; } // Get assembly model swModel = swApp.OpenDoc6(file, type, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref Error, ref Warning) as ModelDoc2; if (Error != 0) { return(false); } if (swModel == null) { return(false); } swModel.Visible = true; // Get first assembly feature swFeat = (Feature)swModel.FirstFeature(); // Iterate over features in FeatureManager design tree while ((swFeat != null)) { if ("MateGroup" == swFeat.GetTypeName()) { swMateFeat = swFeat; break; } swFeat = swFeat = swFeat.GetNextFeature(); } toFile.WriteLine(" " + swMateFeat.Name); toFile.WriteLine(""); // Get first mate, which is a subfeature swSubFeat = (Feature)swMateFeat.GetFirstSubFeature(); while ((swSubFeat != null)) { swMate = (Mate2)swSubFeat.GetSpecificFeature2(); if ((swMate != null)) { for (i = 0; i <= 1; i++) { swMateEnt[i] = swMate.MateEntity(i); swComp = swMateEnt[i].ReferenceComponent; // Initate point nPt[0] = 0.0; nPt[1] = 0.0; nPt[2] = 0.0; vPt = nPt; // Get component origin point swTrans = swComp.Transform2; swMathUtil = (MathUtility)swApp.GetMathUtility(); swOrig = (MathPoint)swMathUtil.CreatePoint(vPt); swOrig = (MathPoint)swOrig.MultiplyTransform(swTrans); // Write parameters to readable ASCII file toFile.WriteLine(" " + swSubFeat.Name); toFile.WriteLine(" Type = " + swMate.Type); toFile.WriteLine(" Alignment = " + swMate.Alignment); toFile.WriteLine(" Can be flipped = " + swMate.CanBeFlipped); toFile.WriteLine(""); toFile.WriteLine(" Component = " + swComp.Name2); toFile.WriteLine(" Origin = (" + ((double[])swOrig.ArrayData)[0] * 1000.0 + ", " + ((double[])swOrig.ArrayData)[1] * 1000.0 + ", " + ((double[])swOrig.ArrayData)[2] * 1000.0 + ")"); toFile.WriteLine(" Mate enity type = " + swMateEnt[i].ReferenceType); entityParameters = (double[])swMateEnt[i].EntityParams; toFile.WriteLine(" (x,y,z) = (" + entityParameters[0] * 1000 + ", " + entityParameters[1] * 1000 + ", " + entityParameters[2] * 1000 + ")"); toFile.WriteLine(" (i,j,k) = (" + entityParameters[3] + ", " + entityParameters[4] + ", " + entityParameters[5] + ")"); toFile.WriteLine(" Radius 1 = " + entityParameters[6] * 1000); toFile.WriteLine(" Radius 2 = " + entityParameters[7] * 1000); toFile.WriteLine(""); // Write parameters to a simplified ASCII file for computation toCalc.Write(swSubFeat.Name); toCalc.Write(" " + swMate.Type); toCalc.Write(" " + swMate.Alignment); toCalc.Write(" " + swMate.CanBeFlipped); toCalc.Write(" " + swComp.Name2); toCalc.Write(" " + ((double[])swOrig.ArrayData)[0] * 1000.0 + "," + ((double[])swOrig.ArrayData)[1] * 1000.0 + "," + ((double[])swOrig.ArrayData)[2] * 1000.0); toCalc.Write(" " + swMateEnt[i].ReferenceType); toCalc.Write(" " + entityParameters[0] * 1000.0 + "," + entityParameters[1] * 1000.0 + "," + entityParameters[2] * 1000.0); toCalc.Write(" " + entityParameters[3] + "," + entityParameters[4] + "," + entityParameters[5]); toCalc.Write(" " + entityParameters[6] * 1000.0); toCalc.WriteLine(" " + entityParameters[7] * 1000.0); } toFile.WriteLine(" "); } // Get the next mate in MateGroup swSubFeat = (Feature)swSubFeat.GetNextSubFeature(); } // Get bounding box around assembly swAssembly = (AssemblyDoc)swModel; corners = swAssembly.GetBox(1); height = (corners[4] - corners[1]) * 1000.0; width = (corners[3] - corners[0]) * 1000.0; depth = (corners[5] - corners[2]) * 1000.0; // Write to file toFile.WriteLine("Aprx. assembly dimensions"); toFile.WriteLine("(Height, Width, Depth) = (" + height + ", " + width + ", " + depth + ")"); toFile.WriteLine(" "); toCalc.WriteLine("dims(hwd) " + height + " " + width + " " + depth); // Get Possible Assembly Directions with interferenceDir function interference inter = new interference(); swAssyDir = inter.interferenceDir(swApp, swModel, swMateFeat, swMateEnt); // Write swAssyDir to file toFile.WriteLine("(x+, x-, y+, y-, z+, z-) = (" + swAssyDir[0] + ", " + swAssyDir[1] + ", " + swAssyDir[2] + ", " + swAssyDir[3] + ", " + swAssyDir[4] + ", " + swAssyDir[5] + ") "); toFile.WriteLine("1 is possible, 0 is not possible"); toFile.WriteLine(""); toFile.WriteLine("All dimensions are in mm"); toCalc.Write("dir " + swAssyDir[0] + " " + swAssyDir[1] + " " + swAssyDir[2] + " " + swAssyDir[3] + " " + swAssyDir[4] + " " + swAssyDir[5]); return(true); } catch (Exception) { return(false); } }
public void DumpTraverseComponent(Component2 swComp, long nLevel, ref string asciitext) { // *** SCAN THE COMPONENT FEATURES if (!swComp.IsRoot()) { Feature swFeat; swFeat = (Feature)swComp.FirstFeature(); DumpTraverseFeatures(swFeat, nLevel, ref asciitext); } // *** RECURSIVE SCAN CHILDREN COMPONENTS object[] vChildComp; Component2 swChildComp; string sPadStr = " "; long i = 0; for (i = 0; i <= nLevel - 1; i++) { sPadStr = sPadStr + " "; } vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; asciitext += sPadStr + "+" + swChildComp.Name2 + " <" + swChildComp.ReferencedConfiguration + ">" +"\n"; // DumpTraverseComponentFeatures(swChildComp, nLevel, ref asciitext); DumpTraverseComponent(swChildComp, nLevel + 1, ref asciitext); } }
public DecorComponentsWithCombo(int inNumber, ComboBox inCombo, Component2 inComponent) { Number = inNumber; Combo = inCombo; Component = inComponent; }
public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor) { // Fetch current properties from the selected part(s) (i.e. ChBody in C::E) for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) { if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc(); // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPart, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid)) { System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed)) { System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous)) { System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!"); } if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted)) { System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!"); } swPartModel.ForceRebuild3(false); // needed? } Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter( "collision_on")).GetDoubleValue())); Set_friction(((Parameter)myattr.GetParameter( "friction")).GetDoubleValue()); Set_rolling_friction(((Parameter)myattr.GetParameter( "rolling_friction")).GetDoubleValue()); Set_spinning_friction(((Parameter)myattr.GetParameter( "spinning_friction")).GetDoubleValue()); Set_restitution(((Parameter)myattr.GetParameter( "restitution")).GetDoubleValue()); Set_collision_envelope(((Parameter)myattr.GetParameter( "collision_envelope")).GetDoubleValue()); Set_collision_margin(((Parameter)myattr.GetParameter( "collision_margin")).GetDoubleValue()); Set_collision_family((int)((Parameter)myattr.GetParameter( "collision_family")).GetDoubleValue()); // fetch SW attribute with Chrono parameters for ChConveyor /* * SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); * if (myattr_conv == null) * { * // if not already added to part, create and attach it * //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); * } */ /* * // fetch SW attribute with Chrono parameters for ChConveyor (if any!) * SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); * if (myattr_conveyor != null) * { * show_conveyor_params = true; * * Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter( * "conveyor_speed")).GetDoubleValue()); * } */ } } }
internal DimensionConfForList(int number, string labelName, string strObjName, int objVal, List<int> idSlave, Component2 component, bool isGrey, int id) { Number = number; LabelName = labelName; StrObjName = strObjName; ObjVal = objVal; IdSlave = idSlave; Component = component; IsGrey = isGrey; Id = id; }
/// <summary> /// 遍历装配体零件 /// </summary> /// <param name="swComp"></param> /// <param name="nLevel"></param> public static void TraverseCompXform(Component2 swComp, long nLevel, bool setcolor = false) { object[] vChild; Component2 swChildComp; string sPadStr = ""; MathTransform swCompXform; // object vXform; long i; for (i = 0; i < nLevel; i++) { sPadStr = sPadStr + " "; } swCompXform = swComp.Transform2; if (swCompXform != null) { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); try { //子零件文件名 //Debug.Print(sPadStr + swComp.Name2); if (swComp.GetSelectByIDString() == "") { //选择id //Debug.Print(swComp.GetSelectByIDString()); } else { } } catch { } if (swModel != null) { Debug.Print("Loading:" + swComp.Name2); //获取零件的一些信息,如属性,名字路径。 string tempPartNum = swModel.get_CustomInfo2(swComp.ReferencedConfiguration, "PartNum"); string tempName2 = swComp.Name2; string tempName = swModel.GetPathName(); string tempConfigName = swComp.ReferencedConfiguration; string tempComponentRef = swComp.ComponentReference; //如果要设定颜色 if (setcolor == true) { double[] matPropVals = (double[])swModel.MaterialPropertyValues; var tempC = GetRadomColor(System.IO.Path.GetFileNameWithoutExtension(swModel.GetPathName())); matPropVals[0] = Convert.ToDouble(tempC.R) / 255; matPropVals[1] = Convert.ToDouble(tempC.G) / 255; matPropVals[2] = Convert.ToDouble(tempC.B) / 255; swModel.MaterialPropertyValues = matPropVals; swModel.WindowRedraw(); } } } else { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); } vChild = (object[])swComp.GetChildren(); for (i = 0; i <= (vChild.Length - 1); i++) { swChildComp = (Component2)vChild[i]; TraverseCompXform(swChildComp, nLevel + 1, setcolor); } }
public SetDecors(Component2 inComponent, string inColorProperty, string inPartColorProperty) { Component = inComponent; ColorProperty = inColorProperty; PartColorProperty = inPartColorProperty; }
/// Convert a SolidWorks component to Wavefront OBJ mesh /// public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress) { StringBuilder textbuilder = new StringBuilder(); Body2 swBody = default(Body2); object[] vBodies = null; object[] vBodiesSolid = null; object[] vBodiesSheet = null; object vBodyInfo; int[] BodiesInfo = null; int j = 0; ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc(); vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo); BodiesInfo = (int[])vBodyInfo; if (vBodiesSolid != null && vBodiesSheet == null) { vBodies = vBodiesSolid; } if (vBodiesSolid == null && vBodiesSheet != null) { vBodies = vBodiesSheet; } if (vBodiesSolid != null && vBodiesSheet != null) { vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray(); } // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); if (vBodies != null) { int iNumBodies = vBodies.Length; int iNumSolidBodies = 0; int iNumSheetBodies = 0; int iNumTesselatedBodies = 0; if (iNumBodies > 0) { asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n"; } int group_vstride = 0; int group_nstride = 0; // Loop through bodies for (j = 0; j <= vBodies.Length - 1; j++) { swBody = (Body2)vBodies[j]; int nBodyType = (int)swBody.GetType(); if (nBodyType == (int)swBodyType_e.swSheetBody) { iNumSheetBodies++; } if (nBodyType == (int)swBodyType_e.swSolidBody) { iNumSolidBodies++; } if ((nBodyType == (int)swBodyType_e.swSheetBody || nBodyType == (int)swBodyType_e.swSolidBody) && !swBody.Name.StartsWith("COLL.") && swBody.Visible) { iNumTesselatedBodies++; CultureInfo bz = new CultureInfo("en-BZ"); //asciitext += "g body_" + iNumTesselatedBodies + "\n"; textbuilder.Append("g body_" + iNumTesselatedBodies + "\n"); Face2 swFace = null; Tessellation swTessellation = null; bool bResult = false; // Pass in null so the whole body will be tessellated swTessellation = (Tessellation)swBody.GetTessellation(null); // Set up the Tessellation object swTessellation.NeedFaceFacetMap = true; swTessellation.NeedVertexParams = true; swTessellation.NeedVertexNormal = true; swTessellation.ImprovedQuality = true; // How to handle matches across common edges swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology; // Do it if (swProgress != null) { swProgress.UpdateTitle("Exporting (tesselate process) ..."); } bResult = swTessellation.Tessellate(); // Get the number of vertices and facets //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount()); //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount()); //Debug.Print("Number of facets: " + swTessellation.GetFacetCount()); // Now get the facet data per face int[] aFacetIds; int iNumFacetIds; int[] aFinIds; int[] aVertexIds; double[] aNormal; double[] aVertexCoords1; double[] aVertexCoords2; double[] aVertexParams; int numv = swTessellation.GetVertexCount(); // Write all vertexes string mline; for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ..."); } aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv); mline = "v " + (aVertexCoords1[0] * ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[1] * ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[2] * ChScale.L).ToString("f6", bz) + "\n"; textbuilder.Append(mline); } // Write all normals for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); } aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + aNormal[0].ToString("f3", bz) + " " + aNormal[1].ToString("f3", bz) + " " + aNormal[2].ToString("f3", bz) + "\n"; textbuilder.Append(mline); } if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles { for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); } aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + (-aNormal[0]).ToString("f3", bz) + " " + (-aNormal[1]).ToString("f3", bz) + " " + (-aNormal[2]).ToString("f3", bz) + "\n"; textbuilder.Append(mline); } } // Write all UV (also with '0' as third value, for compatibility with some OBJ reader) if (saveUV) { for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ..."); } aVertexParams = (double[])swTessellation.GetVertexParams(iv); mline = "vt " + aVertexParams[0].ToString("f4", bz) + " " + aVertexParams[1].ToString("f4", bz) + " " + "0" + "\n"; textbuilder.Append(mline); } } // Loop over faces swFace = (Face2)swBody.GetFirstFace(); while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) { swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); } mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); // There should always be three fins per facet for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); // Three fins per face, two vertexes each fin, // only the 1st vertex of two is needed (because of sharing) if (saveUV) { mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_nstride + 1); } else { mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + group_nstride + 1); } } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } swFace = (Face2)swBody.GetFirstFace(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles { while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) { swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); } mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); if (saveUV) { mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } else { mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } } group_vstride += swTessellation.GetVertexCount(); group_nstride += swTessellation.GetVertexCount(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets: two-sided triangles { group_nstride += swTessellation.GetVertexCount(); } } } // end loop on bodies } // not null body asciitext += textbuilder.ToString(); }
/// Convert a SolidWorks component to Wavefront OBJ mesh /// public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress) { StringBuilder textbuilder = new StringBuilder(); Body2 swBody = default(Body2); object[] vBodies = null; object[] vBodiesSolid = null; object[] vBodiesSheet = null; object vBodyInfo; int[] BodiesInfo = null; int j = 0; ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc(); vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo); BodiesInfo = (int[])vBodyInfo; if (vBodiesSolid != null && vBodiesSheet == null) vBodies = vBodiesSolid; if (vBodiesSolid == null && vBodiesSheet != null) vBodies = vBodiesSheet; if (vBodiesSolid != null && vBodiesSheet != null) vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray(); // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); if (vBodies != null) { int iNumBodies = vBodies.Length; int iNumSolidBodies = 0; int iNumSheetBodies = 0; int iNumTesselatedBodies = 0; if (iNumBodies >0) asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n"; int group_vstride = 0; int group_nstride = 0; // Loop through bodies for (j = 0; j <= vBodies.Length - 1; j++) { swBody = (Body2)vBodies[j]; int nBodyType = (int)swBody.GetType(); if (nBodyType == (int)swBodyType_e.swSheetBody) iNumSheetBodies++; if (nBodyType == (int)swBodyType_e.swSolidBody) iNumSolidBodies++; if ((nBodyType == (int)swBodyType_e.swSheetBody || nBodyType == (int)swBodyType_e.swSolidBody) && !swBody.Name.StartsWith("COLL.") && swBody.Visible) { iNumTesselatedBodies++; CultureInfo bz = new CultureInfo("en-BZ"); //asciitext += "g body_" + iNumTesselatedBodies + "\n"; textbuilder.Append("g body_" + iNumTesselatedBodies + "\n"); Face2 swFace = null; Tessellation swTessellation = null; bool bResult = false; // Pass in null so the whole body will be tessellated swTessellation = (Tessellation)swBody.GetTessellation(null); // Set up the Tessellation object swTessellation.NeedFaceFacetMap = true; swTessellation.NeedVertexParams = true; swTessellation.NeedVertexNormal = true; swTessellation.ImprovedQuality = true; // How to handle matches across common edges swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology; // Do it if (swProgress != null) swProgress.UpdateTitle("Exporting (tesselate process) ..."); bResult = swTessellation.Tessellate(); // Get the number of vertices and facets //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount()); //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount()); //Debug.Print("Number of facets: " + swTessellation.GetFacetCount()); // Now get the facet data per face int[] aFacetIds; int iNumFacetIds; int[] aFinIds; int[] aVertexIds; double[] aNormal; double[] aVertexCoords1; double[] aVertexCoords2; double[] aVertexParams; int numv = swTessellation.GetVertexCount(); // Write all vertexes string mline; for (int iv = 0; iv < numv; iv++) { if ((swProgress != null)&&(iv%200==0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ..."); aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv); mline = "v " + (aVertexCoords1[0]*ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[1]*ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[2]*ChScale.L).ToString("f6", bz) + "\n"; textbuilder.Append(mline); } // Write all normals for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + aNormal[0].ToString("f3", bz) + " " + aNormal[1].ToString("f3", bz) + " " + aNormal[2].ToString("f3", bz) + "\n"; textbuilder.Append(mline); } if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + (-aNormal[0]).ToString("f3", bz) + " " + (-aNormal[1]).ToString("f3", bz) + " " + (-aNormal[2]).ToString("f3", bz) + "\n"; textbuilder.Append(mline); } // Write all UV (also with '0' as third value, for compatibility with some OBJ reader) if (saveUV) for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ..."); aVertexParams = (double[])swTessellation.GetVertexParams(iv); mline = "vt " + aVertexParams[0].ToString("f4", bz) + " " + aVertexParams[1].ToString("f4", bz) + " " + "0" + "\n"; textbuilder.Append(mline); } // Loop over faces swFace = (Face2)swBody.GetFirstFace(); while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); // There should always be three fins per facet for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); // Three fins per face, two vertexes each fin, // only the 1st vertex of two is needed (because of sharing) if (saveUV) mline += " " + (aVertexIds[0] + group_vstride +1) + "/" + (aVertexIds[0] + group_vstride +1) + "/" + (aVertexIds[0] + group_nstride +1); else mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + group_nstride + 1); } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } swFace = (Face2)swBody.GetFirstFace(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); if (saveUV) mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); else mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } group_vstride += swTessellation.GetVertexCount(); group_nstride += swTessellation.GetVertexCount(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets: two-sided triangles group_nstride += swTessellation.GetVertexCount(); } } // end loop on bodies } // not null body asciitext += textbuilder.ToString(); }
private Component2 CheckAllMates(ModelDoc2 model, Component2 originalComp, string[] linkedModels, double[] sBox, string axe, out bool isLeft) { int axeInt = 0; switch (axe.ToLower()) { case "x": axeInt = 3; break; case "y": axeInt = 4; break; case "z": axeInt = 5; break; } if (axeInt == 0) throw new Exception("Не удалось растянуть деталь. В mdb ref_objects_axe не правильно указана ось (axe)."); isLeft = false; //model.ClosestDistance(origPlane, nearestPlane, out point1, out point2); var swFeat = (Feature)model.FirstFeature(); while (swFeat != null) { if (swFeat.GetTypeName2() == "MateGroup") { var mate = swFeat.GetFirstSubFeature(); while (mate != null) { if (mate.GetTypeName() == "MateCoincident") { Mate2 spec = mate.GetSpecificFeature2(); if (spec.GetMateEntityCount() > 1) { var paramsArray = spec.MateEntity(0).EntityParams as double[]; double tst = 0; if (paramsArray != null && paramsArray.Length > axeInt) tst = paramsArray[axeInt]; if (spec.MateEntity(0).ReferenceComponent.Name.Contains(originalComp.Name) && (tst == 1 || tst == -1)) { foreach (string modelName in linkedModels) { if (spec.MateEntity(1).ReferenceComponent.Name.Contains(modelName)) { double avarageZ = (sBox[axeInt - 3] + sBox[axeInt]) / 2; double[] mateBox = spec.MateEntity(1).ReferenceComponent.GetBox(false, false); double mateAvarageZ = (mateBox[axeInt - 3] + mateBox[axeInt]) / 2; if (avarageZ > mateAvarageZ) isLeft = false; else isLeft = true; return spec.MateEntity(1).ReferenceComponent; } } } paramsArray = spec.MateEntity(1).EntityParams as double[]; tst = 0; if (paramsArray != null && paramsArray.Length > axeInt) tst = paramsArray[axeInt]; if (spec.MateEntity(1).ReferenceComponent.Name.Contains(originalComp.Name) && (tst == 1 || tst == -1)) { foreach (string modelName in linkedModels) { if (spec.MateEntity(0).ReferenceComponent.Name.Contains(modelName)) { double avarageZ = (sBox[axeInt - 3] + sBox[axeInt]) / 2; double[] mateBox = spec.MateEntity(0).ReferenceComponent.GetBox(false, false); double mateAvarageZ = (mateBox[axeInt - 3] + mateBox[axeInt]) / 2; if (avarageZ > mateAvarageZ) isLeft = false; else isLeft = true; return spec.MateEntity(0).ReferenceComponent; } } } } } mate = mate.GetNextSubFeature(); } } swFeat = (Feature)swFeat.GetNextFeature(); } return null; }
public static bool ConvertMateToPython( ref Feature swMateFeature, ref string asciitext, ref ISldWorks mSWApplication, ref Hashtable saved_parts, ref int num_link, ref MathTransform roottrasf, ref Component2 assemblyofmates ) { if (swMateFeature == null) return false; Mate2 swMate = (Mate2)swMateFeature.GetSpecificFeature2(); if (swMate == null) return false; object foo =null; bool[] suppressedflags; suppressedflags = (bool[])swMateFeature.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, foo); if (suppressedflags[0] == true) return false; if (swMate.GetMateEntityCount() >= 2) { // Get the mated parts MateEntity2 swEntityA = swMate.MateEntity(0); MateEntity2 swEntityB = swMate.MateEntity(1); Component2 swCompA = swEntityA.ReferenceComponent; Component2 swCompB = swEntityB.ReferenceComponent; double[] paramsA = (double[])swEntityA.EntityParams; double[] paramsB = (double[])swEntityB.EntityParams; // this is needed because parts might reside in subassemblies, and mate params are expressed in parent subassembly MathTransform invroottrasf = (MathTransform)roottrasf.Inverse(); MathTransform trA = roottrasf; MathTransform trB = roottrasf; if (assemblyofmates != null) { MathTransform partrasfA = assemblyofmates.GetTotalTransform(true); if (partrasfA != null) trA = partrasfA.IMultiply(invroottrasf); // row-ordered transf. -> reverse mult.order! MathTransform partrasfB = assemblyofmates.GetTotalTransform(true); if (partrasfB != null) trB = partrasfB.IMultiply(invroottrasf); // row-ordered transf. -> reverse mult.order! } // Fetch the python names using hash map (python names added when scanning parts) ModelDocExtension swModelDocExt = default(ModelDocExtension); ModelDoc2 swModel = (ModelDoc2)mSWApplication.ActiveDoc; swModelDocExt = swModel.Extension; String name1 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompA)]; String name2 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompB)]; // Only constraints between two parts or part & layout can be created if ( ((name1 != null) || (name2 != null)) && (name1 != name2) ) { CultureInfo bz = new CultureInfo("en-BZ"); if (name1 == null) name1 = "body_0"; if (name2 == null) name2 = "body_0"; // Add some comment in Python, to list the referenced SW items asciitext += "\n# Mate constraint: " + swMateFeature.Name + " [" + swMateFeature.GetTypeName2() + "]" + " type:" + swMate.Type + " align:" + swMate.Alignment + " flip:" + swMate.Flipped + "\n"; for (int e = 0; e < swMate.GetMateEntityCount(); e++) { MateEntity2 swEntityN = swMate.MateEntity(e); Component2 swCompN = swEntityN.ReferenceComponent; String ce_nameN = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompN)]; asciitext += "# Entity " + e + ": C::E name: " + ce_nameN + " , SW name: " + swCompN.Name2 + " , SW ref.type:" + swEntityN.Reference.GetType() + " (" + swEntityN.ReferenceType2 + ")\n"; } asciitext += "\n"; // // For each type of SW mate, see which C::E mate constraint(s) // must be created. Some SW mates correspond to more than one C::E constraints. // bool swapAB_1 = false; bool do_CHmate_Xdistance = false; double do_distance_val = 0.0; bool do_CHmate_parallel = false; bool do_parallel_flip = false; bool do_CHmate_orthogonal = false; bool do_CHmate_spherical = false; bool do_CHmate_pointline = false; // to simplify things later... // NOTE: swMate.MateEntity(0).Reference.GetType() seems equivalent to swMate.MateEntity(0).ReferenceType2 // but in some cases the latter fails. bool entity_0_as_FACE = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelFACES); bool entity_0_as_EDGE = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelEDGES) || (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelSKETCHSEGS) || (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelDATUMAXES); bool entity_0_as_VERTEX = (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || (swMate.MateEntity(0).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); bool entity_1_as_FACE = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelFACES); bool entity_1_as_EDGE = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelEDGES) || (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelSKETCHSEGS) || (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelDATUMAXES); bool entity_1_as_VERTEX = (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || (swMate.MateEntity(1).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); Point3D cA = new Point3D(0, 0, 0); Point3D cB = new Point3D(0, 0, 0); Vector3D dA = new Vector3D(1, 0, 0); Vector3D dB = new Vector3D(1, 0, 0); Point3D cAloc = new Point3D(paramsA[0], paramsA[1], paramsA[2]); cA = SWTaskpaneHost.PointTransform(cAloc, ref trA); Point3D cBloc = new Point3D(paramsB[0], paramsB[1], paramsB[2]); cB = SWTaskpaneHost.PointTransform(cBloc, ref trB); if (!entity_0_as_VERTEX) { Vector3D dAloc = new Vector3D(paramsA[3], paramsA[4], paramsA[5]); dA = SWTaskpaneHost.DirTransform(dAloc, ref trA); } if (!entity_1_as_VERTEX) { Vector3D dBloc = new Vector3D(paramsB[3], paramsB[4], paramsB[5]); dB = SWTaskpaneHost.DirTransform(dBloc, ref trB); } if (swMateFeature.GetTypeName2() == "MateCoincident") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_VERTEX)) { do_CHmate_spherical = true; } if ((entity_0_as_VERTEX) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; } if ((entity_0_as_EDGE) && (entity_1_as_VERTEX)) { do_CHmate_pointline = true; swapAB_1 = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_Xdistance = true; swapAB_1 = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_orthogonal = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_Xdistance = true; do_CHmate_orthogonal = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) do_parallel_flip = true; } if (swMateFeature.GetTypeName2() == "MateConcentric") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_pointline = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_pointline = true; swapAB_1 = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_pointline = true; do_CHmate_parallel = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) do_parallel_flip = true; } if (swMateFeature.GetTypeName2() == "MateParallel") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_parallel = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_orthogonal = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) do_parallel_flip = true; } if (swMateFeature.GetTypeName2() == "MatePerpendicular") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_EDGE) && (entity_1_as_EDGE)) { do_CHmate_orthogonal = true; } if ((entity_0_as_EDGE) && (entity_1_as_FACE)) { do_CHmate_parallel = true; } if ((entity_0_as_FACE) && (entity_1_as_EDGE)) { do_CHmate_parallel = true; swapAB_1 = true; } if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) do_parallel_flip = true; } if (swMateFeature.GetTypeName2() == "MateDistanceDim") { if ((entity_0_as_FACE) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; do_CHmate_parallel = true; } if ((entity_0_as_VERTEX) && (entity_1_as_FACE)) { do_CHmate_Xdistance = true; } if ((entity_0_as_FACE) && (entity_1_as_VERTEX)) { do_CHmate_Xdistance = true; swapAB_1 = true; } //***TO DO*** cases of distance line-vs-line and line-vs-vertex and vert-vert. // Those will require another .cpp ChLinkMate specialized class(es). if (swMate.Alignment == (int)swMateAlign_e.swMateAlignANTI_ALIGNED) do_parallel_flip = true; // Get the imposed distance value, in SI units string confnames = ""; do_distance_val = swMate.DisplayDimension.GetDimension2(0).IGetSystemValue3((int)swInConfigurationOpts_e.swThisConfiguration, 0, ref confnames); if (swMate.Flipped) do_distance_val = -do_distance_val; } //// //// WRITE PYHTON CODE CORRESPONDING TO CONSTRAINTS //// if (do_CHmate_Xdistance) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateXdistance()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); if (!entity_0_as_VERTEX) asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); if (!entity_1_as_VERTEX) asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dB)\n", linkname, name1, name2); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dA)\n", linkname, name2, name1); //if (do_distance_val!=0) asciitext += String.Format(bz, "{0}.SetDistance({1})\n", linkname, do_distance_val * ChScale.L *-1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } if (do_CHmate_parallel) { if (Math.Abs(Vector3D.DotProduct(dA, dB)) > 0.98) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateParallel()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); if (do_parallel_flip) asciitext += String.Format(bz, "{0}.SetFlipped(True)\n", linkname); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } else { asciitext += "\n# ChLinkMateParallel skipped because directions not parallel! \n"; } } if (do_CHmate_orthogonal) { if (Math.Abs(Vector3D.DotProduct(dA, dB)) < 0.02) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateOrthogonal()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } else { asciitext += "\n# ChLinkMateOrthogonal skipped because directions not orthogonal! \n"; } } if (do_CHmate_spherical) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateSpherical()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB)\n", linkname, name1, name2); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA)\n", linkname, name2, name1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } if (do_CHmate_pointline) { num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateGeneric()\n", linkname); asciitext += String.Format(bz, "{0}.SetConstrainedCoords(False, True, True, False, False, False)\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); if (!entity_0_as_VERTEX) asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); else asciitext += String.Format(bz, "dA = chrono.VNULL\n"); if (!entity_1_as_VERTEX) asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); else asciitext += String.Format(bz, "dB = chrono.VNULL\n"); // Initialize link, by setting the two csys, in absolute space, if (!swapAB_1) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cB,cA,dB,dA)\n", linkname, name2, name1); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n\n", linkname); } // Now, do some other special mate type that did not fall in combinations // of do_CHmate_pointline, do_CHmate_spherical, etc etc if (swMateFeature.GetTypeName2() == "MateHinge") { // auto flip direction if anti aligned (seems that this is assumed automatically in MateHinge in SW) if (Vector3D.DotProduct(dA, dB) < 0) dB.Negate(); // Hinge constraint must be splitted in two C::E constraints: a coaxial and a point-vs-plane num_link++; String linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateCoaxial()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cA.X * ChScale.L, cA.Y * ChScale.L, cA.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dA.X, dA.Y, dA.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cB.X * ChScale.L, cB.Y * ChScale.L, cB.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dB.X, dB.Y, dB.Z); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Initialize link, by setting the two csys, in absolute space, asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA,dB)\n", linkname, name1, name2); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n", linkname); // NOTE!!! The 'hinge' mate uses 4 references: fetch the two others remaining // and build another C::E link, for point-vs-face mating MateEntity2 swEntityC = swMate.MateEntity(2); MateEntity2 swEntityD = swMate.MateEntity(3); Component2 swCompC = swEntityC.ReferenceComponent; Component2 swCompD = swEntityD.ReferenceComponent; double[] paramsC = (double[])swEntityC.EntityParams; double[] paramsD = (double[])swEntityD.EntityParams; String name3 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompC)]; String name4 = (String)saved_parts[swModelDocExt.GetPersistReference3(swCompD)]; MathTransform trC = roottrasf; MathTransform trD = roottrasf; if (assemblyofmates != null) { MathTransform partrasfC = assemblyofmates.GetTotalTransform(true); if (partrasfC != null) trC = partrasfC.IMultiply(invroottrasf); MathTransform partrasfD = assemblyofmates.GetTotalTransform(true); if (partrasfD != null) trD = partrasfD.IMultiply(invroottrasf); } bool entity_2_as_VERTEX = (swMate.MateEntity(2).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || (swMate.MateEntity(2).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || (swMate.MateEntity(2).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); bool entity_3_as_VERTEX = (swMate.MateEntity(3).Reference.GetType() == (int)swSelectType_e.swSelVERTICES) || (swMate.MateEntity(3).Reference.GetType() == (int)swSelectType_e.swSelSKETCHPOINTS) || (swMate.MateEntity(3).Reference.GetType() == (int)swSelectType_e.swSelDATUMPOINTS); Point3D cC = new Point3D(0, 0, 0); Point3D cD = new Point3D(0, 0, 0); Vector3D dC = new Vector3D(1, 0, 0); Vector3D dD = new Vector3D(1, 0, 0); Point3D cCloc = new Point3D(paramsC[0], paramsC[1], paramsC[2]); cC = SWTaskpaneHost.PointTransform(cCloc, ref trC); Point3D cDloc = new Point3D(paramsD[0], paramsD[1], paramsD[2]); cD = SWTaskpaneHost.PointTransform(cDloc, ref trD); if (!entity_2_as_VERTEX) { Vector3D dCloc = new Vector3D(paramsC[3], paramsC[4], paramsC[5]); dC = SWTaskpaneHost.DirTransform(dCloc, ref trC); } if (!entity_3_as_VERTEX) { Vector3D dDloc = new Vector3D(paramsD[3], paramsD[4], paramsD[5]); dD = SWTaskpaneHost.DirTransform(dDloc, ref trD); } num_link++; linkname = "link_" + num_link; asciitext += String.Format(bz, "{0} = chrono.ChLinkMateXdistance()\n", linkname); asciitext += String.Format(bz, "cA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cC.X * ChScale.L, cC.Y * ChScale.L, cC.Z * ChScale.L); asciitext += String.Format(bz, "dA = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dC.X, dC.Y, dC.Z); asciitext += String.Format(bz, "cB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", cD.X * ChScale.L, cD.Y * ChScale.L, cD.Z * ChScale.L); asciitext += String.Format(bz, "dB = chrono.ChVectorD({0:g},{1:g},{2:g})\n", dD.X, dD.Y, dD.Z); asciitext += String.Format(bz, "{0}.SetName(\"{1}\")\n", linkname, swMateFeature.Name); // Initialize link, by setting the two csys, in absolute space, if (entity_2_as_VERTEX) asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dA)\n", linkname, name3, name4); else asciitext += String.Format(bz, "{0}.Initialize({1},{2},False,cA,cB,dB)\n", linkname, name3, name4); // Insert to a list of exported items asciitext += String.Format(bz, "exported_items.append({0})\n", linkname); return true; } } } return false; }
private void button1_Click_1(object sender, EventArgs e) { button1.Enabled = false; button1.Text = "Proceeding..."; // preventing empty fields if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text) || string.IsNullOrWhiteSpace(textBox3.Text) || string.IsNullOrWhiteSpace(textBox4.Text) || string.IsNullOrWhiteSpace(textBox5.Text) || string.IsNullOrWhiteSpace(textBox6.Text) || string.IsNullOrWhiteSpace(textBox7.Text) || string.IsNullOrWhiteSpace(textBox8.Text)) { MessageBox.Show("Enter all values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int time = Convert.ToInt32(textBox1.Text); int step = Convert.ToInt32(textBox2.Text); int initt1 = Convert.ToInt32(textBox3.Text); int initt2 = Convert.ToInt32(textBox4.Text); int initt3 = Convert.ToInt32(textBox7.Text); int conv = Convert.ToInt32(textBox5.Text); double bulk = Convert.ToDouble(textBox8.Text) + 273.15; // converting to Kelvin units int heatpow = Convert.ToInt32(textBox6.Text); DisposeSW(); // Opening SW 2017 // Additional GUID: F16137AD-8EE8-4D2A-8CAC-DFF5D1F67522 Guid Guid1 = new Guid("6B36082E-677B-49E8-BCB2-76698EBD2906"); object processSW = System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid1)); swApp = (SldWorks)processSW; swApp.Visible = true; CosmosWorks COSMOSWORKS = default(CosmosWorks); CwAddincallback CWObject = default(CwAddincallback); CWModelDoc ActDoc = default(CWModelDoc); CWStudyManager StudyMngr = default(CWStudyManager); CWStudy Study = default(CWStudy); CWThermalStudyOptions ThermalOptions = default(CWThermalStudyOptions); CWConvection CWConv = default(CWConvection); CWMesh CwMesh = default(CWMesh); CWResults CWResult = default(CWResults); CWTemperature CWTemp = default(CWTemperature); ModelDoc2 Part = default(ModelDoc2); CWLoadsAndRestraintsManager LBCMgr = default(CWLoadsAndRestraintsManager); CWHeatPower CWHeatPower = default(CWHeatPower); ModelDoc2 swDoc = null; int bApp = 0; int longstatus = 0; int longwarnings = 0; int errCode = 0; double el = 0; double tl = 0; string cwpath = ""; Part = swApp.OpenDoc6("G:\\assem(simple).SLDASM", (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref longstatus, ref longwarnings); if (Part == null) { MessageBox.Show("Failed to open document"); } swDoc = swApp.IActiveDoc2; // connecting Simulation to SW cwpath = swApp.GetExecutablePath() + @"\Simulation\cosworks.dll"; errCode = swApp.LoadAddIn(cwpath); if (errCode != 0 && errCode != 2) { MessageBox.Show("Failed to load Simulation library"); swApp.ExitApp(); DisposeSW(); Application.Exit(); } // ready-check Simulation add-on CWObject = (CwAddincallback)swApp.GetAddInObject("CosmosWorks.CosmosWorks"); if (CWObject == null) { MessageBox.Show("Failed to start Simulation"); } // ready-check add-on object COSMOSWORKS = CWObject.CosmosWorks; if (COSMOSWORKS == null) { MessageBox.Show("Failed to create CosmosWorks object"); } // connecting add-on to document ActDoc = COSMOSWORKS.ActiveDoc; if (ActDoc == null) { MessageBox.Show("Failed to open document"); } // creating thermal analysis bApp = ActDoc.AddDefaultThermalStudyPlot((int)swsThermalResultComponentTypes_e.swsThermalResultComponentTypes_TEMP, true); StudyMngr = ActDoc.StudyManager; if (StudyMngr == null) { MessageBox.Show("Failed to start analysis manager"); } Study = StudyMngr.CreateNewStudy3("CPU Usage", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeThermal, (int)swsMeshType_e.swsMeshTypeSolid, out errCode); if (Study == null) { MessageBox.Show("Failed to create thermal analysis"); } ThermalOptions = Study.ThermalStudyOptions; Study.ThermalStudyOptions.SolutionType = 0; if (ThermalOptions == null) { MessageBox.Show("No analysis parameters"); } // analysis duration ThermalOptions.CheckFlowConvectionCoef = 0; ThermalOptions.SolverType = 2; ThermalOptions.TotalTime = time; ThermalOptions.TimeIncrement = step; LBCMgr = Study.LoadsAndRestraintsManager; if (LBCMgr == null) { MessageBox.Show("Failed to load loads and restraints manager"); } // lit coordinates swDoc.ShowNamedView2("*Top", 5); swDoc.ViewZoomtofit2(); ISelectionMgr selectionMgr = (ISelectionMgr)swDoc.SelectionManager; bool isSelected = swDoc.Extension.SelectByRay(-0.28387922510520769, 0.081999999999993634, -0.14613487203691797, 0, -1, 0, 0.0047546274155552031, 2, false, 0, 0); if (isSelected) { Entity swEntity = selectionMgr.GetSelectedObject6(1, -1); Component2 swComp = (Component2)swEntity.GetComponent(); object[] fixedpart = { swComp }; CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode); if (errCode != 0) { MessageBox.Show("Failed to add temperature indicator"); } } CWTemp.TemperatureBeginEdit(); CWTemp.TemperatureType = 0; CWTemp.Unit = 2; CWTemp.TemperatureValue = initt2; errCode = CWTemp.TemperatureEndEdit(); if (errCode != 0) { MessageBox.Show("Failed to edit temperature indicator"); } swDoc.ClearSelection2(true); // silicon board coordinates isSelected = swDoc.Extension.SelectByRay(-0.41952594843134139, 0.02199999999999136, -0.41742831868918501, 0, -1, 0, 0.0047546274155552031, 2, false, 0, 0); if (isSelected) { Entity swEntity = selectionMgr.GetSelectedObject6(1, -1); Component2 swComp = (Component2)swEntity.GetComponent(); object[] fixedpart = { swComp }; CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode); if (errCode != 0) { MessageBox.Show("Failed to add temperature indicator"); } } CWTemp.TemperatureBeginEdit(); CWTemp.TemperatureType = 0; CWTemp.Unit = 2; CWTemp.TemperatureValue = initt1; errCode = CWTemp.TemperatureEndEdit(); if (errCode != 0) { MessageBox.Show("Failed to edit temperature indicator"); } swDoc.ClearSelection2(true); // stalks coordinates swDoc.ShowNamedView2("*Bottom", 6); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(-0.42931488722807265, -0.050999999999987722, 0.28597685484736474, 0, 1, 0, 0.0047546274155552031, 2, false, 0, 0); if (isSelected) { Entity swEntity = selectionMgr.GetSelectedObject6(1, -1); Component2 swComp = (Component2)swEntity.GetComponent(); object[] fixedpart = { swComp }; CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode); if (errCode != 0) { MessageBox.Show("Failed to edit temperature indicator"); } } CWTemp.TemperatureBeginEdit(); CWTemp.TemperatureType = 0; CWTemp.Unit = 2; CWTemp.TemperatureValue = initt3; errCode = CWTemp.TemperatureEndEdit(); if (errCode != 0) { MessageBox.Show("Failed to edit temperature indicator"); } swDoc.ClearSelection2(true); // all faces coordinates swDoc.ShowNamedView2("*Front", 1); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(-0.38382731822234351, 0.04982938298755997, 0.40017589628916994, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.18695037482381383, 0.049829382987560122, 0.42176499999999351, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.35735646868976789, 0.0713369482327776, 0.41521684512093771, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.10505618408240869, 0.010950322736590109, 0.4415000000000191, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.43015130490435044, -0.017174954891772284, 0.29464212540386825, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.42932409085645729, -0.016347740843879296, 0.29483222724246616, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0); swDoc.ShowNamedView2("*Back", 2); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(0.3581836827376611, 0.063064807753847776, -0.4148975912216315, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.14558967242916476, 0.053138239179132019, -0.42176499999999351, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.37969124798287845, 0.047347740843881027, -0.40327910794843547, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.033088561915719295, 0.012604750832376084, -0.4415000000000191, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.42766966276067148, -0.014693312748093316, -0.29499856062381014, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.42766966276067131, -0.022138239179130152, -0.29499856062381014, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0); swDoc.ShowNamedView2("*Left", 3); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(-0.42176499999999351, 0.046520526795988171, -0.081066976693512371, 1, 0, 0, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.4415000000000191, 0.0084686805929112003, -0.082721404789298347, 1, 0, 0, 0.0028125277628361371, 2, false, 0, 0); swDoc.ShowNamedView2("*Right", 4); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(0.42176499999999351, 0.052311025131239031, 0.1158099667050172, -1, 0, 0, 0.0028125277628361371, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.4415000000000191, 0.010123108688697121, 0.12490932123184006, -1, 0, 0, 0.0028125277628361371, 2, false, 0, 0); swDoc.ShowNamedView2("*Top", 5); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(-0.19376272580646192, 0.081999999999993634, -0.13541980560506936, 0, -1, 0, 0.0036397418107291194, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.41535877134202892, 0.02199999999999136, -0.42017607667975893, 0, -1, 0, 0.0036397418107291194, 2, false, 0, 0); swDoc.ShowNamedView2("*Bottom", 6); swDoc.ViewZoomtofit2(); isSelected = swDoc.Extension.SelectByRay(-0.20232682418464809, -0.00099999999997635314, 0.23818898614330264, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.42713440661203494, -0.050999999999987722, 0.28743255181787342, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.42713440661203483, -0.050999999999987722, 0.28529152722332685, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(0.4292754312065814, -0.050999999999987722, -0.28422101492605301, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0); isSelected = swDoc.Extension.SelectByRay(-0.42499338201748837, -0.050999999999987722, -0.28636203952059958, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0); if (isSelected) { object selectedFace1 = (object)selectionMgr.GetSelectedObject6(1, -1); object selectedFace2 = (object)selectionMgr.GetSelectedObject6(2, -1); object selectedFace3 = (object)selectionMgr.GetSelectedObject6(3, -1); object selectedFace4 = (object)selectionMgr.GetSelectedObject6(4, -1); object selectedFace5 = (object)selectionMgr.GetSelectedObject6(5, -1); object selectedFace6 = (object)selectionMgr.GetSelectedObject6(6, -1); object selectedFace7 = (object)selectionMgr.GetSelectedObject6(7, -1); object selectedFace8 = (object)selectionMgr.GetSelectedObject6(8, -1); object selectedFace9 = (object)selectionMgr.GetSelectedObject6(9, -1); object selectedFace10 = (object)selectionMgr.GetSelectedObject6(10, -1); object selectedFace11 = (object)selectionMgr.GetSelectedObject6(11, -1); object selectedFace12 = (object)selectionMgr.GetSelectedObject6(12, -1); object selectedFace13 = (object)selectionMgr.GetSelectedObject6(13, -1); object selectedFace14 = (object)selectionMgr.GetSelectedObject6(14, -1); object selectedFace15 = (object)selectionMgr.GetSelectedObject6(15, -1); object selectedFace16 = (object)selectionMgr.GetSelectedObject6(16, -1); object selectedFace17 = (object)selectionMgr.GetSelectedObject6(17, -1); object selectedFace18 = (object)selectionMgr.GetSelectedObject6(18, -1); object selectedFace19 = (object)selectionMgr.GetSelectedObject6(19, -1); object selectedFace20 = (object)selectionMgr.GetSelectedObject6(20, -1); object selectedFace21 = (object)selectionMgr.GetSelectedObject6(21, -1); object selectedFace22 = (object)selectionMgr.GetSelectedObject6(22, -1); object selectedFace23 = (object)selectionMgr.GetSelectedObject6(23, -1); object[] fixedpart = { selectedFace1, selectedFace2, selectedFace3, selectedFace4, selectedFace5, selectedFace6, selectedFace7, selectedFace8, selectedFace9, selectedFace10, selectedFace11, selectedFace12, selectedFace13, selectedFace14, selectedFace15, selectedFace16, selectedFace17, selectedFace18, selectedFace19, selectedFace20,selectedFace21, selectedFace22, selectedFace23 }; CWConv = LBCMgr.AddConvection(fixedpart, out errCode); if (errCode != 0) { MessageBox.Show("Failed to add convection coefficient indicator"); } } CWConv.ConvectionBeginEdit(); CWConv.Unit = 0; CWConv.ConvectionCoefficient = conv; CWConv.BulkAmbientTemperature = bulk; errCode = CWConv.ConvectionEndEdit(); if (errCode != 0) { MessageBox.Show("Failed to edit convection coefficient indicator"); } swDoc.ClearSelection2(true); // stalks coordinates isSelected = swDoc.Extension.SelectByRay(-0.42931488722807265, -0.050999999999987722, 0.28597685484736474, 0, 1, 0, 0.0047546274155552031, 2, false, 0, 0); if (isSelected) { Entity swEntity = selectionMgr.GetSelectedObject6(1, -1); Component2 swComp = (Component2)swEntity.GetComponent(); object[] fixedpart = { swComp }; CWHeatPower = LBCMgr.AddHeatPower(fixedpart, out errCode); if (errCode != 0) { MessageBox.Show("Failed to add thermal power indicator"); } } CWHeatPower.HeatPowerBeginEdit(); CWHeatPower.Unit = 0; CWHeatPower.HPValue = heatpow; CWHeatPower.ReverseDirection = 0; CWHeatPower.IncludeThermostat = 0; errCode = CWHeatPower.HeatPowerEndEdit(); if (errCode != 0) { MessageBox.Show("Failed to edit thermal power indicator"); } swDoc.ShowNamedView2("*Isometric", 7); swDoc.ViewZoomtofit2(); // creating mesh model CwMesh = Study.Mesh; if (CwMesh == null) { MessageBox.Show("No mesh model"); } CwMesh.Quality = 1; CwMesh.GetDefaultElementSizeAndTolerance(0, out el, out tl); errCode = Study.CreateMesh(0, el, tl); if (errCode != 0) { MessageBox.Show("Failed to create mesh model"); } // analysis start errCode = Study.RunAnalysis(); if (errCode != 0) { MessageBox.Show("Failed to start analysi: " + errCode); } CWResult = Study.Results; if (CWResult == null) { MessageBox.Show("No results"); } else { MessageBox.Show("Done", "Results"); button1.Enabled = true; button1.Text = "Thermal analysis"; } double[] max = new double[time / step]; double[] min = new double[time / step]; double[] avg = new double[4]; for (int i = 1; i <= time / step; i++) { CWPlot plot = CWResult.GetPlot("Thermal" + i.ToString(), out errCode); plot.SetComponentUnitAndValueByElem(0, 2, false); object[] results = null; results = (object[])plot.GetMinMaxResultValues(out errCode); max[i - 1] = Convert.ToDouble(results[3].ToString()); min[i - 1] = Convert.ToDouble(results[1].ToString()); if (i == 1) { avg[0] = Convert.ToDouble(results[1].ToString()); avg[1] = Convert.ToDouble(results[3].ToString()); } if (i == time / step) { avg[2] = Convert.ToDouble(results[1].ToString()); avg[3] = Convert.ToDouble(results[3].ToString()); } } double maxValue = max.Max(); double minValue = min.Min(); textBox9.Text = maxValue.ToString("#.##"); textBox10.Text = minValue.ToString("#.##"); double heatdens = Math.Abs(conv * (((initt2 + initt3) / 2) - (initt3 - (maxValue - minValue)))); textBox12.Text = heatdens.ToString("#.##"); double avg1 = (avg[0] + avg[1]) / 2; double avg2 = (avg[2] + avg[3]) / 2; double avgr = avg1 - avg2; textBox15.Text = avgr.ToString("#.##"); }
private bool GetAngel(int number, Component2 component2) { bool vertical = false; OleDbConnection oleDb; if (_mSwAddin.OpenModelDatabase(_swSelModel, out oleDb)) { OleDbCommand cm = component2.IGetModelDoc().GetConfigurationCount() > 1 ? new OleDbCommand( "SELECT * FROM decors_conf WHERE id = " + number + " AND Configuration = '" + component2.ReferencedConfiguration + "'", oleDb) : new OleDbCommand("SELECT * FROM decors_conf WHERE id = " + number, oleDb); var rd = cm.ExecuteReader(); if (rd.Read()) { vertical = (bool)rd["Texture direction"]; } rd.Close(); oleDb.Close(); } return vertical; }
public void DoFunc(int rowindex, int sampleindex) { #region 1.Solidworks应用程序对象--初识SldWorks对象 if (rowindex == 0) // { if (sampleindex == 1) //新建 { SldWorks swApp = API_Learn.Learn_Sldworks.NewSolidworksApp(); swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 } else if (sampleindex == 2) { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); if (swApp != null) { swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 } else { MessageBox.Show("无打开的Solidworks"); } } } #endregion #region 2.Solidworks应用程序对象--文档操作1 else if (rowindex == 1)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); if (sampleindex == 1)//新建 { API_Learn.Learn_Sldworks.NewDoc(swApp); } else if (sampleindex == 2)//打开 { API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugTopBox.SLDPRT", true); } else if (sampleindex == 3)//所有文档 { API_Learn.Learn_Sldworks.GetAllOpenedDoc(swApp); } } #endregion #region 3.Solidworks应用程序对象--文档操作2 else if (rowindex == 2)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); if (sampleindex == 1)//文档切换 { API_Learn.Learn_Sldworks.ActivateDoc(swApp); } else if (sampleindex == 2)//加载 { API_Learn.Learn_Sldworks.LoadThirdPartFile(swApp); } else if (sampleindex == 3)//关闭 { API_Learn.Learn_Sldworks.CloseDoc(swApp); } } #endregion #region 4.Solidworks应用程序对象--文档与系统设置 else if (rowindex == 3)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); if (sampleindex == 1)//系统设置 { API_Learn.Learn_Sldworks.SystamSet(swApp); } else if (sampleindex == 2)//文档设置 { } else if (sampleindex == 3)// { } } #endregion #region 5.Solidworks文档相关对象简介 else if (rowindex == 4)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); if (sampleindex == 1)//获取文档 { API_Learn.Learn_ModelDoc2.GetDocObject(swApp); } else if (sampleindex == 2)// { } else if (sampleindex == 3)// { } } #endregion #region 6.Solidworks草图绘制基础1 else if (rowindex == 5) // { if (sampleindex == 1) //草图绘制 { SldWorks swApp = API_Learn.Learn_Sldworks.NewSolidworksApp(); ModelDoc2 SketchDoc = swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 API_Learn.Learn_SketchManager.DrawSketch(SketchDoc); } else if (sampleindex == 2)// { } else if (sampleindex == 3)// { } } #endregion #region 7.Solidworks草图绘制基础2 else if (rowindex == 6) // { if (sampleindex == 1) //添加集合关系与尺寸 { SldWorks swApp = API_Learn.Learn_Sldworks.NewSolidworksApp(); ModelDoc2 SketchDoc = swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 try { swApp.SetUserPreferenceToggle(10, false);//不弹出尺寸标注对话框 API_Learn.Learn_SketchManager.AddConstraintAndDim(SketchDoc); } catch { } finally { swApp.SetUserPreferenceToggle(10, true);//恢复弹出尺寸标注对话框 } } else if (sampleindex == 2)// { } else if (sampleindex == 3)// { } } #endregion #region 8.Solidworks特征创建基础1 else if (rowindex == 7) // { if (sampleindex == 1) //拉伸特征 { SldWorks swApp = API_Learn.Learn_Sldworks.NewSolidworksApp(); ModelDoc2 FeatDoc = swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 try { swApp.SetUserPreferenceToggle(10, false);//不弹出尺寸标注对话框 API_Learn.Learn_SketchManager.AddConstraintAndDim(FeatDoc); FeatDoc.ClearSelection2(true); API_Learn.Learn_FeatureManager.CreateFeature1(FeatDoc); } catch { } finally { swApp.SetUserPreferenceToggle(10, true);//恢复弹出尺寸标注对话框 } } else if (sampleindex == 2)//基准 { SldWorks swApp = API_Learn.Learn_Sldworks.NewSolidworksApp(); ModelDoc2 FeatDoc = swApp.NewPart();//新建零件,验证获得Solidworks程序对象成功 try { API_Learn.Learn_FeatureManager.CreatePlane(FeatDoc); } catch { } finally { swApp.SetUserPreferenceToggle(10, true);//恢复弹出尺寸标注对话框 } } else if (sampleindex == 3)// { } } #endregion #region 9.Solidworks属性 else if (rowindex == 8)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "Solidworks属性学习.SLDPRT") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\9\Solidworks属性学习.SLDPRT", false); } if (Doc != null) { if (sampleindex == 1)//属性写入 { API_Learn.Learn_CustomPropertyManager.WriteCusp(Doc); } else if (sampleindex == 2)//属性读取 { API_Learn.Learn_CustomPropertyManager.ReadCusp(Doc); } } } #endregion #region 9.Solidworks配置 else if (rowindex == 9)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "ConfigPart.SLDPRT") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\10\ConfigPart.SLDPRT", false); } if (Doc != null) { if (sampleindex == 1)//创建配置 { API_Learn.Learn_Configuration.CreateConfig(Doc); } else if (sampleindex == 2)//读取配置 { API_Learn.Learn_Configuration.GetConfig(Doc); } else if (sampleindex == 3)//删除配置 { API_Learn.Learn_Configuration.DelConfig(Doc); } } } #endregion #region 10.获取选择对象 else if (rowindex == 10)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "SelectionMgr.SLDPRT") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\11\SelectionMgr.SLDPRT", false); } if (Doc != null) { if (sampleindex == 1)//获取面 { API_Learn.Learn_SelectionMgr.GetFace(Doc); } else if (sampleindex == 2)//获取边线 { API_Learn.Learn_SelectionMgr.GetEdge(Doc); } else if (sampleindex == 3)// { API_Learn.Learn_SelectionMgr.GetSelectList(Doc); } } } #endregion #region 11.Solidworks测量工具 else if (rowindex == 11)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "Measure.SLDPRT") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\12\Measure.SLDPRT", false); } if (Doc != null) { if (sampleindex == 1)//圆柱 { API_Learn.Learn_Measure.MeasureFace(Doc); } else if (sampleindex == 2)//边线 { API_Learn.Learn_Measure.MeasureEdge(Doc); } else if (sampleindex == 3)//圆柱与点 { API_Learn.Learn_Measure.MeasurePointFace(Doc); } } } #endregion #region 12.Solidworks尺寸 else if (rowindex == 12)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "Measure.SLDPRT") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\13\Dimension.SLDPRT", false); } if (Doc != null) { if (sampleindex == 1)//圆柱 { API_Learn.Learn_Dimension.GetDim(Doc, "L@草图1"); } else if (sampleindex == 2)//边线 { Dictionary <string, double> Vals = new Dictionary <string, double>(); Vals.Add("Default", 66); Vals.Add("cfg2", 77); API_Learn.Learn_Dimension.SetDim(Doc, "L@草图1", Vals); } else if (sampleindex == 3)//圆柱与点 { } } } #endregion #region 13.Solidworks装配体对象 else if (rowindex == 13)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "Assem.SLDASM") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\14\Assem.SLDASM", false, swDocumentTypes_e.swDocASSEMBLY); } if (Doc != null) { if (sampleindex == 1)//获取子部件 { API_Learn.Learn_AssemblyDoc.GetChildrenComp(Doc); } else if (sampleindex == 2)//插入零部件 { API_Learn.Learn_AssemblyDoc.InsertPart(swApp, Doc, AppDomain.CurrentDomain.BaseDirectory + @"Sample\14\part3.SLDPRT"); } else if (sampleindex == 3)// { } } } #endregion #region 14.Solidworks装配体对象 else if (rowindex == 14)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "装配学习.SLDASM") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\15\装配学习.SLDASM", false, swDocumentTypes_e.swDocASSEMBLY); } if (Doc != null) { if (sampleindex == 1)//部件装配 { API_Learn.Learn_AssemblyDoc.AddMate(swApp, Doc, AppDomain.CurrentDomain.BaseDirectory + @"Sample\15\转轴.SLDPRT"); } else if (sampleindex == 2)// { } else if (sampleindex == 3)// { } } } #endregion #region 15.Solidworks装配体部件设置 else if (rowindex == 15)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "装配学习.SLDASM") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\16\装配学习.SLDASM", false, swDocumentTypes_e.swDocASSEMBLY); } if (Doc != null) { Component2 SwComp = ((AssemblyDoc)swApp.ActiveDoc).GetComponentByName("转轴-1"); if (sampleindex == 1)//部件状态设置,压缩,解压,轻化 { API_Learn.Learn_Component2.SetComponentsStatus(SwComp); } else if (sampleindex == 2)//排除明细表 { API_Learn.Learn_Component2.SetCompBomInclude(SwComp); } else if (sampleindex == 3)//配置 { API_Learn.Learn_Component2.SetCompConfig(swApp.ActiveDoc, SwComp); } } } #endregion #region 16.Solidworks装配体配合对象 else if (rowindex == 16)// { SldWorks swApp = API_Learn.Learn_Sldworks.GetSolidworksApp(); ModelDoc2 Doc = swApp.ActiveDoc; bool ToOpen = false; if (Doc == null) { ToOpen = true; } else { if (Doc.GetTitle() != "装配学习.SLDASM") { ToOpen = true; } } if (ToOpen) { Doc = API_Learn.Learn_Sldworks.OpenDoc(swApp, AppDomain.CurrentDomain.BaseDirectory + @"Sample\17\装配学习.SLDASM", false, swDocumentTypes_e.swDocASSEMBLY); } if (Doc != null) { Component2 SwComp = ((AssemblyDoc)swApp.ActiveDoc).GetComponentByName("转轴-1"); if (sampleindex == 1)//获得配合对象 { API_Learn.Learn_Mate2.GetMateType(SwComp); } else if (sampleindex == 2)//获得配合参数 { API_Learn.Learn_Mate2.GetMateRefrence(SwComp); } else if (sampleindex == 3) { } } } #endregion }
private void RefreshLabel(Component2 swTestSelComp) { var comp = swTestSelComp; string textInfo = ""; bool isDraft = false; do { var m = comp.IGetModelDoc(); if (m != null) { bool draft = (m.CustomInfo2["", "Required Draft"] == "Yes" || m.CustomInfo2[m.IGetActiveConfiguration().Name, "Required Draft"] == "Yes"); if (draft) { var dir = new DirectoryInfo(Path.GetDirectoryName(_mSwAddin.SwModel.GetPathName())); var paths = dir.GetFiles( Path.GetFileNameWithoutExtension(m.GetPathName()) + ".SLDDRW", SearchOption.AllDirectories); string path = null; if (paths.Any()) path = paths[0].FullName; else { if (SwAddin.needWait) { path = Path.Combine(Path.GetDirectoryName(m.GetPathName()), Path.GetFileNameWithoutExtension(m.GetPathName()) + ".SLDDRW"); ThreadPool.QueueUserWorkItem(CheckDWRexistAfterCopy, path); } } if (!string.IsNullOrEmpty(path)) { linkLabel1.Name = path; linkLabel1.Click += LinkLabel1Click; textInfo = m.CustomInfo2["", "Sketch Number"]; isDraft = true; break; } } } comp = comp.GetParent(); } while (comp != null); if (isDraft) { if (linkLabel1.Text == "") { tabMain.Location = new Point(8, 70); btnOK.Location = new Point(btnOK.Location.X, btnOK.Location.Y + 30); btnCancel.Location = new Point(btnCancel.Location.X, btnCancel.Location.Y + 30); Size = new Size(Size.Width, Size.Height + 30); } if (textInfo == "" || textInfo == "0" || textInfo == "Sketch Number") linkLabel1.Text = @"ЭСКИЗ № н/о"; else linkLabel1.Text = @"ЭСКИЗ № " + textInfo; } else { if (linkLabel1.Text != "") { tabMain.Location = new Point(8, 40); btnOK.Location = new Point(btnOK.Location.X, btnOK.Location.Y - 30); btnCancel.Location = new Point(btnCancel.Location.X, btnCancel.Location.Y - 30); Size = new Size(Size.Width, Size.Height - 30); linkLabel1.Text = ""; } } }
public void ProcessTableAnn(BomTableAnnotation swBOMTableAnn, string ConfigName, SldAsm asmPrd) { int nNumRow = 0; string ItemNumber = null; string PartNumber = null; TableAnnotation swTableAnn = (TableAnnotation)swBOMTableAnn; Console.WriteLine(" Table Title " + swTableAnn.Title); IEdmVault5 vault = new EdmVault5(); vault.LoginAuto("科德研发部", 0); if (!vault.IsLoggedIn) { Console.WriteLine("登录PDM失败"); return; } nNumRow = swTableAnn.RowCount; swBOMTableAnn = (BomTableAnnotation)swTableAnn; for (int j = 0; j < swTableAnn.RowCount; j++) { // //for (int i = 0; i < swTableAnn.ColumnCount;i++ ) // Console.WriteLine(swTableAnn.get_Text(j, i)); //获取类别和特有信息 //if (j == swTableAnn.RowCount - 1)//最后一行为标题栏,跳过 // continue; string filePath = ""; string compName = ""; string compConfig = ""; int compCount = swBOMTableAnn.GetComponentsCount2(j, ConfigName, out ItemNumber, out PartNumber); for (int i = 0; i < compCount; i++) { Component2 comp2 = swBOMTableAnn.IGetComponents2(j, ConfigName, i); if (comp2 != null) { filePath = comp2.GetPathName(); compName = comp2.Name2; compConfig = comp2.ReferencedConfiguration; Console.WriteLine(" Component Name :" + comp2.Name2 + " Configuration Name : " + comp2.ReferencedConfiguration); Console.WriteLine(" Component Path :" + comp2.GetPathName()); } } if (filePath == "") { continue; } SldBsp bsp = GetSldPrdInfoFromFile(vault, filePath); if (bsp == null) { continue; } bsp.path = filePath; //SldBsp bsp = new SldBsp(); swTableAnn.get_Text(j, 0); //序号 bsp.number = swTableAnn.get_Text(j, 1); //代号 bsp.name = swTableAnn.get_Text(j, 2); //名称 string amout = swTableAnn.get_Text(j, 3); bsp.amout = amout == ""?0:int.Parse(amout); //数量 bsp.material = swTableAnn.get_Text(j, 4); //材料 string weight = swTableAnn.get_Text(j, 5); bsp.weight = weight == "" ? 0 : int.Parse(weight); //单重 bsp.totalWeight = bsp.weight * bsp.amout; // swTableAnn.get_Text(j, 6);//总重 bsp.remark = swTableAnn.get_Text(j, 7); //备注 string number = swTableAnn.get_Text(j, 8); //测试 if (bsp.number == "") { bsp.number = number; } if (bsp is SldPrt) { asmPrd.sldPrtList.Add((SldPrt)bsp); } else if (bsp is SldStd) { asmPrd.sldStdList.Add((SldStd)bsp); } else if (bsp is SldBuy) { asmPrd.sldBuyList.Add((SldBuy)bsp); } } return; }
private void ReloadAllSetParameters(Component2 swTestSelComp) { #region Очистить все словари местные переменные int downPos = 0; //закоменчено, т.к. этот код вызывает ошибку внутри солида и его закрытие. //замена на похожие методы (ClearSelection2 и т.п.) не помогает /*/ if (!_isMate) { _swAsmDoc.NewSelectionNotify -= NewSelection; _swModel.ClearSelection(); _swAsmDoc.NewSelectionNotify += NewSelection; } /*/ _dictHeightPage.Clear(); _dictPathPict.Clear(); _dictionary.Clear(); _dictConfig.Clear(); _commonList.Clear(); _objListChanged.Clear(); _setNewListForComboBox = true; _butPlusTxt.Clear(); _dimensionConfig.Clear(); _textBoxListForRedraw.Clear(); _numbAndTextBoxes.Clear(); _comboBoxListForRedraw.Clear(); _namesOfColumnNameFromDimLimits.Clear(); refobj = null; #endregion if (swTestSelComp != null) { if (_mSwAddin.GetParentLibraryComponent(swTestSelComp, out _swSelComp)) { ModelDoc2 specModel; _swSelComp = _mSwAddin.GetMdbComponentTopLevel(_swSelComp, out specModel); _swSelModel = _swSelComp.IGetModelDoc(); #region ссылочный эскиз //bool draft = (specModel.CustomInfo2["", "Required Draft"] == "Yes" || // specModel.CustomInfo2[specModel.IGetActiveConfiguration().Name, "Required Draft"] == "Yes"); //if (draft) //{ // tabMain.Location = new Point(8, 70); // var dir = new DirectoryInfo(Path.GetDirectoryName(_mSwAddin.SwModel.GetPathName())); // var paths = // dir.GetFiles( // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + ".SLDDRW", // SearchOption.AllDirectories); // string path=null; // if (paths.Any()) // path = paths[0].FullName; // else // { // if (SwAddin.needWait) // { // path = Path.Combine(Path.GetDirectoryName(specModel.GetPathName()), // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + // ".SLDDRW"); // ThreadPool.QueueUserWorkItem(CheckDWRexistAfterCopy, path); // } // } // if (!string.IsNullOrEmpty(path)) // { // linkLabel1.Name = path; // linkLabel1.Click += LinkLabel1Click; // string textInfo = specModel.CustomInfo2["", "Sketch Number"]; // if (textInfo == "" || textInfo == "0" || textInfo == "Sketch Number") // linkLabel1.Text = @"ЭСКИЗ № н/о"; // else // linkLabel1.Text = @"ЭСКИЗ № " + textInfo; // } // else // tabMain.Location = new Point(8, 40); //} //else //{ // tabMain.Location = new Point(8, 40); // linkLabel1.Text = ""; //} #endregion _lblPrm.Clear(); _btnPrm.Clear(); tbpParams.Controls.Clear(); tbpPos.Controls.Clear(); lblCompName.Text = _swSelComp.Name2; OleDbConnection oleDb; int i; if (_mSwAddin.OpenModelDatabase(_swSelModel, out oleDb)) { using (oleDb) { #region Обработка файла *.mdb if (!tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpPos); tabMain.Controls.Add(tbpParams); tabMain.Controls.Add(tbpPos); } if (Properties.Settings.Default.KitchenModeOn) { tabMain.SelectTab(tbpPos); } else { if (tabMain.SelectedTab != tbpParams) { tabMain.SelectTab(tbpParams); } } var oleSchem = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); OleDbCommand cm; OleDbDataReader rd; listForDimensions = new List<DimensionConfForList>(); #region Если есть objects if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "objects")) { _chkMeasure = new CheckBox { Appearance = Appearance.Button, Location = new Point(133, 12), Name = @"chkMeasure", Size = new Size(80, 24), Text = @"Измерить", TextAlign = ContentAlignment.MiddleCenter, UseVisualStyleBackColor = true }; tbpParams.Controls.Add(_chkMeasure); _chkMeasure.CheckedChanged += StartMeasure; i = 0; bool isNumber = false, isIdSlave = false, isAsmConfig = false, isFixedValues = false; #region Dimension Configuration if ( oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimension_conf")) { cm = new OleDbCommand("SELECT * FROM dimension_conf ORDER BY id", oleDb); rd = cm.ExecuteReader(); var outComps = new LinkedList<Component2>(); if (_mSwAddin.GetComponents( _swSelModel.IGetActiveConfiguration().IGetRootComponent2(), outComps, true, false)) { _dimensionConfig = Decors.GetListComponentForDimension(_mSwAddin, rd, outComps); _dimensionConfig.Sort((x, y) => x.Number.CompareTo(y.Number)); rd.Close(); } } #endregion var thisDataSet = new DataSet(); var testAdapter = new OleDbDataAdapter("SELECT * FROM objects", oleDb); testAdapter.Fill(thisDataSet, "objects"); testAdapter.Dispose(); bool captConfigBool = thisDataSet.Tables["objects"].Columns.Contains("captConf"); foreach (var v in thisDataSet.Tables["objects"].Columns) { var vc = (DataColumn)v; if (vc.ColumnName == "number") isNumber = true; if (vc.ColumnName == "idslave") { if (vc.DataType.Name != "String") MessageBox.Show( @"Неверно указан тип данных в столбце 'ismaster'", _mSwAddin.MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); isIdSlave = true; } if (vc.ColumnName == "mainasmconf" && _swSelModel.GetConfigurationCount() > 1) isAsmConfig = true; if (vc.ColumnName == "fixedvalues") isFixedValues = true; } thisDataSet.Clear(); if (Properties.Settings.Default.CheckParamLimits && oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimlimits")) { testAdapter = new OleDbDataAdapter("SELECT * FROM dimlimits", oleDb); testAdapter.Fill(thisDataSet, "dimlimits"); testAdapter.Dispose(); foreach (var v in thisDataSet.Tables["dimlimits"].Columns) { var vc = (DataColumn)v; _namesOfColumnNameFromDimLimits.Add(vc.ColumnName); } thisDataSet.Clear(); } string currentConf = _swSelComp.ReferencedConfiguration; cm = isNumber ? new OleDbCommand( "SELECT * FROM objects WHERE number>0 ORDER BY number", oleDb) : new OleDbCommand("SELECT * FROM objects ORDER BY id", oleDb); rd = cm.ExecuteReader(); #region Размеры #region Считывание данных из objects int k = 1; var dictWithDiscretValues = new Dictionary<string, List<int>>(); while (rd.Read()) { if (captConfigBool && rd["captConf"] != null && rd["captConf"].ToString() != "all" && rd["captConf"].ToString() != currentConf && !string.IsNullOrEmpty(rd["captConf"].ToString())) continue; if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" || rd["caption"].ToString().Trim() == "") continue; #region Обработка поля mainasmconf if (isAsmConfig) { var neededConf = rd["mainasmconf"].ToString(); bool isNeededConf = neededConf.Split('+').Select(v => v.Trim()).Any( f => f == currentConf); if (neededConf == "all") isNeededConf = true; if (!isNeededConf) continue; } #endregion string strObjName = rd["name"].ToString(); double strObjVal; if (_swSelModel.GetPathName().Contains("_SWLIB_BACKUP")) { string pn = Path.GetFileNameWithoutExtension(_swSelModel.GetPathName()); string last3 = pn.Substring(pn.Length - 4, 4); string[] arr = strObjName.Split('@'); if (arr.Length != 3) throw new Exception("что-то не так"); arr[2] = Path.GetFileNameWithoutExtension(arr[2]) + last3 + Path.GetExtension(arr[2]); strObjName = string.Format("{0}@{1}@{2}", arr[0], arr[1], arr[2]); } if (_mSwAddin.GetObjectValue(_swSelModel, strObjName, (int)rd["type"], out strObjVal)) { int val = GetCorrectIntValue(strObjVal); int number = isNumber ? (int)rd["number"] : (int)rd["id"]; while (number != k && _dimensionConfig.Count != 0) { listForDimensions.AddRange( from dimensionConfiguration in _dimensionConfig where dimensionConfiguration.Number == k select new DimensionConfForList(dimensionConfiguration.Number, dimensionConfiguration.Caption, "", -1, GetListIntFromString( dimensionConfiguration. IdSlave), dimensionConfiguration. Component, false, dimensionConfiguration.Id)); //Logging.Log.Instance.Debug("listForDimensions1:" + listForDimensions.Count.ToString()); k++; } var listId = new List<int>(); try { if (isIdSlave) listId = GetListIntFromString((string)rd["idslave"]); } catch { listId = null; } string labelName; try { labelName = rd["caption"].ToString(); } catch { string[] strObjNameParts = strObjName.Split('@'); labelName = strObjNameParts[0]; } if (isFixedValues) { try { var arr = (string)rd["fixedvalues"]; string[] arrs = arr.Split(','); var list = arrs.Select(s => Convert.ToInt32(s)).ToList(); if (!dictWithDiscretValues.ContainsKey(strObjName)) dictWithDiscretValues.Add(strObjName, list); } catch { } } listForDimensions.Add(new DimensionConfForList(number, labelName, strObjName, val, listId, null, (bool)rd["ismaster"], (int)rd["id"])); //Logging.Log.Instance.Debug("listForDimensions2:" + listForDimensions.Count.ToString()); k++; } } rd.Close(); #endregion listForDimensions.AddRange( _dimensionConfig.Where(x => x.Number >= k).Select( b => new DimensionConfForList(b.Number, b.Caption, "", -1, GetListIntFromString(b.IdSlave), b.Component, false, b.Id))); listForDimensions.Sort((x, y) => x.Number.CompareTo(y.Number)); //Logging.Log.Instance.Debug("listForDimensions3:" + listForDimensions.Count.ToString()); foreach (var dimensionConfForList in listForDimensions) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = dimensionConfForList.LabelName; lblNew.Tag = dimensionConfForList.StrObjName; tbpParams.Controls.Add(lblNew); _lblPrm.AddLast(lblNew); downPos = lblNew.Location.Y + lblNew.Size.Height; if (dimensionConfForList.StrObjName != "") { #region TextBox с размерами if (dictWithDiscretValues.ContainsKey(dimensionConfForList.StrObjName)) { #region Если дискретные значения var comboBoxWithDiscretValues = new ComboBox { Size = new Size(53, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = dimensionConfForList.StrObjName, TabIndex = i }; int val = dimensionConfForList.ObjVal; foreach (int vals in dictWithDiscretValues[dimensionConfForList.StrObjName]) { int ordNumb = comboBoxWithDiscretValues.Items.Add(vals); if (vals == val) comboBoxWithDiscretValues.SelectedIndex = ordNumb; } tbpParams.Controls.Add(comboBoxWithDiscretValues); _comboBoxListForRedraw.Add(comboBoxWithDiscretValues, dimensionConfForList.IdSlave); comboBoxWithDiscretValues.SelectedIndexChanged += ComboBoxWithDiscretValuesSelectedIndexChanged; #endregion } else { #region Если обычные значения int val = GetCorrectIntValue(dimensionConfForList.ObjVal); var txtNew = new TextBox { Size = new Size(35, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Name = lblNew.Text + "@" + dimensionConfForList.ObjVal, Text = val.ToString(), TextAlign = HorizontalAlignment.Right, Tag = dimensionConfForList.StrObjName, TabIndex = i }; _numbAndTextBoxes.Add(dimensionConfForList.Id, txtNew); if (!dimensionConfForList.IsGrey) txtNew.ReadOnly = true; else { _textBoxListForRedraw.Add(txtNew, dimensionConfForList.IdSlave); txtNew.KeyDown += TxtPrmKeyDown; txtNew.TextChanged += TxtNewTextChanged; var btnNew = new Button { ImageKey = @"Units1.ico", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + 4, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = txtNew.Name, Enabled = false }; if (!_butPlusTxt.ContainsKey(btnNew)) _butPlusTxt.Add(btnNew, txtNew); tbpParams.Controls.Add(btnNew); _btnPrm.AddLast(btnNew); btnNew.Click += MeasureLength; #region если есть таблица ref_objects и в ней есть хоть одна строка с соотв-щем id if (refobj == null) { refobj = new List<ref_object>(); if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "ref_objects_axe")) { cm = new OleDbCommand("SELECT * FROM ref_objects LEFT JOIN ref_objects_axe ON ref_objects_axe.id=ref_objects.objectsId", oleDb); rd = cm.ExecuteReader(); while (rd.Read()) { refobj.Add(new ref_object((string)rd["componentName"], (int)rd["objectsId"], (string)rd["axe"], (float)rd["correctionLeft_Up"], (float)rd["correctionRight_Down"])); } rd.Close(); } } ref_object[] currentrefs = refobj.Where(d => d.ObjectId == dimensionConfForList.Id).ToArray(); if (currentrefs.Length > 0) { //добавить кнопку //выбрать из refobj только dimensionConfigForList.Id var btnRef = new Button { ImageKey = @"expand.gif", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + btnNew.Size.Width + 8, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = currentrefs, Enabled = true }; tbpParams.Controls.Add(btnRef); //_btnPrm.AddLast(btnNew); btnRef.Click += ExpandBtn; if (!_butPlusTxt.ContainsKey(btnRef)) _butPlusTxt.Add(btnRef, txtNew); } #endregion } tbpParams.Controls.Add(txtNew); _commonList.Add(txtNew); #endregion } #endregion } else { #region ComboBox с конфигурациями var cmp = dimensionConfForList.Component; var comboBoxConfForDimTab = new ComboBox { Size = new Size(56, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = cmp, TabIndex = i }; var confNames = (string[])cmp.IGetModelDoc().GetConfigurationNames(); foreach (var confName in confNames) { int lonhName = confName.Length * 6; if (comboBoxConfForDimTab.DropDownWidth < lonhName) comboBoxConfForDimTab.DropDownWidth = lonhName; comboBoxConfForDimTab.Items.Add(confName); } comboBoxConfForDimTab.SelectedItem = cmp.ReferencedConfiguration; tbpParams.Controls.Add(comboBoxConfForDimTab); _comboBoxListForRedraw.Add(comboBoxConfForDimTab, dimensionConfForList.IdSlave); comboBoxConfForDimTab.SelectedIndexChanged += ComboBoxConfForDimTabSelectedIndexChanged; #endregion } i++; } #region Добавить выбор конфигурации try { if (_swSelModel.GetConfigurationCount() > 1) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = "Конфигурации:"; tbpParams.Controls.Add(lblNew); //lblNew.Tag = dimensionConfForList.StrObjName; downPos = lblNew.Location.Y + lblNew.Size.Height; string[] configurations = _swSelModel.GetConfigurationNames(); var comboBoxConfig = new ComboBox { Size = new Size(56, 24), Location = new Point(lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), }; string activeConf = _swSelComp.ReferencedConfiguration;//_swSelModel.IGetActiveConfiguration().Name; foreach (var configuration in configurations) { int currentIndex = comboBoxConfig.Items.Add(configuration); if (configuration == activeConf) comboBoxConfig.SelectedIndex = currentIndex; } Size size = TextRenderer.MeasureText(activeConf, comboBoxConfig.Font); int lonhName = size.Width; //nameOfConfiguration.Length * 5; if (comboBoxConfig.DropDownWidth < lonhName) comboBoxConfig.DropDownWidth = lonhName; tbpParams.Controls.Add(comboBoxConfig); comboBoxConfig.SelectedIndexChanged += ConfigurationChanged; } } catch { } #endregion #endregion _dictHeightPage.Add(tbpParams, downPos); } #endregion #region Если есть comments if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "comments")) { cm = new OleDbCommand("SELECT * FROM comments ORDER BY id", oleDb); rd = cm.ExecuteReader(); if (rd.Read()) { try { CommentLayout.Visible = true; WarningPB.Visible = (bool)rd["showSimbol"]; commentsTb.Text = (string)rd["comment"]; Size size = TextRenderer.MeasureText(commentsTb.Text, commentsTb.Font); commentsTb.Height = (size.Width / (commentsTb.Width - 10)) * 30; } catch { CommentLayout.Visible = false; } } rd.Close(); } else { CommentLayout.Visible = false; } #endregion #region Decors if (!ReloadDecorTab(oleDb, oleSchem)) return; #endregion oleDb.Close(); #endregion } } else if (_tabDec != null) tabMain.Controls.Remove(_tabDec); var swFeat = (Feature)_swSelModel.FirstFeature(); i = 0; #region Position var mates = _swSelComp.GetMates(); Dictionary<string, Mate2> existingMates = new Dictionary<string, Mate2>(); if (mates != null) { foreach (var mate in mates) { if (mate is Mate2) { var spec = (Mate2)mate; int mec = spec.GetMateEntityCount(); if (mec > 1) { for (int ik = 0; ik < mec; ik++) { MateEntity2 me = spec.MateEntity(ik); if (me.ReferenceComponent.Name.Contains(_swSelComp.Name)) { Entity tt = me.Reference; var tt2 = tt as Feature; if (tt is RefPlane && tt2 != null) { if (!existingMates.ContainsKey(tt2.Name)) existingMates.Add(tt2.Name, spec); } } } } } } } int downPosPosition = 0; int tabIndex = 0; while (swFeat != null) { if (swFeat.GetTypeName2() == "RefPlane") { string strPlaneName = swFeat.Name; if (strPlaneName.Length > 1) { if (strPlaneName.Substring(0, 1) == "#") { var btnNew = new Button { Size = new Size(120, 20) }; btnNew.Location = new Point(62, 24 + i * (btnNew.Size.Height + 6)); //if (Properties.Settings.Default.KitchenModeOn) // btnNew.Name = strPlaneName;//"btnPos" + i; //else btnNew.Name = "btnPos" + i; btnNew.Text = strPlaneName.Substring(5); btnNew.Tag = strPlaneName; btnNew.TabIndex = tabIndex; tabIndex++; tbpPos.Controls.Add(btnNew); btnNew.Click += AddMate; downPosPosition = btnNew.Location.Y + btnNew.Size.Height; if (existingMates.ContainsKey(strPlaneName)) { //добавить кнопку для отвязки var btnDeattach = new Button { Size = new Size(20, 20) }; btnDeattach.Location = new Point(62 + btnNew.Size.Width + 10, 24 + i * (btnNew.Size.Height + 6)); btnDeattach.Name = strPlaneName; btnDeattach.Text = "X"; btnDeattach.Tag = existingMates[strPlaneName]; tbpPos.Controls.Add(btnDeattach); btnDeattach.Click += DeleteMate; } i++; } } } swFeat = (Feature)swFeat.GetNextFeature(); } _dictHeightPage.Add(tbpPos, downPosPosition); #endregion if (_lblPrm.Count == 0) { tabMain.SelectTab(tbpPos); downPos = downPosPosition; SetSizeForTab(downPos); if (tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpParams); //Logging.Log.Instance.Fatal("Вкладка на РПД не показана.Смотреть listForDimensions"); } } if (rbMode1 != null && rbMode2 != null) { if (controlsToHideWhenChangeMode == null || controlsToHideWhenChangeMode.Count == 0) pnlMode.Visible = false; if (Properties.Settings.Default.DefaultRPDView) { rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); rbMode1.Checked = true; } else { rbMode2.Checked = true; rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); } } SetSizeForTab(_dictHeightPage[tabMain.SelectedTab]); } } }
public void Main() { swSuccess = false; errors = 0; warnings = 0; string swSourcePath = swApp.GetCurrentWorkingDirectory(); string swExportPath = Path.Combine(swSourcePath, "IGS"); string[] tmp = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); if (Directory.Exists(swExportPath)) { Directory.Delete(swExportPath, true); } Directory.CreateDirectory(swExportPath); ModelDoc2 swModel = swApp.ActiveDoc as ModelDoc2; AssemblyDoc swAssem = (AssemblyDoc)swModel; #region TopLevel string igsFileName = MakeFileName(swModel.Extension.Document.GetTitle()); swModel.Extension.SaveAs(Path.Combine(swExportPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //PrintSaveResults(); #endregion TopLevel #region Subassemblies string swExportSubPath = Path.Combine(swExportPath, "Subassemblies"); Directory.CreateDirectory(swExportSubPath); object[] objComps = (object[])swAssem.GetComponents(true); ModelDoc2 igsModel; foreach (object obj in objComps) { swComponent = obj as Component2; Debug.WriteLine(String.Format("Working on {0}.. \n\t {1}", swComponent.Name2, swComponent.GetPathName())); igsModel = swApp.OpenDoc6(swComponent.GetPathName(), (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); igsFileName = MakeFileName(igsModel.Extension.Document.GetTitle()); igsModel.Extension.SaveAs(Path.Combine(swExportSubPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); swApp.CloseDoc(igsModel.GetTitle()); } #endregion Subassemblies #region Parts string swExportPartPath = Path.Combine(swExportPath, "Parts"); Directory.CreateDirectory(swExportPartPath); string[] swPartFiles = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); foreach (string partFile in swPartFiles) { try { igsModel = swApp.OpenDoc6(partFile, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); string[] swConfigs = (string[])igsModel.GetConfigurationNames(); int swConfigCount = igsModel.GetConfigurationCount(); string swConfigFilename; for (int i = 0; i < swConfigCount; i++) { igsModel.ShowConfiguration2(swConfigs[i]); swConfigFilename = igsModel.Extension.Document.GetTitle(); if (swConfigCount > 1) { swConfigFilename += String.Format("-CFG{0}", (i + 1).ToString()); } igsFileName = MakeFileName(swConfigFilename); igsModel.Extension.SaveAs(Path.Combine(swExportPartPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); } swApp.CloseDoc(igsModel.GetTitle()); } catch (NullReferenceException e) { Debug.WriteLine(e.Message); } } #endregion Parts string timeFilename = Path.Combine(swExportPath, "Timestamp.txt"); using (StreamWriter swTimeStamper = new StreamWriter(timeFilename)) { swTimeStamper.WriteLine("Exported on {0} at {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToShortTimeString()); swTimeStamper.Flush(); } }
private bool SetDecorsForEachDetail(Component2 component, string pathPictName, int number, bool fit = false) { if (component.IGetModelDoc().GetType() == (int)swDocumentTypes_e.swDocPART) { double angel = GetAngel(number, component) ? 0 : 90; var m = component.IGetModelDoc(); var rmArr = (object[])m.Extension.GetRenderMaterials(); RenderMaterial rm = null; object swEnt; string fileName = pathPictName.Substring(0, pathPictName.Length - 4) + ".p2m"; if (rmArr == null) { component.Select(false); swEnt = (Entity)_swModel.ISelectionManager.GetSelectedObject6(1, -1); _swModel.ClearSelection(); //rm = m.Extension.CreateRenderMaterial(fileName); } else { if (_swSelModel.GetCustomInfoValue("", "ExtFanerFeats") == "Yes") swEnt = m; else { rm = (RenderMaterial)rmArr[0]; var ent = (object[])rm.GetEntities(); swEnt = ent[0]; } } rm = m.Extension.CreateRenderMaterial(fileName); rm.AddEntity(swEnt); rm.RotationAngle = angel; rm.TextureFilename = pathPictName; rm.FileName = fileName; rm.FixedAspectRatio = false; rm.FitWidth = false; rm.FitHeight = false; rm.Width = 0.3; rm.Height = 0.3; if (fit) { double width = 1; double height = 1; object b = component.GetBox(true, true); if (b != null) { var boxs = (double[])b; double xs1 = boxs[0]; double ys1 = boxs[1]; double zs1 = boxs[2]; double xs2 = boxs[3]; double ys2 = boxs[4]; double zs2 = boxs[5]; double x = Math.Abs(xs1 - xs2); double z = Math.Abs(zs1 - zs2); double y = Math.Abs(ys1 - ys2); if (y < x && y < z) { width = z; height = x; } else if (x < z && x < y) { width = y; height = z; } else if (z < x && z < y) { width = y; height = x; } } rm.Width = width; rm.Height = height; rm.FitWidth = true; rm.FitHeight = true; } var swConfig = (Configuration)m.GetConfigurationByName(component.ReferencedConfiguration); object displayStateNames = swConfig.GetDisplayStates(); int e1, e2; int f; //var texture = m.Extension.CreateTexture(pathPictName, 1, 0, false); //component.RemoveTexture(string.Empty); //component.SetTexture(string.Empty, texture); m.Extension.AddRenderMaterial(rm, out f); m.Extension.AddDisplayStateSpecificRenderMaterial(rm, (int)swDisplayStateOpts_e.swSpecifyDisplayState, displayStateNames, out e1, out e2); if (fit) m.Save2(true); return true; } return false; }
public void Main() { swSuccess = false; errors = 0; warnings = 0; string swSourcePath = swApp.GetCurrentWorkingDirectory(); string swExportPath = Path.Combine(swSourcePath, "IGS"); string[] tmp = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); if (Directory.Exists(swExportPath)) Directory.Delete(swExportPath, true); Directory.CreateDirectory(swExportPath); ModelDoc2 swModel = swApp.ActiveDoc as ModelDoc2; AssemblyDoc swAssem = (AssemblyDoc)swModel; #region TopLevel string igsFileName = MakeFileName(swModel.Extension.Document.GetTitle()); swModel.Extension.SaveAs(Path.Combine(swExportPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //PrintSaveResults(); #endregion TopLevel #region Subassemblies string swExportSubPath = Path.Combine(swExportPath, "Subassemblies"); Directory.CreateDirectory(swExportSubPath); object[] objComps = (object[])swAssem.GetComponents(true); ModelDoc2 igsModel; foreach (object obj in objComps) { swComponent = obj as Component2; Debug.WriteLine(String.Format("Working on {0}.. \n\t {1}", swComponent.Name2, swComponent.GetPathName())); igsModel = swApp.OpenDoc6(swComponent.GetPathName(), (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); igsFileName = MakeFileName(igsModel.Extension.Document.GetTitle()); igsModel.Extension.SaveAs(Path.Combine(swExportSubPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); swApp.CloseDoc(igsModel.GetTitle()); } #endregion Subassemblies #region Parts string swExportPartPath = Path.Combine(swExportPath, "Parts"); Directory.CreateDirectory(swExportPartPath); string[] swPartFiles = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); foreach (string partFile in swPartFiles) { try { igsModel = swApp.OpenDoc6(partFile, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); string[] swConfigs = (string[])igsModel.GetConfigurationNames(); int swConfigCount = igsModel.GetConfigurationCount(); string swConfigFilename; for (int i = 0; i < swConfigCount; i++) { igsModel.ShowConfiguration2(swConfigs[i]); swConfigFilename = igsModel.Extension.Document.GetTitle(); if (swConfigCount > 1) swConfigFilename += String.Format("-CFG{0}", (i+1).ToString()); igsFileName = MakeFileName(swConfigFilename); igsModel.Extension.SaveAs(Path.Combine(swExportPartPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); } swApp.CloseDoc(igsModel.GetTitle()); } catch (NullReferenceException e) { Debug.WriteLine(e.Message); } } #endregion Parts string timeFilename = Path.Combine(swExportPath, "Timestamp.txt"); using (StreamWriter swTimeStamper = new StreamWriter(timeFilename)) { swTimeStamper.WriteLine("Exported on {0} at {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToShortTimeString()); swTimeStamper.Flush(); } }
private void ShowConfigurationDetails(Component2 component, ModelDoc2 model, string nameConfiguration) { if (SwAddin.needWait) { ProgressBar.WaitTime.Instance.ShowWait(); ProgressBar.WaitTime.Instance.SetLabel("Ожидание завершения предедущих операций."); lock (SwAddin.workerLocker) Monitor.Wait(SwAddin.workerLocker); ProgressBar.WaitTime.Instance.HideWait(); } if (component.Select(false) && ((AssemblyDoc)model).CompConfigProperties4(component.GetSuppression(), 0, true, true, nameConfiguration, false)) { int err = 0, wrn = 0; var mod = _mSwAddin.SwApp.OpenDoc6(component.IGetModelDoc().GetPathName(), component.IGetModelDoc().GetType(), 0, nameConfiguration, ref err, ref wrn); var dict = new Dictionary<Component2, ModelDoc2>(); if (mod != null) { mod.ShowConfiguration2(nameConfiguration); if (mod.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { var outList = new LinkedList<Component2>(); if (_mSwAddin.GetComponents(mod.IGetActiveConfiguration().IGetRootComponent2(), outList, true, false)) { foreach (var component2 in outList) { if (mod.GetEquationMgr().GetCount() > 0) for (int i = 0; i < mod.GetEquationMgr().GetCount(); i++) { if (mod.GetEquationMgr().get_Equation(i).Contains( Path.GetFileNameWithoutExtension(component2.GetPathName()))) { if (mod.GetEquationMgr().get_Suppression(i) != component2.IsSuppressed()) mod.GetEquationMgr().set_Suppression(i, component2.IsSuppressed()); } } } foreach (var component2 in outList) { var m = component2.IGetModelDoc(); if (m != null && m.GetConfigurationCount() > 1) { if (dict.ContainsKey(component2)) dict.Add(component2, component.IGetModelDoc()); } } } } mod.Save(); _mSwAddin.SwApp.CloseDoc(mod.GetPathName()); } foreach (var d in dict) ShowConfigurationDetails(d.Key, d.Value, d.Key.ReferencedConfiguration); } }