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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
FC0a: ui/text/font_atlas_debug passes (0.99966): bevy_text's glyph atlas in raea's TSX. raea/ui's FontAtlasSet.atlases(font, font_size, text) is the pages a Text of that text fills, made natively by bevy_text's own code (the fonts.atlases call, raea-sys-fonts atlas.rs: the text shaped in the face as bevy_text shapes it, each glyph its layout meets rasterized by swash and packed by add_glyph_to_atlas, 2 px padding, 512 px pages), each a PNG data: URL an ImageNode shows. The port grows the yellow FiraSans-Bold text every third frame from the example's ChaCha8Rng (rand's random::<u8>() as char: "a6Ò" and a control character by frame 10, drawn as .notdef in both) and shows the page beside it a frame after it's made: the atlas's packing, Ò's base and accent as two glyphs, matches Bevy's. The bar fails 7 of the 10 mutants; of the 3 it passes, the off-pixel probe catches the atlas size (1552 against 680) and its top (1353), and a probe of the text's fully yellow pixels its colour (0 against 1680); the tenth (dropping the repeat check) draws the same three characters by frame 10. runtime/calls tests/fonts.rs (atlases: one page, a glyph met twice packed once).
shinyobjectza800f3cfa5f4
diff --git a/Cargo.lock b/Cargo.lockindex 692b497b..22931658 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14669,6 +14669,7 @@ dependencies = ["raea-io-net","raea-native","raea-runtime-plugins",+ "raea-sys-fonts","raea-sys-mix","raea-sys-ml","raea-sys-speech",@@ -15183,6 +15184,7 @@ dependencies = ["parley","raea-io-net","serde_json",+ "swash","wuff",]diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.listindex 01d80fb5..bde813c6 100644--- a/bench/bevy-parity/examples.list+++ b/bench/bevy-parity/examples.list@@ -111,3 +111,4 @@ ui/text/multiple_text_inputsui/text/text_inputui/ui_materialui/text/system_fonts+ui/text/font_atlas_debugdiff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsvindex 02438e3a..b46b2882 100644--- a/bench/bevy-parity/runs.tsv+++ b/bench/bevy-parity/runs.tsv@@ -110,3 +110,4 @@ ui/text/multiple_text_inputs - 10ui/text/text_input - 10ui/ui_material - 10ui/text/system_fonts - 10+ui/text/font_atlas_debug - 10diff --git a/docs/bevy-parity.md b/docs/bevy-parity.mdindex 8442431e..de88bb4d 100644--- a/docs/bevy-parity.md+++ b/docs/bevy-parity.md@@ -4,7 +4,7 @@ Bevy v0.20.0's examples against their raea TSX ports (docs/control.feature FC0a)don't edit. An example passes when every probed frame passes pixels (SSIM 0.98 and no 32 px tile off by more than 24 of 255) and cost (batch keys andframe time at most 1.25x the example's). Wall time is one machine's, measured in the same run.-Examples: **438**, ported **111**, passing **108**, excluded **16** (docs/bevy-parity/excluded.tsv), left **314**.+Examples: **438**, ported **112**, passing **109**, excluded **16** (docs/bevy-parity/excluded.tsv), left **313**.raea's frame ms is its update's plus the time React takes to step a frame for its 3D (step), which the exampledoesn't pay.@@ -167,6 +167,7 @@ doesn't pay.| ui/text/text_input | 10 | 0.999094 | 12 | 0 / 0 | 448 / 500 | 5 / 7 | 1 / 1 | 47.628 / 2.481 = 2.481 + 0 | yes | || ui/ui_material | 10 | 0.999993 | 0 | 0 / 0 | 446 / 502 | 5 / 7 | 1 / 1 | 47.158 / 2.603 = 2.603 + 0 | yes | || ui/text/system_fonts | 10 | 0.987943 | 18 | 0 / 0 | 1992 / 500 | 5 / 7 | 1 / 1 | 108.413 / 3.042 = 3.042 + 0 | yes | |+| ui/text/font_atlas_debug | 10 | 0.999660 | 6 | 0 / 0 | 445 / 500 | 5 / 7 | 1 / 1 | 43.233 / 2.397 = 2.397 + 0 | yes | |## Excludeddiff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonlindex 1ba723be..a17727ab 100644--- a/docs/bevy-parity/results.jsonl+++ b/docs/bevy-parity/results.jsonl@@ -154,3 +154,4 @@{"example":"ui/text/text_input","frame":10,"ssim":0.999094,"tile":12,"bevy":{"batch_keys":0,"entities":448,"extents":[],"frame":10,"frame_ms":47.628,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.481,"step_ms":null,"cost_ms":2.481},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}{"example":"ui/ui_material","frame":10,"ssim":0.999993,"tile":0,"bevy":{"batch_keys":0,"entities":446,"extents":[],"frame":10,"frame_ms":47.158,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":502,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.603,"step_ms":null,"cost_ms":2.603},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}{"example":"ui/text/system_fonts","frame":10,"ssim":0.987943,"tile":18,"bevy":{"batch_keys":0,"entities":1992,"extents":[],"frame":10,"frame_ms":108.413,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.042,"step_ms":null,"cost_ms":3.042},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"ui/text/font_atlas_debug","frame":10,"ssim":0.999660,"tile":6,"bevy":{"batch_keys":0,"entities":445,"extents":[],"frame":10,"frame_ms":43.233,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.397,"step_ms":null,"cost_ms":2.397},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}diff --git a/runtime/calls/Cargo.toml b/runtime/calls/Cargo.tomlindex a48b07a8..da2c9893 100644--- a/runtime/calls/Cargo.toml+++ b/runtime/calls/Cargo.toml@@ -19,6 +19,7 @@ raea-core-scene = { path = "../../core/scene" }raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }raea-io-net = { path = "../../io/net" }raea-sys-mix = { path = "../../systems/mix" }+raea-sys-fonts = { path = "../../systems/fonts" }raea-sys-ml = { path = "../../systems/ml", optional = true }raea-sys-speech = { path = "../../systems/speech", optional = true }bevy = { version = "=0.20.0", default-features = false, features = ["std"] }diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex 24e6eb1f..6e225937 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -170,6 +170,7 @@ 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.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),}@@ -208,6 +209,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.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"),("media.read", "{ path: string; start: number; end: number }", "string", "bytes start..end of a file, base64"),@@ -299,3 +301,21 @@ fn families() -> Vec<String> {out.dedup();out}++/// bevy_text's atlas pages for `text` in the font file `font` (an asset path: staticFile's /media/x) at `size` px+/// (raea-sys-fonts atlas.rs), each a PNG data: URL.+fn font_atlases(v: &Value) -> R<Value> {+ use base64::Engine as _;+ let bytes = std::fs::read(asset_path(s(v, "font")?)?).map_err(|e| format!("fonts.atlases: {e}"))?;+ let size = v.get("size").and_then(Value::as_f64).ok_or("fonts.atlases: size in px")? as f32;+ let pages = raea_sys_fonts::atlas::atlases(bytes, size, s(v, "text")?)?;+ let mut out = Vec::new();+ for (w, h, rgba) in pages {+ let img = image::RgbaImage::from_raw(w, h, rgba).ok_or("an atlas page's pixels don't fill it")?;+ let mut png = std::io::Cursor::new(Vec::new());+ img.write_to(&mut png, image::ImageFormat::Png).map_err(|e| e.to_string())?;+ let src = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(png.into_inner()));+ out.push(serde_json::json!({ "width": w, "height": h, "src": src }));+ }+ Ok(out.into())+}diff --git a/runtime/calls/tests/fonts.rs b/runtime/calls/tests/fonts.rsindex 51407984..c95f8cba 100644--- a/runtime/calls/tests/fonts.rs+++ b/runtime/calls/tests/fonts.rs@@ -9,3 +9,24 @@ fn families_are_the_systems_sorted_and_each_once() {#[cfg(target_vendor = "apple")]assert!(names.contains(&"Helvetica"), "no Helvetica among {} families", names.len());}++/// fonts.atlases (Bevy's ui/text/font_atlas_debug): one 512 px page for a few glyphs, a glyph met twice packed once,+/// and a larger size filling more of it+#[test]+fn atlases_are_bevy_texts_pages() {+ let font = concat!(env!("CARGO_MANIFEST_DIR"), "/../../engine/rune/media/assets/Inter-Regular.ttf");+ let ink = |size: f64, text: &str| -> (usize, u64) {+ let v = raea_runtime_calls::call("fonts.atlases", &serde_json::json!({ "font": font, "size": size, "text": text })).unwrap();+ let pages = v.as_array().unwrap();+ let png = pages[0]["src"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();+ use base64::Engine as _;+ let img = image::load_from_memory(&base64::engine::general_purpose::STANDARD.decode(png).unwrap()).unwrap().to_rgba8();+ assert_eq!((pages[0]["width"].as_u64(), img.width()), (Some(512), 512));+ (pages.len(), img.pixels().map(|p| p.0[3] as u64).sum())+ };+ let (n, ab) = ink(50.0, "ab");+ assert_eq!(n, 1);+ assert!(ab > 0);+ assert_eq!(ink(50.0, "abab").1, ab, "a glyph met again is packed once");+ assert!(ink(80.0, "ab").1 > ab);+}diff --git a/sdk/raea/bench/bevy-parity/ui/text/font_atlas_debug.tsx b/sdk/raea/bench/bevy-parity/ui/text/font_atlas_debug.tsxnew file mode 100644index 00000000..b51fd128--- /dev/null+++ b/sdk/raea/bench/bevy-parity/ui/text/font_atlas_debug.tsx@@ -0,0 +1,45 @@+// Bevy v0.20.0 examples/ui/text/font_atlas_debug.rs in raea's TSX (docs/control.feature FC0a): a yellow Text in+// FiraSans-Bold at 50 px at the window's bottom left, which every 0.05 s (each third frame at 1/60 s: the Timer's+// 50 ms reached at 50.000001) takes a character from the example's ChaCha8Rng (seed 19878367467713, rand's+// random::<u8>() as char: Latin-1, a control character too) when it hasn't it yet; and over the black clear colour at+// the top left, side by side, the pages of bevy_text's glyph atlas that text fills (FontAtlasSet, natively by+// bevy_text's own code), one more each frame while there are more than shown (the atlas_render_system, which runs a+// frame after the text first fills one). Bevy's Camera2d is the layered <Canvas3D>, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Canvas3D } from "raea/3d";+import { Srgba } from "raea/color";+import { FontAtlasSet, ImageNode, Node, Text, px } from "raea/ui";+import { ChaCha8Rng } from "../../../../../../bench/bevy-parity/lib/rand";++const FONT = staticFile("fonts/FiraSans-Bold.ttf");+const YELLOW = new Srgba(1, 1, 0);++/** the Text's string after `f` updates: the Timer finishes on every third */+function textAt(f: number): string {+ const rng = ChaCha8Rng.seed_from_u64(19878367467713n);+ let s = "a";+ for (let k = 3; k <= f; k += 3) {+ const c = String.fromCharCode(rng.next_u32() & 0xff);+ if (!s.includes(c)) s += c;+ }+ return s;+}++function Shot() {+ const f = useCurrentFrame();+ const text = textAt(f);+ const atlases = FontAtlasSet.atlases(FONT, 50, text);+ // the pages the atlas_render_system has spawned by now: one an update, from the update after the first text layout+ const shown = atlases.slice(0, Math.max(0, f - 1));+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(0, 0, 0)" />+ <Node position_type="Absolute" bottom={px(0)}>+ <Text font={FONT} font_size={{ Px: 50 }} color={YELLOW}>{text}</Text>+ </Node>+ {shown.map((a, i) => <ImageNode key={i} image={a.texture} position_type="Absolute" top={px(0)} left={px(a.width * i)} />)}+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.tsindex 148377e9..e94458b4 100644--- a/sdk/raea/src/native-calls.ts+++ b/sdk/raea/src/native-calls.ts@@ -72,6 +72,8 @@ export interface NativeCalls {"ecs.set": { args: { world: number; id: number; cols: Record<string, number | string | boolean> }; answer: null };/** a new entity: a kind with columns, and/or any components */"ecs.spawn": { args: { world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }; answer: { id: number } };+ /** 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 */+ "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[] };/** drop an engine frame */diff --git a/sdk/raea/src/ui.ts b/sdk/raea/src/ui.tsindex b3279044..7d89c99e 100644--- a/sdk/raea/src/ui.ts+++ b/sdk/raea/src/ui.ts@@ -8,7 +8,7 @@ export * from "@raea/video/panel";// bevy_ui's Node and Text, and bevy_text's TextSpan, with their values (Val, UiRect, BorderRadius, Overflow)export { Node, GhostNode, Text, TextSpan, TextShadow, Text2d, UiScale, Viewport, UiTargetCamera, UiTexture, targetImage, ImageNode, InlineImage, type TextureSlicer, type SliceScaleMode, ImagePlugin, FontVariationTag, TextureAtlasLayout, type ImageNodeProps, px, percent, vw, vh, vmin, vmax, auto, UiRect, BorderRadius, CornerRadius, Overflow, OverflowClipMargin, type NodeProps, type TextProps, type TextStyleProps, type TextRunProps, type Text2dProps, type Val } from "@raea/render/bevy3d";export { LinearGradient, RadialGradient, ConicGradient, ColorStop, AngularColorStop, UiPosition, type Gradient, type RadialGradientShape, type InterpolationColorSpace } from "@raea/render/bevy3d";-export { GridTrack, RepeatedGridTrack, GridPlacement, type GridTrackRepetition, type GridAutoFlow, type MinTrackSizingFunction, type MaxTrackSizingFunction, FontCx, FontSource, type GenericFontFamily } from "@raea/render/bevy3d";+export { GridTrack, RepeatedGridTrack, GridPlacement, type GridTrackRepetition, type GridAutoFlow, type MinTrackSizingFunction, type MaxTrackSizingFunction, FontAtlasSet, type FontAtlas, FontCx, FontSource, type GenericFontFamily } from "@raea/render/bevy3d";export { Rot2, Val2, UiTransform, BoxShadow, BoxShadowSamples, type ShadowStyle } from "@raea/render/bevy3d";export { MaterialNode, type MaterialNodeProps } from "@raea/render/bevy3d";export { FontFeatureTag, FontWidth } from "@raea/render/bevy3d";diff --git a/sdk/render/src/bevy3d.tsx b/sdk/render/src/bevy3d.tsxindex 4abe3ecf..6dcbb804 100644--- a/sdk/render/src/bevy3d.tsx+++ b/sdk/render/src/bevy3d.tsx@@ -41,4 +41,4 @@ export { FontFeatureTag, FontWidth } from "./bevy3d/ui-features";export { GlobalUiDebugOptions, type UiDebugOptions } from "./bevy3d/ui-debug";export type { IgnoreScroll } from "./bevy3d/ui-scroll";export { Scrollbar, ScrollbarThumb, type ScrollbarProps, type ScrollbarThumbProps, type ControlOrientation } from "./bevy3d/ui-scrollbar";-export { FontCx, FontSource, type GenericFontFamily } from "./bevy3d/ui-font";+export { FontAtlasSet, type FontAtlas, FontCx, FontSource, type GenericFontFamily } from "./bevy3d/ui-font";diff --git a/sdk/render/src/bevy3d/ui-font.ts b/sdk/render/src/bevy3d/ui-font.tsindex aba254ef..dbac1eb9 100644--- a/sdk/render/src/bevy3d/ui-font.ts+++ b/sdk/render/src/bevy3d/ui-font.ts@@ -47,3 +47,21 @@ export function fontCss(who: string, font: FontSource | undefined): { family: stexport const FontCx = {family_names: (): string[] => native("fonts.families", {}),};++/** One page of bevy_text's glyph atlas: its texture (a PNG data: URL, which an ImageNode shows) and its size.+ * @bevy bevy_text::FontAtlas */+export interface FontAtlas {+ texture: string;+ width: number;+ height: number;+}++/** bevy_text's FontAtlasSet, the glyph atlases Bevy's text is drawn from, for one face at one size:+ * `atlases(font, font_size, text)` is the pages a Text of `text` in the font file `font` at `font_size` px fills,+ * each glyph rasterized and packed by bevy_text's own code (natively) in the order its layout meets them. A text that+ * grows a character at a time fills them as its last version does.+ * @bevy bevy_text::FontAtlasSet */+export const FontAtlasSet = {+ atlases: (font: string, font_size: number, text: string): FontAtlas[] =>+ native("fonts.atlases", { font, size: font_size, text }).map((a) => ({ texture: a.src, width: a.width, height: a.height })),+};diff --git a/sdk/skills/raea/reference/sdk.md b/sdk/skills/raea/reference/sdk.mdindex 9b2752ff..1f056505 100644--- a/sdk/skills/raea/reference/sdk.md+++ b/sdk/skills/raea/reference/sdk.md@@ -103,7 +103,7 @@ with a capital, hooks with `use`. A component's props are in its file.## `raea/ui` (sdk/raea/src/ui.ts)-`AbsoluteFill`, `AngularColorStop`, `BorderRadius`, `BoxShadow`, `BoxShadowSamples`, `ColorStop`, `ConicGradient`, `CornerRadius`, `EditableText`, `FontCx`, `FontFeatureTag`, `FontSource`, `FontVariationTag`, `FontWidth`, `GhostNode`, `GlobalUiDebugOptions`, `GridPlacement`, `GridTrack`, `ImageNode`, `ImagePlugin`, `InlineImage`, `LinearGradient`, `MaterialNode`, `Node`, `Overflow`, `OverflowClipMargin`, `RadialGradient`, `RepeatedGridTrack`, `Rot2`, `Scrollbar`, `ScrollbarThumb`, `Text`, `Text2d`, `TextShadow`, `TextSpan`, `TextureAtlasLayout`, `UiPosition`, `UiRect`, `UiScale`, `UiTargetCamera`, `UiTexture`, `UiTransform`, `Val2`, `Viewport`, `auto`, `percent`, `px`, `targetImage`, `vh`, `vmax`, `vmin`, `vw`+`AbsoluteFill`, `AngularColorStop`, `BorderRadius`, `BoxShadow`, `BoxShadowSamples`, `ColorStop`, `ConicGradient`, `CornerRadius`, `EditableText`, `FontAtlasSet`, `FontCx`, `FontFeatureTag`, `FontSource`, `FontVariationTag`, `FontWidth`, `GhostNode`, `GlobalUiDebugOptions`, `GridPlacement`, `GridTrack`, `ImageNode`, `ImagePlugin`, `InlineImage`, `LinearGradient`, `MaterialNode`, `Node`, `Overflow`, `OverflowClipMargin`, `RadialGradient`, `RepeatedGridTrack`, `Rot2`, `Scrollbar`, `ScrollbarThumb`, `Text`, `Text2d`, `TextShadow`, `TextSpan`, `TextureAtlasLayout`, `UiPosition`, `UiRect`, `UiScale`, `UiTargetCamera`, `UiTexture`, `UiTransform`, `Val2`, `Viewport`, `auto`, `percent`, `px`, `targetImage`, `vh`, `vmax`, `vmin`, `vw`## `raea/video` (sdk/raea/src/video.ts)diff --git a/systems/fonts/Cargo.toml b/systems/fonts/Cargo.tomlindex adcfdb71..00924d47 100644--- a/systems/fonts/Cargo.toml+++ b/systems/fonts/Cargo.toml@@ -16,6 +16,8 @@ serde_json = "1"# the bundled faces (fonts.rs): one parley font context, Blitz's parley (B0d)parley = { version = "=0.12.0", default-features = false, features = ["std"] }wuff = "0.2"+# bevy_text's glyph rasterizer, for its atlases (atlas.rs)+swash = "=0.2.10"[dev-dependencies]bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_core_pipeline", "bevy_log", "png", "bevy_window"] }diff --git a/systems/fonts/src/atlas.rs b/systems/fonts/src/atlas.rsnew file mode 100644index 00000000..c1d02e5a--- /dev/null+++ b/systems/fonts/src/atlas.rs@@ -0,0 +1,63 @@+//! bevy_text's glyph atlases for a text (Bevy's ui/text/font_atlas_debug shows them): the text shaped in one face at+//! one size as bevy_text shapes it, and each glyph its layout meets, in order, rasterized and packed by bevy_text's own+//! `add_glyph_to_atlas` (swash's alpha mask, 2 px padding, 512 px pages and up), as Bevy's FontAtlasSet holds them for+//! that face and size. Hinting off and smoothing on, Bevy's defaults.++use bevy::asset::Assets;+use bevy::image::Image;+use bevy::text::{FontSmoothing, GlyphCacheKey, add_glyph_to_atlas, get_glyph_atlas_info};+use parley::fontique::Blob;+use parley::{FontContext, LayoutContext, PositionedLayoutItem, StyleProperty};++/// Each atlas page bevy_text fills for `text` in the face `font` (a font file's bytes) at `size` px: its width, height+/// and RGBA (Rgba8UnormSrgb: white, the glyphs' coverage in alpha), in the order the pages were made. Glyphs from a+/// face other than `font` (a fallback's) are in that face's own atlases in Bevy, and left out here.+pub fn atlases(font: Vec<u8>, size: f32, text: &str) -> Result<Vec<(u32, u32, Vec<u8>)>, String> {+ let mut cx = FontContext::default();+ let blob = Blob::from(font);+ let blob_id = blob.id();+ let families = cx.collection.register_fonts(blob, None);+ let family = families.first().ok_or("the font file has no face")?.0;+ let name = cx.collection.family_name(family).ok_or("the font's family has no name")?.to_string();+ let mut lcx = LayoutContext::<()>::new();+ let mut b = lcx.ranged_builder(&mut cx, text, 1.0, true);+ b.push_default(StyleProperty::FontFamily(parley::FontFamily::Single(parley::FontFamilyName::Named(name.into()))));+ b.push_default(StyleProperty::FontSize(size));+ let mut layout = b.build(text);+ layout.break_all_lines(None);++ let mut textures = Assets::<Image>::default();+ let mut pages = Vec::new();+ let mut scale = swash::scale::ScaleContext::new();+ for line in layout.lines() {+ for item in line.items() {+ let PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };+ let run = glyph_run.run();+ let face = run.font();+ if face.data.id() != blob_id {+ continue;+ }+ let font_ref = swash::FontRef::from_index(face.data.as_ref(), face.index as usize).ok_or("swash can't read the face")?;+ let mut scaler = scale+ .builder_with_id(font_ref, [face.data.id(), face.index.into()])+ .size(run.font_size())+ .hint(false)+ .normalized_coords(run.normalized_coords().iter().map(|c| c.to_bits()))+ .build();+ for glyph in glyph_run.positioned_glyphs() {+ let Ok(glyph_id) = u16::try_from(glyph.id) else { continue };+ if get_glyph_atlas_info(&mut pages, GlyphCacheKey { glyph_id }).is_some() {+ continue;+ }+ add_glyph_to_atlas(&mut pages, &mut textures, &mut scaler, FontSmoothing::AntiAliased, glyph_id).map_err(|e| format!("glyph {glyph_id}: {e}"))?;+ }+ }+ }+ pages+ .iter()+ .map(|p| {+ let image = textures.get(&p.texture).ok_or("an atlas page's texture is gone")?;+ Ok((image.width(), image.height(), image.data.clone().ok_or("an atlas page has no pixels")?))+ })+ .collect()+}diff --git a/systems/fonts/src/lib.rs b/systems/fonts/src/lib.rsindex 41dd590a..da12ce02 100644--- a/systems/fonts/src/lib.rs+++ b/systems/fonts/src/lib.rs@@ -6,6 +6,8 @@pub mod google;/// fontique's own generic families under names of their own, for bevy_ui's generic FontSourcespub mod bevy_generics;+/// bevy_text's glyph atlases for a text, as Bevy's FontAtlasSet holds them (the fonts.atlases native call)+pub mod atlas;use std::collections::HashMap;use std::path::{Path, PathBuf};