Hello everyone
Im very new to the CATIA software and i was asked to make a VBA macro that when the user runs this macro it will automatically insert the biggest possible blue sphere on the model of the part that was selected by the user
This is the code i got from the internet but it causes errors and i haven't been able to fix it
If anyone could help out in anyway i would appreciate it alot,thanks for reading!
Sub InsertBiggestSphere()
Dim partDocument As partDocument
Set partDocument = CATIA.ActiveDocument
Dim part As part
Set part = partDocument.part
' Call function to find the biggest possible sphere
Dim center As Point, radius As Double
FindBiggestSphere part, center, radius
' Create the sphere
CreateSphere part, center, radius
End Sub
Sub FindBiggestSphere(part As part, ByRef center As Point, ByRef radius As Double)
' Implement your algorithm to find the biggest possible sphere
' This may involve traversing the part's geometry and analyzing the dimensions
' For example, you can loop through all faces in the part to find the maximum
' distance between any two points. The center of the sphere will be the midpoint
' of the line connecting these two points, and the radius will be half of the distance.
Dim bodies As bodies
Set bodies = part.bodies
Dim hybridBody As Body
Set hybridBody = bodies.Item(1) ' Assuming the first body is the one containing your faces
Dim hybridShapes As hybridShapes
Set hybridShapes = hybridBody.hybridShapes
Dim maxDistance As Double
Dim face1 As HybridShapeFaceExplicit
Dim face2 As HybridShapeFaceExplicit
For Each face1 In hybridShapes
If TypeOf face1 Is HybridShapeFaceExplicit Then ' Check if it's a face
For Each face2 In hybridShapes
If TypeOf face2 Is HybridShapeFaceExplicit Then ' Check if it's a face
If face1 <> face2 Then
Distance = CalculateDistance(face1.StartPoint, face2.EndPoint)
If Distance > maxDistance Then
maxDistance = Distance
center = CalculateMidPoint(face1.StartPoint, face2.EndPoint)
radius = Distance / 2
End If
End If
End If
Next face2
End If
Next face1
End Sub
Sub CreateSphere(part As part, center As Point, ByVal radius As Double)
Dim hybridShapeFactory As hybridShapeFactory
Set hybridShapeFactory = part.hybridShapeFactory
' Create the sphere
Dim sphere As HybridShapeSphere
Set sphere = hybridShapeFactory.AddNewSphere(center, radius)
' Update the part
part.update
End Sub
Function CalculateDistance(p1 As Point, p2 As Point) As Double
Dim deltaX As Double
Dim deltaY As Double
Dim deltaZ As Double
deltaX = p1.X - p2.X
deltaY = p1.Y - p2.Y
deltaZ = p1.Z - p2.Z
CalculateDistance = Sqr(deltaX ^ 2 + deltaY ^ 2 + deltaZ ^ 2)
End Function
Function CalculateMidPoint(p1 As Point, p2 As Point) As Point
Dim midPoint As Point
midPoint.X = (p1.X + p2.X) / 2
midPoint.Y = (p1.Y + p2.Y) / 2
midPoint.Z = (p1.Z + p2.Z) / 2
Set CalculateMidPoint = midPoint
End Function