-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdemo_hsi_auto.py
1752 lines (1516 loc) · 99.8 KB
/
demo_hsi_auto.py
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
import sys
sys.path.append(sys.path[0]+"/../")
sys.path.append(sys.path[0]+"/../../")
import os
import tqdm
os.environ['API_KEY'] = 'AIzaSyCQc_UseY-HguVvknzL9BQAJfdiN16O67Q'
# os.environ['http_proxy'] = 'http://127.0.0.1:7890'
import pickle
import numpy as np
import torch
import trimesh
import shutil
import copy
import time
import ast
sys.path.append(os.getcwd())
from scipy.spatial.transform import Rotation as R
from test_navmesh import *
from exp_GAMMAPrimitive.utils.environments import *
from exp_GAMMAPrimitive.utils import config_env
from pathlib import Path
import collections
import subprocess
from get_scene import ReplicaScene
from scipy.spatial.transform import Rotation
from vis_gen import rollout_primitives
from HHInter.rearrange_dataset import get_new_coordinate
from HHInter.infer import pipeline_merge
from HHInter.utils.slerp_alignment import slerp_poses, slerp_translation, aligining_bodies
from HHInter.global_path import *
from HHInter.models.blocks import MoshRegressor
import google.generativeai as genai
import bisect
from operator import itemgetter
from itertools import groupby
from HHInter.models.losses import GeneralContactLoss
bm_path = get_SMPL_SMPLH_SMPLX_body_model_path()
bm = smplx.create(bm_path, model_type='smplx',
gender='neutral', ext='npz',
num_pca_comps=12,
create_global_orient=True,
create_body_pose=True,
create_betas=True,
create_left_hand_pose=True,
create_right_hand_pose=True,
create_expression=True,
create_jaw_pose=True,
create_leye_pose=True,
create_reye_pose=True,
create_transl=True,
batch_size=1
).eval().cuda()
def params2torch(params, dtype=torch.float32):
return {k: torch.cuda.FloatTensor(v) if type(v) == np.ndarray else v for k, v in params.items()}
def project_to_navmesh(navmesh, points):
closest, _, _ = trimesh.proximity.closest_point(navmesh, points)
return closest
def params2numpy(params):
return {k: v.detach().cpu().numpy() if type(v) == torch.Tensor else v for k, v in params.items()}
def get_navmesh(navmesh_path, scene_path, agent_radius, floor_height=0.0, visualize=False):
if navmesh_path.exists():
navmesh = trimesh.load(navmesh_path, force='mesh')
else:
scene_mesh = trimesh.load(scene_path, force='mesh')
"""assume the scene coords are z-up"""
scene_mesh.vertices[:, 2] -= floor_height
scene_mesh.apply_transform(zup_to_shapenet)
navmesh = create_navmesh(scene_mesh, export_path=navmesh_path, agent_radius=agent_radius, visualize=visualize)
navmesh.vertices[:, 2] = 0
return navmesh
# Judge whether the point is within the navmesh region
def is_inside(navmesh, points_2d):
points_2d = torch.from_numpy(points_2d).cuda().float() # [P, 1, 2]
triangles = torch.cuda.FloatTensor(np.stack([navmesh.vertices[navmesh.faces[:, 0], :2],
navmesh.vertices[navmesh.faces[:, 1], :2],
navmesh.vertices[navmesh.faces[:, 2], :2]], axis=-1)).permute(0, 2, 1)[
None, ...] # [1, F, 3, 2]
def sign(p1, p2, p3):
return (p1[:, :, 0] - p3[:, :, 0]) * (p2[:, :, 1] - p3[:, :, 1]) - (p2[:, :, 0] - p3[:, :, 0]) * (
p1[:, :, 1] - p3[:, :, 1])
d1 = sign(points_2d, triangles[:, :, 0, :], triangles[:, :, 1, :])
d2 = sign(points_2d, triangles[:, :, 1, :], triangles[:, :, 2, :])
d3 = sign(points_2d, triangles[:, :, 2, :], triangles[:, :, 0, :])
has_neg = (d1 < 0) | (d2 < 0) | (d3 < 0)
has_pos = (d1 > 0) | (d2 > 0) | (d3 > 0)
inside_triangle = ~(has_neg & has_pos) # [P, F]
return inside_triangle.any(-1)[0]
def scene_sdf(mesh_path, sdf_path):
if os.path.exists(sdf_path):
with open(sdf_path, 'rb') as f:
object_sdf = pickle.load(f)
return object_sdf
mesh = trimesh.load(mesh_path, force='mesh')
voxel_resolution = 256
extents = mesh.bounding_box.extents
extents = np.array([extents[0] + 2, extents[1] + 2, 0.5])
transform = np.array([[1.0, 0.0, 0.0, 0],
[0.0, 1.0, 0.0, 0],
[0.0, 0.0, 1.0, -0.25],
[0.0, 0.0, 0.0, 1.0],
])
transform[:2, 3] += mesh.centroid[:2]
floor_mesh = trimesh.creation.box(extents=extents,
transform=transform,
)
scene_mesh = mesh + floor_mesh
# scene_mesh.show()
scene_extents = extents + np.array([2, 2, 1])
scene_scale = np.max(scene_extents) * 0.5
scene_centroid = mesh.bounding_box.centroid
scene_mesh.vertices -= scene_centroid
scene_mesh.vertices /= scene_scale
sign_method = 'normal'
surface_point_cloud = get_surface_point_cloud(scene_mesh, surface_point_method='sample', scan_count=100,
scan_resolution=400, sample_point_count=10000000,
calculate_normals=(sign_method == 'normal'))
sdf_grid, gradient_grid = surface_point_cloud.get_voxels(voxel_resolution, sign_method == 'depth', sample_count=11,
pad=False,
check_result=False, return_gradients=True)
object_sdf = {
'grid': sdf_grid * scene_scale,
'gradient_grid': gradient_grid,
'dim': voxel_resolution,
'centroid': scene_centroid,
'scale': scene_scale,
}
sdf_grids = torch.from_numpy(object_sdf['grid'])
object_sdf['grid'] = sdf_grids.squeeze().unsqueeze(0).unsqueeze(0).to(dtype=torch.float32) # 1x1xDxDxD
if 'gradient_grid' in object_sdf:
gradient_grids = torch.from_numpy(object_sdf['gradient_grid'])
object_sdf['gradient_grid'] = gradient_grids.permute(3, 0, 1, 2).unsqueeze(0).to(
dtype=torch.float32) # 1x3xDxDxD
object_sdf['centroid'] = torch.tensor(object_sdf['centroid']).reshape(1, 1, 3).to(dtype=torch.float32)
with open(sdf_path, 'wb') as f:
pickle.dump(object_sdf, f)
return object_sdf
def calc_sdf(vertices, sdf_dict):
sdf_centroid = sdf_dict['centroid']
sdf_scale = sdf_dict['scale']
sdf_grids = sdf_dict['grid']
batch_size, num_vertices, _ = vertices.shape
vertices = vertices.reshape(1, -1, 3) # [B, V, 3]
vertices = (vertices - sdf_centroid) / sdf_scale # convert to [-1, 1]
sdf_values = F.grid_sample(sdf_grids,
vertices[:, :, [2, 1, 0]].view(1, batch_size * num_vertices, 1, 1, 3),
# [2,1,0] permute because of grid_sample assumes different dimension order, see below
padding_mode='border',
align_corners=True
# not sure whether need this: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html#torch.nn.functional.grid_sample
).reshape(batch_size, num_vertices)
return sdf_values
def llm_order_generation(objects):
try:
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE"
}
]
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(model_name='gemini-1.5-flash', safety_settings=safety_settings)
print("\nBelow is the input prompt for the model to generate the plot and motions for the actors based on the given objects:")
print("===================================================================================================================")
prompts = "Suppose you are a movie director tasked with creating a plot involving the motions of two actors, " \
"Amy (female) and Jack (male), in a scene. You will be provided with a list of objects present in the scene. " \
"Based on these objects, you need to design a plot and specify the motions for the actors. The actors can perform " \
"three types of motions: walking in the scene, interacting with the objects (only supporting sitting and lying), " \
"and human-to-human interactions (including handshakes, hugs, fighting, etc.).\n" \
"Your goal is to ensure the designed plot is reasonable and interesting. You need to output both the plot and the " \
"specific motions for the actors. Also you should ensure that the output motion orders for the actors are strictly aligned to the order rules. Below is an example to illustrate the input and expected output:\n\n" \
"### Example\n" \
"**Input:**\n" \
"Objects: [chair, table, sofa, stool]\n\n" \
"**Output Plot:**\n" \
"Plot: 'Jack and Amy are two friends who meet in a cafe. Jack is sitting on the chair, and Amy walks in and then " \
"sits on the sofa. They talk to each other. After a while, they stand up and shake hands.'\n\n" \
"**Output Amy Motion Order:**\n" \
"Motions: [None | sofa | sit | HHI: the two people greet each other by shaking hands.]\n\n" \
"**Output Jack Motion Order:**\n" \
"Motions: [chair | sit | HHI: the two people greet each other by shaking hands.]\n\n" \
"### Motion Order Rules that need to be strictly followed:\n" \
"- The motion order for each actor is a list.\n" \
"- The element in the order list can only be one of the following types: None, the name of an object, a human-to-human interaction description with a prefix 'HHI:', and 'sit' or 'lie'. Other elements are prohibited.\n" \
"- 'None' denotes the actor will be at a random position in the scene.\n" \
"- The name of any object denotes the actor will be near that object.\n" \
"- If 'None' and the name of an object are next to each other, the actor will walk from the random position to the object, and vice versa.\n" \
"- If two objects are next to each other, the actor will walk from the first object to the second.\n" \
"- If two 'None' entries are next to each other, the actor will walk from the first random position to the second random position.\n" \
"- 'sit' and 'lie' denotes the interaction with objects. Ensure such order follows the interacted object's name (e.g., 'chair', 'sit'). Note that only 'sit' and 'lie' are allowed. Other descriptions like 'walk through', 'walk to', 'look at', 'turn on', 'pick up' are prohibited.\n" \
"- For the human-to-human interaction order, prefix the interaction order with 'HHI:' (e.g., 'HHI: the two performers greet each other by shaking hands.'). There should be the same number of HHI orders in both order lists, " \
"and these HHI orders should be in the same order, with their context being the same in both order lists. " \
"Note that there shouldn't be any human names in the HHI descriptions, use terms like 'the person', 'the performer', 'the guy', etc. Also, any descrption about interactions with objects are prohibited in the HHI descriptions. Only interactions between two human bodies are allowed." \
"Also the HHI description cannot involve motions like sitting or lying. Here are several examples of human-human interaction descriptions:\n" \
" - 'the two face each other and make an embracing motion with their arms, then move their arms away from the center and lower them to the ground.'\n" \
" - 'one approaches the other and gives them a hug. The other rejects the hug and moves away to another location.'\n" \
" - 'one person makes a peace sign with their left hand, and the other person wraps an arm around their shoulder, and they take a group photo together.'\n" \
" - 'one person stretches both hands over their head, while the other leans to the right and touches the first person's waist with their right hand.'\n" \
" - 'one attempts to hit the head of the other with their left fist, and the other responds by using their left fist to defend.'\n\n" \
f"With the above example and instructions, please design a plot and generate the motions for the actors based on the given objects: [{objects}]."
print(prompts)
response = model.generate_content(prompts)
print("\nBelow is the generated plot and motions for the actors based on the given objects:")
print("==================================================================================")
print(response.text)
return response.text
except Exception as e:
print(e)
print("get caption failed, try again.....")
return ''
def llm_order_revision(order_1, order_2):
try:
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE"
}
]
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(model_name='gemini-1.5-flash', safety_settings=safety_settings)
print("\nBelow is the input prompt for the model to revise the given two motion order lists:")
print("===============================================================================")
prompts = "You need to make sure the given two motion order lists are strictly aligned to the following rules. If not, please adapt it into the right type by removing/adding/modifying some elements.\n" \
"### Motion Order Rules:\n" \
"- No single and double quotation marks in the motion order lists.\n" \
"- Orders are separated by a vertical bar '|'" \
"- The element in the order list can only be one of the following types: None, the name of an object, a human-to-human interaction description with a prefix 'HHI:', and 'sit' or 'lie'. Other elements are prohibited.\n" \
"- If not prefixed with 'HHI:', only 'sit' and 'lie' are allowed. Others like 'walk through', 'walk to', 'look at', 'turn on', 'pick up', etc., are prohibited.\n" \
"- For the human-to-human interaction order prefixed with 'HHI:', there should be the same number of HHI orders in both order lists, " \
"and these HHI orders should be in the same order, with their context being the same in both order lists. " \
"Note that there shouldn't be any human names in the HHI descriptions, use terms like 'the person', 'the performer', 'the guy', etc. Also, any descrption about interactions with objects are prohibited in the HHI descriptions. Only interactions between two human bodies are allowed." \
"Also the HHI description cannot involve motions like sitting or lying. Here are several examples of human-human interaction descriptions:\n" \
" 'the two face each other and make an embracing motion with their arms, then move their arms away from the center and lower them to the ground.',\n" \
" 'one approaches the other and gives them a hug. The other rejects the hug and moves away to another location.',\n" \
" 'one person makes a peace sign with their left hand, and the other person wraps an arm around their shoulder, and they take a group photo together.',\n" \
" 'one person stretches both hands over their head, while the other leans to the right and touches the first person's waist with their right hand.',\n" \
" 'one attempts to hit the head of the other with their left fist, and the other responds by using their left fist to defend.'\n\n" \
"Please check the following two motion order lists and adapt them into the right type.\n\n" \
"### Input two motion order lists\n" \
"**Motion Order List 1:**\n" \
f"Motions: [{order_1}]\n" \
"**Motion Order List 2:**\n" \
f"Motions: [{order_2}]\n" \
"The output should be only the corrected motion order lists. If the input is correct, please output the same order list. No other explanations or reasonings are needed."
print(prompts)
response = model.generate_content(prompts)
print("\nBelow is the revised motion order lists:")
print("=========================================")
print(response.text)
return response.text
except Exception as e:
print(e)
print("get caption failed, try again.....")
return ''
def first_scene_preparation(json_path, scene_dir, scene_name):
"""Prepare the scene, including the object meshes and the scene mesh."""
with open(json_path, 'r') as f:
semantic_statistic = json.load(f)
accessible_object = collections.defaultdict(list)
for obj in semantic_statistic['objects']:
accessible_object[obj["class_name"]].append(obj)
print("Accessible object: ", accessible_object.keys())
if 'replica' in str(scene_dir):
data_folder = Path('data/replica')
export_ids = []
# build from original scene
if not os.path.exists(data_folder / scene_name / 'mesh_floor.ply'):
scene = ReplicaScene(scene_name, data_folder, build=True, zero_floor=True)
scene.mesh.export(data_folder / scene_name / 'mesh_floor.ply')
for obj_id in range(len(semantic_statistic["id_to_label"])):
# Need to re-export mesh, because initial exported ones are not subtracted by floor height.
# if not os.path.exists(scene_dir / 'instances' / f'{obj_id}.ply'):
obj_category = scene.category_names[obj_id]
instance_mesh = scene.get_mesh_with_accessory(obj_id)
instance_mesh.export(scene_dir / 'instances' / f'{obj_id}.ply')
else:
print("Scene is not from Replica dataset, please check the scene path.")
exit(0)
return accessible_object
def orders_revision(input_orders_1, input_orders_2, accessible_object):
"""Revise the orders to ensure it is reasonable and valid."""
processed_orders = [None, None]
for iid, input_orders in enumerate([input_orders_1, input_orders_2]):
id = 0
while id < len(input_orders):
cur_order = input_orders[id]
if cur_order is None:
if id != 0 and input_orders[id - 1] is not None and (
"sit" in input_orders[id - 1] or "lie" in input_orders[id - 1]):
print(f"Need to stand up before walking, automatically add 'stand' order.")
input_orders.insert(id, "stand")
elif isinstance(cur_order, list):
pass
elif "HHI" == cur_order[:3]:
if id == 0 or id == 1:
print(f"Need to have walking order before human-human interaction")
# Insert two to ensure walking motions.
input_orders.insert(id, None)
if id == 0:
input_orders.insert(id, None)
elif input_orders[id - 1] is not None and ("sit" in input_orders[id - 1] or "lie" in input_orders[id - 1]):
print(f"Need to stand up before walking, automatically add 'stand' order.")
input_orders.insert(id, "stand")
elif "sit" in cur_order or "lie" in cur_order or "stand" in cur_order:
if id == 0:
print(f"Not support '{cur_order}' interact from start, will skip it.")
input_orders.pop(id)
continue
elif input_orders[id - 1] is None:
print(f"Not support '{cur_order}' interact without object, will skip it.")
input_orders.pop(id)
continue
elif "stand" in cur_order:
if "sit" not in input_orders[id - 1] and "lie" not in input_orders[id - 1]:
print(f"Not support 'stand' before 'sit' and 'lie', will skip it.")
input_orders.pop(id)
continue
else:
input_orders[id] = "sit on" if "sit" in cur_order else "lie on"
elif cur_order in accessible_object.keys():
if id != 0 and input_orders[id - 1] is not None and (
"sit" in input_orders[id - 1] or "lie" in input_orders[id - 1]):
print(f"Need to stand up before walking, automatically add 'stand' order.")
input_orders.insert(id, "stand")
else:
print(f"Order {cur_order} is unrecognizable, will skip it.")
input_orders.pop(id)
continue
id += 1
if len(input_orders) <= 1:
print("At least two orders are needed for the demo. Replace the missing object with random sample.")
input_orders = [None] * (3 - len(input_orders)) + input_orders # Use 3 to avoid skipped order.
processed_orders[iid] = input_orders
# At last, ensure the number of HHI orders are the same. Not put it at first because one case: one person sit then HHI,
# while the other object/None then HHI. This will lead to different HHI prompt due to the added ' The two performers stand up.'.
hhi_num_1 = len([order for order in input_orders_1 if order is not None and "HHI:" in order[:4]])
hhi_num_2 = len([order for order in input_orders_2 if order is not None and "HHI:" in order[:4]])
if hhi_num_1 != hhi_num_2:
raise ValueError("The number of HHI orders are not the same, please check the input orders.")
# Then check if the context of the HHI orders are the same. If not, copy the HHI order context from the first order list to the second order list.
hhi_orders_1 = [id for id, order in enumerate(input_orders_1) if order is not None and "HHI:" in order[:4]]
hhi_orders_2 = [id for id, order in enumerate(input_orders_2) if order is not None and "HHI:" in order[:4]]
for id in range(hhi_num_1):
if input_orders_1[hhi_orders_1[id]] != input_orders_2[hhi_orders_2[id]]:
print(f"HHI order {id} in the two order lists are different, will copy the context from the first order list to the second order list.")
input_orders_2[hhi_orders_2[id]] = input_orders_1[hhi_orders_1[id]]
return processed_orders
def orders_segmentation(processed_orders):
"""Segment the orders into different parts when encountering the 'stand' order or 'HHI' order"""
segmented_orders = [None, None]
for iid, input_orders in enumerate(processed_orders):
# break the orders with the 'stand' order. And save these segments into a list.
order_segments = []
seg = []
for cur_order in input_orders:
seg.append(cur_order)
if cur_order is not None and ("stand" in cur_order or "HHI" in cur_order[:3]):
if len(seg) > 0:
order_segments.append(seg)
seg = []
if len(seg) > 0:
order_segments.append(seg)
segmented_orders[iid] = order_segments
return segmented_orders
def walking_path_points_generation(scene_dir, scene_name, scene_path, segmented_orders, accessible_object, navmesh_loose,
extents, centroid, scene_mesh, floor_height=0.0, visualize=False):
"""Generate the walking path points for the orders. Also will generate the target pose if there are object interaction orders."""
all_wpaths = [[], []]
append_vars = [[], []]
for iid, order_segments in enumerate(segmented_orders):
# order_segments: [[order1, order2, ...], [order1, order2, ...], ...]
if iid == 1:
# Calculate the wpaths distance for `0` order_segments. This is for collision revision.
# Only consider the first seg, otherwise the logics will be too complex.
all_intermediate_points_A = np.concatenate(all_wpaths[0][0], axis=0)
# Calculate the cumulated distance of each point to the first point.
cumulated_distance_A = np.zeros(len(all_intermediate_points_A))
cumulated_distance_A[1:] = np.linalg.norm(all_intermediate_points_A[1:] - all_intermediate_points_A[:-1], axis=1)
cumulated_distance_A = np.cumsum(cumulated_distance_A)
for indx, seg_orders in enumerate(order_segments):
# seg_orders: [order1, order2, ...]
# randomly sample points within the area defined above
marginal = 0
only_points_return_flag = False
if indx != 0:
"This is to ensure the adjacent segments' wpaths are connected."
if "HHI" in order_segments[indx - 1][-1][:3]:
# Will not calculate wpath, leave the calculation in the latter motion generation step.
only_points_return_flag = True
points = []
elif "stand" in order_segments[indx - 1][-1]:
# the points in the right is the last segment of the walking path, and -2 denotes sit or lie target point.
points = [points[-2]]
marginal = 1
else:
raise ValueError("The last order of the previous segment should be 'stand' or 'HHI'.")
else:
points = []
var = []
repeat_times = 0
while len(points) < len(seg_orders) + marginal:
i = len(points) - marginal
if seg_orders[i] is None:
# randomly sample a point within the scene area
point = np.random.rand(3) * extents - extents / 2 + centroid
point[2] = 0
elif isinstance(seg_orders[i], list):
point = np.array(seg_orders[i])
point[2] = 0
elif "HHI" in seg_orders[i][:3]:
point = None
# For two HHI directly adjacent case, need to add a point (another point will from the last seg) to
# ensure there is a walking for frame number alignment.
# 'copy' here will be used as a dictation of copying last point in the latter step.
if len(points) == 0: # This case, only_points_return_flag is of course True.
points.append('copy')
if not only_points_return_flag and len(points) == 1:
points.append(points[0])
elif not ("sit" in seg_orders[i] or "lie" in seg_orders[i] or "stand" in seg_orders[i]):
ratio = (2 + repeat_times // 20) if seg_orders[i] != "floor" else 1
select = np.random.choice(len(accessible_object[seg_orders[i]]))
object = accessible_object[seg_orders[i]][select]
# Load instance mesh and use trimesh to extract extents and centroid
mesh_path = scene_dir / 'instances' / f'{object["id"]}.ply'
mesh = trimesh.load(mesh_path, force='mesh')
object_extents = mesh.bounding_box.extents
object_centroid = mesh.bounding_box.centroid
# The following is not accurate, as 'abb' in the json is actually not the world coordinate.
# object_extents = np.array(object["oriented_bbox"]["abb"]["sizes"])
# object_centroid = np.array(object["oriented_bbox"]["abb"]["center"])
# randomly sample a point in a larger cuboid area
point = (np.random.rand(3) * object_extents - object_extents / 2) * ratio
point += object_centroid
point[2] = 0
repeat_times += 1
elif "sit" in seg_orders[i] or "lie" in seg_orders[i]:
action_in = seg_orders[i]
action_out = action_in.split(' ')[0]
obj_name = accessible_object[seg_orders[i - 1]][select]["id"]
mesh_path = scene_dir / 'instances' / f'{obj_name}.ply'
sdf_path = scene_dir / 'sdf' / f'{obj_name}_sdf_gradient.pkl'
"For 'lie' motion, first use 'sit' motion to determine the human body orientation."
if "lie" in seg_orders[i]:
action_in_tmp = action_in.replace("lie", "sit")
command = (
f'python synthesize/coins_sample.py --exp_name test --lr_posa 0.01 --max_step_body 100 '
f'--weight_penetration 10 --weight_pose 10 --weight_init 0 --weight_contact_semantic 1 '
f'--num_sample 1 --num_try 8 --visualize 1 --full_scene 1 '
f'--action \"{action_in_tmp}\" --obj_path \"{mesh_path}\" --obj_category \"{obj_name}\" '
f'--obj_id 0 --scene_path \"{scene_path}\" --scene_name \"{scene_name}\"')
subprocess.run(command)
interaction_path_dir = Path(
f'results/coins/two_stage/{scene_name}/test/optimization_after_get_body') / action_in_tmp / f'{action_in_tmp}_{obj_name}_0/'
interaction_path_list = list(interaction_path_dir.glob('*.pkl'))
interaction_path_list = [p for p in interaction_path_list if p.name != 'results.pkl']
target_interaction_path = random.choice(interaction_path_list)
with open(target_interaction_path, 'rb') as f:
target_interaction = pickle.load(f)
smplx_params = target_interaction['smplx_param']
body_orient = torch.cuda.FloatTensor(smplx_params['global_orient']).squeeze()
command = (f'python synthesize/coins_sample.py --exp_name test --lr_posa 0.01 --max_step_body 100 '
f'--weight_penetration 10 --weight_pose 10 --weight_init 0 --weight_contact_semantic 1 '
f'--num_sample 1 --num_try 8 --visualize 1 --full_scene 1 '
f'--action \"{action_in}\" --obj_path \"{mesh_path}\" --obj_category \"{obj_name}\" '
f'--obj_id 0 --scene_path \"{scene_path}\" --scene_name \"{scene_name}\"')
print(command)
subprocess.run(command)
interaction_path_dir = Path(
f'results/coins/two_stage/{scene_name}/test/optimization_after_get_body') / action_in / f'{action_in}_{obj_name}_0/'
interaction_path_list = list(interaction_path_dir.glob('*.pkl'))
interaction_path_list = [p for p in interaction_path_list if p.name != 'results.pkl']
interaction_name = 'inter_' + str(obj_name) + '_' + action_out
target_point_path = Path('results', 'tmp', scene_name, interaction_name, 'target_point.pkl')
target_point_path.parent.mkdir(exist_ok=True, parents=True)
target_body_path = Path('results', 'tmp', scene_name, interaction_name, 'target_body.pkl')
target_interaction_path = random.choice(interaction_path_list)
with open(target_interaction_path, 'rb') as f:
target_interaction = pickle.load(f)
smplx_params = target_interaction['smplx_param']
if 'left_hand_pose' in smplx_params:
del smplx_params['left_hand_pose']
if 'right_hand_pose' in smplx_params:
del smplx_params['right_hand_pose']
smplx_params['transl'][:, 2] -= floor_height
smplx_params['gender'] = 'male'
with open(target_body_path, 'wb') as f:
pickle.dump(smplx_params, f)
smplx_params = params2torch(smplx_params)
pelvis = bm(**smplx_params).joints[0, 0, :].detach().cpu().numpy()
r = torch.cuda.FloatTensor(1).uniform_() * 0.2 + 1.0
# r = 1.0
theta = torch.cuda.FloatTensor(1).uniform_() * torch.pi / 3 - torch.pi / 6
if "sit" in seg_orders[i]:
body_orient = torch.cuda.FloatTensor(smplx_params['global_orient']).squeeze()
# Comment: actually is R @ [0, 0, 1], as [0, 0, 1] is the forward direction in the body frame (y-up).
forward_dir = pytorch3d.transforms.axis_angle_to_matrix(body_orient)[:, 2]
forward_dir[2] = 0
forward_dir = forward_dir / torch.norm(forward_dir)
random_rot = pytorch3d.transforms.euler_angles_to_matrix(torch.cuda.FloatTensor([0, 0, theta]),
convention="XYZ")
forward_dir = torch.matmul(random_rot, forward_dir)
point = pelvis + (forward_dir * r).detach().cpu().numpy()
point[2] = 0
if not is_inside(navmesh_loose, point[:2].reshape(1, 1, 2)):
point = project_to_navmesh(navmesh_loose, np.array([point]))[0]
with open(target_point_path, 'wb') as f:
pickle.dump(point, f)
# These vars are needed in the following step.
var = [action_out, interaction_name, target_point_path, target_body_path, mesh_path, sdf_path]
else: # stand
point = None
# judge whether the point is within the navmesh region
if point is not None and not is_inside(navmesh_loose, point[:2].reshape(1, 1, 2)):
continue
# judge whether the point is too close to Character A's point. Only consider the first seg.
# Logic here is to use the point's cumulated distance to determine the point of similar time in Character
# A's path. Then compare if the distance between the two points is less than 0.3, which will easily lead to
# collision. We skip this process for human-scene interaction, whose resampling cost is expensive.
if collision_revision_flag:
if iid == 1 and indx == 0 and not(seg_orders[i] is not None and ("sit" in seg_orders[i] or "lie" in seg_orders[i])) and point is not None:
wpaths = [] if len(points) > 0 else [point.reshape(1, -1)]
for i in range(len(points)):
start_point = points[i]
target_point = points[i + 1] if i + 1 < len(points) else point
if target_point is None:
continue
start_target = np.stack([start_point, target_point])
wpath = path_find(navmesh_loose, start_target[0], start_target[1], visualize=False,
scene_mesh=scene_mesh)
if len(wpath) == 0:
wpath = np.stack([start_point, target_point])
if len(wpath) == 1:
wpath = np.concatenate([wpath, wpath + np.random.randn(3) * 0.01], axis=0)
wpaths.append(wpath)
all_intermediate_points_B = np.concatenate(wpaths, axis=0)
if len(all_intermediate_points_B) > 1:
# Calculate the cumulated distance of current point to the first point.
distance = np.linalg.norm(all_intermediate_points_B[1:] - all_intermediate_points_B[:-1], axis=1).sum()
else:
distance = 0
# bisect determine 'distance' index in 'cumulated_distance_A'.
index = bisect.bisect_left(cumulated_distance_A, distance)
# judge if point is within 0.3 scope of the point of Character A, if so, continue to resample.
if index < len(all_intermediate_points_A):
if np.linalg.norm(all_intermediate_points_A[index] - point) < 0.3:
continue
if index + 1 < len(all_intermediate_points_A):
if np.linalg.norm(all_intermediate_points_A[index + 1] - point) < 0.3:
continue
else:
if np.linalg.norm(all_intermediate_points_A[-1] - point) < 0.3:
continue
points.append(point)
repeat_times = 0
# Visualize points
if visualize:
scene = pyrender.Scene()
scene.add(pyrender.Mesh.from_trimesh(scene_mesh))
navmesh_loose_copy = deepcopy(navmesh_loose)
navmesh_loose_copy.vertices[:, 2] += 0.2
navmesh_loose_copy.visual.vertex_colors = np.array([0, 0, 200, 50])
scene.add(pyrender.Mesh.from_trimesh(navmesh_loose_copy))
for p in points:
if p is None:
continue
sm = trimesh.creation.uv_sphere(radius=0.05)
sm.visual.vertex_colors = [1.0, 0.0, 0.0]
tfs = np.tile(np.eye(4), (1, 1, 1))
tfs[:, :3, 3] = p
scene.add(pyrender.Mesh.from_trimesh(sm, poses=tfs))
viewer = pyrender.Viewer(scene, use_raymond_lighting=True)
if only_points_return_flag:
all_wpaths[iid].append(points)
else:
wpaths = []
# From the start to the end of the points, iteratively sample two adjacent points as the start and target points
for i in range(len(points) - 1):
start_point = points[i]
target_point = points[i + 1]
if target_point is None: # stand
continue
start_target = np.stack([start_point, target_point])
# find collision free path
wpath = path_find(navmesh_loose, start_target[0], start_target[1], visualize=False,
scene_mesh=scene_mesh)
# When point is at edges, maybe no path.
if len(wpath) == 0:
wpath = np.stack([start_point, target_point])
# when the last is stand and the current is only HHI order, wpath will be only one (due to copy of stand).
if len(wpath) == 1:
wpath = np.concatenate([wpath, wpath + np.random.randn(3) * 0.01], axis=0)
wpaths.append(wpath)
all_wpaths[iid].append(wpaths)
append_vars[iid].append(var)
return all_wpaths, append_vars
def mid_further_split_orders(all_wpaths, segmented_orders, append_vars):
"""Further splitting mid-order according to HHI text. This is to ensure each segment has the same length and also to suffice
the HHI interaction generation that behind the two person locomotion/HSI has ended."""
humaninter_segs = []
tmp_A = []
tmp_B = []
iiid_A = 0
iiid_B = 0
while iiid_A < len(all_wpaths[0]):
wpaths_A, seg_orders_A, var_A = all_wpaths[0][iiid_A], segmented_orders[0][iiid_A], append_vars[0][iiid_A]
# HHI text will be always at the end of the orders if exists, due to the above segment script.
if seg_orders_A[-1] is not None and "HHI" in seg_orders_A[-1][:3]:
tmp_B = []
while True:
wpaths_B, seg_orders_B, var_B = all_wpaths[1][iiid_B], segmented_orders[1][iiid_B], append_vars[1][
iiid_B]
iiid_B += 1
if seg_orders_B[-1] == seg_orders_A[-1]:
# Avoid redundant empty segments when two HHInter segments are next to each other.
if len(tmp_A) > 0 or len(tmp_B) > 0:
humaninter_segs.append([tmp_A, tmp_B])
tmp_B = []
tmp_B.append([wpaths_B, seg_orders_B, var_B])
break
else:
tmp_B.append([wpaths_B, seg_orders_B, var_B])
tmp_A = []
tmp_A.append([wpaths_A, seg_orders_A, var_A])
# Ensure the HHInter orders are independently separated from others.
humaninter_segs.append([tmp_A, tmp_B])
tmp_A = tmp_B = []
else:
tmp_A.append([wpaths_A, seg_orders_A, var_A])
iiid_A += 1
if len(tmp_A) > 0 or iiid_B < len(all_wpaths[1]):
tmp_B = []
while iiid_B < len(all_wpaths[1]):
wpaths_B, seg_orders_B, var_B = all_wpaths[1][iiid_B], segmented_orders[1][iiid_B], append_vars[1][iiid_B]
tmp_B.append([wpaths_B, seg_orders_B, var_B])
iiid_B += 1
humaninter_segs.append([tmp_A, tmp_B])
return humaninter_segs
def motion_generation(humaninter_segs, result_path, scene_path, scene_name, navmesh_tight_path, navmesh_loose,
scene_mesh, wpath_path, path_name, scene_sdf_path, floor_height=0.0):
for ind, humaninter_seg in enumerate(humaninter_segs):
# humaninter_seg: [[[wpaths_A1, seg_orders_A1, var_A1], [wpaths_A2, seg_orders_A2, var_A2], ...],
# [[wpaths_B1, seg_orders_B1, var_B1], [wpaths_A2, seg_orders_A2, var_A2], ...]]
if (result_path / 'person1.pkl').exists():
with open(result_path / 'person1.pkl', 'rb') as f:
data = pickle.load(f)
motions = data['motion']
smplx_param_A = rollout_primitives(motions)
else:
smplx_param_A = []
if (result_path / 'person2.pkl').exists():
with open(result_path / 'person2.pkl', 'rb') as f:
data = pickle.load(f)
motions = data['motion']
smplx_param_B = rollout_primitives(motions)
else:
smplx_param_B = []
"To ensure motion consistency when the last seg is HHI, which needs to be after HHI generation."
if ind != 0:
for iid, smplx_param in zip([0, 1], [smplx_param_A, smplx_param_B]):
# There will be case that humaninter_seg is A:[], B:[...], thus need to check the last last segment.
if (len(humaninter_segs[ind - 1][iid]) and humaninter_segs[ind - 1][iid][-1][1][-1][:3] == "HHI") or \
(not len(humaninter_segs[ind - 1][iid]) and ind >= 2 and humaninter_segs[ind - 2][iid][-1][1][-1][:3] == "HHI"):
"In this case, the return wpath is still sampled points (search 'only_points_return_flag' in the former step)," \
"Need to add the final position of the last generated HHI motion to the points and then calculate the wpath."
points = ([np.append(smplx_param[-1][:2], 0)] + humaninter_seg[iid][0][0]) if len(smplx_param) > 0 and len(humaninter_seg[iid]) else []
wpaths = []
# From the start to the end of the points, iteratively sample two adjacent points as the start and target points
for i in range(len(points) - 1):
start_point = points[i]
target_point = points[i + 1]
if isinstance(target_point, str) and target_point == 'copy':
target_point = points[i]
if target_point is None: # stand or HHI
continue
start_target = np.stack([start_point, target_point])
# find collision free path
wpath = path_find(navmesh_loose, start_target[0], start_target[1], visualize=False,
scene_mesh=scene_mesh)
# When point is at edges, maybe no path.
if len(wpath) == 0:
wpath = np.stack([start_point, target_point])
# when use 'copy', only return one point.
if len(wpath) == 1:
wpath = np.concatenate([wpath, wpath + np.random.randn(3) * 0.01], axis=0)
wpaths.append(wpath)
if len(humaninter_seg[iid]):
humaninter_seg[iid][0][0] = wpaths
"Ensure the cumulated motion time of the two persons are consistent. Index [1] because the HHInter " \
"orders are independently separated from others."
if len(humaninter_seg[0]) and humaninter_seg[0][0][1][-1] is not None and humaninter_seg[0][0][1][-1][:3] == "HHI":
human_inter_flag = True
# Wpaths number.
# +2 because person2 needs to walk to the front of the person1.
max_frames = max(len(np.concatenate(humaninter_seg[0][0][0], axis=0)) if len(humaninter_seg[0][0][0]) != 0 else 0,
(len(np.concatenate(humaninter_seg[1][0][0], axis=0)) + 2) if len(humaninter_seg[1][0][0]) != 0 else 2) * 7
# Supple the frames to ensure the two persons have the same motion time.
if len(smplx_param_A) > len(smplx_param_B):
frames_supple = np.array([0, (len(smplx_param_A) - len(smplx_param_B) + 5) // 10]) + max_frames
else:
frames_supple = np.array([(len(smplx_param_B) - len(smplx_param_A) + 5) // 10, 0]) + max_frames
else:
human_inter_flag = False
"----------------------------------------------------------------------------------------"
"Generate single person motion and human-object interaction"
"----------------------------------------------------------------------------------------"
for iid, multipel_vars in enumerate(humaninter_seg):
if (result_path / f'person{iid + 1}.pkl').exists():
last_motion_path = result_path / f'person{iid + 1}.pkl'
else:
last_motion_path = None
for iiid, (wpaths, seg_orders, var) in enumerate(multipel_vars):
print("Current generation order: ", seg_orders)
if len(var):
action_out, interaction_name, target_point_path, target_body_path, mesh_path, sdf_path = var
# wpaths = np.array([[[0.0,0.0, 0], [0.4, 0.2, 0]], [[0.3,1.3, 0], [0.4, 1.0, 0]]])[[iid]]
# wpath = wpaths[0]
if human_inter_flag:
"Ensure the forward directions are opposite for the human interaction."
if iid == 1:
with open(result_path / 'person1.pkl', 'rb') as f:
data = pickle.load(f)
motions = data['motion']
smplx_param_A = rollout_primitives(motions)
# Get the forward direction of the first person.
body_orient = torch.cuda.FloatTensor(smplx_param_A[-1, 3:6]).squeeze()
forward_dir = pytorch3d.transforms.axis_angle_to_matrix(body_orient)[:, 2]
forward_dir[2] = 0
forward_dir = forward_dir / torch.norm(forward_dir)
try_num = 0
offset_coeff = 0.3
while try_num < 10:
r = torch.FloatTensor(1).uniform_() * 0.2 + 1.
theta = torch.cuda.FloatTensor(1).uniform_() * torch.pi - torch.pi / 2
random_rot = pytorch3d.transforms.euler_angles_to_matrix(
torch.cuda.FloatTensor([0, 0, theta]),
convention="XYZ")
first_person_dir = torch.matmul(random_rot, forward_dir).cpu().numpy()
"Add two points to walk to the front of the first person and then turn body back."
additional_front_point = smplx_param_A[-1, :3] + r.cpu().numpy() * first_person_dir
if is_inside(navmesh_loose, additional_front_point[:2].reshape(1, 1, 2)):
break
else:
try_num += 1
if not is_inside(navmesh_loose, additional_front_point[:2].reshape(1, 1, 2)):
additional_front_point = project_to_navmesh(navmesh_loose, np.array([additional_front_point]))[0]
additional_front_point[2] = 0
additional_point = additional_front_point - offset_coeff * first_person_dir
if not is_inside(navmesh_loose, additional_point[:2].reshape(1, 1, 2)):
additional_point = project_to_navmesh(navmesh_loose, np.array([additional_point]))[0]
additional_point[2] = 0
points = [wpaths[-1][-1], additional_front_point, additional_point]
# From the start to the end of the points, iteratively sample two adjacent points as the start and target points
tmp_wpaths = []
for i in range(len(points) - 1):
start_point = points[i]
target_point = points[i + 1]
if target_point is None: # stand
continue
start_target = np.stack([start_point, target_point])
# find collision free path
wpath = path_find(navmesh_loose, start_target[0], start_target[1], visualize=False,
scene_mesh=scene_mesh)
# When point is at edges, maybe no path.
if len(wpath) == 0:
wpath = np.stack([start_point, target_point])
tmp_wpaths.append(wpath)
wpaths[-1] = np.concatenate(
[wpaths[-1], np.concatenate(tmp_wpaths, axis=0)[1:]],
axis=0)
if len(wpaths): # Decide if pure interaction.
wpath = np.concatenate(wpaths, axis=0)
with open(wpath_path, 'wb') as f:
pickle.dump(wpath, f)
# If HHInter, the max_depth is set to frames_supple to ensure the two persons have the same motion time.
max_depth = 30 * len(wpath) if not human_inter_flag else frames_supple[iid]
cfg_policy = 'MPVAEPolicy_frame_label_walk_collision/map_nostop'
cfg_policy_path = f'../results/exp_GAMMAPrimitive/{cfg_policy}'
command = (
f"python synthesize/gen_locomotion_unify.py --goal_thresh 0.5 --goal_thresh_final 0.25 --max_depth {max_depth} --num_gen1 128 --num_gen2 16 --num_expand 8 "
f"--project_dir . --cfg_policy {cfg_policy_path} "
f"--gen_name policy_search --num_sequence 1 "
f"--scene_path {scene_path} --scene_name {scene_name} --navmesh_path {navmesh_tight_path} --floor_height {floor_height:.2f} --wpath_path {wpath_path} --path_name {path_name} "
f"--weight_pene 1 "
f"--visualize 0 --use_zero_pose 1 --use_zero_shape 1 --random_orient 0 --clip_far 1"
)
if last_motion_path is not None:
command += f" --last_motion_path {last_motion_path}"
# If HHInter, the no_early_stop is set to ensure the two persons have the same motion time.
if human_inter_flag:
command += f" --no_early_stop"
subprocess.run(command)
last_motion_path = f'results/locomotion/{scene_name}/{path_name}/{cfg_policy}/policy_search/seq000/results_ssm2_67_condi_marker_map_0.pkl'
# If HHInter, there is only single motion before HHInteraction.
if human_inter_flag:
continue
if seg_orders[-1] is not None and (
"sit" in seg_orders[-1] or "lie" in seg_orders[-1] or "stand" in seg_orders[-1]):
# TODO: whether need to decide 1/2 frame policy by the existence of pre-locomotion.
seq_name = interaction_name + '_down'
command = "python synthesize/gen_interaction_unify.py --goal_thresh_final -1 --max_depth 15 --num_gen1 128 --num_gen2 32 --num_expand 4 " \
"--project_dir . --cfg_policy ../results/exp_GAMMAPrimitive/MPVAEPolicy_{}_marker/{}_2frame " \
"--gen_name policy_search --num_sequence 1 " \
"--random_seed 1 --scene_path {} --scene_name {} --sdf_path {} --mesh_path {} --floor_height {:.2f} " \
"--target_body_path {} --interaction_name {} --start_point_path {} " \
"--use_zero_pose 1 --weight_target_dist 1 --history_mode 2 " \
"--visualize 0".format(action_out, action_out, scene_path, scene_name, sdf_path,
mesh_path,
floor_height,
target_body_path,
seq_name, target_point_path)
if last_motion_path is not None:
command += f" --last_motion_path {last_motion_path}"
print(command)
subprocess.run(command)
last_motion_path = f'results/interaction/{scene_name}/{seq_name}/MPVAEPolicy_{action_out}_marker/{action_out}_2frame/policy_search/seq000/results_ssm2_67_condi_marker_inter_0.pkl'
if seg_orders[-1] is not None and ("stand" in seg_orders[-1]): # stand
"""stand up"""
command = "python synthesize/gen_interaction_unify.py --goal_thresh_final 0.3 --max_depth 10 --num_gen1 128 --num_gen2 16 --num_expand 8 " \
"--project_dir . --cfg_policy ../results/exp_GAMMAPrimitive/MPVAEPolicy_{}_marker/{}_2frame " \
"--gen_name policy_search --num_sequence 1 " \
"--random_seed 1 --scene_path {} --scene_name {} --sdf_path {} --mesh_path {} --floor_height {:.2f} " \
"--target_point_path {} --interaction_name {} " \
"--use_zero_pose 0 --weight_target_dist 1 --history_mode 2 " \
"--visualize 0".format(action_out, action_out, scene_path, scene_name, sdf_path,
mesh_path,
floor_height,
target_point_path, interaction_name + '_up')
if last_motion_path is not None:
command += f" --last_motion_path {last_motion_path}"
print(command)
subprocess.run(command)
last_motion_path = f'results/interaction/{scene_name}/{interaction_name}_up/MPVAEPolicy_{action_out}_marker/{action_out}_2frame/policy_search/seq000/results_ssm2_67_condi_marker_inter_0.pkl'
if last_motion_path is not None:
if last_motion_path != result_path / f'person{iid + 1}.pkl':
shutil.copy(last_motion_path, result_path / f'person{iid + 1}.pkl')
"----------------------------------------------------------------------------------------"
"----------------------------------------------------------------------------------------"
"After fininshing the single motion of the two persons, we need to do the HHInteraction."
"----------------------------------------------------------------------------------------"
if human_inter_flag:
text = humaninter_seg[0][0][1][-1][4:]
with open(get_SSM_SMPLX_body_marker_path()) as f:
marker_ssm_67 = list(json.load(f)['markersets'][0]['indices'].values())
"Convert the markers of the last motion of the two persons to the canonical markers."