Skip to content

Code-first video & image, rendered natively on WebGPU.

fix: rendering and component bugs found on the component docs

okanasl465422b307ee
diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
index adcc57d2..c744cb23 100644
--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
@@ -2854,6 +2854,80 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
return res;
}
+ // A box with nothing inside (a fill, a bar, a card's backing) and
+ // nothing that needs it isolated draws straight onto the
+ // destination: a group texture would cost a full-canvas clear
+ // and composite for one rect.
+ if (
+ (!nodeVM.children || nodeVM.children.length === 0) &&
+ (!Array.isArray(lop.effects) || lop.effects.length === 0) &&
+ blendMode === "normal" &&
+ !(target?.motionBlurShutter ?? lop.motionBlurShutter) &&
+ (typeof lop.relighting !== "object" || !lop.relighting) &&
+ (typeof lop.relight !== "object" || !lop.relight) &&
+ (typeof target?.relighting !== "object" || !target?.relighting) &&
+ (typeof target?.relight !== "object" || !target?.relight) &&
+ (typeof lop.deflicker !== "object" || !lop.deflicker) &&
+ (typeof target?.deflicker !== "object" || !target?.deflicker)
+ ) {
+ if (layerOpacity <= 0)
+ return { finalTex: activeTex, finalView: activeView };
+ const br = Math.min(
+ target?.borderRadius ?? lop.borderRadius ?? lop.strokeRadius ?? 0,
+ layerW / 2,
+ layerH / 2,
+ );
+ const paint = shouldPaintContainerBackground(kind, lop.background);
+ const border =
+ lop.borderWidth !== undefined && lop.borderColor
+ ? createBorderTexture(
+ ctx,
+ encoder,
+ layerW,
+ layerH,
+ br,
+ lop.borderWidth,
+ lop.borderColor,
+ lop.strokeAlign ?? "inside",
+ [activeTex, targetTexture, ...excludes],
+ )
+ : null;
+ if (paint || border) {
+ const pass = ctx.renderer.beginFrame(
+ encoder,
+ activeView,
+ { r: 0, g: 0, b: 0, a: 0 },
+ targetW,
+ targetH,
+ "load",
+ );
+ ctx.renderer.pushTransform(layerMatrix);
+ if (paint)
+ ctx.renderer.drawRect(
+ pass,
+ { x: 0, y: 0, width: layerW, height: layerH },
+ lop.background,
+ br,
+ { opacity: layerOpacity },
+ );
+ if (border)
+ ctx.renderer.drawTexture(
+ pass,
+ border.borderTex,
+ {
+ x: border.ox,
+ y: border.oy,
+ width: border.ow,
+ height: border.oh,
+ },
+ { opacity: layerOpacity },
+ );
+ ctx.renderer.popTransform();
+ pass.end();
+ }
+ return { finalTex: activeTex, finalView: activeView };
+ }
+
// Otherwise, draw container background + children + border onto a temporary group texture,
// and composite/blend the group texture onto destTex.
const groupExcludes = [activeTex, targetTexture, ...excludes];
@@ -4350,6 +4424,9 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
}
};
+/** Pixels of room around a border texture for its anti-aliased edge. */
+const BORDER_AA_MARGIN = 2;
+
function createBorderTexture(
ctx: RenderContextValue,
encoder: GPUCommandEncoder,
@@ -4411,8 +4488,12 @@ function createBorderTexture(
return null;
}
- const borderTexW = Math.ceil(ow);
- const borderTexH = Math.ceil(oh);
+ // A margin around the border's own box: its anti-aliased outer edge lies
+ // half a pixel outside it, and a rounded border touching the texture's
+ // edge would lose that fringe (flat spots, plain to see once scaled up).
+ const m = BORDER_AA_MARGIN;
+ const borderTexW = Math.ceil(ow + 2 * m);
+ const borderTexH = Math.ceil(oh + 2 * m);
const outerTex = ctx.renderer.getTemporaryTexture(
borderTexW,
@@ -4441,7 +4522,7 @@ function createBorderTexture(
);
ctx.renderer.drawRect(
outerDrawPass,
- { x: 0, y: 0, width: ow, height: oh },
+ { x: m, y: m, width: ow, height: oh },
borderColor,
outerRadius,
);
@@ -4477,7 +4558,7 @@ function createBorderTexture(
);
ctx.renderer.drawRect(
innerDrawPass,
- { x: borderWidth, y: borderWidth, width: innerW, height: innerH },
+ { x: m + borderWidth, y: m + borderWidth, width: innerW, height: innerH },
{ r: 1, g: 1, b: 1, a: 1 },
innerRadius,
);
@@ -4490,8 +4571,20 @@ function createBorderTexture(
"mask-out",
excludeTextures,
);
- return { borderTex, ox, oy, ow, oh };
+ return {
+ borderTex,
+ ox: ox - m,
+ oy: oy - m,
+ ow: borderTexW,
+ oh: borderTexH,
+ };
}
- return { borderTex: outerTex, ox, oy, ow, oh };
+ return {
+ borderTex: outerTex,
+ ox: ox - m,
+ oy: oy - m,
+ ow: borderTexW,
+ oh: borderTexH,
+ };
}
diff --git a/nodes/node-layer-style/src/renderers/webgpu-renderer.ts b/nodes/node-layer-style/src/renderers/webgpu-renderer.ts
index d8858aab..66deaa14 100644
--- a/nodes/node-layer-style/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-layer-style/src/renderers/webgpu-renderer.ts
@@ -8,10 +8,7 @@ import {
fragmentBindGroupLayout,
PREMULTIPLIED_BLEND,
} from "@framefields/node-sdk/gpu";
-import {
- computeLayerStylePadding,
- type LayerStyleNodeConfig,
-} from "../shared/config.js";
+import type { LayerStyleNodeConfig } from "../shared/config.js";
interface LayerStyleOp extends LayerStyleNodeConfig {
op: "LayerStyle";
@@ -745,13 +742,11 @@ export const WebGPURenderer: WebGPUNodeRenderer = async (args) => {
return Math.max(clampMin, Math.min(clampMax, fallbackVal));
};
- // 1. Render child media into temporary texture at its natural size and draw centered with padding
- const padding = computeLayerStylePadding(op);
- const padX = padding.padX;
- const padY = padding.padY;
-
- const childW = Math.max(1, width - padX * 2);
- const childH = Math.max(1, height - padY * 2);
+ // 1. Render the child at the target's own size. Shrinking it to leave room
+ // for a shadow's offset squashed it (and, on a container's canvas-sized
+ // group, moved everything in it); a shadow past the edge is clipped.
+ const childW = width;
+ const childH = height;
const childTex = ctx.renderer.getTemporaryTexture(childW, childH, [
...(props.excludeTextures || []),
@@ -802,7 +797,7 @@ export const WebGPURenderer: WebGPUNodeRenderer = async (args) => {
ctx.renderer.drawTexture(
inputPass,
childTex,
- { x: padX, y: padY, width: childW, height: childH },
+ { x: 0, y: 0, width: childW, height: childH },
{ opacity: 1 },
);
inputPass.end();
diff --git a/nodes/node-layer-style/src/shared/config.ts b/nodes/node-layer-style/src/shared/config.ts
index cab30637..e8e2bab2 100644
--- a/nodes/node-layer-style/src/shared/config.ts
+++ b/nodes/node-layer-style/src/shared/config.ts
@@ -237,36 +237,6 @@ export type BevelEmbossStyle = z.infer<typeof BevelEmbossStyleSchema>;
export type ColorOverlayStyle = z.infer<typeof ColorOverlayStyleSchema>;
export type LayerStyleNodeConfig = z.infer<typeof LayerStyleNodeConfigSchema>;
-export function computeLayerStylePadding(config: LayerStyleNodeConfig): {
- padX: number;
- padY: number;
-} {
- let padX = 0;
- let padY = 0;
-
- // Drop Shadow: offset distance expansion only (blur size does not increase metadata dimensions)
- if (config.dropShadow?.enabled) {
- const angleRad = ((config.dropShadow.angle ?? 120) * Math.PI) / 180;
- const dist = config.dropShadow.distance ?? 0;
- const dx = Math.ceil(Math.abs(Math.cos(angleRad)) * dist);
- const dy = Math.ceil(Math.abs(Math.sin(angleRad)) * dist);
- padX = Math.max(padX, dx);
- padY = Math.max(padY, dy);
- }
-
- // Stroke expansion (outside / center)
- if (config.stroke?.enabled && config.stroke.position !== "inside") {
- const strokePad =
- config.stroke.position === "outside"
- ? Math.ceil(config.stroke.size ?? 2)
- : Math.ceil((config.stroke.size ?? 2) * 0.5);
- padX = Math.max(padX, strokePad);
- padY = Math.max(padY, strokePad);
- }
-
- return { padX, padY };
-}
-
export interface ConfigHandleBinding {
configKey: string;
dataTypes: DataType[];
diff --git a/packages/components/src/captions/index.test.ts b/packages/components/src/captions/index.test.ts
index 72f4166a..eb45b09b 100644
--- a/packages/components/src/captions/index.test.ts
+++ b/packages/components/src/captions/index.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { bind } from "../core/contract.js";
import { evaluateGlyphExpression, type GlyphAnimator } from "../core/glyphs.js";
+import { themes } from "../core/theme.js";
import { fakeHost } from "../test/fake-host.js";
import { captions } from "./index.js";
@@ -32,6 +33,31 @@ const words = "Ship it faster than ever before today"
}));
describe("Captions", () => {
+ it("an emphasised word on the highlight marker reads in ink, not accent on accent", () => {
+ // Paper: ink reads on its accent, so only emphasised words switch.
+ const c = make()({
+ id: "c",
+ words,
+ style: "highlight",
+ emphasis: ["faster"],
+ theme: themes.paper,
+ });
+ const phrase = find(c, "c-phrase-0");
+ const onMarker = phrase?.animators?.find((a) => a.name === "on-marker");
+ expect(onMarker).toBeDefined();
+ const expr = onMarker?.selectors[0]?.expression ?? "";
+ const phraseStart = c.cues.phrases[0]?.frame ?? 0;
+ const local = (c.cues.words[2]?.frame ?? 0) - phraseStart + 3;
+ // "faster" (word 2) switches on the marker; plain words keep their ink.
+ expect(evaluateGlyphExpression(expr, { frame: local, wordIndex: 2 })).toBe(
+ 1,
+ );
+ const plain = (c.cues.words[1]?.frame ?? 0) - phraseStart + 3;
+ expect(evaluateGlyphExpression(expr, { frame: plain, wordIndex: 1 })).toBe(
+ 0,
+ );
+ });
+
it("cues every word on round(start × fps), in the parent's timeline", () => {
const c = make()({ id: "c", words, at: 10 });
expect(c.cues.words.map((w) => w.frame)).toEqual(
diff --git a/packages/components/src/captions/index.ts b/packages/components/src/captions/index.ts
index 83177d42..aa3bfc54 100644
--- a/packages/components/src/captions/index.ts
+++ b/packages/components/src/captions/index.ts
@@ -365,8 +365,11 @@ export const captions = /* @__PURE__ */ defineComponent({
);
marker.animate(markerKeys(rects, wStart, pad, glide));
plates.push(marker);
- // Text on the marker reads in the background colour when ink wouldn't.
- if ((contrastRatio(ink, accent) ?? 21) < 3)
+ // Text on the marker must read against it: every word in the
+ // background colour when ink wouldn't, else only the emphasised
+ // ones (accent on the accent marker), in ink.
+ const inkReads = (contrastRatio(ink, accent) ?? 21) >= 3;
+ if (!inkReads || emphasisWeights.some(Boolean))
animators.push(
glyphAnimator(
"on-marker",
@@ -375,8 +378,9 @@ export const captions = /* @__PURE__ */ defineComponent({
"word",
wStart.map((f) => f + Math.ceil(glide / 2)),
wEnd.map((f) => f + Math.ceil(glide / 2)),
+ inkReads ? emphasisWeights : undefined,
),
- { fillColor: theme.color.bg },
+ { fillColor: inkReads ? ink : theme.color.bg },
),
);
break;
diff --git a/packages/components/src/lower-third/index.ts b/packages/components/src/lower-third/index.ts
index 3c6c428b..125743a1 100644
--- a/packages/components/src/lower-third/index.ts
+++ b/packages/components/src/lower-third/index.ts
@@ -18,6 +18,9 @@ import type { Animatable } from "../core/host.js";
import { themeFrames } from "../core/theme.js";
export const LOWER_THIRD_LAYOUTS = ["bar", "stacked", "tag", "line"] as const;
+
+/** Cap height as a share of the font size (Inter and most UI sans faces). */
+const CAP_HEIGHT = 0.72;
export type LowerThirdLayout = (typeof LOWER_THIRD_LAYOUTS)[number];
export interface LowerThirdCues {
@@ -331,6 +334,9 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
fontSize: roleSize,
fontWeight: 500,
fill: theme.color.muted,
+ // Centred on the name's capitals, not on its baseline: one
+ // line in a pill reads as aligned when the caps share a middle.
+ baselineShift: -(nameSize - roleSize) * CAP_HEIGHT * 0.5,
},
]
: []),
diff --git a/packages/components/src/meter/index.test.ts b/packages/components/src/meter/index.test.ts
index b1d4ab35..7830a8aa 100644
--- a/packages/components/src/meter/index.test.ts
+++ b/packages/components/src/meter/index.test.ts
@@ -31,6 +31,20 @@ const track = (n: Node | undefined, prop: string) =>
n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? [];
describe("Meter", () => {
+ it("keeps a counter taller than its stars inside the root (nothing above the top)", () => {
+ const m = make()({ id: "m", kind: "stars", value: 2, counter: true });
+ const kids = (
+ m as unknown as { children: Array<{ y?: number; height?: number }> }
+ ).children;
+ expect(Math.min(...kids.map((k) => k.y ?? 0))).toBe(0);
+ const counter = find(m, "m-counter") as
+ | { y?: number; height?: number }
+ | undefined;
+ expect((counter?.y ?? 0) + (counter?.height ?? 0)).toBeLessThanOrEqual(
+ (m as unknown as { height: number }).height,
+ );
+ });
+
it("fills to (value − from) / (max − from) on the value's own keys", () => {
const m = make()({
id: "m",
diff --git a/packages/components/src/meter/index.ts b/packages/components/src/meter/index.ts
index 2a14e727..526fab9a 100644
--- a/packages/components/src/meter/index.ts
+++ b/packages/components/src/meter/index.ts
@@ -404,6 +404,20 @@ export const meter = /* @__PURE__ */ defineComponent({
}
}
+ // Centring the counter on a shorter row can put it above the top; the
+ // root box clips what's outside it, so move everything down instead.
+ const top = Math.min(
+ 0,
+ ...children.map((n) => (n as unknown as { y?: number }).y ?? 0),
+ );
+ if (top < 0) {
+ for (const n of children) {
+ const node = n as unknown as { y?: number };
+ node.y = (node.y ?? 0) - top;
+ }
+ H -= top;
+ }
+
const settled = Math.max(
last,
(
diff --git a/packages/core/src/utils/gradient.test.ts b/packages/core/src/utils/gradient.test.ts
index 2ba41a79..7d7bd077 100644
--- a/packages/core/src/utils/gradient.test.ts
+++ b/packages/core/src/utils/gradient.test.ts
@@ -62,6 +62,16 @@ describe("parseCssGradient", () => {
expect(c?.from).toBe(90);
expect(c?.center).toEqual([0, 0]);
expect(c?.stops[1].offset).toBeCloseTo(0.5);
+ // The size keyword is kept: closest-side lands the last stop on the box's edge.
+ expect(
+ parseCssGradient("radial-gradient(closest-side, #fff 40%, transparent)")
+ ?.extent,
+ ).toBe("closest-side");
+ expect(
+ parseCssGradient(
+ "radial-gradient(circle farthest-side at 10% 10%, red, blue)",
+ ),
+ ).toMatchObject({ shape: "circle", extent: "farthest-side" });
// No config: the first part is a stop.
expect(parseCssGradient("radial-gradient(red, blue)")?.stops).toHaveLength(
2,
diff --git a/packages/core/src/utils/gradient.ts b/packages/core/src/utils/gradient.ts
index 4d29ebc1..137ff43d 100644
--- a/packages/core/src/utils/gradient.ts
+++ b/packages/core/src/utils/gradient.ts
@@ -14,15 +14,23 @@ export interface ParsedGradientStop {
color: Rgba;
}
+export type RadialExtent =
+ | "closest-side"
+ | "closest-corner"
+ | "farthest-side"
+ | "farthest-corner";
+
export interface ParsedGradient {
type: GradientType;
/** Linear: CSS angle in degrees (0 = to top, 90 = to right, 180 = to bottom). */
angle: number;
/** Radial / conic center as a fraction of the box (0.5, 0.5 = middle). */
center: [number, number];
- /** Radial: circle or ellipse sized to the farthest corner, or explicit px radii. */
+ /** Radial: circle or ellipse, sized by `extent` unless `radius` gives px radii. */
shape: "circle" | "ellipse";
radius?: [number, number];
+ /** Radial size keyword (CSS): where the last stop lands. Default farthest-corner. */
+ extent?: RadialExtent;
/** Conic: start angle in degrees (0 = top, clockwise). */
from: number;
stops: ParsedGradientStop[];
@@ -235,6 +243,10 @@ function parseUncached(input: string): ParsedGradient | null {
if (at >= 0) g.center = parsePosition(tokens.slice(at + 1));
if (type === "radial") {
if (before.includes("circle")) g.shape = "circle";
+ const extent = before.find((t) =>
+ /^(closest|farthest)-(side|corner)$/.test(t),
+ );
+ if (extent) g.extent = extent as RadialExtent;
const px = before
.filter((t) => /px$/.test(t))
.map((t) => parseFloat(t));
diff --git a/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.test.ts b/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.test.ts
new file mode 100644
index 00000000..504a26b9
--- /dev/null
+++ b/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.test.ts
@@ -0,0 +1,53 @@
+import { parseCssGradient } from "@framefields/core";
+import { describe, expect, it } from "vitest";
+import { radialExtent } from "./gradient-uniforms.js";
+
+const g = (css: string) => {
+ const parsed = parseCssGradient(css);
+ if (!parsed) throw new Error(`not a gradient: ${css}`);
+ return parsed;
+};
+
+describe("radialExtent", () => {
+ // Centre 30 px from the left, 70 from the right, 10 from the top, 40 from the bottom.
+ const at = [30, 70, 10, 40] as const;
+
+ it("closest-side reaches the nearest edge on each axis", () => {
+ expect(
+ radialExtent(g("radial-gradient(closest-side, red, blue)"), ...at),
+ ).toEqual([30, 10]);
+ expect(
+ radialExtent(g("radial-gradient(circle closest-side, red, blue)"), ...at),
+ ).toEqual([10, 10]);
+ });
+
+ it("farthest-side reaches the far edge on each axis", () => {
+ expect(
+ radialExtent(g("radial-gradient(farthest-side, red, blue)"), ...at),
+ ).toEqual([70, 40]);
+ expect(
+ radialExtent(
+ g("radial-gradient(circle farthest-side, red, blue)"),
+ ...at,
+ ),
+ ).toEqual([70, 70]);
+ });
+
+ it("corners pass through the corner; farthest-corner is the default", () => {
+ const [cx, cy] = radialExtent(
+ g("radial-gradient(closest-corner, red, blue)"),
+ ...at,
+ );
+ expect(cx).toBeCloseTo(30 * Math.SQRT2);
+ expect(cy).toBeCloseTo(10 * Math.SQRT2);
+ expect(
+ radialExtent(
+ g("radial-gradient(circle farthest-corner, red, blue)"),
+ ...at,
+ )[0],
+ ).toBeCloseTo(Math.hypot(70, 40));
+ expect(radialExtent(g("radial-gradient(red, blue)"), ...at)).toEqual(
+ radialExtent(g("radial-gradient(farthest-corner, red, blue)"), ...at),
+ );
+ });
+});
diff --git a/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.ts b/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.ts
index 81d9d550..4fd1ba61 100644
--- a/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.ts
+++ b/packages/webgpu-renderers/src/renderer2d/gradient-uniforms.ts
@@ -58,15 +58,13 @@ export function packGradientUniforms(
if (gradient.radius) {
[rx, ry] = gradient.radius;
} else {
- // farthest-corner, as CSS sizes radial gradients by default.
- const fx = Math.max(cx - box.x, box.x + w - cx);
- const fy = Math.max(cy - box.y, box.y + h - cy);
- if (gradient.shape === "circle") {
- rx = ry = Math.hypot(fx, fy);
- } else {
- rx = fx * Math.SQRT2;
- ry = fy * Math.SQRT2;
- }
+ [rx, ry] = radialExtent(
+ gradient,
+ cx - box.x,
+ box.x + w - cx,
+ cy - box.y,
+ box.y + h - cy,
+ );
}
out[offset + 6] = rx;
out[offset + 7] = ry;
@@ -80,3 +78,34 @@ export function packGradientUniforms(
out.set(lab, offset + 16 + i * 4);
});
}
+
+/**
+ * Radii of a radial gradient from its size keyword, as CSS sizes them: the
+ * centre's distances to the box's left, right, top and bottom edges in.
+ * Default (no keyword) is farthest-corner.
+ */
+export function radialExtent(
+ gradient: Pick<ParsedGradient, "shape" | "extent">,
+ left: number,
+ right: number,
+ top: number,
+ bottom: number,
+): [number, number] {
+ const extent = gradient.extent ?? "farthest-corner";
+ const farthest = extent.startsWith("farthest");
+ const sx = farthest ? Math.max(left, right) : Math.min(left, right);
+ const sy = farthest ? Math.max(top, bottom) : Math.min(top, bottom);
+ const circle = gradient.shape === "circle";
+ if (extent.endsWith("side")) {
+ if (!circle) return [sx, sy];
+ const r = farthest ? Math.max(sx, sy) : Math.min(sx, sy);
+ return [r, r];
+ }
+ // Corners: a circle through the corner; an ellipse with the sides' aspect
+ // ratio scaled until it passes through it (√2 × the side radii).
+ if (circle) {
+ const r = Math.hypot(sx, sy);
+ return [r, r];
+ }
+ return [sx * Math.SQRT2, sy * Math.SQRT2];
+}
diff --git a/packages/webgpu-renderers/src/renderer2d/solid-pipeline.ts b/packages/webgpu-renderers/src/renderer2d/solid-pipeline.ts
index 757b35ba..ab87969f 100644
--- a/packages/webgpu-renderers/src/renderer2d/solid-pipeline.ts
+++ b/packages/webgpu-renderers/src/renderer2d/solid-pipeline.ts
@@ -100,14 +100,29 @@ export class SolidPipeline {
this.uniformData,
);
- this.vertexData[0] = rect.x;
- this.vertexData[1] = rect.y;
- this.vertexData[2] = rect.x + rect.width;
- this.vertexData[3] = rect.y;
- this.vertexData[4] = rect.x;
- this.vertexData[5] = rect.y + rect.height;
- this.vertexData[6] = rect.x + rect.width;
- this.vertexData[7] = rect.y + rect.height;
+ // A rounded shape's anti-aliased edge reaches half a device pixel past
+ // the rect; grow the quad by a couple of device pixels (in local units)
+ // so it isn't cut where the curve meets the rect's sides.
+ let grow = 0;
+ if (cornerRadius > 0) {
+ const m = opts?.transform
+ ? transformStack.getCurrent().multiply(opts.transform)
+ : transformStack.getCurrent();
+ const scale = Math.min(Math.hypot(m.a, m.b), Math.hypot(m.c, m.d));
+ grow = 2 / Math.max(scale, 1e-3);
+ }
+ const x0 = rect.x - grow;
+ const y0 = rect.y - grow;
+ const x1 = rect.x + rect.width + grow;
+ const y1 = rect.y + rect.height + grow;
+ this.vertexData[0] = x0;
+ this.vertexData[1] = y0;
+ this.vertexData[2] = x1;
+ this.vertexData[3] = y0;
+ this.vertexData[4] = x0;
+ this.vertexData[5] = y1;
+ this.vertexData[6] = x1;
+ this.vertexData[7] = y1;
const vertexBuffer = this.vertexPool.getBuffer(
this.device,
diff --git a/packages/webgpu-renderers/src/shaders/solid.ts b/packages/webgpu-renderers/src/shaders/solid.ts
index 297dc196..0d6e93db 100644
--- a/packages/webgpu-renderers/src/shaders/solid.ts
+++ b/packages/webgpu-renderers/src/shaders/solid.ts
@@ -42,7 +42,13 @@ fn sdRoundedRect(p: vec2<f32>, b: vec2<f32>, r: f32) -> f32 {
let radius = u.params.w;
let d = sdRoundedRect(in.localPos - center, halfSize, radius);
- let edgeAlpha = 1.0 - smoothstep(0.0, 1.0, d);
+ // Rounded shapes: one device pixel of coverage centred on the edge (the
+ // quad has room for its outer half). Square ones keep their exact edge.
+ let fw = max(fwidth(d), 1e-4);
+ var edgeAlpha = 1.0 - smoothstep(0.0, 1.0, d);
+ if (radius > 0.0) {
+ edgeAlpha = clamp(0.5 - d / fw, 0.0, 1.0);
+ }
var fill = u.color;
if (u.gradient.info.x > 0.5) {
fill = evalGradient(u.gradient, in.localPos);
diff --git a/packages/webgpu-renderers/src/slug/text-shaping.test.ts b/packages/webgpu-renderers/src/slug/text-shaping.test.ts
index e0f954d3..3afbc405 100644
--- a/packages/webgpu-renderers/src/slug/text-shaping.test.ts
+++ b/packages/webgpu-renderers/src/slug/text-shaping.test.ts
@@ -129,6 +129,15 @@ describe("RTL line layout", () => {
).toEqual(["אב גד", "הו זח"]);
});
+ it("keeps a paragraph's indent and drops the space a wrap leaves", () => {
+ const p = shapeParagraph([{ text: " ab cd", style }]);
+ const lines = breakLines(p.clusters, 3);
+ expect(lines.map((l) => l.map((c) => c.text).join(""))).toEqual([
+ " ab ",
+ "cd",
+ ]);
+ });
+
it("aligns start to the right edge and keeps trailing spaces out of the ink", () => {
const result = SlugGeometry.layout(
"אב גד",
diff --git a/packages/webgpu-renderers/src/slug/text-shaping.ts b/packages/webgpu-renderers/src/slug/text-shaping.ts
index 884c7fe1..257de8a2 100644
--- a/packages/webgpu-renderers/src/slug/text-shaping.ts
+++ b/packages/webgpu-renderers/src/slug/text-shaping.ts
@@ -726,9 +726,10 @@ export function shapeLineFromFont(
// ── Lines ────────────────────────────────────────────────────────────────
/**
- * Greedy word wrap over clusters in logical order: breaks only between
- * whitespace and non-whitespace runs, drops whitespace at the start of each
- * line, and never splits a word.
+ * Greedy word wrap over one paragraph's clusters in logical order: breaks
+ * only between whitespace and non-whitespace runs and never splits a word.
+ * Whitespace a wrap leaves at the start of a line is dropped; the paragraph's
+ * own leading whitespace (an indent) is kept.
*/
export function breakLines<S extends ShapeStyle>(
clusters: ShapedCluster<S>[],
@@ -751,7 +752,7 @@ export function breakLines<S extends ShapeStyle>(
i = j;
if (isSpace) {
- if (line.length === 0) continue;
+ if (line.length === 0 && lines.length > 0) continue;
line.push(...token);
lineWidth += tokenWidth;
continue;
@@ -782,6 +783,9 @@ export interface PlacedLine<S extends ShapeStyle = ShapeStyle> {
/** Visible extent of the line (whitespace and outer letter spacing excluded). */
inkLeft: number;
inkRight: number;
+ /** The paragraph's indent (its leading whitespace), on the side it reads from. */
+ indentLeft: number;
+ indentRight: number;
}
/**
@@ -840,7 +844,18 @@ export function placeLine<S extends ShapeStyle>(
inkLeft = 0;
inkRight = 0;
}
- return { clusters, inkLeft, inkRight };
+ // Leading whitespace (kept only on a paragraph's first line) is an indent:
+ // alignment keeps it, on the left for LTR paragraphs, the right for RTL.
+ let indent = 0;
+ for (let i = 0; i < n && line[i].isSpace; i++) indent += line[i].advance;
+ const rtl = (baseLevel & 1) === 1;
+ return {
+ clusters,
+ inkLeft,
+ inkRight,
+ indentLeft: rtl ? 0 : indent,
+ indentRight: rtl ? indent : 0,
+ };
}
/** Resolves `start`/`end` against a paragraph's direction. */
@@ -860,9 +875,11 @@ export function alignOffset(
align: "left" | "center" | "right",
width: number,
): number {
+ const left = line.inkLeft - line.indentLeft;
+ const right = line.inkRight + line.indentRight;
if (align === "center") {
- return (width - (line.inkRight - line.inkLeft)) / 2 - line.inkLeft;
+ return (width - (right - left)) / 2 - left;
}
- if (align === "right") return width - line.inkRight;
- return -line.inkLeft;
+ if (align === "right") return width - right;
+ return -left;
}