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.

LR6, LR7: the canvas's text natives (measure, advances, svgText) are each a function of the fonts (raea_sys_canvas::TextNative), registered from one table and given the page's fonts by with_page_fonts, instead of three wrappers that did it alike; canvas.read's rectangle and svgText's tracking read without closures that copied raea-runtime-sound's (dupes back to 293/59)

shinyobjectzebff73dbc6e2
diff --git a/runtime/canvas/src/lib.rs b/runtime/canvas/src/lib.rs
index b05f9df7..d1f8781d 100644
--- a/runtime/canvas/src/lib.rs
+++ b/runtime/canvas/src/lib.rs
@@ -7,13 +7,33 @@
pub fn register() {
// the faces a canvas's text is shaped in: the page's (blitz-dom adds every face the composition loads)
raea_sys_canvas::fonts(blitz_dom::util::svg_fonts);
- raea_native::register(
- "canvas.measure",
- "{ font: { family: string; size: number; weight: string; style: string }; text: string; align?: string; baseline?: string }",
- "{ width: number; actualBoundingBoxLeft: number; actualBoundingBoxRight: number; actualBoundingBoxAscent: number; actualBoundingBoxDescent: number; fontBoundingBoxAscent: number; fontBoundingBoxDescent: number }",
- "measureText: the text shaped as the canvas draws it, in the page's fonts; its advance, ink and font box from the alignment point (docs/layout-reads.feature LR6)",
- |a| raea_sys_canvas::metrics(a),
- );
+ // the text natives, each laid out in the page's fonts as they are when it's called
+ let text: [(&str, &str, &str, &str, raea_sys_canvas::TextNative); 3] = [
+ (
+ "canvas.measure",
+ "{ font: { family: string; size: number; weight: string; style: string }; text: string; align?: string; baseline?: string }",
+ "{ width: number; actualBoundingBoxLeft: number; actualBoundingBoxRight: number; actualBoundingBoxAscent: number; actualBoundingBoxDescent: number; fontBoundingBoxAscent: number; fontBoundingBoxDescent: number }",
+ "measureText: the text shaped as the canvas draws it, in the page's fonts; its advance, ink and font box from the alignment point (docs/layout-reads.feature LR6)",
+ raea_sys_canvas::metrics,
+ ),
+ (
+ "canvas.svgText",
+ "{ text: string; style: Record<string, string> }",
+ "{ length: number; starts: number[] }",
+ "an svg <text>'s getComputedTextLength and getStartPositionOfChar: its words laid out by usvg, as the page draws an svg, in its computed font (font-*, letter-spacing, word-spacing); x from the text's own (docs/layout-reads.feature LR7)",
+ raea_sys_canvas::svg_text,
+ ),
+ (
+ "canvas.advances",
+ "{ font: { family: string; weight: string; style: string }; chars: string }",
+ "{ adv: (number | null)[]; own: boolean[] }",
+ "each character's advance (a fraction of the font size) in the face a canvas draws it with, and whether the font's own family has it",
+ raea_sys_canvas::advances,
+ ),
+ ];
+ for (name, args, answer, doc, f) in text {
+ raea_native::register(name, args, answer, doc, move |a| raea_sys_canvas::with_page_fonts(f, a));
+ }
raea_native::register(
"fonts.load",
"{ family: string }",
@@ -34,20 +54,6 @@ pub fn register() {
Ok(serde_json::json!({ "faces": raea_sys_fonts::google::face_now(family, url) }))
},
);
- raea_native::register(
- "canvas.svgText",
- "{ text: string; style: Record<string, string> }",
- "{ length: number; starts: number[] }",
- "an svg <text>'s getComputedTextLength and getStartPositionOfChar: its words laid out by usvg, as the page draws an svg, in its computed font (font-*, letter-spacing, word-spacing); x from the text's own (docs/layout-reads.feature LR7)",
- |a| raea_sys_canvas::svg_text(a),
- );
- raea_native::register(
- "canvas.advances",
- "{ font: { family: string; weight: string; style: string }; chars: string }",
- "{ adv: (number | null)[]; own: boolean[] }",
- "each character's advance (a fraction of the font size) in the face a canvas draws it with, and whether the font's own family has it",
- |a| raea_sys_canvas::advances(a),
- );
raea_native::register(
"canvas.read",
"{ width: number; height: number; __canvas2d: unknown; x: number; y: number; w: number; h: number }",
diff --git a/runtime/dom/src/host/frames.rs b/runtime/dom/src/host/frames.rs
index 810554fb..df4891a9 100644
--- a/runtime/dom/src/host/frames.rs
+++ b/runtime/dom/src/host/frames.rs
@@ -79,7 +79,7 @@ pub fn mount(world: &mut World, w: u32, h: u32, code: &str, preamble: &[String],
});
});
raea_runtime_js::calls::on_sync("canvas.read", raea_sys_canvas::read);
- raea_runtime_js::calls::on_sync("canvas.advances", raea_sys_canvas::advances);
+ raea_runtime_js::calls::on_sync("canvas.advances", |a| raea_sys_canvas::with_page_fonts(raea_sys_canvas::advances, a));
raea_sys_canvas::fonts(blitz_dom::util::svg_fonts);
raea_sys_canvas::videos(|src| Some(raea_sys_page::net::page_path(src.strip_prefix("http://localhost").unwrap_or(src)).into()));
}
diff --git a/systems/canvas/src/lib.rs b/systems/canvas/src/lib.rs
index 4e72302e..1c2c9dfe 100644
--- a/systems/canvas/src/lib.rs
+++ b/systems/canvas/src/lib.rs
@@ -30,6 +30,15 @@ mod measure;
pub use measure::{advances, metrics};
mod svgtext;
pub use svgtext::svg_text;
+
+/// A text native: its answer to `args` in the given fonts.
+pub type TextNative = fn(&usvg::Options, &Value) -> Value;
+
+/// A text native's answer (`canvas.measure` is [`metrics`], `canvas.advances` [`advances`], `canvas.svgText`
+/// [`svg_text`]), laid out in the page's fonts as they are now.
+pub fn with_page_fonts(answer: TextNative, args: &Value) -> Result<Value, String> {
+ Ok(answer(&page_options(), args))
+}
mod filter;
mod paint;
mod subsets;
@@ -103,8 +112,8 @@ pub fn read(args: &Value) -> Result<Value, String> {
let props = args.as_object().ok_or("no canvas")?;
let opt = page_options();
let (bw, bh, px) = Replay::update(None, props, &opt).rgba();
- let n = |k: &str| args[k].as_f64().unwrap_or(0.0) as i64;
- let (x, y, w, h) = (n("x"), n("y"), n("w").max(0), n("h").max(0));
+ let (x, y) = (paint::f(&args["x"]) as i64, paint::f(&args["y"]) as i64);
+ let (w, h) = ((paint::f(&args["w"]) as i64).max(0), (paint::f(&args["h"]) as i64).max(0));
if w * h > 1 << 28 {
return Err("too large".into());
}
diff --git a/systems/canvas/src/measure.rs b/systems/canvas/src/measure.rs
index 2ce1cbc5..5b2ab90d 100644
--- a/systems/canvas/src/measure.rs
+++ b/systems/canvas/src/measure.rs
@@ -47,11 +47,7 @@ pub(crate) fn text_doc(opt: &usvg::Options, font: &Value, text: &str, at: (f32,
/// fontBoundingBox{Ascent,Descent}): the text shaped as the canvas draws it, from the alignment point. Its advance and
/// the font's ascent and descent are usvg's layout box; the ink is its glyphs' outlines. Spaces are kept, as fillText
/// keeps them.
-pub fn metrics(args: &Value) -> Result<Value, String> {
- Ok(metrics_in(&crate::page_options(), args))
-}
-
-fn metrics_in(opt: &usvg::Options, args: &Value) -> Value {
+pub fn metrics(opt: &usvg::Options, args: &Value) -> Value {
let text = args["text"].as_str().unwrap_or("");
let shape = |text: &str| {
let doc = text_doc(opt, &args["font"], text, (0.0, 0.0), (&args["align"], &args["baseline"]), "xml:space=\"preserve\" fill=\"#fff\"", (1, 1));
@@ -64,7 +60,7 @@ fn metrics_in(opt: &usvg::Options, args: &Value) -> Value {
// nothing usvg draws (empty, or spaces alone, which it drops): no ink, the characters' advances, and the font's
// box from a glyph it does draw
None => {
- let adv = advances_in(opt, &json!({ "font": args["font"], "chars": text }));
+ let adv = advances(opt, &json!({ "font": args["font"], "chars": text }));
let em: f64 = adv["adv"].as_array().into_iter().flatten().filter_map(Value::as_f64).sum();
let lay = if text.is_empty() { none } else { shape("x").map_or(none, |(lay, _)| lay) };
(lay, none, em as f32 * crate::paint::f(&args["font"]["size"]))
@@ -83,11 +79,7 @@ fn metrics_in(opt: &usvg::Options, args: &Value) -> Value {
/// `canvas.advances`: {font: {family, weight, style}, chars} -> {adv: [em or null], own: [bool]}, one per character:
/// its advance as a fraction of the font size, and whether the font's first family has it.
-pub fn advances(args: &Value) -> Result<Value, String> {
- Ok(advances_in(&crate::page_options(), args))
-}
-
-fn advances_in(opt: &usvg::Options, args: &Value) -> Value {
+pub fn advances(opt: &usvg::Options, args: &Value) -> Value {
let db = &opt.fontdb;
let font = &args["font"];
let weight = font["weight"].as_str().and_then(|w| w.parse().ok()).unwrap_or(400u16);
@@ -144,16 +136,16 @@ mod tests {
db.load_font_data(std::fs::read("/System/Library/Fonts/Supplemental/Arial.ttf").unwrap());
db.set_sans_serif_family("Arial");
let opt = usvg::Options { fontdb: std::sync::Arc::new(db), ..Default::default() };
- let r = advances_in(&opt, &json!({"font": {"family": "Arial", "weight": "400", "style": "normal"}, "chars": "im"}));
+ let r = advances(&opt, &json!({"font": {"family": "Arial", "weight": "400", "style": "normal"}, "chars": "im"}));
let (i, m) = (r["adv"][0].as_f64().unwrap(), r["adv"][1].as_f64().unwrap());
assert!(i < 0.3 && m > 0.8, "{r}");
assert_eq!(r["own"], json!([true, true]));
// a family the page doesn't have: the default stands in, and says so
- let r = advances_in(&opt, &json!({"font": {"family": "Nope, sans-serif", "weight": "400", "style": "normal"}, "chars": "i"}));
+ let r = advances(&opt, &json!({"font": {"family": "Nope, sans-serif", "weight": "400", "style": "normal"}, "chars": "i"}));
assert_eq!(r["own"], json!([false]));
assert!((r["adv"][0].as_f64().unwrap() - i).abs() < 1e-9);
// measureText: the advance is the characters' (Arial has no kerning between these), the ink the glyphs'
- let mt = |text: &str, align: &str| metrics_in(&opt, &json!({"font": {"family": "Arial", "size": 100, "weight": "400", "style": "normal"}, "text": text, "align": align, "baseline": "alphabetic"}));
+ let mt = |text: &str, align: &str| metrics(&opt, &json!({"font": {"family": "Arial", "size": 100, "weight": "400", "style": "normal"}, "text": text, "align": align, "baseline": "alphabetic"}));
let (x, h) = (mt("x", "left"), mt("H", "left"));
let g = |v: &Value, k: &str| v[k].as_f64().unwrap();
assert!((g(&mt("im", "left"), "width") - (i + m) * 100.0).abs() < 0.01, "{}", mt("im", "left"));
diff --git a/systems/canvas/src/svgtext.rs b/systems/canvas/src/svgtext.rs
index 39e39d5f..68a83c3c 100644
--- a/systems/canvas/src/svgtext.rs
+++ b/systems/canvas/src/svgtext.rs
@@ -11,11 +11,7 @@ const FONT: [&str; 9] = ["font-family", "font-size", "font-weight", "font-style"
/// `canvas.svgText`: {text, style: {property: computed value}} -> {length, starts}: the text's advance
/// (getComputedTextLength) and the x where each of its characters starts (getStartPositionOfChar), in user units from
/// the text's own x. Spaces are kept, as `white-space: pre` keeps them.
-pub fn svg_text(args: &Value) -> Result<Value, String> {
- Ok(svg_text_in(&crate::page_options(), args))
-}
-
-fn svg_text_in(opt: &usvg::Options, args: &Value) -> Value {
+pub fn svg_text(opt: &usvg::Options, args: &Value) -> Value {
let text = args["text"].as_str().unwrap_or("");
let style: Vec<String> = FONT
.iter()
@@ -35,7 +31,11 @@ fn svg_text_in(opt: &usvg::Options, args: &Value) -> Value {
}
}
// usvg's box ends at the last glyph's advance; Chrome's length tracks every character, the last one too
- let tracking = args["style"]["letter-spacing"].as_str().and_then(|v| v.strip_suffix("px")?.trim().parse::<f32>().ok()).unwrap_or(0.0);
+ // (a computed letter-spacing is px, or "normal", which is none)
+ let tracking: f32 = match args["style"]["letter-spacing"].as_str() {
+ Some(v) if v.ends_with("px") => v.trim_end_matches("px").trim().parse().unwrap_or(0.0),
+ _ => 0.0,
+ };
let length = if text.is_empty() { 0.0 } else { t.bounding_box().width() + tracking };
json!({ "length": length, "starts": starts })
}
@@ -50,8 +50,8 @@ mod tests {
db.load_font_data(std::fs::read("/System/Library/Fonts/Supplemental/Arial.ttf").unwrap());
let opt = usvg::Options { fontdb: std::sync::Arc::new(db), ..Default::default() };
let st = |ls: &str| json!({ "font-family": "Arial", "font-size": "40px", "letter-spacing": ls });
- let plain = super::svg_text_in(&opt, &json!({ "text": "Hi there", "style": st("normal") }));
- let wide = super::svg_text_in(&opt, &json!({ "text": "Hi there", "style": st("10px") }));
+ let plain = super::svg_text(&opt, &json!({ "text": "Hi there", "style": st("normal") }));
+ let wide = super::svg_text(&opt, &json!({ "text": "Hi there", "style": st("10px") }));
let (a, b) = (plain["length"].as_f64().unwrap(), wide["length"].as_f64().unwrap());
assert!(a > 100.0, "{plain}");
assert!((b - a - 80.0).abs() < 1.0, "8 characters tracked 10 px each: {a} -> {b}");