Skip to content

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

feat(examples): add 27_rtl_text, Arabic and Hebrew in 2D and 3D

okanasl770687160556
diff --git a/examples/27_rtl_text/README.md b/examples/27_rtl_text/README.md
new file mode 100644
index 00000000..45d2a416
--- /dev/null
+++ b/examples/27_rtl_text/README.md
@@ -0,0 +1,35 @@
+# 27 — Right-to-left text
+
+A 16-second tour of Arabic and Hebrew in framefields, in 2D and 3D: the text is shaped with the
+font's OpenType tables (joining forms, ligatures, vowel marks), laid out right to left with the
+Unicode Bidirectional Algorithm, and wrapped from the right.
+
+```bash
+pnpm fonts # Cairo, Noto Naskh Arabic, Rubik, Inter from google/fonts → assets/fonts/
+pnpm render grid # output/grid.png, a 16-frame contact sheet
+pnpm render frames 140 300 400
+pnpm render # output/rtl-text.mp4
+pnpm render:src grid # same, on the engine's source (no package builds)
+```
+
+The fonts are SIL OFL faces from google/fonts. They are gitignored; `src/fetch-fonts.ts` records
+where they come from.
+
+## The scenes
+
+| Scene | What it shows |
+|---|---|
+| Arabic (2D) | A mixed Arabic / English / number sentence in Cairo: letters join, `لا` forms the lam-alef ligature, the shadda sits on its letter, and "AI" and "2026" read left to right inside the right-to-left line. Words pop in reading order, so the reveal starts at the right. Below it, a fully vowelled proverb in Noto Naskh Arabic is typed out; each letter changes form as the next one arrives. |
+| Hebrew (2D) | A Rubik headline rising letter by letter from the right; a paragraph that mixes Hebrew, English and a number, set with `direction: "rtl"` and `align: "start"` (the right edge); and Hebrew along a curve with `pathOptions`. |
+| 3D | Solid `Layer3D.text` with `extrusionDepth`: the words are shaped exactly like 2D text and then extruded, so Arabic joins in 3D too. Flat `Layer3D.text` captions sit on planes in the same space, centred with `FontManager.measure`. |
+
+## Direction and alignment
+
+Text layers take `direction: "auto" | "ltr" | "rtl"`. The default, `"auto"`, takes each
+paragraph's direction from its first strong character, so Arabic and Hebrew need nothing set.
+`align: "start"` and `"end"` follow the direction: for right-to-left text, `start` is the right
+edge.
+
+The Hebrew paragraph sets `direction: "rtl"` because it opens with the Latin word "framefields":
+with `"auto"` the whole paragraph would read left to right, as it would in a browser with
+`dir="auto"`.
diff --git a/examples/27_rtl_text/package.json b/examples/27_rtl_text/package.json
new file mode 100644
index 00000000..12f75d3a
--- /dev/null
+++ b/examples/27_rtl_text/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@framefields/example-27-rtl-text",
+ "version": "2.0.11",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "fonts": "tsx src/fetch-fonts.ts",
+ "render": "tsx src/render.ts",
+ "render:src": "tsx --tsconfig tsconfig.dev.json --conditions=development src/render.ts",
+ "typecheck": "tsc --noEmit -p ."
+ },
+ "dependencies": {
+ "framefields": "workspace:*"
+ },
+ "devDependencies": {
+ "@framefields/tsconfig": "workspace:*",
+ "@types/node": "^24.1.0",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3"
+ }
+}
diff --git a/examples/27_rtl_text/src/fetch-fonts.ts b/examples/27_rtl_text/src/fetch-fonts.ts
new file mode 100644
index 00000000..2c15ff33
--- /dev/null
+++ b/examples/27_rtl_text/src/fetch-fonts.ts
@@ -0,0 +1,32 @@
+/**
+ * pnpm fonts → assets/fonts/. Arabic and Hebrew faces from google/fonts (all SIL OFL).
+ * Font files are gitignored; this script is the record of where they came from.
+ * Idempotent: an existing file is kept.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { FONTS } from "./theme.js";
+
+const BASE = "https://raw.githubusercontent.com/google/fonts/main/ofl";
+
+const FONT_FILES: Record<string, string> = {
+ // Arabic + Latin, variable weight: the face from the original bug report.
+ "Cairo.ttf": "cairo/Cairo%5Bslnt,wght%5D.ttf",
+ // Arabic with full vowel marks (harakat) placed through GPOS anchors.
+ "NotoNaskhArabic.ttf": "notonaskharabic/NotoNaskhArabic%5Bwght%5D.ttf",
+ // Hebrew + Latin, variable weight.
+ "Rubik.ttf": "rubik/Rubik%5Bwght%5D.ttf",
+ // Latin labels.
+ "Inter.ttf": "inter/Inter%5Bopsz,wght%5D.ttf",
+};
+
+await fs.mkdir(FONTS, { recursive: true });
+for (const [file, src] of Object.entries(FONT_FILES)) {
+ const target = path.join(FONTS, file);
+ if (await fs.stat(target).catch(() => null)) continue;
+ const res = await fetch(`${BASE}/${src}`);
+ if (!res.ok) throw new Error(`${src}: HTTP ${res.status}`);
+ await fs.writeFile(target, Buffer.from(await res.arrayBuffer()));
+ console.log(target);
+}
+process.exit(0);
diff --git a/examples/27_rtl_text/src/film.ts b/examples/27_rtl_text/src/film.ts
new file mode 100644
index 00000000..24d22507
--- /dev/null
+++ b/examples/27_rtl_text/src/film.ts
@@ -0,0 +1,49 @@
+import { Composition, Layer, Transition } from "framefields";
+import { ARABIC_FRAMES, arabicScene } from "./scenes/arabic.js";
+import { HEBREW_FRAMES, hebrewScene } from "./scenes/hebrew.js";
+import { THREE_D_FRAMES, threeDScene } from "./scenes/three-d.js";
+import { FPS, H, PAPER, registerFonts, W } from "./theme.js";
+
+const sequence = () =>
+ Layer.sequence(
+ [
+ { scene: arabicScene(), duration: ARABIC_FRAMES },
+ {
+ scene: hebrewScene(),
+ duration: HEBREW_FRAMES,
+ transition: Transition.push("right", 18),
+ },
+ {
+ scene: threeDScene(),
+ duration: THREE_D_FRAMES,
+ transition: Transition.fadeThrough(16),
+ },
+ ],
+ { width: W, height: H },
+ );
+
+const TRANSITIONS = 18 + 16;
+/** Total length in frames: the scenes back to back, less the transition overlaps. */
+export const DURATION =
+ ARABIC_FRAMES + HEBREW_FRAMES + THREE_D_FRAMES - TRANSITIONS;
+
+export async function buildFilm(): Promise<Composition> {
+ await registerFonts();
+ const film = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (DURATION / FPS) * 1000,
+ backgroundColor: PAPER,
+ });
+ // Scenes are built after the fonts are registered: extruded text and the
+ // caption measurements read the real outlines.
+ const scenes = sequence();
+ if (scenes.totalFrames !== DURATION) {
+ throw new Error(
+ `Sequence is ${scenes.totalFrames} frames, expected ${DURATION}`,
+ );
+ }
+ film.add(scenes);
+ return film;
+}
diff --git a/examples/27_rtl_text/src/render.ts b/examples/27_rtl_text/src/render.ts
new file mode 100644
index 00000000..6157aa55
--- /dev/null
+++ b/examples/27_rtl_text/src/render.ts
@@ -0,0 +1,66 @@
+/**
+ * pnpm render → output/rtl-text.mp4
+ * pnpm render frames 60 180 → output/frames/f0060.png …
+ * pnpm render grid → output/grid.png, a contact sheet of the whole film
+ * pnpm render preview → live player on localhost; add --open for the system browser
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer, startPreview } from "framefields";
+import { buildFilm, DURATION } from "./film.js";
+import { OUTPUT } from "./theme.js";
+
+const [mode = "video", ...args] = process.argv.slice(2);
+
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "RTL text", open: args.includes("--open") },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
+const film = await buildFilm();
+await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
+
+if (mode === "frames") {
+ const renderer = new HeadlessMediaRenderer();
+ for (const frame of args.map(Number)) {
+ const file = path.join(
+ OUTPUT,
+ "frames",
+ `f${String(frame).padStart(4, "0")}.png`,
+ );
+ await fs.writeFile(file, await film.renderFrame({ frame, renderer }));
+ console.log(file);
+ }
+} else if (mode === "grid") {
+ const frames = Array.from({ length: 16 }, (_, i) =>
+ Math.round((i * (DURATION - 1)) / 15),
+ );
+ const file = path.join(OUTPUT, "grid.png");
+ await fs.writeFile(
+ file,
+ await film.renderFrameGrid({
+ frames,
+ columns: 4,
+ cellWidth: 480,
+ showLabels: true,
+ }),
+ );
+ console.log(file);
+} else {
+ const started = Date.now();
+ const result = await film.renderVideo({
+ outputPath: path.join(OUTPUT, "rtl-text.mp4"),
+ quality: "high",
+ });
+ await result.cleanup?.().catch(() => {});
+ console.log(
+ `${result.filePath} (${((Date.now() - started) / 1000).toFixed(1)} s)`,
+ );
+}
+process.exit(0);
diff --git a/examples/27_rtl_text/src/scenes/arabic.ts b/examples/27_rtl_text/src/scenes/arabic.ts
new file mode 100644
index 00000000..cf6d5e48
--- /dev/null
+++ b/examples/27_rtl_text/src/scenes/arabic.ts
@@ -0,0 +1,63 @@
+/**
+ * Arabic in 2D: the sentence from the original bug report in Cairo (joined
+ * letters, lam-alef, the shadda on its letter, "AI" and "2026" left to right
+ * inside a right-to-left line), then a fully vowelled proverb in Naskh typed
+ * out, its letters changing form as each next one arrives.
+ */
+import { Layer, LayerAnimation, TextAnimator } from "framefields";
+import { ACCENT, CAIRO, INK, label, NASKH, PAPER, scene, W } from "../theme.js";
+
+export const ARABIC_FRAMES = 165;
+
+const HEADLINE = "الذكاء الاصطناعي AI هيغيّر شغلنا في 2026، بس لازم نتعلّم صح.";
+const PROVERB = "اُطْلُبُوا الْعِلْمَ مِنَ الْمَهْدِ إِلَى اللَّحْدِ";
+
+export function arabicScene() {
+ return scene("arabic", PAPER, [
+ Layer.text(HEADLINE, {
+ id: "ar-headline",
+ position: "absolute",
+ x: 160,
+ y: 150,
+ width: W - 320,
+ fontFamily: CAIRO,
+ fontWeight: 700,
+ fontSize: 100,
+ lineHeight: 1.35,
+ fill: INK,
+ align: "center",
+ animators: [TextAnimator.wordPop({ y: 30 })],
+ }).animate(LayerAnimation.create().kineticSweep(-1, 1, 6, 66)),
+ Layer.box({
+ id: "ar-rule",
+ position: "absolute",
+ x: W / 2 - 120,
+ y: 560,
+ width: 240,
+ height: 4,
+ background: ACCENT,
+ borderRadius: 2,
+ }).animate(
+ LayerAnimation.create().keys("opacity", [
+ [50, 0],
+ [70, 1, "power2.out"],
+ ]),
+ ),
+ Layer.text(PROVERB, {
+ id: "ar-proverb",
+ position: "absolute",
+ x: 160,
+ y: 620,
+ width: W - 320,
+ fontFamily: NASKH,
+ fontWeight: 500,
+ fontSize: 88,
+ fill: ACCENT,
+ align: "center",
+ }).animate(LayerAnimation.create().typewriter(70, 140)),
+ label(
+ "ar-label",
+ "Arabic · Cairo and Noto Naskh Arabic · joining forms, lam-alef, vowel marks, right to left",
+ ),
+ ]);
+}
diff --git a/examples/27_rtl_text/src/scenes/hebrew.ts b/examples/27_rtl_text/src/scenes/hebrew.ts
new file mode 100644
index 00000000..ec56c1cf
--- /dev/null
+++ b/examples/27_rtl_text/src/scenes/hebrew.ts
@@ -0,0 +1,76 @@
+/**
+ * Hebrew in 2D: a headline rising letter by letter in reading order (from
+ * the right), a mixed Hebrew / English / number paragraph aligned to its
+ * start (the right edge), and Hebrew flowing along a curve.
+ */
+import {
+ Layer,
+ LayerAnimation,
+ TextAnimator,
+ TextPathBuilder,
+} from "framefields";
+import { INK, label, PAPER, RUBIK, scene, TEAL, W } from "../theme.js";
+
+export const HEBREW_FRAMES = 165;
+
+export function hebrewScene() {
+ return scene("hebrew", PAPER, [
+ Layer.text("שלום עולם", {
+ id: "he-title",
+ position: "absolute",
+ x: 0,
+ y: 110,
+ width: W,
+ fontFamily: RUBIK,
+ fontWeight: 800,
+ fontSize: 180,
+ fill: INK,
+ align: "center",
+ animators: [TextAnimator.waveRise({ y: 60, rotationX: 60 })],
+ }).animate(LayerAnimation.create().kineticSweep(-1, 1, 4, 50)),
+ Layer.text(
+ "framefields מציירת עברית מימין לשמאל, עם English ו-2026 בתוך השורה.",
+ {
+ id: "he-mixed",
+ position: "absolute",
+ x: 260,
+ y: 380,
+ width: W - 520,
+ fontFamily: RUBIK,
+ fontWeight: 500,
+ fontSize: 64,
+ lineHeight: 1.3,
+ fill: INK,
+ // The paragraph opens with a Latin word, so "auto" would read it
+ // left to right (as a browser does); force Hebrew's direction.
+ direction: "rtl",
+ // "start" is then the right edge.
+ align: "start",
+ },
+ ).animate(LayerAnimation.create().typewriter(30, 100)),
+ Layer.text("טקסט שזורם לאורך מסלול · טקסט שזורם לאורך מסלול", {
+ id: "he-path",
+ position: "absolute",
+ x: 0,
+ y: 560,
+ width: W,
+ height: 400,
+ fontFamily: RUBIK,
+ fontWeight: 600,
+ fontSize: 56,
+ fill: TEAL,
+ pathOptions: TextPathBuilder.fromSvg("M 380 330 Q 960 20 1540 330")
+ .forceAlignment(true)
+ .build(),
+ }).animate(
+ LayerAnimation.create().keys("opacity", [
+ [90, 0],
+ [115, 1, "power2.out"],
+ ]),
+ ),
+ label(
+ "he-label",
+ "Hebrew · Rubik · right to left, embedded English and numbers, text on a path",
+ ),
+ ]);
+}
diff --git a/examples/27_rtl_text/src/scenes/three-d.ts b/examples/27_rtl_text/src/scenes/three-d.ts
new file mode 100644
index 00000000..425d6d42
--- /dev/null
+++ b/examples/27_rtl_text/src/scenes/three-d.ts
@@ -0,0 +1,131 @@
+/**
+ * Arabic and Hebrew in 3D: solid extruded words (shaped like 2D text, then
+ * tessellated and extruded) turning under a studio light, and flat
+ * `Layer3D.text` captions on planes in the same space.
+ */
+import {
+ FontManager,
+ Layer,
+ Layer3D,
+ LayerAnimation,
+ Lighting,
+} from "framefields";
+import {
+ ACCENT,
+ CAIRO,
+ H,
+ label,
+ RUBIK,
+ SANS,
+ STUDIO,
+ scene,
+ TEAL,
+ W,
+} from "../theme.js";
+
+export const THREE_D_FRAMES = 180;
+
+const CX = W / 2;
+const CY = H / 2;
+
+/**
+ * A planar caption centred on `cx`: a planar text node's `x` is its left
+ * edge, so measure the shaped line (right to left included) and shift.
+ */
+function caption(
+ id: string,
+ text: string,
+ family: string,
+ cx: number,
+ fill: string,
+) {
+ const fontSize = 64;
+ const { width } = FontManager.measure(text, {
+ fontFamily: family,
+ fontSize,
+ fontWeight: 600,
+ });
+ return Layer3D.text({
+ id,
+ text,
+ fontFamily: family,
+ fontWeight: 600,
+ fontSize,
+ fill,
+ material: "unlit",
+ x: cx - width / 2,
+ y: CY + 200,
+ z: 0,
+ });
+}
+
+/** A slow turn and settle, so the side walls catch the light. */
+function turn(from: number, to: number) {
+ return LayerAnimation.create()
+ .keys("rotateY", [
+ [0, from],
+ [THREE_D_FRAMES, to, "sine.inOut"],
+ ])
+ .keys("opacity", [
+ [0, 0],
+ [20, 1, "power2.out"],
+ ]);
+}
+
+export function threeDScene() {
+ return scene("three-d", STUDIO, [
+ ...Lighting.studio({ target: [CX, CY, 0], shadows: false }),
+ Layer3D.text({
+ id: "x-arabic",
+ text: "مرحبا",
+ fontFamily: CAIRO,
+ fontWeight: 800,
+ fontSize: 300,
+ extrusionDepth: 70,
+ fill: ACCENT,
+ bevelColor: "#7c2d12",
+ roughness: 0.35,
+ x: CX - 400,
+ y: CY - 60,
+ z: 0,
+ }).animate(turn(-28, 18)),
+ Layer3D.text({
+ id: "x-hebrew",
+ text: "שלום",
+ fontFamily: RUBIK,
+ fontWeight: 800,
+ fontSize: 280,
+ extrusionDepth: 70,
+ fill: TEAL,
+ bevelColor: "#134e4a",
+ roughness: 0.35,
+ x: CX + 400,
+ y: CY - 60,
+ z: 0,
+ }).animate(turn(28, -18)),
+ caption("p-arabic", "نص ثلاثي الأبعاد", CAIRO, CX - 400, "#f3e8dc").animate(
+ turn(-12, 8),
+ ),
+ caption("p-hebrew", "טקסט תלת־ממדי", RUBIK, CX + 400, "#d9f2ee").animate(
+ turn(12, -8),
+ ),
+ Layer.text("3D", {
+ id: "x-kicker",
+ position: "absolute",
+ x: 0,
+ y: 90,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontWeight: 700,
+ fontSize: 34,
+ fill: "#9ca3af",
+ letterSpacing: 6,
+ }),
+ label(
+ "x-label",
+ "Extruded Layer3D.text (Cairo, Rubik) and planar Layer3D.text captions",
+ "#9ca3af",
+ ),
+ ]);
+}
diff --git a/examples/27_rtl_text/src/theme.ts b/examples/27_rtl_text/src/theme.ts
new file mode 100644
index 00000000..bd585bb0
--- /dev/null
+++ b/examples/27_rtl_text/src/theme.ts
@@ -0,0 +1,76 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { FontManager, Layer, type LayoutNode } from "framefields";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+export const FONTS = path.resolve(HERE, "../assets/fonts");
+export const OUTPUT = path.resolve(HERE, "../output");
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+
+/** Ink on warm paper for the 2D scenes; a dark studio for the 3D one. */
+export const PAPER = "#f2ede4";
+export const INK = "#1b1a17";
+export const MUTED = "#7a746a";
+export const ACCENT = "#c2410c";
+export const TEAL = "#0f766e";
+export const STUDIO = "#111216";
+
+/** Arabic + Latin (the face from the original bug report). */
+export const CAIRO = "Cairo";
+/** Arabic with full vowel marks. */
+export const NASKH = "Noto Naskh Arabic";
+/** Hebrew + Latin. */
+export const RUBIK = "Rubik";
+/** Latin labels. */
+export const SANS = "Inter";
+
+const FACES: Record<string, string> = {
+ [CAIRO]: "Cairo.ttf",
+ [NASKH]: "NotoNaskhArabic.ttf",
+ [RUBIK]: "Rubik.ttf",
+ [SANS]: "Inter.ttf",
+};
+
+export async function registerFonts(): Promise<void> {
+ for (const [family, file] of Object.entries(FACES)) {
+ const source = path.join(FONTS, file);
+ if (!fs.existsSync(source)) {
+ throw new Error(`Missing ${source}. Run \`pnpm fonts\` first.`);
+ }
+ await FontManager.register({ family, source });
+ }
+}
+
+/** A full-frame scene root; `Layer.sequence` sets its start and length. */
+export function scene(id: string, background: string, children: unknown[]) {
+ return Layer.box({
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background,
+ children: children as LayoutNode[],
+ });
+}
+
+/** The small Latin caption naming what a scene shows. */
+export function label(id: string, text: string, color = MUTED) {
+ return Layer.text(text, {
+ id,
+ position: "absolute",
+ x: 0,
+ y: H - 110,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: 28,
+ fill: color,
+ letterSpacing: 0.5,
+ });
+}
diff --git a/examples/27_rtl_text/tsconfig.dev.json b/examples/27_rtl_text/tsconfig.dev.json
new file mode 100644
index 00000000..c5e4355b
--- /dev/null
+++ b/examples/27_rtl_text/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@framefields/**/*"
+ ]
+}
diff --git a/examples/27_rtl_text/tsconfig.json b/examples/27_rtl_text/tsconfig.json
new file mode 100644
index 00000000..999801f9
--- /dev/null
+++ b/examples/27_rtl_text/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "@framefields/tsconfig/base.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "target": "ES2022",
+ "noEmit": true
+ },
+ "include": ["src/**/*"]
+}
diff --git a/packages/framefields/src/shapes3d.ts b/packages/framefields/src/shapes3d.ts
index 63cc2f42..6e479fca 100644
--- a/packages/framefields/src/shapes3d.ts
+++ b/packages/framefields/src/shapes3d.ts
@@ -216,6 +216,12 @@ export interface Text3DOptions extends Surface3DOptions {
scaleY?: number;
scaleZ?: number;
align?: "start" | "center" | "end" | "left" | "right";
+ /**
+ * Base direction: "auto" (default) takes it from the first strong
+ * character, so Arabic and Hebrew read right to left. "start"/"end"
+ * alignment follows it.
+ */
+ direction?: "ltr" | "rtl" | "auto";
verticalAlign?: "top" | "middle" | "bottom";
letterSpacing?: number;
lineHeight?: number;
@@ -792,6 +798,7 @@ export const Layer3D = {
fontStyle: options.fontStyle,
fill: options.fill ?? "#ffffff",
align: (options.align as any) ?? "center",
+ direction: options.direction,
verticalAlign: options.verticalAlign ?? "middle",
letterSpacing: options.letterSpacing,
lineHeight: options.lineHeight,
@@ -844,6 +851,7 @@ export const Layer3D = {
curveSegments: options.curveSegments,
curveTolerance,
align: options.align,
+ direction: options.direction,
verticalAlign: options.verticalAlign,
letterSpacing: options.letterSpacing,
// The mesh's own shading only knows these; glass and the like are
diff --git a/packages/webgpu-renderers/src/renderer3d/text-extruder.test.ts b/packages/webgpu-renderers/src/renderer3d/text-extruder.test.ts
index e86b58a0..7be77df9 100644
--- a/packages/webgpu-renderers/src/renderer3d/text-extruder.test.ts
+++ b/packages/webgpu-renderers/src/renderer3d/text-extruder.test.ts
@@ -203,4 +203,20 @@ describe("Extruded 3D Text Polygonal Mesh Generator", () => {
expect(zNormals(front.normals)).toContain(-1);
expect(zNormals(side.normals).every((z) => z === 0)).toBe(true);
});
+
+ it("aligns start/end by the text's direction", () => {
+ const font = loadInter();
+ const at = (direction: "ltr" | "rtl") =>
+ generateExtrudedTextGeometry({
+ text: "Hi",
+ font,
+ fontSize: 100,
+ depth: 10,
+ align: "start",
+ direction,
+ }).bounds;
+ // Left to right, start is the left edge; right to left, the right edge.
+ expect(at("ltr").minX).toBeCloseTo(0, 5);
+ expect(at("rtl").maxX).toBeCloseTo(0, 5);
+ });
});
diff --git a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts b/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
index 9d9f0dce..f9217d80 100644
--- a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
+++ b/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
@@ -2,6 +2,8 @@ import earcut from "earcut";
import type * as fontkit from "fontkit";
import { Path2D } from "skia-canvas";
import type { Material3D, Mesh3DData, Model3DData } from "../loaders/types.js";
+import type { FontkitFont } from "../slug/slug-generator.js";
+import { shapeLineFromFont } from "../slug/text-shaping.js";
export interface Point2D {
x: number;
@@ -23,8 +25,10 @@ export interface ExtrudedTextGeometryOptions {
* text and tight bowls stay round while straight stems stay cheap.
*/
curveTolerance?: number;
- /** "start"/"end" read as left/right (the text runs left to right) */
+ /** "start"/"end" follow the text direction (left/right for LTR text) */
align?: "left" | "center" | "right" | "start" | "end";
+ /** Base direction; "auto" (default) takes it from the first strong character. */
+ direction?: "ltr" | "rtl" | "auto";
verticalAlign?: "top" | "middle" | "bottom";
letterSpacing?: number;
/** Letter faces: the front cap (toward a default camera, -z) and the back cap */
@@ -472,31 +476,31 @@ export function generateExtrudedTextGeometry(
const unitsPerEm = font.unitsPerEm || 1000;
const scale = fontSize / unitsPerEm;
- const run = font.layout(options.text);
- let cursorX = 0;
+ // Shaped and ordered like 2D text: joining forms, ligatures and marks,
+ // and right-to-left runs laid out right to left.
+ const line = shapeLineFromFont(
+ font as unknown as FontkitFont,
+ options.text.replace(/\n/g, " "),
+ {
+ direction: options.direction,
+ letterSpacing: options.letterSpacing ? options.letterSpacing / scale : 0,
+ },
+ );
const polygons: PolygonHierarchy[] = [];
- for (let i = 0; i < run.glyphs.length; i++) {
- const glyph = run.glyphs[i]!;
- const pos = run.positions[i]!;
- const glyphX = cursorX + (pos.xOffset ?? 0);
- const glyphY = pos.yOffset ?? 0;
-
+ for (const placed of line.glyphs) {
+ const glyph = font.getGlyph(placed.glyphId);
const glyphPolys = glyphPolygonsAt(
font,
glyph,
- glyphX,
- glyphY,
+ placed.x,
+ placed.y,
scale,
flattening,
);
for (const gp of glyphPolys) {
polygons.push(gp);
}
-
- cursorX +=
- (pos.xAdvance ?? glyph.advanceWidth ?? 0) +
- (options.letterSpacing ? options.letterSpacing / scale : 0);
}
let minX = Number.POSITIVE_INFINITY;
@@ -531,10 +535,21 @@ export function generateExtrudedTextGeometry(
const w = maxX - minX;
const h = maxY - minY;
+ // "start"/"end" follow the text's direction.
+ const rtl = (line.baseLevel & 1) === 1;
+ const align =
+ options.align === "start"
+ ? rtl
+ ? "right"
+ : "left"
+ : options.align === "end"
+ ? rtl
+ ? "left"
+ : "right"
+ : options.align;
let alignOffsetX = (minX + maxX) / 2;
- if (options.align === "left" || options.align === "start")
- alignOffsetX = minX;
- if (options.align === "right" || options.align === "end") alignOffsetX = maxX;
+ if (align === "left") alignOffsetX = minX;
+ if (align === "right") alignOffsetX = maxX;
let alignOffsetY = (minY + maxY) / 2;
if (options.verticalAlign === "top") alignOffsetY = minY;
diff --git a/packages/webgpu-renderers/src/slug/text-shaping.ts b/packages/webgpu-renderers/src/slug/text-shaping.ts
index 1a03f772..884c7fe1 100644
--- a/packages/webgpu-renderers/src/slug/text-shaping.ts
+++ b/packages/webgpu-renderers/src/slug/text-shaping.ts
@@ -64,6 +64,8 @@ interface ShapeOptions {
direction?: TextDirection;
/** Optional ligatures (`liga`, `clig`); required ones such as lam-alef always apply. */
ligatures?: boolean;
+ /** Set emoji apart for bitmap drawing (default); false shapes them as glyphs. */
+ emoji?: boolean;
}
const EMOJI_REGEX =
@@ -204,7 +206,7 @@ const SHAPE_CACHE_MAX = 2048;
const shapeCache = new Map<string, RunGlyph[]>();
function resolveShapingSource(font: SlugFont): FontkitFont | null {
- const own = getSlugFontSource(font);
+ const own = getSlugFontSource(font) ?? viewSources.get(font);
if (own) return own;
if (!font.fontFamily) return null;
const parsed = (globalThis as Record<symbol, unknown>)[
@@ -512,7 +514,9 @@ export function shapeParagraph<S extends ShapeStyle>(
const { start, text: gt } = graphemes[g];
for (let k = 0; k < gt.length; k++) graphemeAt[start + k] = g;
}
- const isEmojiGrapheme = graphemes.map((g) => EMOJI_REGEX.test(g.text));
+ const isEmojiGrapheme = graphemes.map(
+ (g) => options.emoji !== false && EMOJI_REGEX.test(g.text),
+ );
// Glyphs per grapheme, and ligature merges (a glyph spanning graphemes).
const glyphsOf: RunGlyph[][] = graphemes.map(() => []);
@@ -615,6 +619,110 @@ export function shapeParagraph<S extends ShapeStyle>(
return { clusters, baseLevel };
}
+// ── Shaping straight from a fontkit font ─────────────────────────────────
+
+/** Glyph-only stand-ins for fontkit fonts that are shaped but never drawn by Slug. */
+const viewSources = new WeakMap<SlugFont, FontkitFont>();
+const fontViews = new WeakMap<FontkitFont, SlugFont>();
+
+/** A glyph map that makes a metrics-only record for any glyph id asked for. */
+class GlyphRecordMap extends Map<number, SlugCodePoint> {
+ constructor(private readonly source: FontkitFont) {
+ super();
+ }
+ override get(id: number): SlugCodePoint | undefined {
+ let record = super.get(id);
+ if (!record) {
+ let advanceWidth = 0;
+ try {
+ advanceWidth = this.source.getGlyph?.(id)?.advanceWidth ?? 0;
+ } catch {
+ advanceWidth = 0;
+ }
+ record = {
+ codePoint: -2,
+ glyphId: id,
+ width: 0,
+ height: 0,
+ advanceWidth,
+ bearingX: 0,
+ bearingY: 0,
+ bandCount: 0,
+ bandDimX: 0,
+ bandDimY: 0,
+ bandsTexCoordX: 0,
+ bandsTexCoordY: 0,
+ };
+ super.set(id, record);
+ }
+ return record;
+ }
+ override has(id: number): boolean {
+ return this.get(id) !== undefined;
+ }
+}
+
+function fontView(source: FontkitFont): SlugFont {
+ let view = fontViews.get(source);
+ if (!view) {
+ const glyphs = new GlyphRecordMap(source);
+ view = {
+ codePoints: new Map([[-1, glyphs.get(0) as SlugCodePoint]]),
+ glyphs,
+ curvesTex: null as unknown as GPUTexture,
+ bandsTex: null as unknown as GPUTexture,
+ ascender: source.ascent || 0,
+ descender: source.descent || 0,
+ lineGap: source.lineGap || 0,
+ unitsPerEm: source.unitsPerEm || 1000,
+ };
+ fontViews.set(source, view);
+ viewSources.set(view, source);
+ }
+ return view;
+}
+
+export interface PositionedGlyph {
+ glyphId: number;
+ /** Pen position, font units from the line's left edge. */
+ x: number;
+ /** Baseline offset, font units, positive up. */
+ y: number;
+}
+
+/**
+ * Shapes and orders one line of text set straight from a fontkit font (for
+ * geometry built from outlines, such as extruded 3D text). Positions are in
+ * font units, left to right; `letterSpacing` is in font units too.
+ */
+export function shapeLineFromFont(
+ source: FontkitFont,
+ text: string,
+ options: ShapeOptions & { letterSpacing?: number } = {},
+): { glyphs: PositionedGlyph[]; width: number; baseLevel: number } {
+ const font = fontView(source);
+ const letterSpacing = options.letterSpacing ?? 0;
+ const p = shapeParagraph(
+ [{ text, style: { font, fontSize: font.unitsPerEm, letterSpacing } }],
+ {
+ direction: options.direction,
+ ligatures: options.ligatures ?? letterSpacing === 0,
+ emoji: false,
+ },
+ );
+ const line = placeLine(p.clusters, p.baseLevel);
+ const glyphs: PositionedGlyph[] = [];
+ let width = 0;
+ for (const { cluster, x } of line.clusters) {
+ width = x + cluster.advance;
+ for (const g of cluster.glyphs) {
+ if (g.cp.glyphId === undefined) continue;
+ glyphs.push({ glyphId: g.cp.glyphId, x: x + g.dx, y: -g.dy });
+ }
+ }
+ return { glyphs, width, baseLevel: p.baseLevel };
+}
+
// ── Lines ────────────────────────────────────────────────────────────────
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7365a1ba..4026adbb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -350,32 +350,7 @@ importers:
specifier: ^4.1.11
- examples/25_bakery:
- dependencies:
- '@framefields/compositions':
- specifier: workspace:*
- version: link:../../packages/compositions
- framefields:
- specifier: workspace:*
- version: link:../../packages/framefields
- mediabunny:
- specifier: ^1.51.0
- version: 1.51.0
- devDependencies:
- '@framefields/tsconfig':
- specifier: workspace:*
- version: link:../../packages/tsconfig
- '@types/node':
- specifier: ^24.1.0
- version: 24.10.14
- tsx:
- specifier: ^4.20.3
- version: 4.21.0
- typescript:
- specifier: ^5.8.3
- version: 5.9.3
-
- examples/26_mac_keyboard:
+ examples/26_mac_keyboard_from_3d_primitives:
dependencies:
framefields:
specifier: workspace:*
@@ -394,7 +369,7 @@ importers:
specifier: ^5.8.3
version: 5.9.3
- examples/26_mac_keyboard_from_3d_primitives:
+ examples/27_rtl_text:
dependencies:
framefields:
specifier: workspace:*