NX二次开发集合
前言:
01. NX二次开发:获取部件族数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // Mandatory UF Includes 2 #include <uf.h> 3 #include <uf_object_types.h> 4 #include <uf_draw.h> 5 #include <uf_part.h> 6 #include <uf_ugmgr.h> 7 #include <uf_ui.h> 8 #include <uf_obj.h> 9 #include <uf_drf.h> 10 #include <uf_curve.h> 11 #include <uf_fam.h> 12 #include <uf_disp.h> 13 //------------------------------------------------------------------------------ 14 // Entry point(s) for unmanaged internal NXOpen C/C++ programs 15 //------------------------------------------------------------------------------ 16 extern "C" DllExport void ufusr(char *parm, int *returnCode, int rlen) 17 { 18 try 19 { 20 UF_CALL(UF_initialize()); 21 22 // 获取NXSession并初始化 23 NXOpen::Session *theSession = NXOpen::Session::GetSession(); 24 NXOpen::Part *displayPart(theSession->Parts()->Display()); 25 NXOpen::Part *workPart(theSession->Parts()->Work()); 26 NXOpen::UI *theUI = NXOpen::UI::GetUI(); 27 28 getPartFamilyData(workPart); 29 30 UF_CALL(UF_terminate()); 31 } 32 catch (const NXException& e1) 33 { 34 UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message()); 35 } 36 catch (const exception& e2) 37 { 38 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what()); 39 } 40 catch (...) 41 { 42 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception."); 43 } 44 } 45 46 void getPartFamilyData(Part* workPart) 47 { 48 tag_t part = workPart->Tag(); 49 logical is_template; 50 int fam_cnt, ii, jj; 51 char part_fspec[MAX_FSPEC_SIZE + 1]; 52 UF_FAM_family_data_t family_data; 53 54 UF_PART_ask_part_name(part, part_fspec); 55 UF_CALL(UF_PART_is_family_template(part, &is_template)); 56 57 std::vector<std::vector<std::string>> familyNameAndValues; 58 std::vector<std::string> familyAttrName, familyNameAndValue; 59 if (is_template) 60 { 61 int type, subtype; 62 char print_str[132]; 63 tag_t *fam_tags, fam_attr = NULL_TAG; 64 tag_t disp_part = UF_PART_ask_display_part(); 65 UF_FAM_member_data_t mem_data; 66 UF_FAM_attribute_data_t attr_data; 67 68 UF_UI_open_listing_window(); 69 70 UF_CALL(UF_PART_ask_families(part, &fam_cnt, &fam_tags)); 71 sprintf(print_str, "\n\nTag of family of %s: %d\n", part_fspec, fam_tags[0]); 72 UF_UI_write_listing_window(print_str); 73 74 UF_CALL(UF_FAM_ask_family_data(fam_tags[0], &family_data)); 75 sprintf(print_str, " Number of family members: %d\n\n", family_data.member_count); 76 UF_UI_write_listing_window(print_str); 77 78 while (!UF_CALL(UF_OBJ_cycle_objs_in_part(disp_part, UF_fam_attr_type, &fam_attr)) && (fam_attr != NULL_TAG)) 79 { 80 UF_CALL(UF_OBJ_ask_type_and_subtype(fam_attr, &type, &subtype)); 81 82 attr_data.subtype = UF_fam_attr_name_subtype; 83 attr_data.base_object = NULL_TAG; 84 85 UF_CALL(UF_FAM_ask_attribute_data(fam_attr, &attr_data)); 86 sprintf(print_str, "%-15s", attr_data.name); 87 UF_UI_write_listing_window(print_str); 88 familyAttrName.push_back(print_str); 89 } 90 91 UF_UI_write_listing_window("\n"); 92 UF_CALL(UF_FAM_free_attribute_data(&attr_data)); 93 for (ii = 0; ii < family_data.member_count; ii++) 94 { 95 UF_CALL(UF_FAM_ask_member_row_data(fam_tags[0], ii, &mem_data)); 96 for (jj = 0; jj < mem_data.value_count; jj++) 97 { 98 sprintf(print_str, "%-15s", mem_data.values[jj]); 99 UF_UI_write_listing_window(print_str); 100 familyNameAndValue.push_back(print_str); 101 } 102 UF_UI_write_listing_window("\n"); 103 familyNameAndValues.push_back(familyNameAndValue); 104 familyNameAndValue.clear(); 105 } 106 UF_free(fam_tags); 107 } 108 else 109 uc1601("Work part is not a template part", 1); 110 }
02. NX二次开发:导出图片到文件夹
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //================ 2 // NX二次开发:导出图片到文件夹 3 //================ 4 // 模型导出图片 5 bool exportModlPict(Session *theSession) 6 { 7 bool bFlag = false; 8 int errorCodes = UF_CALL(UF_DISP_create_image("E:\\1.png", UF_DISP_PNG, UF_DISP_WHITE)); 9 return bFlag; 10 } 11 12 bool exportModlPict(std::string& pngpath) 13 { 14 NXOpen::UI *theUI = NXOpen::UI::GetUI(); 15 NXOpen::Gateway::ImageExportBuilder *imageExportBuilder1 = theUI->CreateImageExportBuilder(); 16 17 imageExportBuilder1->SetRegionMode(false); 18 imageExportBuilder1->SetRegionWidth(1); 19 imageExportBuilder1->SetRegionHeight(1); 20 imageExportBuilder1->SetFileFormat(NXOpen::Gateway::ImageExportBuilder::FileFormatsPng); 21 imageExportBuilder1->SetFileName(NXOpen::NXString(std::string(pngpath), NXOpen::NXString::UTF8)); 22 imageExportBuilder1->SetBackgroundOption(NXOpen::Gateway::ImageExportBuilder::BackgroundOptionsOriginal); 23 imageExportBuilder1->SetEnhanceEdges(false); 24 25 NXOpen::NXObject *nXObject1 = imageExportBuilder1->Commit(); 26 imageExportBuilder1->Destroy(); 27 return true; 28 } 29 30 bool setModlViewLayout(Part *workPart) 31 { 32 NXOpen::Layout *layout1(dynamic_cast<NXOpen::Layout *>(workPart->Layouts()->FindObject("L1"))); 33 NXOpen::ModelingView *modelingView1(dynamic_cast<NXOpen::ModelingView *>(workPart->ModelingViews()->FindObject("Trimetric"))); 34 layout1->ReplaceView(workPart->ModelingViews()->WorkView(), modelingView1, true); 35 return true; 36 } 37 38 bool modlViewRotate(Part *workPart, double angle, double vecX, double vecY, double vecZ) 39 { 40 NXOpen::Point3d origin1(0.0, 0.0, 0.0); 41 NXOpen::Vector3d vector1(vecX, vecY, vecZ); 42 workPart->ModelingViews()->WorkView()->Rotate(origin1, vector1, angle); 43 return true; 44 } 45 46 void FindTreeFiles(std::string& modl_path, std::vector<std::string> &modl_paths, std::vector<std::string> &file_names) 47 { 48 intptr_t hFile = 0; 49 struct _finddata_t fileinfo; 50 string p; 51 if ((hFile = _findfirst(p.assign(modl_path).append("\\*.prt").c_str(), &fileinfo)) != -1) { 52 do 53 { 54 if ((fileinfo.attrib & _A_SUBDIR)){ 55 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) 56 FindTreeFiles(p.assign(modl_path).append("\\").append(fileinfo.name), modl_paths, file_names); 57 } 58 else{ 59 modl_paths.push_back(p.assign(modl_path).append("\\").append(fileinfo.name)); 60 std::string tempText = fileinfo.name; 61 file_names.push_back(tempText.substr(0, tempText.find_last_of("."))); 62 } 63 } while (_findnext(hFile, &fileinfo) == 0); 64 } 65 } 66 67 bool doExportModlPng(Session *theSession, Part *workPart, Part *displayPart) 68 { 69 std::string dllpath = "E:\\workspace\\export_modl_png"; 70 std::string modlpath = dllpath + "\\export_modl_dir"; 71 if (_access(modlpath.c_str(), 0) == -1){ 72 print(modlpath + " 模型文件夹路径不存在"); 73 return false; 74 } 75 76 // 导出图片文件夹路径 77 std::string export_png_dir = dllpath + "\\export_png_dir"; 78 if (_access(export_png_dir.c_str(), 0) == -1) 79 _mkdir(export_png_dir.c_str()); 80 81 // 获取模型文件夹路径下的prt文件 82 std::vector<std::string> modl_paths, file_names; 83 FindTreeFiles(modlpath, modl_paths, file_names); 84 if (modl_paths.empty()){ 85 print("模型文件夹路径下获取到的数量为0"); 86 return false; 87 } 88 89 for (size_t i = 0; i < modl_paths.size(); i++) 90 { 91 // openModl 92 tag_t partTAG = NULL_TAG; 93 std::string retError = ""; 94 openModl(modl_paths[i], partTAG, retError); 95 if (NULL_TAG == partTAG || retError == "Error") 96 continue; 97 98 theSession = NXOpen::Session::GetSession(); 99 displayPart = (theSession->Parts()->Display()); 100 workPart = (theSession->Parts()->Work()); 101 102 103 // 设置不显示左下角坐标系 104 workPart->Preferences()->ScreenVisualization()->SetTriadVisibility(false); 105 // 设置模型摆正到 Trimetric 106 setModlViewLayout(workPart); 107 // 第一次导出图片 108 exportModlPict(export_png_dir + "\\" + file_names[i] + string("_Trimetric.png")); 109 110 111 // F8摆正视图 112 workPart->ModelingViews()->WorkView()->SnapToClosestCannedOrientation(); 113 // 适合窗口 114 displayPart->ModelingViews()->WorkView()->Fit(); 115 // 第二次导出图片 116 exportModlPict(export_png_dir + "\\" + file_names[i] + string("_X.png")); 117 118 119 // 旋转一个角度 120 modlViewRotate(workPart, 90.0, 0.0, 0.0, 1.0); 121 // 适合窗口 122 displayPart->ModelingViews()->WorkView()->Fit(); 123 // 第三次导出图片 124 exportModlPict(export_png_dir + "\\" + file_names[i] + string("_Y.png")); 125 126 127 // 旋转一个角度 128 modlViewRotate(workPart, -90.0, 1.0, 0.0, 0.0); 129 // 适合窗口 130 displayPart->ModelingViews()->WorkView()->Fit(); 131 // 第四次导出图片 132 exportModlPict(export_png_dir + "\\" + file_names[i] + string("_Z.png")); 133 134 135 // closeModl 136 closeModl(partTAG); 137 } 138 139 return true; 140 } 141 142 143 //------------------------------------------------------------------------------ 144 // Entry point(s) for unmanaged internal NXOpen C/C++ programs 145 //------------------------------------------------------------------------------ 146 extern "C" DllExport void ufusr(char *parm, int *returnCode, int rlen) 147 { 148 try 149 { 150 UF_CALL(UF_initialize()); 151 152 // 获取NXSession并初始化 153 NXOpen::Session *theSession = NXOpen::Session::GetSession(); 154 NXOpen::Part *displayPart(theSession->Parts()->Display()); 155 NXOpen::Part *workPart(theSession->Parts()->Work()); 156 NXOpen::UI *theUI = NXOpen::UI::GetUI(); 157 158 doExportModlPng(theSession, workPart, displayPart); 159 160 UF_CALL(UF_terminate()); 161 } 162 catch (const NXException& e1) 163 { 164 UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message()); 165 } 166 catch (const exception& e2) 167 { 168 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what()); 169 } 170 catch (...) 171 { 172 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception."); 173 } 174 }
03. NX二次开发:遍历装配树结构和零件建模特征
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //=================================== 2 // 遍历装配结构 3 //=================================== 4 void getChildrenComponents(Assemblies::Component* rootComponent, std::vector<Assemblies::Component*> &childrenComponents, std::vector<NXString> &DisplayNames) 5 { 6 std::vector<NXOpen::Assemblies::Component *> childrens = rootComponent->GetChildren(); 7 for (size_t i = 0; i < childrens.size(); i++){ 8 indent_level++; 9 childrenComponents.push_back(childrens[i]); 10 11 std::string strText = ""; 12 for (size_t i = 0; i < indent_level; i++) 13 strText += " "; 14 15 DisplayNames.push_back(strText + childrens[i]->DisplayName().GetText()); 16 getChildrenComponents(childrens[i], childrenComponents, DisplayNames); 17 indent_level--; 18 } 19 } 20 // 判断是否是装配 21 bool IsAssemblyPart(Part* displayPart) 22 { 23 NXOpen::Assemblies::Component * rootComponent = displayPart->ComponentAssembly()->RootComponent(); 24 if (rootComponent){ 25 std::vector<NXOpen::Assemblies::Component *> childrens = rootComponent->GetChildren(); 26 return childrens.empty() ? false : true; 27 } 28 return false; 29 } 30 31 //------------------------------------------------------------------------------ 32 // Entry point(s) for unmanaged internal NXOpen C/C++ programs 33 //------------------------------------------------------------------------------ 34 extern "C" DllExport void ufusr(char *parm, int *returnCode, int rlen) 35 { 36 try 37 { 38 UF_CALL(UF_initialize()); 39 40 // 获取NXSession并初始化 41 NXOpen::Session *theSession = NXOpen::Session::GetSession(); 42 NXOpen::Part *displayPart(theSession->Parts()->Display()); 43 NXOpen::Part *workPart(theSession->Parts()->Work()); 44 NXOpen::UI *theUI = NXOpen::UI::GetUI(); 45 46 { 47 // 判断是否是装配,是装配则遍历装配树所有层级;非装配则获取部件所有建模特征;最后打印输出结果 48 if (IsAssemblyPart(displayPart)){ 49 // 遍历装配结构 50 std::vector<NXOpen::NXString> DisplayNames; 51 std::vector<NXOpen::Assemblies::Component*> childrenComponents; 52 NXOpen::Assemblies::Component * rootComponent = displayPart->ComponentAssembly()->RootComponent(); 53 childrenComponents.push_back(rootComponent); 54 DisplayNames.push_back(rootComponent->DisplayName()); 55 getChildrenComponents(rootComponent, childrenComponents, DisplayNames); 56 57 for (size_t i = 0; i < DisplayNames.size(); i++) 58 print(DisplayNames[i]); 59 } 60 else 61 { 62 // 获取所有特征 63 NXOpen::Features::FeatureCollection *features = displayPart->Features(); 64 Features::FeatureCollection::iterator itr = features->begin(); 65 for (; itr != features->end(); itr++) 66 { 67 print((*itr)->FeatureType()); 68 print((*itr)->GetFeatureName()); 69 std::string strText = (*itr)->FeatureType().GetText(); 70 } 71 } 72 } 73 UF_CALL(UF_terminate()); 74 } 75 catch (const NXException& e1) 76 { 77 UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message()); 78 } 79 catch (const exception& e2) 80 { 81 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what()); 82 } 83 catch (...) 84 { 85 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception."); 86 } 87 }
04. NX二次开发:克隆本地模型到Teamcenter
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //================ 2 // NX二次开发:克隆本地模型到Teamcenter 3 //================ 4 5 #pragma warning(disable:4996) 6 7 static void ECHO(char *format, ...) 8 { 9 char msg[UF_UI_MAX_STRING_LEN + 1]; 10 va_list args; 11 va_start(args, format); 12 vsprintf(msg, format, args); 13 va_end(args); 14 UF_UI_open_listing_window(); 15 UF_UI_write_listing_window(msg); 16 UF_print_syslog(msg, FALSE); 17 } 18 #define WRITE_S(X) (write_string_to_listing_window(#X, X)) 19 void build_temp_filespec(char *fspec, int ftype, char *new_spec); 20 21 #define UF_CALLI(X) (report_error1( __FILE__, __LINE__, #X, (X))) 22 static int report_error1(char *file, int line, char *call, int irc) 23 { 24 if (irc) 25 { 26 char err[133]; 27 28 UF_get_fail_message(irc, err); 29 ECHO("*** ERROR code %d at line %d in %s:\n", 30 irc, line, file); 31 ECHO("+++ %s\n", err); 32 ECHO("%s;\n", call); 33 } 34 35 return(irc); 36 } 37 38 static void write_string_to_listing_window(char *title, const char *string) 39 { 40 if (string != NULL) 41 ECHO("%s = \"%s\"\n", title, string); 42 else 43 ECHO("%s = NULL\n", title); 44 } 45 46 void build_temp_filespec(char *fspec, int ftype, char *new_spec) 47 { 48 char *tmp_dir; 49 UF_CALLI(UF_translate_variable("UGII_TMP_DIR", &tmp_dir)); 50 UF_CALLI(uc4575(tmp_dir, ftype, fspec, new_spec)); 51 } 52 53 void doClonePart() 54 { 55 UF_UGMGR_initialize(0, NULL); 56 57 logical isActive; 58 UF_is_ugmanager_active(&isActive); 59 if (isActive){ 60 int _ErrorCode = 0; 61 UF_CALLI(UF_CLONE_initialise(UF_CLONE_import_operation)); 62 UF_CALLI(UF_CLONE_set_def_action(UF_CLONE_use_existing)); 63 UF_CALLI(UF_CLONE_set_def_assoc_file_copy(FALSE)); 64 65 char clone_log[MAX_FSPEC_SIZE + 1]; 66 build_temp_filespec("Clone_Existing_Import", 47, clone_log); 67 UF_CALLI(UF_CLONE_set_logfile(clone_log)); 68 WRITE_S(clone_log); 69 uc4561(clone_log, 0); 70 71 char *itemId = "E:\\03_NXModl\\0000000025.prt"; 72 UF_CALLI(UF_CLONE_set_def_item_type("A2_hwpart")); 73 _ErrorCode = UF_CALLI(UF_CLONE_add_part(itemId)); 74 if (_ErrorCode) 75 return; 76 77 int num; 78 char part_number[133] = { "" }; 79 _ErrorCode = uc1600("title", part_number, &num); 80 switch (_ErrorCode) 81 { 82 case 1: 83 print("back"); 84 break; 85 case 2: 86 print("cancel"); 87 break; 88 case 3: 89 print("OK"); 90 break; 91 case 5: 92 print("Data entered"); 93 break; 94 case 8: 95 print("Disallowed status"); 96 break; 97 default: 98 break; 99 } 100 char encoded_name[MAX_FSPEC_BUFSIZE]; 101 _ErrorCode = UF_CALLI(UF_UGMGR_encode_part_filename(part_number, "00", NULL, NULL, encoded_name)); 102 if (_ErrorCode) 103 return; 104 WRITE_S(encoded_name); 105 106 UF_CLONE_naming_failures_t name_fails; 107 UF_CALLI(UF_CLONE_set_naming(itemId, UF_CLONE_user_name, encoded_name)); 108 UF_CALLI(UF_CLONE_init_naming_failures(&name_fails)); 109 UF_CALLI(UF_CLONE_perform_clone(&name_fails)); 110 111 UF_CALLI(UF_CLONE_terminate()); 112 } 113 114 UF_UGMGR_terminate(); 115 } 116 117 118 //------------------------------------------------------------------------------ 119 // Entry point(s) for unmanaged internal NXOpen C/C++ programs 120 //------------------------------------------------------------------------------ 121 extern "C" DllExport void ufusr(char *parm, int *returnCode, int rlen) 122 { 123 try 124 { 125 UF_CALL(UF_initialize()); 126 127 // 获取NXSession并初始化 128 NXOpen::Session *theSession = NXOpen::Session::GetSession(); 129 NXOpen::Part *displayPart(theSession->Parts()->Display()); 130 NXOpen::Part *workPart(theSession->Parts()->Work()); 131 NXOpen::UI *theUI = NXOpen::UI::GetUI(); 132 133 doClonePart(); 134 135 UF_CALL(UF_terminate()); 136 } 137 catch (const NXException& e1) 138 { 139 UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message()); 140 } 141 catch (const exception& e2) 142 { 143 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what()); 144 } 145 catch (...) 146 { 147 UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception."); 148 } 149 }
05. NX二次开发:
06. NX二次开发:
07. NX二次开发:
08. NX二次开发:
09. NX二次开发:
10. NX二次开发:
11. NX二次开发:
12. NX二次开发:
13. NX二次开发:
14. NX二次开发:
15. NX二次开发:
16. NX二次开发:
17. NX二次开发:
18. NX二次开发:
19. NX二次开发:
20. NX二次开发:
21. NX二次开发: