Changing all line layers of a subassembly

Changing all line layers of a subassembly

will_roe
Enthusiast Enthusiast
709 Views
2 Replies
Message 1 of 3

Changing all line layers of a subassembly

will_roe
Enthusiast
Enthusiast

I use the below to grey out certain parts in an assembly. I could of sworn this used to work on sub-assemblies but now it doesn't am I wrong?

 

 

Class ThisRule
	Public oTargetName As String
	Public oTargetLayer As String

	Sub Main

		oTargetName = "M21-TEST-001"
		oTargetLayer = "TEST"

		If ThisApplication.ActiveDocument.DocumentType <> _
		DocumentTypeEnum.kDrawingDocumentObject Then Return 'exit rule

		' Get the active drawing document. 
		Dim oDoc As DrawingDocument
		oDoc = ThisApplication.ActiveDocument

		Dim oLayers As LayersEnumerator
		oLayers = oDoc.StylesManager.Layers

		Dim oLayer As Layer
		For Each xLayer In oLayers
			If xLayer.name = oTargetLayer Then
				oLayer = xLayer
				Exit For
			End If
		Next

		If oLayer Is Nothing Then
			MsgBox("No layer named """ & oTargetLayer & """ was found in this drawing." _
			& vbLf & vbLf & "Cannot continue.", , "iLogic")
			Exit Sub
		End If

		Dim oSheets As Sheets
		oSheets = oDoc.Sheets
		Dim oSheet As Sheet

		'get current sheet so it can
		'be made active again later
		Dim oCurrentSheet As Sheet
		oCurrentSheet = oDoc.ActiveSheet

		Dim oViews As DrawingViews
		Dim oView As DrawingView

		' Iterate through the sheets
		For Each oSheet In oSheets
			'activate the sheet
			oSheet.Activate

			'get the collection of view on the sheet
			oViews = oSheet.DrawingViews

			' Iterate through the views on the sheet
			For Each oView In oViews

				If oView.ReferencedDocumentDescriptor Is Nothing Then Continue For
					
				Dim docDesc As DocumentDescriptor
				docDesc = oView.ReferencedDocumentDescriptor

				' Verify that the drawing view is of an assembly. 
				If docDesc.ReferencedDocumentType <> kAssemblyDocumentObject Then
					Continue For
				End If

				' Get the component definition for the assembly. 
				Dim asmDef As AssemblyComponentDefinition
				asmDef = docDesc.ReferencedDocument.ComponentDefinition

				' Process the view, wrapping it in a transaction so the 
				' each view can be undone with a single undo operation. 
				Dim trans As Transaction
				trans = ThisApplication.TransactionManager.StartTransaction( _
				oDoc, "Change drawing view color")

				' Call the recursive function that does all the work. 
				Call ProcessAssemblyColor(oView, asmDef.Occurrences)
				trans.End
			Next
			'update the sheet
			oSheet.Update
		Next

		'return to original sheet	
		oCurrentSheet.Activate

	End Sub


	Private Sub ProcessAssemblyColor(drawView As DrawingView, _
		Occurrences As ComponentOccurrences)

		Logger.Info("------------" & drawView.Name)
		' Iterate through the current collection of occurrences. 
		Dim occ As ComponentOccurrence
		For Each occ In Occurrences
			' Check to see if this occurrence is a part or assembly. 
			If occ.DefinitionDocumentType = kPartDocumentObject Then
				If Not occ.Name.Contains(oTargetName) Then Continue For
				Logger.Info(occ.Name)
				' ** It's a part so process the layer

				' Get the TransientsObjects object to use later. 
				Dim transObjs As TransientObjects
				transObjs = ThisApplication.TransientObjects

				Dim oLayers As LayersEnumerator
				oLayers = drawView.Parent.Parent.StylesManager.layers

				Dim oLayer As Layer
				oLayer = oLayers.Item(oTargetLayer)

				Dim oDoc As DrawingDocument
				oDoc = drawView.Parent.Parent

				' Get all of the curves associated with this occurrence. 
				On Error Resume Next
				Dim drawcurves As DrawingCurvesEnumerator
				drawcurves = drawView.DrawingCurves(occ)
				If Err.Number = 0 Then
					On Error GoTo 0

					' Create an empty collection. 
					Dim objColl As ObjectCollection
					objColl = transObjs.CreateObjectCollection()

					' Add the curve segments to the collection. 
					Dim drawCurve As DrawingCurve
					For Each drawCurve In drawcurves
						Dim segment As DrawingCurveSegment
						For Each segment In drawCurve.Segments
							objColl.Add(segment)
						Next
					Next

					' Change the layer of all of the segments. 
					Call drawView.Parent.ChangeLayer(objColl, oLayer)
				End If
				On Error GoTo 0
			ElseIf occ.DefinitionDocumentType = kAssemblyDocumentObject Then
				' It's an assembly so process its contents. 
				Call ProcessAssemblyColor(drawView, occ.SubOccurrences)
			Else
				Continue For
			End If
		Next
	End Sub
End Class

 

Accepted solutions (1)
710 Views
2 Replies
Replies (2)
Message 2 of 3

WCrihfield
Mentor
Mentor
Accepted solution

Hi @will_roe.  Most of this looks OK, but there are a few places I might have done things a little differently.  I know that top level components (ComponentOccurrence objects), and that ComponentOccurrenceProxy objects will work as input to the DrawingView.DrawingCurves property/method, but I believe that those proxy versions need to be in the context of the top level assembly.  I don't know how much you may already know about proxies and how they work, but it is a fairly complex/advanced topic.  If the component is in a sub-assembly, then that component is seen as a ComponentOccurrenceProxy from the perspective of the top level assembly (or from the parent of the sub-assembly, if deeper).  And if the component is more than one layer deep, you would need to essentially step up that proxy ladder to get to the top level.  What I mean by that is:  get the real ComponentOccurrence object that is within the sub-sub assembly, then use its CreateGeometryProxy method get the proxy of it that is now in the context of the next level parent assembly (sub assembly now), then use the component that represents the sub-assembly, and use its CreateGeometryProxy method to get a reference to the proxy at its parent assembly level, until the proxy's geometry is within the context (the 3D coordinate space) of the top level assembly.  Then you can use that top level proxy to get the drawing curves.  It can be a lot of work by code.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 3 of 3

generico01B97TL
Explorer
Explorer

En un plano 2D (.idw), con este código se puede cambiar de capa todas las piezas que pertenecen a una representación de vista en 3D, en .

 Te ofrece la representación de vista que quieres y la capa a la que quieres enviar esas piezas.

 

Sub Main()
Dim oDrawDoc As DrawingDocument = ThisApplication.ActiveDocument

' 1. Verificar si hay vistas y obtener el archivo 3D de referencia
Dim oSheet As Sheet = oDrawDoc.ActiveSheet
If oSheet.DrawingViews.Count = 0 Then
MessageBox.Show("No hay vistas de dibujo en la hoja activa.", "Aviso")
Exit Sub
End If

Dim oFirstView As DrawingView = oSheet.DrawingViews.Item(1)
Dim oRefDoc As Document = oFirstView.ReferencedDocumentDescriptor.ReferencedDocument

If oRefDoc.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
MessageBox.Show("El modelo referenciado en la primera vista no es un ensamblaje.", "Aviso")
Exit Sub
End If

Dim oAsmDoc As AssemblyDocument = oRefDoc
Dim oAsmDef As AssemblyComponentDefinition = oAsmDoc.ComponentDefinition

' 2. LEER AUTOMÁTICAMENTE LAS REPRESENTACIONES DE VISTA 3D
Dim listaVistas As New ArrayList
Dim oViewRep As DesignViewRepresentation
For Each oViewRep In oAsmDef.RepresentationsManager.DesignViewRepresentations
listaVistas.Add(oViewRep.Name)
Next

' 3. LEER Y FILTRAR CAPAS DE FORMA LIMPIA DESDE EL GESTOR DE ESTILOS
Dim listaCapas As New ArrayList
Dim oLayerItem As Layer

For Each oLayerItem In oDrawDoc.StylesManager.Layers
Dim nombreCapa As String = oLayerItem.Name

' Filtro maestro: Las capas internas del sistema de Inventor empiezan por caracteres especiales
' como un guion bajo "_", o contienen palabras fijas de anotaciones automáticas.
If Not nombreCapa.StartsWith("_") AndAlso _
Not nombreCapa.ToLower().StartsWith("symbol") AndAlso _
Not nombreCapa.ToLower().Contains("border") AndAlso _
Not nombreCapa.ToLower().Contains("title block") Then

listaCapas.Add(nombreCapa)
End If
Next

' Plan de respaldo de seguridad por si las exclusiones fueran demasiado estrictas
If listaCapas.Count = 0 Then
For Each oLayerItem In oDrawDoc.StylesManager.Layers
listaCapas.Add(oLayerItem.Name)
Next
End If

' Ordenar alfabéticamente las capas para tu comodidad visual
listaCapas.Sort()

' 4. MOSTRAR MENÚS EN PANTALLA AL USUARIO
Dim seleccionVista As String = InputListBox("Selecciona la Representación de Vista 3D a procesar:", _
listaVistas, listaVistas.Item(0), "iLogic - Selección de Vista", "Vistas de Diseño Disponibles:")
If seleccionVista = "" Then Exit Sub

' Preselección inteligente de la capa de ejes si existe en tu listado
Dim preseleccionCapa As String = listaCapas.Item(0)
If listaCapas.Contains("Ejes") Then preseleccionCapa = "Ejes"

Dim seleccionCapa As String = InputListBox("Selecciona la Capa de destino para las líneas en el plano:", _
listaCapas, preseleccionCapa, "iLogic - Selección de Capa", "Capas Disponibles en el Editor de Estilos:")
If seleccionCapa = "" Then Exit Sub

' 5. Procesar la Capa destino elegida
Dim oLayer As Layer = oDrawDoc.StylesManager.Layers.Item(seleccionCapa)

' 6. Activar la representación 3D elegida para sincronizar las visibilidades
Try
oAsmDef.RepresentationsManager.DesignViewRepresentations.Item(seleccionVista).Activate()
Catch
MessageBox.Show("Error al activar la representación 3D.", "Error")
Exit Sub
End Try

' GUARDADO ULTRA-EFICIENTE: Extraemos todas las piezas y subpiezas visibles mediante AllReferencedOccurrences
Dim componentesVisibles As New List(Of ComponentOccurrence)

For Each oDoc In oAsmDoc.AllReferencedDocuments
Dim oRefOccs As ComponentOccurrencesEnumerator = oAsmDef.Occurrences.AllReferencedOccurrences(oDoc)
For Each oOcc As ComponentOccurrence In oRefOccs
If oOcc.Visible = True Then
componentesVisibles.Add(oOcc)
End If
Next
Next

' Desactivar parpadeo de pantalla para optimizar la velocidad al máximo
ThisApplication.ScreenUpdating = False

' 7. RECORRER TODAS LAS VISTAS Y CAMBIAR LAS CAPAS
Dim contadorLineas As Integer = 0
For Each docSheet As Sheet In oDrawDoc.Sheets
For Each oView As DrawingView In docSheet.DrawingViews
If oView.ReferencedDocumentDescriptor.ReferencedDocument Is oAsmDoc Then
For Each oOcc As ComponentOccurrence In componentesVisibles
Try
Dim oCurves As DrawingCurvesEnumerator = oView.DrawingCurves(oOcc)
If oCurves IsNot Nothing Then
For Each oCurve As DrawingCurve In oCurves
For Each oSegment As DrawingCurveSegment In oCurve.Segments
oSegment.Layer = oLayer
contadorLineas += 1
Next
Next
End If
Catch
' Continúa de forma segura si la pieza no aparece proyectada en esta vista
End Try
Next
End If
Next
Next

' Reactivar la visualización gráfica de Inventor y actualizar el plano
ThisApplication.ScreenUpdating = True
oDrawDoc.Update()

MessageBox.Show("¡Proceso completado con éxito absoluto en toda la estructura!" & vbCrLf & _
"Vista de diseño analizada: " & seleccionVista & vbCrLf & _
"Capa destino aplicada: " & seleccionCapa & vbCrLf & _
"Líneas modificadas: " & contadorLineas, "iLogic Éxito")
End Sub