Error on custom made rectangle program

Error on custom made rectangle program

Mehmet_Fatih_Turker
Advocate Advocate
1,824 Views
15 Replies
Message 1 of 16

Error on custom made rectangle program

Mehmet_Fatih_Turker
Advocate
Advocate

 

AddReference "System.Drawing"
AddReference "Microsoft.Office.Interop.Excel"
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Sub Main()
    ' Define the list to store rectangle dimensions
    Dim rectangles As New List(Of Tuple(Of Double, Double))
	Dim RectNo As Byte = 1
    Dim length As Double
    Dim width As Double
	Dim oPartCompDef As PartComponentDefinition = ThisApplication.ActiveDocument.ComponentDefinition
	Dim oSketch As PlanarSketch = oPartCompDef.Sketches.Add(oPartCompDef.WorkPlanes.Item(3))
	Dim oOriginPoint As SketchPoint
	Dim oRectangleLines = oSketch.SketchLines
    Dim prevWidth As Double = 0 ' Initialize the previous rectangle's dimensions
	
		Do
			
			done = GetRectangleDimensions(RectNo, prevWidth, length, width)
			If done Then Exit Do ' Exit the loop if the user finishes input	
	        rectangles.Add(Tuple.Create(length, width)) ' Add the valid rectangle dimensions to the list			
			prevWidth =width
		    RectNo += 1 
			
		Loop Until done
	
	ShowRectangleList(rectangles)

    For Each rect In rectangles
		
		DrawRectangle(oSketch, rect.Item1, rect.Item2)
		ApplyDimsofRectangles(oSketch, oRectangleLines)
    	oOriginPoint = CheckOriginSketchPoint(oPartCompDef, oSketch)
    	CoincidentConstraint(oMidSketchPoint, oOriginPoint, oSketch)
		
    Next
	
End Sub

Function GetRectangleDimensions(RectNo As Byte, prevWidth As Double, ByRef length As Double, ByRef width As Double) As Boolean

	Dim done As Boolean = False
	
	'get length with validation
	length=GetValidatedInput("Ener the length of the" &RectNo.ToString()& "rectangle (or type 'd' to finish)","Rectangle", done)
	If done Then Return True
		width = GetValidatedInput("Enter the width of the " & RectNo.ToString() & " rectangle (or type 'd' to finish)", "Rectangle", done) + prevWidth
	
	If done Then
        MessageBox.Show("You can't finish without specifying the width for this rectangle!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
		
        Return False ' Prevent finishing without width input
    End If
	
	Return False ' Continue the loop
	
End Function

Function GetValidatedInput(prompt As String, title As String, ByRef done As Boolean) As Double

    Dim validInput As Boolean = False
    Dim result As Double = 0
	
	Do
		Dim input As String = InputBox(prompt, title)
		If input.ToLower() = "d" Then
			done = True
			Exit Function 'return from the function if "d" is entered
		End If
		
        Try
            result = CDbl(input)
            validInput = True
        Catch ex As Exception
            MessageBox.Show("Invalid input! Please enter numeric values.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try		
		
		Loop Until validInput
    
	Return result
	
End Function

Sub DrawRectangle(oSketch As PlanarSketch, length As Double, width As Double)

    Dim halfLength As Double = length / 20
    Dim halfWidth As Double = width / 20

    ' Validate dimensions
    If halfLength <= 0 Or halfWidth <= 0 Then
        MessageBox.Show("Invalid dimensions: length=" & length & ", width=" & width)
        Exit Sub
    End If

    ' Create points
    Dim centerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, 0)
    Dim cornerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(halfLength, halfWidth)

    ' Ensure points are valid
    If centerPoint Is Nothing Or cornerPoint Is Nothing Then
        MessageBox.Show("Invalid points: Center or Corner point is null")
        Exit Sub
    End If

    ' Add rectangle
    Try
        oRectangleLines = oSketch.SketchLines.AddAsTwoPointCenteredRectangle(centerPoint, cornerPoint)
    Catch ex As Exception
        MessageBox.Show("Error adding rectangle: " & ex.Message)
    End Try
	
End Sub

Sub ApplyDimsofRectangles(oSketch As PlanarSketch, oRectangleLines As SketchLines)

    ' Extract the lines for dimensioning	
	Dim oLine3 As SketchLine = oRectangleLines(3)
	Dim oLine2 As SketchLine = oRectangleLines(2)
	' Create valid Point2d objects for dimension text locations
    
	Dim oDimPositionHorizontal As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, oLine3.StartSketchPoint.Geometry.Y + 1)
	
    Dim oDimPositionVertical As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(oLine2.StartSketchPoint.Geometry.X + 1, 0)

    ' Add dimension constraints to the rectangle 'oLine1.StartSketchPoint.Geometry.X + 1 'oLine2.StartSketchPoint.Geometry.Y + 10
	
	Try
		
         oSketch.DimensionConstraints.AddTwoPointDistance(oLine3.StartSketchPoint, oLine3.EndSketchPoint, DimensionOrientationEnum.kHorizontalDim, oDimPositionHorizontal)
		 
    Catch ex As Exception
        MessageBox.Show("Error adding horizontal dimension: " & ex.Message)
    End Try

    Try
		
         oSketch.DimensionConstraints.AddTwoPointDistance(oLine2.StartSketchPoint, oLine2.EndSketchPoint, DimensionOrientationEnum.kVerticalDim, oDimPositionVertical)

    Catch ex As Exception
        MessageBox.Show("Error adding vertical dimension: " & ex.Message)
    End Try

End Sub

Sub CoincidentConstraint(SketchPnt1 As SketchPoint, SketchPnt2 As SketchPoint, Sketch As PlanarSketch)
    Try
        Sketch.GeometricConstraints.AddCoincident(SketchPnt1, SketchPnt2)
    Catch ex As Exception
        ' Handle the exception if needed
    End Try
End Sub

Function CheckOriginSketchPoint(CompDef As PartComponentDefinition, Sketch As PlanarSketch) As SketchPoint
    Dim OriginSketchPoint As SketchPoint = Nothing
    For Each pSketchPoint As SketchPoint In Sketch.SketchPoints
        If pSketchPoint.ReferencedEntity IsNot Nothing Then
            OriginSketchPoint = pSketchPoint
            Exit For
        End If
    Next
    If OriginSketchPoint Is Nothing Then
        OriginSketchPoint = Sketch.AddByProjectingEntity(CompDef.WorkPoints(1))
    End If
    Return OriginSketchPoint
End Function


