UpdateFeature

本文详细介绍了如何使用地理数据库特征类更新特征,包括单个特征的更新、使用游标批量更新多个特征、删除特征以及优化特定情况下的性能。通过实例演示了使用IFeature.Store方法和游标操作的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Updating features

This topic explains how to updates features in a geodatabase feature class. Two approaches are shown, one that updates an individual feature using the IFeature.Store method, and one that uses a cursor to update multiple features at once. Additional information includes how to delete features and how to optimize performance in certain situations.

1.Updating individual features

// Get a known feature using its Object ID.
IFeature feature = featureClass.GetFeature(1);

// Assign a new point as the feature's shape.
IPoint newLocation = new PointClass { X = 1000, Y = 1000 };
feature.Shape = newLocation;

// Find the position of the "NAME" field and modify it.
int nameFieldIndex = featureClass.FindField("NAME");
feature.set_Value(nameFieldIndex, "My Value");

// Store the changes.
feature.Store();

2.Using cursors to perform updates

// Create a ComReleaser for cursor management.
using (ComReleaser comReleaser = new ComReleaser())
{
  // Use ITable.Update to create an update cursor.
  ICursor updateCursor = table.Update(null, true);
  comReleaser.ManageLifetime(updateCursor);

  // Find the positions of the fields used to get and set values.
  int firstNameIndex = table.FindField("FirstName");
  int lastNameIndex = table.FindField("LastName");
  int emailIndex = table.FindField("Email");
  IRow row = null;
  while ((row = updateCursor.NextRow()) != null)
  {
    // Get the first and last names.
    String firstName = Convert.ToString(row.get_Value(firstNameIndex));
    String lastName = Convert.ToString(row.get_Value(lastNameIndex));

    // Append the first letter of the first name and the entire last name with
    // an @ (at) symbol and the e-mail domain to make an e-mail address.
    String emailAddress = String.Concat(firstName[0], lastName, "@MyCompanyName.com");
    row.set_Value(emailIndex, emailAddress);
    updateCursor.UpdateRow(row);
  }
}

3.Using a search cursor
// Create a ComReleaser for cursor management.
using (ComReleaser comReleaser = new ComReleaser())
{
  // Use IFeatureClass.Search to create a search cursor.
  IFeatureCursor searchCursor = featureClass.Search(null, false);
  comReleaser.ManageLifetime(searchCursor);

  // Find the positions of the fields used to get and set values.
  int laneFieldIndex = featureClass.FindField("LANE_COUNT");
  int speedFieldIndex = featureClass.FindField("SPEED_LIMIT");
  IFeature feature = null;
  while ((feature = searchCursor.NextFeature()) != null)
  {
    // Check the lane count of the feature.
    int laneCount = Convert.ToInt32(feature.get_Value(laneFieldIndex));

    // Set the speed limit based on the lane count.
    int speedLimit = (laneCount == 2) ? 50 : 80;
    feature.set_Value(speedFieldIndex, speedLimit);
    feature.Store();
  }
}

4.Deleting features

// Define a constraint on the features to be deleted.
IQueryFilter queryFilter = new QueryFilterClass
{
  WhereClause = "TERM = 'Village'"
};

// Create a ComReleaser for cursor management.
using (ComReleaser comReleaser = new ComReleaser())
{
  // Create and manage a cursor.
  IFeatureCursor searchCursor = featureClass.Search(queryFilter, false);
  comReleaser.ManageLifetime(searchCursor);

  // Delete the retrieved features.
  IFeature feature = null;
  while ((feature = searchCursor.NextFeature()) != null)
  {
    feature.Delete();
  }
}
// Define a constraint on the features to be deleted.
IQueryFilter queryFilter = new QueryFilterClass
{
  WhereClause = "TERM = 'Village'"
};

// Cast the feature class to the ITable interface.
ITable table = (ITable)featureClass;
table.DeleteSearchedRows(queryFilter);


5.UpdateSearchedRows
// Find the position of the field that will be updated.
int typeFieldIndex = featureClass.FindField("TYPE");

// Create a query filter defining which fields will be updated
// (the subfields) and how to constrain which rows are updated
// (the where clause).
IQueryFilter queryFilter = new QueryFilterClass
{
  SubFields = "TYPE",
  WhereClause = "LANE_COUNT = 4"
};

// Create a ComReleaser for buffer management.
using (ComReleaser comReleaser = new ComReleaser())
{
  // Create a feature buffer containing the values to be updated.
  IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
  featureBuffer.set_Value(typeFieldIndex, "Highway");
  comReleaser.ManageLifetime(featureBuffer);

  // Cast the class to ITable and perform the updates.
  ITable table = (ITable)featureClass;
  IRowBuffer rowBuffer = (IRowBuffer)featureBuffer;
  table.UpdateSearchedRows(queryFilter, rowBuffer);
}

6.Scoping edit operations with search cursors
// One edit operation for every edit.
while ((feature = cursor.NextFeature()) != null)
{
  workspaceEdit.StartEditOperation();
  feature.set_Value(1, "abcde");
  feature.Store();
  Marshal.ReleaseComObject(feature);
  workspaceEdit.StopEditOperation();
}

// One edit operation for every 500 edits.
int count = 0;
while ((feature = cursor.NextFeature()) != null)
{
  count++;
  workspaceEdit.StartEditOperation();
  feature.set_Value(1, "abcde");
  feature.Store();
  Marshal.ReleaseComObject(feature);
  if (count % 500 == 0)
  {
    workspaceEdit.StopEditOperation();
  }
}
workspaceEdit.StopEditOperation();



//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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值