Skip to content

Open source CapCut alternative.

TypeScript

feat(site): pen mask drawn on the stage [rebuild]

David Le07b6b6f59164
diff --git a/site/packages/effects-kit/src/mask.test.ts b/site/packages/effects-kit/src/mask.test.ts
index 028f895b..e6a77ffe 100644
--- a/site/packages/effects-kit/src/mask.test.ts
+++ b/site/packages/effects-kit/src/mask.test.ts
@@ -6,6 +6,9 @@ import {
isMaskAnimated,
maskFrameAt,
maskKeyAt,
+ maskOutlinePathD,
+ maskSizeAxes,
+ penClosed,
restingMaskFrame,
type Mask,
type MaskKey,
@@ -92,7 +95,9 @@ describe("mask shapes", () => {
await import("./mask");
expect(MASK_SHAPE_KINDS).toEqual(MASK_KINDS.filter((k) => k !== "subject"));
for (const kind of MASK_SHAPE_KINDS) {
- const d = maskOutlinePathD({ kind }, 200, 100, 1000);
+ // A pen's outline is whatever was drawn; the others carry their own.
+ const points = kind === "pen" ? [{ x: -0.5, y: -0.5 }, { x: 0.5, y: -0.5 }, { x: 0, y: 0.5 }] : undefined;
+ const d = maskOutlinePathD({ kind, points }, 200, 100, 1000);
expect(d.startsWith("M")).toBe(true);
if (kind !== "linear" && kind !== "mirror") expect(d.endsWith("Z")).toBe(true);
}
@@ -116,3 +121,29 @@ describe("mask shapes", () => {
expect(maskOutlinePathD({ kind: "square" }, 200, 100, 1000)).toBe("M-100 -100 h200 v200 h-200 Z");
});
});
+
+describe("pen masks", () => {
+ const tri = [
+ { x: -0.5, y: -0.5 },
+ { x: 0.5, y: -0.5 },
+ { x: 0, y: 0.5 },
+ ];
+
+ test("a pen box starts as the whole frame, so points are frame fractions", () => {
+ expect(restingMaskFrame({ kind: "pen" })).toEqual({ x: 0, y: 0, w: 1, h: 1, rotation: 0, feather: 0, radius: 0 });
+ expect(maskSizeAxes("pen")).toEqual(["w", "h"]);
+ });
+
+ test("the outline closes at three corners and not before", () => {
+ expect(penClosed({ kind: "pen" })).toBe(false);
+ expect(penClosed({ kind: "pen", points: tri.slice(0, 2) })).toBe(false);
+ expect(penClosed({ kind: "pen", points: tri })).toBe(true);
+ expect(maskOutlinePathD({ kind: "pen" }, 100, 100, 200)).toBe("");
+ });
+
+ test("the outline path scales the corners by the box and centers on the offset", () => {
+ expect(maskOutlinePathD({ kind: "pen", points: tri }, 200, 100, 300, 0, 10, 20)).toBe(
+ "M-90 -30 L110 -30 L10 70 Z"
+ );
+ });
+});
diff --git a/site/packages/effects-kit/src/mask.ts b/site/packages/effects-kit/src/mask.ts
index 4e9947ca..dfebe29d 100644
--- a/site/packages/effects-kit/src/mask.ts
+++ b/site/packages/effects-kit/src/mask.ts
@@ -1,7 +1,7 @@
/**
* Masks: per-layer coverage that trims a layer's pixels to a shape — a
- * rounded rect, an ellipse, a half-plane, a band, a heart, a star, a polygon
- * — or to the person in the shot. The mask travels with its layer: its center is an offset from the
+ * rounded rect, an ellipse, a half-plane, a band, a heart, a star, a polygon,
+ * a pen-drawn outline — or to the person in the shot. The mask travels with its layer: its center is an offset from the
* layer's anchor, so a keyframed or dragged layer carries its mask along in
* every renderer.
*
@@ -30,6 +30,7 @@ export type MaskKind =
| "triangle"
| "diamond"
| "hexagon"
+ | "pen"
| "subject";
/** Every mask kind with the name the UI shows for it, in picker order. The
@@ -45,6 +46,7 @@ export const MASK_SHAPES: { id: MaskKind; label: string }[] = [
{ id: "triangle", label: "Triangle" },
{ id: "diamond", label: "Diamond" },
{ id: "hexagon", label: "Hexagon" },
+ { id: "pen", label: "Pen" },
{ id: "subject", label: "Subject" },
];
@@ -73,6 +75,42 @@ export function maskPolyKind(kind: MaskKind): ShapeKind | null {
}
}
+/** One corner of a pen mask's outline, as an offset from the mask's center
+ * in fractions of its w × h box: (−0.5, −0.5) is the box's top-left corner.
+ * The box carries the outline, so the mask's position, size, rotation and
+ * keys move the drawing as one piece. */
+export interface MaskPoint {
+ x: number;
+ y: number;
+}
+
+/** The fewest corners a pen outline closes with. */
+export const PEN_MIN_POINTS = 3;
+
+/** Whether a pen mask has an outline to cut with. Short of that the mask is
+ * still being drawn and the whole picture shows. */
+export function penClosed(m: Mask): boolean {
+ return m.kind === "pen" && (m.points?.length ?? 0) >= PEN_MIN_POINTS;
+}
+
+/** Trace a pen outline into `sink`, its box w × h px centered on (dx, dy). */
+export function tracePen(
+ sink: { moveTo(x: number, y: number): void; lineTo(x: number, y: number): void; closePath(): void },
+ points: MaskPoint[],
+ w: number,
+ h: number,
+ dx = 0,
+ dy = 0
+): void {
+ points.forEach((p, i) => {
+ const x = dx + p.x * w;
+ const y = dy + p.y * h;
+ if (i === 0) sink.moveTo(x, y);
+ else sink.lineTo(x, y);
+ });
+ sink.closePath();
+}
+
/** Which size axes a kind has: a square one side, a mirror band one height,
* a linear edge none, every filled outline both. */
export function maskSizeAxes(kind: MaskKind): ("w" | "h")[] {
@@ -111,6 +149,23 @@ export function maskOutlinePathD(
const side = m.kind === "square" ? w : h;
const poly = maskPolyKind(m.kind);
if (poly) return shapePathD(poly, w, h, dx - w / 2, dy - h / 2);
+ if (m.kind === "pen") {
+ if (!penClosed(m)) return "";
+ const parts: string[] = [];
+ tracePen(
+ {
+ moveTo: (x, y) => parts.push(`M${n(x)} ${n(y)}`),
+ lineTo: (x, y) => parts.push(`L${n(x)} ${n(y)}`),
+ closePath: () => parts.push("Z"),
+ },
+ m.points!,
+ w,
+ h,
+ dx,
+ dy
+ );
+ return parts.join(" ");
+ }
if (m.kind === "rect" || m.kind === "square") {
const r = Math.min(radiusPx, w / 2, side / 2);
const x0 = dx - w / 2;
@@ -168,6 +223,9 @@ export interface Mask {
invert?: boolean;
/** Rect or square corner radius, design px; a key can carry its own. */
radius?: number;
+ /** A pen mask's corners, in order around the outline. Fewer than
+ * PEN_MIN_POINTS means the outline is still being drawn. */
+ points?: MaskPoint[];
/** Keyframed geometry, its own track beside the layer's pose keys. */
kf?: MaskKey[];
}
@@ -184,11 +242,13 @@ export interface MaskFrame {
}
export function restingMaskFrame(m: Mask): MaskFrame {
+ // A pen outline is drawn in frame space, so its box starts as the frame.
+ const size = m.kind === "pen" ? 1 : 0.5;
return {
x: m.x ?? 0,
y: m.y ?? 0,
- w: m.w ?? 0.5,
- h: m.h ?? 0.5,
+ w: m.w ?? size,
+ h: m.h ?? size,
rotation: m.rotation ?? 0,
feather: m.feather ?? 0,
radius: m.radius ?? 0,
@@ -308,6 +368,17 @@ export function paintMaskCoverage(
ctx.beginPath();
tracePolyShape(ctx, maskPolyKind(m.kind)!, w, h, -w / 2, -h / 2);
ctx.fill();
+ } else if (m.kind === "pen") {
+ // The drawn outline filled into the w×h box. While it is still being
+ // drawn the whole picture shows, so the user draws over what they see.
+ if (!penClosed(m)) {
+ ctx.fillRect(-big, -big, big * 2, big * 2);
+ } else {
+ if (feather > 0 && "filter" in ctx) ctx.filter = `blur(${feather / 2}px)`;
+ ctx.beginPath();
+ tracePen(ctx, m.points!, w, h);
+ ctx.fill();
+ }
} else if (m.kind === "linear") {
// Half-plane: at rotation 0 the top half stays. The gradient band spans
// the feather, centered on the edge line.
diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.ts
index 1299be0a..41b49c98 100644
--- a/site/src/cut/components/Inspector.tools.ts
+++ b/site/src/cut/components/Inspector.tools.ts
@@ -25,6 +25,7 @@ import {
MASK_FEATHER_MAX,
MASK_KINDS,
MASK_RADIUS_MAX,
+ PEN_MIN_POINTS,
} from "@donkeycut/effects-kit";
import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";
@@ -107,7 +108,7 @@ export const INSPECTOR_TOOLS = [
{
name: "set_mask",
description:
- "Mask an overlay element or a video clip — trim its picture to a shape or to the person in the shot. Kinds: rect (rounded box), square (rounded square, side = w of the frame width), circle (ellipse; w and h are frame fractions, so a perfect circle needs w × frame width = h × frame height — omitting h gives you that circle), linear (half-plane: at rotation 0 the top side stays), mirror (band across the item), heart / star / triangle / diamond / hexagon (the outline filled into the w × h box, point up), subject (the person matte: invert true sits the item behind the speaker; invert false keeps it only on the person — an element newly masked as subject defaults to behind, a clip to on-person). Position is the mask center's offset from the item's own center (a clip's region center), in frame fractions; w/h size it in frame fractions; feather softens the edge; invert keeps what the shape leaves out; radius rounds a rect or square's corners. Subject masks use only feather and invert. Pass kind \"none\" to remove the mask. `keys` animates the geometry over time — each key is the full geometry at a moment, moving linearly between keys; pass an empty list to clear the keys and keep the mask still.",
+ "Mask an overlay element or a video clip — trim its picture to a shape or to the person in the shot. Kinds: rect (rounded box), square (rounded square, side = w of the frame width), circle (ellipse; w and h are frame fractions, so a perfect circle needs w × frame width = h × frame height — omitting h gives you that circle), linear (half-plane: at rotation 0 the top side stays), mirror (band across the item), heart / star / triangle / diamond / hexagon (the outline filled into the w × h box, point up), pen (an outline you give as `points` — the shape for any region the fixed shapes miss: the gap between two hands, a doorway, a screen in the shot; its box defaults to the whole frame, w = h = 1, so a point is an offset from the item's center in frame fractions, (-0.5, -0.5) the frame's top-left corner; the box's position, size, rotation and keys then carry the whole drawing), subject (the person matte: invert true sits the item behind the speaker; invert false keeps it only on the person — an element newly masked as subject defaults to behind, a clip to on-person). Position is the mask center's offset from the item's own center (a clip's region center), in frame fractions; w/h size it in frame fractions; feather softens the edge; invert keeps what the shape leaves out; radius rounds a rect or square's corners. Subject masks use only feather and invert. Pass kind \"none\" to remove the mask. `keys` animates the geometry over time — each key is the full geometry at a moment, moving linearly between keys; pass an empty list to clear the keys and keep the mask still.",
inputSchema: obj({
id: str("Overlay element id or video clip id"),
kind: {
@@ -123,6 +124,11 @@ export const INSPECTOR_TOOLS = [
feather: num(`Edge softness, px at the 1080 design short side (0..${MASK_FEATHER_MAX})`),
invert: bool("Keep the pixels outside the shape"),
radius: num(`Rect or square corner radius, px at 1080 short side (0..${MASK_RADIUS_MAX})`),
+ points: {
+ type: "array",
+ description: `Pen only: the outline's corners in order around it, at least ${PEN_MIN_POINTS}, each an offset from the mask center in fractions of the mask box (with the pen's default w = h = 1: frame fractions from the item's center, -0.5..0.5 inside the frame); replaces the outline`,
+ items: obj({ x: num("Offset x, fraction of the mask box width"), y: num("Offset y, fraction of the mask box height") }, ["x", "y"]),
+ },
keys: {
type: "array",
description:
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index b39e7510..3e6c67f2 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -2,7 +2,7 @@
import { useQueryClient } from "@tanstack/react-query";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
-import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, Scissors, Smile, Sparkles, Trash2, Type, User, Volume2 } from "lucide-react";
+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PenTool, Scissors, Smile, Sparkles, Trash2, Type, User, Volume2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useSpeedCurveUi } from "@/cut/lib/speedCurveUi";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
@@ -75,6 +75,7 @@ import {
maskHasRadius,
maskOutlinePathD,
maskSizeAxes,
+ penClosed,
restingMaskFrame,
} from "@donkeycut/effects-kit";
import { clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";
@@ -3115,6 +3116,7 @@ function KeyRow({
* top half, a mirror its band; the person matte wears a figure. */
function MaskShapeIcon({ kind }: { kind: MaskKind }) {
if (kind === "subject") return <User className="size-[18px]" strokeWidth={1.75} />;
+ if (kind === "pen") return <PenTool className="size-[18px]" strokeWidth={1.75} />;
const d = maskOutlinePathD({ kind }, 15, kind === "square" ? 15 : 12, 12, 2.5);
return (
<svg viewBox="-10 -10 20 20" className="size-[18px]" fill="none" stroke="currentColor" strokeWidth={1.5}>
@@ -3546,6 +3548,14 @@ function MaskSection({ target }: { target: MaskTarget }) {
};
const sizeAxes = m ? maskSizeAxes(m.kind) : [];
const subject = m?.kind === "subject";
+ // A pen outline still being drawn has no geometry to edit yet.
+ const drawing = !!m && m.kind === "pen" && !penClosed(m);
+ // A pen mask starts over: the outline goes, and the box returns to the
+ // frame so the next drawing lands where the clicks fall.
+ const redraw = () => {
+ if (!m) return;
+ target.set({ kind: "pen", invert: m.invert, feather: m.feather });
+ };
// A circle at rest is round: w and h are fractions of different frame
// edges, so equal pixels means unequal fractions.
const roundCircle = (w: number) => {
@@ -3566,12 +3576,12 @@ function MaskSection({ target }: { target: MaskTarget }) {
return;
}
setLinked(null);
- target.set({ kind: m.kind, invert: m.invert, kf: m.kf, ...(subject ? {} : geom) });
+ target.set({ kind: m.kind, invert: m.invert, kf: m.kf, points: m.points, ...(subject ? {} : geom) });
};
return (
<Section
title="Mask"
- info="Trim the picture to a shape, or to the person in the shot (Subject). Drag the shape to move it, its grips to resize, the lollipop to rotate, the chevron under it to feather the edge, and the corner grip to round a box. Invert keeps what the shape leaves out — an inverted Subject mask sits the picture behind the speaker."
+ info="Trim the picture to a shape, to an outline you draw (Pen), or to the person in the shot (Subject). Drag the shape to move it, its grips to resize, the lollipop to rotate, the chevron under it to feather the edge, and the corner grip to round a box. Pen: click the picture to place corners and click the first one to close; drag a corner to move it, the small grip on an edge to add one, double-click a corner to remove it. Invert keeps what the shape leaves out — an inverted Subject mask sits the picture behind the speaker."
enabled={!!m}
onEnabledChange={(v) => target.set(v ? { kind: "rect" } : undefined)}
aside={
@@ -3580,9 +3590,10 @@ function MaskSection({ target }: { target: MaskTarget }) {
variant="ghost"
size="sm"
className="h-7 px-2 text-[12px] text-muted-foreground"
- onClick={reset}
+ onClick={m.kind === "pen" ? redraw : reset}
+ disabled={drawing}
>
- Reset
+ {m.kind === "pen" ? "Redraw" : "Reset"}
</Button>
) : undefined
}
@@ -3609,13 +3620,18 @@ function MaskSection({ target }: { target: MaskTarget }) {
// A fresh circle starts perfectly round: w and h are frame
// fractions, so equal pixels means unequal fractions. The
// size link and ⇧-drag on the stage keep it round after.
+ // Pen is drawn fresh over the frame, so its box starts as
+ // the frame; leaving it drops the outline.
+ if (kind === "pen") return redraw();
const patch =
kind === "circle" && !hasMaskKeys(m)
? roundCircle(m.w ?? 0.5)
: kind === "subject" && m.kind !== "subject" && target.subjectStartsBehind
? { invert: true }
: {};
- target.set({ ...m, ...patch, kind });
+ const rest = { ...m };
+ delete rest.points;
+ target.set({ ...rest, ...patch, kind });
}}
>
<MaskShapeIcon kind={s.id} />
@@ -3623,7 +3639,13 @@ function MaskSection({ target }: { target: MaskTarget }) {
</button>
))}
</div>
- {!subject && (
+ {drawing && (
+ <p className="px-1 py-1.5 text-[11.5px] leading-snug text-muted-foreground">
+ Click the picture to place corners. Click the first corner, double-click, or press
+ Enter to close the outline.
+ </p>
+ )}
+ {!subject && !drawing && (
<KeyRow
element={target.element}
now={now}
@@ -3634,7 +3656,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
onSeek={seek}
/>
)}
- {!subject && (
+ {!subject && !drawing && (
<Row label="Position">
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
@@ -3664,7 +3686,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
))}
</Row>
)}
- {sizeAxes.length > 0 && (
+ {sizeAxes.length > 0 && !drawing && (
<Row label="Size">
{sizeAxes.map((axis, i) => (
<span key={axis} className="flex items-center gap-1">
@@ -3706,7 +3728,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
))}
</Row>
)}
- {!subject && (
+ {!subject && !drawing && (
<Row label="Rotation">
<ValueSlider
label="Mask rotation"
@@ -3731,6 +3753,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
/>
</Row>
)}
+ {!drawing && (
<Row label="Feather">
<ValueSlider
label="Feather"
@@ -3753,6 +3776,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
}}
/>
</Row>
+ )}
{maskHasRadius(m.kind) && (
<Row label="Radius">
<ValueSlider
@@ -3777,13 +3801,15 @@ function MaskSection({ target }: { target: MaskTarget }) {
/>
</Row>
)}
- <Row label="Invert">
- <Switch
- checked={!!m.invert}
- onCheckedChange={(v) => target.set({ ...m, invert: v || undefined })}
- aria-label="Invert mask"
- />
- </Row>
+ {!drawing && (
+ <Row label="Invert">
+ <Switch
+ checked={!!m.invert}
+ onCheckedChange={(v) => target.set({ ...m, invert: v || undefined })}
+ aria-label="Invert mask"
+ />
+ </Row>
+ )}
</>
)}
</Section>
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index ed3851de..cf348bf9 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -1,7 +1,7 @@
"use client";
import { guideSnapLines } from "@/cut/lib/guides";
-import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";
+import { createContext, Fragment, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { createPortal } from "react-dom";
import { releaseAnimRest, useAnimPreview } from "@/cut/lib/animPreview";
import { startDrag } from "@/cut/lib/drag";
@@ -16,7 +16,7 @@ import {
subtitleLaneCount,
trackPos,
} from "@/cut/lib/subtitles";
-import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, MASK_FEATHER_MAX, MASK_RADIUS_MAX, maskFrameAt, maskHasRadius, maskOutlinePathD, maskSizeAxes, overlayWords, paintMaskCoverage, resolveShadow, shapeMetrics, shapePathD, textStretch, WORD_ACCENT_DEFAULT, wordDrawsAt, type LottieHandle, type Mask, type MaskKey, type OverlayFrameState, type WordDraw } from "@donkeycut/effects-kit";
+import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, MASK_FEATHER_MAX, MASK_RADIUS_MAX, maskFrameAt, maskHasRadius, maskOutlinePathD, maskSizeAxes, overlayWords, paintMaskCoverage, PEN_MIN_POINTS, penClosed, resolveShadow, shapeMetrics, shapePathD, textStretch, WORD_ACCENT_DEFAULT, wordDrawsAt, type LottieHandle, type Mask, type MaskKey, type MaskPoint, type OverlayFrameState, type WordDraw } from "@donkeycut/effects-kit";
import {
LINE_HEIGHT,
PLATE_PAD_X,
@@ -1392,6 +1392,13 @@ function useMaskCss(
* `rotation`/`poseScale`, then through the mask's own angle for the resize.
* With mask keys in play a drag writes the key at the playhead, the same
* contract as dragging a keyframed element.
+ *
+ * A pen mask adds its own two states. Unclosed, the stage becomes a drawing
+ * surface: a click places a corner, clicking the first corner (or a
+ * double-click, or Enter) closes the outline, Backspace takes the last corner
+ * back and Escape clears the draft. Closed, every corner wears a grip that
+ * drags it, a hollow grip on each edge adds a corner there, and a
+ * double-click on a corner removes it.
*/
export function MaskGizmoCore({
mask: m,
@@ -1401,6 +1408,7 @@ export function MaskGizmoCore({
rotation,
poseScale,
writeGeom,
+ writePoints,
begin,
}: {
mask: Mask;
@@ -1411,9 +1419,13 @@ export function MaskGizmoCore({
poseScale: number;
/** Keyed geometry: lands on the key at the playhead when keys exist. */
writeGeom: (patch: Partial<Omit<MaskKey, "t">>) => void;
+ /** A pen mask's corners, on the mask itself (corners are never keyed). */
+ writePoints: (points: MaskPoint[]) => void;
begin: () => void;
}) {
const f = maskFrameAt(m, tLocal);
+ const pen = m.kind === "pen";
+ const drawing = pen && !penClosed(m);
// Guide lines while a drag sits on a detent: `rot` is the locked quarter
// turn, `x`/`y` mark the mask centered on an axis, `w`/`h` a size locked at
// exactly full frame. Local space, so on an element they ride its transform
@@ -1432,6 +1444,11 @@ export function MaskGizmoCore({
/** The corner radius shown while its grip drags; null when idle. */
const [round, setRound] = useState<number | null>(null);
const interiorRef = useRef<HTMLDivElement>(null);
+ /** The pen corners placed so far, local px around the anchor, while the
+ * outline is open; the pointer's current spot trails the last one. */
+ const [draft, setDraft] = useState<{ x: number; y: number }[]>([]);
+ const [trail, setTrail] = useState<{ x: number; y: number } | null>(null);
+ const drawRef = useRef<SVGSVGElement>(null);
// Screen deltas → the box's local space (undo the element transform).
const toLocal = (dx: number, dy: number) => {
const r = (-rotation * Math.PI) / 180;
@@ -1443,6 +1460,95 @@ export function MaskGizmoCore({
};
const theta = (f.rotation * Math.PI) / 180;
const sizable = maskSizeAxes(m.kind).length > 0;
+ // A screen point in the gizmo's local px: the drawing surface's own matrix
+ // folds in every transform above it, the layer's pose included.
+ const localPoint = (clientX: number, clientY: number) => {
+ const ctm = drawRef.current?.getScreenCTM();
+ if (!ctm) return { x: 0, y: 0 };
+ const pt = new DOMPoint(clientX, clientY).matrixTransform(ctm.inverse());
+ return { x: pt.x, y: pt.y };
+ };
+ // Local px → a pen corner in the mask's box: back through the mask's
+ // center and angle, then in fractions of its size.
+ const toPoint = (lx: number, ly: number): MaskPoint => {
+ const ox = lx - f.x * stageWidth;
+ const oy = ly - f.y * stageHeight;
+ const mx = ox * Math.cos(theta) + oy * Math.sin(theta);
+ const my = -ox * Math.sin(theta) + oy * Math.cos(theta);
+ return {
+ x: +(mx / Math.max(1e-6, f.w * stageWidth)).toFixed(4),
+ y: +(my / Math.max(1e-6, f.h * stageHeight)).toFixed(4),
+ };
+ };
+ const closeDraft = (pts: { x: number; y: number }[]) => {
+ if (pts.length < PEN_MIN_POINTS) return;
+ begin();
+ writePoints(pts.map((p) => toPoint(p.x, p.y)));
+ setDraft([]);
+ setTrail(null);
+ };
+ // Two corners within a grip's reach of each other are one corner: a
+ // double-click's second press, or a click back on the first corner.
+ const near = (a: { x: number; y: number }, b: { x: number; y: number }) =>
+ Math.hypot(a.x - b.x, a.y - b.y) < 10 / (poseScale || 1);
+ const placeCorner = (e: React.PointerEvent) => {
+ if (e.button !== 0) return;
+ e.stopPropagation();
+ e.preventDefault();
+ const at = localPoint(e.clientX, e.clientY);
+ if (draft.length >= PEN_MIN_POINTS && near(at, draft[0]!)) return closeDraft(draft);
+ if (draft.length > 0 && near(at, draft[draft.length - 1]!)) return;
+ setDraft([...draft, at]);
+ };
+ // Keys while drawing: Enter closes, Backspace takes a corner back, Escape
+ // clears the draft. Captured on the window ahead of the editor's own
+ // shortcuts, so Escape never reaches the selection.
+ useEffect(() => {
+ if (!drawing) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Enter") closeDraft(draft);
+ else if (e.key === "Backspace") setDraft(draft.slice(0, -1));
+ else if (e.key === "Escape") setDraft([]);
+ else return;
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [drawing, draft]);
+ // A corner grip drags its corner; a hollow edge grip adds one where it
+ // sits and drags it from there. A double-click on a corner removes it.
+ const dragCorner = (e: React.PointerEvent, points: MaskPoint[], index: number) => {
+ e.stopPropagation();
+ begin();
+ const p0 = points[index]!;
+ startDrag(e, {
+ onMove: (dx, dy) => {
+ const l = toLocal(dx, dy);
+ const mx = l.x * Math.cos(theta) + l.y * Math.sin(theta);
+ const my = -l.x * Math.sin(theta) + l.y * Math.cos(theta);
+ const next = points.slice();
+ next[index] = {
+ x: +(p0.x + mx / Math.max(1e-6, f.w * stageWidth)).toFixed(4),
+ y: +(p0.y + my / Math.max(1e-6, f.h * stageHeight)).toFixed(4),
+ };
+ writePoints(next);
+ },
+ });
+ };
+ const addCorner = (e: React.PointerEvent, points: MaskPoint[], after: number) => {
+ const a = points[after]!;
+ const b = points[(after + 1) % points.length]!;
+ const next = points.slice();
+ next.splice(after + 1, 0, { x: +((a.x + b.x) / 2).toFixed(4), y: +((a.y + b.y) / 2).toFixed(4) });
+ dragCorner(e, next, after + 1);
+ };
+ const removeCorner = (points: MaskPoint[], index: number) => {
+ if (points.length <= PEN_MIN_POINTS) return;
+ begin();
+ writePoints(points.filter((_, i) => i !== index));
+ };
// The outline traces the mask's hard edge in local px; a square's side is
// `w` of the frame width on both axes (the painter's rule), and
// linear/mirror edges run wider than any frame so they always cross it.
@@ -1453,8 +1559,9 @@ export function MaskGizmoCore({
const span = stageWidth + stageHeight;
// Which grips the kind can honor: a square's axes move together, a mirror
// band only opens and closes, and a linear edge has no size at all.
- const maskHandles: ResizeHandle[] =
- m.kind === "square"
+ const maskHandles: ResizeHandle[] = drawing
+ ? []
+ : m.kind === "square"
? CORNER_HANDLES
: m.kind === "mirror"
? ["n", "s"]
@@ -1643,6 +1750,64 @@ export function MaskGizmoCore({
// the outline; linear/mirror get a grabbable strip along their edge line.
const grabW = m.kind === "linear" || m.kind === "mirror" ? span * 2 : w;
const grabH = m.kind === "linear" ? 28 : m.kind === "mirror" ? Math.max(h, 28) : h;
+ const points = pen && !drawing ? m.points! : null;
+ const grip = {
+ borderColor: "#ff9f0a",
+ boxShadow: "0 1px 4px rgba(0,0,0,0.4)",
+ };
+ if (drawing) {
+ const outline = draft.map((p) => `${p.x},${p.y}`).join(" ");
+ return (
+ <svg
+ ref={drawRef}
+ className="absolute overflow-visible"
+ width={1}
+ height={1}
+ style={{ left: "50%", top: "50%", cursor: "crosshair" }}
+ onPointerDown={placeCorner}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ closeDraft(draft);
+ }}
+ onPointerMove={(e) => setTrail(localPoint(e.clientX, e.clientY))}
+ onPointerLeave={() => setTrail(null)}
+ >
+ <rect x={-span} y={-span} width={span * 2} height={span * 2} fill="transparent" style={{ pointerEvents: "all" }} />
+ {draft.length > 0 && (
+ <>
+ <polyline points={outline} {...edge} />
+ {trail && (
+ <line
+ x1={draft[draft.length - 1]!.x}
+ y1={draft[draft.length - 1]!.y}
+ x2={trail.x}
+ y2={trail.y}
+ stroke="#ff9f0a"
+ strokeOpacity={0.6}
+ strokeWidth={1.5}
+ strokeDasharray="6 4"
+ vectorEffect="non-scaling-stroke"
+ className="pointer-events-none"
+ />
+ )}
+ {draft.map((p, i) => (
+ <circle
+ key={i}
+ cx={p.x}
+ cy={p.y}
+ r={i === 0 && draft.length >= PEN_MIN_POINTS ? 7 : 5}
+ fill="#ffffff"
+ stroke="#ff9f0a"
+ strokeWidth={2.5}
+ vectorEffect="non-scaling-stroke"
+ className="pointer-events-none"
+ />
+ ))}
+ </>
+ )}
+ </svg>
+ );
+ }
return (
<>
<div
@@ -1692,6 +1857,35 @@ export function MaskGizmoCore({
transform: `rotate(${f.rotation}deg)`,
}}
>
+ {points &&
+ points.map((p, i) => {
+ const q = points[(i + 1) % points.length]!;
+ return (
+ <Fragment key={i}>
+ <span
+ title="Drag to move the corner; double-click to remove it"
+ onPointerDown={(e) => dragCorner(e, points, i)}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ removeCorner(points, i);
+ }}
+ className="pointer-events-auto absolute block size-[11px] cursor-move rounded-full border-[2.5px] bg-white"
+ style={{ left: p.x * w, top: p.y * h, transform: "translate(-50%, -50%)", ...grip }}
+ />
+ <span
+ title="Drag to add a corner here"
+ onPointerDown={(e) => addCorner(e, points, i)}
+ className="pointer-events-auto absolute block size-[7px] cursor-copy rounded-full border-[1.5px] bg-white/70"
+ style={{
+ left: ((p.x + q.x) / 2) * w,
+ top: ((p.y + q.y) / 2) * h,
+ transform: "translate(-50%, -50%)",
+ ...grip,
+ }}
+ />
+ </Fragment>
+ );
+ })}
<div
className="absolute left-0"
style={{ top: bottom + featherPx / 2 + 22, transform: "translate(-50%, -50%)" }}
@@ -1831,6 +2025,10 @@ function MaskGizmo({
if (hasMaskKeys(cur)) return st().setOverlayMaskKey(o.id, tLocal, patch, { transient: true });
st().updateOverlayTransient(o.id, { mask: { ...cur, ...patch } });
};
+ const writePoints = (points: MaskPoint[]) => {
+ const cur = st().overlays.find((x) => x.id === o.id)?.mask;
+ if (cur) st().updateOverlayTransient(o.id, { mask: { ...cur, points } });
+ };
return (
<MaskGizmoCore
mask={o.mask!}
@@ -1840,6 +2038,7 @@ function MaskGizmo({
rotation={rotation}
poseScale={poseScale}
writeGeom={writeGeom}
+ writePoints={writePoints}
begin={() => st().pushHistory()}
/>
);
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index 0882b96f..526c4c29 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -21,7 +21,7 @@ import {
} from "@/cut/lib/posterCache";
import { resizePreviewSurface, setPreviewCanvas } from "@/cut/lib/previewCanvas";
import { CLIP_MAX_ZOOM, clipCovers, clipKeyed, clipPoseAt, clipZoom, contentRect, frameOf, isFullRect, rectOf, REGION_MAX_SCALE, type VideoClip } from "@/cut/lib/types";
-import { hasMaskKeys, type MaskKey } from "@donkeycut/effects-kit";
+import { hasMaskKeys, type MaskKey, type MaskPoint } from "@donkeycut/effects-kit";
import { cn } from "@/lib/utils";
import { MaskGizmoCore, OverlayChromeHost, OverlayLayer, StagePress } from "./OverlayLayer";
import { GuideHandles, GuideOverlay } from "./GuideOverlay";
@@ -1252,6 +1252,11 @@ function ClipMaskGizmo({ stage }: { stage: { w: number; h: number } }) {
if (hasMaskKeys(cur)) return st.setClipMaskKey(clip.id, tLocal, patch, { transient: true });
st.updateClipTransient(clip.id, { mask: { ...cur, ...patch } });
};
+ const writePoints = (points: MaskPoint[]) => {
+ const st = useEditor.getState();
+ const cur = st.clips.find((c) => c.id === clip.id)?.mask;
+ if (cur) st.updateClipTransient(clip.id, { mask: { ...cur, points } });
+ };
return (
<div
className="absolute"
@@ -1271,6 +1276,7 @@ function ClipMaskGizmo({ stage }: { stage: { w: number; h: number } }) {
rotation={pose?.rotation ?? 0}
poseScale={pose?.scale ?? 1}
writeGeom={writeGeom}
+ writePoints={writePoints}
begin={() => useEditor.getState().pushHistory()}
/>
</div>
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 909e7875..054bff3b 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -47,6 +47,8 @@ import {
MASK_KINDS,
MASK_RADIUS_MAX,
maskHasRadius,
+ PEN_MIN_POINTS,
+ penClosed,
type RemovalStroke,
type StrokeStyleId,
} from "@donkeycut/effects-kit";
@@ -655,6 +657,24 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
};
// A radius belongs to a box; a shape that has no corners to round drops it.
if (!maskHasRadius(mask.kind)) delete mask.radius;
+ // A pen outline is its corners; every other kind has no use for them.
+ if (mask.kind === "pen") {
+ if (Array.isArray(input.points)) {
+ const pts = (input.points as unknown[]).map((p) => {
+ const q = p as Record<string, unknown>;
+ if (!isNum(q?.x) || !isNum(q?.y))
+ throw new ToolError("Every pen point needs numeric x and y.");
+ return { x: clamp(q.x, -2, 2), y: clamp(q.y, -2, 2) };
+ });
+ if (pts.length < PEN_MIN_POINTS)
+ throw new ToolError(`A pen outline needs at least ${PEN_MIN_POINTS} points.`);
+ mask.points = pts;
+ }
+ if (!penClosed(mask))
+ throw new ToolError(`A pen mask needs \`points\`: at least ${PEN_MIN_POINTS} corners.`);
+ } else {
+ delete mask.points;
+ }
// An element newly masked by the person starts behind them — the common
// ask — unless the call named a direction; invert false shows it only on
// the person. Clips keep the plain direction (Subject keeps the person).
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 0d7a860c..979a3cce 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -207,7 +207,7 @@ Effects (add_effect): time-ranged treatments over the finished cut. Three famili
Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, stretch_x/stretch_y (glyph stretch multipliers, the side grips' axis-only resize), stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — ${GOOGLE_FONT_IDS.join(", ")} — and so do the user's own: a .ttf/.otf/.woff/.woff2 file dropped on the Library is offered in every project under a font id like "font:<id>". Editor_state lists the ones this account has under \`fonts\` — use an id from there instead of guessing at a family name, and when someone asks for a typeface that is not in the list, tell them the Library takes font files.
Animation (set_overlay_animation): every element takes preset In/Out ramps (${OVERLAY_ANIM_STYLE_IDS.join(", ")} — typewriter for titles only; the per-letter styles sweep a title character by character), a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration, and a Move that says what it does WHILE it holds. A title takes one more: Words (${WORD_EFFECT_IDS.join(", ")}), which plays the line word by word — an emphasis travelling along a line that is fully up, or a build assembling the line as it is spoken. Entrances 0.3–0.6s read well; one loop per scene, sparingly; a move on the lines that matter. All of them are slots on the element, applied internally; the keyframe track (set_overlay_keyframes) is the separate power tier for motion the names do not cover, and slots compose over it.
Keyframes (set_overlay_keyframes): for motion no preset covers — a path across the frame, a slow push in, a drift that holds first. A key is a whole pose (position, scale, rotation, opacity) at a time in seconds from the element's start; the pose moves linearly between keys and holds outside them, and presets still compose on top. Two or three keys carry almost everything; reach for a preset first and keyframes when the user describes a specific path or timing. In the UI the diamond in the inspector adds a key at the playhead, and dragging the element then records into it. set_clip_keyframes is the same track on a video clip (any track): pans, push-ins, picture-in-picture flights, spins, and fades on the footage itself.
-Masks (set_mask): trim any element or video clip to a shape — ${MASK_SHAPE_KINDS.join(", ")} — with feather, invert, rounded corners on a box, and its own keyframe track for reveals and wipes. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Groups: the user can group elements (select several, Group in the inspector) — selecting one selects all, and moves/resize/rotate/timing ride together.
+Masks (set_mask): trim any element or video clip to a shape — ${MASK_SHAPE_KINDS.join(", ")} — with feather, invert, rounded corners on a box, and its own keyframe track for reveals and wipes. The pen kind takes an outline as points, for any region the fixed shapes miss: the gap framed between two hands, a doorway, a screen — read the region's corners off a captured frame in frame fractions, and stack a masked copy of the shot (a filter, a title) so it shows through only there. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Groups: the user can group elements (select several, Group in the inspector) — selecting one selects all, and moves/resize/rotate/timing ride together.
Composite builds: these primitives compose. Stacked overlay video copies, masks and their keys, pose keyframes, staggered starts, and shapes construct effects beyond any preset list. Given a reference (a screenshot or clip of an effect the user wants), reverse-engineer it:
1. Read the reference as layers. For each visible piece, decide what it is: live footage, a cropped or repeated slice of the footage, a solid graphic, text, or empty background.
2. Map each layer to a primitive. A slice of the picture = a copy of the same asset on its own overlay track (add_overlay_video, layout full, matching trim so every copy's picture lines up with the base) trimmed by a mask whose x/y offsets place it — a full-frame copy under a mask shows the true part of the picture at that spot, so masked copies tile back into the whole image. Gap lines and borders come from sizing masks under their spacing (track 0 left empty plays black through the gaps) or from stroked shapes. Solid panels are shapes; words are titles.