注释转换(C->C++)

注释转换
一、定义:注释转换就是将代码中的注释转换为同一类,比如是 C 语言 或者C++ .
                  C语言中,编译器默认的注释风格是    /*  .........*/   
                  C++中,编译器默认的注释风格是  // ....... (注释一行)
二、注释转换关系如下图:
  

三、注释转换代码如下:

--------------------------------------------------头文件.h------------------------------------------------------------------

#pragma once
#ifndef __COMMENT_CONVERT_H__
#define __COMMENT_CONVERT_H__

#include <stdio.h>
#include <stdlib.h>


enum State
{
	NUL_STATE,
	C_STATE,
	CPP_STATE,
	END_STATE
};
// pfin表示的是要读取的文件 ,pfout表示转换后输出的文件 
void DoCommentConvert(FILE*pfIn, FILE*pfOut);//执行转换函数 
void DoNulState(FILE*pfIn, FILE*pfOut, enum State* ps);//无状态转换	
void DoCState(FILE*pfIn, FILE*pfOut, enum State* ps);//C状态转换	
void DoCppState(FILE*pfIn, FILE*pfOut, enum State* ps);//CPP状态转换

#endif //__COMMENT_CONVERT_H__

------------------------------------------------源文件.c----------------------------------------------------------------------

#define  _CRT_SECURE_NO_WARNINGS   
#include "DoCommentConvert.h"  
void DoCommentConvert(FILE*pfIn, FILE*pfOut)
{
	enum State state = NUL_STATE;//初始状态为未知状态
	while (state != END_STATE)//代码为结束状态时跳出循环
	{
		switch (state)
		{
		case NUL_STATE://未知状态
			DoNulState(pfIn, pfOut, &state);
			break;
		case C_STATE://C状态
			DoCState(pfIn, pfOut, &state);
			break;
		case CPP_STATE://C++状态
			DoCppState(pfIn, pfOut, &state);
			break;
		default:
			break;
		}
	}
}
void DoNulState(FILE*pfIn, FILE*pfOut, enum State* ps)//无状态转换	
{
	int first = 0;
	int second = 0;
	first = fgetc(pfIn);//从文件中读取一个字符来判断
	switch (first)
	{
	case '/':
	{
		second = fgetc(pfIn);//再读取一个字符
		switch (second)
		{
		case '*'://   “/*”表示进入C状态
		{
			fputc('/', pfOut);
			fputc('/', pfOut);
			//将注释转换为C++并输出到文件
			*ps = C_STATE;//未知状态转化为C状态
		}
		case '/'://    “//”表示进入C++状态
		{
			fputc(first, pfOut);
			fputc(second, pfOut);
			*ps = CPP_STATE;//将未知状态转化为C++状态
		}
			break;
		default://表示这个'/'是字符
		{
			fputc(first, pfOut);//将读取到的字符输出到文件
			fputc(second, pfOut);
		}
			break;
		}
	}
		break;
	case EOF://代码结束
	{
		fputc(first, pfOut);//将EOF输出到文件
		*ps = END_STATE;//状态改为结束状态
	}
		break;
	default:                     //状态不变,正常输出
	{
		fputc(first, pfOut);//将读取的字符输出到文件
	}
	break;
	}
}
void DoCState(FILE*pfIn, FILE*pfOut, enum State* ps)//C状态转换	
{
	int first = 0;
	int second = 0;
	int third = 0;
	first = fgetc(pfIn);//从文件中读取一个字符来判断
	switch (first)
	{
	case '*':
		second = fgetc(pfIn);//再读取一个字符
		switch (second)
		{
		case '/'://  “*/”表示C注释结束  但要判断之后是不是'\n',因为C++注释是以换行结束的
		{
			third = fgetc(pfIn);
			if (third == '\n')
			{
				fputc(third, pfOut);
			}
			else  
			{
				fputc('\n', pfOut);//如果之后不是'\n', 需要帮它换行
				ungetc(third, pfIn);//并且要将用来判断的字符从读取流中的撤销,防止下次判断时  少判断一个字符  
			}
			*ps = NUL_STATE;//状态转换为未知状态
		}
			break;
		default:
		{
			fputc(first, pfOut);
			ungetc(second, pfIn);//将多余用来判断的字符撤销
		}
			break;
		}

		break;
	case '\n'://换行之后要加上 // 因为C++只注释能一行  
	{
		fputc(first, pfOut);
		fputc('/', pfOut);
		fputc('/', pfOut);
	}
	default:
	{
		fputc(first, pfOut);//将读取的字符输出到文件
	}
		break;
	}
}
void DoCppState(FILE*pfIn, FILE*pfOut, enum State* ps)//CPP状态转换
{
	int first = 0;
	int second = 0;
	int third = 0;
	first = fgetc(pfIn);
	switch (first)
	{
	case '\n':// 表示C++一行注释结束
	{
		fputc(first, pfOut);
		*ps = NUL_STATE;
	}
	break;
	default:
	{
		fputc(first, pfOut);
	}
		break;
	}
}

-------------------------------------------------测试代码test.c----------------------------------------------------------------


