-
Notifications
You must be signed in to change notification settings - Fork 0
/
rigid_body_transform.txt
254 lines (206 loc) · 9.41 KB
/
rigid_body_transform.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import adsk.core
import adsk.fusion
import traceback
from scipy.spatial.transform import Rotation
import numpy as np
def get_sub_matrix(matrix, rows,cols):
if not isinstance(matrix, adsk.core.Matrix3D):
raise ValueError("La matrice deve essere di tipo Matrix3D di Fusion 360")
sub_matrix = adsk.core.Matrix3D.create()
for row in range(rows):
for col in range(cols):
element = matrix.getCell(row, col)
sub_matrix.setCell(row, col, element)
return sub_matrix
def round_matrix_elements(transformation_matrix, decimal_places=2):
if not isinstance(transformation_matrix, adsk.core.Matrix3D):
raise ValueError("La matrice deve essere di tipo Matrix3D di Fusion 360")
rounded_matrix = adsk.core.Matrix3D.create()
for row in range(4):
for col in range(4):
element = transformation_matrix.getCell(row, col)
rounded_element = round(element, decimal_places)
rounded_matrix.setCell(row, col , rounded_element)
return rounded_matrix
def transpose_matrix(matrix):
# Verifica se la matrice passata è di tipo Matrix3D di Fusion 360
if not isinstance(matrix, adsk.core.Matrix3D):
raise ValueError("La matrice deve essere di tipo Matrix3D di Fusion 360")
# Crea una nuova matrice vuota
transposed_matrix = adsk.core.Matrix3D.create()
# Esegui la trasposta copiando gli elementi dalla matrice originale
for row in range(4):
for col in range(4):
transposed_matrix.setCell(col, row, matrix.getCell(row, col))
return transposed_matrix
def matrix_to_string(matrix):
result = ''
for row in range(4):
for col in range(4):
result += str(matrix.getCell(row, col))
if col < 3:
result += ', '
if row < 3:
result += '\n'
return result
def matrix_to_euler(matrix):
if not isinstance(matrix, adsk.core.Matrix3D):
raise ValueError("La matrice deve essere di tipo Matrix3D di Fusion 360")
R = get_sub_matrix(matrix,3,3)
matrix_float = [[R.getCell(row, col) for col in range(3)] for row in range(3)]
rotation = Rotation.from_matrix(matrix_float)
# Ottieni gli angoli di Eulero (roll, pitch, yaw) in radianti
euler_angles_rad = rotation.as_euler('xyz', degrees=False)
yaw = euler_angles_rad[2]
pitch = euler_angles_rad[1]
roll = euler_angles_rad[0]
return roll, pitch, yaw
def write_to_file(file_path, data):
try:
with open(file_path, 'w') as file:
file.write(data)
except Exception as e:
return str(e)
return None
def vector_to_string(vector):
return f'({vector.x}, {vector.y}, {vector.z})'
def divide_vector(vector, divisor):
return adsk.core.Vector3D.create(round(vector.x,2) / divisor, round(vector.y,2) / divisor, round(vector.z,2) / divisor)
def get_transform(occurrence):
# Ottieni la trasformazione (posa) dell'occorrenza
transform = round_matrix_elements(occurrence.transform2)
#transform = occurrence.transform2
return transform
def normalize(vector):
vector_ = vector.copy()
vector_.normalize()
vector__ = adsk.core.Vector3D.create(round(vector_.x, 2), round(vector_.y, 2), round(vector_.z, 2))
return vector__
def transform_info(transform_):
transform = transform_['transform']
(origin, xAxis, yAxis, zAxis) = transform.getAsCoordinateSystem()
origin = divide_vector(origin,100)
(roll,pitch,yaw) = matrix_to_euler(transform)
transform_info = {
'name': transform_['name'],
'origin': origin,
'xaxis': normalize(xAxis),
'yaxis': normalize(yAxis),
'zaxis': normalize(zAxis),
'roll': roll,
'pitch': pitch,
'yaw': yaw,
'T': transform
}
return transform_info
def write_transforms(file_path, transforms):
try:
with open(file_path, 'w') as file:
for transform in transforms:
transform_i = transform_info(transform)
with open(file_path, 'a') as file:
file.write("Transform of {}\n".format(transform_i['name']))
file.write("Origin: {}\n".format(vector_to_string(transform_i['origin'])))
file.write("X-Axis: {}\n".format(vector_to_string(transform_i['xaxis'])))
file.write("Y-Axis: {}\n".format(vector_to_string(transform_i['yaxis'])))
file.write("Z-Axis: {}\n".format(vector_to_string(transform_i['zaxis'])))
file.write("Roll,Pitch,Yaw: ({},{},{})\n".format(transform_i['roll'],transform_i['pitch'],transform_i['yaw']))
file.write("Transform: \n{}\n\n".format(matrix_to_string(transform_i['T'])))
file.write("----------------------------\n")
error = False
except Exception as e:
error = True
return error
def get_relative_transform(parent,child):
parent_transform_base = get_transform(parent)
child_transform_base = get_transform(child)
base_transform_parent = parent_transform_base.copy()
base_transform_parent.invert()
base_transform_parent_ = np.array(base_transform_parent.asArray()).reshape(4,4)
child_transform_base_ = np.array(child_transform_base.asArray()).reshape(4,4)
child_transform_parent_ = np.dot(base_transform_parent_,child_transform_base_)
child_transform_parent = adsk.core.Matrix3D.create()
for row in range(4):
for col in range(4):
child_transform_parent.setCell(row, col, child_transform_parent_[row,col])
return child_transform_parent
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
design = app.activeProduct
if not design:
ui.messageBox('Nessun documento attivo.')
return
# ottieni lista componenti progetto, occorrenze e giunti
root = design.rootComponent
components = design.allComponents
ui.messageBox("start",'Message')
transforms = []
"""for component in components:
ui.messageBox(component.name,'component')
joints = component.allJoints
for joint in joints:
child = joint.occurrenceOne # child - component1 in the joint definition
parent = joint.occurrenceTwo # parent - component2 in the joint definition
#ui.messageBox(child.name,'child')
#ui.messageBox(parent.name,'parent')
#if child is None: break
#if parent is None: break
transform = get_relative_transform(parent,child)
rel_name = parent.name + "_T_" + child.name
transform_ = {
'name': rel_name,
'transform': transform
}
transforms.append(transform_)"""
# Ottieni la raccolta di tutti gli oggetti di occorrenza nel documento
rigid_groups = root.rigidGroups
for rigid_group in rigid_groups:
ui.messageBox('Gruppo Rigido: {}'.format(rigid_group.name))
# Itera sulle occorrenze dei componenti nel gruppo rigido
'''for occurrence in rigid_group.occurrences:
component = occurrence.component
ui.messageBox(' - Occorrenza del componente: {}'.format(component.name))
'''
num_occurrences = rigid_group.occurrences.count
for i in range(num_occurrences-1):
parent = rigid_group.occurrences.item(i)
ui.messageBox(' - parent: {}'.format(parent.component.name))
child = rigid_group.occurrences.item(i+1)
ui.messageBox(' - child: {}'.format(child.component.name))
transform = get_relative_transform(parent,child)
rel_name = parent.name + "_T_" + child.name
transform_ = {
'name': rel_name,
'transform': transform
}
transforms.append(transform_)
'''
occurrence1 = rigid_group.occurrences.item(0)
ui.messageBox(' - Occurrence1: {}'.format(occurrence1.component.name))
parent = occurrence1
occurrence2 = rigid_group.occurrences.item(1)
ui.messageBox(' - Occurrence2: {}'.format(occurrence2.component.name))
child = occurrence2
transform = get_relative_transform(parent,child)
rel_name = parent.name + "_T_" + child.name
transform_ = {
'name': rel_name,
'transform': transform
}
transforms.append(transform_)
'''
# Specifica il percorso del file in cui scrivere i dati
file_path = 'C:\\Users\\Marco\\Desktop\\Transform_Fusion360\\pose_data.txt'
error = write_transforms(file_path,transforms)
if not(error):
ui.messageBox(f"Le informazioni sulla trasformazione sono state salvate in {file_path}")
else:
ui.messageBox(f"Errore salvataggio file, verifica il percorso: {file_path}")
except:
if ui:
ui.messageBox('An error occurred:\n{}'.format(traceback.format_exc()))
if __name__ == '__main__':
run(None)