private void angleMateManipulator(Feature angleMateFeat) { swMate = (Mate2)angleMateFeat.GetSpecificFeature2(); swAngleMateData = (AngleMateFeatureData)swFeat.GetDefinition(); // Controlador xbox if (miApp.XBoxConInstance.PlugStatus) { //Calcular el incremento //Sumar incremento double delta = (double)getDelta(miApp.XBoxConInstance.LeftThumbX); if (Math.Abs(delta) > 0) { swAngleMateData.Angle = swAngleMateData.Angle + delta; //Aplicar en el modelo angleMateFeat.ModifyDefinition(swAngleMateData, swModel, null); } } else { MessageBox.Show("No es posible controlar el mate angular sin control conectado"); } }
public static Mate2 AddAxisCoinMate <TAxisOne, TAxisTwo>(this AssemblyDoc doc, TAxisOne axisOne, TAxisTwo axisTwo) { int mateError = 0; Mate2 swMate = default; SelectEntityOrFeature <TAxisOne>(axisOne, false); SelectEntityOrFeature <TAxisTwo>(axisTwo, true); swMate = doc.AddMate5((int)swMateType_e.swMateCOINCIDENT, AxisAlign(axisOne, axisTwo).SWToInt(), false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out mateError); return(swMate); }
/// <summary> /// 轴配合 /// </summary> /// <typeparam name="TAxisOne"></typeparam> /// <typeparam name="TAxisTwo"></typeparam> /// <param name="doc"></param> /// <param name="axisOne"></param> /// <param name="compAxisTwo"></param> /// <param name="mathUtility"></param> /// <param name="comp"></param> /// <returns></returns> public static Mate2 AddAxisCoinMate <TAxisOne, TAxisTwo>(this AssemblyDoc doc, TAxisOne axisOne, TAxisTwo compAxisTwo, MathUtility mathUtility = null, Component2 comp = null) { int mateError = 0; Mate2 swMate = default; SelectEntityOrFeature <TAxisOne>(axisOne, false); SelectEntityOrFeature <TAxisTwo>(compAxisTwo, true); swMate = doc.AddMate5((int)swMateType_e.swMateCOINCIDENT, AxisAlign(axisOne, compAxisTwo, mathUtility, comp).SWToInt(), false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out mateError); return(swMate); }
/// <summary> /// 获得配合类型 /// </summary> /// <param name="SwComp"></param> public static void GetMateType(Component2 SwComp) { object[] CompMateObjs = SwComp.GetMates(); foreach (object ObjMate in CompMateObjs) { if (ObjMate is Mate2) { Mate2 SwMate = (Mate2)ObjMate; System.Windows.MessageBox.Show(Enum.Parse(typeof(swMateType_e), SwMate.Type.ToString().Trim()).ToString().Trim()); } } }
// Recherche de l'arrete de devant sur laquelle est contrainte la platine. private Edge ArreteDevant(List <Mate2> listeContraintes, Face2 faceDessus) { Mate2 Ct = null; // On rechercher la contrainte avec un point foreach (Mate2 Contrainte in listeContraintes) { foreach (MateEntity2 Ent in Contrainte.eListeDesEntitesDeContrainte()) { if (Ent.ReferenceType2 == (int)swSelectType_e.swSelEXTSKETCHPOINTS) { Ct = Contrainte; break; } } if (Ct.IsRef()) { break; } } if (Ct.IsNull()) { return(null); } Face2 F_Devant = null; // On recherche la face associée à cette contrainte foreach (MateEntity2 Ent in Ct.eListeDesEntitesDeContrainte()) { if (Ent.ReferenceType2 == (int)swSelectType_e.swSelFACES) { F_Devant = (Face2)Ent.Reference; break; } } if (F_Devant.IsNull()) { return(null); } List <Edge> ListeArretes = F_Devant.eListeDesArretesCommunes(faceDessus); if (ListeArretes.Count > 0) { return(ListeArretes[0]); } return(null); }
// Recherche de l'arrete sur laquelle est contrainte la platine. private Edge ArretePlatine(List <Mate2> listeContraintes, Feature planContrainte, Face2 f_Dessus) { Mate2 Contrainte = null; foreach (Mate2 Ct in listeContraintes) { foreach (MateEntity2 Ent in Ct.eListeDesEntitesDeContrainte()) { // Si l'entite est un plan if (Ent.ReferenceType2 == (int)swSelectType_e.swSelDATUMPLANES) { RefPlane P = Ent.Reference; Feature F = (Feature)P; // On vérifie que le plan a le même nom que le plan contrainte if (planContrainte.Name == F.Name) { Contrainte = Ct; break; } } } if (Contrainte.IsRef()) { break; } } foreach (MateEntity2 Ent in Contrainte.eListeDesEntitesDeContrainte()) { // On récupère la face associée à la contrainte if (Ent.ReferenceType2 == (int)swSelectType_e.swSelFACES) { Face2 F = Ent.Reference; // Liste des arrêtes communes, normalement, il n'y en a qu'une List <Edge> L = F.eListeDesArretesCommunes(f_Dessus); // On renvoi la première if (L.Count > 0) { return(L[0]); } } } return(null); }
private void Run(Component2 Comp) { try { List <Feature> ListePlanRef; if (CompBase.IsNull()) { ListePlanRef = MdlBase.eListeFonctions(f => { return(f.GetTypeName2() == FeatureType.swTnRefPlane); }); } else { ListePlanRef = CompBase.eListeFonctions(f => { return(f.GetTypeName2() == FeatureType.swTnRefPlane); }); } Log.Message(Comp.Name2); List <Feature> ListePlan = Comp.eListeFonctions(f => { return(f.GetTypeName2() == FeatureType.swTnRefPlane); }); Boolean EstFixe = Comp.IsFixed(); Comp.eLiberer(_Ass); Mate2 FxContrainte = null; int Erreur = 0; for (int i = 0; i < Math.Min(3, Math.Min(ListePlanRef.Count, ListePlan.Count)); i++) { Feature PlanRef = ListePlanRef[i]; Feature Plan = ListePlan[i]; PlanRef.eSelectionnerById2(MdlBase, -1, false); Plan.eSelectionnerById2(MdlBase, -1, true); FxContrainte = _Ass.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, true, 0, out Erreur); } MdlBase.eEffacerSelection(); if (EstFixe || FixerComposant) { Comp.eFixer(_Ass); } } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
/// <summary> /// 获得配合类型 /// </summary> /// <param name="SwComp"></param> public static void GetMateRefrence(Component2 SwComp) { object[] CompMateObjs = SwComp.GetMates(); StringBuilder Sb = new StringBuilder(""); foreach (object ObjMate in CompMateObjs) { if (ObjMate is Mate2) { Mate2 SwMate = (Mate2)ObjMate; Sb.Append("配合【" + ((Feature)SwMate).Name + "】参考对象:\r\n"); //配合名称 int n = SwMate.GetMateEntityCount(); for (int i = 0; i < n; i++) //配合参考 { MateEntity2 SwMateEntity2 = SwMate.MateEntity(i); string reftype = Enum.Parse(typeof(swSelectType_e), SwMateEntity2.ReferenceType2.ToString().Trim()).ToString().Trim(); string comp = SwMateEntity2.ReferenceComponent.Name2; string refname = SwMateEntity2.Reference.Name; Sb.Append("部件【" + comp + "】,参考【" + refname + "】" + ",类型【" + reftype + "】"); DisplayDimension SwDispDim = SwMate.DisplayDimension2[0]; if (SwDispDim != null) { if (SwMate.Type == (int)swMateType_e.swMateANGLE) { Sb.Append(",角度=" + SwDispDim.GetDimension2(0).Value.ToString().Trim()); } else if (SwMate.Type == (int)swMateType_e.swMateDISTANCE) { Sb.Append(",尺寸=" + SwDispDim.GetDimension2(0).Value.ToString().Trim()); } } Sb.Append("\r\n"); } Sb.Append("\r\n"); } } System.Windows.MessageBox.Show(Sb.ToString().Trim()); }
/// <summary> /// 面重合配合 /// </summary> /// <typeparam name="TFaceOne"></typeparam> /// <typeparam name="TFaceTwo"></typeparam> /// <param name="doc"></param> /// <param name="faceOne"></param> /// <param name="faceTwo"></param> /// <param name="mateAlign"></param> /// <returns></returns> public static Mate2 AddFaceCoinMate <TFaceOne, TFaceTwo>(this IAssemblyDoc doc, TFaceOne faceOne, TFaceTwo faceTwo, MateAlignExtension mateAlign) { int mateError = 0; Mate2 swMate = default; SelectEntityOrFeature(faceOne, false); SelectEntityOrFeature(faceTwo, true); switch (mateAlign) { case MateAlignExtension.SameAlign: swMate = doc.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out mateError); break; case MateAlignExtension.AntiAlign: swMate = doc.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignANTI_ALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out mateError); break; default: break; } return(swMate); }
/// <summary> /// 面重合配合 /// </summary> /// <typeparam name="TFaceOne"></typeparam> /// <typeparam name="TFaceTwo"></typeparam> /// <param name="doc"></param> /// <param name="faceOne"></param> /// <param name="faceTwo"></param> /// <param name="mateAlign"></param> /// <param name="dis">距离,正负代表方向</param> /// <returns></returns> public static Mate2 AddFaceDisMate <TFaceOne, TFaceTwo>(this IAssemblyDoc doc, TFaceOne faceOne, TFaceTwo faceTwo, MateAlignExtension mateAlign, double dis) { int mateError = 0; Mate2 swMate = default; SelectEntityOrFeature(faceOne, false); SelectEntityOrFeature(faceTwo, true); switch (mateAlign) { case MateAlignExtension.SameAlign: if (dis > 0) { swMate = doc.AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignALIGNED, false, dis, dis, dis, 0, 0, 0, 0, 0, false, false, 0, out mateError); } else { swMate = doc.AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignALIGNED, true, -dis, -dis, -dis, 0, 0, 0, 0, 0, false, false, 0, out mateError); } break; case MateAlignExtension.AntiAlign: if (dis > 0) { swMate = doc.AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignANTI_ALIGNED, false, dis, dis, dis, 0, 0, 0, 0, 0, false, false, 0, out mateError); } else { swMate = doc.AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignANTI_ALIGNED, true, -dis, -dis, -dis, 0, 0, 0, 0, 0, false, false, 0, out mateError); } break; default: break; } return(swMate); }
/// <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); }
/// <summary> /// 创建SWMate对象 /// </summary> /// <param name="mate"></param> /// <returns></returns> private static SWMate CreateSWMate(Mate2 mate) { if (mate == null) return null; int entityCount = 0; SWMate swMate = new SWMate(); //角度和距离是否反向 swMate.Flipped = mate.Flipped; //最大差值 swMate.MaxVariation = mate.MaximumVariation; //最小差值 swMate.MinVariation = mate.MinimumVariation; //配合相关实体 entityCount = mate.GetMateEntityCount(); for (int i = 0; i < entityCount; ++i) { swMate.MateEntities.Add(CreateSWMateEntity((MateEntity2)mate.MateEntity(i))); } #region switch mate type switch (mate.Type) { case (int)swMateType_e.swMateANGLE: swMate.MateType = SWMateType.ANGLE; break; case (int)swMateType_e.swMateCAMFOLLOWER: swMate.MateType = SWMateType.CAMFOLLOWER; break; case (int)swMateType_e.swMateCOINCIDENT: swMate.MateType = SWMateType.COINCIDENT; break; case (int)swMateType_e.swMateCONCENTRIC: swMate.MateType = SWMateType.CONCENTRIC; break; case (int)swMateType_e.swMateCOORDINATE: swMate.MateType = SWMateType.COORDINATE; break; case (int)swMateType_e.swMateDISTANCE: swMate.MateType = SWMateType.DISTANCE; break; case (int)swMateType_e.swMateGEAR: swMate.MateType = SWMateType.GEAR; break; case (int)swMateType_e.swMateHINGE: swMate.MateType = SWMateType.HINGE; break; case (int)swMateType_e.swMateLINEARCOUPLER: swMate.MateType = SWMateType.LINEARCOUPLER; break; case (int)swMateType_e.swMateLOCK: swMate.MateType = SWMateType.LOCK; break; case (int)swMateType_e.swMateLOCKTOSKETCH: swMate.MateType = SWMateType.LOCKTOSKETCH; break; case (int)swMateType_e.swMateMAXMATES: swMate.MateType = SWMateType.MAXMATES; break; case (int)swMateType_e.swMatePARALLEL: swMate.MateType = SWMateType.PARALLEL; break; case (int)swMateType_e.swMatePATH: swMate.MateType = SWMateType.PATH; break; case (int)swMateType_e.swMatePERPENDICULAR: swMate.MateType = SWMateType.PERPENDICULAR; break; case (int)swMateType_e.swMateRACKPINION: swMate.MateType = SWMateType.RACKPINION; break; case (int)swMateType_e.swMateSCREW: swMate.MateType = SWMateType.SCREW; break; case (int)swMateType_e.swMateSLIDER: swMate.MateType = SWMateType.SLIDER; break; case (int)swMateType_e.swMateSLOT: swMate.MateType = SWMateType.SLOT; break; case (int)swMateType_e.swMateSYMMETRIC: swMate.MateType = SWMateType.SYMMETRIC; break; case (int)swMateType_e.swMateTANGENT: swMate.MateType = SWMateType.TANGENT; break; case (int)swMateType_e.swMateUNIVERSALJOINT: swMate.MateType = SWMateType.UNIVERSALJOINT; break; case (int)swMateType_e.swMateUNKNOWN: swMate.MateType = SWMateType.UNKNOWN; break; case (int)swMateType_e.swMateWIDTH: swMate.MateType = SWMateType.WIDTH; break; } #endregion return swMate; }
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 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); }
protected override void Command() { Ass = MdlBase.eAssemblyDoc(); try { CurveDrivenPatternFeatureData def = FonctionRepetition.GetDefinition(); Object[] tabB = def.PatternBodyArray; Body2 b = (Body2)tabB[0]; MathTransform compRepetTrans = ComposantRepetition.Transform2; MathTransform baseMarcheTrans = Marche.Transform2; Vertex v = (Vertex)Point; Edge e = (Edge)Arrete; List <Face2> ListeFace = FonctionRepetition.eListeDesFaces(); Sketch sk = PointMarche.GetSketch(); Feature fPointMarche = (Feature)sk; List <Component2> ListeComposants = new List <Component2>() { Marche }; Double arr = 0.0001; for (int i = 1; i <= (def.D1InstanceCount + def.D2InstanceCount); i++) { MathTransform bodyTrans = def.GetTransform(i); if (bodyTrans.IsNull()) { break; } MathTransform Transform = compRepetTrans.Inverse(); Transform = Transform.Multiply(bodyTrans); Transform = Transform.Multiply(compRepetTrans); Transform = baseMarcheTrans.Multiply(Transform); gPoint pt = new gPoint(v); gSegment sg = new gSegment(e); pt.MultiplyTransfom(bodyTrans); sg.MultiplyTransfom(bodyTrans); Vertex vertex = null; Edge edge = null; foreach (Face2 face in ListeFace) { foreach (Edge ed in face.eListeDesArretes()) { gSegment s = new gSegment(ed); if (sg.Compare(s, arr)) { edge = ed; } if (s.Start.Comparer(pt, arr)) { vertex = ed.GetStartVertex(); } if (s.End.Comparer(pt, arr)) { vertex = ed.GetEndVertex(); } if (edge.IsRef() && vertex.IsRef()) { break; } } if (edge.IsRef() && vertex.IsRef()) { break; } } Entity eVertex = (Entity)vertex; Entity eEdge = (Entity)edge; Component2 cp = Ass.AddComponent5(Marche.GetPathName(), (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", 0, 0, 0); if (cp.IsNull()) { continue; } // Quand on réinsere un composant, les précédentes contraintes sont recrées. // On les supprime pour eviter des conflits Object[] Mates = cp.GetMates(); if (Mates.IsRef()) { foreach (Feature mate in Mates) { mate.eSelect(); MdlBase.Extension.DeleteSelection2((int)swDeleteSelectionOptions_e.swDelete_Absorbed); } } WindowLog.Ecrire(cp.Name2); cp.Transform2 = Transform; ListeComposants.Add(cp); int longstatus = 0; MdlBase.eEffacerSelection(); eVertex.eSelectEntite(false); Feature f = cp.FeatureByName(fPointMarche.Name); Sketch sketchOrigine = f.GetSpecificFeature2(); Object[] tabPt = sketchOrigine.GetSketchPoints2(); SketchPoint origine = (SketchPoint)tabPt[0]; origine.Select4(true, null); Mate2 mPoint = Ass.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignCLOSEST, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); eEdge.eSelectEntite(false); cp.FeatureByName(AxeMarche.Name).eSelect(true); Mate2 mAxe = Ass.AddMate5((int)swMateType_e.swMateANGLE, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); Plan.eSelect(false); cp.FeatureByName(PlanMarche.Name).eSelect(true); Mate2 mPlan = Ass.AddMate5((int)swMateType_e.swMatePARALLEL, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); Feature m = (Feature)mPoint; WindowLog.Ecrire(" " + m.Name); m = (Feature)mAxe; WindowLog.Ecrire(" " + m.Name); m = (Feature)mPlan; WindowLog.Ecrire(" " + m.Name); } MdlBase.eEffacerSelection(); foreach (var cp in ListeComposants) { cp.eSelectById(MdlBase, -1, true); } Feature Dossier = MdlBase.FeatureManager.InsertFeatureTreeFolder2((int)swFeatureTreeFolderType_e.swFeatureTreeFolder_Containing); Dossier.eRenommerFonction(String.Format("Marches ({0} {1}) ", ComposantRepetition.Name2, FonctionRepetition.Name)); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
public void Main() { ModelDoc2 swDoc; PartDoc swPart = null; DrawingDoc swDrawing = null; AssemblyDoc swAssembly = null; bool boolstatus = false; int longstatus = 0; int longwarnings = 0; string FileLocation = "E:\\My Douments\\MQP\\SOLIDWORKS\\Gear Creation script\\"; //directory for all parts created and modified in this code (Templates should be here) string Gear_Template = "Spur gear - Metric Template.sldprt"; //filename of the spur gear template string Housing = "GEAR_HOUSING_MACRO.sldprt"; //filename for gearbox housing string ASSEMBLY = "GEARBOX_ASSEMBLY_MACRO.sldasm"; //filename for Assembly file string SHAFT_TEMPLATE = "SHAFT_TEMPLATE.sldprt"; int i; //number of gears to create (replace with input data later) //***************************CREATE GEARS*********************************** int num_gears = 5; //number of gears in assembly to generate double[][] Gear_info = new double[num_gears][]; //array of arrays(jagged) to store data about each gear //raw gear data {#teeth, width,shaft,locked to shaft, other gear to mesh with(255 indicates no output),distance from } // 0 1 2 3 4 5 Gear_info[0] = new double[] { 10, 4, 0, 1, 1, 0.000 }; // #teeth, width mm, which shaft to connect to, if locked on shaft, distance between shafts Gear_info[1] = new double[] { 40, 4, 1, 0, 2, 0.000 }; Gear_info[2] = new double[] { 20, 4, 2, 1, 255, 0.000 }; Gear_info[3] = new double[] { 40, 4, 2, 1, 4, 0.004 }; Gear_info[4] = new double[] { 20, 4, 1, 1, 255, 0.004 }; //shaft info double Shaft_Diameter = 1; //diameter in mm (also used for bore dia. in gears) int num_shafts = 3; double Shaft_length = 2 * Gear_info[0][1]; //length of shaft, make slightly larger than width of gear for now double Modulus = .25; //gear modulus for all gears double[] shaft_spacing = new double[] { 4, 5, 8 }; //temporarily use this for the shaft spacing for (i = 0; i < num_gears; i++) //create each gear based off the template { swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + Gear_Template, 1, 0, "", ref longstatus, ref longwarnings))); double NUM_TEETH = Gear_info[i][0]; Double WIDTH = Gear_info[i][1];// gear depth in mm double SHOW_TEETH = NUM_TEETH; //change sketch dimmensions in the reference sketch: "HoldingSke" ((Dimension)(swDoc.Parameter("Show_teeth@HoldingSke"))).SystemValue = SHOW_TEETH * (3.14159 / 180); //have to convert degrees to radians, num_teeth is saved as angle measurment in the sketch ((Dimension)(swDoc.Parameter("Num_teeth@HoldingSke"))).SystemValue = NUM_TEETH * (3.14159 / 180); //display all the teeth ((Dimension)(swDoc.Parameter("Width@HoldingSke"))).SystemValue = WIDTH / 1000; ((Dimension)(swDoc.Parameter("Bore@HoldingSke"))).SystemValue = Shaft_Diameter / 1000; ((Dimension)(swDoc.Parameter("Module@HoldingSke"))).SystemValue = Modulus / 1000; boolstatus = swDoc.EditRebuild3(); //rebuild the document longstatus = swDoc.SaveAs3(FileLocation + "GEAR_MACRO" + i + ".sldprt", 0, 2); //save gear as gear number i in a new folder called MACRO_PARTS } //***************************CREATE SHAFTS*********************************** for (i = 0; i < num_shafts; i++) { swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + SHAFT_TEMPLATE, 1, 0, "", ref longstatus, ref longwarnings))); //change sketch dimmensions ((Dimension)(swDoc.Parameter("Diameter@Sketch1"))).SystemValue = Shaft_Diameter / 1000; ((Dimension)(swDoc.Parameter("Shaft Length@Sketch1"))).SystemValue = Shaft_length / 1000; boolstatus = swDoc.EditRebuild3(); //rebuild the document longstatus = swDoc.SaveAs3(FileLocation + "SHAFT_MACRO" + i + ".sldprt", 0, 2); //save gear as gear number i in a new folder called MACRO_PARTS //code to create shafts of set diameters or something } //***************************CREATE ASSEMBLY*********************************** //Open All components to be added for (i = 0; i < num_gears; i++) { swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "GEAR_MACRO" + i + ".sldprt", 1, 0, "", ref longstatus, ref longwarnings))); swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "SHAFT_MACRO" + i + ".sldprt", 1, 0, "", ref longstatus, ref longwarnings))); } //Open the assembly swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "Assembly_Template.SLDASM", 2, 0, "", ref longstatus, ref longwarnings))); swDoc = ((ModelDoc2)(swApp.ActiveDoc)); swApp.ActivateDoc2("Assembly_Template.SLDASM", false, ref longstatus); swAssembly = ((AssemblyDoc)(swDoc)); //add components to SW assembly //****** Currently Parts must already be opened seperately to add to assmebly ******* //***************************SHAFT MATES*********************************** //names of edges and faces in the template: Front Edge ( circle along front) // Surface (cylinder surface of rod) //make face coincident with corresponding hole on housing Mate2 myMate = null; //insert shaft //insert point for mate //align along axis //mate oring to point double[][] Shaft_coord = new double[num_shafts][]; //array of arrays(jagged) to store data about each gear double x; double y; double z; //shaft coords x, y, z Shaft_coord[0] = new double[] { .000, .000, .000 }; Shaft_coord[1] = new double[] { .000, .000, .008 }; Shaft_coord[2] = new double[] { .000, .000, .018 }; //Shaft_coord[3] = new double[] {.019, .000, 0}; for (i = 0; i < num_shafts; i++) { boolstatus = swAssembly.AddComponent(FileLocation + "SHAFT_Macro" + i + ".sldprt", 0, 0, 0); if (i == 0) { swDoc.ClearSelection2(true); boolstatus = swDoc.Extension.SelectByID2("SHAFT_MACRO" + i + "-1@Assembly_Template", "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssembly.UnfixComponent(); } x = Shaft_coord[i][0]; y = Shaft_coord[i][1]; z = Shaft_coord[i][2]; boolstatus = swDoc.Extension.SelectByID2("Shaft coords sketch", "SKETCH", 0, 0, 0, false, 0, null, 0); swDoc.EditSketch(); swDoc.ClearSelection2(true); SketchPoint skPoint = null; skPoint = ((SketchPoint)(swDoc.SketchManager.CreatePoint(x, y, z))); //create a point //have to make point fixed! //make origin coincident to its sketch point boolstatus = swDoc.Extension.SelectByID2("Point" + (i + 11) + "@Shaft coords sketch", "EXTSKETCHPOINT", x, y, z, true, 1, null, 0); boolstatus = swDoc.Extension.SelectByID2("Point1@Origin@SHAFT_MACRO" + i + "-1@Assembly_Template", "EXTSKETCHPOINT", 0, 0, 0, true, 1, null, 0); myMate = null; swAssembly = ((AssemblyDoc)(swDoc)); myMate = ((Mate2)(swAssembly.AddMate5(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus))); swDoc.ClearSelection2(true); swDoc.EditRebuild3(); //parallel to axis boolstatus = swDoc.Extension.SelectByID2("Center Axis@SHAFT_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, false, 0, null, 0); boolstatus = swDoc.Extension.SelectByID2("Line1@Reference Direction", "EXTSKETCHSEGMENT", 0, 0, 0.0021382559642120218, true, 1, null, 0); myMate = null; swAssembly = ((AssemblyDoc)(swDoc)); myMate = ((Mate2)(swAssembly.AddMate5(3, 1, false, 0.0029999999999767309, 0.001, 0.001, 0.001, 0.001, 0, 0.5235987755983, 0.5235987755983, false, false, 0, out longstatus))); swDoc.ClearSelection2(true); swDoc.EditRebuild3(); } //***************************GEAR MATES*********************************** string face_sel; //holds string with name of the face to select for (i = 0; i < num_gears; i++) { Double DistanceMate = Gear_info[i][5]; // gear loacation on shaft boolstatus = swAssembly.AddComponent(FileLocation + "GEAR_MACRO" + i + ".sldprt", -0.5, 0, 0); //Distance mate from edge of shaft boolstatus = swDoc.Extension.SelectByID2("EDGE@GEAR_MACRO" + i + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //face plane of gear boolstatus = swDoc.Extension.SelectByID2("Right@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //shaft hole in housing myMate = (Mate2)swAssembly.AddMate5(5, 1, false, DistanceMate, DistanceMate, DistanceMate, 0, 0, 0, 0, 0, false, false, 0, out longstatus); swDoc.ClearSelection2(true); //concentric to shaft boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0); //axis of gear boolstatus = swDoc.Extension.SelectByID2("Center Axis@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0); //axis of shaft myMate = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus); swDoc.ClearSelection2(true); //lock to shaft if (Gear_info[i][3] == 1) //if gear locked to shaft (make two planes coincident) { boolstatus = swDoc.Extension.SelectByID2("Plane2@GEAR_MACRO" + i + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //face plane of shaft boolstatus = swDoc.Extension.SelectByID2("Front@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //shaft hole in housing myMate = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus); swDoc.ClearSelection2(true); swDoc.EditRebuild3(); } } //gear mate for (i = 0; i < (num_gears); i++) { if (Gear_info[i][4] != 255) //if -1 that means do not make a gear mate (don't make gear mate for last gear sinc it is output, no gear to mesh to!!!!) { boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0); //axis of gear boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + Gear_info[i][4] + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0); //axis of gear myMate = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateGEAR, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, Gear_info[i][0], Gear_info[i + 1][0], 0, 0, 0, false, false, out longstatus); //gear mate, specify num. and denom. of gear ratio as #teeth on gear swDoc.ClearSelection2(true); swDoc.EditRebuild3(); } } /* * * * // boolstatus = swDoc.Extension.SelectByID2("", "FACE", -0.00455748224163699, 0.0037205844126901866, 0.004682722786242266, false, 0, null, 0); * // boolstatus = swDoc.Extension.SelectByID2("", "FACE", 0.0018884588073433406, 0.00336302382845588, -0.00060759657679909651, true, 0, null, 1); * // swDoc.ClearSelection2(true); * * boolstatus = swDoc.Extension.SelectByID2("Plane3@30 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0); * boolstatus = swDoc.Extension.SelectByID2("Plane3@50 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0); * //Mate2 myMate = null; * // swAssembly = ((AssemblyDoc)(swDoc)); * * //add mate to two parts (by selection) * // myMate = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus); * // swDoc.ClearSelection2(true); * * * boolstatus = swDoc.Extension.SelectByID2("Bore of@50 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0); * * * swDoc.EditRebuild3(); */ }
/// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <param name="partsname"></param> private void CreateNewAssembly(string assemblyName, List <string> partsname) { string assemblyDefaultPath = iswApp.GetDocumentTemplate(2, "", 0, 0, 0); var part = iswApp.NewDocument(assemblyDefaultPath, 0, 0, 0); if (part != null) { AssemblyDoc assemblyDoc = part as AssemblyDoc; ModelDoc2 modelDoc2 = assemblyDoc as ModelDoc2; ModelDocExtension swModExt = default(ModelDocExtension); int errors = 0; int warnings = 0; swModExt = (ModelDocExtension)modelDoc2.Extension; swModExt.SaveAs(assemblyName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, errors, warnings); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; int i = 0; int tempV = ProgressBar.Value; foreach (var partN in partsname) { labStatus.Text = "正在装配-->" + Path.GetFileNameWithoutExtension(partN); ProgressBar.Value = tempV + i; iswApp.OpenDoc6(partN.ToString(), 1, 32, "", ref errors, ref warnings); assemblyDoc = (AssemblyDoc)iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors); Component2 swInsertedComponent = default(Component2); swInsertedComponent = assemblyDoc.AddComponent5(partN, 0, "", false, "", 0, 0, 0); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; modelDoc2.ClearSelection2(true); modelDoc2.Extension.SelectByID2(swInsertedComponent.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); assemblyDoc.UnfixComponent(); modelDoc2.ClearSelection2(true); modelDoc2.Extension.SelectByID2("Point1@Origin@" + swInsertedComponent.GetSelectByIDString(), "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0); modelDoc2.Extension.SelectByID2("Point1@Origin", "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0); Mate2 mate2 = default(Mate2); mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0, 0, 0, 0.001, 0, 0, 0, false, false, 0, out int warings); modelDoc2.ClearSelection2(true); modelDoc2.EditRebuild3(); iswApp.CloseDoc(partN); i = i + 1; } iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; modelDoc2.ShowNamedView2("*等轴测", 7); modelDoc2.ViewZoomtofit2(); modelDoc2.Save(); } ProgressBar.Value = ProgressBar.Maximum; }
/// <summary> /// 创建SWMate对象 /// </summary> /// <param name="mate"></param> /// <returns></returns> private static SWMate CreateSWMate(Mate2 mate) { if (mate == null) { return(null); } int entityCount = 0; SWMate swMate = new SWMate(); //角度和距离是否反向 swMate.Flipped = mate.Flipped; //最大差值 swMate.MaxVariation = mate.MaximumVariation; //最小差值 swMate.MinVariation = mate.MinimumVariation; //配合相关实体 entityCount = mate.GetMateEntityCount(); for (int i = 0; i < entityCount; ++i) { swMate.MateEntities.Add(CreateSWMateEntity((MateEntity2)mate.MateEntity(i))); } #region switch mate type switch (mate.Type) { case (int)swMateType_e.swMateANGLE: swMate.MateType = SWMateType.ANGLE; break; case (int)swMateType_e.swMateCAMFOLLOWER: swMate.MateType = SWMateType.CAMFOLLOWER; break; case (int)swMateType_e.swMateCOINCIDENT: swMate.MateType = SWMateType.COINCIDENT; break; case (int)swMateType_e.swMateCONCENTRIC: swMate.MateType = SWMateType.CONCENTRIC; break; case (int)swMateType_e.swMateCOORDINATE: swMate.MateType = SWMateType.COORDINATE; break; case (int)swMateType_e.swMateDISTANCE: swMate.MateType = SWMateType.DISTANCE; break; case (int)swMateType_e.swMateGEAR: swMate.MateType = SWMateType.GEAR; break; case (int)swMateType_e.swMateHINGE: swMate.MateType = SWMateType.HINGE; break; case (int)swMateType_e.swMateLINEARCOUPLER: swMate.MateType = SWMateType.LINEARCOUPLER; break; case (int)swMateType_e.swMateLOCK: swMate.MateType = SWMateType.LOCK; break; case (int)swMateType_e.swMateLOCKTOSKETCH: swMate.MateType = SWMateType.LOCKTOSKETCH; break; case (int)swMateType_e.swMateMAXMATES: swMate.MateType = SWMateType.MAXMATES; break; case (int)swMateType_e.swMatePARALLEL: swMate.MateType = SWMateType.PARALLEL; break; case (int)swMateType_e.swMatePATH: swMate.MateType = SWMateType.PATH; break; case (int)swMateType_e.swMatePERPENDICULAR: swMate.MateType = SWMateType.PERPENDICULAR; break; case (int)swMateType_e.swMateRACKPINION: swMate.MateType = SWMateType.RACKPINION; break; case (int)swMateType_e.swMateSCREW: swMate.MateType = SWMateType.SCREW; break; case (int)swMateType_e.swMateSLIDER: swMate.MateType = SWMateType.SLIDER; break; case (int)swMateType_e.swMateSLOT: swMate.MateType = SWMateType.SLOT; break; case (int)swMateType_e.swMateSYMMETRIC: swMate.MateType = SWMateType.SYMMETRIC; break; case (int)swMateType_e.swMateTANGENT: swMate.MateType = SWMateType.TANGENT; break; case (int)swMateType_e.swMateUNIVERSALJOINT: swMate.MateType = SWMateType.UNIVERSALJOINT; break; case (int)swMateType_e.swMateUNKNOWN: swMate.MateType = SWMateType.UNKNOWN; break; case (int)swMateType_e.swMateWIDTH: swMate.MateType = SWMateType.WIDTH; break; } #endregion return(swMate); }
/// <summary> /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样 /// </summary> /// <param name="sendTocustomer"></param> /// <param name="localModel"></param> /// <returns></returns> public bool CheckTwoParts(string sendTocustomer, string localModel) { bool different1 = false; bool different2 = false; swApp = ConnectToSolidWorks(); // swApp = ConnectToSolidWorks(); //加载参考关系零件 swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly); //后台模式 前台不显示界面 swApp.EnableBackgroundProcessing = true; //禁止记录文件路径 swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true); swApp.OpenDoc(localModel, 1); swApp.OpenDoc(sendTocustomer, 1); ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc; string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString(); string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly); AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0); Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0); Component2 insertComponentLocal = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0); string sendSelect = insertComponentSendtoCustomer.GetSelectByIDString(); string localSelect = insertComponentLocal.GetSelectByIDString(); swModel = (ModelDoc2)swApp.ActiveDoc; bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0); bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0); int longstatus; Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.SaveAs(LocalPath + @"\TopCheck.sldasm"); //不显示特征树 //swModel.Extension.HideFeatureManager(true); swModel.ClearSelection2(true); //swModel.FeatureManager.ViewFeatures = false; //FeatureManager featureManager = swModel.FeatureManager; //禁用特征树 //featureManager.EnableFeatureTree = false; // swModel.FeatureManager.EnableFeatureTreeWindow = false; #region first join Component2 sendToCustomerBodies = default(Component2); List <Component2> sendToCustomerBodiesList = new List <Component2>(); object swFaceOrPlane = default(object); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies); sendToCustomerBodies.Select(true); assemblyDoc.FixComponent(); sendToCustomerBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); object[] splits = sendToCustomerBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1"; ModelDoc2 compModel = default(ModelDoc2); compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } bool ret; ret = sendToCustomerBodies.SaveVirtualComponent(compName); sendToCustomerBodiesList.Add(sendToCustomerBodies); insertComponentSendtoCustomer.Select(false); swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2(); #region 获取所有零件中的零件,每一个实体做一次反切 List <string> bodyNamesCustomer = new List <string>(); PartDoc swPart = null; object vBody; swPart = (PartDoc)swModel; // Solid bodies object[] vBodyArr = null; Body2 swBody = default(Body2); MathTransform swMathTrans = null; vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true); if ((vBodyArr != null)) { // Debug.Print(" Number of solid bodies: " + vBodyArr.Length); foreach (object vBody_loopVariable in vBodyArr) { vBody = vBody_loopVariable; swBody = (Body2)vBody; string[] vConfigName = null; vConfigName = (string[])swModel.GetConfigurationNames(); string sMatDB = ""; string sMatName = swBody.GetMaterialPropertyName("", out sMatDB); //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName)); //Debug.Print("Body--> " + swBody.Name + " " + ""); bodyNamesCustomer.Add(swBody.Name); } } //如果实体数量大于1,则继续新建对应数量的join 实体。 OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1); if (bodyNamesCustomer.Count > 1) { assemblyDoc.EditAssembly(); for (int i = 0; i < bodyNamesCustomer.Count - 1; i++) { Component2 returnpart = default(Component2); var partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart); sendToCustomerBodiesList.Add(returnpart); OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1); } } // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0) //Dim myFeature As Object //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True) #endregion 获取所有零件中的零件,每一个实体做一次反切 //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); Feature theFeature; //theFeature = swModel.FeatureByPositionReverse(0); //if (theFeature.Name.Contains("Cavity")) //{ // //theFeature.Select(true); // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.BreakAllExternalReferences(); // different1 = true; // //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有 //} //else //{ // //无法Join时表示 全切了。 // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.EditSuppress(); //} //sendToCustomerBodies.Select(true); assemblyDoc.EditAssembly(); #endregion first join #region sercond join2 Component2 localBodies = default(Component2); List <Component2> LocalBodiesList = new List <Component2>(); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies); localBodies.Select(true); assemblyDoc.FixComponent(); localBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); splits = localBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1"; compModel = default(ModelDoc2); compModel = (ModelDoc2)localBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } ret = localBodies.SaveVirtualComponent(compName); LocalBodiesList.Add(localBodies); insertComponentLocal.Select(false); swModel = (ModelDoc2)localBodies.GetModelDoc2(); #region 获取所有零件中的零件,每一个实体做一次反切 List <string> bodyNamesLocal = new List <string>(); PartDoc swPart2 = null; object vBody2; swPart2 = (PartDoc)swModel; // Solid bodies object[] vBodyArr2 = null; Body2 swBody2 = default(Body2); MathTransform swMathTrans2 = null; vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true); if ((vBodyArr2 != null)) { // Debug.Print(" Number of solid bodies: " + vBodyArr.Length); foreach (object vBody_loopVariable in vBodyArr2) { vBody2 = vBody_loopVariable; swBody2 = (Body2)vBody2; string[] vConfigName = null; vConfigName = (string[])swModel.GetConfigurationNames(); string sMatDB = ""; string sMatName = swBody2.GetMaterialPropertyName("", out sMatDB); //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName)); bodyNamesLocal.Add(swBody2.Name); } } //如果实体数量大于1,则继续新建对应数量的join 实体。 OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2); if (bodyNamesLocal.Count > 1) { assemblyDoc.EditAssembly(); for (int i = 0; i < bodyNamesLocal.Count - 1; i++) { Component2 returnpart = default(Component2); var partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart); LocalBodiesList.Add(returnpart); OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2); } } // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0) //Dim myFeature As Object //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True) #endregion 获取所有零件中的零件,每一个实体做一次反切 //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); //theFeature = swModel.FeatureByPositionReverse(0); //swModel = (ModelDoc2)localBodies.GetModelDoc2(); //theFeature = swModel.FeatureByPositionReverse(0); //if (theFeature.Name.Contains("Cavity")) //{ // //theFeature.Select(true); // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.BreakAllExternalReferences(); // different2 = true; // //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有 //} //else //{ // //无法Join时表示 全切了。 // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.EditSuppress(); //} //localBodies.Select(true); //assemblyDoc.EditAssembly(); #endregion sercond join2 #region joinPartPublic Component2 publicBodies = default(Component2); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies); publicBodies.Select(true); assemblyDoc.FixComponent(); publicBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); splits = publicBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies"; compModel = default(ModelDoc2); compModel = (ModelDoc2)publicBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } ret = publicBodies.SaveVirtualComponent(compName); swModel.ClearSelection(); foreach (var item in sendToCustomerBodiesList) { item.Select(false); assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); theFeature = (Feature)swModel.FeatureByPositionReverse(0); swModel = (ModelDoc2)publicBodies.GetModelDoc2(); theFeature = (Feature)swModel.FeatureByPositionReverse(0); if (theFeature.Name.Contains("Cavity")) { //theFeature.Select(true); swModel = (ModelDoc2)swApp.ActiveDoc; bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); swModel.BreakAllExternalReferences(); //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有 } else { } } foreach (var item in LocalBodiesList) { item.Select(false); assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); theFeature = (Feature)swModel.FeatureByPositionReverse(0); swModel = (ModelDoc2)publicBodies.GetModelDoc2(); theFeature = (Feature)swModel.FeatureByPositionReverse(0); if (theFeature.Name.Contains("Cavity")) { //theFeature.Select(true); swModel = (ModelDoc2)swApp.ActiveDoc; bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); swModel.BreakAllExternalReferences(); //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有 } else { } } publicBodies.Select(true); assemblyDoc.EditAssembly(); #endregion joinPartPublic foreach (var item in sendToCustomerBodiesList) { item.Select(false); setColour(Color.Red); } foreach (var item in LocalBodiesList) { item.Select(false); setColour(Color.Blue); } swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ClearSelection2(true); insertComponentLocal.Select(false); insertComponentSendtoCustomer.Select(true); swModel.HideComponent2(); swModel.ClearSelection2(true); publicBodies.Select(false); assemblyDoc.SetComponentTransparent(true); setColour(Color.Green); swModel.EditRebuild3(); swModel.Save(); swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0); swApp.CloseDoc("TopCheck.sldasm"); swApp.CloseAllDocuments(true); swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ShowNamedView2("*Isometric", 7); swModel.ViewZoomtofit2(); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false); try { System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm"); System.IO.File.Delete(LocalPath + @"\localBodies.sldprt"); System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt"); System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt"); } catch (Exception) { } //第二次反向剪切 swApp.CloseDoc(sendTocustomer); swApp.CloseDoc(localModel); swModel.FeatureManager.EnableFeatureTree = true; swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2); if (different1 == false && different2 == false) { return(false); } else { return(true); } }