Export Flat Pattern of Sheet Metal parts to .idw with descriptions

Export Flat Pattern of Sheet Metal parts to .idw with descriptions

marcoPNQPT
Contributor Contributor
162 Views
0 Replies
Message 1 of 1

Export Flat Pattern of Sheet Metal parts to .idw with descriptions

marcoPNQPT
Contributor
Contributor

Hi all, 

I have created a rule to run from .iam to extract all sheet metal flat patterns (including from sub-assemblies) and export them to .idw drawing on 1:1 scale. The rule also provides notes for each item with material type, thickness and q.ty. 

The rule prompts the user to browse for a .idw drawing blank. This should be a drawing already existing in the target folder rather then a template drawing. If other items already exist in this drawing the rule will add to them.

I have created this using ChatGPT so the code might be dirty and inefficient.

I would appreciate it if someone versant with iLogic language could optimize the code or debug where necessary. The code seems to be running well so far.

Here's the code:

 

Option Explicit

Sub Main()
Try
' Get the active assembly document
Dim oAsmDoc As AssemblyDocument = TryCast(ThisApplication.ActiveDocument, AssemblyDocument)
If oAsmDoc Is Nothing Then
MsgBox("No active assembly document found.", vbCritical, "Error")
Exit Sub
End If

' Prompt user to select an existing IDW drawing file
Dim currentDocumentPath As String = oAsmDoc.FullFileName
Dim initialDirectory As String = System.IO.Path.GetDirectoryName(currentDocumentPath)
Dim existingDrawingPath As String = BrowseForFile("Select the existing Drawing File", "IDW Files (*.idw)|*.idw", initialDirectory, False)

If String.IsNullOrEmpty(existingDrawingPath) Then
MsgBox("No existing drawing file selected. Exiting.", vbExclamation, "Error")
Exit Sub
End If

' Open the existing drawing document
Dim oDrawingDoc As DrawingDocument = ThisApplication.Documents.Open(existingDrawingPath)
Dim oSheet As Sheet = oDrawingDoc.Sheets.Item(1)

' Dictionary to track processed parts and their quantities
Dim processedParts As New Dictionary(Of String, Integer)

' First pass: Count occurrences of each sheet metal part
CountOccurrences(oAsmDoc.ComponentDefinition.Occurrences, processedParts)

' Second pass: Add flat patterns for unique parts
Dim xPosition As Double = 100 ' Starting X position
Dim yPosition As Double = 100 ' Starting Y position
Dim viewSpacing As Double = 50 ' Spacing between views

For Each partPath In processedParts.Keys
Try
Dim oPartDoc As PartDocument = ThisApplication.Documents.Open(partPath, False)

' Add the flat pattern to drawing
If Not AddFlatPatternToDrawing(oDrawingDoc, oSheet, oPartDoc, processedParts(partPath), xPosition, yPosition) Then
oPartDoc.Close(False)
Continue For
End If

' Update position for next view
xPosition += viewSpacing
If xPosition > 500 Then ' Start new row if we're too far right
xPosition = 100
yPosition += 200
End If

oPartDoc.Close(False)
Catch ex As Exception
MsgBox("Error processing " & System.IO.Path.GetFileName(partPath) & ": " & ex.Message, vbExclamation, "Error")
End Try
Next

' Save the drawing
oDrawingDoc.Update2(True)
MsgBox("Successfully added " & processedParts.Count & " flat patterns to drawing.", vbInformation, "Complete")

Catch ex As Exception
MsgBox("Unexpected error in Main(): " & ex.Message, vbCritical, "Error")
End Try
End Sub

Private Sub CountOccurrences(oOccurrences As ComponentOccurrences, ByRef processedParts As Dictionary(Of String, Integer))
Dim oOccurrence As ComponentOccurrence
For Each oOccurrence In oOccurrences
Try
If oOccurrence.Definition Is Nothing Then Continue For

Dim oPartDoc As PartDocument = TryCast(oOccurrence.Definition.Document, PartDocument)
If oPartDoc IsNot Nothing Then
If TypeOf oPartDoc.ComponentDefinition Is SheetMetalComponentDefinition Then
Dim partPath As String = oPartDoc.FullFileName
If String.IsNullOrEmpty(partPath) Then Continue For

