/// <summary> /// Creates a new joint editor proptery manager page that allows the user to edit joint properties. /// </summary> /// <param name="robot">Active robot model</param> /// <param name="joint">Joint to be edited</param> /// <param name="document">Active assembly document</param> /// <param name="swApp">Solidworks application environment</param> public JointPMPage(RobotModel robot, Joint joint, AssemblyDoc document, SldWorks swApp) { //Validate parameters if (robot == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null robot model."); if (document == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null assembly document."); if (swApp == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null solidworks application interface."); //Initialize fields this.robot = robot; this.swApp = swApp; currentJoint = joint; mathUtil = ((IMathUtility)swApp.GetMathUtility()); //AssemblyDoc inherits ModelDoc2 but the relationship dosn't carry through the COM interface //Having two fields prevents having to cast half of the time modelDoc = (ModelDoc2)document; assemblyDoc = document; //Setup the page, its controls and their visual layout SetupPage(); SelectionObservers = new List<SelectionObserver>(); ButtonObservers = new List<ButtonObserver>(); CheckboxObservers = new List<CheckboxObserver>(); }
public JointAxis(SldWorks swApp, AssemblyDoc asm, StorageModel swData, string path, Joint current, int index, RobotModel robot) { this.swApp = swApp; this.asmDoc = asm; this.modelDoc = (ModelDoc2)asm; this.swData = swData; this.path = path; this.owner = current; this.robot = robot; this.AxisIndex = index; if (EffortLimit == 0) { this.EffortLimit = 1; } if (this.VelocityLimit == 0) { this.VelocityLimit = 1; } if (Axis != null) { CalcAxisVectors(); //CalcLimits(null); } if (index == 2) { IsContinuous = true; } }
/// <summary> /// Выполняет метод для компонентов сборки (подсборки и детали) /// </summary> /// <param name="assemblyDoc">Сборка</param> /// <param name="actionForPart">Метод для детали</param> /// <param name="actionForAssembly">Метод для подсборок</param> public static void DoSmthForEachComponent(AssemblyDoc assemblyDoc, Action<ModelDoc2> actionForPart, Action<ModelDoc2> actionForAssembly) { object[] components = (object[])assemblyDoc.GetComponents(true); if (components.Length == 0) return; foreach (var item in components) { Component2 component = (Component2)item; ModelDoc2 model = component.IGetModelDoc(); if (model != null) { AssemblyDoc ad = model as AssemblyDoc; if (ad != null) { actionForAssembly(model); DoSmthForEachComponent(ad, actionForPart, actionForAssembly); continue; } PartDoc pd = model as PartDoc; if (pd != null) actionForPart(model); } } }
public AssemblyEventHandler(ModelDoc2 modDoc, SwAddin addin) : base(modDoc, addin) { doc = (AssemblyDoc)document; swModel = modDoc; swAddin = addin; }
/// <summary> /// Constructor /// </summary> /// <param name="iSwApp">Solidworks app</param> /// <param name="asm">The assembly document the export takes place in</param> public STLExporter(SldWorks iSwApp, AssemblyDoc asm) { this.iSwApp = iSwApp; this.asm = asm; saveUserPreferences(); setSTLExportPreferences(); }
public static AssemblyDom Build(AssemblyDoc asmDoc, Assembly asm, Func<MemberDom, bool> filterMembers, FindOptions findOptions) { var ret = new AssemblyDom { _name = asmDoc.Name, ReflectionAssembly = asm }; asmDoc.MergeWithReflection(asm, findOptions, out ret.ErrorUnboundTypes, out ret.ErrorUnboundMembers); ret.AllTypes = asmDoc.Types.Select(_ => TypeDom.Build(_, ret, filterMembers)).ToArray(); ret.FillNamespaces(); ret.FillNestedTypes(); return ret; }
public void TestFindHiddenComponens(string modelName, int expected) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; Assert.Equal(expected, Common.FindHiddenComponents(assyDoc.GetComponents(false)).Count); SwApp.CloseAllDocuments(true); }
protected override void SubscribeAssemblyEvents(AssemblyDoc assm) { assm.LoadFromStorageNotify += OnLoadFromStorageNotify; assm.LoadFromStorageStoreNotify += OnLoadFromStorageStoreNotify; assm.SaveToStorageStoreNotify += OnSaveToStorageStoreNotify; assm.SaveToStorageNotify += OnSaveToStorageNotify; SubscribeIdleEvent(); }
public void TestShowAllComponents(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; Common.ShowAllComponents(doc, new List <string>()); Assert.Equal(0, Common.FindHiddenComponents(assyDoc.GetComponents(false)).Count); SwApp.CloseAllDocuments(true); }
protected override void Command() { _Ass = MdlBase.eAssemblyDoc(); foreach (Component2 cp in ListeComposants) { Run(cp); } MdlBase.EditRebuild3(); }
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> /// action for specific type components /// </summary> /// <param name="doc">assemblydoc instance</param> /// <param name="action">action you need todo</param> /// <param name="documentTypes">the doc type whick define with type of <see cref="swDocumentTypes_e"/></param> /// <param name="topOnly"></param> public static void UsingAllComponents(this AssemblyDoc doc, Action <Component2> action, swDocumentTypes_e documentTypes, bool topOnly = false) { var comps = doc.GetComponents(topOnly) as Object[]; foreach (Component2 comp in comps) { if (comp.GetCompType() == documentTypes) { action(comp); } } }
public void TestGetCountNodeCollection(string modelName, int expected) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); Assert.Equal(expected, Common.GetCount(baseNode.Nodes)); SwApp.CloseAllDocuments(true); }
public static AssemblyDom Build(AssemblyDoc asmDoc, Assembly asm, Func <MemberDom, bool> filterMembers, FindOptions findOptions) { var ret = new AssemblyDom { _name = asmDoc.Name, ReflectionAssembly = asm }; asmDoc.MergeWithReflection(asm, findOptions, out ret.ErrorUnboundTypes, out ret.ErrorUnboundMembers); ret.AllTypes = asmDoc.Types.Select(_ => TypeDom.Build(_, ret, filterMembers)).ToArray(); ret.FillNamespaces(); ret.FillNestedTypes(); return(ret); }
/// <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); }
public static void Set_transparency(ModelDoc2 swModel, string name) { AssemblyDoc swAssembly = null; Component2 swComp = null; ModelDoc2 swCompDoc = null; bool boolstatus = false; try { if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { swModel.ClearSelection2(true); // boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0); // SelectionMgr SwSelMgr = swModel.SelectionManager; swAssembly = (AssemblyDoc)swModel; var Components = swAssembly.GetComponents(false); for (int i = 0; i < Components.Length; i++) { //swComp = swAssembly.GetComponentByName(name); swComp = Components[i]; if (swComp != null) { if (swComp.Name2.Contains(name)) { // MessageBox.Show(name); var vMatProps = swComp.MaterialPropertyValues; if (vMatProps == null) { swCompDoc = swComp.GetModelDoc(); if (swCompDoc == null) { return; } vMatProps = swCompDoc.MaterialPropertyValues; } vMatProps[7] = 1; //Transparency swComp.MaterialPropertyValues = vMatProps; swModel.ClearSelection2(true); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } }
public void TestSaveSWComponentsList(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; object[] componentObjs = assyDoc.GetComponents(false); List <Component2> components = componentObjs.Cast <Component2>().ToList(); List <byte[]> pids = Common.SaveSWComponents(doc, components); Assert.Equal(pids.Count, components.Count); SwApp.CloseAllDocuments(true); }
public void TestLoadSWComponentsList(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); List <Component2> components = Common.LoadSWComponents(doc, baseNode.Link.SWComponentPIDs); Assert.Equal(baseNode.Link.SWComponentPIDs.Count, components.Count); SwApp.CloseAllDocuments(true); }
protected override void UnsubscribeAssemblyEvents(AssemblyDoc assm) { assm.AddItemNotify -= OnAddItemNotify; assm.DeleteItemNotify -= OnDeleteItemNotify; assm.DeleteItemPreNotify -= OnDeleteItemPreNotify; if (m_DocHandler.App.IsVersionNewerOrEqual(SwVersion_e.Sw2016)) { assm.PreRenameItemNotify -= OnPreRenameItemNotify; } assm.RenameItemNotify -= OnRenameItemNotify; }
private void ExportButtonClick(object sender, EventArgs e) { swModelDoc = swApp.ActiveDoc; swModelDocExt = swModelDoc.Extension; swAssDoc = swApp.ActiveDoc as AssemblyDoc; swFeat = (Feature)swModelDoc.FirstFeature(); swFeatMgr = (FeatureManager)swModelDoc.FeatureManager; while ((swFeat != null)) { sFeatType = swFeat.GetTypeName(); if (sFeatType == "CommentsFolder") { swCommentFolder = (CommentFolder)swFeat.GetSpecificFeature2(); nbrComments = swCommentFolder.GetCommentCount(); vComments = (object[])swCommentFolder.GetComments(); for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); swModelDocExt.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "CoordinateSystem"); swModelDocExt.SaveAs("C:/Users/Izmar/Documents/vmpc_models/jan2018/stlexport/" + swComment.Text + ".STL", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, ref errors, ref warnings); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); } } // Get next feature in FeatureManager design tree swFeat = (Feature)swFeat.GetNextFeature(); } }
private void OnlyKeepNamedBody(string v, string s, AssemblyDoc assemblyDoc, Component2 sendToCustomerBodies, Component2 insertComponentSendtoCustomer, ref bool diff1) { //var tempswModel = (ModelDoc2)swModel; var swModel = (ModelDoc2)swApp.ActiveDoc; swModel.Extension.SelectByID2(v + "@" + s, "SOLIDBODY", 0, 0, 0, false, 0, null, 0); var myFeature = swModel.FeatureManager.InsertDeleteBody2(true); insertComponentSendtoCustomer.Select(false); assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); Feature theFeature; var tempPart = (ModelDoc2)sendToCustomerBodies.GetModelDoc2(); theFeature = (Feature)tempPart.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(); diff1 = 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(); theFeature = (Feature)tempPart.FeatureByPositionReverse(1); if (theFeature.Name.Contains("Join")) { b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); swModel.EditSuppress(); } } sendToCustomerBodies.Select(true); assemblyDoc.EditAssembly(); }
private void Contraindre(Feature plan, Face2 e) { AssemblyDoc Ass = MdlBase.eAssemblyDoc(); e.eSelectEntite(MdlBase); plan.eSelect(true); int longstatus = 0; 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.ClearSelection2(true); }
public void TestLoadSWComponentsLinkNode(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); List <string> problemLinks = new List <string>(); Common.LoadSWComponents(doc, baseNode, problemLinks); Assert.Empty(problemLinks); SwApp.CloseAllDocuments(true); }
public void TestLoadSWComponent(string modelName, byte[] pid) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); baseNode.Link.SWMainComponentPID = baseNode.Link.SWComponentPIDs[0]; Component2 component = Common.LoadSWComponent(doc, baseNode.Link.SWMainComponentPID); Assert.NotNull(component); SwApp.CloseAllDocuments(true); }
private void ExportToDXF(AssemblyDoc assembly) { Print("Fetching components..."); var itemExtractor = new AssemblyItemExtractor(assembly); itemExtractor.TopLevelOnly = false; var items = itemExtractor.GetItems(); Print("Found " + items.Count); Print(""); ExportToDXF(items); }
//Except for an exclusionary list, this shows all the components public static void ShowAllComponents(ModelDoc2 model, List <string> hiddenComponents) { AssemblyDoc assyDoc = (AssemblyDoc)model; List <Component2> componentsToShow = new List <Component2>(); object[] varComps = assyDoc.GetComponents(false); foreach (Component2 comp in varComps) { if (!hiddenComponents.Contains(comp.Name2)) { componentsToShow.Add(comp); } } ShowComponents(model, componentsToShow); }
public void TestSaveSWComponent(string modelName, string componentName, byte[] expected) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; Component2 component = assyDoc.GetComponentByName(componentName); Assert.NotNull(component); LinkNode baseNode = ConfigurationSerialization.LoadBaseNodeFromModel(doc, out bool abortProcess); Assert.False(abortProcess); baseNode.Link.SWMainComponent = component; byte[] pid = CommonSwOperations.SaveSWComponent(doc, baseNode.Link.SWMainComponent); Assert.NotNull(pid); Assert.Equal(expected.Length, pid.Length); SwApp.CloseAllDocuments(true); }
public void TestHideComponents(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; List <string> hiddenComponentNames = Common.FindHiddenComponents(assyDoc.GetComponents(false)); List <Component2> hiddenComponents = hiddenComponentNames.Select(name => assyDoc.GetComponentByName(name)).ToList(); Common.ShowAllComponents(doc, new List <string>()); Common.HideComponents(doc, hiddenComponents); List <string> hiddenComponentNames2 = Common.FindHiddenComponents(assyDoc.GetComponents(false)); Assert.Equal(hiddenComponentNames.Count, hiddenComponentNames2.Count); SwApp.CloseAllDocuments(true); }
public string CreateNewJoinPart(AssemblyDoc assemblyDoc, Component2 insertComponentSendtoCustomer, Component2 insertComponentLocal, ModelDoc2 swModel, string partname, out Component2 returnpart) { Component2 sendToCustomerBodies = default(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()) + "\\" + partname; 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); returnpart = sendToCustomerBodies; return(sendToCustomerBodies.GetSelectByIDString()); }
public static void createSWAssembly() { swApp = SolidWorksSingleton.swApp; //create a assembly swAssy = swApp.INewAssembly(); //activate assembly swModel = swApp.ActiveDoc; assignAssyProperties(); createPartNumber(2); //Save the assy under a specific number swModel.SaveAs(saveName); }
/// <summary> /// Convert ModelDoc2 to AssemblyDoc and resolve all light weight components /// </summary> /// <param name="document"></param> /// <returns></returns> public static AssemblyDoc ToAssemblyDocument(ModelDoc2 document) { swComponentResolveStatus_e res = swComponentResolveStatus_e.swResolveOk; AssemblyDoc swAsm = null; if ((int)swDocumentTypes_e.swDocASSEMBLY == document.GetType()) { swAsm = (AssemblyDoc)document; //res = (swComponentResolveStatus_e)swAsm.ResolveAllLightWeightComponents(false); //MessageObserver.Instance.SetMessage("Resolve All LightWeight Components: code {" + res + "}"); } else { MessageBox.Show("Unable to cast SolidWorksDocument to AssemblyDoc type, cause it's paart. " + document.GetTitle()); } return(swAsm); }
public void SaveAs() { IModelDoc2 modDoc = (IModelDoc2)iSwApp.ActiveDoc; ModelDocExtension mDocExten; IModelDoc2 swModel; AssemblyDoc asmDoc = (AssemblyDoc)modDoc; SelectionMgr selectionMgr = modDoc.SelectionManager; Component2 component; string path; string recentPath; int errors = 0; int warnings = 0; recentPath = iSwApp.GetRecentFiles()[0].Substring(0, modDoc.GetPathName().LastIndexOf("\\")); int looptime = selectionMgr.GetSelectedObjectCount2(-1); while (looptime >= 1) { try { looptime--; component = selectionMgr.GetSelectedObject6(looptime + 1, -1); swModel = (IModelDoc2)component.GetModelDoc2(); mDocExten = swModel.Extension; //todo:校核是否是零件类,现在是直接抛出 //另存为对话框 SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "另存为"; sfd.InitialDirectory = recentPath;//更改为最近使用 sfd.Filter = "零件| *.sldprt"; sfd.ShowDialog(); path = sfd.FileName; if (path == "") { return; } //另存为新零件 mDocExten.SaveAs(path, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //替换现有零件 asmDoc.ReplaceComponents(path, "", false, true); } catch { } } }
public FrmEdge(SwAddin swAddin) { InitializeComponent(); _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; pbEdge11.Image = null; pbEdge12.Image = null; pbEdge21.Image = null; pbEdge22.Image = null; NewSelection(); Show(); }
public void InitAndRunSwApp() { // инициализация объекта приложения Solidworks swApp = new SldWorks(); int error = 0; int warning = 0; // открытие документа сборки муфты // для локальной сборки // assemblyPath = ProjectDocument.workPath + ProjectDocument.asmName; swModel = swApp.OpenDoc6(assemblyPath, (int)swDocumentTypes_e.swDocASSEMBLY, 0, "", ref error, ref warning); assembly = swModel as AssemblyDoc; IModelView myModelView = swModel.ActiveView; myModelView.FrameState = (int)swWindowState_e.swWindowMaximized; }
public void Main() { ModelDoc2 swDoc = null; PartDoc swPart = null; DrawingDoc swDrawing = null; AssemblyDoc swAssembly = null; bool boolstatus = false; int longstatus = 0; int longwarnings = 0; // // New Document double swSheetWidth; swSheetWidth = 0; double swSheetHeight; swSheetHeight = 0; swDoc = ((ModelDoc2)(swApp.NewDocument("D:\\Program Files\\SolidWorks Corp\\SOLIDWORKS (2)\\lang\\chinese\\Tutorial\\part.prtdot" + "", 0, swSheetWidth, swSheetHeight))); swPart = swDoc; swApp.ActivateDoc2("Part1", false, ref longstatus); swDoc = ((ModelDoc2)(swApp.ActiveDoc)); ModelView myModelView = null; myModelView = ((ModelView)(swDoc.ActiveView)); myModelView.FrameState = ((int)(swWindowState_e.swWindowMaximized)); swDoc.SketchManager.InsertSketch(true); boolstatus = swDoc.Extension.SelectByID2("Front", "PLANE", -0.068230578696965388, 0.046649779711848, 0.0043111746054159822, false, 0, null, 0); swDoc.ClearSelection2(true); boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstToRectEntity)), ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), false); boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstLineDiagonalType)), ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), true); Array vSkLines = null; vSkLines = ((Array)(swDoc.SketchManager.CreateCornerRectangle(-0.05212005640233669, 0.022239709930839985, 0, 0.043660780232323892, -0.038612502517961472, 0))); swDoc.ClearSelection2(true); swDoc.SketchManager.InsertSketch(true); // // Named View swDoc.ShowNamedView2("*Trimetric", 8); swDoc.ViewZoomtofit2(); Feature myFeature = null; myFeature = ((Feature)(swDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.025, 0.01, false, false, false, false, 0.017453292519943334, 0.017453292519943334, false, false, false, false, true, true, true, 0, 0, false))); swDoc.ISelectionManager.EnableContourSelection = false; }
//Actualizar el tipo de documento y castear el tipo al swDoc correcto public void updateSwDoc() { //Crear objetos swDoc if (SwModel.GetType() == (int)swDocumentTypes_e.swDocPART) { swPart = (PartDoc)SwModel; } else if (SwModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { swAssy = (AssemblyDoc)SwModel; } else if (SwModel.GetType() == (int)swDocumentTypes_e.swDocDRAWING) { swDraw = (DrawingDoc)SwModel; } subToSelectionListeners(); }
/// <summary> /// Convert ModelDoc2 to AssemblyDoc and resolve all light weight components /// </summary> /// <param name="document"></param> /// <returns></returns> public static AssemblyDoc ToAssemblyDocument(ModelDoc2 document) { AssemblyDoc swAsm = null; try { if ((int)swDocumentTypes_e.swDocASSEMBLY == document.GetType()) { swAsm = (AssemblyDoc)document; swAsm.ResolveAllLightWeightComponents(false); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); throw; } return(swAsm); }
public FrmSetParameters(SwAddin swAddin) { InitializeComponent(); bitmap = Properties.Resources.Brush; tabMain.AutoSize = true; KeyDown += FormKeyDown; _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; _swAsmDoc.AddItemNotify += AddNewItem; tabMain.Selected += TabMainTabSelected; tabMain.SelectedIndexChanged += TabMainSelectedIndexChanged; if (!Properties.Settings.Default.SetParentWindow) TopMost = true; Show(); NewSelection(); }
/// <summary> /// Creates a new joint /// </summary> /// <param name="path">Path to this joint in the StorageModel</param> /// <param name="owner">The Link that owns this joint (child Link in the joint)</param> public Joint(string path, Link parent, Link child) { this.swApp = RobotInfo.SwApp; this.asmDoc = RobotInfo.AssemDoc; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; this.robot = RobotInfo.Robot; this.Parent = parent; Parent.ChildJoints.Add(this); this.Child = child; this.Selected = false; this.Type = JointFactory.DefaultJointType; RobotInfo.WriteToLogFile("Getting Joint Specifics (Joint)"); jointSpecifics = JointFactory.GetSpecificJoint(Type,path,this); RobotInfo.WriteToLogFile("Successfully created Joint Specifics (Joint)"); if (swData.GetDouble(path) == 0) { swData.SetDouble(path, 1); } }
/// <summary> /// Выполняет метод для компонентов сборки (подсборки и детали) /// </summary> /// <param name="assemblyDoc">Сборка</param> /// <param name="actionForPart">Метод для компонентов</param> public static void DoSmthForEachComponent(AssemblyDoc assemblyDoc, Action<ModelDoc2> action) { DoSmthForEachComponent(assemblyDoc, action, action); }
/// <summary> /// Loads a joint that has already been created /// </summary> /// <param name="swApp">Solidworks app</param> /// <param name="asm">Assembly document this joint and its robot belong to</param> /// <param name="swData">StorageModel that this joint is tored in</param> /// <param name="path">Path to this joint in the StorageModel</param> /// <param name="robot">The Robot model that the joint is in</param> public Joint(string path) { this.swApp = RobotInfo.SwApp; this.asmDoc = RobotInfo.AssemDoc; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; this.robot = RobotInfo.Robot; this.Parent = robot.GetLink(parentId); Parent.ChildJoints.Add(this); this.Child = robot.GetLink(childId); this.Selected = false; if(this.Type == null || this.Type.Equals("")) this.Type = JointFactory.DefaultJointType; RobotInfo.WriteToLogFile("Loading existing joint (Joint)"); jointSpecifics = JointFactory.GetSpecificJoint(Type, path, this); if (swData.GetDouble(path) == 0) { swData.SetDouble(path, 1); } }
/// <summary> /// Creates a new link belonging to the given assembly /// </summary> /// <param name="swApp">The Solidworks App</param> /// <param name="asm"> The assembly that this Link is in</param> /// <param name="swData"> The Storage model that this Link is stored in </param> /// <param name="path"> The path to the StorageModel location of this link </param> /// <param name="baseLink"> Whether this Link is the base link of the model or not </param> public Link(String path, int id) { this.Selected = false; this.asmDoc = RobotInfo.AssemDoc; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; this.swApp = RobotInfo.SwApp; this.Id = id; this.robot = RobotInfo.Robot; attachments = new List<Attachment>(); ParentJoints = new List<Joint>(); ChildJoints = new List<Joint>(); nextAttachmentNum = 0; nextJointNum = 0; isBaseLink = false; if (swData.GetDouble(path) == 0) { swData.SetDouble(path, 1); Name = "NewLink"; this.color = DefaultColors[0]; } attachmentNums = new DoubleStorageArray(swData, path + "/attachmentNums"); parentJointNums = new DoubleStorageArray(swData, path + "/jointNums"); ModelConfiguration physical = new ModelConfiguration(path + "/physicalComps", (int)ModelConfiguration.ModelConfigType.Physical,this); ModelConfiguration visual = new ModelConfiguration(path + "/visualComps", (int)ModelConfiguration.ModelConfigType.Visual,this); ModelConfiguration collision = new ModelConfiguration(path + "/collisionComps", (int)ModelConfiguration.ModelConfigType.Collision,this); LinkModels = new ModelConfiguration[] { physical, visual, collision }; }
/// <summary> /// Constructor for setting up the link property manager page /// </summary> /// <param name="robot">The robot model</param> /// <param name="link">The link that will be edited</param> /// <param name="document">Active assembly document</param> /// <param name="swApp">The solidworks app</param> public LinkPMPage(RobotModel robot, AssemblyDoc document, SldWorks swApp, int type) { //Validate parameters if (robot == null) throw new ProgramErrorException("Tried to create a LinkEditorPMPage with a null robot model."); if (document == null) throw new ProgramErrorException("Tried to create a LinkEditorPMPage with a null assembly document."); if (swApp == null) throw new ProgramErrorException("Tried to create a LinkEditorPMPage with a null solidworks application interface."); //Initialize fields this.robot = robot; this.swApp = swApp; this.linksColored = false; currentModelConfig = type; //AssemblyDoc inherits ModelDoc2 but the relationship dosn't carry through the COM interface //Having two fields prevents having to cast half of the time modelDoc = (ModelDoc2)document; assemblyDoc = document; //Setup the page, its controls and their visual layout SetupPage(); }
/// <summary> /// Méthode interne. /// Initialiser l'objet eAssemblage. /// </summary> /// <param name="Modele"></param> /// <returns></returns> internal Boolean Init(eModele Modele) { Log.Methode(cNOMCLASSE); if ((Modele != null) && Modele.EstInitialise && (Modele.TypeDuModele == TypeFichier_e.cAssemblage)) { Log.Message(Modele.FichierSw.Chemin); _Modele = Modele; _SwAssemblage = Modele.SwModele as AssemblyDoc; _EstInitialise = true; } else { Log.Message("!!!!! Erreur d'initialisation"); } return _EstInitialise; }
/// <summary> /// Hook up events for the assembly context. /// </summary> /// <param name="md">A ModelDoc2 object.</param> private void ConnectAssemblyEvents(ModelDoc2 md) { if ((md.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) && !AssmEventsAssigned) { ad = (AssemblyDoc)md; ad.UserSelectionPreNotify += ad_UserSelectionPreNotify; // user clicks part/subassembly ad.UserSelectionPostNotify += ad_UserSelectionPostNotify; // doc closing, I think. ad.DestroyNotify2 += ad_DestroyNotify2; // Not sure, and not implemented yet. ad.ActiveDisplayStateChangePostNotify += ad_ActiveDisplayStateChangePostNotify; // switching docs ad.ActiveViewChangeNotify += ad_ActiveViewChangeNotify; DisconnectDrawingEvents(); AssmEventsAssigned = true; } else { // We're already set up, I guess. } }
public AssemblyEventHandler(ModelDoc2 modDoc, SwAddin addin) : base(modDoc, addin) { _doc = (AssemblyDoc)Document; }
/// <summary> /// Constructer /// </summary> /// <param name="robot">Robot model to be used for export</param> /// <param name="iSwApp">The solidworks app</param> /// <param name="asm">The assembly document</param> public RobotExporter(RobotModel robot, SldWorks iSwApp, AssemblyDoc asm) { this.robot = robot; this.iSwApp = iSwApp; this.asm = asm; }
/// <summary> /// Sets the various properties of the current robot /// </summary> /// <param name="swApp">The solidworks application</param> /// <param name="asmDoc">The current assembly</param> /// <param name="swData">The current storage model</param> /// <param name="robot">the current robot</param> public static void SetProperties(SldWorks swApp, AssemblyDoc asmDoc, StorageModel swData, RobotModel robot) { SwApp = swApp; ModelDoc = (ModelDoc2)asmDoc; AssemDoc = asmDoc; SwData = swData; Robot = robot; mathUtil = SwApp.GetMathUtility(); }
/// <summary> /// Выполняет метод для каждой детали в сборке /// </summary> /// <param name="assemblyDoc">Сборка</param> /// <param name="actionForPart">Метод для детали</param> public static void DoSmthForEachPart(AssemblyDoc assemblyDoc, Action<ModelDoc2> actionForPart) { DoSmthForEachComponent(assemblyDoc, actionForPart, new Action<ModelDoc2>((ad) => { })); }
/// <summary> /// Constructor /// </summary> /// <param name="robot">Robot model to be exported</param> /// <param name="iSwApp">Solidworks app</param> /// <param name="asm">Assembly that the robot model is in</param> public URDFExporter(RobotModel robot, SldWorks iSwApp, AssemblyDoc asm) : base(robot, iSwApp, asm) { }
/// <summary> /// Loads a robot from an assembly document, if a robot dosn't already /// exist one will be created /// </summary> /// <param name="asm">Assembly document containing a robot model</param> /// <param name="swApp">Interface for interacting with Solidworks</param> public RobotModel(AssemblyDoc asm, SldWorks swApp) { RobotInfo.WriteToLogFile("Robot Created (Robot)"); var assembly = typeof(JointSpecifics).Assembly; Type[] types = assembly.GetTypes().Where( t => t.IsSubclassOf(typeof(JointSpecifics)) && !t.IsAbstract).ToArray(); foreach (Type t in types) { System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(t.TypeHandle); } RobotInfo.WriteToLogFile("Initialized JointTypes = " + String.Join(", ",JointFactory.GetTypesList()) + " (Robot)"); //Setup fields this.swApp = swApp; this.asmDoc = asm; this.modelDoc = (ModelDoc2)asm; swData = new StorageModel(modelDoc); Selected = false; RobotInfo.SetProperties(swApp, asmDoc, swData, this); RobotInfo.WriteToLogFile("Setup Fields Setup"); //If the robot data dosn't exist yet, create it with default values if (swData.GetDouble("robot") == 0) { swData.SetDouble("robot", 1); /*PhysicalConfig = "Default"; VisualConfig = "Default"; CollisionConfig = "Default";*/ Name = ((ModelDoc2)asm).GetTitle(); RobotInfo.WriteToLogFile("Robot Data created with Default Values"); } RobotInfo.WriteToLogFile("Robot Data created"); LinkNums = new DoubleStorageArray(swData, "robot/linkNums"); nextLinkNum = 0; RobotInfo.WriteToLogFile("LinkNums Storage Array Created"); Links = new Dictionary<int,Link>(); //Load link structure Link newLink; if (LinkNums.Count == 0) { LinkNums.AddItem(0); RobotInfo.WriteToLogFile("New Link added to LinkNums"); } Configuration currentConfig = modelDoc.ConfigurationManager.ActiveConfiguration; foreach (double d in LinkNums) { newLink = new Link("robot/link" + (int)d, (int)d); RobotInfo.WriteToLogFile("New Link Created"); Links.Add((int)d,newLink); if (d >= nextLinkNum) nextLinkNum = (int)d + 1; } Links[0].isBaseLink = true; foreach (Link l in Links.Values.ToArray()) { l.InitializeJoints(); l.InitializeAttachments(); } modelDoc.ShowConfiguration2(ConfigName); CalcAxisVectors(); CalcOrigin(); modelDoc.ShowConfiguration2(currentConfig.Name); }
public AssemblyEventHandler(ModelDoc2 modDoc, DimensionRecorder addin) : base(modDoc,addin) { doc = (AssemblyDoc)document; }
//Calculates the free degree of freedom (if exists), and then determines the location of the joint, the axis of rotation/translation, and the type of joint public void estimateGlobalJointFromComponents(AssemblyDoc assy, link parent, link child) { //Create the ref objects int R1Status, R2Status, L1Status, L2Status, R1DirStatus, R2DirStatus, DOFs; MathPoint RPoint1, RPoint2; MathVector RDir1, RDir2, LDir1, LDir2; // Surpress Limit Mates to properly find degrees of freedom. They don't work with the API call List<Mate2> limitMates = new List<Mate2>(); limitMates = suppressLimitMates(child.SWMainComponent); if (child.SWMainComponent != null) { // The wonderful undocumented API call I found to get the degrees of freedom in a joint. // https://forum.solidworks.com/thread/57414 int remainingDOFs = child.SWMainComponent.GetRemainingDOFs(out R1Status, out RPoint1, out R1DirStatus, out RDir1, out R2Status, out RPoint2, out R2DirStatus, out RDir2, out L1Status, out LDir1, out L2Status, out LDir2); DOFs = remainingDOFs; // Convert the gotten degrees of freedom to a joint type, origin and axis child.Joint.type = "fixed"; child.Joint.Origin.xyz = ops.getXYZ(child.SWMainComponent.Transform2); child.Joint.Origin.rpy = ops.getRPY(child.SWMainComponent.Transform2); if (DOFs == 0 && (R1Status + L1Status > 0)) { if (R1Status == 1) { child.Joint.type = "continuous"; child.Joint.Axis.xyz = RDir1.ArrayData; child.Joint.Origin.xyz = RPoint1.ArrayData; child.Joint.Origin.rpy = ops.getRPY(child.SWMainComponent.Transform2); moveOrigin(parent, child); } else if (L1Status == 1) { child.Joint.type = "prismatic"; child.Joint.Axis.xyz = LDir1.ArrayData; child.Joint.Origin.xyz = RPoint1.ArrayData; child.Joint.Origin.rpy = ops.getRPY(child.SWMainComponent.Transform2); moveOrigin(parent, child); } } ops.threshold(child.Joint.Origin.xyz, 0.00001); ops.threshold(child.Joint.Origin.rpy, 0.00001); unsuppressLimitMates(limitMates); if (limitMates.Count > 0) { addLimits(child.Joint, limitMates); } } }