Writing Inventor API code that modifies multiple BRep entities

By Philippe Leefsma

I was dealing with a support case recently where the developer was noticing an unexpected behavior: he was selecting multiple faces and his code was iterating through the SelectSet to create multiple MoveFaceFeatures one after the other. The first feature was created successfully, but the subsequent ones will fail.

There are two reasons why such an approach will fail:

1/ The content of the SelectSet will be cleared after each transacting operation, such as a feature creation, so you should store each selected entity in a collection or your custom data structure if the rest of your code is going to perform transaction, directly or as a result of invoking an API method.

2/ After any operation that is going to modify the BRep, you should assume that any pointer to BRep entities isn’t valid anymore, even if the modification was not involving precisely those entities (Faces, Edges and so on…). The correct approach for that scenario is to store ReferenceKeys of the selected entities prior to do any modification to the BRep and use those later when you need to process the entity.

Here is a VBA sample that illustrates the approach. It assumes the user has selected several faces from the UI and will create MoveFaceFeature for each of them:

Sub CreateMoveFace()

    Dim oPart As PartDocument
    Set oPart = ThisApplication.ActiveDocument
   
    Dim oDef As PartComponentDefinition
    Set oDef = oPart.ComponentDefinition
    
    Dim oFace As face, colFaces As FaceCollection
    Dim oMFD As MoveFaceDefinition, oMF As MoveFaceFeature
   
    ‘ Get the reference keys for the selected faces.
    Dim keyContext As Long
    keyContext = oPart.ReferenceKeyManager.CreateKeyContext
   
    Dim keyCollection As New collection
    For Each oFace In oPart.SelectSet
        Dim key() As Byte
        Call oFace.GetReferenceKey(key, keyContext)
        Call keyCollection.Add(key)
    Next
   
    Dim tempKey As Variant
    For Each tempKey In keyCollection


        key = tempKey
        Set oFace = oPart.ReferenceKeyManager.BindKeyToObject( _

            key, keyContext)


        Set colFaces =  _

            ThisApplication.TransientObjects.CreateFaceCollection

        Call colFaces.Add(oFace)

        Set oMFD = oDef.Features.MoveFaceFeatures.CreateDefinition( _

            colFaces)

        Call oMFD.SetDirectionAndDistanceMoveType(0.1, oFace)

        Set oMF = oDef.Features.MoveFaceFeatures.Add(oMFD)

    Next


End Sub


Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading