from pathlib import Path
import csv,json,subprocess,bisect
import numpy as np
from scipy.spatial.transform import Rotation
from PIL import Image,ImageDraw,ImageFont
BASE=Path(__file__).resolve().parent; S=BASE/'t265_capture/sessions/scene-20261110-173018';O=BASE/'weekly_extensions_20261110';O.mkdir(exist_ok=True)
def read(p):
 with p.open(encoding='utf-8',newline='') as f:return list(csv.DictReader(f))
v=read(S/'video_frames.csv');r=read(S/'pose/pose.csv'); vt=np.array([int(x['host_monotonic_ns']) for x in v],dtype='int64');pt=np.array([int(x['host_monotonic_ns']) for x in r],dtype='int64');p=np.array([[float(x[k]) for k in ('x','y','z')] for x in r]);q=np.array([[float(x[k]) for k in ('qx','qy','qz','qw')] for x in r]);R=Rotation.from_quat(q); offset=np.array([0,0,.10]); tool=p+R.apply(offset)
# Orthographic illustration, not a viewpoint registered to the webcam.
def proj(x):return np.column_stack((x[:,0]-.6*x[:,1],-x[:,2]-.35*x[:,1]))
path=proj(tool);lo=path.min(0);hi=path.max(0);center=(lo+hi)/2;extent=max(float((hi-lo).max())+.16,.2);scale=250/extent
def coords(x):return (proj(np.atleast_2d(x))-center)*scale+np.array([970,315])
ff='ffmpeg'; dec=subprocess.Popen([ff,'-loglevel','error','-i',str(S/'scene.mp4'),'-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
out=O/'virtual_gripper.mp4'
if out.exists():raise FileExistsError(out)
enc=subprocess.Popen([ff,'-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1280x720','-framerate','15','-i','pipe:0','-an','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(out)],stdin=subprocess.PIPE)
font='C:/Windows/Fonts/msyh.ttc'; title=ImageFont.truetype(font,25); body=ImageFont.truetype(font,19);small=ImageFont.truetype(font,16)
start=max(vt[0],pt[0]);end=min(vt[-1],pt[-1]);n=int((end-start)*15//1_000_000_000)+1;size=320*240*3; current=-1
try:
 for k in range(n):
  clock=start+k*1_000_000_000//15; vi=bisect.bisect_right(vt,clock)-1;pi=bisect.bisect_right(pt,clock)-1
  while current<vi:
   b=dec.stdout.read(size)
   if len(b)!=size:raise RuntimeError('video shorter than timestamp log')
   current+=1;im=Image.frombytes('RGB',(320,240),b)
  canvas=Image.new('RGB',(1280,720),'white');canvas.paste(im.resize((640,480)),(0,96));d=ImageDraw.Draw(canvas)
  d.rectangle((0,0,1280,65),fill='#192b43');d.text((20,14),'真实位姿驱动的虚拟夹爪 · 运动学示意',font=title,fill='white')
  d.text((18,70),'实景（无声，按接收时间近似对应）',font=small,fill='#26374a');d.text((670,72),'虚拟夹爪和假设工具点轨迹',font=body,fill='#26374a');d.rectangle((650,105,1270,500),outline='#b7c6d5',width=2)
  pathxy=coords(tool[:pi+1: max(1,(pi+1)//800)]);points=[tuple(a) for a in pathxy];
  if len(points)>1:d.line(points,fill='#8cb8d2',width=2)
  # Represent an idealized gripper frame; size and mounting are assumed, jaws do not open or grasp.
  local=np.array([[0,0,0],[0,0,.10],[-.04,0,.10],[-.04,0,.15],[.04,0,.10],[.04,0,.15]])
  transformed=p[pi]+R[pi].apply(local); pts=coords(transformed)
  def ln(a,b,color,width):d.line([tuple(pts[a]),tuple(pts[b])],fill=color,width=width)
  ln(0,1,'#334c67',5);ln(2,4,'#0072b2',7);ln(2,3,'#0072b2',7);ln(4,5,'#0072b2',7)
  x,y=pts[1];d.ellipse((x-5,y-5,x+5,y+5),fill='#d55e00')
  d.text((670,520),'安装偏移：局部 +Z 100 mm（假设）',font=body,fill='#26374a');d.text((670,552),'夹爪形状为示意；未标定、无接触与动力学',font=small,fill='#744b21')
  d.text((20,598),f'回放时间 {(clock-start)/1e9:05.2f} s',font=body,fill='#26374a');d.text((20,635),'实景与位姿按主机接收时间近似对齐，延迟未标定',font=small,fill='#744b21');d.text((20,667),'虚拟投影视角未与实景相机对齐；动作方向不可直接比较',font=small,fill='#744b21')
  enc.stdin.write(canvas.tobytes())
  if k==n//2:canvas.save(O/'virtual_gripper_preview.png')
finally:
 dec.terminate();dec.wait();enc.stdin.close();code=enc.wait()
if code:raise RuntimeError('video encoder failed')
(O/'virtual_gripper_metadata.json').write_text(json.dumps({'source_pose':str(S/'pose/pose.csv'),'source_video':str(S/'scene.mp4'),'frames':n,'fps':15,'tool_offset_m_local':[0,0,.1],'model':'idealized schematic, no calibrated extrinsic, no jaw motion, collision or dynamics','sync':'host receipt approximate'},indent=2),encoding='utf-8')
print('created',out,'frames',n)
