【NX】NX开发入门练习寻找倒圆角设置颜色和添加属性

news2025/1/16 2:47:07

实现功能如标题,当时学习nx开发用的练习题,用的是nx8.5的32位版本,对于设置属性,一种是可以在界面中查看的属性,一种是隐藏的不能再界面中查看的自定义属性(但是可以正常读取)。

 

下面是完整代码:

//==============================================================================
//  WARNING!!  This file is overwritten by the Block Styler while generating
//  the automation code. Any modifications to this file will be lost after
//  generating the code again.
//
//       Filename:  D:\NXOPEN\application\modelingExercise.hpp
//
//        This file was generated by the NX Block Styler
//        Created by: hp
//              Version: NX 8.5
//              Date: 04-24-2023  (Format: mm-dd-yyyy)
//              Time: 09:58
//
//==============================================================================

#ifndef MODELINGEXERCISE_H_INCLUDED
#define MODELINGEXERCISE_H_INCLUDED

//------------------------------------------------------------------------------
//These includes are needed for the following template code
//------------------------------------------------------------------------------
#include <uf_defs.h>
#include <uf_ui_types.h>
#include <iostream>
#include <NXOpen/Session.hxx>
#include <NXOpen/UI.hxx>
#include <NXOpen/NXMessageBox.hxx>
#include <NXOpen/Callback.hxx>
#include <NXOpen/NXException.hxx>
#include <NXOpen/BlockStyler_UIBlock.hxx>
#include <NXOpen/BlockStyler_BlockDialog.hxx>
#include <NXOpen/BlockStyler_PropertyList.hxx>
#include <NXOpen/BlockStyler_Group.hxx>
#include <NXOpen/BlockStyler_Button.hxx>

//------------------------------------------------------------------------------
// Namespaces needed for following template
//------------------------------------------------------------------------------
using namespace std;
using namespace NXOpen;
using namespace NXOpen::BlockStyler;

class DllExport modelingExercise
{
    // class members
public:
    static Session *theSession;
    static UI *theUI;
    modelingExercise();
    ~modelingExercise();
    int Show();
    
    //----------------------- BlockStyler Callback Prototypes ---------------------
    // The following member function prototypes define the callbacks 
    // specified in your BlockStyler dialog.  The empty implementation
    // of these prototypes is provided in the modelingExercise.cpp file. 
    // You are REQUIRED to write the implementation for these functions.
    //------------------------------------------------------------------------------
    void initialize_cb();
    void dialogShown_cb();
    int apply_cb();
    int ok_cb();
    int update_cb(NXOpen::BlockStyler::UIBlock* block);
    PropertyList* GetBlockProperties(const char *blockID);
    
private:
    const char* theDlxFileName;
    NXOpen::BlockStyler::BlockDialog* theDialog;
    NXOpen::BlockStyler::Group* gpexercise;// Block type: Group
    NXOpen::BlockStyler::Button* btnCreateBlock;// Block type: Button
    NXOpen::BlockStyler::Button* btnFillet;// Block type: Button
    NXOpen::BlockStyler::Button* btnCalcArea;// Block type: Button
    
};
#endif //MODELINGEXERCISE_H_INCLUDED

实现:

//==============================================================================
//  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:\NXOPEN\application\modelingExercise.cpp
//
//        This file was generated by the NX Block UI Styler
//        Created by: hp
//              Version: NX 8.5
//              Date: 04-24-2023  (Format: mm-dd-yyyy)
//              Time: 09:58 (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.
//==============================================================================

//------------------------------------------------------------------------------
//These includes are needed for the following template code
//------------------------------------------------------------------------------
#include "modelingExercise.hpp"

