VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 4)
9d57416 verified
Raw History Blame Contribute Delete
22.8 kB
export type SceneFocus={id?:string;label?:string;entity_ids:string[];span_s:number[]|null;regions_uv:[number,number][][]};
import {explanation} from './text.ts';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { Actor, ReviewEvent, ScriptReview, SegmentView, Track, UV } from './contract.ts';
import './situation-overlay.css';
import type { ReviewClock } from './clock.ts';
import { INITIAL_UNITS_PER_PIXEL, panBox, viewportScale, zoomBox } from './geometry.ts';
import { layoutRoomLabels } from './layout.ts';
import { bracket, intentAt, sample, screenAngle, stateAt } from './lookup.ts';
import { actorStyle, INTENT_LABELS, KIND_LABELS, shapePath, STATE_LABELS, STATUS_LABELS } from './visual.ts';
const TAIL_SECONDS = 15, TAIL_SLICES = 15;
const VIEW_SECTOR_LENGTH_M = 4; // Drawing length only, never a visibility claim.
export function sectorPath(hfov_rad: number, r: number): string {
const x = r * Math.cos(hfov_rad / 2), y = r * Math.sin(hfov_rad / 2);
return `M0,0 L${x},${-y} A${r},${r} 0 ${hfov_rad > Math.PI ? 1 : 0} 1 ${x},${y} Z`;
}
export function overlayEvents(review: ScriptReview | undefined): ReviewEvent[] {
if (!review) return [];
const unique = new Map<string, ReviewEvent>();
for (const event of [...review.planned, ...review.situations, ...(review.actual_arrangements ?? [])]) {
if (!unique.has(event.id)) unique.set(event.id, event);
}
return [...unique.values()].filter(event => event.regions_uv.length > 0 ||
(event.kind !== '前往/停留' && event.span_s !== null));
}
// 同一处的多条区域(如停留和看它的共视)标签往下错开一行,不叠在一起;中心相距 0.1 m 内算同一处
export function nextLabelRow(placed: UV[], [u, v]: UV): number {
const row = placed.filter(([a, b]) => Math.hypot(a - u, b - v) < 0.1).length;
placed.push([u, v]);
return row;
}
export function activeEventIds(events: ReviewEvent[], t: number): Set<string> {
return new Set(events.filter(event => event.span_s !== null && event.span_s[0] <= t && t <= event.span_s[1]).map(event => event.id));
}
// Signed-area centroid; also handles a repeated closing vertex. Degenerate regions use the vertex mean.
function regionCenter(points: UV[]): UV {
let area = 0, u = 0, v = 0;
points.forEach((p, i) => {
const q = points[(i + 1) % points.length], cross = p[0] * q[1] - q[0] * p[1];
area += cross; u += (p[0] + q[0]) * cross; v += (p[1] + q[1]) * cross;
});
return Math.abs(area) > 1e-12 ? [u / (3 * area), v / (3 * area)] :
[points.reduce((sum, p) => sum + p[0], 0) / points.length, points.reduce((sum, p) => sum + p[1], 0) / points.length];
}
// The narrowest template is the square (1.64 units across).
const MIN_MARKER_RADIUS_PX = 10 / 1.64;
const pathFromUV = (points: UV[], close = false) => points.map((p, i) => `${i ? 'L' : 'M'}${p[0]},${-p[1]}`).join(' ') + (close ? ' Z' : '');
function trackPath(track: Track, start: number, end: number): string {
const [lo] = bracket(track.t_s, start), [hi] = bracket(track.t_s, end);
const a = sample(track, start), b = sample(track, end);
const points: UV[] = [[a.u, a.v]];
for (let i = lo + 1; i <= hi; i++) points.push([track.u_m[i], track.v_m[i]]);
points.push([b.u, b.v]);
return pathFromUV(points);
}
function ActorLayer({actor, view, clock, visible, unitsPerPixel, onHover, onSelect, showLabel, layer, focus}: {
actor: Actor; view: SegmentView; clock: ReviewClock; visible: boolean; unitsPerPixel: number;
onHover: (id: string | null) => void; onSelect: (id: string) => void; showLabel: boolean; layer: 'traces' | 'markers';
focus?:SceneFocus|null;
}) {
const group = useRef<SVGGElement>(null), body = useRef<SVGGElement>(null), arrow = useRef<SVGGElement>(null);
const camera = useRef<SVGGElement>(null), target = useRef<SVGGElement>(null), connector = useRef<SVGLineElement>(null);
const marker = useRef<SVGGElement>(null), label = useRef<SVGTextElement>(null), tails = useRef<(SVGPathElement | null)[]>([]);
const symbol = useRef<SVGPathElement>(null);
const discards = useRef<(SVGGElement | null)[]>([]);
const track = view.tracks[actor.id], observer = view.observers[actor.id], style = actorStyle(actor);
const ownDiscards = useMemo(() => view.discards.filter(d => d.actor_id === actor.id), [view, actor.id]);
const fullPath = useMemo(() => pathFromUV(track.u_m.map((u, i) => [u, track.v_m[i]])), [track]);
useEffect(() => clock.subscribe(({time}) => {
if (!visible || !group.current) return;
const value = sample(track, time), radius = Math.max(actor.radius_m ?? 0, MIN_MARKER_RADIUS_PX * unitsPerPixel);
body.current?.setAttribute('transform', `translate(${value.u},${-value.v})`);
marker.current?.setAttribute('transform', `scale(${radius})`);
arrow.current?.setAttribute('display', value.yaw === null ? 'none' : '');
if(value.yaw !== null) arrow.current?.setAttribute('transform', `rotate(${screenAngle(value.yaw, view.frame)}) scale(${Math.max(.6, (actor.radius_m ?? 0) + .25)})`);
body.current?.setAttribute('data-u', String(value.u)); body.current?.setAttribute('data-v', String(value.v));
symbol.current?.setAttribute('stroke', actor.virtual ? '#263343' : 'white');
symbol.current?.setAttribute('stroke-width', '2');
if (label.current) {
label.current.setAttribute('y', String(observer ? -radius - 7 * unitsPerPixel : radius + 14 * unitsPerPixel));
label.current.setAttribute('font-size', String(11 * unitsPerPixel));
label.current.setAttribute('stroke-width', String(3 * unitsPerPixel));
}
camera.current?.setAttribute('display', value.cameraYaw === null && value.yaw === null ? 'none' : '');
camera.current?.setAttribute('transform', `translate(${(value.cameraU ?? value.u) - value.u},${-((value.cameraV ?? value.v) - value.v)}) rotate(${screenAngle(value.cameraYaw ?? value.yaw ?? 0, view.frame)})`);
if (camera.current) {
camera.current.dataset.u = String(value.cameraU ?? value.u); camera.current.dataset.v = String(value.cameraV ?? value.v);
camera.current.querySelector('circle')?.setAttribute('r', String(2.5 * unitsPerPixel));
}
const intent = intentAt(view.intents[actor.id], time), destination = intent?.target?.position_uv;
const showTarget = !!destination && ['go_to', 'station'].includes(intent!.kind);
target.current?.setAttribute('display', showTarget ? '' : 'none'); connector.current?.setAttribute('display', showTarget ? '' : 'none');
if (showTarget && destination) {
target.current?.setAttribute('transform', `translate(${destination[0]},${-destination[1]}) scale(${radius})`);
connector.current?.setAttribute('x1', String(value.u)); connector.current?.setAttribute('y1', String(-value.v));
connector.current?.setAttribute('x2', String(destination[0])); connector.current?.setAttribute('y2', String(-destination[1]));
}
for (let i = 0; i < TAIL_SLICES; i++) {
const end = Math.max(clock.start, time - (TAIL_SLICES - 1 - i) * TAIL_SECONDS / TAIL_SLICES);
const start = Math.max(clock.start, end - TAIL_SECONDS / TAIL_SLICES);
tails.current[i]?.setAttribute('d', end > start ? trackPath(track, start, end) : '');
}
ownDiscards.forEach((d, i) => {
const node = discards.current[i]; if (!node) return;
node.setAttribute('display', time >= d.time_s ? '' : 'none');
node.setAttribute('opacity', String(.22 + .65 * Math.max(0, 1 - (time - d.time_s) / 30)));
node.setAttribute('transform', `translate(${d.target_uv[0]},${-d.target_uv[1]}) scale(${7 * unitsPerPixel})`);
});
}), [clock, visible, track, view, actor, unitsPerPixel, ownDiscards, layer]);
const cameraElement = observer && <g ref={camera} className="camera-sector" data-camera-marker={actor.id}><path d={sectorPath(observer.hfov_rad, VIEW_SECTOR_LENGTH_M)} fill={style.color} fillOpacity={.16} stroke={style.color} strokeWidth={1} strokeDasharray={actor.virtual ? '3 3' : undefined} vectorEffect="non-scaling-stroke" /><line x2={VIEW_SECTOR_LENGTH_M} stroke={style.color} strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />{track.cam_u_m && <circle fill="#263343" stroke="white" strokeWidth={1} vectorEffect="non-scaling-stroke" />}</g>;
return <g ref={group} display={visible ? undefined : 'none'} data-actor-layer={layer === 'markers' ? actor.id : undefined}>
{layer === 'traces' && <>
<path className="full-track" d={fullPath} stroke={style.color} style={{opacity:focus ? .08 : undefined}} />
{focus?.span_s&&focus.entity_ids.includes(actor.id)&&<path data-focus-path={actor.id} d={trackPath(track,focus.span_s[0],focus.span_s[1])} stroke={style.color} fill="none" strokeWidth={3} vectorEffect="non-scaling-stroke"/>}
{Array.from({length: TAIL_SLICES}, (_, i) => <path key={i} ref={node => {tails.current[i] = node;}} className="tail" stroke={style.color} opacity={focus ? .04 : .08 + .67 * (i + 1) / TAIL_SLICES} />)}
<line ref={connector} className="intent-connector" stroke={style.color} />
<g ref={target} className="target-marker"><path d={shapePath(style.shape)} fill="white" stroke={style.color} vectorEffect="non-scaling-stroke" strokeWidth={2} /></g>
{ownDiscards.map((d, i) => <g key={i} ref={node => {discards.current[i] = node;}} className="discard-map" data-rejection-kind={d.event_kind} data-rejection-actor={actor.id} data-event-time={d.time_s}>
<path d={d.event_kind === 'proposal_failure' ? 'M0,-1 L1,0 L0,1 L-1,0 Z' : 'M-.7,-.7 L.7,.7 M-.7,.7 L.7,-.7'} fill="none" stroke={style.color} vectorEffect="non-scaling-stroke" strokeWidth={2} />
<title>{actor.id} · {d.event_kind === 'proposal_failure' ? '提案失败' : '丢弃'} · {d.time_s.toFixed(1)} 秒 · {explanation(d.reason)}</title>
</g>)}
</>}
{layer === 'markers' && <g ref={body} id={'actor-marker-' + actor.id} data-actor-marker={actor.id} onClick={() => onSelect(actor.id)} onPointerEnter={() => onHover(actor.id)} onPointerLeave={() => onHover(null)}>
{!track.cam_u_m && cameraElement}
<g ref={marker}><path ref={symbol} id={'actor-symbol-' + actor.id} d={shapePath(style.shape)} fill={style.color} stroke={actor.virtual ? '#263343' : 'white'} strokeWidth={2} strokeDasharray={actor.virtual ? '3 3' : undefined} vectorEffect="non-scaling-stroke" /></g>
<g ref={arrow} className="heading-arrow"><path id={'actor-heading-' + actor.id} d="M0,0 L1,0 M.7,-.18 L1,0 L.7,.18" fill="none" stroke={style.color} strokeWidth={2.5} vectorEffect="non-scaling-stroke" /></g>
{track.cam_u_m && cameraElement}
<text ref={label} textAnchor="middle" className="actor-label" data-label-actor={actor.id} display={showLabel ? undefined : 'none'}>{actor.id}</text>
</g>}
</g>;
}
export function Scene({view, clock, visible, onBasemapReady, focus}: {view: SegmentView; clock: ReviewClock; visible: Set<string>; onBasemapReady?: () => void;focus?:SceneFocus|null}) {
const panel = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null), tooltip = useRef<HTMLDivElement>(null);
const [[lowU, lowV], [highU, highV]] = view.basemap.bounds_uv;
const width = highU - lowU, height = highV - lowV;
const initialBox = useMemo(() => [lowU - width * .025, -highV - height * .025, width * 1.05, height * 1.05], [lowU, highV, width, height]);
const [box, setBox] = useState(initialBox), [unitsPerPixel, setUnitsPerPixel] = useState(INITIAL_UNITS_PER_PIXEL);
const [expanded, setExpanded] = useState(false);
const [mapHeight, setMapHeight] = useState(500);
const [hover, setHover] = useState<string | null>(null);
const [selected, setSelected] = useState<string | null>(null);
const [showSituations, setShowSituations] = useState(true);
const events = useMemo(() => overlayEvents(view.review), [view.review]);
const [activeIds, setActiveIds] = useState(() => activeEventIds(events, clock.snapshot().time));
useEffect(() => {
let previous: Set<string> | null = null;
return clock.subscribe(({time}) => {
const next = activeEventIds(events, time);
if (previous && previous.size === next.size && [...next].every(id => previous!.has(id))) return;
previous = next;
setActiveIds(next);
});
}, [events, clock]);
// A focused review event shares its region objects with review; question focuses have no regions.
const focusEvent = events.find(event => event.id === focus?.id || event.regions_uv === focus?.regions_uv);
const regionEvents: SceneFocus[] = [...events];
if (focus?.regions_uv.length && !focusEvent) regionEvents.push(focus);
const drag = useRef<{x: number; y: number; box: number[]} | null>(null);
useEffect(() => {
const node = svg.current; if (!node) return;
const update = () => {
if (!node.isConnected) return;
const rect = node.getBoundingClientRect();
setUnitsPerPixel(previous => viewportScale(box, rect, previous));
// Follow the map's aspect ratio, independent of screenshot/window height.
setMapHeight(Math.max(220, Math.min(720, rect.width * height / width * 1.05)));
};
const observer = new ResizeObserver(update); observer.observe(node); update();
window.addEventListener('resize', update);
return () => {observer.disconnect(); window.removeEventListener('resize', update);};
}, [box]);
useLayoutEffect(() => {
const node = svg.current; if (!node) return;
const polygons = Object.fromEntries(view.basemap.rooms.map(room => [room.id, room.polygon_uv]));
layoutRoomLabels(node, polygons);
let disposed = false;
document.fonts.ready.then(() => {if (!disposed) layoutRoomLabels(node, polygons);});
return () => {disposed = true;};
}, [box, unitsPerPixel, mapHeight, expanded, view]);
useEffect(() => {
const changed = () => setExpanded(document.fullscreenElement === panel.current);
document.addEventListener('fullscreenchange', changed);
return () => document.removeEventListener('fullscreenchange', changed);
}, []);
useEffect(() => {
const node = svg.current; if (!node) return;
// React delegates wheel with a passive listener. Use a scoped non-passive
// listener so zoom does not also scroll the document or log a warning.
const wheel = (event: WheelEvent) => {
event.preventDefault();
const matrix = node.getScreenCTM(); if (!matrix) return;
const inverse = matrix.inverse();
if (![inverse.a, inverse.b, inverse.c, inverse.d, inverse.e, inverse.f].every(Number.isFinite)) return;
const point = new DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
if (![point.x, point.y].every(Number.isFinite)) return;
zoom(event.deltaY > 0 ? 1.12 : .89, [point.x, point.y]);
};
node.addEventListener('wheel', wheel, {passive: false});
return () => node.removeEventListener('wheel', wheel);
}, [width]);
useEffect(() => clock.subscribe(({time}) => {
svg.current?.setAttribute('data-clock-time', String(time));
if (!tooltip.current || !hover) return;
const actor = view.actors.find(a => a.id === hover)!;
const value = sample(view.tracks[hover], time), state = stateAt(view.states[hover], time), intent = intentAt(view.intents[hover], time);
const destination = intent?.target?.position_uv?.map(n => n.toFixed(2)).join(', ') || intent?.target?.region_id || '无目标';
tooltip.current.textContent = [actor.id + ' · ' + (KIND_LABELS[actor.kind] || actor.kind),
`状态:${state ? STATE_LABELS[state.state] : '未知'}${state ? '\n依据:' + explanation(state.reason) : ''}${state?.forced === true ? '\n被迫:是(生成记录)' : ''}${state?.waiting_for.length ? '\n在等:' + state.waiting_for.join('、') : ''}`,
`意图:${intent ? `${INTENT_LABELS[intent.kind] || intent.kind} · ${destination} · ${STATUS_LABELS[intent.status]}` : '无正在执行的意图'}`,
`平移速率(显示段均值):${value.speed.toFixed(3)} m/s 已走:${value.distance.toFixed(2)} m`].join('\n');
}), [clock, hover, view]);
const occluders = useMemo(() => view.basemap.occluder_contours_uv.map(p => pathFromUV(p, true)).join(' '), [view]);
function zoom(factor: number, center?: UV) {
setBox(old => zoomBox(old, width, factor, center));
}
return <div ref={panel} className={'scene-panel ' + (expanded ? 'scene-expanded' : '')}>
<div className="scene-toolbar"><span>俯视 · +u 向右 / +v 向上 · 点主体可固定标签</span><div><button data-fullscreen onClick={() => {if (expanded) void document.exitFullscreen(); else void panel.current?.requestFullscreen();}}>{expanded ? '退出全屏' : '全屏地图'}</button><button onClick={() => zoom(.8)} aria-label="放大俯视图">+</button><button onClick={() => zoom(1.25)} aria-label="缩小俯视图">−</button><button onClick={() => {setBox(initialBox); setSelected(null);}}>复位</button></div></div>
<svg ref={svg} id="topdown" style={{height: mapHeight}} data-units-per-pixel={unitsPerPixel} viewBox={box.join(' ')} preserveAspectRatio="xMidYMin meet" role="img" aria-label="动态剧本俯视图"
onPointerDown={e => {if ((e.target as Element).closest('[data-actor-marker]')) return; drag.current = {x: e.clientX, y: e.clientY, box}; e.currentTarget.setPointerCapture(e.pointerId);}}
onPointerMove={e => {if (!drag.current) return; const {x, y, box: old} = drag.current; setBox(panBox(old, e.clientX - x, e.clientY - y, unitsPerPixel));}}
onPointerUp={() => {drag.current = null;}} onPointerCancel={() => {drag.current = null;}}>
<image onLoad={()=>{svg.current?.setAttribute("data-map-load","loaded");onBasemapReady?.();}} onError={()=>{svg.current?.setAttribute("data-map-load","failed");onBasemapReady?.();}} href={view.basemap.raster.url} x={lowU} y={-highV} width={width} height={height} preserveAspectRatio="none" />
{showSituations && <g className="situation-regions">{(labelRows => regionEvents.map((event, i) => {
const highlighted = event === focus || event === focusEvent || (event.id !== undefined && activeIds.has(event.id));
return event.regions_uv.filter(region => region.length > 0).map((region, j) => {
const [u, v] = regionCenter(region);
const row = highlighted ? nextLabelRow(labelRows, [u, v]) : 0;
return <g key={`${i}-${j}`} data-situation-region={event.id} data-active={highlighted}>
<path data-covisible-region d={pathFromUV(region, true)} className={'situation-region' + (highlighted ? ' is-active' : '')} />
{highlighted && <text x={u} y={-v + row * 14 * unitsPerPixel} textAnchor="middle" className="situation-label" fontSize={11 * unitsPerPixel} strokeWidth={3 * unitsPerPixel}>{event.label ?? '选中区域'}{event.span_s ? ` ${event.span_s[0]}–${event.span_s[1]} s` : ''}</text>}
</g>;
});
}))([] as UV[])}</g>}
<path d={occluders} className="occluders" fillRule="evenodd" />
{view.basemap.rooms.map(room => <g key={room.id}><path d={pathFromUV(room.polygon_uv, true)} className="room-outline" /><text data-room-label={room.id} style={{visibility: 'hidden'}} x={room.label_uv[0]} y={-room.label_uv[1]} textAnchor="middle" className="room-label" fontSize={11 * unitsPerPixel} strokeWidth={2 * unitsPerPixel}>{room.name}<title>{room.id} · 原始标注:{room.name}</title></text></g>)}
{view.basemap.doorways.map(d => <path key={d.id} d={pathFromUV(d.segment_uv)} className="doorway"><title>{d.id}</title></path>)}
{view.basemap.stop_points.map(p => <circle key={p.id} cx={p.position_uv[0]} cy={-p.position_uv[1]} r={1.7 * unitsPerPixel} className="stop-point"><title>{p.id}</title></circle>)}
{view.actors.map(actor => <ActorLayer key={'traces-' + actor.id} layer="traces" focus={focus} actor={actor} view={view} clock={clock} visible={visible.has(actor.id)} unitsPerPixel={unitsPerPixel} onHover={setHover} onSelect={setSelected} showLabel={hover === actor.id || selected === actor.id} />)}
{showSituations && <g className="situation-paths">{events.filter(event => activeIds.has(event.id) && event.span_s).flatMap(event =>
view.actors.filter(actor => !actor.kind.startsWith('observer') && visible.has(actor.id) && event.entity_ids.includes(actor.id)).map(actor =>
<path key={`${event.id}-${actor.id}`} data-situation-path={event.id} data-situation-actor={actor.id} d={trackPath(view.tracks[actor.id], event.span_s![0], event.span_s![1])} stroke={actorStyle(actor).color} fill="none" strokeWidth={4} vectorEffect="non-scaling-stroke" />))}</g>}
{view.actors.map(actor => <ActorLayer key={'markers-' + actor.id} layer="markers" focus={focus} actor={actor} view={view} clock={clock} visible={visible.has(actor.id)} unitsPerPixel={unitsPerPixel} onHover={setHover} onSelect={setSelected} showLabel={hover === actor.id || selected === actor.id} />)}
</svg>
<div ref={tooltip} className="actor-tooltip" role="tooltip" hidden={!hover} />
<details className="map-legend"><summary aria-label="俯视图图例">?</summary><div className="map-key">
<label className="situation-toggle"><input type="checkbox" checked={showSituations} onChange={event => setShowSituations(event.target.checked)} />显示情形</label>
{events.length === 0 && <span className="situation-empty">本段没有情形数据</span>}
<span data-map-symbol="position"><b className="key-position">●</b>实心:当前位置</span>
<span data-map-symbol="target"><b className="key-target">○┄</b>空心 / 虚线:目标</span>
<span data-map-symbol="discard"><b className="key-discard">×</b>丢弃目标(悬停原因)</span>
<span data-map-symbol="proposal-failure"><b>◇</b>提案失败(意图状态保留)</span>
<span data-map-symbol="tail"><i className="key-tail" />最近 15 秒彗尾</span>
<span data-map-symbol="track"><i className="key-track" />淡线:全段轨迹</span>
<span data-map-symbol="heading"><b>→</b>机身朝向</span>
<span data-map-symbol="virtual"><i className="key-virtual" />虚线轮廓:虚拟观察者</span>
<span data-map-symbol="room"><i className="key-room" />细灰线:房间边界</span>
<span data-map-symbol="nav"><i className="nav-key" />{view.review ? "静态高度带未占用(不代表可导航)" : "自由空间"}</span>
<span data-map-symbol="wall"><i className="wall-key" />1.5 m 高度遮挡</span>
<span data-map-symbol="door"><i className="door-key" />门口</span>
<span data-map-symbol="stop"><i className="key-stop" />停靠点</span>
{Object.keys(view.observers).length > 0 && <><span data-map-symbol="view-sector">扇形:水平视场示意(4 m,没按墙裁剪,不等于渲染可见区)</span><span>虚线:镜头方向</span></>}
</div></details>
</div>;
}