The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Body Double Live: the double covers the whole outline, clothes and hair included
Adarsh063ff8c3821b
diff --git a/src/components/body-double/hmr.worker.ts b/src/components/body-double/hmr.worker.tsindex 380c6fc5..71021f81 100644--- a/src/components/body-double/hmr.worker.ts+++ b/src/components/body-double/hmr.worker.ts@@ -4,6 +4,7 @@* so the page keeps drawing the camera at its own frame rate. Nothing leaves the browser.*/import { createHmr, type DrawBody, type Hmr, toDrawBody } from "@/lib/body-double/hmr";+import { createOutlineFinder, type Outline, type OutlineFinder, outlineBox } from "@/lib/body-double/outline";export type LiveRequest =| { type: "start" }@@ -13,13 +14,15 @@ export type LiveRequest =export type LiveReply =| { type: "progress"; share: number }| { type: "ready"; faces: Uint32Array; engine: Hmr["engine"] }- | { type: "body"; body: DrawBody; focal: number; width: number; height: number; at: number; ms: number }+ | { type: "body"; body: DrawBody; outline: Outline | null; focal: number; width: number; height: number; at: number; ms: number }| { type: "skip"; at: number }| { type: "error"; message: string };const post = (r: LiveReply, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(r, transfer);let hmr: Hmr | null = null;+/** The full outline (MediaPipe person segmenter); Live goes on with the body alone if it can't load. */+let outlines: OutlineFinder | null = null;let starting: Promise<void> | null = null;self.onmessage = async (e: MessageEvent<LiveRequest>) => {@@ -30,6 +33,10 @@ self.onmessage = async (e: MessageEvent<LiveRequest>) => {hmr = h;// A copy: the worker keeps its own faces for the normals.post({ type: "ready", faces: h.faces.slice(), engine: h.engine });+ // The outline loads after the body (one GPU set-up at a time); frames until then carry no outline.+ createOutlineFinder()+ .then((o) => (outlines = o))+ .catch(() => (outlines = null));}).catch((err: unknown) => {starting = null;@@ -48,9 +55,18 @@ self.onmessage = async (e: MessageEvent<LiveRequest>) => {}const t0 = performance.now();try {- const res = await hmr.step(m.bitmap, m.width, m.height, m.at / 1000);+ // The outline first: it covers clothes and hair, and its box is where the body model looks this frame.+ let outline: Outline | null = null;+ try {+ outline = outlines ? await outlines.find(m.bitmap, m.width, m.height, m.at) : null;+ } catch {+ outline = null;+ }+ const res = await hmr.step(m.bitmap, m.width, m.height, m.at / 1000, outline && outlineBox(outline, m.width, m.height));const body = toDrawBody(res.verts, res.cam, hmr.faces);- post({ type: "body", body, focal: res.f, width: m.width, height: m.height, at: m.at, ms: performance.now() - t0 }, [body.positions.buffer, body.normals.buffer]);+ const transfer: Transferable[] = [body.positions.buffer, body.normals.buffer];+ if (outline) transfer.push(outline.data.buffer);+ post({ type: "body", body, outline, focal: res.f, width: m.width, height: m.height, at: m.at, ms: performance.now() - t0 }, transfer);} catch (err) {post({ type: "error", message: err instanceof Error ? err.message : "Live stopped" });} finally {diff --git a/src/components/body-double/live-view.tsx b/src/components/body-double/live-view.tsxindex e652f130..f0265441 100644--- a/src/components/body-double/live-view.tsx+++ b/src/components/body-double/live-view.tsx@@ -8,6 +8,7 @@ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironmentimport { toast } from "sonner";import { Button } from "@/components/ui/button";import { type DrawBody, N_VERTS } from "@/lib/body-double/hmr";+import type { Outline } from "@/lib/body-double/outline";import { BODY_DOUBLE_DEMOS } from "@/lib/catalog/body-double";import { usePlayInView } from "./use-play-in-view";import { cn } from "@/lib/utils";@@ -64,12 +65,75 @@ function lookMaterial(look: LiveLook, envMap: THREE.Texture): THREE.Material {return new THREE.MeshPhysicalMaterial({ color: 0xf3f0ff, metalness: 1, roughness: 0.07, envMap, envMapIntensity: 1.35, clearcoat: 1, clearcoatRoughness: 0.04 });}+const LOOK_INDEX: Record<LiveLook, number> = { chrome: 0, iris: 1, holo: 2, wire: 3 };++/**+ * The full outline as a full-screen layer under the 3D body: the person mask (clothes and hair included), softened into+ * a height field whose slope gives a surface, lit in the same look as the body.+ */+function outlineMaterial() {+ return new THREE.ShaderMaterial({+ glslVersion: THREE.GLSL3,+ transparent: true,+ depthTest: false,+ depthWrite: false,+ uniforms: { uMask: { value: null as THREE.Texture | null }, uTexel: { value: new THREE.Vector2(1 / 256, 1 / 192) }, uLook: { value: 0 }, uTime: { value: 0 } },+ vertexShader: `out vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`,+ fragmentShader: `+ uniform sampler2D uMask; uniform vec2 uTexel; uniform int uLook; uniform float uTime; in vec2 vUv; out vec4 outColor;+ float m(vec2 uv){ return texture(uMask, vec2(uv.x, 1.0 - uv.y)).r; }+ // A rounded surface over the whole outline: the mask softened at three sizes by its mip levels (edge, limb, body),+ // so the slope turns across each limb and the middle stays full.+ float h(vec2 uv){+ vec2 t = vec2(uv.x, 1.0 - uv.y);+ return 0.3 * textureLod(uMask, t, 1.0).r + 0.35 * textureLod(uMask, t, 2.5).r + 0.35 * textureLod(uMask, t, 4.0).r;+ }+ void main(){+ float a = smoothstep(0.35, 0.65, m(vUv));+ if (a < 0.01) discard;+ vec2 d = uTexel * 3.0;+ float dx = h(vUv + vec2(d.x, 0.0)) - h(vUv - vec2(d.x, 0.0));+ float dy = h(vUv + vec2(0.0, d.y)) - h(vUv - vec2(0.0, d.y));+ vec3 n = normalize(vec3(-dx * 1.5, dy * 1.5, 0.5));+ vec3 col;+ if (uLook == 2) {+ float fres = pow(1.0 - n.z, 1.5);+ vec3 c = mix(vec3(.72,.55,1.), vec3(.35,.95,1.), .5 + .5*sin(vUv.y*6.0 + uTime*.8));+ float scan = .75 + .25*sin(vUv.y*900.0 - uTime*6.0);+ // Opaque, so nothing of the person shows through; brighter toward the outline.+ col = c * (.42 + 1.2*fres) * scan;+ } else if (uLook == 3) {+ float g = max(step(0.93, fract(vUv.x*96.0)), step(0.93, fract(vUv.y*72.0)));+ float edge = a - smoothstep(0.55, 0.8, m(vUv));+ // A pale mannequin drawn with a grid: it covers the person, the lines show its shape.+ col = mix(vec3(0.95,0.94,0.98), vec3(0.55,0.5,0.85), max(g * 0.8, edge));+ } else {+ vec3 r = vec3(n.x, n.y, n.z);+ float sky = smoothstep(-0.6, 0.8, r.y);+ vec3 base = mix(vec3(0.42,0.42,0.47), vec3(0.98,0.97,1.0), sky);+ base += 0.55 * exp(-pow((r.y - 0.08) * 6.0, 2.0)) * vec3(0.9,0.9,1.0);+ base *= 0.75 + 0.25 * smoothstep(-0.8, 0.8, r.x);+ float fres = pow(1.0 - n.z, 2.0);+ float spec = pow(max(dot(n, normalize(vec3(-0.45, 0.6, 0.7))), 0.0), 28.0);+ col = base * (0.7 + 0.5 * fres) + spec * 0.85;+ if (uLook == 1) {+ vec3 rainbow = 0.5 + 0.5*cos(6.2832*(vec3(0.0,0.33,0.67) + dot(n.xy, vec2(0.8,0.5))*1.2 + 0.1));+ col = mix(col, col*rainbow*1.35, 0.55);+ }+ }+ outColor = vec4(col, a);+ }`,+ });+}+type Scenes = {/** The body whose normals the geometry holds. */shown?: unknown;+ /** Whether the full outline shows under the body. */+ outlineOn: boolean;geometry: THREE.BufferGeometry;positions: Float32Array;- overlay: { r: THREE.WebGLRenderer; scene: THREE.Scene; cam: THREE.PerspectiveCamera; mesh: THREE.Mesh; env: THREE.Texture };+ overlay: { r: THREE.WebGLRenderer; scene: THREE.Scene; cam: THREE.PerspectiveCamera; mesh: THREE.Mesh; env: THREE.Texture; outline: THREE.Mesh<THREE.PlaneGeometry, THREE.ShaderMaterial> };orbit: { r: THREE.WebGLRenderer; scene: THREE.Scene; cam: THREE.PerspectiveCamera; mesh: THREE.Mesh; env: THREE.Texture; body: THREE.Group; floor: THREE.Object3D[]; controls: OrbitControls };dispose(): void;};@@ -93,7 +157,13 @@ function makeScenes(overlayCanvas: HTMLCanvasElement, orbitCanvas: HTMLCanvasEleconst oCam = new THREE.PerspectiveCamera(50, 4 / 3, 0.05, 100);const oMesh = new THREE.Mesh(geometry, lookMaterial(look, oEnv));oMesh.visible = false;+ oMesh.renderOrder = 1;oScene.add(oMesh);+ const outline = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), outlineMaterial());+ outline.frustumCulled = false;+ outline.visible = false;+ outline.renderOrder = 0;+ oScene.add(outline);const key = new THREE.DirectionalLight(0xffffff, 1.6);key.position.set(-1, 2, 1);oScene.add(key);@@ -122,14 +192,18 @@ function makeScenes(overlayCanvas: HTMLCanvasElement, orbitCanvas: HTMLCanvasElerScene.add(key2);return {+ outlineOn: true,geometry,positions,- overlay: { r: or, scene: oScene, cam: oCam, mesh: oMesh, env: oEnv },+ overlay: { r: or, scene: oScene, cam: oCam, mesh: oMesh, env: oEnv, outline },orbit: { r: rr, scene: rScene, cam: rCam, mesh: rMesh, env: rEnv, body, floor: [disc, ring], controls },dispose() {controls.dispose();geometry.dispose();for (const m of [oMesh, rMesh]) (m.material as THREE.Material).dispose();+ outline.geometry.dispose();+ outline.material.uniforms.uMask.value?.dispose();+ outline.material.dispose();oEnv.dispose();rEnv.dispose();or.dispose();@@ -139,7 +213,7 @@ function makeScenes(overlayCanvas: HTMLCanvasElement, orbitCanvas: HTMLCanvasEle}/** One body from the worker, with the moment its camera frame was taken. */-type Found = { body: DrawBody; focal: number; width: number; height: number; at: number };+type Found = { body: DrawBody; outline: Outline | null; focal: number; width: number; height: number; at: number };/*** The newest body pushed forward to now along its own motion (from the body before it), so it stays on the person@@ -147,8 +221,10 @@ type Found = { body: DrawBody; focal: number; width: number; height: number; at:*/function drawBody(s: Scenes, last: Found, prev: Found | null, now: number) {const p = s.positions, a = last.body.positions;+ // A small nudge only (at most 80 ms ahead), and none across a jump (a seek, a lost frame), so the body stays with+ // its outline, which comes from the same frame.const step = prev ? last.at - prev.at : 0;- const k = prev && step > 0 ? 0.85 * Math.min(1.5, Math.max(0, (now - last.at) / step)) : 0;+ const k = prev && step > 0 && step < 200 ? 0.7 * Math.min(1, Math.min(now - last.at, 80) / step) : 0;if (k > 0 && prev) {const b = prev.body.positions;for (let i = 0; i < p.length; i++) p[i] = a[i] + (a[i] - b[i]) * k;@@ -161,7 +237,26 @@ function drawBody(s: Scenes, last: Found, prev: Found | null, now: number) {(n.array as Float32Array).set(last.body.normals);n.needsUpdate = true;s.geometry.computeBoundingSphere();+ const o = last.outline, u = s.overlay.outline.material.uniforms;+ if (o) {+ const old = u.uMask.value as THREE.DataTexture | null;+ if (old && old.image.width === o.width && old.image.height === o.height) {+ (old.image.data as Uint8Array).set(o.data);+ old.needsUpdate = true;+ } else {+ old?.dispose();+ const t = new THREE.DataTexture(o.data, o.width, o.height, THREE.RedFormat, THREE.UnsignedByteType);+ t.magFilter = THREE.LinearFilter;+ t.minFilter = THREE.LinearMipmapLinearFilter;+ t.generateMipmaps = true;+ t.needsUpdate = true;+ u.uMask.value = t;+ u.uTexel.value.set(1 / o.width, 1 / o.height);+ }+ }+ s.overlay.outline.visible = s.outlineOn && !!u.uMask.value;}+ s.overlay.outline.material.uniforms.uTime.value = now / 1000;s.overlay.cam.fov = (2 * Math.atan(last.height / (2 * last.focal)) * 180) / Math.PI;s.overlay.cam.aspect = last.width / last.height;s.overlay.cam.updateProjectionMatrix();@@ -205,6 +300,7 @@ export function LiveView() {const rec = useRef<{ recorder: MediaRecorder; canvas: HTMLCanvasElement; chunks: Blob[] } | null>(null);const [source, setSource] = useState<Source | null>(null);const [look, setLook] = useState<LiveLook>("chrome");+ const [outlineOn, setOutlineOn] = useState(true);const [mirror, setMirror] = useState(true);const [status, setStatus] = useState<{ kind: "idle" | "loading" | "live" | "error"; text?: string; share?: number }>({ kind: "idle" });const [stats, setStats] = useState<{ fps: number; ms: number; engine: string } | null>(null);@@ -250,8 +346,16 @@ export function LiveView() {(m.material as THREE.Material).dispose();m.material = lookMaterial(look, env);}+ s.overlay.outline.material.uniforms.uLook.value = LOOK_INDEX[look];}, [look]);+ useEffect(() => {+ const s = scenes.current;+ if (!s) return;+ s.outlineOn = outlineOn;+ s.overlay.outline.visible = outlineOn && !!s.overlay.outline.material.uniforms.uMask.value;+ }, [outlineOn]);+const size = useCallback((W: number, H: number) => {const s = scenes.current, stage = stageRef.current;if (!s || !stage) return;@@ -310,7 +414,7 @@ export function LiveView() {loopRef.current();} else if (m.type === "body") {r.prev = r.last;- r.last = { body: m.body, focal: m.focal, width: m.width, height: m.height, at: m.at };+ r.last = { body: m.body, outline: m.outline, focal: m.focal, width: m.width, height: m.height, at: m.at };r.busy = false;r.fps.push(performance.now());while (r.fps.length > 30) r.fps.shift();@@ -478,6 +582,9 @@ export function LiveView() {<Button variant={recording ? "destructive" : "outline"} size="sm" className="rounded-full" onClick={toggleRecord}>{recording ? <Square className="size-3.5" /> : <Circle className="size-3.5" />} {recording ? "Stop and save" : "Record"}</Button>+ <Button variant={outlineOn ? "secondary" : "outline"} size="sm" className="rounded-full" aria-pressed={outlineOn} onClick={() => setOutlineOn((o) => !o)}>+ Full outline+ </Button><Button variant="outline" size="sm" className="rounded-full" onClick={() => worker.current?.postMessage({ type: "reset" } satisfies LiveRequest)}><RefreshCw className="size-3.5" /> Find me again</Button>@@ -492,7 +599,7 @@ export function LiveView() {)}</div>)}- <p className="text-[12px] text-muted-foreground">One person at a time, best in full view. For everyone in a shot, or a file to animate with, use Photo or Clip.</p>+ <p className="text-[12px] text-muted-foreground">One person at a time, best in full view. Full outline covers clothes and hair too. For everyone in a shot, or a file to animate with, use Photo or Clip.</p></div></div></div>diff --git a/src/lib/body-double/hmr.ts b/src/lib/body-double/hmr.tsindex 1c5bdc35..fc1cebd7 100644--- a/src/lib/body-double/hmr.ts+++ b/src/lib/body-double/hmr.ts@@ -169,7 +169,13 @@ export function toDrawBody(verts: Float32Array, cam: Float32Array, faces: Uint32}return { positions, normals, centre: [sx / N_VERTS, sy / N_VERTS, sz / N_VERTS], floor: minY };}-export type Hmr = { step(source: CanvasImageSource, W: number, H: number, t: number): Promise<HmrFrame>; resetTrack(): void; faces: Uint32Array; engine: "WebGPU" | "WebAssembly" };+export type Hmr = {+ /** One frame's body; `person` (a tight box x1, y1, x2, y2 in its pixels) replaces the box tracked from the last frame. */+ step(source: CanvasImageSource, W: number, H: number, t: number, person?: number[] | null): Promise<HmrFrame>;+ resetTrack(): void;+ faces: Uint32Array;+ engine: "WebGPU" | "WebAssembly";+};export const hasWebGpu = () => typeof navigator !== "undefined" && "gpu" in navigator;@@ -219,8 +225,9 @@ export async function createHmr(onProgress?: (share: number) => void): Promise<HsmoothCam.reset();};- async function step(source: CanvasImageSource, W: number, H: number, t: number): Promise<HmrFrame> {+ async function step(source: CanvasImageSource, W: number, H: number, t: number, person?: number[] | null): Promise<HmrFrame> {const f = 1.05 * Math.hypot(W, H);+ if (person) box = person;if (!box) {const s = Math.min(W, H) / EXPAND;box = [W / 2 - s / 2, H / 2 - s / 2, W / 2 + s / 2, H / 2 + s / 2];diff --git a/src/lib/body-double/outline.ts b/src/lib/body-double/outline.tsnew file mode 100644index 00000000..3fd856ef--- /dev/null+++ b/src/lib/body-double/outline.ts@@ -0,0 +1,93 @@+/**+ * Body Double Live's full outline: each person's whole silhouette, clothes and hair included, from Google's MediaPipe+ * person segmenter (Apache-2.0), so the double covers what the 3D body alone doesn't (a coat, wide trousers, long hair).+ * The task library loads from its pinned CDN build when Live starts, and runs on the GPU (WebGL) where it can.+ * Worker-safe: no DOM.+ */++const TASKS_VERSION = "0.10.21";+const TASKS_BASE = `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${TASKS_VERSION}`;+/** Background, hair, body skin, face skin, clothes, other: a person is everything but the background. */+const MODEL = "https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/1/selfie_multiclass_256x256.tflite";+/** The mask's width; its height keeps the frame's shape. */+export const OUTLINE_WIDTH = 256;++export type Outline = { data: Uint8Array; width: number; height: number };++/**+ * The person's tight box in a frame W x H wide, from the outline (the pixels over half sure), or null when there is+ * barely anyone: Live's body crop follows it, so a fast move or a new person never loses the body.+ */+export function outlineBox(o: Outline, W: number, H: number): number[] | null {+ let x1 = o.width, y1 = o.height, x2 = -1, y2 = -1, n = 0;+ for (let y = 0; y < o.height; y++)+ for (let x = 0; x < o.width; x++)+ if (o.data[y * o.width + x] > 128) {+ n++;+ if (x < x1) x1 = x;+ if (x > x2) x2 = x;+ if (y < y1) y1 = y;+ if (y > y2) y2 = y;+ }+ if (n < o.width * o.height * 0.01) return null;+ const sx = W / o.width, sy = H / o.height;+ return [x1 * sx, y1 * sy, (x2 + 1) * sx, (y2 + 1) * sy];+}++// The slice of the task library this file uses.+type MpMask = { getAsFloat32Array(): Float32Array; close(): void };+type Segmenter = {+ segmentForVideo(image: ImageBitmap, timestamp: number): { confidenceMasks?: MpMask[]; close(): void };+ close(): void;+};+type Tasks = {+ FilesetResolver: { forVisionTasks(base: string): Promise<unknown> };+ ImageSegmenter: { createFromOptions(fileset: unknown, options: Record<string, unknown>): Promise<Segmenter> };+};++export type OutlineFinder = { find(frame: ImageBitmap, width: number, height: number, at: number): Promise<Outline | null>; close(): void };++export async function createOutlineFinder(): Promise<OutlineFinder> {+ const tasks = (await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${TASKS_BASE}/vision_bundle.mjs`)) as Tasks;+ const fileset = await tasks.FilesetResolver.forVisionTasks(`${TASKS_BASE}/wasm`);+ const make = (delegate: "GPU" | "CPU") =>+ tasks.ImageSegmenter.createFromOptions(fileset, {+ baseOptions: { modelAssetPath: MODEL, delegate },+ runningMode: "VIDEO",+ outputConfidenceMasks: true,+ outputCategoryMask: false,+ ...(delegate === "GPU" && typeof OffscreenCanvas !== "undefined" && { canvas: new OffscreenCanvas(1, 1) }),+ });+ let seg: Segmenter;+ try {+ seg = await make("GPU");+ } catch {+ seg = await make("CPU");+ }+ let last = -1;+ return {+ async find(frame, width, height, at) {+ const h = Math.max(2, Math.round((OUTLINE_WIDTH * height) / width));+ const small = await createImageBitmap(frame, { resizeWidth: OUTLINE_WIDTH, resizeHeight: h, resizeQuality: "medium" });+ try {+ // The task wants timestamps that only go up.+ const t = Math.max(last + 1, Math.round(at));+ last = t;+ const res = seg.segmentForVideo(small, t);+ const bg = res.confidenceMasks?.[0];+ if (!bg) {+ res.close();+ return null;+ }+ const f = bg.getAsFloat32Array();+ const data = new Uint8Array(f.length);+ for (let i = 0; i < f.length; i++) data[i] = Math.round((1 - f[i]) * 255);+ res.close();+ return { data, width: OUTLINE_WIDTH, height: h };+ } finally {+ small.close();+ }+ },+ close: () => seg.close(),+ };+}