forked from WPI-AIM/ambf_addon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathambf_addon.py
More file actions
2058 lines (1733 loc) · 93.6 KB
/
ambf_addon.py
File metadata and controls
2058 lines (1733 loc) · 93.6 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Author: Adnan Munawar
# Email: amunawar@wpi.edu
# Lab: aimlab.wpi.edu
bl_info = {
"name": "Asynchronous Multi-Body Framework (AMBF) Config Creator",
"author": "Adnan Munawar",
"version": (0, 1),
"blender": (2, 79, 0),
"location": "View3D > Add > Mesh > AMBF",
"description": "Helps Generate AMBF Config File and Saves both High and Low Resolution(Collision) Meshes",
"warning": "",
"wiki_url": "https://github.com/WPI-AIM/ambf_addon",
"category": "AMBF",
}
import bpy
import math
import yaml
import os
from pathlib import Path
import mathutils
from enum import Enum
from collections import OrderedDict, Counter
from datetime import datetime
# https://stackoverflow.com/questions/31605131/dumping-a-dictionary-to-a-yaml-file-while-preserving-order/31609484
def represent_dictionary_order(self, dict_data):
return self.represent_mapping('tag:yaml.org,2002:map', dict_data.items())
def setup_yaml():
yaml.add_representer(OrderedDict, represent_dictionary_order)
# Enum Class for Mesh Type
class MeshType(Enum):
meshSTL = 0
meshOBJ = 1
mesh3DS = 2
meshPLY = 3
def get_extension(val):
if val == MeshType.meshSTL.value:
extension = '.STL'
elif val == MeshType.meshOBJ.value:
extension = '.OBJ'
elif val == MeshType.mesh3DS.value:
extension = '.3DS'
elif val == MeshType.meshPLY.value:
extension = '.PLY'
else:
extension = None
return extension
def skew_mat(v):
m = mathutils.Matrix.Identity(3)
m.Identity(3)
m[0][0] = 0
m[0][1] = -v.z
m[0][2] = v.y
m[1][0] = v.z
m[1][1] = 0
m[1][2] = -v.x
m[2][0] = -v.y
m[2][1] = v.x
m[2][2] = 0
return m
def vec_norm(v):
return math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
def round_vec(v):
for i in range(0, 3):
v[i] = round(v[i], 3)
return v
# https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/897677#897677
def rot_matrix_from_vecs(v1, v2):
out = mathutils.Matrix.Identity(3)
vcross = v1.cross(v2)
vdot = v1.dot(v2)
rot_angle = v1.angle(v2)
if 1.0 - vdot < 0.1:
return out
elif 1.0 + vdot < 0.1:
# This is a more involved case, find out the orthogonal vector to vecA
nx = mathutils.Vector([1, 0, 0])
temp_ang = v1.angle(nx)
if 0.1 < abs(temp_ang) < 3.13:
axis = v1.cross(nx)
out = out.Rotation(rot_angle, 3, axis)
else:
ny = mathutils.Vector([0, 1, 0])
axis = v1.cross(ny)
out = out.Rotation(rot_angle, 3, axis)
else:
skew_v = skew_mat(vcross)
out = mathutils.Matrix.Identity(3) + skew_v + skew_v * skew_v * ((1 - vdot) / (vec_norm(vcross) ** 2))
return out
# Get rotation matrix to represent rotation between two vectors
# Brute force implementation
def get_rot_mat_from_vecs(vecA, vecB):
# Angle between two axis
angle = vecA.angle(vecB)
# Axis of rotation between child's joints axis and constraint_axis
if abs(angle) <= 0.1:
# Doesn't matter which axis we chose, the rot mat is going to be identity
# as angle is almost 0
axis = mathutils.Vector([0, 1, 0])
elif abs(angle) >= 3.13:
# This is a more involved case, find out the orthogonal vector to vecA
nx = mathutils.Vector([1, 0, 0])
temp_ang = vecA.angle(nx)
if 0.1 < abs(temp_ang) < 3.13:
axis = vecA.cross(nx)
else:
ny = mathutils.Vector([0, 1, 0])
axis = vecA.cross(ny)
else:
axis = vecA.cross(vecB)
mat = mathutils.Matrix()
# Rotation matrix representing the above angular offset
rot_mat = mat.Rotation(angle, 4, axis)
return rot_mat, angle
# Global Variables
class CommonConfig:
# Since there isn't a convenient way of defining parallel linkages (hence detached joints) due to the
# limit on 1 parent per body. We use kind of a hack. This prefix is what we we search for it we find an
# empty body with the mentioned prefix.
detached_joint_prefix = ['redundant', 'Redundant', 'REDUNDANT', 'detached', 'Detached', 'DETACHED']
namespace = ''
num_collision_groups = 20
# Some properties don't exist in Blender are supported in AMBF. If an AMBF file is loaded
# and then resaved, we can capture the extra properties of bodies and joints and take
# them into consideration before re saving the AMBF File so we don't reset those values
loaded_body_map = {}
loaded_joint_map = {}
def update_global_namespace(context):
CommonConfig.namespace = context.scene.ambf_namespace
if CommonConfig.namespace[-1] != '/':
print('WARNING, MULTI-BODY NAMESPACE SHOULD END WITH \'/\'')
CommonConfig.namespace += '/'
context.scene.ambf_namespace += CommonConfig.namespace
def set_global_namespace(context, namespace):
CommonConfig.namespace = namespace
if CommonConfig.namespace[-1] != '/':
print('WARNING, MULTI-BODY NAMESPACE SHOULD END WITH \'/\'')
CommonConfig.namespace += '/'
context.scene.ambf_namespace = CommonConfig.namespace
def get_body_namespace(fullname):
last_occurance = fullname.rfind('/')
_body_namespace = ''
if last_occurance >= 0:
# This means that the name contains a namespace
_body_namespace = fullname[0:last_occurance+1]
return _body_namespace
def remove_namespace_prefix(full_name):
last_occurance = full_name.rfind('/')
if last_occurance > 0:
# Body name contains a namespace
_name = full_name[last_occurance+1:]
else:
# Body name doesn't have a namespace
_name = full_name
return _name
def replace_dot_from_obj_names(char_subs = '_'):
for obj in bpy.data.objects:
obj.name = obj.name.replace('.', char_subs)
def compare_body_namespace_with_global(fullname):
last_occurance = fullname.rfind('/')
_is_namespace_same = False
_body_namespace = ''
_name = ''
if last_occurance >= 0:
# This means that the name contains a namespace
_body_namespace = fullname[0:last_occurance+1]
_name = fullname[last_occurance+1:]
if CommonConfig.namespace == _body_namespace:
# The CommonConfig namespace is the same as the body namespace
_is_namespace_same = True
else:
# The CommonConfig namespace is different form body namespace
_is_namespace_same = False
else:
# The body's name does not contain and namespace
_is_namespace_same = False
# print("FULLNAME: %s, BODY: %s, NAMESPACE: %s NAMESPACE_MATCHED: %d" %
# (fullname, _name, _body_namespace, _is_namespace_same))
return _is_namespace_same
def add_namespace_prefix(name):
return CommonConfig.namespace + name
def get_grand_parent(body):
grand_parent = body
while grand_parent.parent is not None:
grand_parent = grand_parent.parent
return grand_parent
def downward_tree_pass(body, _heirarichal_bodies_list, _added_bodies_list):
if body is None or _added_bodies_list[body] is True:
return
else:
# print('DOWNWARD TREE PASS: ', body.name)
_heirarichal_bodies_list.append(body)
_added_bodies_list[body] = True
for child in body.children:
downward_tree_pass(child, _heirarichal_bodies_list, _added_bodies_list)
def populate_heirarchial_tree():
# Create a dict with {body, added_flag} elements
# The added_flag is to check if the body has already
# been added
_added_bodies_list = {}
_heirarchial_bodies_list = []
for obj in bpy.data.objects:
_added_bodies_list[obj] = False
for obj in bpy.data.objects:
grand_parent = get_grand_parent(obj)
# print('CALLING DOWNWARD TREE PASS FOR: ', grand_parent.name)
downward_tree_pass(grand_parent, _heirarchial_bodies_list, _added_bodies_list)
for body in _heirarchial_bodies_list:
print(body.name, "--->",)
return _heirarchial_bodies_list
# Courtesy: https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file
def prepend_comment_to_file(filename, comment):
temp_filename = filename + '.tmp'
with open(filename,'r') as f:
with open(temp_filename, 'w') as f2:
f2.write(comment)
f2.write(f.read())
os.rename(temp_filename, filename)
def select_all_objects(select=True):
# First deselect all objects
for obj in bpy.data.objects:
obj.select = select
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the major axis by comparing the dimensions of the bounding box
def get_major_axis(dims):
d = dims
axes = {0: 'x', 1: 'y', 2: 'z'}
sum_diff = [abs(d[0] - d[1]) + abs(d[0] - d[2]),
abs(d[1] - d[0]) + abs(d[1] - d[2]),
abs(d[2] - d[0]) + abs(d[2] - d[1])]
# If the bounds are equal, choose the z axis
if sum_diff[0] == sum_diff[1] and sum_diff[1] == sum_diff[2]:
axis_idx = 2
else:
axis_idx = sum_diff.index(max(sum_diff))
return axes[axis_idx], axis_idx
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the median axis (not-major and non-minor or the middle axis) by comparing
# the dimensions of the bounding box
def get_median_axis(dims):
axes = {0: 'x', 1: 'y', 2: 'z'}
maj_ax, maj_ax_idx = get_major_axis(dims)
min_ax, min_ax_idx = get_minor_axis(dims)
med_axes_idx = [1, 1, 1]
med_axes_idx[maj_ax_idx] = 0
med_axes_idx[min_ax_idx] = 0
axis_idx = med_axes_idx.index(max(med_axes_idx))
return axes[axis_idx], axis_idx
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the minor axis by comparing the dimensions of the bounding box
def get_minor_axis(dims):
d = dims
axes = {0: 'x', 1: 'y', 2: 'z'}
sum_diff = [abs(d[0] - d[1]) + abs(d[0] - d[2]),
abs(d[1] - d[0]) + abs(d[1] - d[2]),
abs(d[2] - d[0]) + abs(d[2] - d[1])]
max_idx = sum_diff.index(max(sum_diff))
min_idx = sum_diff.index(min(sum_diff))
sort_idx = [1, 1, 1]
sort_idx[max_idx] = 0
sort_idx[min_idx] = 0
median_idx = sort_idx.index(max(sort_idx))
return axes[median_idx], median_idx
# Body Template for the some commonly used of afBody's data
class BodyTemplate:
def __init__(self):
self._ambf_data = OrderedDict()
self._ambf_data['name'] = ""
self._ambf_data['mesh'] = ""
self._ambf_data['mass'] = 0.0
self._ambf_data['inertia'] = {'ix': 0.0, 'iy': 0.0, 'iz': 0.0}
self._ambf_data['collision margin'] = 0.001
self._ambf_data['scale'] = 1.0
self._ambf_data['location'] = {'position': {'x': 0, 'y': 0, 'z': 0},
'orientation': {'r': 0, 'p': 0, 'y': 0}}
self._ambf_data['inertial offset'] = {'position': {'x': 0, 'y': 0, 'z': 0},
'orientation': {'r': 0, 'p': 0, 'y': 0}}
# self._ambf_data['controller'] = {'linear': {'P': 1000, 'I': 0, 'D': 1},
# 'angular': {'P': 1000, 'I': 0, 'D': 1}}
self._ambf_data['color'] = 'random'
# Transform of Child Rel to Joint, which in inverse of t_c_j
self.t_j_c = mathutils.Matrix()
# Joint Template for the some commonly used of afJoint's data
class JointTemplate:
def __init__(self):
self._ambf_data = OrderedDict()
self._ambf_data['name'] = ''
self._ambf_data['parent'] = ''
self._ambf_data['child'] = ''
self._ambf_data['parent axis'] = {'x': 0, 'y': 0.0, 'z': 1.0}
self._ambf_data['parent pivot'] = {'x': 0, 'y': 0.0, 'z': 0}
self._ambf_data['child axis'] = {'x': 0, 'y': 0.0, 'z': 1.0}
self._ambf_data['child pivot'] = {'x': 0, 'y': 0.0, 'z': 0}
self._ambf_data['joint limits'] = {'low': -1.2, 'high': 1.2}
self._ambf_data['controller'] = {'P': 1000, 'I': 0, 'D': 1}
class GenerateAMBF(bpy.types.Operator):
"""Tooltip"""
bl_idname = "ambf.add_create_ambf_config"
bl_label = "Write Multi-Body AMBF Config"
bl_description = "This generated the AMBF Config file in the location and filename specified in the field" \
" above"
def __init__(self):
self._body_names_list = []
self._joint_names_list = []
self.body_name_prefix = 'BODY '
self.joint_name_prefix = 'JOINT '
self._ambf_yaml = None
def execute(self, context):
self.generate_ambf_yaml(context)
return {'FINISHED'}
# This joint adds the body prefix str if set to all the bodies in the AMBF
def add_body_prefix_str(self, urdf_body_str):
return self.body_name_prefix + urdf_body_str
# This method add the joint prefix if set to all the joints in AMBF
def add_joint_prefix_str(self, urdf_joint_str):
return self.joint_name_prefix + urdf_joint_str
# Courtesy of:
# https://blender.stackexchange.com/questions/62040/get-center-of-geometry-of-an-object
def compute_local_com(self, obj):
vcos = [ v.co for v in obj.data.vertices ]
find_center = lambda l: ( max(l) + min(l)) / 2
x, y, z = [[v[i] for v in vcos] for i in range(3)]
center = [find_center(axis) for axis in [x, y, z]]
for i in range(0, 3):
center[i] = center[i] * obj.scale[i]
return center
def generate_body_data(self, ambf_yaml, obj_handle):
if obj_handle.hide is True:
return
body = BodyTemplate()
body_data = body._ambf_data
if not compare_body_namespace_with_global(obj_handle.name):
if get_body_namespace(obj_handle.name) != '':
body_data['namespace'] = get_body_namespace(obj_handle.name)
obj_handle_name = remove_namespace_prefix(obj_handle.name)
body_yaml_name = self.add_body_prefix_str(obj_handle_name)
output_mesh = bpy.context.scene['mesh_output_type']
body_data['name'] = obj_handle_name
# If the obj is root body of a Multi-Body and has children
# then we should enable the publishing of its joint names
# and joint positions
if obj_handle.parent is None and obj_handle.children:
body_data['publish joint names'] = True
body_data['publish joint positions'] = True
world_pos = obj_handle.matrix_world.translation
world_rot = obj_handle.matrix_world.to_euler()
body_pos = body_data['location']['position']
body_rot = body_data['location']['orientation']
body_pos['x'] = round(world_pos.x, 3)
body_pos['y'] = round(world_pos.y, 3)
body_pos['z'] = round(world_pos.z, 3)
body_rot['r'] = round(world_rot[0], 3)
body_rot['p'] = round(world_rot[1], 3)
body_rot['y'] = round(world_rot[2], 3)
if obj_handle.type == 'EMPTY':
# Check for a special case for defining joints for parallel linkages
_is_detached_joint = False
for _detached_prefix_search_str in CommonConfig.detached_joint_prefix:
if obj_handle_name.rfind(_detached_prefix_search_str) == 0:
_is_detached_joint = True
break
if _is_detached_joint:
print('INFO: JOINT %s FOR PARALLEL LINKAGE FOUND' % obj_handle_name)
return
else:
body_data['mesh'] = ''
if obj_handle_name in ['world', 'World', 'WORLD']:
body_data['mass'] = 0
else:
body_data['mass'] = 0.1
body_data['inertia'] = {'ix': 0.01, 'iy': 0.01, 'iz': 0.01}
elif obj_handle.type == 'MESH':
if obj_handle.rigid_body:
if obj_handle.rigid_body.type == 'PASSIVE':
body_data['mass'] = 0.0
else:
body_data['mass'] = round(obj_handle.rigid_body.mass, 3)
body_data['friction'] = {'rolling': 0.01, 'static': 0.5}
body_data['damping'] = {'linear': 0.1, 'angular': 0.1}
body_data['restitution'] = round(obj_handle.rigid_body.restitution)
body_data['friction']['static'] = round(obj_handle.rigid_body.friction, 3)
body_data['damping']['linear'] = round(obj_handle.rigid_body.linear_damping, 3)
body_data['damping']['angular'] = round(obj_handle.rigid_body.angular_damping, 3)
body_data['collision groups'] = [idx for idx, chk in
enumerate(obj_handle.rigid_body.collision_groups) if chk == True]
if obj_handle.rigid_body.use_margin is True:
body_data['collision margin'] = round(obj_handle.rigid_body.collision_margin, 3)
# Now lets load the loaded data if any from loaded AMBF File
_body_col_geo_already_defined = False
if obj_handle in CommonConfig.loaded_body_map:
if 'controller' in CommonConfig.loaded_body_map[obj_handle]:
body_data['controller'] = CommonConfig.loaded_body_map[obj_handle]['controller']
if 'collision shape' in CommonConfig.loaded_body_map[obj_handle]:
_body_col_geo_already_defined = True
if obj_handle.rigid_body.collision_shape not in ['CONVEX_HULL', 'MESH']:
ocs = obj_handle.rigid_body.collision_shape
# There isn't a mechanism to change the collision shapes much in Blender. For this reason
# if a collision shape has already been defined in the loaded AMBF and it matches the shape
# for the Blender body, just use the shape and geometry from the loaded AMBF Config Body
if _body_col_geo_already_defined and ocs == CommonConfig.loaded_body_map[obj_handle]['collision shape']:
body_data['collision shape'] = CommonConfig.loaded_body_map[obj_handle]['collision shape']
body_data['collision geometry'] = CommonConfig.loaded_body_map[obj_handle]['collision geometry']
else:
body_data['collision shape'] = ocs
bcg = OrderedDict()
dims = obj_handle.dimensions.copy()
od = [round(dims[0], 3), round(dims[1], 3), round(dims[2], 3)]
# Now we need to find out the geometry of the shape
if ocs == 'BOX':
bcg = {'x': od[0], 'y': od[1], 'z': od[2]}
elif ocs == 'SPHERE':
bcg = {'radius': max(od)/2.0}
elif ocs == 'CYLINDER':
major_ax_char, major_ax_idx = get_major_axis(od)
median_ax_char, median_ax_idx = get_median_axis(od)
bcg = {'radius': od[median_ax_idx]/2.0, 'height': od[major_ax_idx], 'axis': major_ax_char}
elif ocs == 'CAPSULE':
major_ax_char, major_ax_idx = get_major_axis(od)
median_ax_char, median_ax_idx = get_median_axis(od)
bcg = {'radius': od[median_ax_idx]/2.0, 'height': od[major_ax_idx], 'axis': major_ax_char}
elif ocs == 'CONE':
major_ax_char, major_ax_idx = get_major_axis(od)
median_ax_char, median_ax_idx = get_median_axis(od)
bcg = {'radius': od[median_ax_idx]/2.0, 'height': od[major_ax_idx], 'axis': major_ax_char}
body_data['collision geometry'] = bcg
del body_data['inertia']
body_data['mesh'] = obj_handle_name + get_extension(output_mesh)
body_com = self.compute_local_com(obj_handle)
body_d_pos = body_data['inertial offset']['position']
body_d_pos['x'] = round(body_com[0], 3)
body_d_pos['y'] = round(body_com[1], 3)
body_d_pos['z'] = round(body_com[2], 3)
if obj_handle.data.materials:
del body_data['color']
body_data['color components'] = OrderedDict()
body_data['color components'] = {'diffuse': {'r': 1.0, 'g': 1.0, 'b': 1.0},
'specular': {'r': 1.0, 'g': 1.0, 'b': 1.0},
'ambient': {'level': 0.5},
'transparency': 1.0}
body_data['color components']['diffuse']['r'] = round(obj_handle.data.materials[0].diffuse_color[0], 4)
body_data['color components']['diffuse']['g'] = round(obj_handle.data.materials[0].diffuse_color[1], 4)
body_data['color components']['diffuse']['b'] = round(obj_handle.data.materials[0].diffuse_color[2], 4)
body_data['color components']['specular']['r'] = round(obj_handle.data.materials[0].specular_color[0], 4)
body_data['color components']['specular']['g'] = round(obj_handle.data.materials[0].specular_color[1], 4)
body_data['color components']['specular']['b'] = round(obj_handle.data.materials[0].specular_color[2], 4)
body_data['color components']['ambient']['level'] = round(obj_handle.data.materials[0].ambient, 4)
body_data['color components']['transparency'] = round(obj_handle.data.materials[0].alpha, 4)
ambf_yaml[body_yaml_name] = body_data
self._body_names_list.append(body_yaml_name)
def generate_joint_data(self, ambf_yaml, obj_handle):
if obj_handle.hide is True:
return
if obj_handle.rigid_body_constraint:
if obj_handle.rigid_body_constraint.object1:
if obj_handle.rigid_body_constraint.object1.hide is True:
return
if obj_handle.rigid_body_constraint.object2:
if obj_handle.rigid_body_constraint.object2.hide is True:
return
if obj_handle.rigid_body_constraint.type in ['FIXED', 'HINGE', 'SLIDER', 'POINT', 'GENERIC', 'GENERIC_SPRING']:
constraint = obj_handle.rigid_body_constraint
joint_template = JointTemplate()
joint_data = joint_template._ambf_data
if constraint.object1:
parent_obj_handle = constraint.object1
child_obj_handle = constraint.object2
parent_obj_handle_name = remove_namespace_prefix(parent_obj_handle.name)
child_obj_handle_name = remove_namespace_prefix(child_obj_handle.name)
obj_handle_name = remove_namespace_prefix(obj_handle.name)
joint_data['name'] = parent_obj_handle_name + "-" + child_obj_handle_name
joint_data['parent'] = self.add_body_prefix_str(parent_obj_handle_name)
joint_data['child'] = self.add_body_prefix_str(child_obj_handle_name)
# parent_body_data = self._ambf_yaml[self.get_body_prefixed_name(parent_obj_handle_name)]
# child_body_data = self._ambf_yaml[self.get_body_prefixed_name(child_obj_handle_name)]
# Since there isn't a convenient way of defining detached joints and hence parallel linkages due
# to the limit on 1 parent per body. We use a hack. This is how it works. In Blender
# we start by defining an empty body that has to have specific prefix as the first word
# in its name. Next we set up the rigid_body_constraint of this empty body as follows. For the RBC
# , we set the parent of this empty body to be the link that we want as the parent for
# the detached joint and the child body as the corresponding child of the detached joint.
# Remember, this empty body is only a place holder and won't be added to
# AMBF. Next, its recommended to set the parent body of this empty body as it's parent in Blender
# and by that I mean the tree hierarchy parent (having set the the parent in the rigid body
# constraint property is different from parent in tree hierarchy). From there on, make sure to
# rotate this empty body such that the z axis / x axis is in the direction of the joint axis if
# the detached joint is supposed to be revolute or prismatic respectively.
_is_detached_joint = False
if obj_handle.type == 'EMPTY':
# Check for a special case for defining joints for parallel linkages
for _detached_prefix_search_str in CommonConfig.detached_joint_prefix:
if obj_handle_name.rfind(_detached_prefix_search_str) == 0:
_is_detached_joint = True
break
if _is_detached_joint:
print('INFO: FOR BODY \"%s\" ADDING DETACHED JOINT' % obj_handle_name)
parent_pivot, parent_axis = self.compute_pivot_and_axis(
parent_obj_handle, obj_handle, constraint)
child_pivot, child_axis = self.compute_pivot_and_axis(
child_obj_handle, obj_handle, constraint)
# Add this field to the joint data, it will come in handy for blender later
joint_data['detached'] = True
else:
parent_pivot, parent_axis = self.compute_pivot_and_axis(
parent_obj_handle, child_obj_handle, constraint)
child_pivot = mathutils.Vector([0, 0, 0])
child_axis, ax_idx = self.get_joint_axis(constraint)
parent_pivot_data = joint_data["parent pivot"]
parent_axis_data = joint_data["parent axis"]
parent_pivot_data['x'] = round(parent_pivot.x, 3)
parent_pivot_data['y'] = round(parent_pivot.y, 3)
parent_pivot_data['z'] = round(parent_pivot.z, 3)
parent_axis_data['x'] = round(parent_axis.x, 3)
parent_axis_data['y'] = round(parent_axis.y, 3)
parent_axis_data['z'] = round(parent_axis.z, 3)
child_pivot_data = joint_data["child pivot"]
child_axis_data = joint_data["child axis"]
child_pivot_data['x'] = round(child_pivot.x, 3)
child_pivot_data['y'] = round(child_pivot.y, 3)
child_pivot_data['z'] = round(child_pivot.z, 3)
child_axis_data['x'] = round(child_axis.x, 3)
child_axis_data['y'] = round(child_axis.y, 3)
child_axis_data['z'] = round(child_axis.z, 3)
# This method assigns joint limits, joint_type, joint damping and stiffness for spring joints
self.assign_joint_params(constraint, joint_data)
# The use of pivot and axis does not fully define the connection and relative
# transform between two bodies it is very likely that we need an additional offset
# of the child body as in most of the cases of URDF's For this purpose, we calculate
# the offset as follows
r_c_p_ambf = rot_matrix_from_vecs(child_axis, parent_axis)
r_p_c_ambf = r_c_p_ambf.to_3x3().copy()
r_p_c_ambf.invert()
t_p_w = parent_obj_handle.matrix_world.copy()
r_w_p = t_p_w.to_3x3().copy()
r_w_p.invert()
r_c_w = child_obj_handle.matrix_world.to_3x3().copy()
r_c_p_blender = r_w_p * r_c_w
r_angular_offset = r_p_c_ambf * r_c_p_blender
offset_axis_angle = r_angular_offset.to_quaternion().to_axis_angle()
if abs(offset_axis_angle[1]) > 0.01:
# print '*****************************'
# print joint_data['name']
# print 'Joint Axis, '
# print '\t', joint.axis
# print 'Offset Axis'
# print '\t', offset_axis_angle[1]
offset_angle = round(offset_axis_angle[1], 3)
# offset_angle = round(offset_angle, 3)
# print 'Offset Angle: \t', offset_angle
# print('OFFSET ANGLE', offset_axis_angle[1])
# print('CHILD AXIS', child_axis)
# print('OFFSET AXIS', offset_axis_angle)
# print('DOT PRODUCT', parent_axis.dot(offset_axis_angle[0]))
if abs(1.0 - child_axis.dot(offset_axis_angle[0])) < 0.1:
joint_data['offset'] = offset_angle
# print ': SAME DIRECTION'
elif abs(1.0 + child_axis.dot(offset_axis_angle[0])) < 0.1:
joint_data['offset'] = -offset_angle
# print ': OPPOSITE DIRECTION'
else:
print('ERROR: SHOULD\'NT GET HERE')
joint_yaml_name = self.add_joint_prefix_str(joint_data['name'])
ambf_yaml[joint_yaml_name] = joint_data
self._joint_names_list.append(joint_yaml_name)
# Finally get some rough values for the controller gains
p_mass = 0.01
c_mass = 0.01
if parent_obj_handle.rigid_body:
p_mass = parent_obj_handle.rigid_body.mass
if child_obj_handle.rigid_body:
c_mass = child_obj_handle.rigid_body.mass
# Now lets load the loaded data if any from loaded AMBF File
_jnt_ctrlr_already_defined = False
if constraint in CommonConfig.loaded_joint_map:
if 'controller' in CommonConfig.loaded_joint_map[constraint]:
joint_data['controller'] = CommonConfig.loaded_joint_map[constraint]['controller']
_jnt_ctrlr_already_defined = True
# The maximum damping in Blender for joints in 1.0, however
# we can specify higher in AMBF, if a damping has been defined and
# is higher than 1.0, consider it
if 'damping' in CommonConfig.loaded_joint_map[constraint]:
if 'damping' in joint_data:
if joint_data['damping'] == 1.0 and CommonConfig.loaded_joint_map[constraint]['damping'] > 1.0:
joint_data['damping'] = CommonConfig.loaded_joint_map[constraint]['damping']
else:
joint_data['damping'] = CommonConfig.loaded_joint_map[constraint]['damping']
if not _jnt_ctrlr_already_defined:
joint_data["controller"]["P"] = round((p_mass + c_mass) * 1000.0, 3)
joint_data["controller"]["D"] = round((p_mass + c_mass) * 2.0, 3)
# Get the joints axis as a vector
def get_joint_axis(self, constraint):
if constraint.type == 'HINGE':
ax_idx = 2
elif constraint.type == 'SLIDER':
ax_idx = 0
elif constraint.type == 'GENERIC':
ax_idx = 2
if constraint.use_limit_lin_x or constraint.use_limit_ang_x:
ax_idx = 0
elif constraint.use_limit_lin_y or constraint.use_limit_ang_y:
ax_idx = 1
elif constraint.use_limit_lin_z or constraint.use_limit_ang_z:
ax_idx = 2
elif constraint.type == 'GENERIC_SPRING':
if constraint.use_limit_lin_x or constraint.use_limit_ang_x:
ax_idx = 0
elif constraint.use_limit_lin_y or constraint.use_limit_ang_y:
ax_idx = 1
elif constraint.use_limit_lin_z or constraint.use_limit_ang_z:
ax_idx = 2
elif constraint.type == 'POINT':
ax_idx = 2
elif constraint.type == 'FIXED':
ax_idx = 2
# The third col of rotation matrix is the z axes of child in parent
joint_axis = mathutils.Vector([0, 0, 0])
joint_axis[ax_idx] = 1.0
return joint_axis, ax_idx
# Since changing the scale of the bodies directly impacts the rotation matrix, we have
# to take that into account while calculating offset of child from parent using
# transform manipulation
def compute_pivot_and_axis(self, parent, child, constraint):
# Since the rotation matrix is carrying the scale, separate out just
# the rotation component
# Transform of Parent in World
t_p_w = parent.matrix_world.copy().to_euler().to_matrix().to_4x4()
t_p_w.translation = parent.matrix_world.copy().translation
# Since the rotation matrix is carrying the scale, separate out just
# the rotation component
# Transform of Child in World
t_c_w = child.matrix_world.copy().to_euler().to_matrix().to_4x4()
t_c_w.translation = child.matrix_world.copy().translation
# Copy over the transform to invert it
t_w_p = t_p_w.copy()
t_w_p.invert()
# Transform of Child in Parent
# t_c_p = t_w_p * t_c_w
t_c_p = t_w_p * t_c_w
pivot = t_c_p.translation
joint_axis, axis_idx = self.get_joint_axis(constraint)
# The third col of rotation matrix is the z axes of child in parent
axis = mathutils.Vector(t_c_p.col[axis_idx][0:3])
return pivot, axis
# Assign the joint parameters that include joint limits, type, damping and joint stiffness for spring joints
def assign_joint_params(self, constraint, joint_data):
if constraint.type == 'HINGE':
if constraint.use_limit_ang_z:
joint_data['type'] = 'revolute'
higher_limit = constraint.limit_ang_z_upper
lower_limit = constraint.limit_ang_z_lower
else:
joint_data['type'] = 'continuous'
elif constraint.type == 'SLIDER':
joint_data['type'] = 'prismatic'
higher_limit = constraint.limit_lin_x_upper
lower_limit = constraint.limit_lin_x_lower
elif constraint.type == 'GENERIC':
if constraint.use_limit_lin_x:
joint_data['type'] = 'prismatic'
higher_limit = constraint.limit_lin_x_upper
lower_limit = constraint.limit_lin_x_lower
elif constraint.use_limit_lin_y:
joint_data['type'] = 'prismatic'
higher_limit = constraint.limit_lin_y_upper
lower_limit = constraint.limit_lin_y_lower
elif constraint.use_limit_lin_z:
joint_data['type'] = 'prismatic'
higher_limit = constraint.limit_lin_z_upper
lower_limit = constraint.limit_lin_z_lower
elif constraint.use_limit_ang_x:
joint_data['type'] = 'revolute'
higher_limit = constraint.limit_ang_x_upper
lower_limit = constraint.limit_ang_x_lower
elif constraint.use_limit_ang_y:
joint_data['type'] = 'revolute'
higher_limit = constraint.limit_ang_y_upper
lower_limit = constraint.limit_ang_y_lower
elif constraint.use_limit_ang_z:
joint_data['type'] = 'revolute'
higher_limit = constraint.limit_ang_z_upper
lower_limit = constraint.limit_ang_z_lower
elif constraint.type == 'GENERIC_SPRING':
if constraint.use_limit_lin_x:
joint_data['type'] = 'linear spring'
higher_limit = constraint.limit_lin_x_upper
lower_limit = constraint.limit_lin_x_lower
if constraint.use_spring_x:
joint_data['damping'] = constraint.spring_damping_x
joint_data['stiffness'] = constraint.spring_stiffness_x
elif constraint.use_limit_lin_y:
joint_data['type'] = 'linear spring'
higher_limit = constraint.limit_lin_y_upper
lower_limit = constraint.limit_lin_y_lower
if constraint.use_spring_y:
joint_data['damping'] = constraint.spring_damping_y
joint_data['stiffness'] = constraint.spring_stiffness_y
elif constraint.use_limit_lin_z:
joint_data['type'] = 'linear spring'
higher_limit = constraint.limit_lin_z_upper
lower_limit = constraint.limit_lin_z_lower
if constraint.use_spring_z:
joint_data['damping'] = constraint.spring_damping_z
joint_data['stiffness'] = constraint.spring_stiffness_z
elif constraint.use_limit_ang_x:
joint_data['type'] = 'torsion spring'
higher_limit = constraint.limit_ang_x_upper
lower_limit = constraint.limit_ang_x_lower
if constraint.use_spring_ang_x:
joint_data['damping'] = constraint.spring_damping_ang_x
joint_data['stiffness'] = constraint.spring_stiffness_ang_x
elif constraint.use_limit_ang_y:
joint_data['type'] = 'torsion spring'
higher_limit = constraint.limit_ang_y_upper
lower_limit = constraint.limit_ang_y_lower
if constraint.use_spring_ang_y:
joint_data['damping'] = constraint.spring_damping_ang_y
joint_data['stiffness'] = constraint.spring_stiffness_ang_y
elif constraint.use_limit_ang_z:
joint_data['type'] = 'torsion spring'
higher_limit = constraint.limit_ang_z_upper
lower_limit = constraint.limit_ang_z_lower
if constraint.use_spring_ang_z:
joint_data['damping'] = constraint.spring_damping_ang_z
joint_data['stiffness'] = constraint.spring_stiffness_ang_z
elif constraint.type == 'POINT':
joint_data['type'] = 'p2p'
elif constraint.type == 'FIXED':
joint_data['type'] = 'fixed'
if joint_data['type'] in ['fixed', 'p2p']:
del joint_data["joint limits"]
elif joint_data['type'] == 'continuous':
del joint_data["joint limits"]['low']
del joint_data["joint limits"]['high']
else:
joint_limit_data = joint_data["joint limits"]
joint_limit_data['low'] = round(lower_limit, 3)
joint_limit_data['high'] = round(higher_limit, 3)
def generate_ambf_yaml(self, context):
num_objs = len(bpy.data.objects)
save_to = bpy.path.abspath(context.scene.ambf_yaml_conf_path)
filename = os.path.basename(save_to)
save_dir = os.path.dirname(save_to)
if not filename:
filename = 'default.yaml'
output_filename = os.path.join(save_dir, filename)
# if a file exists by that name, save a backup
if os.path.isfile(output_filename):
os.rename(output_filename, output_filename + '.old')
output_file = open(output_filename, 'w')
print('Output filename is: ', output_filename)
# For inorder processing, set the bodies and joints tag at the top of the map
self._ambf_yaml = OrderedDict()
self._ambf_yaml['bodies'] = []
self._ambf_yaml['joints'] = []
print('SAVE PATH', bpy.path.abspath(save_dir))
print('AMBF CONFIG PATH', bpy.path.abspath(context.scene.ambf_yaml_mesh_path))
rel_mesh_path = os.path.relpath(bpy.path.abspath(context.scene.ambf_yaml_mesh_path), bpy.path.abspath(save_dir))
self._ambf_yaml['high resolution path'] = rel_mesh_path + '/high_res/'
self._ambf_yaml['low resolution path'] = rel_mesh_path + '/low_res/'
self._ambf_yaml['ignore inter-collision'] = context.scene.ignore_inter_collision
update_global_namespace(context)
if CommonConfig.namespace is not "":
self._ambf_yaml['namespace'] = CommonConfig.namespace
# We want in-order processing, so make sure to
# add bodies to ambf in a hierarchial fashion.
_heirarichal_bodies_list = populate_heirarchial_tree()
for body in _heirarichal_bodies_list:
self.generate_body_data(self._ambf_yaml, body)
for body in _heirarichal_bodies_list:
self.generate_joint_data(self._ambf_yaml, body)
# Now populate the bodies and joints tag
self._ambf_yaml['bodies'] = self._body_names_list
self._ambf_yaml['joints'] = self._joint_names_list
yaml.dump(self._ambf_yaml, output_file)
header_str = "# AMBF Version: %s\n" \
"# Generated By: ambf_addon for Blender %s\n" \
"# Link: %s\n" \
"# Generated on: %s\n"\
% (str(bl_info['version']).replace(', ', '.'),
str(bl_info['blender']).replace(', ', '.'),
bl_info['wiki_url'],
datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
prepend_comment_to_file(output_filename, header_str)
class SaveMeshes(bpy.types.Operator):
bl_idname = "ambf.add_save_meshes"
bl_label = "Save Meshes"
bl_description = "This saves the meshes in base folder specifed in the field above. Two folders" \
" are created in the base folder named, \"high_res\" and \"low_res\" to store the" \
" high-res and low-res meshes separately"
def execute(self, context):
replace_dot_from_obj_names()
self.save_meshes(context)
return {'FINISHED'}
# This recursive function is specialized to deal with
# tree based hierarchy. In such cases we have to ensure
# to move the parent to origin first and then its children successively
# otherwise moving any parent after its child has been moved with move the
# child as well
def set_to_origin(self, p_obj, obj_name_mat_list):
if p_obj.children is None:
return
obj_name_mat_list.append([p_obj.name, p_obj.matrix_world.copy()])
# Since setting the world transform clears the embedded scale
# of the object, we need to re-scale the object after putting it to origin
scale_mat = mathutils.Matrix()
scale_mat = scale_mat.Scale(p_obj.matrix_world.median_scale, 4)
p_obj.matrix_world.identity()
p_obj.matrix_world = scale_mat
for c_obj in p_obj.children:
self.set_to_origin(c_obj, obj_name_mat_list)
# Since Blender exports meshes w.r.t world transform and not the
# the local mesh transform, we explicitly push each object to origin
# and remember its world transform for putting it back later on
def set_all_meshes_to_origin(self):
obj_name_mat_list = []
for p_obj in bpy.data.objects:
if p_obj.parent is None:
self.set_to_origin(p_obj, obj_name_mat_list)
return obj_name_mat_list
# This recursive function works in similar fashion to the
# set_to_origin function, but uses the know default transform
# to set the tree back to default in a hierarchial fashion
def reset_back_to_default(self, p_obj_handle, obj_name_mat_list):
if p_obj_handle.children is None:
return
for item in obj_name_mat_list:
if p_obj_handle.name == item[0]:
p_obj_handle.matrix_world = item[1]
for c_obj_handle in p_obj_handle.children:
self.reset_back_to_default(c_obj_handle, obj_name_mat_list)
def reset_meshes_to_original_position(self, obj_name_mat_list):