#include <uf_defs.h>
#include <NXOpen/NXException.hxx>
#include <NXOpen/Session.hxx>
#include <NXOpen/AttributeManager.hxx>
#include <NXOpen/AttributePropertiesBaseBuilder.hxx>
#include <NXOpen/AttributePropertiesBuilder.hxx>
#include <NXOpen/BasePart.hxx>
#include <NXOpen/Body.hxx>
#include <NXOpen/Builder.hxx>
#include <NXOpen/DateBuilder.hxx>
#include <NXOpen/DateItemBuilder.hxx>
#include <NXOpen/DateItemBuilderList.hxx>
#include <NXOpen/Edge.hxx>
#include <NXOpen/EdgeMultipleSeedTangentRule.hxx>
#include <NXOpen/Expression.hxx>
#include <NXOpen/ExpressionCollection.hxx>
#include <NXOpen/FeatureGeneralPropertiesBuilder.hxx>
#include <NXOpen/Features_Block.hxx>
#include <NXOpen/Features_BlockFeatureBuilder.hxx>
#include <NXOpen/Features_EdgeBlend.hxx>
#include <NXOpen/Features_EdgeBlendBuilder.hxx>
#include <NXOpen/Features_Feature.hxx>
#include <NXOpen/Features_FeatureBuilder.hxx>
#include <NXOpen/Features_FeatureCollection.hxx>
#include <NXOpen/Features_IContainerFeature.hxx>
#include <NXOpen/GeometricUtilities_BlendLimitsData.hxx>
#include <NXOpen/GeometricUtilities_BooleanOperation.hxx>
#include <NXOpen/GeometricUtilities_FacePlaneSelectionBuilder.hxx>
#include <NXOpen/GeometricUtilities_FacePlaneSelectionBuilderCollection.hxx>
#include <NXOpen/NXObject.hxx>
#include <NXOpen/Part.hxx>
#include <NXOpen/PartCollection.hxx>
#include <NXOpen/Plane.hxx>
#include <NXOpen/PlaneCollection.hxx>
#include <NXOpen/Point.hxx>
#include <NXOpen/PointCollection.hxx>
#include <NXOpen/Preferences_PartModeling.hxx>
#include <NXOpen/Preferences_PartPreferences.hxx>
#include <NXOpen/PropertiesManager.hxx>
#include <NXOpen/ScCollector.hxx>
#include <NXOpen/ScCollectorCollection.hxx>
#include <NXOpen/ScRuleFactory.hxx>
#include <NXOpen/SelectNXObjectList.hxx>
#include <NXOpen/SelectionIntentRule.hxx>
#include <NXOpen/Session.hxx>
#include <NXOpen/TaggedObjectList.hxx>
#include <NXOpen/Unit.hxx>
#include <NXOpen/UnitCollection.hxx>

#include <NXOpen/DisplayableObject.hxx>
#include <NXOpen/DisplayManager.hxx>
#include <NXOpen/DisplayModification.hxx>
#include <NXOpen/Face.hxx>
#include <NXOpen/Body.hxx>
#include <NXOpen/BodyCollection.hxx>
#include <NXOpen/ListingWindow.hxx>
#include <sstream>

#include <NXOpen/MeasureFaces.hxx>
#include <NXOpen/MeasureFaceBuilder.hxx>
#include <NXOpen/SelectDisplayableObjectList.hxx>


//------------------------------------------------------------------------------
// Initialize static variables
//------------------------------------------------------------------------------
Session *(modelingExercise::theSession) = NULL;
UI *(modelingExercise::theUI) = NULL;
//------------------------------------------------------------------------------
// Constructor for NX Styler class
//------------------------------------------------------------------------------
modelingExercise::modelingExercise()
{
    try
    {
        // Initialize the NX Open C++ API environment
        modelingExercise::theSession = NXOpen::Session::GetSession();
        modelingExercise::theUI = UI::GetUI();
        theDlxFileName = "modelingExercise.dlx";
        theDialog = modelingExercise::theUI->CreateDialog(theDlxFileName);
        // Registration of callback functions
        theDialog->AddApplyHandler(make_callback(this, &modelingExercise::apply_cb));
        theDialog->AddOkHandler(make_callback(this, &modelingExercise::ok_cb));
        theDialog->AddUpdateHandler(make_callback(this, &modelingExercise::update_cb));
        theDialog->AddInitializeHandler(make_callback(this, &modelingExercise::initialize_cb));
        theDialog->AddDialogShownHandler(make_callback(this, &modelingExercise::dialogShown_cb));
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        throw;
    }
}

