Datasets:

File size: 44,923 Bytes
dbf8921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ddc1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbf8921
 
 
 
4ddc1be
dbf8921
 
 
 
 
 
 
 
 
 
 
 
 
4ddc1be
dbf8921
 
 
 
4ddc1be
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ee215408-e60b-4209-a09a-f84a8fd5ffa1",
   "metadata": {},
   "source": [
    "# HOT3D Data Reader\n",
    "\n",
    "This notebook is adapted from the HOT3D official tutorial. It supports both **Aria** and **Quest3** devices and uses only the **MANO** hand model (no UmeTrack or object assets required).\n",
    "\n",
    "## Sections\n",
    "- **Section 0**: Initialization (update the two paths, then run)\n",
    "- **Section 1**: Image streams + camera calibration\n",
    "- **Section 2.a**: Device / headset pose trajectory\n",
    "- **Section 2.b**: Hand wrist trajectory\n",
    "- **Section 2.b.a**: Hand landmarks (skeleton) + mesh\n",
    "- **Section 2.c**: Object poses (requires assets folder, skipped automatically otherwise)\n",
    "- **Section 3.b**: Hand 2D bounding boxes\n",
    "- **Section 4**: Eye gaze (Aria only, skipped automatically on Quest3)\n",
    "- **Section 5**: Hand keypoint reprojection onto image\n",
    "\n",
    "```\n",
    "Hot3dDataProvider\n",
    "|- device_data_provider        -> image data + camera calibration\n",
    "|- device_pose_data_provider   -> device pose\n",
    "|- mano_hand_data_provider     -> hand pose (MANO)\n",
    "|- object_pose_data_provider   -> object pose\n",
    "|- hand_box2d_data_provider    -> hand 2D bounding boxes\n",
    "|- object_box2d_data_provider  -> object 2D bounding boxes\n",
    "```\n",
    "\n",
    "> All pose data is in **world coordinates** (meters)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97bcb96c-4910-4a60-9a41-c3b34ee7ac7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 0: DataProvider initialization\n",
    "#\n",
    "# Only the two paths below need to be updated; everything else adapts automatically\n",
    "# to Aria or Quest3.\n",
    "\n",
    "import os\n",
    "import sys\n",
    "\n",
    "# Make sure the hot3d package is importable from this notebook\n",
    "notebook_dir = os.path.abspath('')\n",
    "if notebook_dir not in sys.path:\n",
    "    sys.path.insert(0, notebook_dir)\n",
    "\n",
    "from dataset_api import Hot3dDataProvider\n",
    "from data_loaders.mano_layer import MANOHandModel\n",
    "from data_loaders.headsets import Headset\n",
    "from projectaria_tools.core.stream_id import StreamId\n",
    "\n",
    "# ── Update these two paths ───────────────────────────────────────\n",
    "sequence_path   = \"/home/zhang/3D_Reconstruct/HOT3D/hot3d/hot3d/dataset/P0002_2f137f83\"\n",
    "mano_model_path = \"/home/zhang/Downloads/mano_v1_2/models\"\n",
    "# ────────────────────────────────────────────────────────────────\n",
    "\n",
    "# Load MANO hand model (requires smplx: pip install smplx)\n",
    "mano_hand_model = MANOHandModel(mano_model_path)\n",
    "\n",
    "# Initialize the data provider.\n",
    "# object_library=None: no assets folder needed when only reading hand data.\n",
    "hot3d_data_provider = Hot3dDataProvider(\n",
    "    sequence_folder=sequence_path,\n",
    "    object_library=None,\n",
    "    mano_hand_model=mano_hand_model,\n",
    ")\n",
    "\n",
    "# Auto-detect device type and pick the corresponding primary camera stream_id\n",
    "device_type = hot3d_data_provider.get_device_type()\n",
    "print(f\"Device type: {device_type}\")\n",
    "\n",
    "if device_type == Headset.Aria:\n",
    "    main_stream_id = StreamId(\"214-1\")   # Aria: RGB camera\n",
    "else:\n",
    "    main_stream_id = StreamId(\"1201-1\")  # Quest3: SLAM Left camera\n",
    "\n",
    "print(f\"Primary stream_id: {main_stream_id}\")\n",
    "print(f\"Data statistics: {hot3d_data_provider.get_data_statistics()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24dae021-1cfe-440a-a5c8-6f44851219e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Utility functions for Rerun visualization\n",
    "\n",
    "import rerun as rr\n",
    "import numpy as np\n",
    "from projectaria_tools.core.sophus import SE3\n",
    "from projectaria_tools.utils.rerun_helpers import ToTransform3D\n",
    "\n",
    "\n",
    "def log_image(image: np.array, label: str, static=False) -> None:\n",
    "    rr.log(label, rr.Image(image), static=static)\n",
    "\n",
    "\n",
    "def log_pose(pose: SE3, label: str, static=False) -> None:\n",
    "    rr.log(label, ToTransform3D(pose, False), static=static)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7447d83-bf07-4bfb-8e4f-9d548617cde7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 1: Image streams + camera calibration\n",
    "\n",
    "from tqdm import tqdm\n",
    "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n",
    "\n",
    "device_data_provider = hot3d_data_provider.device_data_provider\n",
    "image_stream_ids = device_data_provider.get_image_stream_ids()\n",
    "\n",
    "# Timestamp retrieval differs between Aria and Quest3\n",
    "if device_type == Headset.Aria:\n",
    "    timestamps = device_data_provider.get_sequence_timestamps(\n",
    "        stream_id=main_stream_id,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "else:\n",
    "    timestamps = device_data_provider.get_sequence_timestamps()\n",
    "\n",
    "print(f\"Sequence : {os.path.basename(os.path.normpath(sequence_path))}\")\n",
    "print(f\"Streams  : {image_stream_ids}\")\n",
    "print(f\"Frames   : {len(timestamps)}\")\n",
    "\n",
    "rr.init(\"Device images\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Sample one frame every 200 timestamps to keep the visualization fast\n",
    "for timestamp_ns in tqdm(timestamps[::200]):\n",
    "    for stream_id in image_stream_ids:\n",
    "        image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        if image_data is not None:\n",
    "            log_image(label=f\"img/{image_stream_label}\", image=image_data)\n",
    "\n",
    "# Print calibration parameters for each camera stream\n",
    "for stream_id in image_stream_ids:\n",
    "    [extrinsics, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
    "    label = device_data_provider.get_image_stream_label(stream_id)\n",
    "    print(f\"\\n[{label}] intrinsics: {intrinsics}\")\n",
    "\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d199e9c-7359-43b2-8ecd-807db548def0",
   "metadata": {},
   "source": [
    "# GT Data Provider API\n",
    "\n",
    "All GT data providers share the same query interface:\n",
    "```python\n",
    "result = provider.get_X_at_timestamp(\n",
    "    timestamp_ns=timestamp_ns,\n",
    "    time_query_options=TimeQueryOptions.CLOSEST,\n",
    "    time_domain=TimeDomain.TIME_CODE,\n",
    ")\n",
    "```\n",
    "- If the exact timestamp is not found, the **closest** sample is returned.\n",
    "- The delta time (`dt`) between the queried and returned timestamp is also available.\n",
    "\n",
    "Available providers:\n",
    "```\n",
    "|- device_pose_data_provider   -> device/headset pose\n",
    "|- mano_hand_data_provider     -> hand pose (MANO)\n",
    "|- object_pose_data_provider   -> object pose\n",
    "|- hand_box2d_data_provider    -> hand 2D bbox + visibility\n",
    "|- object_box2d_data_provider  -> object 2D bbox + visibility\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c473c3-174f-4cff-9d58-0650b580da72",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 2.a: Device / headset pose trajectory\n",
    "\n",
    "device_pose_provider = hot3d_data_provider.device_pose_data_provider\n",
    "\n",
    "rr.init(\"Device/Headset trajectory\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "pose_translations = []\n",
    "for timestamp_ns in tqdm(timestamps):\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    if device_pose_provider is None:\n",
    "        continue\n",
    "    result = device_pose_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    if result is None:\n",
    "        continue\n",
    "\n",
    "    T_world_device = result.pose3d.T_world_device\n",
    "    log_pose(pose=T_world_device, label=\"world/device\")\n",
    "    pose_translations.append(T_world_device.translation()[0])\n",
    "\n",
    "rr.log(\"world/device_trajectory\", rr.LineStrips3D([pose_translations]), static=True)\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5253618-2ca2-4d11-a605-aa5aa19c54eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 2.b: Hand wrist trajectory (MANO only)\n",
    "\n",
    "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n",
    "if hand_data_provider is None:\n",
    "    print(\"MANO hand data provider not initialized. Check mano_model_path and smplx installation.\")\n",
    "\n",
    "rr.init(\"Hand wrist trajectory\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "left_traj, right_traj = [], []\n",
    "for timestamp_ns in tqdm(timestamps):\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    if hand_data_provider is None:\n",
    "        continue\n",
    "    result = hand_data_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    if result is None:\n",
    "        continue\n",
    "\n",
    "    for hand_pose in result.pose3d_collection.poses.values():\n",
    "        label = hand_pose.handedness_label()\n",
    "        T_world_wrist = hand_pose.wrist_pose\n",
    "        log_pose(pose=T_world_wrist, label=f\"world/hand/{label}\")\n",
    "        if hand_pose.is_left_hand():\n",
    "            left_traj.append(T_world_wrist.translation()[0])\n",
    "        else:\n",
    "            right_traj.append(T_world_wrist.translation()[0])\n",
    "\n",
    "if left_traj:\n",
    "    rr.log(\"world/left_hand_traj\", rr.LineStrips3D([left_traj]), static=True)\n",
    "if right_traj:\n",
    "    rr.log(\"world/right_hand_traj\", rr.LineStrips3D([right_traj]), static=True)\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a013c63-65e6-4c38-b378-141c8c7ae3ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 2.b.a: Hand landmarks (skeleton) and mesh\n",
    "#\n",
    "# Left hand  -> landmark line strips (skeleton)\n",
    "# Right hand -> triangular mesh\n",
    "\n",
    "from data_loaders.hand_common import LANDMARK_CONNECTIVITY\n",
    "\n",
    "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n",
    "\n",
    "rr.init(\"Hand Landmark / Mesh\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "for timestamp_ns in tqdm(timestamps[:300]):\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    if hand_data_provider is None:\n",
    "        continue\n",
    "    result = hand_data_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    if result is None:\n",
    "        continue\n",
    "\n",
    "    for hand_pose in result.pose3d_collection.poses.values():\n",
    "        label = hand_pose.handedness_label()\n",
    "\n",
    "        if hand_pose.is_left_hand():\n",
    "            # Skeleton: connected landmark line strips\n",
    "            landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n",
    "            points = [\n",
    "                [landmarks[i].numpy().tolist() for i in conn]\n",
    "                for conn in LANDMARK_CONNECTIVITY\n",
    "            ]\n",
    "            rr.log(f\"world/{label}/joints\", rr.LineStrips3D(points, radii=0.002))\n",
    "\n",
    "        else:\n",
    "            # Mesh: vertices, triangle indices, and vertex normals\n",
    "            verts = hand_data_provider.get_hand_mesh_vertices(hand_pose)\n",
    "            triangles, normals = hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose)\n",
    "            rr.log(\n",
    "                f\"world/{label}/mesh\",\n",
    "                rr.Mesh3D(\n",
    "                    vertex_positions=verts,\n",
    "                    vertex_normals=normals,\n",
    "                    triangle_indices=triangles,\n",
    "                ),\n",
    "            )\n",
    "\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a909427f-d8c5-40a7-8eba-8702de2a313b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 2.c: Object poses\n",
    "# Requires object_library (assets folder). Skipped automatically if not available.\n",
    "\n",
    "if hot3d_data_provider._object_library is None:\n",
    "    print(\"Skipping Section 2.c: object_library=None (no assets folder loaded)\")\n",
    "else:\n",
    "    from data_loaders.loader_object_library import ObjectLibrary\n",
    "    object_library = hot3d_data_provider._object_library\n",
    "    object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
    "    object_cache_status = {}\n",
    "\n",
    "    rr.init(\"Object pose\")\n",
    "    rec = rr.memory_recording()\n",
    "\n",
    "    for timestamp_ns in tqdm(timestamps[100:300]):\n",
    "        rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "        rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "        result = object_pose_data_provider.get_pose_at_timestamp(\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            time_query_options=TimeQueryOptions.CLOSEST,\n",
    "            time_domain=TimeDomain.TIME_CODE,\n",
    "        )\n",
    "        if result is None:\n",
    "            continue\n",
    "\n",
    "        object_uids = object_pose_data_provider.object_uids_with_poses\n",
    "        logging_status = {x: False for x in object_uids}\n",
    "\n",
    "        for object_uid, object_pose3d in result.pose3d_collection.poses.items():\n",
    "            object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n",
    "            log_pose(pose=object_pose3d.T_world_object, label=f\"world/objects/{object_name}\")\n",
    "            logging_status[object_uid] = True\n",
    "            if object_uid not in object_cache_status:\n",
    "                object_cache_status[object_uid] = True\n",
    "                asset_path = ObjectLibrary.get_cad_asset_path(\n",
    "                    object_library_folderpath=object_library.asset_folder_name,\n",
    "                    object_id=object_uid,\n",
    "                )\n",
    "                rr.log(f\"world/objects/{object_name}\", rr.Asset3D(path=asset_path))\n",
    "\n",
    "        for object_uid, displayed in logging_status.items():\n",
    "            if not displayed:\n",
    "                object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n",
    "                rr.log(f\"world/objects/{object_name}\", rr.Clear.recursive())\n",
    "                object_cache_status.pop(object_uid, None)\n",
    "\n",
    "    rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f31214ce-108e-403e-b66f-2c224ab450f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 3: 2D Bounding Boxes\n",
    "# Bbox data is queried by TIMESTAMP + STREAM_ID and contains an amodal bbox and a visibility ratio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b841145d-a114-4693-a0d4-492f9629bbbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 3.a: Object 2D bounding boxes\n",
    "# Requires object_library. Skipped automatically if not available.\n",
    "\n",
    "if hot3d_data_provider._object_library is None:\n",
    "    print(\"Skipping Section 3.a: object_library=None\")\n",
    "else:\n",
    "    import matplotlib.pyplot as plt\n",
    "    object_library = hot3d_data_provider._object_library\n",
    "    object_box2d_data_provider = hot3d_data_provider.object_box2d_data_provider\n",
    "    object_uids = list(object_box2d_data_provider.object_uids)\n",
    "    color_map = plt.get_cmap(\"viridis\")\n",
    "    object_box2d_colors = color_map(np.linspace(0, 1, len(object_uids)))\n",
    "\n",
    "    rr.init(\"Object bounding boxes\")\n",
    "    rec = rr.memory_recording()\n",
    "\n",
    "    stream_id = main_stream_id\n",
    "    for timestamp_ns in tqdm(timestamps[100:200]):\n",
    "        rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "        rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "        result = object_box2d_data_provider.get_bbox_at_timestamp(\n",
    "            stream_id=stream_id,\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            time_query_options=TimeQueryOptions.CLOSEST,\n",
    "            time_domain=TimeDomain.TIME_CODE,\n",
    "        )\n",
    "        if result is None or result.box2d_collection is None:\n",
    "            continue\n",
    "\n",
    "        for object_uid in result.box2d_collection.object_uid_list:\n",
    "            object_name = object_library.object_id_to_name_dict[object_uid]\n",
    "            ab = result.box2d_collection.box2ds[object_uid]\n",
    "            bbox = ab.box2d\n",
    "            if bbox is None:\n",
    "                continue\n",
    "            rr.log(\n",
    "                f\"{stream_id}_raw/bbox/{object_name}\",\n",
    "                rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n",
    "                           colors=object_box2d_colors[object_uids.index(object_uid)]),\n",
    "            )\n",
    "            rr.log(f\"visibility/{object_name}\", rr.Scalar(ab.visibility_ratio))\n",
    "            image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "            if image_data is not None:\n",
    "                log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
    "\n",
    "    rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d1daf98-2df6-4d0a-ae38-331060353b99",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 3.b: Hand 2D bounding boxes\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from data_loaders.loader_hand_poses import LEFT_HAND_INDEX, RIGHT_HAND_INDEX\n",
    "\n",
    "hand_box2d_data_provider = hot3d_data_provider.hand_box2d_data_provider\n",
    "hand_uids = [LEFT_HAND_INDEX, RIGHT_HAND_INDEX]\n",
    "hand_names = {LEFT_HAND_INDEX: \"left\", RIGHT_HAND_INDEX: \"right\"}\n",
    "color_map = plt.get_cmap(\"viridis\")\n",
    "hand_box2d_colors = color_map(np.linspace(0, 1, 2))\n",
    "\n",
    "rr.init(\"Hand bounding boxes\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "stream_id = main_stream_id\n",
    "if stream_id not in hand_box2d_data_provider.stream_ids:\n",
    "    print(f\"stream_id {stream_id} has no hand bbox data. Available: {hand_box2d_data_provider.stream_ids}\")\n",
    "\n",
    "for timestamp_ns in tqdm(timestamps[100:200]):\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    result = hand_box2d_data_provider.get_bbox_at_timestamp(\n",
    "        stream_id=stream_id,\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    if result is None or result.box2d_collection is None:\n",
    "        continue\n",
    "\n",
    "    for i, hand_uid in enumerate(hand_uids):\n",
    "        ab = result.box2d_collection.box2ds[hand_uid]\n",
    "        bbox = ab.box2d\n",
    "        if bbox is None:\n",
    "            continue\n",
    "        hand_name = hand_names[hand_uid]\n",
    "        rr.log(\n",
    "            f\"{stream_id}_raw/bbox/{hand_name}\",\n",
    "            rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n",
    "                       colors=hand_box2d_colors[i]),\n",
    "        )\n",
    "        rr.log(f\"visibility/{hand_name}\", rr.Scalar(ab.visibility_ratio))\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        if image_data is not None:\n",
    "            log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
    "\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8bad34e-a8ab-437d-84ff-1c046ca35d51",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 4: Eye gaze (Aria only, skipped automatically on Quest3)\n",
    "\n",
    "if device_type != Headset.Aria:\n",
    "    print(f\"Skipping Section 4: eye gaze is Aria-only (current device: {device_type})\")\n",
    "else:\n",
    "    from projectaria_tools.core.calibration import FISHEYE624\n",
    "\n",
    "    rr.init(\"Eye Gaze reprojection\")\n",
    "    rec = rr.memory_recording()\n",
    "\n",
    "    stream_id = StreamId(\"214-1\")\n",
    "    for timestamp_ns in tqdm(timestamps[100:120]):\n",
    "        rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "        rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "        eye_gaze = device_data_provider.get_eye_gaze(timestamp_ns)\n",
    "        if eye_gaze is None:\n",
    "            continue\n",
    "\n",
    "        proj = device_data_provider.get_eye_gaze_in_camera(\n",
    "            stream_id, timestamp_ns, camera_model=FISHEYE624\n",
    "        )\n",
    "        if proj is None or not proj.any():\n",
    "            continue\n",
    "\n",
    "        rr.log(f\"{stream_id}/eye-gaze\", rr.Points2D(proj, radii=20))\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        if image_data is not None:\n",
    "            log_image(label=str(stream_id), image=image_data)\n",
    "\n",
    "    rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4d6ac37-e3b3-401a-83b7-e09a42a183a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Section 5: Hand keypoint reprojection onto image\n",
    "#\n",
    "# Projects 3D world-space hand landmarks through the camera extrinsics + intrinsics\n",
    "# to obtain 2D pixel coordinates, then overlays them on the image.\n",
    "\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "from typing import Any, Optional\n",
    "from data_loaders.HeadsetPose3dProvider import HeadsetPose3dProvider\n",
    "from data_loaders.loader_hand_poses import Handedness, HandPose3dCollection\n",
    "from projectaria_tools.core.calibration import CameraCalibration\n",
    "from projectaria_tools.core.sophus import SE3\n",
    "\n",
    "# Use a mid-sequence frame; clamp so the index is always valid\n",
    "frame_idx = min(420, len(timestamps) - 1)\n",
    "timestamp_ns = timestamps[frame_idx]\n",
    "image_streamid = main_stream_id  # Aria -> 214-1, Quest3 -> 1201-1\n",
    "\n",
    "image_stream_label = device_data_provider.get_image_stream_label(image_streamid)\n",
    "image_data = device_data_provider.get_image(timestamp_ns, image_streamid)\n",
    "\n",
    "\n",
    "def get_hand_poses(ts):\n",
    "    if hand_data_provider is None:\n",
    "        return None\n",
    "    result = hand_data_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=ts,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    return result.pose3d_collection if result else None\n",
    "\n",
    "\n",
    "def get_camera_pose(ts, stream_id):\n",
    "    \"\"\"Returns (T_world_camera, intrinsics) or None.\"\"\"\n",
    "    if device_pose_provider is None:\n",
    "        return None\n",
    "    result = device_pose_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=ts,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "    )\n",
    "    if result is None:\n",
    "        return None\n",
    "    [T_device_camera, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
    "    T_world_camera = result.pose3d.T_world_device @ T_device_camera\n",
    "    return T_world_camera, intrinsics\n",
    "\n",
    "\n",
    "hand_data  = get_hand_poses(timestamp_ns)\n",
    "camera_pose = get_camera_pose(timestamp_ns, image_streamid)\n",
    "\n",
    "if hand_data is None or camera_pose is None or image_data is None:\n",
    "    print(\"Missing hand data, camera pose, or image — cannot project.\")\n",
    "else:\n",
    "    T_world_camera, intrinsics = camera_pose\n",
    "    plt.figure(figsize=(10, 8))\n",
    "    plt.imshow(image_data, interpolation=\"nearest\")\n",
    "    plt.title(f\"{image_stream_label}  frame={frame_idx}\")\n",
    "\n",
    "    for hand_pose in hand_data.poses.values():\n",
    "        label = hand_pose.handedness_label()\n",
    "        landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n",
    "\n",
    "        # Gather all 3D points along the skeleton connectivity\n",
    "        all_pts_3d = [\n",
    "            landmarks[idx].numpy()\n",
    "            for conn in LANDMARK_CONNECTIVITY\n",
    "            for idx in conn\n",
    "        ]\n",
    "\n",
    "        # Project each 3D world point into the camera image plane\n",
    "        projected = []\n",
    "        for pt_world in all_pts_3d:\n",
    "            pt_cam = T_world_camera.inverse() @ pt_world\n",
    "            pt_2d  = intrinsics.project(pt_cam)\n",
    "            if pt_2d is not None:\n",
    "                projected.append(pt_2d)\n",
    "\n",
    "        color = 'r' if hand_pose.handedness == Handedness.Right else 'b'\n",
    "        print(f\"{label} hand: {len(projected)} keypoints visible in image\")\n",
    "        if projected:\n",
    "            plt.scatter([p[0] for p in projected], [p[1] for p in projected],\n",
    "                        s=3, c=color, label=label)\n",
    "\n",
    "    plt.legend()\n",
    "    plt.axis('off')\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88f7a32a",
   "metadata": {},
   "source": [
    "#\n",
    "# Segmentation Code Sample\n",
    "#\n",
    "Written by Zhonghao Zhang (FKZZddd): \n",
    "This script was copied and adapted from the original script provided by Meta for HOT3D dataset. \n",
    "The original script can be found at HOT3D/hot3d/hot3d/render_3d.py in the HOT3D repository.\n",
    "\n",
    "Used for segmentation of hand meshes by restoring the hands pose and shape data on sense.\n",
    "setup_hand_at_timestamp is the main function that segments hands and adds hand meshes to the scene\n",
    "This script was tested on BOTH Aria and Quest3. By modifying sequence_folder=\"./dataset/P0002_2f137f83\". The script can detect the device type and load the corresponding data for rendering.\n",
    "#\n",
    "# Code Sample\n",
    "#\n",
    "Installation:\n",
    "- pip install pyrender trimesh\n",
    "#\n",
    "Details:\n",
    "Demonstrate how to use PyRender to render HOT3D meshes (objects, hands) for a given timestamp & stream_id\n",
    "- As OpenGL rendering is rectilinear, color, segmentation and depth buffer are also rectilinear rendering\n",
    "- We then show how to map the rectilinear image back to the original fisheye image (but do not we are loosing some field of view)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b11b22eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Dict, List, Optional, Tuple\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "try:\n",
    "    import trimesh\n",
    "    from pyrender import (\n",
    "        IntrinsicsCamera,\n",
    "        Mesh,\n",
    "        Node,\n",
    "        OffscreenRenderer,\n",
    "        RenderFlags,\n",
    "        Scene,\n",
    "    )\n",
    "except ImportError:\n",
    "    print(\"trimesh or pyrender modules are missing. Please install them.\")\n",
    "\n",
    "from data_loaders.HandDataProviderBase import HandDataProviderBase\n",
    "from data_loaders.headsets import Headset\n",
    "from data_loaders.loader_object_library import load_object_library, ObjectLibrary\n",
    "from dataset_api import Hot3dDataProvider\n",
    "from PIL import Image\n",
    "from projectaria_tools.core.calibration import (\n",
    "    CameraCalibration,\n",
    "    distort_by_calibration,\n",
    "    FISHEYE624,\n",
    "    LINEAR,\n",
    ")\n",
    "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n",
    "from projectaria_tools.core.sophus import SE3\n",
    "from projectaria_tools.core.stream_id import StreamId\n",
    "from tqdm import tqdm\n",
    "\n",
    "# Matrix transform to change Aria camera pose to PyRender coordinate system\n",
    "# PyRender: +Z = back, +Y = up, +X = right\n",
    "# Aria: +Z = forward, +Y = down, +X = right\n",
    "T_ARIA_OPENGL = SE3.from_matrix(\n",
    "    np.array(\n",
    "        [\n",
    "            [1.0, 0.0, 0.0, 0.0],\n",
    "            [0.0, -1.0, 0.0, 0.0],\n",
    "            [0.0, 0.0, -1.0, 0.0],\n",
    "            [0.0, 0.0, 0.0, 1.0],\n",
    "        ]\n",
    "    )\n",
    ")\n",
    "\n",
    "ACCEPTABLE_TIME_DELTA = 0  # To retrieve exact GT\n",
    "\n",
    "\n",
    "def load_meshes_scene(\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    ") -> Dict[str, Mesh]:\n",
    "    \"\"\"\n",
    "    Load all meshes in the scene and hash them by object_uid\n",
    "    \"\"\"\n",
    "\n",
    "    object_library = hot3d_data_provider.object_library\n",
    "    object_library_folderpath = object_library.asset_folder_name\n",
    "\n",
    "    object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
    "    object_uids = object_pose_data_provider.object_uids_with_poses\n",
    "\n",
    "    #\n",
    "    # Load all meshes in the scene and store them in a dict\n",
    "    #\n",
    "    meshes: Dict[str, Mesh] = {}\n",
    "    for object_uid in tqdm(object_uids):\n",
    "        object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(\n",
    "            object_library_folderpath=object_library_folderpath,\n",
    "            object_id=object_uid,\n",
    "        )\n",
    "        # Load the mesh, merge its component\n",
    "        scene = trimesh.load_mesh(\n",
    "            object_cad_asset_filepath,\n",
    "            process=True,\n",
    "            merge_primitives=True,\n",
    "            file_type=\"glb\",\n",
    "        )\n",
    "        # Represent the scene by a single mesh\n",
    "        glb_mesh = scene.to_mesh()\n",
    "        # Store the resulting mesh in the dict\n",
    "        meshes[object_uid] = Mesh.from_trimesh(glb_mesh)\n",
    "\n",
    "    return meshes\n",
    "\n",
    "\n",
    "def setup_objects_at_timestamp(\n",
    "    scene: Scene,\n",
    "    meshes: Dict[str, Mesh],\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    "    timestamp_ns: int,\n",
    ") -> Dict[str, Node]:\n",
    "    \"\"\"\n",
    "    Setup object meshes in the scene for the specified timestamp\n",
    "    \"\"\"\n",
    "\n",
    "    object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
    "\n",
    "    pyrender_node_meshes = {}\n",
    "    object_poses_with_dt = None\n",
    "    if object_pose_data_provider is not None:\n",
    "        object_poses_with_dt = object_pose_data_provider.get_pose_at_timestamp(\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            time_query_options=TimeQueryOptions.CLOSEST,\n",
    "            time_domain=TimeDomain.TIME_CODE,\n",
    "            acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
    "        )\n",
    "        if object_poses_with_dt is not None:\n",
    "            objects_pose3d_collection = object_poses_with_dt.pose3d_collection\n",
    "            for (\n",
    "                object_uid,\n",
    "                object_pose3d,\n",
    "            ) in objects_pose3d_collection.poses.items():\n",
    "                transform = object_pose3d.T_world_object.to_matrix()\n",
    "                pyrender_node_meshes[object_uid] = scene.add(\n",
    "                    meshes[object_uid], pose=transform\n",
    "                )\n",
    "\n",
    "    return pyrender_node_meshes\n",
    "\n",
    "\n",
    "def get_camera_calibration(\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    "    timestamp_ns: int,\n",
    "    stream_id: StreamId,\n",
    "    camera_model=LINEAR,\n",
    ") -> Optional[Tuple[SE3, CameraCalibration]]:\n",
    "    \"\"\"\n",
    "    Return the camera calibration\n",
    "    \"\"\"\n",
    "    device_data_provider = hot3d_data_provider.device_data_provider\n",
    "    if hot3d_data_provider.get_device_type() is Headset.Aria:\n",
    "        return device_data_provider.get_online_camera_calibration(\n",
    "            stream_id=stream_id,\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            camera_model=camera_model,\n",
    "        )\n",
    "    elif hot3d_data_provider.get_device_type() is Headset.Quest3:\n",
    "        return device_data_provider.get_camera_calibration(\n",
    "            stream_id=stream_id,\n",
    "            camera_model=camera_model,\n",
    "        )\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "\n",
    "def setup_camera_at_timestamp(\n",
    "    scene: Scene,\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    "    timestamp_ns: int,\n",
    "    stream_id: StreamId,\n",
    ") -> Tuple[Node, List[int]]:\n",
    "    \"\"\"\n",
    "    Setup a rectilinear camera for the specified stream_id and timestamp\n",
    "    \"\"\"\n",
    "\n",
    "    device_data_provider = hot3d_data_provider.device_data_provider\n",
    "    device_pose_provider = hot3d_data_provider.device_pose_data_provider\n",
    "\n",
    "    [T_device_camera, intrinsics] = get_camera_calibration(\n",
    "        hot3d_data_provider=hot3d_data_provider,\n",
    "        stream_id=stream_id,\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        camera_model=LINEAR,\n",
    "    )\n",
    "\n",
    "    headset_pose3d_with_dt = None\n",
    "    if device_data_provider is not None:\n",
    "        headset_pose3d_with_dt = device_pose_provider.get_pose_at_timestamp(\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            time_query_options=TimeQueryOptions.CLOSEST,\n",
    "            time_domain=TimeDomain.TIME_CODE,\n",
    "            acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
    "        )\n",
    "        if headset_pose3d_with_dt is not None:\n",
    "            headset_pose3d = headset_pose3d_with_dt.pose3d\n",
    "            focal_lengths = intrinsics.get_focal_lengths()\n",
    "            principal_point = intrinsics.get_principal_point()\n",
    "            camera = IntrinsicsCamera(\n",
    "                focal_lengths[0],\n",
    "                focal_lengths[0],\n",
    "                principal_point[0],\n",
    "                principal_point[1],\n",
    "                znear=0.05,\n",
    "                zfar=100.0,\n",
    "                name=None,\n",
    "            )\n",
    "\n",
    "            camera_pose = (\n",
    "                (headset_pose3d.T_world_device @ T_device_camera) @ T_ARIA_OPENGL\n",
    "            ).to_matrix()\n",
    "\n",
    "            camera_node = scene.add(camera, pose=camera_pose)\n",
    "    return [camera_node, intrinsics.get_image_size().tolist()]\n",
    "\n",
    "\n",
    "def setup_hand_at_timestamp(\n",
    "    scene: Scene,\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    "    timestamp_ns: int,\n",
    "    hand_data_provider: HandDataProviderBase,\n",
    ") -> Dict[str, Mesh]:\n",
    "    \"\"\"\n",
    "    Add hand meshes to the scene for the specified timestamp\n",
    "    \"\"\"\n",
    "\n",
    "    pyrender_node_meshes = {}\n",
    "\n",
    "    if hand_data_provider is None:\n",
    "        return []\n",
    "\n",
    "    hand_poses_with_dt = hand_data_provider.get_pose_at_timestamp(\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        time_query_options=TimeQueryOptions.CLOSEST,\n",
    "        time_domain=TimeDomain.TIME_CODE,\n",
    "        acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
    "    )\n",
    "    if hand_poses_with_dt is not None:\n",
    "        hand_pose_collection = hand_poses_with_dt.pose3d_collection\n",
    "\n",
    "        for hand_pose_data in hand_pose_collection.poses.values():\n",
    "            handedness_label = hand_pose_data.handedness_label()\n",
    "\n",
    "            hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(\n",
    "                hand_pose_data\n",
    "            )\n",
    "\n",
    "            [hand_triangles, hand_vertex_normals] = (\n",
    "                hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data)\n",
    "            )\n",
    "\n",
    "            pyrender_node_meshes[handedness_label] = scene.add(\n",
    "                Mesh.from_trimesh(\n",
    "                    trimesh.Trimesh(\n",
    "                        vertices=hand_mesh_vertices,\n",
    "                        normals=hand_vertex_normals,\n",
    "                        faces=hand_triangles,\n",
    "                    )\n",
    "                )\n",
    "            )\n",
    "    return pyrender_node_meshes\n",
    "\n",
    "\n",
    "def offscreen_render(\n",
    "    scene: Scene,\n",
    "    resolution: List[int],  # [width, height]\n",
    ") -> Tuple[np.ndarray, np.ndarray]:\n",
    "    \"\"\"\n",
    "    Return COLOR and DEPTH images\n",
    "    \"\"\"\n",
    "    renderer = OffscreenRenderer(resolution[0], resolution[1])\n",
    "    color, depth = renderer.render(scene)  # , flags=RenderFlags.RGBA)\n",
    "\n",
    "    nm = {\n",
    "        node: 20 * (i + 1) for i, node in enumerate(scene.mesh_nodes)\n",
    "    }  # Node->Seg Id map\n",
    "    seg = renderer.render(scene, RenderFlags.SEG, nm)[0]\n",
    "\n",
    "    renderer.delete()\n",
    "    return [color, depth, seg]\n",
    "\n",
    "\n",
    "def distort_rendering(\n",
    "    image: np.ndarray,\n",
    "    hot3d_data_provider: Hot3dDataProvider,\n",
    "    timestamp_ns: int,\n",
    "    stream_id: StreamId,\n",
    ") -> np.ndarray:\n",
    "    \"\"\"\n",
    "    Map a rectilinear image to the native Fisheye camera model.\n",
    "    - Do notice that we are loosing some field of view.\n",
    "    \"\"\"\n",
    "\n",
    "    # Retrieve the camera model we want to distort to\n",
    "    [T_device_camera, intrinsics_raw] = get_camera_calibration(\n",
    "        hot3d_data_provider=hot3d_data_provider,\n",
    "        stream_id=stream_id,\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        camera_model=FISHEYE624,\n",
    "    )\n",
    "\n",
    "    # Retrieve the camera model we used for rendering\n",
    "    [T_device_camera, intrinsics_linear] = get_camera_calibration(\n",
    "        hot3d_data_provider=hot3d_data_provider,\n",
    "        stream_id=stream_id,\n",
    "        timestamp_ns=timestamp_ns,\n",
    "        camera_model=LINEAR,\n",
    "    )\n",
    "\n",
    "    re_distorted_image = distort_by_calibration(\n",
    "        image,\n",
    "        intrinsics_raw,\n",
    "        intrinsics_linear,\n",
    "    )\n",
    "\n",
    "    return re_distorted_image\n",
    "\n",
    "\n",
    "\n",
    "#The main function \n",
    "#Set object_library=None because object meshes are unnecessary for project.\n",
    "hot3d_data_provider = Hot3dDataProvider(\n",
    "    # sequence_folder=\"./data_loaders/tests/data_sample/Aria/P0003_c701bd11\",\n",
    "    sequence_folder=\"./dataset/P0002_2f137f83\",\n",
    "    object_library=None,\n",
    ")\n",
    "print(f\"data_provider statistics: {hot3d_data_provider.get_data_statistics()}\")\n",
    "\n",
    "scene_meshes = {}\n",
    "\n",
    "# Define timestamps and stream ids that need rendering\n",
    "# Default attempts all stream ids and a timestamp in the middle of the sequence\n",
    "\n",
    "#total timestamps/2\n",
    "timestamps = hot3d_data_provider.device_data_provider.get_sequence_timestamps()\n",
    "timestamp_list = [timestamps[len(timestamps) // 2]]\n",
    "stream_id_list = (\n",
    "    [StreamId(\"1201-1\"), StreamId(\"1201-2\"), StreamId(\"214-1\")]\n",
    "    if hot3d_data_provider.get_device_type() is Headset.Aria\n",
    "    else [StreamId(\"1201-1\"), StreamId(\"1201-2\")]\n",
    ")\n",
    "\n",
    "# Main rendering loop\n",
    "print(f\"Rendering for: {stream_id_list}\")\n",
    "for stream_id in stream_id_list:\n",
    "    for timestamp_ns in timestamp_list:\n",
    "        # Initialize the scene\n",
    "        scene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))\n",
    "\n",
    "        # Add hands into scene, the main function that do segmentation\n",
    "        setup_hand_at_timestamp(\n",
    "            scene=scene,\n",
    "            hot3d_data_provider=hot3d_data_provider,\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            hand_data_provider=hot3d_data_provider.umetrack_hand_data_provider,\n",
    "        )\n",
    "\n",
    "        # Setup camera rendering (for the specific stream_id and timestamp)\n",
    "        camera_node_and_resolution = setup_camera_at_timestamp(\n",
    "            scene=scene,\n",
    "            hot3d_data_provider=hot3d_data_provider,\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            stream_id=stream_id,\n",
    "        )\n",
    "\n",
    "        print(camera_node_and_resolution)\n",
    "        # Setup off screen rendering (to save rendering buffer to disk as image)\n",
    "        [color, depth, seg] = offscreen_render(scene, camera_node_and_resolution[1])\n",
    "\n",
    "        camera_node_and_resolution = setup_camera_at_timestamp(\n",
    "            scene=scene,\n",
    "            hot3d_data_provider=hot3d_data_provider,\n",
    "            timestamp_ns=timestamp_ns,\n",
    "            stream_id=stream_id,\n",
    "        )\n",
    "        \n",
    "        im = Image.fromarray(color)\n",
    "        im.save(f\"render_native_{stream_id}_{timestamp_ns}.png\")\n",
    "\n",
    "        # im = Image.fromarray(distorted_seg)\n",
    "        im = Image.fromarray(seg)\n",
    "        im.save(f\"seg_ref_{stream_id}_{timestamp_ns}.png\")\n",
    "\n",
    "        # Save \"depth\" buffer\n",
    "        # im = Image.fromarray(depth)\n",
    "        # im.save(f\"depth_ref_{stream_id}_{timestamp_ns}.tiff\")\n",
    "\n",
    "        image_data_raw = hot3d_data_provider.device_data_provider.get_image(\n",
    "            timestamp_ns, stream_id\n",
    "        )\n",
    "        if image_data_raw is not None:\n",
    "            im = Image.fromarray(image_data_raw)\n",
    "            im.save(f\"image_ref_{stream_id}_{timestamp_ns}.png\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hamer",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}