Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea/text loadFont: a composition asks for a Google Fonts family by name and the page gets it (part of #13)

shinyobjectzac39b671ee4d
diff --git a/bench/load-font/check.sh b/bench/load-font/check.sh
new file mode 100755
index 00000000..53e58d34
--- /dev/null
+++ b/bench/load-font/check.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# raea/text loadFont: a composition that asks for a Google Fonts family by name gets it, as a stylesheet link gets it
+# in Chrome (#13: snapcn's components load theirs by name). "Hello raea" in Rubik Mono One, a
+# family no Mac has: with loadFont its frame must differ from the same text without it (which falls back as it did),
+# and a second render offline (RAEA_OFFLINE=1, from raea's URL cache) must match the first exactly. The first render
+# needs the network (fonts.googleapis.com). Exits 1 on a failure.
+# bench/load-font/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
+cd "$(dirname "$0")/../.." || exit 2
+BIN=${RAEA_BIN:-$PWD/target/release/raea}
+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-load-font.XXXXXX")
+export RAEA_CACHE=$OUT/cache
+trap 'rm -rf "$OUT"' EXIT
+comp() { # NAME LINES
+ cat > "$OUT/$1.tsx" <<TSX
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+$2
+const Shot = () => (
+ <AbsoluteFill style={{ backgroundColor: "#fff", color: "#000", fontFamily, fontSize: 64, padding: 20 }}>Hello raea</AbsoluteFill>
+);
+registerRoot(() => <Composition id="f" component={Shot} width={640} height={160} fps={30} durationInFrames={1} />);
+TSX
+}
+frame() { # NAME OUT
+ "$BIN" render "$OUT/$1.tsx" -o "$OUT/$2.mp4" > "$OUT/$2.log" 2>&1 || { echo "FAIL $2: the render failed"; sed 's/^/ /' "$OUT/$2.log" | tail -6; exit 1; }
+ ffmpeg -loglevel error -i "$OUT/$2.mp4" -frames:v 1 -y "$OUT/$2.png" || { echo "FAIL $2: no frame"; exit 1; }
+}
+comp on 'import { loadFont } from "raea/text";
+const { fontFamily } = loadFont("Rubik Mono One");'
+comp off 'const fontFamily = "Rubik Mono One";'
+frame on on
+frame off off
+RAEA_OFFLINE=1 frame on again
+status=0
+diff=$(magick compare -metric AE "$OUT/on.png" "$OUT/off.png" null: 2>&1 | cut -d' ' -f1)
+(( ${diff%.*} > 1000 )) && echo "ok loadFont changes the text's face ($diff px differ)" || { echo "FAIL loadFont: only $diff px differ from the fallback"; status=1; }
+same=$(magick compare -metric AE "$OUT/on.png" "$OUT/again.png" null: 2>&1 | cut -d' ' -f1)
+[ "${same%.*}" = 0 ] && echo "ok offline, from the cache: the same frame" || { echo "FAIL offline: $same px differ"; status=1; }
+[ $status = 0 ] && echo "PASS loadFont"
+exit $status
diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rs
index 6e225937..35a2138b 100644
--- a/runtime/calls/src/lib.rs
+++ b/runtime/calls/src/lib.rs
@@ -170,6 +170,11 @@ pub fn call(name: &str, v: &Value) -> R<Value> {
// placement by relations (raea-core-place)
"place.solve" => raea_core_place::solve_json(v),
"fonts.families" => Ok(families().into()),
+ "fonts.google" => {
+ let family = s(v, "family")?;
+ raea_sys_fonts::google::want(&family);
+ Ok(json!({ "family": family }))
+ }
"fonts.atlases" => font_atlases(v),
n if n.starts_with("solid.") || n.starts_with("section.") => solid::call(&mut st, n, v),
n => media::call(&mut st, n, v),
@@ -209,6 +214,7 @@ pub fn register() {
("solid.free", "{ id: number }", "null", "drop a solid"),
("place.solve", "{ objects: { id: string; size: [number, number, number]; at?: [number, number, number]; yaw?: number; fixed?: boolean }[]; rules: Record<string, string | number>[]; room?: { min: [number, number]; max: [number, number] } }", "{ objects: { id: string; at: [number, number, number]; yaw: number; size: [number, number, number] }[]; found: { part: string; check: string; level: string; says: string }[]; errors: number }", "boxes placed by relations (on, against, beside, near, apart, facing, align, clear), what can't hold found"),
("fonts.families", "{}", "string[]", "the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them"),
+ ("fonts.google", "{ family: string }", "{ family: string }", "a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont)"),
("fonts.atlases", "{ font: string; size: number; text: string }", "{ width: number; height: number; src: string }[]", "bevy_text's glyph atlases for a text in a font file at a size px, each page a PNG data: URL, as Bevy's FontAtlasSet holds them"),
("media.live", "{}", "{ vdecs: number; vencs: number; adecs: number; frames: number; solids: number; worlds: number }", "how many native coders, frames, solids and worlds are alive (for leak checks)"),
("media.size", "{ path: string }", "number", "a file's size in bytes"),
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index e94458b4..a20980f1 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -76,6 +76,8 @@ export interface NativeCalls {
"fonts.atlases": { args: { font: string; size: number; text: string }; answer: { width: number; height: number; src: string }[] };
/** the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them */
"fonts.families": { args: {}; answer: string[] };
+ /** a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont) */
+ "fonts.google": { args: { family: string }; answer: { family: string } };
/** drop an engine frame */
"frame.free": { args: { frame: number }; answer: null };
/** an engine frame's size */
diff --git a/sdk/raea/src/text.ts b/sdk/raea/src/text.ts
index 6e2a9a15..94880f04 100644
--- a/sdk/raea/src/text.ts
+++ b/sdk/raea/src/text.ts
@@ -3,3 +3,4 @@
// raea/text (bevy_text): text in the world, and time anchored to the words said.
export { Text3D, RichText, Span, type Text3DProps, type RichTextProps, type SpanProps, type GlyphInfo, type GlyphStyle } from "./3d";
export * from "@raea/video/words";
+export { loadFont } from "@raea/video/fonts";
diff --git a/sdk/skills/raea/reference/sdk.md b/sdk/skills/raea/reference/sdk.md
index 1f056505..48e3c649 100644
--- a/sdk/skills/raea/reference/sdk.md
+++ b/sdk/skills/raea/reference/sdk.md
@@ -91,7 +91,7 @@ with a capital, hooks with `use`. A component's props are in its file.
## `raea/text` (sdk/raea/src/text.ts)
-`RichText`, `Span`, `Text3D`
+`RichText`, `Span`, `Text3D`, `loadFont`
## `raea/time` (sdk/raea/src/time.ts)
diff --git a/sdk/video/package.json b/sdk/video/package.json
index bbc48001..58ad11e0 100644
--- a/sdk/video/package.json
+++ b/sdk/video/package.json
@@ -19,7 +19,8 @@
"./codecs": "./src/codecs.ts",
"./arena": "./src/arena.tsx",
"./input-region": "./src/input-region.tsx",
- "./css": "./src/css.ts"
+ "./css": "./src/css.ts",
+ "./fonts": "./src/fonts.ts"
},
"peerDependencies": { "react": "19.2.0" }
}
diff --git a/sdk/video/src/fonts.ts b/sdk/video/src/fonts.ts
new file mode 100644
index 00000000..99c55030
--- /dev/null
+++ b/sdk/video/src/fonts.ts
@@ -0,0 +1,26 @@
+// loadFont (raea/text): a Google Fonts family for the page, as a stylesheet <link> loads it in Chrome. Inside raea the
+// page fetches the family's Latin faces (each weight and style Google has) once, through raea's URL cache
+// (raea-sys-fonts google.rs), so a render stays a function of its code and plays offline once cached. Families
+// nobody asked for aren't fetched: Chrome loads only what a page links (RAEA_PAGE_GOOGLE_FONTS=1 fetches every family
+// a page names). In a browser it links Google's stylesheet, so the same code shows the same family there.
+import { hasNative, native } from "@raea/app/native";
+
+// every weight, upright and italic: Google answers with the ones the family has (as google.rs asks)
+const WEIGHTS = "100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i";
+const asked = new Set<string>();
+
+/** The page gets Google Fonts' `family` ("Inter", "Space Grotesk"); `fontFamily` is the name to style text with. */
+export function loadFont(family: string): { fontFamily: string } {
+ const name = family.trim();
+ if (!name || asked.has(name)) return { fontFamily: name };
+ asked.add(name);
+ if (hasNative()) {
+ native("fonts.google", { family: name });
+ } else if (typeof document !== "undefined" && document.head) {
+ const link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.href = `https://fonts.googleapis.com/css?family=${encodeURIComponent(name).replace(/%20/g, "+")}:${WEIGHTS}&display=block`;
+ document.head.appendChild(link);
+ }
+ return { fontFamily: name };
+}
diff --git a/systems/fonts/src/google.rs b/systems/fonts/src/google.rs
index 78247ca3..6a0f38d5 100644
--- a/systems/fonts/src/google.rs
+++ b/systems/fonts/src/google.rs
@@ -23,17 +23,41 @@ static FAMILIES: Mutex<Option<HashMap<String, Faces>>> = Mutex::new(None);
/// Every weight, upright and italic: Google's CSS API answers with the ones the family has
const WEIGHTS: &str = "100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i";
-/// RAEA_PAGE_GOOGLE_FONTS=1 turns it on (off by default: Chrome loads only what a page links)
-pub fn enabled() -> bool {
+/// Families a composition asked for by name (raea/text loadFont, the `fonts.google` call), as a stylesheet link
+/// asks Chrome for them: fetched whatever RAEA_PAGE_GOOGLE_FONTS says, and only these when it's off
+static WANTED: Mutex<Vec<String>> = Mutex::new(Vec::new());
+
+/// RAEA_PAGE_GOOGLE_FONTS=1: every family a page names (off by default: Chrome loads only what a page links)
+fn every() -> bool {
static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| std::env::var("RAEA_PAGE_GOOGLE_FONTS").as_deref() == Ok("1"));
*ON
}
+/// `family` wanted from Google Fonts (case aside), as a page that links its stylesheet wants it
+pub fn want(family: &str) {
+ let mut w = WANTED.lock().unwrap();
+ if !w.iter().any(|f| f.eq_ignore_ascii_case(family)) {
+ w.push(family.to_string());
+ }
+}
+
+fn wanted(family: &str) -> bool {
+ every() || WANTED.lock().unwrap().iter().any(|f| f.eq_ignore_ascii_case(family))
+}
+
+/// Whether a page looks for missing families at all: RAEA_PAGE_GOOGLE_FONTS=1, or a family asked for by name
+pub fn enabled() -> bool {
+ every() || !WANTED.lock().unwrap().is_empty()
+}
+
/// Gives `doc` the faces of each family its elements name that it has none of and Google Fonts has; true when one
/// was given (its text is laid out again).
pub fn load_missing(doc: &mut BaseDocument) -> bool {
let mut loaded = false;
for family in doc.missing_font_families() {
+ if !wanted(&family) {
+ continue;
+ }
let faces = FAMILIES.lock().unwrap().get_or_insert_default().get(&family).cloned();
let faces = faces.unwrap_or_else(|| {
let found = Arc::new(fetch(&family));
diff --git a/systems/page/src/lib.rs b/systems/page/src/lib.rs
index c7ded21c..ad84dfc7 100644
--- a/systems/page/src/lib.rs
+++ b/systems/page/src/lib.rs
@@ -158,7 +158,8 @@ pub fn resolve(mut docs: NonSendMut<Docs>, pages: Query<(Entity, &Page)>, time:
let t0 = std::time::Instant::now();
doc.resolve(at);
// families it names that no face here has, from Google Fonts by name (raea-sys-fonts google.rs), looked for when its
- // nodes change: the second resolve below lays its text out in them. Only with RAEA_PAGE_GOOGLE_FONTS=1: Chrome
+ // nodes change: the second resolve below lays its text out in them. Only those raea/text loadFont asked for (or
+ // every one with RAEA_PAGE_GOOGLE_FONTS=1): Chrome
// loads only what a page links, so a family that isn't installed falls back there (ui-parity's p12 cases name
// Inter, and so does every composition's root through sdk/react)
if raea_sys_fonts::google::enabled() && scanned.insert(e, doc.tree().len()) != Some(doc.tree().len()) && raea_sys_fonts::google::load_missing(doc) {