//------------------------------------------------------------------------------
// Destructor for NX Styler class
//------------------------------------------------------------------------------
modelingExercise::~modelingExercise()
{
    if (theDialog != NULL)
    {
        delete theDialog;
        theDialog = NULL;
    }
}
//------------------------------- 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_ROOT_DIR\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)
{
    modelingExercise *themodelingExercise = NULL;
    try
    {
        themodelingExercise = new modelingExercise();
        // The following method shows the dialog immediately
        themodelingExercise->Show();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    if(themodelingExercise != NULL)
    {
        delete themodelingExercise;
        themodelingExercise = 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 -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
}

int modelingExercise::Show()
{
    try
    {
        theDialog->Show();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return 0;
}

//------------------------------------------------------------------------------
//---------------------Block UI Styler Callback Functions--------------------------
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//Callback Name: initialize_cb
//------------------------------------------------------------------------------
void modelingExercise::initialize_cb()
{
    try
    {
        gpexercise = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("gpexercise"));
        btnCreateBlock = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnCreateBlock"));
        btnFillet = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnFillet"));
        btnCalcArea = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("btnCalcArea"));
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::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 modelingExercise::dialogShown_cb()
{
    try
    {
        //---- Enter your callback code here -----
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
}

/*!
 * @brief  创建立方体
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
static int CreateBlock()
{
	Session *theSession = Session::GetSession();
	Part *workPart(theSession->Parts()->Work());
	Part *displayPart(theSession->Parts()->Display());

	Features::Feature *nullFeatures_Feature(NULL);

	Features::BlockFeatureBuilder *blockFeatureBuilder1;
	blockFeatureBuilder1 = workPart->Features()->CreateBlockFeatureBuilder(nullFeatures_Feature);

	blockFeatureBuilder1->BooleanOption()->SetType(GeometricUtilities::BooleanOperation::BooleanTypeCreate);

	std::vector<Body *> targetBodies1(1);
	Body *nullBody(NULL);
	targetBodies1[0] = nullBody;
	blockFeatureBuilder1->BooleanOption()->SetTargetBodies(targetBodies1);

	blockFeatureBuilder1->BooleanOption()->SetType(GeometricUtilities::BooleanOperation::BooleanTypeCreate);

	std::vector<Body *> targetBodies2(1);
	targetBodies2[0] = nullBody;
	blockFeatureBuilder1->BooleanOption()->SetTargetBodies(targetBodies2);

	Point3d coordinates1(0.0, 0.0, 0.0);
	Point *point1;
	point1 = workPart->Points()->CreatePoint(coordinates1);

	Unit *unit1(dynamic_cast<Unit *>(workPart->UnitCollection()->FindObject("MilliMeter")));
	Expression *expression1;
	expression1 = workPart->Expressions()->CreateSystemExpressionWithUnits("0", unit1);

	blockFeatureBuilder1->SetType(Features::BlockFeatureBuilder::TypesOriginAndEdgeLengths);

	blockFeatureBuilder1->SetOriginPoint(point1);

	Point3d originPoint1(0.0, 0.0, 0.0);
	blockFeatureBuilder1->SetOriginAndLengths(originPoint1, "20", "20", "20");

	blockFeatureBuilder1->SetBooleanOperationAndTarget(Features::Feature::BooleanTypeCreate, nullBody);

	Features::Feature *feature1;
	feature1 = blockFeatureBuilder1->CommitFeature();

	blockFeatureBuilder1->Destroy();

	workPart->Expressions()->Delete(expression1);

	//倒圆角
	Features::EdgeBlendBuilder *edgeBlendBuilder1;
	edgeBlendBuilder1 = workPart->Features()->CreateEdgeBlendBuilder(nullFeatures_Feature);

	GeometricUtilities::BlendLimitsData *blendLimitsData1;
	blendLimitsData1 = edgeBlendBuilder1->LimitsListData();

	Point3d origin1(0.0, 0.0, 0.0);
	Vector3d normal1(0.0, 0.0, 1.0);
	Plane *plane1;
	plane1 = workPart->Planes()->CreatePlane(origin1, normal1, SmartObject::UpdateOptionWithinModeling);

	GeometricUtilities::FacePlaneSelectionBuilder *facePlaneSelectionBuilder1;
	facePlaneSelectionBuilder1 = workPart->FacePlaneSelectionBuilderData()->Create();

	ScCollector *scCollector1;
	scCollector1 = workPart->ScCollectors()->CreateCollector();

	std::vector<Edge *> seedEdges1(1);
	Features::Block *block1(dynamic_cast<Features::Block *>(feature1));
	Edge *edge1(dynamic_cast<Edge *>(block1->FindObject("EDGE * 1 * 6 {(20,20,20)(20,10,20)(20,0,20) BLOCK(2)}")));
	seedEdges1[0] = edge1;
	EdgeMultipleSeedTangentRule *edgeMultipleSeedTangentRule1;
	edgeMultipleSeedTangentRule1 = workPart->ScRuleFactory()->CreateRuleEdgeMultipleSeedTangent(seedEdges1, 0.05, true);

	std::vector<SelectionIntentRule *> rules1(1);
	rules1[0] = edgeMultipleSeedTangentRule1;
	scCollector1->ReplaceRules(rules1, false);

	edgeBlendBuilder1->SetTolerance(0.001);

	edgeBlendBuilder1->SetAllInstancesOption(false);

	edgeBlendBuilder1->SetRemoveSelfIntersection(true);

	edgeBlendBuilder1->SetPatchComplexGeometryAreas(true);

	edgeBlendBuilder1->SetLimitFailingAreas(true);

	edgeBlendBuilder1->SetConvexConcaveY(false);

	edgeBlendBuilder1->SetRollOverSmoothEdge(true);

	edgeBlendBuilder1->SetRollOntoEdge(true);

	edgeBlendBuilder1->SetMoveSharpEdge(true);

	edgeBlendBuilder1->SetTrimmingOption(false);

	edgeBlendBuilder1->SetOverlapOption(Features::EdgeBlendBuilder::OverlapAnyConvexityRollOver);

	edgeBlendBuilder1->SetBlendOrder(Features::EdgeBlendBuilder::OrderOfBlendingConvexFirst);

	edgeBlendBuilder1->SetSetbackOption(Features::EdgeBlendBuilder::SetbackSeparateFromCorner);

	int csIndex1;
	csIndex1 = edgeBlendBuilder1->AddChainset(scCollector1, "5");

	Features::Feature *feature2;
	feature2 = edgeBlendBuilder1->CommitFeature();

	workPart->FacePlaneSelectionBuilderData()->Destroy(facePlaneSelectionBuilder1);

	edgeBlendBuilder1->Destroy();

#if 0
	//添加界面属性
	Session::UndoMarkId markId7;
	markId7 = theSession->SetUndoMark(Session::MarkVisibilityVisible, "Start");

	std::vector<NXObject *> objects1(1);
	Features::EdgeBlend *edgeBlend1(dynamic_cast<Features::EdgeBlend *>(feature2));
	objects1[0] = edgeBlend1;
	AttributePropertiesBuilder *attributePropertiesBuilder1;
	attributePropertiesBuilder1 = theSession->AttributeManager()->CreateAttributePropertiesBuilder(workPart, objects1, AttributePropertiesBuilder::OperationTypeNone);

	attributePropertiesBuilder1->SetArray(false);

	attributePropertiesBuilder1->SetDataType(AttributePropertiesBaseBuilder::DataTypeOptionsString);

	attributePropertiesBuilder1->SetUnits("MilliMeter");

	std::vector<NXObject *> objects2(1);
	objects2[0] = edgeBlend1;
	FeatureGeneralPropertiesBuilder *featureGeneralPropertiesBuilder1;
	featureGeneralPropertiesBuilder1 = workPart->PropertiesManager()->CreateFeatureGeneralPropertiesBuilder(objects2);

	theSession->SetUndoMarkName(markId7, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247 \345\257\271\350\257\235\346\241\206", NXString::UTF8));

	attributePropertiesBuilder1->DateValue()->DateItem()->SetDay(DateItemBuilder::DayOfMonthDay23);

	attributePropertiesBuilder1->DateValue()->DateItem()->SetMonth(DateItemBuilder::MonthOfYearApr);

	attributePropertiesBuilder1->DateValue()->DateItem()->SetYear("2023");

	attributePropertiesBuilder1->DateValue()->DateItem()->SetTime("00:00:00");

	std::vector<NXObject *> objects3(1);
	objects3[0] = edgeBlend1;
	attributePropertiesBuilder1->SetAttributeObjects(objects3);

	attributePropertiesBuilder1->SetUnits("MilliMeter");

	attributePropertiesBuilder1->SetCategory("class");

	attributePropertiesBuilder1->SetTitle("FaceType");

	attributePropertiesBuilder1->SetArray(false);

	Session::UndoMarkId markId8;
	markId8 = theSession->SetUndoMark(Session::MarkVisibilityInvisible, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	attributePropertiesBuilder1->SetStringValue("cylinder");

	theSession->DeleteUndoMark(markId8, NULL);

	Session::UndoMarkId markId9;
	markId9 = theSession->SetUndoMark(Session::MarkVisibilityInvisible, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	NXObject *nXObject1;
	nXObject1 = attributePropertiesBuilder1->Commit();

	NXObject *nXObject2;
	nXObject2 = featureGeneralPropertiesBuilder1->Commit();

	theSession->DeleteUndoMark(markId9, NULL);

	theSession->SetUndoMarkName(markId7, NXString("\350\276\271\345\200\222\345\234\206\345\261\236\346\200\247", NXString::UTF8));

	attributePropertiesBuilder1->Destroy();

	featureGeneralPropertiesBuilder1->Destroy();

#else
	//NXOpen对部件加属性
	BodyCollection* bc = workPart->Bodies();

	//遍历所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		std::vector<NXOpen::Face *> faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			// 获取选择的面
			NXOpen::Face* face = dynamic_cast<NXOpen::Face*>(faces[j]);

			//找到圆角面,并且添加属性FaceType
			if (faces[j]->SolidFaceType() == Face::FaceTypeCylindrical)
			{
				Face* faceCylindrical = faces[j];

				std::vector<NXObject *> objects1(1);
				objects1[0] = faceCylindrical;

				AttributePropertiesBuilder *attributePropertiesBuilder1;
				attributePropertiesBuilder1 = theSession->AttributeManager()->CreateAttributePropertiesBuilder(workPart, objects1, AttributePropertiesBuilder::OperationTypeNone);
				attributePropertiesBuilder1->SetTitle("FaceType");
				attributePropertiesBuilder1->SetStringValue("cylinder");
				NXObject *nXObject1;
				nXObject1 = attributePropertiesBuilder1->Commit();

				attributePropertiesBuilder1->Destroy();
			}
		}
	}
#endif

	return 0;
}


/*!
 * @brief  改变面的颜色
 * @return 无
 * @param  对象组,颜色索引
 * @author zhanglu
 * @date   2023/04/24
 */
static void ChangeFaceColor(std::vector<NXOpen::DisplayableObject*> displayableobjects, int color)
{
	Session* theSession = Session::GetSession();
	NXOpen::DisplayModification* displaymodification = theSession->DisplayManager()->NewDisplayModification();
	displaymodification->ApplyToAllFaces();
	displaymodification->SetNewColor(color);
	displaymodification->Apply(displayableobjects);
}

/*!
 * @brief  圆角面涂色
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
int ColorFillet()
{
	// 获取所有的圆角面
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());

	//ListingWindow* lw = theSession->ListingWindow();
	//lw->Open();

	NXOpen::Part* displayPart(theSession->Parts()->Display());

	BodyCollection* bc = workPart->Bodies();

	std::vector<Face*> faces;

	int nFaceTypeCylindricalCount = 0;

	std::stringstream ss;

	std::vector<NXOpen::DisplayableObject*> vDisObjectsToRed;
	std::vector<NXOpen::DisplayableObject*> vDisObjectsToWhite;

	//便利所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			// 获取选择的面		
#if 1
			NXOpen::Face* face = dynamic_cast<NXOpen::Face*>(faces[j]);

			//std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetAttributeTitlesByType(NXOpen::NXObject::AttributeType::AttributeTypeString);
			std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetUserAttributes(NXOpen::NXObject::AttributeType::AttributeTypeString);

			int a = vAttributes.size();
			for (int k = 0; k < a; ++k)
			{
				std::string sA = vAttributes[k].Title.GetText();

				if (sA == "FaceType")
				{
					Face * faceCylindrical = faces[j];
					if (faces[j]->Color() != 186)
					{
						vDisObjectsToRed.push_back(faceCylindrical);
					}
					else
					{
						vDisObjectsToWhite.push_back(faceCylindrical);
					}
				}
			}
#else
			//找到圆角面
			if (faces[j]->SolidFaceType() == Face::FaceTypeCylindrical)
			{
				Face* faceCylindrical = faces[j];

				nFaceTypeCylindricalCount++;

				//此处为何没能获取界面添加的属性值 非界面正常获取
				//std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faceCylindrical->GetUserAttributes(NXOpen::NXObject::AttributeType::AttributeTypeString);
				std::vector<NXOpen::NXObject::AttributeInformation> vAttributes = faces[j]->GetAttributeTitlesByType(NXOpen::NXObject::AttributeType::AttributeTypeString);

				ss << vAttributes.size() << std::endl;

				for (int j = 0; j < vAttributes.size(); ++j)
				{
					lw->WriteLine(vAttributes[j].Title.GetText());
				}

				if (faces[j]->Color() != 186)
				{
					vDisObjectsToRed.push_back(faceCylindrical);
				}
				else
				{
					vDisObjectsToWhite.push_back(faceCylindrical);
				}
			}
#endif
		}
	}

	ChangeFaceColor(vDisObjectsToRed, 186);
	ChangeFaceColor(vDisObjectsToWhite, 1);

	//lw->WriteLine(ss.str());

	return 0;
}

/*!
 * @brief  求面积
 * @return 0
 * @param  面对象,面积
 * @author zhanglu
 * @date   2023/04/24
 */
static void AskFaceAreas(Face* face, double& areaValue)
{
	//获取面积
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());
	NXOpen::Part* displayPart(theSession->Parts()->Display());

	NXObject* nullNXObject(NULL);
	NXOpen::MeasureFaceBuilder* measureFaceBuilder1;
	measureFaceBuilder1 = workPart->MeasureManager()->CreateMeasureFaceBuilder(nullNXObject);
	std::vector<IParameterizedSurface*> objects1(1);
	objects1[0] = face;

	MeasureFaces* measureFaces1;
	Unit* unit1 = workPart->UnitCollection()->FindObject("SquareMilliMeter");
	Unit* unit2 = workPart->UnitCollection()->FindObject("MilliMeter");
	measureFaces1 = workPart->MeasureManager()->NewFaceProperties(unit1, unit2, 0.9999, objects1);

	measureFaceBuilder1->FaceObjects()->Clear();
	measureFaceBuilder1->Destroy();
	theSession->CleanUpFacetedFacesAndEdges();
	areaValue = measureFaces1->Area();
}

/*!
 * @brief  获取红色面的面积
 * @return 0
 * @param  无
 * @author zhanglu
 * @date   2023/04/24
 */
static int CalcArea()
{
	// 获取所有的圆角面
	NXOpen::Session* theSession = NXOpen::Session::GetSession();
	NXOpen::Part* workPart(theSession->Parts()->Work());
	ListingWindow* lw = theSession->ListingWindow();

	NXOpen::Part* displayPart(theSession->Parts()->Display());

	BodyCollection* bc = workPart->Bodies();

	std::vector<Face*> faces;

	stringstream ss;

	std::vector<NXOpen::DisplayableObject*> vDisObjectsToCalcArea;

	double dArea = 0.0;

	//便利所有体
	for (auto it = bc->begin(); it != bc->end(); ++it)
	{
		Body* body = *it;
		faces = body->GetFaces();

		for (size_t j = 0; j < faces.size(); j++)
		{
			if (faces[j]->Color() == 186)
			{
				double areaValue;
				AskFaceAreas(faces[j], areaValue);

				dArea += areaValue;
			}
		}
	}

	lw->Open();

	NXOpen::NXString strInfo;

	ss << dArea;

	lw->WriteLine(ss.str());

	return 0;
}


//------------------------------------------------------------------------------
//Callback Name: apply_cb
//------------------------------------------------------------------------------
int modelingExercise::apply_cb()
{
    int errorCode = 0;
    try
    {
        //---- Enter your callback code here -----
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        errorCode = 1;
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return errorCode;
}

//------------------------------------------------------------------------------
//Callback Name: update_cb
//------------------------------------------------------------------------------
int modelingExercise::update_cb(NXOpen::BlockStyler::UIBlock* block)
{
    try
    {
        if(block == btnCreateBlock)
        {
        //---------Enter your code here-----------
			if (CreateBlock() != 0)
			{

			}
        }
        else if(block == btnFillet)
        {
        //---------Enter your code here-----------
			if (ColorFillet() != 0)
			{

			}
        }
        else if(block == btnCalcArea)
        {
        //---------Enter your code here-----------
			if (CalcArea() != 0)
			{
				
			}
        }
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return 0;
}

//------------------------------------------------------------------------------
//Callback Name: ok_cb
//------------------------------------------------------------------------------
int modelingExercise::ok_cb()
{
    int errorCode = 0;
    try
    {
        errorCode = apply_cb();
    }
    catch(exception& ex)
    {
        //---- Enter your exception handling code here -----
        errorCode = 1;
        modelingExercise::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
    }
    return errorCode;
}

//------------------------------------------------------------------------------
//Function Name: GetBlockProperties
//Description: Returns the propertylist of the specified BlockID
//------------------------------------------------------------------------------
PropertyList* modelingExercise::GetBlockProperties(const char *blockID)
{
    return theDialog->GetBlockProperties(blockID);
}

欢迎交流与讨论。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/829982.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Netty:ByteBuf的引用计数

说明 Netty的ByteBuf有一个对它本身的引用计数。 可以通过ByteBuf的retain()增加1个引用计数&#xff0c;通过retain(int increment)增加一定数量的引用计数。 通过release()减少1个引用计数&#xff0c;通过release(int decrement)减少一定数量的引用计数。 通过refCnt()查看…

科普 | 以太坊坎昆升级是什么

坎昆升级是什么 坎昆&#xff0c;是墨西哥一个著名的旅游城市&#xff0c;也是 Devcon 3 大会的举办地&#xff0c;按照以太坊升级命名的规律&#xff0c;以地名命名的升级&#xff0c;是针对以太坊执行层的升级。 之前同样命名的还有柏林升级、伦敦升级和这次的上海升级等。…

webapi部署几个错误

第一个错误&#xff1a;无法读取配置节“system.serviceModel”&#xff0c;因为它缺少节声明 发现服务器上没有安装.net Framework 3.5.1 第二个错误&#xff1a;未能从程序集“SYSTEM.SERVICEMODEL, VERSION3.0.0.0 先安装.net framework 4.0再安装 3.5 就会出现这个问题…

8.3线程状态

new: 调用start()方法之前的状态. blocked: 因为锁而阻塞. waiting: 因为调用wait()方法而阻塞. timed_waiting: 因为调用sleep()方法而阻塞. terminated: run()方法执行完毕之后线程的状态.

opencv-33 图像平滑处理-中值滤波cv2.medianBlur()

中值滤波是一种常见的图像处理滤波技术&#xff0c;用于去除图像中的噪声。它的原理是用一个滑动窗口&#xff08;也称为卷积核&#xff09;在图像上移动&#xff0c;对窗口中的像素值进行排序&#xff0c;然后用窗口中像素值的中值来替换中心像素的值。这样&#xff0c;中值滤…

【Valgrind】Valgrind安装(ubuntu系统)

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

SonarQube入门 - 搭建本地环境

一、SonarQube是什么&#xff1f; SonarQube是一种自我管理的自动代码审查工具&#xff0c;可以系统地帮助您交付干净的代码。作为我们Sonar 解决方案的核心元素 &#xff0c;SonarQube 集成到您现有的工作流程中并检测代码中的问题&#xff0c;以帮助您对项目执行持续的代码检…

GD32F103VE点灯

GD32F103VE点灯主要用来学习端口引脚的输出配置。它由LED.c&#xff0c;LED.h&#xff0c;SoftDelay.c和main.c组成。 #include "gd32f10x.h" //使能uint8_t,uint16_t,uint32_t,uint64_t,int8_t,int16_t,int32_t,int64_t #include "SoftDelay.h"#include …

企业微信小程序在调用wx.qy.login时返回错误信息qy.login:fail

原因是大概是绑定了多个企业但是在开发者工具中没有选择正确的企业 解决方法&#xff1a; 重新选择企业后即可成功获取code

BS框架说明

B/S架构 1.B/S框架&#xff0c;意思是前端&#xff08;Browser 浏览器&#xff0c;小程序、app、自己写的&#xff09;和服务器端&#xff08;Server&#xff09;组成的系统的框架结构 2.B/S框架&#xff0c;也可理解为web架构&#xff0c;包含前端、后端、数据库三大组成部分…

考研/面试 数据结构大题必会代码(理解+记忆,实现使用C++,STL库)

文章目录 一. 线性表1. 逆置顺序表所有元素2. 删除线性链表中数据域为 item 的所有结点3. 逆转线性链表(递归(快速解题)非递归)4. 复制线性链表&#xff08;递归&#xff09;5. 将两个按值有序排列的非空线性链表合并为一个按值有序的线性链表 二. 树1. 建立二叉树&#xff08;…

【快应用】同时传递事件对象和自定义参数 ,无法正确接收事件对象

【关键词】 事件绑定、自定义参数、事件对象 【问题背景】 在快应用中采用如下方式绑定组件的事件方法&#xff0c;同时传递事件对象和自定义参数&#xff0c;发现回调方法中没有正确接收到事件对象。 问题代码如下&#xff1a; <template><!-- Only one root nod…

2023年信息系统项目管理师-粗略了解整体主要知识脉络

1. 五大过程组 2.十大知识领域 3. 十大知识领域与五大过程组的关系 4. 十大知识领域的关系图

Meta 烧掉百亿豪赌的未来:元宇宙,还有出路吗?

社交平台的下一步是什么&#xff1f; 2021年10月&#xff0c;Facebook联合创始人兼CEO马克扎克伯格在年度 Connect 开发者大会上正式宣布&#xff0c;Facebook公司将更名为Meta。这一举动标志着扎克伯格决心将公司转型为一家“元宇宙公司”&#xff0c;全力投入到元宇宙的技术…

【物联网】DMA传输原理与实现详解(超详细)

DMA&#xff08;Direct Memory Access&#xff0c;直接内存访问&#xff09;是一种计算机数据传输方式&#xff0c;允许外围设备直接访问系统内存&#xff0c;而无需CPU的干预。 文章目录 Part 1: DMA的工作原理配置阶段&#xff1a;数据传输阶段&#xff1a; Part 2: DMA数据…

java读写properties文件和xml文件,解决中文乱码问题

文章目录 前言一、properties文件1.1properties格式介绍1.2读取项目resource/templates下面properties并处理中文乱码问题1.3读取本地properties并处理中文乱码问题1.4修改properties文件 二、XML文件2.1xml文件格式2.2读取xml文件2.3写xml文件 前言 在开发当中我们经常需要用…

【NX】NX二次开发中拉伸曲线完整范例

之前做项目测试用到的代码&#xff0c;开发的版本是NX8.5的32位版本&#xff0c;这个代码实现起来也不难&#xff0c;其实就是调用了UG的API而已。 那么我在这里提供完整的代码&#xff1a; //author&#xff1a;autumoon //邮箱&#xff1a;9506163.com //日期&#xff1a;20…

spring AOP学习

概念 面向切面编程横向扩展动态代理 相关术语 动态代理 spring在运行期&#xff0c;生成动态代理对象&#xff0c;不需要特殊的编译器 Spring AOP的底层就是通过JDK动态代理或者CGLIb动态代理技术为目标Bean执行横向织入 目标对象实现了接口&#xff0c;spring使用JDK的ja…

利用微软Bing AI语言大模型辅助提高写代码、阅读代码、解bug的效率

目录 1 怎么才能使用Bing AI 2 Bing AI使用举例 2.1 代码没看懂&#xff0c;可以问Bing AI 2.2 当你不确定你程序理解的是否正确时&#xff0c;可以问Bing AI 2.3 程序编译出现bug&#xff0c;可以问Bing AI 1 怎么才能使用Bing AI 要想使用Bing AI&#xff0c;必须用微软…

【学会动态规划】剑指 Offer II 091. 粉刷房子(14)

目录 动态规划怎么学&#xff1f; 1. 题目解析 2. 算法原理 1. 状态表示 2. 状态转移方程 3. 初始化 4. 填表顺序 5. 返回值 3. 代码编写 写在最后&#xff1a; 动态规划怎么学&#xff1f; 学习一个算法没有捷径&#xff0c;更何况是学习动态规划&#xff0c; 跟我…