File size: 13,904 Bytes
d4159be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Local LoomG2 adapter: independent Rerun UI, original files are read-only."""
from pathlib import Path
import argparse
import json
import math
import subprocess
import socket
from contextlib import ExitStack
import cv2
import h5py
import numpy as np
import pyarrow.parquet as pq
import rerun as rr
import rerun.blueprint as bp
from tactile_display import render as render_tactile, points as tactile_points, particles as tactile_particles
from mano_display import load as load_mano, vertex_normals
from world_trails import RollingTrail, COLORS as TRAIL_COLORS

ROOT = Path(__file__).resolve().parent
SCENES = []
EDGES = [(a, b) for chain in [[0,1,2,3], [0,4,5,6,7], [0,8,9,10,11],
                              [0,12,13,14,15], [0,16,17,18,19]]
         for a,b in zip(chain,chain[1:])]
CAMERAS = ['head_RGB','head_gray_left','head_gray_right','wrist_left','wrist_right']

# Exact camera frustum geometry from portable_preview's world viewer (camera +Z forward).
HEAD_VERTICES=np.array([[-.025,-.018,0],[.025,-.018,0],[.025,.018,0],[-.025,.018,0],
                       [-.075,-.052,.145],[.075,-.052,.145],[.075,.052,.145],[-.075,.052,.145]])
HEAD_FACES=np.array([0,1,2,0,2,3,0,4,5,0,5,1,1,5,6,1,6,2,2,6,7,2,7,3,3,7,4,3,4,0]).reshape(-1,3)
HEAD_EDGES=[(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7)]

class DisplayRecording:
    # Keep dense visual data separate from the sparse event tracks in native STREAMS.
    def __init__(self, recording): self.recording=recording
    def __getattr__(self,name): return getattr(self.recording,name)
    def log(self,path,*args,**kwargs): self.recording.log('data/'+path,*args,**kwargs)
    def stream(self,path,*args,**kwargs): self.recording.log(path,*args,**kwargs)

def contact_mask(adc,side):
    active=np.zeros(len(adc),dtype=bool)
    for _,_,_,indices in tactile_points(side,adc.shape[1]):
        value=adc[:,indices].astype(float).mean(axis=1)
        active |= np.floor(value+.5)>0
    return active

def layout(native_video=False):
    def video(key, name):
        bounds = bp.VisualBounds2D(x_range=[0,1280], y_range=[0,720 if key.startswith('wrist') else 800]) if native_video else None
        return bp.Spatial2DView(origin=f'data/video/{key}', name=name, visual_bounds=bounds)
    return bp.Blueprint(
        bp.Horizontal(
            bp.Vertical(
                bp.Tabs(video('head_RGB','Head RGB'),
                        bp.Horizontal(video('head_gray_left','Left Stereo'), video('head_gray_right','Right Stereo')),active_tab=0),
                bp.Horizontal(video('wrist_left','Left Wrist Camera'), video('wrist_right','Right Wrist Camera')),
                bp.Spatial2DView(origin='data/depth',name='Left Depth (m)'),row_shares=[4,3,3]),
            bp.Vertical(bp.Spatial2DView(origin='data/tactile/left',name='Left Tactile',background=[0,0,0]),
                        bp.Spatial2DView(origin='data/tactile/right',name='Right Tactile',background=[0,0,0])),
            bp.Vertical(
                bp.Spatial3DView(origin='data/world', name='World Space - Head and Hands',
                    overrides={f'data/world/{side}/skeleton':bp.EntityBehavior(visible=False)
                               for side in ['left','right']}),
                bp.TimeSeriesView(origin='data/imu',name='Head IMU Orientation - xyzw'),row_shares=[8,2]),
            column_shares=[4,2.5,5]),
        bp.TimePanel(timeline='time',fps=30,playback_speed=1,play_state='paused'),
        auto_layout=False, auto_views=False)

def world_skeleton(rec,side,positions):
    """Stable, pickable joint entities without labels cluttering the world view."""
    path='world/'+side+'/skeleton'
    valid=np.isfinite(positions).all(axis=1)
    prefix='L' if side=='left' else 'R'
    color=[255,224,160] if side=='left' else [165,235,255]
    for joint,position in enumerate(positions):
        joint_path=f'{path}/joints/{prefix}{joint:02d}'
        if valid[joint]:
            rec.log(joint_path,rr.Points3D([position],radii=.0045,colors=color,
                                         labels=[f'{prefix}{joint:02d}'],show_labels=False))
        else:
            rec.log(joint_path,rr.Clear(recursive=True))
    lines=[positions[[a,b]] for a,b in EDGES if valid[a] and valid[b]]
    if lines:
        rec.log(path+'/bones',rr.LineStrips3D(lines,radii=.002,colors=color))
    else:
        rec.log(path+'/bones',rr.Clear(recursive=True))

def convert(item, mocap_overlay=False, *, output=None, mesh_cache=None, stream_url=None):
    ep=ROOT/item['local']
    if output is None:
        cache=ROOT/('recordings-english-mocap-overlay-named' if mocap_overlay else 'recordings-english')
        output=cache/f"{item['scene']}_{item['episode']}.rrd"
    output=Path(output)
    output.parent.mkdir(parents=True,exist_ok=True)
    temporary=output.with_suffix('.partial.rrd')
    sync=pq.read_table(ep/'meta/timeline/sync.parquet').to_pydict()
    times=np.asarray(sync['master_ts']); frames=np.asarray(sync['frame_idx'])
    assert len(times)>0 and np.all(np.diff(times)>0)
    n=len(times)
    rec=rr.RecordingStream(item.get('application','LoomG2 - '+item['scene'].title()),recording_id=item['episode'])
    if stream_url:
        rec.set_sinks(rr.FileSink(temporary),rr.GrpcSink(stream_url))
    else:
        rec.save(temporary)
    if not stream_url:
        rec.send_recording_name(item['episode'])
    rec=DisplayRecording(rec)
    # The library installs the layout once per scene; switching episodes preserves UI choices.
    if not stream_url:
        rec.send_blueprint(layout())
    # A per-recording snapshot of the real episode directory, for the native Blueprint panel.
    for file in sorted(ep.rglob('*')):
        if file.is_file():
            rec.stream('__directory/'+item['episode']+'/'+file.relative_to(ep).as_posix(),
                       rr.TextDocument(file.relative_to(ep).as_posix()),static=True)
    meshes=load_mano(Path(mesh_cache) if mesh_cache else ROOT/'mesh-cache'/item['scene'],n)
    overlay=None
    if mocap_overlay:
        from mocap_rgb_overlay import MocapRgbOverlay
        overlay=MocapRgbOverlay(ep)
    rec.log('world',rr.ViewCoordinates.RIGHT_HAND_Z_UP,static=True)
    for side in ['left','right']:
        rec.log(f'tactile/{side}/legend',rr.TextDocument('Original portable_preview hand layout; default display scale ADC 0–40.'),static=True)
    report={'scene':item['scene'],'episode':item['episode'],'frames':n,'duration_s':float(times[-1]),'videos':{},'omitted':['3D tactile attachment: no channel-to-space mapping','EMF sensor poses: not present','IMU acceleration/angular velocity: not present']}
    with ExitStack() as stack:
        def dataset(file,key):
            d=stack.enter_context(h5py.File(ep/file,'r'))[key]
            assert len(d)==n,(file,len(d),n)
            return d
        tactile={s:dataset(f'tactile/{s}.h5','adc')[:] for s in ['left','right']}
        for side,values in tactile.items():
            rec.stream('__tactile/'+side+'/layout',rr.TextDocument(json.dumps(
                tactile_particles(side,values.shape[1]),ensure_ascii=False,separators=(',',':'))),static=True)
        world=stack.enter_context(h5py.File(ep/'world_pose/world_motion.h5','r'))
        poses={k:world[k][:] for k in ['left_world_m','right_world_m','head_position_m','head_quaternion_xyzw']}
        assert all(len(v)==n for v in poses.values())
        trails={key:RollingTrail(poses['head_position_m'] if key=='head' else poses[key+'_world_m'][:,0],times)
                for key in ['head','left','right']}
        imu=dataset('imu/head_imu.h5','aligned/orientation')[:]
        depth=dataset('head_depth/head_depth.h5','depth')
        actions=json.loads((ep/'annotations/auto_actions.json').read_text(encoding='utf-8')).get('actions',[])
        actions=[a for a in actions if isinstance(a.get('start'),(int,float)) and isinstance(a.get('end'),(int,float)) and a['start']<=a['end']]
        contact={side:contact_mask(values,side) for side,values in tactile.items()}
        report['contact']={side:{'active_frames':int(mask.sum()),'total_frames':n} for side,mask in contact.items()}
        for side,label in [('left','01 Left Tactile'),('right','02 Right Tactile')]:
            rec.stream('01 Tactile/'+label,rr.TextDocument('Visible tactile ADC > 0; blank means no contact.'),static=True)
        captures={k:cv2.VideoCapture(str(ep/'camera'/f'{k}.mp4')) for k in CAMERAS}
        for cap in captures.values():stack.callback(cap.release)
        assert all(c.isOpened() for c in captures.values())
        counts={k:0 for k in CAMERAS}
        report['tactile_channels']={s:int(v.shape[1]) for s,v in tactile.items()}
        for i,t in enumerate(times):
            rec.set_time('time',duration=float(t));rec.set_time('frame',sequence=int(frames[i]))
            for key,trail in trails.items():
                segments=trail.window(i)
                if len(segments):
                    rec.log('world/trails/'+key,rr.LineStrips3D(segments,
                            radii=rr.Radius.ui_points(.75),colors=TRAIL_COLORS[key]))
                else:
                    rec.log('world/trails/'+key,rr.Clear(recursive=True))
            for side,color in [('left',[255,145,45]),('right',[70,190,255])]:
                mesh=meshes[i][side]
                if mesh is not None and mesh['transform'] is not None:
                    transform=mesh['transform']
                    vertices=mesh['vertices']@transform[:3,:3].T+transform[:3,3]
                    rec.log('world/'+side+'/mano',rr.Mesh3D(vertex_positions=vertices,
                            vertex_normals=vertex_normals(vertices,mesh['faces']),
                            triangle_indices=mesh['faces'],albedo_factor=color,
                            face_rendering=rr.components.MeshFaceRendering.DoubleSided))
                else:
                    rec.log('world/'+side+'/mano',rr.Clear(recursive=True))
                world_skeleton(rec,side,poses[side+'_world_m'][i])
                rec.stream('__tactile/'+side+'/adc',rr.TextDocument(json.dumps(
                    {'frame':int(frames[i]),'values':tactile[side][i].tolist()},separators=(',',':'))))
                rec.log(f'tactile/{side}/adc',rr.Image(render_tactile(side,tactile[side][i])).compress(jpeg_quality=90))
            for side,label in [('left','01 Left Tactile'),('right','02 Right Tactile')]:
                if contact[side][i]:
                    rec.stream('01 Tactile/'+label,rr.TextLog('Tactile contact',color=[255,155,45] if side=='left' else [70,190,255]))
            head=poses['head_position_m'][i]
            q=poses['head_quaternion_xyzw'][i]
            if np.isfinite(head).all() and np.isfinite(q).all() and np.linalg.norm(q)>1e-8:
                # Do not clear a valid transform at the same timestamp: Rerun's TF
                # cache tracks clears by time, so chunk loading order can mask it.
                rec.log('world/head',rr.Transform3D(translation=head,quaternion=q/np.linalg.norm(q)))
                rec.log('world/head/model',rr.Mesh3D(vertex_positions=HEAD_VERTICES,triangle_indices=HEAD_FACES,albedo_factor=[232,238,246,75]))
                rec.log('world/head/outline',rr.LineStrips3D([HEAD_VERTICES[[a,b]] for a,b in HEAD_EDGES],colors=[255,255,255],radii=.0008))
            else:
                rec.log('world/head',rr.Clear(recursive=True))
            for k,v in zip('xyzw',imu[i]):
                rec.log('imu/'+k,rr.Scalars(float(v)))
            for k,cap in captures.items():
                ok,image=cap.read()
                if not ok: raise RuntimeError(f'{k}: missing video frame {i}/{n}')
                image=cv2.resize(image,(640,round(image.shape[0]*640/image.shape[1])))
                rec.log('video/'+k,rr.Image(cv2.cvtColor(image,cv2.COLOR_BGR2RGB)).compress(jpeg_quality=80))
                counts[k]+=1
            if overlay is not None:
                for side,color in [('left',[255,145,45]),('right',[70,190,255])]:
                    path=f'video/head_RGB/mocap_overlay/{side}'
                    uv=overlay.project(i,side)
                    valid=np.isfinite(uv).all(axis=1)
                    if valid.any():
                        rec.log(path+'/joints',rr.Points2D(uv[valid],colors=color,radii=2.2))
                        segments=[uv[[a,b]] for a,b in EDGES if valid[a] and valid[b]]
                        rec.log(path+'/bones',rr.LineStrips2D(segments,colors=color,radii=1.2))
                    else:
                        rec.log(path,rr.Clear(recursive=True))
            # Keep depth values/invalid zeros intact; spatially decimate for responsive playback.
            rec.log('depth/image',rr.DepthImage(depth[i][::4,::4],meter=1000,depth_range=[0,3000]))
            for j,a in enumerate(actions):
                on=a['start']<=frames[i]<=a['end']
                if on:
                    rec.stream(f'02 Actions/{j+1:02d}',rr.TextLog(a.get('label','')))
            if i%200==0:print(item['scene'],i,'/',n,flush=True)
        report['videos']=counts
    rec.flush();rec.disconnect()
    temporary.replace(output)
    output.with_suffix('.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    print('READY',output,flush=True)
    return output

def main():
    parser = argparse.ArgumentParser(description='LoomG2 portable data player')
    parser.add_argument('--open', action='store_true')
    parser.add_argument('--scene')
    parser.add_argument('--data-root', type=Path, default=ROOT.parent / 'data')
    args = parser.parse_args()
    from compact_player import serve
    serve(args.data_root, args.scene)

if __name__ == '__main__':
    main()