If processedParts.ContainsKey(partPath) Then
processedParts(partPath) += 1
Else
' Only count parts that can actually be unfolded
Dim smCompDef As SheetMetalComponentDefinition = oPartDoc.ComponentDefinition
If smCompDef.HasFlatPattern OrElse CanUnfold(smCompDef) Then
processedParts.Add(partPath, 1)
End If
End If
End If
ElseIf TypeOf oOccurrence.Definition Is AssemblyComponentDefinition Then
CountOccurrences(oOccurrence.SubOccurrences, processedParts)
End If
Catch ex As Exception
MsgBox("Error counting occurrences: " & ex.Message, vbExclamation, "Warning")
End Try
Next
End Sub

Private Function CanUnfold(smCompDef As SheetMetalComponentDefinition) As Boolean
Try
If Not smCompDef.HasFlatPattern Then
smCompDef.Unfold()
End If
Return True
Catch
Return False
End Try
End Function

Private Function AddFlatPatternToDrawing(oDrawingDoc As DrawingDocument, oSheet As Sheet, oPartDoc As PartDocument, quantity As Integer, xPos As Double, yPos As Double) As Boolean
Try
Dim smCompDef As SheetMetalComponentDefinition = oPartDoc.ComponentDefinition
If smCompDef Is Nothing Then Return False

' Ensure we have a flat pattern
If Not smCompDef.HasFlatPattern Then
smCompDef.Unfold()
If Not smCompDef.HasFlatPattern Then
MsgBox(oPartDoc.DisplayName & " has no flat pattern and cannot be unfolded.", vbExclamation, "Skipped")
Return False
End If
End If

' Get thickness - completely rewritten for robustness
Dim thickness As String
Try
If smCompDef.UseSheetMetalStyleThickness Then
thickness = smCompDef.ActiveSheetMetalStyle.Thickness.ToString()
Else
' Safely convert thickness to mm with error handling
Dim thicknessValue As Double = smCompDef.Thickness.Value * 10
thickness = Math.Round(thicknessValue, 2).ToString() & "mm"
End If
Catch
thickness = "Unknown"
End Try

' Get material with error handling
Dim material As String
Try
material = oPartDoc.ComponentDefinition.Material.Name
Catch
material = "Unknown"
End Try

' Create view options
Dim oBaseViewOptions As NameValueMap = ThisApplication.TransientObjects.CreateNameValueMap
oBaseViewOptions.Add("SheetMetalFoldedModel", False)

' Create position point
Dim oPoint0 As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(xPos, yPos)
If Double.IsNaN(oPoint0.X) Or Double.IsNaN(oPoint0.Y) Then
oPoint0 = ThisApplication.TransientGeometry.CreatePoint2d(100, 100)
End If

' Add the base view
Dim oView As DrawingView = oSheet.DrawingViews.AddBaseView( _
oPartDoc, _
oPoint0, _
1.0, _
ViewOrientationTypeEnum.kFrontViewOrientation, _
DrawingViewStyleEnum.kHiddenLineRemovedDrawingViewStyle, _
Nothing, _
Nothing, _
oBaseViewOptions)

If oView Is Nothing Then
MsgBox("Failed to create view for " & oPartDoc.DisplayName, vbExclamation, "Error")
Return False
End If

' Add label with metadata
oView.ShowLabel = True
oView.Label.FormattedText = "ITEM" & vbCrLf & "MATERIAL: " & thickness & " " & material & vbCrLf & "QTY: " & quantity

Return True

Catch ex As Exception
MsgBox("Error adding " & oPartDoc.DisplayName & ": " & ex.Message, vbExclamation, "Error")
Return False
End Try
End Function

Private Function BrowseForFile(title As String, filter As String, initialDirectory As String, isSaveDialog As Boolean) As String
If isSaveDialog Then
Dim saveFileDialog As New System.Windows.Forms.SaveFileDialog()
saveFileDialog.Title = title
saveFileDialog.Filter = filter
saveFileDialog.InitialDirectory = initialDirectory
saveFileDialog.DefaultExt = "idw"
saveFileDialog.AddExtension = True
If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Return saveFileDialog.FileName
Else
Return String.Empty
End If
Else
Dim openFileDialog As New System.Windows.Forms.OpenFileDialog()
openFileDialog.Title = title
openFileDialog.Filter = filter
openFileDialog.InitialDirectory = initialDirectory
If openFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Return openFileDialog.FileName
Else
Return String.Empty
End If
End If
End Function

 

 

0 Likes
163 Views
0 Replies
Replies (0)