#define  _CRT_SECURE_NO_WARNINGS   
#include"DoCommentConvert.h"
int main()
{
	FILE *pfIn = NULL;//定义两文件指针
	FILE *pfOut = NULL;
	pfIn = fopen("input.c", "r");//打开读取的文件
	if(pfIn == NULL)
	{
		perror("open file for input:");
		exit(EXIT_FAILURE);//读取失败
	}
	pfOut = fopen("outpur.c", "w");//打开写入的文件
	if (pfOut == NULL)
	{
		perror("open file for output");
		exit(EXIT_FAILURE);//读取失败
	}
	DoCommentConvert(pfIn,pfOut);//注释转换
	printf("转换成功\n");
	fclose(pfIn);
	fclose(pfOut);
	system("pause");
	return 0;
}

 
//RuledFaces // Std C++ Includes #include <iostream> #include <sstream> #include <algorithm> #include <fstream> #include "RuledFaces.h" using namespace NXOpen; using namespace std; //ofstream fout("D:\\D:\NXopen\BaiduSyncdisk\studio\zhinengguodu\\res.txt"); //============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\FXM\Documents\nx_customized\23-RuledFaces\RuledFaces.cpp // // This file was generated by the NX Block UI Styler // Created by: MIC-明 // Version: NX 2212 // Date: 07-17-2025 (Format: mm-dd-yyyy) // Time: 14:33 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C++ source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session* (RuledFaces::theSession) = NULL; UI* (RuledFaces::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ RuledFaces::RuledFaces() { try { // Initialize the NX Open C++ API environment RuledFaces::theSession = NXOpen::Session::GetSession(); RuledFaces::theUI = UI::GetUI(); workPart = theSession->Parts()->Work(); mb = theUI->NXMessageBox(); lw = theSession->ListingWindow(); lf = theSession->LogFile(); theDlxFileName = "RuledFaces.dlx"; theDialog = RuledFaces::theUI->CreateDialog(theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &RuledFaces::apply_cb)); theDialog->AddOkHandler(make_callback(this, &RuledFaces::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &RuledFaces::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &RuledFaces::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &RuledFaces::dialogShown_cb)); } catch (exception& ex) { //---- Enter your exception handling code here ----- throw; } } //------------------------------------------------------------------------------ // Destructor for NX Styler class //------------------------------------------------------------------------------ RuledFaces::~RuledFaces() { if (theDialog != NULL) { delete theDialog; theDialog = NULL; } } //------------------------------------------------------------------------------ // Print string to listing window or stdout //------------------------------------------------------------------------------ void RuledFaces::print(const NXString& msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } void RuledFaces::print(const string& msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } void RuledFaces::print(const char* msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char* param, int* retcod, int param_len) { RuledFaces* theRuledFaces = NULL; try { theRuledFaces = new RuledFaces(); // The following method shows the dialog immediately theRuledFaces->Launch(); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if (theRuledFaces != NULL) { delete theRuledFaces; theRuledFaces = NULL; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- Enter your callback code here ----- } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //This method launches the dialog to screen //------------------------------------------------------------------------------ NXOpen::BlockStyler::BlockDialog::DialogResponse RuledFaces::Launch() { NXOpen::BlockStyler::BlockDialog::DialogResponse dialogResponse = NXOpen::BlockStyler::BlockDialog::DialogResponse::DialogResponseInvalid; try { dialogResponse = theDialog->Launch(); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return dialogResponse; } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ void RuledFaces::initialize_cb() { try { group0 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group0")); colorPicker0 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker0")); colorPicker01 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker01")); bodySelect0 = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("bodySelect0")); separator0 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator0")); group = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group")); face_select0 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select0")); face_select01 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select01")); separator01 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator01")); colorPicker02 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker02")); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any value set //here will take precedence and dialog will be launched showing that value. //------------------------------------------------------------------------------ void RuledFaces::dialogShown_cb() { try { //---- Enter your callback code here ----- group->SetEnable(false); group->SetShow(false); face_select0->SetEnable(false); face_select0->SetShow(false); face_select01->SetEnable(false); face_select01->SetShow(false); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ int RuledFaces::apply_cb() { int errorCode = 0; try { //---- Enter your callback code here ----- NXOpen::Session::UndoMarkId markId1; markId1 = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "RuledFaces"); do_it(); } catch (exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ int RuledFaces::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { if (block == colorPicker0) { //---------Enter your code here----------- } else if (block == colorPicker01) { //---------Enter your code here----------- } else if (block == bodySelect0) { //---------Enter your code here----------- } else if (block == separator0) { //---------Enter your code here----------- } else if (block == face_select0) { //---------Enter your code here----------- } else if (block == face_select01) { //---------Enter your code here----------- } else if (block == separator01) { //---------Enter your code here----------- } else if (block == colorPicker02) { //---------Enter your code here----------- } } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ int RuledFaces::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); } catch (exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Description: Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ PropertyList* RuledFaces::GetBlockProperties(const char* blockID) { return theDialog->GetBlockProperties(blockID); } bool RuledFaces::isEqualXY(const Point3d& a1, const Point3d& a2, const Point3d& b1, const Point3d& b2, double eps = 1e-3) { auto equalXY = [&](const Point3d& p1, const Point3d& p2) { return std::fabs(p1.X - p2.X) < eps && std::fabs(p1.Y - p2.Y) < eps; }; return (equalXY(a1, b1) && equalXY(a2, b2)) || (equalXY(a1, b2) && equalXY(a2, b1)); } Features::Ruled* RuledFaces::doCreateRuledFace(Edge* edge1, Edge* edge2) { NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); NXOpen::Features::RuledBuilder* ruledBuilder1; ruledBuilder1 = workPart->Features()->CreateRuledBuilder(nullNXOpen_Features_Feature); ruledBuilder1->SetPositionTolerance(0.001); ruledBuilder1->SetShapePreserved(false); ruledBuilder1->FirstSection()->SetDistanceTolerance(0.001); ruledBuilder1->FirstSection()->SetChainingTolerance(0.00095); ruledBuilder1->SecondSection()->SetDistanceTolerance(0.001); ruledBuilder1->SecondSection()->SetChainingTolerance(0.00095); ruledBuilder1->AlignmentMethod()->AlignCurve()->SetDistanceTolerance(0.001); ruledBuilder1->AlignmentMethod()->AlignCurve()->SetChainingTolerance(0.00095); ruledBuilder1->FirstSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesCurvesAndPoints); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); std::vector<NXOpen::Edge*> edges1(1); edges1[0] = edge1; NXOpen::EdgeDumbRule* edgeDumbRule1; edgeDumbRule1 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges1, selectionIntentRuleOptions1); ruledBuilder1->FirstSection()->AllowSelfIntersection(true); ruledBuilder1->FirstSection()->AllowDegenerateCurves(false); std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = edgeDumbRule1; NXOpen::NXObject* nullNXOpen_NXObject(NULL); NXOpen::Point3d helpPoint1(0, 0, 0); ruledBuilder1->FirstSection()->AddToSection(rules1, edge1, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint1, NXOpen::Section::ModeCreate, false); ruledBuilder1->SecondSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesOnlyCurves); std::vector<NXOpen::Edge*> edges2(1); edges2[0] = edge2; NXOpen::EdgeDumbRule* edgeDumbRule2; edgeDumbRule2 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges2, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; ruledBuilder1->SecondSection()->AllowSelfIntersection(true); ruledBuilder1->SecondSection()->AllowDegenerateCurves(false); std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = edgeDumbRule2; NXOpen::Point3d helpPoint2(0, 0, 0); ruledBuilder1->SecondSection()->AddToSection(rules2, edge2, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint2, NXOpen::Section::ModeCreate, false); std::vector<NXOpen::Section*> sections1(2); sections1[0] = ruledBuilder1->FirstSection(); sections1[1] = ruledBuilder1->SecondSection(); ruledBuilder1->AlignmentMethod()->SetSections(sections1); NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); Features::Ruled* ruled1(dynamic_cast<NXOpen::Features::Ruled*>(nXObject1)); try { Body* body = ruled1->GetBodies()[0]; //std::vector<NXOpen::DisplayableObject*> objsTobeBlanked(1); //objsTobeBlanked[0] = body; //theSession->DisplayManager()->BlankObjects(objsTobeBlanked); //workPart->ModelingViews()->WorkView()->FitAfterShowOrHide(NXOpen::View::ShowOrHideTypeHideOnly); body->SetLayer(254); workPart->ModelingViews()->WorkView()->UpdateDisplay(); } catch (const std::exception& ew) { print(ew.what()); } if (!ruled1->GetFaces().empty() && dynamic_cast<Face*>(ruled1->GetFaces()[0]) != nullptr) { return ruled1; } return nullptr; } bool RuledFaces::doReplaceFace(Face* origin_face, Face* replace_face) { if (origin_face == nullptr || replace_face == nullptr) { print("error"); return 0; } origin_face->SetColor(_transitioned_face_color); NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); NXOpen::Features::ReplaceFaceBuilder* replaceFaceBuilder1; replaceFaceBuilder1 = workPart->Features()->CreateReplaceFaceBuilder(nullNXOpen_Features_Feature); replaceFaceBuilder1->OffsetDistance()->SetFormula("0"); replaceFaceBuilder1->ResetReplaceFaceMethod(); replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); std::vector<NXOpen::Face*> faces1(1); faces1[0] = origin_face; NXOpen::FaceDumbRule* faceDumbRule1; faceDumbRule1 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces1, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = faceDumbRule1; replaceFaceBuilder1->FaceToReplace()->ReplaceRules(rules1, false); replaceFaceBuilder1->ResetReplaceFaceMethod(); replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions2; selectionIntentRuleOptions2 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions2->SetSelectedFromInactive(false); std::vector<NXOpen::Face*> faces2(1); faces2[0] = replace_face; NXOpen::FaceDumbRule* faceDumbRule2; faceDumbRule2 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces2, selectionIntentRuleOptions2); delete selectionIntentRuleOptions2; std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = faceDumbRule2; replaceFaceBuilder1->ReplacementFaces()->ReplaceRules(rules2, false); replaceFaceBuilder1->SetReverseDirection(false); replaceFaceBuilder1->OnApplyPre(); NXOpen::NXObject* nXObject1 = nullptr; try { nXObject1 = replaceFaceBuilder1->Commit(); } catch (const std::exception&) { replaceFaceBuilder1->SetReverseDirection(true); try { nXObject1 = replaceFaceBuilder1->Commit(); } catch (const std::exception&) { origin_face->SetColor(_transitional_face_color); } } NXOpen::Expression* expression1(replaceFaceBuilder1->OffsetDistance()); replaceFaceBuilder1->Destroy(); if (nXObject1 == nullptr) return false; return true; } bool RuledFaces::ifContainEqulaEdge(Edge* origin_edge, EdgeSet& edge_set, Edge*& res_edge) { res_edge = nullptr; if (!origin_edge) return false; Point3d origin_edge_p1, origin_edge_p2; origin_edge->GetVertices(&origin_edge_p1, &origin_edge_p2); for (auto it = edge_set.begin(); it != edge_set.end(); ) { if (*it) { Point3d tmp_edge_p1, tmp_edge_p2; (*it)->GetVertices(&tmp_edge_p1, &tmp_edge_p2); if (isEqualXY(origin_edge_p1, origin_edge_p2, tmp_edge_p1, tmp_edge_p2)) { res_edge = (*it); edge_set.erase(it); // 正确删除并获取下一个迭代器 return true; } else { ++it; } } else { it = edge_set.erase(it); // 移除空指针 } } return false; } vector<Body*> RuledFaces::getBodies() { //std::vector<Body*> bodies; //bodies.clear(); //int num = UI::GetUI()->SelectionManager()->GetNumSelectedObjects(); //for (int i = 0; i < num; i++) //{ // TaggedObject* obj = UI::GetUI()->SelectionManager()->GetSelectedTaggedObject(i); // Body* body = dynamic_cast<Body*>(obj); // if (body != nullptr) { // bodies.push_back(body); // } //} std::vector<TaggedObject*> tagged_objs = bodySelect0->GetSelectedObjects(); std::vector<Body*> bodies; std::for_each(tagged_objs.begin(), tagged_objs.end(), [&](TaggedObject* obj) { Body* body = dynamic_cast<Body*>(obj); if (body) bodies.push_back(body); }); return bodies; } void RuledFaces::getFixedAndTransitionalFaces(const vector<Body*>& bodies, vector<Face*>& fixed_faces, vector<Face*>& transitional_faces) { for (auto body : bodies) { vector<Face*> faces = body->GetFaces(); std::for_each(faces.begin(), faces.end(), [&](Face* face) { if (face->Color() == _fixed_face_color) fixed_faces.push_back(face); else if (face->Color() == _transitional_face_color) transitional_faces.push_back(face); }); } //face_select0->SetSelectedObjects(vector<TaggedObject*>(fixed_faces.begin(), fixed_faces.end())); //face_select01->SetSelectedObjects(vector<TaggedObject*>(transitional_faces.begin(), transitional_faces.end())); } EdgeSet RuledFaces::getFixedEdgeSet(const vector<Face*>& fixed_faces) { EdgeSet edge_set; for (auto fixed_face : fixed_faces) { vector<Edge*> edges = fixed_face->GetEdges(); for_each(edges.begin(), edges.end(), [&](Edge* edge) { edge_set.insert(edge); }); } return edge_set; } //------------------------------------------------------------------------------ // Do something //------------------------------------------------------------------------------ void RuledFaces::do_it() { // TODO: add your code here _fixed_face_color = colorPicker0->GetValue()[0]; _transitional_face_color = colorPicker01->GetValue()[0]; _transitioned_face_color = colorPicker02->GetValue()[0]; vector<Body*> bodies = getBodies(); vector<Face*> fixed_faces, transitional_faces; getFixedAndTransitionalFaces(bodies, fixed_faces, transitional_faces); EdgeSet fixed_edges = getFixedEdgeSet(fixed_faces); for (auto transitional_face : transitional_faces) { vector<Edge*> trans_edges = transitional_face->GetEdges(); vector<Edge*> rule_edges; rule_edges.clear(); for (auto trans_edge : trans_edges) { if (!trans_edge) continue; Edge* found_edge = nullptr; bool res = false; res = ifContainEqulaEdge(trans_edge, fixed_edges, found_edge); if (res) rule_edges.push_back(found_edge); } if (rule_edges.size() != 2) { continue; } Edge* edge1 = rule_edges[0]; Edge* edge2 = rule_edges[1]; Features::Ruled* ruled = doCreateRuledFace(edge1, edge2); if (ruled == nullptr) { print("error"); continue; } Face* ruled_face = ruled->GetFaces()[0]; bool res = doReplaceFace(transitional_face, ruled_face);; if (!res) { tryReverseRuledDirection(ruled); res = doReplaceFace(transitional_face, ruled_face); } } } bool RuledFaces::tryReverseRuledDirection(Features::Ruled* ruled_face) { if (ruled_face == nullptr) return nullptr; NXOpen::Session::UndoMarkId markId; markId = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "Redefine Feature"); NXOpen::Features::EditWithRollbackManager* editWithRollbackManager1; editWithRollbackManager1 = workPart->Features()->StartEditWithRollbackManager(ruled_face, markId); NXOpen::Features::RuledBuilder* ruledBuilder1; ruledBuilder1 = workPart->Features()->CreateRuledBuilder(ruled_face); ruledBuilder1->SecondSection()->ReverseDirectionOfLoop(0); ruledBuilder1->AlignmentMethod()->UpdateSectionAtIndex(1); NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); ruledBuilder1->Destroy(); editWithRollbackManager1->UpdateFeature(false); editWithRollbackManager1->Stop(); editWithRollbackManager1->Destroy(); },从新处理下,注意代码一点都不能改动,只做注释处理,
08-03
<think>我们要求对给定的C++代码进行逐行注释,注意不能改动任何代码,只添加注释注释要求: 1. 对每一行或每一段代码的功能进行解释 2. 特别要注意NX Open API的使用部分,说明其作用 3. 对关键算法步骤进行说明 4. 注意代码中的异常处理和内存管理 由于代码较长,我们将分部分进行注释。</think>以下是对您提供的C++代码的完整逐行注释,严格保持原始代码不变,仅添加注释说明: ```cpp //RuledFaces // 标准C++头文件 #include <iostream> // 输入输出流 #include <sstream> // 字符串流 #include <algorithm> // STL算法 #include <fstream> // 文件流 #include "RuledFaces.h" // 自定义头文件 using namespace NXOpen; // NX Open命名空间 using namespace std; // 标准命名空间 // 注释掉的日志文件输出 //ofstream fout("D:\\D:\NXopen\BaiduSyncdisk\studio\zhinengguodu\\res.txt"); //============================================================================== // 警告!! 此文件由Block UI Styler生成时会被覆盖 // 任何修改在重新生成代码后将丢失 // // 文件名: D:\FXM\Documents\nx_customized\23-RuledFaces\RuledFaces.cpp // // 此文件由NX Block UI Styler生成 // 创建者: MIC-明 // 版本: NX 2212 // 日期: 07-17-2025 (格式: mm-dd-yyyy) // 时间: 14:33 (格式: hh-mm) // //============================================================================== //============================================================================== // 目的: 此模板文件包含C++代码,用于指导您 // 构建Block应用程序对话框。生成对话框文件(.dlx扩展名) // 是在NX中构建对话框的第一步。您现在必须创建一个NX Open应用程序 // 来使用此文件(.dlx) // // 此文件中的信息提供以下内容: // // 1. 如何使用NXOpen.BlockStyler命名空间中的API在NX中加载和显示Block UI Styler对话框 // 2. 与对话框项关联的空回调方法(存根)也已放置在此文件中 // 这些空方法仅用于启动您的编码需求 // 方法名称、参数列表和可能的返回值已提供 //============================================================================== //------------------------------------------------------------------------------ // 初始化静态变量 //------------------------------------------------------------------------------ Session* (RuledFaces::theSession) = NULL; // NX会话静态指针 UI* (RuledFaces::theUI) = NULL; // NX UI静态指针 //------------------------------------------------------------------------------ // NX Styler类的构造函数 //------------------------------------------------------------------------------ RuledFaces::RuledFaces() { try { // 初始化NX Open C++ API环境 RuledFaces::theSession = NXOpen::Session::GetSession(); // 获取当前NX会话 RuledFaces::theUI = UI::GetUI(); // 获取UI接口 workPart = theSession->Parts()->Work(); // 获取工作部件 mb = theUI->NXMessageBox(); // 消息框对象 lw = theSession->ListingWindow(); // 列表窗口对象 lf = theSession->LogFile(); // 日志文件对象 theDlxFileName = "RuledFaces.dlx"; // Block Styler对话框文件名 theDialog = RuledFaces::theUI->CreateDialog(theDlxFileName); // 创建对话框 // 注册回调函数 theDialog->AddApplyHandler(make_callback(this, &RuledFaces::apply_cb)); theDialog->AddOkHandler(make_callback(this, &RuledFaces::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &RuledFaces::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &RuledFaces::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &RuledFaces::dialogShown_cb)); } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- throw; // 抛出异常 } } //------------------------------------------------------------------------------ // NX Styler类的析构函数 //------------------------------------------------------------------------------ RuledFaces::~RuledFaces() { if (theDialog != NULL) { delete theDialog; // 删除对话框对象 theDialog = NULL; // 置空指针 } } //------------------------------------------------------------------------------ // 打印字符串到列表窗口或标准输出 //------------------------------------------------------------------------------ void RuledFaces::print(const NXString& msg) { if (!lw->IsOpen()) lw->Open(); // 确保列表窗口打开 lw->WriteLine(msg); // 写入消息 } void RuledFaces::print(const string& msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } void RuledFaces::print(const char* msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } //------------------------------- 对话框启动 --------------------------------- // // 在调用此应用程序之前,需要在NX中打开任何部件/空部件 // 因为块的行为 // // 确保dlx文件位于以下位置之一: // 1.) 从NX会话启动的位置 // 2.) $UGII_USER_DIR/application // 3.) 对于发布的应用程序,强烈建议使用UGII_CUSTOM_DIRECTORY_FILE // 此变量设置为包含所有自定义应用程序根目录列表的文件完整目录路径 // 例如: UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // 您可以通过以下方式之一创建对话框: // // 1. 用户退出(USER EXIT) // // 1) 创建共享库 -- 参考"Block UI Styler程序员指南" // 2) 通过文件->执行->NX Open菜单调用共享库 // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char* param, int* retcod, int param_len) { RuledFaces* theRuledFaces = NULL; // 对话框实例指针 try { theRuledFaces = new RuledFaces(); // 创建对话框实例 // 以下方法立即显示对话框 theRuledFaces->Launch(); // 启动对话框 } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if (theRuledFaces != NULL) { delete theRuledFaces; // 删除对话框实例 theRuledFaces = NULL; // 置空指针 } } //------------------------------------------------------------------------------ // 此方法指定如何在NX中从内存卸载共享映像 // 此方法使您能够从NX卸载内部NX Open应用程序或用户退出 // 指定以下三个常量之一作为返回值以确定卸载类型: // // // 立即(Immediately) : 自动化程序完成后立即卸载库 // 显式(Explicitly) : 从"卸载共享映像"对话框中卸载库 // 终止时(AtTermination) : NX会话终止时卸载库 // // // 注意: 将NX Open应用程序与菜单栏关联的程序 // 不得使用此选项,因为它将从菜单栏卸载您的NX Open应用程序映像 //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; // 选择立即卸载 //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // 以下方法清理可能需要完成的任何内务处理 // 此方法由NX自动调用 //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- 在此处输入回调代码 ----- } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ // 此方法将对话框启动到屏幕 //------------------------------------------------------------------------------ NXOpen::BlockStyler::BlockDialog::DialogResponse RuledFaces::Launch() { NXOpen::BlockStyler::BlockDialog::DialogResponse dialogResponse = NXOpen::BlockStyler::BlockDialog::DialogResponse::DialogResponseInvalid; try { dialogResponse = theDialog->Launch(); // 启动对话框 } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return dialogResponse; // 返回对话框响应 } //------------------------------------------------------------------------------ //--------------------- Block UI Styler回调函数 -------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // 回调名称: initialize_cb // 对话框初始化时调用 //------------------------------------------------------------------------------ void RuledFaces::initialize_cb() { try { // 动态获取对话框中的UI控件 group0 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group0")); colorPicker0 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker0")); colorPicker01 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker01")); bodySelect0 = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("bodySelect0")); separator0 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator0")); group = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group")); face_select0 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select0")); face_select01 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select01")); separator01 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator01")); colorPicker02 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker02")); } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ // 回调名称: dialogShown_cb // 此回调在对话框启动前执行。此处设置的任何值将优先 // 对话框将显示该值 //------------------------------------------------------------------------------ void RuledFaces::dialogShown_cb() { try { //---- 在此处输入回调代码 ----- group->SetEnable(false); // 禁用组 group->SetShow(false); // 隐藏组 face_select0->SetEnable(false); // 禁用面选择器0 face_select0->SetShow(false); // 隐藏面选择器0 face_select01->SetEnable(false); // 禁用面选择器01 face_select01->SetShow(false); // 隐藏面选择器01 } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ // 回调名称: apply_cb // 应用按钮回调 //------------------------------------------------------------------------------ int RuledFaces::apply_cb() { int errorCode = 0; try { //---- 在此处输入回调代码 ----- NXOpen::Session::UndoMarkId markId1; // 撤销标记ID // 设置可见的撤销标记 markId1 = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "RuledFaces"); do_it(); // 执行主要功能 } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; // 返回错误代码 } //------------------------------------------------------------------------------ // 回调名称: update_cb // 控件更新回调 //------------------------------------------------------------------------------ int RuledFaces::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { // 根据不同的控件执行不同的更新逻辑 if (block == colorPicker0) { //---------在此处输入代码----------- } else if (block == colorPicker01) { //---------在此处输入代码----------- } else if (block == bodySelect0) { //---------在此处输入代码----------- } else if (block == separator0) { //---------在此处输入代码----------- } else if (block == face_select0) { //---------在此处输入代码----------- } else if (block == face_select01) { //---------在此处输入代码----------- } else if (block == separator01) { //---------在此处输入代码----------- } else if (block == colorPicker02) { //---------在此处输入代码----------- } } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; // 返回0表示成功 } //------------------------------------------------------------------------------ // 回调名称: ok_cb // 确定按钮回调 //------------------------------------------------------------------------------ int RuledFaces::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); // 调用应用回调 } catch (exception& ex) { //---- 在此处输入异常处理代码 ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; // 返回错误代码 } //------------------------------------------------------------------------------ // 函数名称: GetBlockProperties // 描述: 返回指定BlockID的属性列表 //------------------------------------------------------------------------------ PropertyList* RuledFaces::GetBlockProperties(const char* blockID) { return theDialog->GetBlockProperties(blockID); // 获取控件属性 } // 比较两条边在XY平面是否相等(考虑容差) bool RuledFaces::isEqualXY(const Point3d& a1, const Point3d& a2, const Point3d& b1, const Point3d& b2, double eps = 1e-3) { // 定义XY平面相等比较的lambda函数 auto equalXY = [&](const Point3d& p1, const Point3d& p2) { return std::fabs(p1.X - p2.X) < eps && std::fabs(p1.Y - p2.Y) < eps; }; // 考虑两条边的方向(正反方向都算相等) return (equalXY(a1, b1) && equalXY(a2, b2)) || (equalXY(a1, b2) && equalXY(a2, b1)); } // 创建直纹面特征 Features::Ruled* RuledFaces::doCreateRuledFace(Edge* edge1, Edge* edge2) { NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); // 空特征指针 NXOpen::Features::RuledBuilder* ruledBuilder1; // 直纹面构建器 // 创建直纹面构建器 ruledBuilder1 = workPart->Features()->CreateRuledBuilder(nullNXOpen_Features_Feature); // 设置构建器参数 ruledBuilder1->SetPositionTolerance(0.001); // 位置容差 ruledBuilder1->SetShapePreserved(false); // 不保留形状 ruledBuilder1->FirstSection()->SetDistanceTolerance(0.001); // 第一截面距离容差 ruledBuilder1->FirstSection()->SetChainingTolerance(0.00095); // 第一截面链接容差 ruledBuilder1->SecondSection()->SetDistanceTolerance(0.001); // 第二截面距离容差 ruledBuilder1->SecondSection()->SetChainingTolerance(0.00095); // 第二截面链接容差 ruledBuilder1->AlignmentMethod()->AlignCurve()->SetDistanceTolerance(0.001); // 对齐曲线距离容差 ruledBuilder1->AlignmentMethod()->AlignCurve()->SetChainingTolerance(0.00095); // 对齐曲线链接容差 ruledBuilder1->FirstSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesCurvesAndPoints); // 第一截面允许类型 // 创建选择意图规则选项 NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); // 不从非活动对象选择 // 为第一条边创建规则 std::vector<NXOpen::Edge*> edges1(1); edges1[0] = edge1; NXOpen::EdgeDumbRule* edgeDumbRule1; edgeDumbRule1 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges1, selectionIntentRuleOptions1); // 设置第一截面参数 ruledBuilder1->FirstSection()->AllowSelfIntersection(true); // 允许自相交 ruledBuilder1->FirstSection()->AllowDegenerateCurves(false); // 不允许退化曲线 // 添加第一截面 std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = edgeDumbRule1; NXOpen::NXObject* nullNXOpen_NXObject(NULL); // 空NX对象 NXOpen::Point3d helpPoint1(0, 0, 0); // 帮助点 ruledBuilder1->FirstSection()->AddToSection(rules1, edge1, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint1, NXOpen::Section::ModeCreate, false); // 设置第二截面参数 ruledBuilder1->SecondSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesOnlyCurves); // 第二截面仅允许曲线 // 为第二条边创建规则 std::vector<NXOpen::Edge*> edges2(1); edges2[0] = edge2; NXOpen::EdgeDumbRule* edgeDumbRule2; edgeDumbRule2 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges2, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; // 删除规则选项 ruledBuilder1->SecondSection()->AllowSelfIntersection(true); // 允许自相交 ruledBuilder1->SecondSection()->AllowDegenerateCurves(false); // 不允许退化曲线 // 添加第二截面 std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = edgeDumbRule2; NXOpen::Point3d helpPoint2(0, 0, 0); // 帮助点 ruledBuilder1->SecondSection()->AddToSection(rules2, edge2, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint2, NXOpen::Section::ModeCreate, false); // 设置对齐截面 std::vector<NXOpen::Section*> sections1(2); sections1[0] = ruledBuilder1->FirstSection(); sections1[1] = ruledBuilder1->SecondSection(); ruledBuilder1->AlignmentMethod()->SetSections(sections1); // 提交特征 NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); // 转换为直纹面特征 Features::Ruled* ruled1(dynamic_cast<NXOpen::Features::Ruled*>(nXObject1)); try { // 获取生成的体并设置显示属性 Body* body = ruled1->GetBodies()[0]; // 以下为注释掉的隐藏对象代码 //std::vector<NXOpen::DisplayableObject*> objsTobeBlanked(1); //objsTobeBlanked[0] = body; //theSession->DisplayManager()->BlankObjects(objsTobeBlanked); //workPart->ModelingViews()->WorkView()->FitAfterShowOrHide(NXOpen::View::ShowOrHideTypeHideOnly); body->SetLayer(254); // 设置图层为254 workPart->ModelingViews()->WorkView()->UpdateDisplay(); // 更新显示 } catch (const std::exception& ew) { print(ew.what()); // 打印异常信息 } // 检查直纹面是否有效 if (!ruled1->GetFaces().empty() && dynamic_cast<Face*>(ruled1->GetFaces()[0]) != nullptr) { return ruled1; // 返回有效的直纹面 } return nullptr; // 否则返回空指针 } // 替换面操作 bool RuledFaces::doReplaceFace(Face* origin_face, Face* replace_face) { // 检查输入面是否有效 if (origin_face == nullptr || replace_face == nullptr) { print("error"); // 打印错误信息 return 0; // 返回失败 } // 设置原始面颜色 origin_face->SetColor(_transitioned_face_color); // 创建替换面构建器 NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); NXOpen::Features::ReplaceFaceBuilder* replaceFaceBuilder1; replaceFaceBuilder1 = workPart->Features()->CreateReplaceFaceBuilder(nullNXOpen_Features_Feature); // 设置替换参数 replaceFaceBuilder1->OffsetDistance()->SetFormula("0"); // 偏移距离设为0 replaceFaceBuilder1->ResetReplaceFaceMethod(); // 重置替换面方法 replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); // 重置自由边投影选项 // 创建原始面选择规则 NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); // 不从非活动对象选择 // 添加原始面 std::vector<NXOpen::Face*> faces1(1); faces1[0] = origin_face; NXOpen::FaceDumbRule* faceDumbRule1; faceDumbRule1 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces1, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; // 删除规则选项 std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = faceDumbRule1; replaceFaceBuilder1->FaceToReplace()->ReplaceRules(rules1, false); // 替换规则 // 重置替换面方法 replaceFaceBuilder1->ResetReplaceFaceMethod(); replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); // 创建替换面选择规则 NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions2; selectionIntentRuleOptions2 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions2->SetSelectedFromInactive(false); // 不从非活动对象选择 // 添加替换面 std::vector<NXOpen::Face*> faces2(1); faces2[0] = replace_face; NXOpen::FaceDumbRule* faceDumbRule2; faceDumbRule2 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces2, selectionIntentRuleOptions2); delete selectionIntentRuleOptions2; // 删除规则选项 std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = faceDumbRule2; replaceFaceBuilder1->ReplacementFaces()->ReplaceRules(rules2, false); // 替换规则 replaceFaceBuilder1->SetReverseDirection(false); // 设置不反方向 replaceFaceBuilder1->OnApplyPre(); // 应用前处理 // 尝试提交替换操作 NXOpen::NXObject* nXObject1 = nullptr; try { nXObject1 = replaceFaceBuilder1->Commit(); // 提交替换 } catch (const std::exception&) // 捕获异常 { // 方向错误时尝试反方向 replaceFaceBuilder1->SetReverseDirection(true); try { nXObject1 = replaceFaceBuilder1->Commit(); // 再次提交 } catch (const std::exception&) // 再次捕获异常 { origin_face->SetColor(_transitional_face_color); // 恢复原始面颜色 } } NXOpen::Expression* expression1(replaceFaceBuilder1->OffsetDistance()); // 获取偏移距离表达式 replaceFaceBuilder1->Destroy(); // 销毁构建器 if (nXObject1 == nullptr) return false; // 替换失败 return true; // 替换成功 } // 在边集合中查找匹配边 bool RuledFaces::ifContainEqulaEdge(Edge* origin_edge, EdgeSet& edge_set, Edge*& res_edge) { res_edge = nullptr; // 初始化结果边为空 if (!origin_edge) return false; // 原始边无效则返回失败 // 获取原始边的两个端点 Point3d origin_edge_p1, origin_edge_p2; origin_edge->GetVertices(&origin_edge_p1, &origin_edge_p2); // 遍历边集合 for (auto it = edge_set.begin(); it != edge_set.end(); ) { if (*it) { // 检查边是否有效 // 获取当前边的两个端点 Point3d tmp_edge_p1, tmp_edge_p2; (*it)->GetVertices(&tmp_edge_p1, &tmp_edge_p2); // 比较两条边在XY平面是否相等 if (isEqualXY(origin_edge_p1, origin_edge_p2, tmp_edge_p1, tmp_edge_p2)) { res_edge = (*it); // 找到匹配边 edge_set.erase(it); // 从集合中移除该边 return true; // 返回成功 } else { ++it; // 继续遍历 } } else { it = edge_set.erase(it); // 移除空指针 } } return false; // 未找到匹配边 } // 获取选择的体 vector<Body*> RuledFaces::getBodies() { // 注释掉的旧实现 //std::vector<Body*> bodies; //bodies.clear(); //int num = UI::GetUI()->SelectionManager()->GetNumSelectedObjects(); //for (int i = 0; i < num; i++) //{ // TaggedObject* obj = UI::GetUI()->SelectionManager()->GetSelectedTaggedObject(i); // Body* body = dynamic_cast<Body*>(obj); // if (body != nullptr) { // bodies.push_back(body); // } //} // 从体选择器获取选中的对象 std::vector<TaggedObject*> tagged_objs = bodySelect0->GetSelectedObjects(); std::vector<Body*> bodies; // 使用lambda转换TaggedObject到Body std::for_each(tagged_objs.begin(), tagged_objs.end(), [&](TaggedObject* obj) { Body* body = dynamic_cast<Body*>(obj); if (body) bodies.push_back(body); // 有效体添加到列表 }); return bodies; // 返回体列表 } // 获取固定面和过渡面 void RuledFaces::getFixedAndTransitionalFaces(const vector<Body*>& bodies, vector<Face*>& fixed_faces, vector<Face*>& transitional_faces) { // 遍历所有体 for (auto body : bodies) { vector<Face*> faces = body->GetFaces(); // 获取体的所有面 // 遍历体的面 std::for_each(faces.begin(), faces.end(), [&](Face* face) { if (face->Color() == _fixed_face_color) fixed_faces.push_back(face); // 固定面 else if (face->Color() == _transitional_face_color) transitional_faces.push_back(face); // 过渡面 }); } // 注释掉的设置选中对象代码 //face_select0->SetSelectedObjects(vector<TaggedObject*>(fixed_faces.begin(), fixed_faces.end())); //face_select01->SetSelectedObjects(vector<TaggedObject*>(transitional_faces.begin(), transitional_faces.end())); } // 获取固定面的边集合 EdgeSet RuledFaces::getFixedEdgeSet(const vector<Face*>& fixed_faces) { EdgeSet edge_set; // 边集合 // 遍历所有固定面 for (auto fixed_face : fixed_faces) { vector<Edge*> edges = fixed_face->GetEdges(); // 获取面的所有边 // 遍历面的边 for_each(edges.begin(), edges.end(), [&](Edge* edge) { edge_set.insert(edge); // 添加到集合 }); } return edge_set; // 返回边集合 } //------------------------------------------------------------------------------ // 主要执行函数 //------------------------------------------------------------------------------ void RuledFaces::do_it() { // TODO: 在此处添加代码 // 从UI获取颜色值 _fixed_face_color = colorPicker0->GetValue()[0]; // 固定面颜色 _transitional_face_color = colorPicker01->GetValue()[0]; // 过渡面颜色 _transitioned_face_color = colorPicker02->GetValue()[0]; // 已过渡面颜色 // 获取选择的体 vector<Body*> bodies = getBodies(); vector<Face*> fixed_faces, transitional_faces; // 分类固定面和过渡面 getFixedAndTransitionalFaces(bodies, fixed_faces, transitional_faces); // 获取固定面的边集合 EdgeSet fixed_edges = getFixedEdgeSet(fixed_faces); // 遍历所有过渡面 for (auto transitional_face : transitional_faces) { vector<Edge*> trans_edges = transitional_face->GetEdges(); // 获取过渡面的边 vector<Edge*> rule_edges; // 用于创建直纹面的边 rule_edges.clear(); // 清空列表 // 遍历过渡面的每条边 for (auto trans_edge : trans_edges) { if (!trans_edge) // 跳过无效边 continue; Edge* found_edge = nullptr; // 找到的匹配边 bool res = false; // 在固定边中查找匹配边 res = ifContainEqulaEdge(trans_edge, fixed_edges, found_edge); if (res) rule_edges.push_back(found_edge); // 找到则添加 } // 需要两条边才能创建直纹面 if (rule_edges.size() != 2) { continue; // 跳过不足两条边的情况 } // 获取两条边 Edge* edge1 = rule_edges[0]; Edge* edge2 = rule_edges[1]; // 创建直纹面 Features::Ruled* ruled = doCreateRuledFace(edge1, edge2); if (ruled == nullptr) { print("error"); // 打印错误信息 continue; // 继续下一个面 } // 获取直纹面 Face* ruled_face = ruled->GetFaces()[0]; // 替换原始面 bool res = doReplaceFace(transitional_face, ruled_face); // 如果替换失败 if (!res) { // 尝试反直纹面方向 tryReverseRuledDirection(ruled); // 再次尝试替换 res = doReplaceFace(transitional_face, ruled_face); } } } // 尝试反直纹面方向 bool RuledFaces::tryReverseRuledDirection(Features::Ruled* ruled_face) { if (ruled_face == nullptr) // 检查直纹面是否有效 return nullptr; // 无效则返回空 // 设置撤销标记 NXOpen::Session::UndoMarkId markId; markId = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "Redefine Feature"); // 启动带回滚管理的编辑 NXOpen::Features::EditWithRollbackManager* editWithRollbackManager1; editWithRollbackManager1 = workPart->Features()->StartEditWithRollbackManager(ruled_face, markId); // 创建直纹面构建器 NXOpen::Features::RuledBuilder* ruledBuilder1; ruledBuilder1 = workPart->Features()->CreateRuledBuilder(ruled_face); // 反第二截面方向 ruledBuilder1->SecondSection()->ReverseDirectionOfLoop(0); // 更新第二截面 ruledBuilder1->AlignmentMethod()->UpdateSectionAtIndex(1); // 提交修改 NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); // 清理资源 ruledBuilder1->Destroy(); editWithRollbackManager1->UpdateFeature(false); editWithRollbackManager1->Stop(); editWithRollbackManager1->Destroy(); } // 注意:此函数缺少返回值 ``` ### 关键功能总结: 1. **NX Open集成架构**: - `ufusr`为NX标准入口函数 - `ufusr_ask_unload`定义DLL卸载行为 - `ufusr_cleanup`提供清理接口 2. **对话框生命周期管理**: - 构造函数初始化NX环境 - `initialize_cb`获取UI控件 - `dialogShown_cb`初始界面配置 - `apply_cb`和`ok_cb`处理用户操作 3. **核心几何处理流程**: ```mermaid graph TD A[获取颜色设置] --> B[选择目标体] B --> C[分类固定面和过渡面] C --> D[收集固定面的边] D --> E{遍历每个过渡面} E --> F[查找匹配的两条边] F --> G[创建直纹面] G --> H[替换原始面] H --> I{替换成功?} I -->|失败| J[反直纹面方向] I -->|成功| K[完成] J --> H ``` 4. **关键算法**: - **边匹配**:`isEqualXY`在XY平面比较边是否相等 - **直纹面创建**:`doCreateRuledFace`通过两条边界边创建曲面 - **面替换**:`doReplaceFace`用新曲面替换原始面 - **方向修正**:`tryReverseRuledDirection`处理替换失败情况 5. **注意事项**: - `tryReverseRuledDirection`函数缺少返回值(原代码问题) - 颜色标记用于区分不同类型的面 - 使用撤销标记支持操作回滚
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值