Sub ShowRectangleList(rectangles As List(Of Tuple(Of Double, Double)))
    Dim rectangleListString As String = "Current list of rectangles:" & vbCrLf
    For Each rect In rectangles
        rectangleListString &= "Length: " & rect.Item1 & ", Width: " & rect.Item2 & vbCrLf
    Next
    MessageBox.Show(rectangleListString, "Rectangle List", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

 

 
Hi all is there anyone help me finding error here ? at the first rectangle everything works just fine but when program goes to second and third rectangle. it draws the rectangles but it just doesnt constrain and doesnt put dimension to sketch. Im probably got tired but I just cant see the error...

Mehmet_Fatih_Turker_0-1723472604533.png

 

Thanks in advance

0 Likes
1,825 Views
15 Replies
Replies (15)
Message 2 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

Any help ?

0 Likes
Message 3 of 16

_dscholtes_
Advocate
Advocate

@Mehmet_Fatih_Turker wrote:

 

 

    ' Extract the lines for dimensioning	
	Dim oLine3 As SketchLine = oRectangleLines(3)
	Dim oLine2 As SketchLine = oRectangleLines(2)

 

 

I'm pretty sure, those indexes (2 and 3) are not correct after adding your second rectangle. I expect it's using the same lines and location points to place the dimensions for each rectangle, therefore placing identical dimensions on top of each-other.

0 Likes
Message 4 of 16

J-Camper
Advisor
Advisor
Accepted solution

@Mehmet_Fatih_Turker,

I tried not to modify the format too much, but the biggest issue I saw was you were treating non global variables as global.  I changed some of your sub routines to functions.  Try This:

AddReference "System.Drawing"
AddReference "Microsoft.Office.Interop.Excel"
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Sub Main()
    ' Define the list to store rectangle dimensions
    Dim rectangles As New List(Of Tuple(Of Double, Double))
	Dim RectNo As Byte = 1
    Dim length As Double
    Dim width As Double
	Dim oPartCompDef As PartComponentDefinition = ThisApplication.ActiveDocument.ComponentDefinition
	Dim oSketch As PlanarSketch = oPartCompDef.Sketches.Add(oPartCompDef.WorkPlanes.Item(3))
	Dim oOriginPoint As SketchPoint
	Dim oRectangleLines As SketchEntitiesEnumerator'= oSketch.SketchLines
	Dim oMidSketchPoint As SketchPoint
	
		Do
			Dim InputTuple As Tuple(Of Double, Double) = GetRectangleDimensions(RectNo)
			done = InputTuple Is Nothing
			If done Then Exit Do ' Exit the loop if the user finishes input	
	        rectangles.Add(InputTuple) ' Add the valid rectangle dimensions to the list			
		    RectNo += 1 
		Loop Until done
	
	ShowRectangleList(rectangles)
	
	oOriginPoint = CheckOriginSketchPoint(oPartCompDef, oSketch)
	
    For Each rect In rectangles
		
		oRectangleLines = DrawRectangle(oSketch, rect.Item1, rect.Item2)
		Logger.Trace(oRectangleLines.Count)
		oMidSketchPoint = ApplyDimsofRectangles(oSketch, oRectangleLines)
    	CoincidentConstraint(oMidSketchPoint, oOriginPoint, oSketch)
		
    Next
	
End Sub

Function GetRectangleDimensions(RectNo As Byte) As Tuple(Of Double, Double)

	Dim done As Boolean = False
	Dim Inputlength As Double = 0.0
	Dim Inputwidth As Double = 1.0
	'get length with validation
	Inputlength = GetValidatedInput("Ener the length of the" &RectNo.ToString()& "rectangle (or type 'd' to finish)","Rectangle", done)
	If Inputlength = 0 Then Return Nothing
	
	While Inputwidth <> 0
		Inputwidth = GetValidatedInput("Enter the width of the " & RectNo.ToString() & " rectangle (or type 'd' to finish)", "Rectangle", done) '+ prevWidth
		If Inputwidth <> 0 Then Exit While
		MessageBox.Show("You can't finish without specifying the width for this rectangle!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
	End While
	
	Return Tuple.Create(Inputlength,Inputwidth) ' Continue the loop
	
End Function

Function GetValidatedInput(prompt As String, title As String, ByRef done As Boolean) As Double

    Dim validInput As Boolean = False
    Dim result As Double = 0
	
	Do
		Dim input As String = InputBox(prompt, title)
		If input.ToLower() = "d" Then
			done = True
			Exit Function 'return from the function if "d" is entered
		End If
		
        Try
            result = CDbl(input)
            validInput = True
        Catch ex As Exception
            MessageBox.Show("Invalid input! Please enter numeric values.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try		
		
		Loop Until validInput
    
	Return result
	
End Function

Function DrawRectangle(oSketch As PlanarSketch, length As Double, width As Double) As SketchEntitiesEnumerator

    Dim halfLength As Double = length / 20
    Dim halfWidth As Double = width / 20

    ' Validate dimensions
    If halfLength <= 0 Or halfWidth <= 0 Then
        MessageBox.Show("Invalid dimensions: length=" & length & ", width=" & width)
        Exit Function
    End If

    ' Create points
    Dim centerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, 0)
    Dim cornerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(halfLength, halfWidth)

    ' Ensure points are valid
    If centerPoint Is Nothing Or cornerPoint Is Nothing Then
        MessageBox.Show("Invalid points: Center or Corner point is null")
        Exit Function
    End If

    ' Add rectangle
    Try
        Return oSketch.SketchLines.AddAsTwoPointCenteredRectangle(centerPoint, cornerPoint)
    Catch ex As Exception
        MessageBox.Show("Error adding rectangle: " & ex.Message)
		Return Nothing
    End Try
End Function

Function ApplyDimsofRectangles(oSketch As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator) As SketchPoint

    ' Extract the lines for dimensioning	
	Dim oLine3 As SketchLine = oRectangleLines(3)
	Dim oLine2 As SketchLine = oRectangleLines(2)
	' Create valid Point2d objects for dimension text locations
    
	Dim oDimPositionHorizontal As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, oLine3.StartSketchPoint.Geometry.Y + 1)
	
    Dim oDimPositionVertical As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(oLine2.StartSketchPoint.Geometry.X + 1, 0)

    ' Add dimension constraints to the rectangle 'oLine1.StartSketchPoint.Geometry.X + 1 'oLine2.StartSketchPoint.Geometry.Y + 10
	
	Try
		
         oSketch.DimensionConstraints.AddTwoPointDistance(oLine3.StartSketchPoint, oLine3.EndSketchPoint, DimensionOrientationEnum.kHorizontalDim, oDimPositionHorizontal)
		 
    Catch ex As Exception
        MessageBox.Show("Error adding horizontal dimension: " & ex.Message)
    End Try

    Try
		
         oSketch.DimensionConstraints.AddTwoPointDistance(oLine2.StartSketchPoint, oLine2.EndSketchPoint, DimensionOrientationEnum.kVerticalDim, oDimPositionVertical)

    Catch ex As Exception
        MessageBox.Show("Error adding vertical dimension: " & ex.Message)
    End Try
	
	Return oSketch.SketchPoints.Item(oSketch.SketchPoints.Count)

End Function

Sub CoincidentConstraint(SketchPnt1 As SketchPoint, SketchPnt2 As SketchPoint, Sketch As PlanarSketch)
    Try
        Sketch.GeometricConstraints.AddCoincident(SketchPnt1, SketchPnt2)
    Catch ex As Exception
        ' Handle the exception if needed
    End Try
End Sub

Function CheckOriginSketchPoint(CompDef As PartComponentDefinition, Sketch As PlanarSketch) As SketchPoint
    Dim OriginSketchPoint As SketchPoint = Nothing
    For Each pSketchPoint As SketchPoint In Sketch.SketchPoints
        If pSketchPoint.ReferencedEntity IsNot Nothing Then
            OriginSketchPoint = pSketchPoint
            Exit For
        End If
    Next
    If OriginSketchPoint Is Nothing Then
        OriginSketchPoint = Sketch.AddByProjectingEntity(CompDef.WorkPoints(1))
    End If
    Return OriginSketchPoint
End Function

Sub ShowRectangleList(rectangles As List(Of Tuple(Of Double, Double)))
    Dim rectangleListString As String = "Current list of rectangles:" & vbCrLf
    For Each rect In rectangles
        rectangleListString &= "Length: " & rect.Item1 & ", Width: " & rect.Item2 & vbCrLf
    Next
    MessageBox.Show(rectangleListString, "Rectangle List", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
0 Likes
Message 5 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

Hi @J-Camper  

 

You have changed lots of think and it was very good for improving my skills. So thank you for that.

 

But another questions rises 🙂

 

		oMidSketchPoint = ApplyDimsofRectangles(oSketch, oRectangleLines)

 

 

 In here ApplyDimsofRectangles returns a point. But that should only to apply dimension on created rectangles(at least from my perspective). Could you please explain why did you use that function in this way, if possible ?

 

 

		Logger.Trace(oRectangleLines.Count)

 

 

Why did you use this method ?

 

	Dim oRectangleLines As SketchEntitiesEnumerator = oSketch.SketchLines

 

Can I keep the rectangle lines as list in order to use it in different place ? Also, can I directly catch one of the lines center point in order to constrain to other point ?

0 Likes
Message 6 of 16

J-Camper
Advisor
Advisor

@Mehmet_Fatih_Turker,

To answer your questions in order:

1. I made it return a point, but I changed how i got the point so it didn't really need to be that way.  My first plan was to return the midpoint of one of the construction lines created in the centerpoint rectangle command.  I changed my mind after setting up the sub as a function because the centerpoint rectangle command already creates a point there.  That point is not included in the SketchEntitiesEnumerator, it only contains the 6 sketchlines, so I'm instead getting the last sketchpoint that was created in the sketch and returning as midpoint.  Getting the last sketchpoint created in the sketch could have been retrieved outside of the function.


TLDR: It didn't need to be a function as i changed how I retrieved the midpoint, but had already set it up as a function.

 

2. The Logger.Trace("String here") creates and entry in the iLogic Log window.  I use this when debugging as it does not required closing a messagebox and you can copy paste out of the log window:

temp_png.png

 

3. The Method used to create a rectangle returns an enumerator of sketchentities.  If you would like to keep a list of them, you can cast the enumerator into an IEnumerable and convert that to a list:

Dim LineList As List(Of SketchLine) = oRectangleLines.Cast(Of SketchLine).ToList()

You would have to keep a list of lists though since you are creating multiple rectangles.  Or you could add each list together into a single large list, depending on what your intention with those sketchlines is.

Let me know you you have any further questions, or if anything you want further explanation on any of my answers.

0 Likes
Message 7 of 16

J-Camper
Advisor
Advisor
Accepted solution

@Mehmet_Fatih_Turker,

Also if you are interested, I have attached a text file with more of the original rule layout changed.  I tried not to modify your original too much in my first post, but I would have gone about things differently if I was starting from scratch.

Message 8 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

Hi @J-Camper Thanks for sharing. I'm also developing my code in order to get aligned with current design scenario.

 

 

AddReference "System.Drawing"
AddReference "Microsoft.Office.Interop.Excel"
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Sub Main()
	
	If Not DocumentTypeValidation(ThisApplication) Then
		 
        Exit Sub ' Exit the main subroutine if validation fails
    
	End If
	
	Dim oThisSession As Inventor.Application = ThisApplication
	Dim oPartCompDef As PartComponentDefinition = oThisSession.ActiveDocument.ComponentDefinition
	Dim asd As PlanarSketch
    Dim rectangles As New List(Of Tuple(Of Double, Double))
	Dim RectNo As Byte = 1
	Dim xprevOffset As Double = 0.0
	Dim yprevOffset As Double = 0.0
	Dim xprevHeight As Double = 0.0
	Dim yprevHeight As Double = 0.0
	Dim RectIndex As Byte = 1
		
	Do 
		
		Dim InputTuple As Tuple(Of Double, Double) = GetRectangleDimensions(RectNo, done)
  		
		If InputTuple Is Nothing Then 
			
			Exit Do	
		
		End If
		
		rectangles.Add(InputTuple)	' Add the dimensions to the list		
		
		RectNo += 1
		
	Loop
	
	ShowRectangleList(rectangles)
	
	Dim oSketch As PlanarSketch = oPartCompDef.Sketches.Add(oPartCompDef.WorkPlanes.Item(3)) 'Create sketch after getting rect values
	Dim oOriginPoint as SketchPoint = CheckOriginSketchPoint(oPartCompDef, oSketch)
	Dim prevRectangleLines As SketchEntitiesEnumerator = Nothing ' To store the lines of the previous rectangle
	Dim prevMidOfThirdLine As SketchPoint = Nothing ' To store the midpoint of the third line of the previous rectangle


    For Each rect In rectangles
		
		Dim currentRectangleLines  = DrawRectangle(oSketch, rect.Item1, rect.Item2) ' Draw the rectangle using the dimensions
		ApplyDimsofRectangles(oSketch, currentRectangleLines, RectIndex, xprevOffset, yprevOffset, xprevHeight, yprevHeight)
    	Dim currentMidOfFirstLine = GetMidpointOfLinesMiddlePoint(oSketch, currentRectangleLines)
    	Dim currentMidOfThirdLine = GetRectThirdlineMidPoint(oSketch, currentRectangleLines)
		
		If RectIndex = 1 Then
			
        	' First rectangle: Constrain its first line midpoint to the origin
        	CoincidentConstraint(currentMidOfFirstLine, oOriginPoint, oSketch)
			
		Else
			
        	' Constrain the first line midpoint of the current rectangle to the third line midpoint of the previous rectangle
        	CoincidentConstraint(currentMidOfFirstLine, prevMidOfThirdLine, oSketch)
			
    	End If
		
'		currentMidOfThirdLine = GetRectThirdlineMidPoint(oSketch, currentRectangleLines)
		prevMidOfThirdLine = currentMidOfThirdLine 
		
		RectIndex += 1
		
    Next
	
	oThisSession.ActiveView.GoHome()
	oThisSession.ActiveDocument.save()
	
End Sub

Function GetRectangleDimensions(RectNo As Byte, ByRef done As Boolean) As Tuple(Of Double, Double)

    Dim Inputlength As Double = 0.0
    Dim Inputwidth As Double = 0.0

    ' Get length with validation
    Inputlength = GetValidatedInput("Enter the length of the " & RectNo.ToString() & " rectangle (or type 'd' to finish)", "Rectangle", done)
    
    If done Then Return Nothing ' Exit if the user finishes input during length entry
    
    Do
        ' Get width with validation, user cannot exit here
        Inputwidth = GetValidatedInput("Enter the width of the " & RectNo.ToString() & " rectangle ", "Rectangle", done) 
        
        If done Then
            done = False ' Reset done flag so that the user cannot exit at this stage
            MessageBox.Show("You can't finish without specifying the width for this rectangle!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            Exit Do ' Exit loop if a valid width is entered
        End If
    
    Loop

    Return Tuple.Create(Inputlength, Inputwidth)

End Function

Function GetValidatedInput(prompt As String, title As String, ByRef done As Boolean) As Double

    Dim validInput As Boolean = False
    Dim result As Double = 0

    While Not validInput
        Dim input As String = InputBox(prompt, title)
		
        If input.ToLower() = "d" Then
			
            done = True
			
            Return 0 ' Return 0 or any default value if "d" is entered
			
        End If
        
        Try
            result = CDbl(input)
			
            If result > 0 Then
				
                validInput = True ' Valid input only if it's positive
				
            Else
				
                MessageBox.Show("Value must be a positive number. Please enter a valid value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            
			End If
            
        Catch ex As Exception
			
            MessageBox.Show("Invalid input! Please enter numeric values.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
		
        End Try
		
    End While
    
    Return result
	
End Function

Function ApplyDimsofRectangles(oSketch As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator, RectIndex As Byte, ByRef xprevOffset As Double, ByRef yprevOffset As Double, ByRef xprevHeight As Double, ByRef yprevHeight As Double) As SketchPoint
	
	Dim oLine3 = oRectangleLines(3) ' Extract the lines for dimensioning
    Dim oLine2 = oRectangleLines(2) ' Extract the lines for dimensioning
	
	Dim xcurrentHeight = oLine3.Length ' Current rectangle's height
	Dim ycurrentHeight = oLine2.Length ' Current rectangle's height

	If RectIndex = 1 Then ' First dimension
		
		xOffset = x
		yOffset = y
		
	ElseIf RectIndex = 2 Then ' Second dimension
		
		xOffset = x + a + (xprevHeight - xcurrentHeight) / 2
		yOffset = y + a + (yprevHeight - ycurrentHeight) / 2
		
	Else ' Subsequent dimensions
		
		xOffset = xprevOffset + a + (xprevHeight - xcurrentHeight) / 2
		yOffset = yprevOffset + a + (yprevHeight - ycurrentHeight) / 2
		
	End If

	xprevOffset = xOffset ' Update xprevOffset for the next rectangle
	yprevOffset = yOffset ' Update yprevOffset for the next rectangle
	xprevHeight = xcurrentHeight ' Update xprevHeight for the next rectangle
	yprevHeight = ycurrentHeight ' Update yprevHeight for the next rectangle
	
	Dim oDimPositionHorizontal = ThisApplication.TransientGeometry.CreatePoint2d(0, oLine3.StartSketchPoint.Geometry.Y + yOffset) ' Create Point2d objects for dimension text locations with updated offsets
	Dim oDimPositionVertical = ThisApplication.TransientGeometry.CreatePoint2d(oLine2.StartSketchPoint.Geometry.X + xOffset, 0) ' Create Point2d objects for dimension text locations with updated offsets

    Try ' Add dimension constraints to the rectangle
		
        oSketch.DimensionConstraints.AddTwoPointDistance(oLine3.StartSketchPoint, oLine3.EndSketchPoint, DimensionOrientationEnum.kHorizontalDim, oDimPositionHorizontal)
		
    Catch ex As Exception
		
        MessageBox.Show("Error adding horizontal dimension: " & ex.Message)
		
    End Try

    Try
		
        oSketch.DimensionConstraints.AddTwoPointDistance(oLine2.StartSketchPoint, oLine2.EndSketchPoint, DimensionOrientationEnum.kVerticalDim, oDimPositionVertical)
    
	Catch ex As Exception
       
	   MessageBox.Show("Error adding vertical dimension: " & ex.Message)
   
    End Try
	
	Return oSketch.SketchPoints.Item(oSketch.SketchPoints.Count) 'SketchPoints.Count returns the last added "SketchPoint" in the collection. 

End Function

Function CoincidentConstraint(SketchPnt1 As SketchPoint, SketchPnt2 As SketchPoint, Sketch As PlanarSketch)

	Try
		
		Return Sketch.GeometricConstraints.AddCoincident(SketchPnt1, SketchPnt2)
	
	Catch ex As Exception  ' Handle the exception if needed
	
	End Try

End Function

Function MidpointConstraint(Point As SketchPoint, Line As SketchLine, Sketch As PlanarSketch)

	Try
		
		Return Sketch.GeometricConstraints.AddMidpoint(Point, Line)
		
	Catch ex As Exception  ' Handle the exception if needed
		
	End Try
	
End Function

Function CheckOriginSketchPoint(CompDef As PartComponentDefinition, Sketch As PlanarSketch) As SketchPoint

    Dim OriginSketchPoint As SketchPoint = Nothing
	
    For Each pSketchPoint As SketchPoint In Sketch.SketchPoints
		
        If pSketchPoint.ReferencedEntity IsNot Nothing Then
			
            OriginSketchPoint = pSketchPoint
			
      		Exit For
        End If
    Next
	
    If OriginSketchPoint Is Nothing Then
		
        OriginSketchPoint = Sketch.AddByProjectingEntity(CompDef.WorkPoints(1))
		
    End If
	
    Return OriginSketchPoint
	
End Function

Function DrawRectangle(oSketch As PlanarSketch, length As Double, width As Double) As SketchEntitiesEnumerator

    Dim halfLength As Double = length / 20
    Dim halfWidth As Double = width / 20

    ' Validate dimensions
    If halfLength <= 0 Or halfWidth <= 0 Then
		
        MessageBox.Show("Invalid dimensions: length=" & length & ", width=" & width)
		
        Return Nothing ' Return Nothing in case of invalid input
		
    End If

    ' Create points
    Dim centerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, 0)
    Dim cornerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(halfLength * 2, halfWidth * 2)

    ' Validate points
    If centerPoint Is Nothing Or cornerPoint Is Nothing Then
		
        MessageBox.Show("Invalid points: Center or Corner point is null")
		
        Return Nothing ' Return Nothing if points are not valid
		
    End If

    Try
		
        ' Add rectangle
        Return oSketch.SketchLines.AddAsTwoPointRectangle(centerPoint, cornerPoint)
		
    Catch ex As Exception
		
        MessageBox.Show("Error adding rectangle: " & ex.Message)
		
        Return Nothing ' Return Nothing on failure
		
    End Try
	
End Function


Function GetMidpointOfLinesMiddlePoint(oSketch As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator) As SketchPoint
	
    Dim midpointSketchPoint As SketchPoint = oSketch.SketchPoints.Add(ThisApplication.TransientGeometry.CreatePoint2d(2, 1))
	
	MidpointConstraint(midpointSketchPoint, oRectangleLines(1) , oSketch)

    Return midpointSketchPoint    ' Return the midpoint as a Point2d object
	
End Function

Function GetRectThirdlineMidPoint(oSketch As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator) As SketchPoint
	
    Dim midpointRectThirdLinePoint As SketchPoint = oSketch.SketchPoints.Add(ThisApplication.TransientGeometry.CreatePoint2d(3, 2))
	
	MidpointConstraint(midpointRectThirdLinePoint, oRectangleLines(3) , oSketch)

    Return midpointRectThirdLinePoint    ' Return the midpoint as a Point2d object
	
End Function

Sub ShowRectangleList(Rectangles As List(Of Tuple(Of Double, Double)))

    Dim TotalRects As Byte = Rectangles.Count
	
	Dim rectangleListString As String = "Total number of rectangles: " & TotalRects.ToString()
	
	rectangleListString &= vbCrLf & "Current list of rectangles:" & vbCrLf
	
    For Each rect In Rectangles
		
        rectangleListString &= "Length: " & rect.Item1 & ", Width: " & rect.Item2 & vbCrLf
		
    Next
	
    MessageBox.Show(rectangleListString, "Rectangle List", MessageBoxButtons.OK, MessageBoxIcon.Information)
	
End Sub

Function DocumentTypeValidation ( oCurrentSession As Inventor.Application ) As Boolean
	
	If oCurrentSession.ActiveDocument Is Nothing Then
		
		MsgBox("No active document found.")
		
		Return False
	
	End If
	
	Dim Doc As PartDocument = TryCast(oCurrentSession.ActiveDocument, PartDocument)

	If Doc Is Nothing Then
		
		MessageBox.Show("This rule works with part documents only.", "iLogic Rule",MessageBoxButtons.OK, MessageBoxIcon.Warning)
	
		Return False
	
	End If
	
	Return True ' If the function reaches here, the active document is a part document

End Function

 

 

It creates rectangles side by side like this.

Mehmet_Fatih_Turker_0-1725609032775.png

Dimensions are just messed up 🙂  I will try to relocate those. I actually want rectangles in my sketch to be mirrored after all rectangles created. But I searched, so far, seems like iLogic doesnt provide mirror feature. Is there anyway to mirror something in skecth via APİ ?

0 Likes
Message 9 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

Hi @J-Camper thanks for sharing

0 Likes
Message 10 of 16

J-Camper
Advisor
Advisor
Accepted solution

The mirror sketch feature builds SymmetryConstraints for new sketch entities.  for line segments, this is as simple as applying symmetry of the start and end points.  For curves, radial and elliptical, it adds symmetry constraints between the center point, sketchcurve, and start/endpoints [if an arc]. Here is test code to examine any Symmetry Constraints in a given sketch:

Dim PickSketch As PlanarSketch = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kSketchObjectFilter, "Select a planar sketch")
If IsNothing(PickSketch) Then Exit Sub ' If nothing gets selected then we're done
	
For Each geoCon As GeometricConstraint In PickSketch.GeometricConstraints
	If geoCon.Type <> ObjectTypeEnum.kSymmetryConstraintObject Then Logger.Trace(CType(geoCon.Type, ObjectTypeEnum).ToString) : Continue For
	
	Dim Highlighter As HighlightSet = ThisApplication.ActiveDocument.CreateHighlightSet
	Highlighter.AddItem(geoCon.EntityOne)
	Highlighter.AddItem(geoCon.EntityTwo)
	Highlighter.AddItem(geoCon.SymmetryLine)
	
	MessageBox.Show("SymmetryConstraint Entities and Symmetry Line", "Pause")
	Highlighter.Clear
Next

 

In order to mimic the mirror feature you would need to create sketch entities of the same type as the originals you want mirrored.  Then create symmetry constraints to define the new entities. 

Let me know if you have any questions.

0 Likes
Message 11 of 16

Mehmet_Fatih_Turker
Advocate
Advocate
AddReference "System.Drawing"
AddReference "Microsoft.Office.Interop.Excel"
Option Explicit On
Option Infer Off
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Sub Main()
	
	If Not DocumentTypeValidation(ThisApplication) Then
		 
        Exit Sub ' Exit the main subroutine if validation fails
    
	End If
	
	Dim oThisSession As Inventor.Application = ThisApplication
	Dim oPartCompDef = oThisSession.ActiveDocument.ComponentDefinition

    Dim rectangles As New List(Of Tuple(Of Double, Double))
	Dim RectNo As Byte = 1
	Dim length As Double = 0.0
	Dim yprevOffset As Double = 0.0
	Dim xLength As Double = 0.0
	Dim yprevHeight As Double = 0.0
	Dim RectIndex As Byte = 1
	Dim isdone As Boolean = False
		
	Do 
		
		Dim InputTuple As Tuple(Of Double, Double) = GetRectangleDimensions(RectNo, isdone)
		
		If InputTuple Is Nothing Then 
			
			Exit Do	
		
		End If
		
		If RectNo = 1 Then
			
			 xLength = InputTuple.Item1
			
		End If
		
		rectangles.Add(InputTuple)	' Add the dimensions to the list		
		
		RectNo += 1
		
	Loop
	
	ShowList(rectangles)
	
	Dim SketchforCore As PlanarSketch = oPartCompDef.Sketches.Add(oPartCompDef.WorkPlanes.Item(3))'Create sketch after getting rect values	
	Dim oOriginPoint As SketchPoint = CheckOriginSketchPoint(oPartCompDef, SketchforCore)
	Dim prevRectangleLines As SketchEntitiesEnumerator = Nothing ' To store the lines of the previous rectangle
	Dim prevMidOfThirdLine As SketchPoint = Nothing ' To store the midpoint of the third line of the previous rectangle
	Dim symmetryLine As SketchLine = CheckYSketchAxis(oPartCompDef, SketchforCore)
	symmetryLine.Construction = True
	
    For Each rect As Tuple(Of Double, Double) In rectangles
		
		Dim currentRectangleLines  = DrawRectangle(SketchforCore,rect.Item1, rect.Item2) ' Draw the rectangle using the dimensions
		ApplyDimsofRectangles(SketchforCore, currentRectangleLines)
    	Dim currentMidOfFirstLine = GetMidpointOfLinesMiddlePoint(SketchforCore, currentRectangleLines)
    	Dim currentMidOfThirdLine = GetRectThirdlineMidPoint(SketchforCore, currentRectangleLines)
		
		If RectIndex = 1 Then
			
        	CoincidentConstraint(currentMidOfFirstLine, oOriginPoint, SketchforCore) ' First rectangle: Constrain its first line midpoint to the origin

		Else
			
        	CoincidentConstraint(currentMidOfFirstLine, prevMidOfThirdLine, SketchforCore) ' Constrain the first line midpoint of the current rectangle to the third line midpoint of the previous rectangle
			
    	End If
		
		If RectIndex < rectangles.Count Then
        
			Dim symmetryRect = SketchforCore.SketchLines.AddAsTwoPointRectangle(ThisApplication.TransientGeometry.CreatePoint2d(0, 0), ThisApplication.TransientGeometry.CreatePoint2d(1, 1))
        	
			AddSymmetryForRectangle(SketchforCore, currentRectangleLines, symmetryRect, symmetryLine) ' Apply symmetry constraints to the rectangle
    	
		End If
				
		prevMidOfThirdLine = currentMidOfThirdLine 
		
		RectIndex += 1
		
    Next
	
	ThisApplication.ActiveView.GoHome()
	ThisApplication.ActiveDocument.save()
	
End Sub

Function ApplyDimsofRectangles(sketchtoApplyDims As PlanarSketch, rectangleLines As SketchEntitiesEnumerator ) As SketchPoint
	
	Dim doc As PartDocument = ThisApplication.ActiveDocument
	Dim compDef As PartComponentDefinition = doc.ComponentDefinition
	Dim params As Inventor.Parameters = compDef.Parameters
	
	Dim horDimName As String = "Length_"
    Dim verDimName As String = "Width_"
	
	Dim oLine3 = rectangleLines(3) ' Extract the lines for dimensioning
    Dim oLine2 = rectangleLines(2) ' Extract the lines for dimensioning

	Dim oLengthDimPositionHorizontal = ThisApplication.TransientGeometry.CreatePoint2d(0, 0) ' Create Point2d for dimension text locations
	Dim oWidthDimPositionVertical = ThisApplication.TransientGeometry.CreatePoint2d(0, 0) ' Create Point2d for dimension text locations
	
	Dim indexHor As Byte = 1
	Dim indexVer As Byte = 1
	

    Try ' Add horizontal dimension constraint
			
		Dim horizontalDim As DimensionConstraint
				
        horizontalDim = sketchtoApplyDims.DimensionConstraints.AddTwoPointDistance(oLine2.StartSketchPoint, oLine2.EndSketchPoint, DimensionOrientationEnum.kVerticalDim, oWidthDimPositionVertical)
        
		Dim newNameHor As String = horDimName & indexHor.ToString()
		
		Dim HorNameExists As Boolean = True
			 
		While HorNameExists 'İs true
			
			HorNameExists = False 'setting variable to false imidiately
			
			For Each param As Inventor.Parameter In params ' iterates over all existing parameters  in the part document to check if the name already exists
				
				If param.Name = newNameHor Then
					
					HorNameExists = True 'setting variable to true if name matches found
					
					Exit For ' exits for each loop with setting variable to true in order to keep the while loop running
				
				End If
			
			Next
		
			If HorNameExists Then ' if variable is true, program gets into if  
				
				indexHor += 1 ' rise up one by one
				newNameHor = horDimName & indexHor.ToString() ' assign new name

			End If
			
		End While 'ends while if variable is false as set at the beginning of loop / iterates again if variable is true
		
		horizontalDim.Parameter.Name = newNameHor ' asigns new name

    Catch ex As Exception
		
        MessageBox.Show("Error adding horizontal dimension: " & ex.Message)
		
    End Try
	
    Try ' Add vertical dimension constraint
		
        Dim verticalDim As DimensionConstraint 

        verticalDim = sketchtoApplyDims.DimensionConstraints.AddTwoPointDistance(oLine3.StartSketchPoint, oLine3.EndSketchPoint, DimensionOrientationEnum.kHorizontalDim, oLengthDimPositionHorizontal) 
		
		Dim newNameVer As String = verDimName & indexVer.ToString()
		
		Dim VerNameExists As Boolean = True
		
		While VerNameExists ' same as above
			
			VerNameExists=False
			
			For Each param As Inventor.Parameter In params
				
				If param.Name = newNameVer Then
					
					VerNameExists = True
					
					Exit For
				
				End If
			
			Next
		
			If VerNameExists Then
				
				indexVer += 1
				newNameVer = verDimName & indexVer.ToString()

			End If
			
		End While
		
		verticalDim.Parameter.Name = newNameVer 
   
	Catch ex As Exception
		
	   MessageBox.Show("Error adding vertical dimension: " & ex.Message)
   
    End Try
	
	Return sketchtoApplyDims.SketchPoints.Item(sketchtoApplyDims.SketchPoints.Count) ' Return the last added SketchPoint

End Function

Function GetRectangleDimensions(thingCount As Byte, ByRef donetoFinish As Boolean) As Tuple(Of Double, Double)

    Dim Inputlength As Double = 0.0
    Dim Inputwidth As Double = 0.0

    Inputlength = GetValidatedInput("Enter the length of the " & thingCount.ToString() & " rectangle (or type 'd' to finish)", "Rectangle", donetoFinish) ' Get length with validation
    
    If donetoFinish Then Return Nothing ' Exit if the user finishes input during length entry
    
    Do

        Inputwidth = GetValidatedInput("Enter the width of the " & thingCount.ToString() & " rectangle ", "Rectangle", donetoFinish) ' Get width with validation, user cannot exit here
        
        If donetoFinish Then
			
            donetoFinish = False ' Reset done flag so that the user cannot exit at this stage
			
            MessageBox.Show("You can't finish without specifying the width for this rectangle!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
			
        Else
			
            Exit Do ' Exit loop if a valid width is entered
			
        End If
    
    Loop

    Return Tuple.Create(Inputlength, Inputwidth)

End Function

Function GetValidatedInput(prompt As String, title As String, ByRef isDonetoValid As Boolean) As Double

    Dim validInput As Boolean = False
    Dim result As Double = 0

    While Not validInput
        Dim input As String = InputBox(prompt, title)
		
        If input.ToLower() = "d" Then
			
            isDonetoValid = True
			
            Return 0 ' Return 0 or any default value if "d" is entered
			
        End If
        
        Try
            result = CDbl(input)
			
            If result > 0 Then
				
                validInput = True ' Valid input only if it's positive
				
            Else
				
                MessageBox.Show("Value must be a positive number. Please enter a valid value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            
			End If
            
        Catch ex As Exception
			
            MessageBox.Show("Invalid input! Please enter numeric values.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
		
        End Try
		
    End While
    
    Return result
	
End Function

Function CheckYSketchAxis (ComponentDefinition As PartComponentDefinition, Sketch As PlanarSketch) As SketchLine
		
    Dim SketchYAxis As SketchLine = Sketch.AddByProjectingEntity(ComponentDefinition.WorkAxes(2))
	
    Return SketchYAxis
	
End Function

Function CoincidentConstraint(Basepoint As SketchPoint, SecondPointtoSellect As SketchPoint, SketchforCoincidentConstraint As PlanarSketch)

	Try
		
		Return SketchforCoincidentConstraint.GeometricConstraints.AddCoincident(Basepoint, SecondPointtoSellect)
	
	Catch ex As Exception  ' Handle the exception if needed
	
	End Try

End Function

Function MidpointConstraint(Point As SketchPoint, baseLine As SketchLine, SketchforMidpointConstraint As PlanarSketch)

	Try
		
		Return SketchforMidpointConstraint.GeometricConstraints.AddMidpoint(Point, baseLine)
		
	Catch ex As Exception  ' Handle the exception if needed
		
	End Try
	
End Function

Function AddSymmetryForRectangle(Sketch As PlanarSketch, thingforBase As SketchEntitiesEnumerator, thingforSymmetry As SketchEntitiesEnumerator, symmetryLine As SketchLine)
    
	Try
       
        Dim lineCount As Integer = thingforBase.Count ' Get the count of lines in the rectangle

        For i As Integer = 1 To lineCount ' Loop through all lines dynamically
           
		   Sketch.GeometricConstraints.AddSymmetry(thingforBase(i), thingforSymmetry(i), symmetryLine)
       
	    Next
    
	Catch ex As Exception
        
		MessageBox.Show("Symmetry Constraint failed: " & ex.Message)
   
    End Try
	
End Function

Function CheckOriginSketchPoint(ComponentDefinition As PartComponentDefinition, Sketch As PlanarSketch) As SketchPoint

    Dim OriginSketchPoint As SketchPoint = Nothing
	
    For Each pSketchPoint As SketchPoint In Sketch.SketchPoints
		
        If pSketchPoint.ReferencedEntity IsNot Nothing Then
			
            OriginSketchPoint = pSketchPoint
			
      		Exit For
        End If
    Next
	
    If OriginSketchPoint Is Nothing Then
		
        OriginSketchPoint = Sketch.AddByProjectingEntity(ComponentDefinition.WorkPoints(1))
		
    End If
	
    Return OriginSketchPoint
	
End Function

Function DrawRectangle(sketchforRect As PlanarSketch, length As Double, width As Double) As SketchEntitiesEnumerator

    If length <= 0 Or width <= 0 Then ' Validate dimensions
		
        MessageBox.Show("Invalid dimensions: length=" & length & ", width=" & width)
		
        Return Nothing ' Return Nothing in case of invalid input
		
    End If

    ' Create points
    Dim centerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(0, 0)
    Dim cornerPoint As Point2d = ThisApplication.TransientGeometry.CreatePoint2d(width/10, length/10)

    ' Validate points
    If centerPoint Is Nothing Or cornerPoint Is Nothing Then
		
        MessageBox.Show("Invalid points: Center or Corner point is null")
		
        Return Nothing ' Return Nothing if points are not valid
		
    End If

    Try
		 
        Return sketchforRect.SketchLines.AddAsTwoPointRectangle(centerPoint, cornerPoint) ' Add rectangle
		
    Catch ex As Exception
		
        MessageBox.Show("Error adding rectangle: " & ex.Message)
		
        Return Nothing ' Return Nothing on failure
		
    End Try
	
End Function

Function GetMidpointOfLinesMiddlePoint(sketchforMidPoint As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator) As SketchPoint
	
    Dim midpointSketchPoint As SketchPoint = sketchforMidPoint.SketchPoints.Add(ThisApplication.TransientGeometry.CreatePoint2d(2, 1))
	
	MidpointConstraint(midpointSketchPoint, oRectangleLines(4) , sketchforMidPoint)

    Return midpointSketchPoint    ' Return the midpoint as a Point2d object
	
End Function

Function GetRectThirdlineMidPoint(sketchforMidPoint As PlanarSketch, oRectangleLines As SketchEntitiesEnumerator) As SketchPoint
	
    Dim midpointRectThirdLinePoint As SketchPoint = sketchforMidPoint.SketchPoints.Add(ThisApplication.TransientGeometry.CreatePoint2d(3, 2))
	
	MidpointConstraint(midpointRectThirdLinePoint, oRectangleLines(2) , sketchforMidPoint)

    Return midpointRectThirdLinePoint    ' Return the midpoint as a Point2d object
	
End Function

Sub ShowList(Things As List(Of Tuple(Of Double, Double)))

    Dim TotalThings As Byte = Things.Count
	
	Dim thingListString As String = "Total number of rectangles: " & TotalThings.ToString()
									thingListString &= vbCrLf & "Current list of rectangles:" & vbCrLf
	
    For Each thing As Tuple(Of Double, Double) In Things
		
        thingListString &= "Length: " & thing.Item1 & ", Width: " & thing.Item2 & vbCrLf
		
    Next
	
    MessageBox.Show(thingListString, "Rectangle List", MessageBoxButtons.OK, MessageBoxIcon.Information)
	
End Sub

Function DocumentTypeValidation ( oSession As Inventor.Application ) As Boolean
	
	If oSession.ActiveDocument Is Nothing Then
		
		MsgBox("No active document found.")
		
		Return False
	
	End If
	
	Dim Doc As PartDocument = TryCast(oSession.ActiveDocument, PartDocument)

	If Doc Is Nothing Then
		
		MessageBox.Show("This rule works with part documents only.", "iLogic Rule",MessageBoxButtons.OK, MessageBoxIcon.Warning)
	
		Return False
	
	End If
	
	Return True ' If the function reaches here, the active document is a part document

End Function

 

@J-Camper Hi again 🙂 Hope this response will not be deleted at all because I couldn't post this response for 2 or 3 times. Thank you for your response and wise approach, it helped me a lot. I first draw my actual rect and random rect as second. then created the function like this 

Function AddSymmetryForRectangle(Sketch As PlanarSketch, thingforBase As SketchEntitiesEnumerator, thingforSymmetry As SketchEntitiesEnumerator, symmetryLine As SketchLine)
    
	Try
       
        Dim lineCount As Integer = thingforBase.Count ' Get the count of lines in the rectangle

        For i As Integer = 1 To lineCount ' Loop through all lines dynamically
           
		   Sketch.GeometricConstraints.AddSymmetry(thingforBase(i), thingforSymmetry(i), symmetryLine)
       
	    Next
    
	Catch ex As Exception
        
		MessageBox.Show("Symmetry Constraint failed: " & ex.Message)
   
    End Try
	
End Function

 

Then used it in main sub like this 

			AddSymmetryForRectangle(SketchforCore, currentRectangleLines, symmetryRect, symmetryLine) ' Apply symmetry constraints to the rectangle

 

and end product is this 

Mehmet_Fatih_Turker_0-1726749152124.png

 

 İts the almost end of this stage 🙂 . As last question, I wanted to relocate dimensions to a proper positions but seems like couldn't menage to do that. First I stored them in Lists regarding their classes like this 

Function AlignHorizontalAndVerticalDimensions(activeSketch As PlanarSketch) As Boolean
	
	Dim horDims As New List(Of DimensionConstraint)
    Dim verDims As New List(Of DimensionConstraint)
	
	Dim oDim As DimensionConstraint
	
    For Each oDim In activeSketch.DimensionConstraints
		
        MessageBox.Show("For succeed")

        ' Check for horizontal and vertical dimensions using DimensionTypeEnum
        If oDim.Type = DimensionTypeEnum.kHorizontalDimensionType Then
			
            oDim.TextPoint = ThisApplication.TransientGeometry.CreatePoint2d(5, 7)
            MessageBox.Show("Horizontal dimension aligned")
            horDims.Add(oDim) ' Store the horizontal dimension if needed

        ElseIf oDim.Type = DimensionTypeEnum.kVerticalDimensionType Then
			
            oDim.TextPoint = ThisApplication.TransientGeometry.CreatePoint2d(15, 8)
            MessageBox.Show("Vertical dimension aligned")
            verDims.Add(oDim) ' Store the vertical dimension if needed
			
        End If
    Next
	
	Return True
	
End Function

and used it in main sub but didnt work so far. Is there any suggestion ?

From that, I will open new topic to ask new question 🙂

0 Likes
Message 12 of 16

J-Camper
Advisor
Advisor

@Mehmet_Fatih_Turker,

You are making the dimension constraints with (0,0) as the text point.  If you change the Text points to be:

 

Vertical Dimension text point = (<X value of Horizontal line segment midpoint> + <offset value>, <Y value of Horizontal line segment midpoint>)

&

Horizontal Dimension text point = (<X value of Vertical line segment midpoint>, <Y value of Vertical line segment midpoint> + <offset value>)

 

in your "ApplyDimsofRectangles" function then your dimensions should be in logical positions:
 

	Dim oLengthDimPositionHorizontal = ThisApplication.TransientGeometry.CreatePoint2d(oLine3.Geometry.MidPoint.X+2, oLine3.Geometry.MidPoint.Y) ' Create Point2d for dimension text locations
	Dim oWidthDimPositionVertical = ThisApplication.TransientGeometry.CreatePoint2d(oLine2.Geometry.MidPoint.X, oLine2.Geometry.MidPoint.Y+2) ' Create Point2d for dimension text locations

 

Let me know if you have any questions

0 Likes
Message 13 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

What I mean was to keep them in a line like for instance, all dimensions at this position at first

Mehmet_Fatih_Turker_1-1726817932259.png

 

 


Then, to that position 

Mehmet_Fatih_Turker_2-1726818025332.png

Program creates rects at default location then apply dimensions then moves those rectangles to required position.When program carries rects to regarding places, dimensions are floating freely, Which means, even though I apply positioning at the stage of ApplyDimsofRectangles, it doesnt remain at required position in the next stages.  




0 Likes
Message 14 of 16

J-Camper
Advisor
Advisor
Accepted solution

@Mehmet_Fatih_Turker,

Okay, the problem you have with your rule is you are checking and ObjectTypeEnum (oDim.Type) against a DimensionTypeEnum, which will always return false and never actually do what is in the If block.

I worked it out in the code below for 2 derived classes of the dimensionconstraint:

Sub Main
	
	Dim PickSketch As PlanarSketch = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kSketchObjectFilter, "Select")
	If IsNothing(PickSketch) Then Exit Sub ' If nothing gets selected then we're done
	
	Dim DimCons As List (Of List(Of DimensionConstraint)) = AlignHorizontalAndVerticalDimensions(PickSketch)
	
End Sub

Function AlignHorizontalAndVerticalDimensions(activeSketch As PlanarSketch) As List(Of List(Of DimensionConstraint))
	Dim OutPutList As New List(Of List(Of DimensionConstraint))
	Dim horDims As New List(Of DimensionConstraint)
    Dim verDims As New List(Of DimensionConstraint)
	
    For Each oDim As DimensionConstraint In activeSketch.DimensionConstraints
		       	
		Dim DimConClasification As DimensionOrientationEnum = GetOrientationFromDimensionConstraint(oDim)
		
		If DimConClasification = Nothing Then Logger.Debug("Function: ""GetOrientationFromDimensionConstraint"" returned ""Nothing""") : Continue For
		
        If DimConClasification = DimensionOrientationEnum.kHorizontalDim
			
            oDim.TextPoint = ThisApplication.TransientGeometry.CreatePoint2d(5, 7)
            'MessageBox.Show("Horizontal dimension aligned")
            horDims.Add(oDim) ' Store the horizontal dimension if needed

        ElseIf DimConClasification = DimensionOrientationEnum.kVerticalDim
			
            oDim.TextPoint = ThisApplication.TransientGeometry.CreatePoint2d(15, 8)
            'MessageBox.Show("Vertical dimension aligned")
            verDims.Add(oDim) ' Store the vertical dimension if needed
		
		Else
			Logger.Debug("Dimension constraint clasification: " & CType(DimConClasification, DimensionOrientationEnum).ToString)
        End If
    Next
	
	If horDims.Count > 0 Then OutPutList.Add(horDims)
	If verDims.Count > 0 Then OutPutList.Add(verDims)
	
	Return OutPutList
	
End Function

Function GetOrientationFromDimensionConstraint(DimCon As DimensionConstraint) As DimensionOrientationEnum

	Select Case DimCon.Type
		Case ObjectTypeEnum.kTwoPointDistanceDimConstraintObject
			Return DimCon.Orientation 'Can be set to aligned, but in current orientation appears vertical or horizontal
			
		Case ObjectTypeEnum.kOffsetDimConstraintObject
			Dim OffsetSkLine As SketchLine = TryCast(DimCon.Line, SketchLine)
			If OffsetSkLine Is Nothing Then 
				Logger.Debug("DimensionConstraint, of type OffsetDimConstraint, did not have a line as offset object")
			Else
				Dim Xdif As Double = OffsetSkLine.Geometry.StartPoint.X - OffsetSkLine.Geometry.EndPoint.X
				Dim Ydif As Double = OffsetSkLine.Geometry.StartPoint.Y - OffsetSkLine.Geometry.EndPoint.Y
				If Xdif = 0 And Ydif = 0
					Logger.Debug("SketchLine X&Y differences are both Zero")
				Else If Xdif = 0 
					Return DimensionOrientationEnum.kHorizontalDim
				Else If Ydif = 0
					Return DimensionOrientationEnum.kVerticalDim
				Else
					Return DimensionOrientationEnum.kAlignedDim
				End If
			End If
			
		Case Else
			Dim DerivedClass As String = CType(DimCon.Type, ObjectTypeEnum).ToString
			DerivedClass = Right(DerivedClass, DerivedClass.Length - 1)
			DerivedClass = Left(DerivedClass, DerivedClass.Length - 6)
			Logger.Debug("DimensionConstraint Orientation not programed for derived class: " & DerivedClass)
	End Select
	
	Return Nothing
		
End Function

 

Let me know if you have any questions

0 Likes
Message 15 of 16

Mehmet_Fatih_Turker
Advocate
Advocate

@J-Camper 

How come did you reach to DimCon.Orientation or DimCon.Line properties ? I couldnt find in DimensionConstraint object. Also it doesnt listed in 

https://help.autodesk.com/view/INVNTOR/2023/ENU/?guid=GUID-7CDE8986-36C4-4AC6-B88B-55481AD3AD5D


0 Likes
Message 16 of 16

J-Camper
Advisor
Advisor
Accepted solution

At the bottom of that web page, there are Derived classes listed.  Derived classes contain methods/properties from the base Class, but also their own methods/properties, which are not in the base.  The "OffsetDim" and "TwoPointDistanceDim" Constraints are the two derived classes for linear dimensions:
temp_png.png
In the code I posted, I check the ObjectTypeEnum, which specifically indicates one of the derived classes instead of the base class, and then process the constraint per the most direct available methods/properties of the specific derived class.

0 Likes