mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
web: embed fonts, catalogs, the icon font and the studio HDR deflated
The web build is under a 24 MiB download budget. Its embedded data is now stored deflated and inflated once at startup: the craft-fonts faces, the translation catalogs, the Phosphor icon font and the studio environment HDR. egui's default faces come from craft-ui's deflated copies instead of egui's default_fonts feature, and the engine's built-in text fonts (Ubuntu Light, Hack) come from the same copies through text_cmds::provide_built_in_fonts. Desktop builds are unchanged.
This commit is contained in:
1 parent
e70e4cbf84
commit
2332602c4e
11 files changed
+298
-30
No files matched your search
Generated
+1
@@ -6172,6 +6172,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"egui_kittest",
|
||||
"flate2",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
|
||||
@@ -18,8 +18,9 @@ texturecraft-engine = { workspace = true }
|
||||
texturecraft-ui-egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. No `default_fonts`: the UI takes egui's faces
|
||||
# from craft-ui's deflated copies (the wasm is under a download budget).
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "persistence"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
|
||||
@@ -18,12 +18,13 @@ texturecraft-paint = { workspace = true }
|
||||
texturecraft-bake = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
epaint_default_fonts = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The built-in text fonts; the web build gets them from the app (`text_cmds::provide_built_in_fonts`).
|
||||
epaint_default_fonts = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies]
|
||||
|
||||
@@ -24,7 +24,38 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
|
||||
/// The built-in fonts' names, in [`provide_built_in_fonts`]'s order.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const BUILT_IN_NAMES: [&str; 2] = ["Ubuntu Light", "Hack"];
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
static BUILT_IN_SOURCE: std::sync::OnceLock<fn() -> [&'static [u8]; 2]> = std::sync::OnceLock::new();
|
||||
|
||||
/// The web build's built-in fonts, Ubuntu Light and Hack, from `source`. The browser app already carries egui's faces
|
||||
/// (deflated, for its download budget), so it says where to get them instead of the engine embedding a second, raw
|
||||
/// copy. `source` runs once, when text first needs a built-in font. Only the first call counts.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn provide_built_in_fonts(source: fn() -> [&'static [u8]; 2]) {
|
||||
let _ = BUILT_IN_SOURCE.set(source);
|
||||
}
|
||||
|
||||
/// The built-in fonts: names and bytes. On the web the bytes are empty without [`provide_built_in_fonts`].
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn built_in() -> [(&'static str, &'static [u8]); 2] {
|
||||
static BYTES: std::sync::OnceLock<[&'static [u8]; 2]> = std::sync::OnceLock::new();
|
||||
let bytes = match BUILT_IN_SOURCE.get() {
|
||||
Some(source) => *BYTES.get_or_init(*source),
|
||||
None => [&[] as &[u8], &[]],
|
||||
};
|
||||
[(BUILT_IN_NAMES[0], bytes[0]), (BUILT_IN_NAMES[1], bytes[1])]
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn built_in() -> [(&'static str, &'static [u8]); 2] {
|
||||
BUILT_IN
|
||||
}
|
||||
|
||||
/// Families tried, in order, when no font is asked for.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
|
||||
@@ -54,7 +85,7 @@ fn fonts() -> Value {
|
||||
let families: Vec<(String, Vec<String>)> = Vec::new();
|
||||
json!({
|
||||
"installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::<Vec<_>>(),
|
||||
"builtIn": BUILT_IN.map(|(name, _)| name),
|
||||
"builtIn": built_in().map(|(name, _)| name),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -62,7 +93,8 @@ fn fonts() -> Value {
|
||||
/// or the first default family installed, else the built-in font.
|
||||
fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> {
|
||||
let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
||||
if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
let built_in = built_in();
|
||||
if let Some((_, bytes)) = built_in.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
return Ok((std::borrow::Cow::Borrowed(bytes), 0));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -91,7 +123,7 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow:
|
||||
let _ = style;
|
||||
match family {
|
||||
Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))),
|
||||
None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)),
|
||||
None => Ok((std::borrow::Cow::Borrowed(built_in[0].1), 0)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ workspace = true
|
||||
chrono = { workspace = true }
|
||||
texturecraft-engine = { workspace = true }
|
||||
texturecraft-render = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] }
|
||||
# egui's default fonts: on desktop from egui; the web build uses craft-ui's deflated copies (`fonts::egui_default_definitions`).
|
||||
eframe = { workspace = true, features = ["wgpu", "persistence"] }
|
||||
egui = { workspace = true }
|
||||
craft-ui = { workspace = true }
|
||||
craft-behavior = { workspace = true }
|
||||
@@ -32,6 +33,7 @@ craft-image-codecs = { workspace = true }
|
||||
|
||||
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
eframe = { workspace = true, features = ["default_fonts"] }
|
||||
sys-locale = "0.3"
|
||||
# Help > Check for Updates and the check at start (updates_ui.rs).
|
||||
craft-update = { workspace = true }
|
||||
@@ -61,12 +63,16 @@ zbus = { version = "5.19", default-features = false, features = ["async-io", "bl
|
||||
# versions craft-libs' craft-fonts-build subsets with).
|
||||
[build-dependencies]
|
||||
craft-i18n = { workspace = true }
|
||||
# The web build embeds its fonts and catalogs deflated (build.rs, `fonts::CraftFont`, `i18n`).
|
||||
flate2 = { workspace = true }
|
||||
skera = "0.8"
|
||||
skrifa = { version = "0.48", default-features = false, features = ["std"] }
|
||||
|
||||
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-zip = { workspace = true }
|
||||
# Inflates the embedded fonts and catalogs of the web build.
|
||||
flate2 = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
@@ -74,6 +80,8 @@ js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# build.rs's `i18n_build.rs`, which tests/i18n_build.rs includes.
|
||||
flate2 = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
|
||||
+40
-1
@@ -33,6 +33,7 @@ type Faces = &'static [(&'static str, &'static str)];
|
||||
|
||||
fn main() {
|
||||
let catalogs = i18n_build::embed();
|
||||
deflate_assets();
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
@@ -94,10 +95,20 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
path = out;
|
||||
}
|
||||
|
||||
// The web build embeds its faces deflated: the wasm is under a download budget and fonts halve.
|
||||
if wasm {
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?;
|
||||
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(".deflate");
|
||||
let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(name);
|
||||
std::fs::write(&deflated, i18n_build::deflate(&bytes)?).map_err(|e| format!("{}: {e}", deflated.display()))?;
|
||||
path = deflated;
|
||||
}
|
||||
|
||||
let scripts: Vec<String> = tags.iter().map(|s| format!("{s:?}")).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},",
|
||||
" CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], data: include_bytes!({:?}), deflated: {wasm} }},",
|
||||
scripts.join(", "),
|
||||
path.display().to_string(),
|
||||
);
|
||||
@@ -156,3 +167,31 @@ fn subset(font: &FontRef, unicodes: &IntSet<u32>) -> Result<Vec<u8>, String> {
|
||||
);
|
||||
subset_font(font, &plan).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The files a web build embeds deflated (the wasm is under a download budget): the icon font and the studio
|
||||
/// environment, from this crate's directory to the name they have under `OUT_DIR` (`name.deflate`). The other builds
|
||||
/// include the files themselves.
|
||||
const DEFLATED_ASSETS: &[(&str, &str)] =
|
||||
&[("../../vendor/egui-phosphor/res/Phosphor.ttf", "Phosphor.ttf"), ("../../assets/hdr/studio_small_09_512.hdr", "studio_small_09_512.hdr")];
|
||||
|
||||
/// Writes [`DEFLATED_ASSETS`] under `OUT_DIR` for the web build.
|
||||
fn deflate_assets() {
|
||||
if !std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32") {
|
||||
return;
|
||||
}
|
||||
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
|
||||
let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
for (source, name) in DEFLATED_ASSETS {
|
||||
let source = manifest.join(source);
|
||||
println!("cargo::rerun-if-changed={}", source.display());
|
||||
let target = out.join(format!("{name}.deflate"));
|
||||
let written = std::fs::read(&source)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|bytes| i18n_build::deflate(&bytes))
|
||||
.and_then(|d| std::fs::write(&target, d).map_err(|e| e.to_string()));
|
||||
if let Err(e) = written {
|
||||
println!("cargo::error={}: {e}", source.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,62 @@ use std::path::Path;
|
||||
|
||||
/// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts
|
||||
/// its CJK interface face to those characters.
|
||||
#[allow(dead_code)] // used by tests/i18n_build.rs, not by build.rs
|
||||
pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>), String> {
|
||||
let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n");
|
||||
collect_into(dir, required, None)
|
||||
}
|
||||
|
||||
/// `bytes` deflated (raw deflate, as `flate2::read::DeflateDecoder` reads it).
|
||||
pub fn deflate(bytes: &[u8]) -> Result<Vec<u8>, String> {
|
||||
use std::io::Write as _;
|
||||
let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::best());
|
||||
encoder.write_all(bytes).map_err(|e| e.to_string())?;
|
||||
encoder.finish().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// What the generated source does with the catalogs' text. A web build downloads the wasm, so it embeds each catalog
|
||||
/// deflated (written under `out`) and inflates all of them on first use; other builds embed the text itself.
|
||||
const INFLATE_FN: &str = r#"
|
||||
fn inflate_text(deflated: &[u8]) -> &'static str {
|
||||
use std::io::Read as _;
|
||||
let mut text = String::new();
|
||||
// A catalog that does not inflate leaves its language without translations, never a panic.
|
||||
if flate2::read::DeflateDecoder::new(deflated).take(64 << 20).read_to_string(&mut text).is_err() {
|
||||
text.clear();
|
||||
}
|
||||
Box::leak(text.into_boxed_str())
|
||||
}
|
||||
|
||||
pub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {
|
||||
static CATALOGS: std::sync::OnceLock<&'static craft_i18n::Embedded> = std::sync::OnceLock::new();
|
||||
CATALOGS.get_or_init(|| {
|
||||
let catalogs: Vec<(&'static str, &'static str, &'static str)> =
|
||||
CRAFT_I18N_DEFLATED.iter().map(|&(locale, common, app)| (locale, inflate_text(common), inflate_text(app))).collect();
|
||||
Box::leak(catalogs.into_boxed_slice())
|
||||
})
|
||||
}
|
||||
"#;
|
||||
|
||||
/// [`collect`], embedding the catalogs deflated under the directory `deflated_in` when it is given.
|
||||
pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Path>) -> Result<(String, Vec<char>), String> {
|
||||
let mut source = match deflated_in {
|
||||
Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"),
|
||||
None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"),
|
||||
};
|
||||
let close = |mut source: String| {
|
||||
source.push_str("];\n");
|
||||
source.push_str(if deflated_in.is_some() {
|
||||
INFLATE_FN
|
||||
} else {
|
||||
"\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n"
|
||||
});
|
||||
source
|
||||
};
|
||||
let Some(dir) = dir else {
|
||||
if required {
|
||||
return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into());
|
||||
}
|
||||
source.push_str("];\n");
|
||||
return Ok((source, Vec::new()));
|
||||
return Ok((close(source), Vec::new()));
|
||||
};
|
||||
|
||||
if !dir.is_absolute() {
|
||||
@@ -48,10 +96,19 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
let name = file.to_str().ok_or("non-UTF-8 catalog path")?;
|
||||
println!("cargo::rerun-if-changed={name}");
|
||||
|
||||
let include = match deflated_in {
|
||||
Some(out) => {
|
||||
let copy = out.join(format!("{locale}.{}.deflate", file.file_stem().and_then(|n| n.to_str()).unwrap_or("catalog")));
|
||||
std::fs::write(©, deflate(text.as_bytes())?).map_err(|e| format!("{}: {e}", copy.display()))?;
|
||||
format!("include_bytes!({:?})", copy.display().to_string())
|
||||
}
|
||||
None => format!("include_str!({name:?})"),
|
||||
};
|
||||
// The shared runtime needs static inputs for this short-lived build process
|
||||
Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str())))
|
||||
Ok((include, Box::leak(text.into_boxed_str())))
|
||||
};
|
||||
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") };
|
||||
let empty = if deflated_in.is_some() { "&[]" } else { "\"\"" };
|
||||
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { (empty.into(), "") };
|
||||
let (app, app_text) = embed(&app)?;
|
||||
characters.extend(shared_text.chars().chain(app_text.chars()));
|
||||
let code: &'static str = Box::leak(locale.to_owned().into_boxed_str());
|
||||
@@ -70,10 +127,9 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; ")));
|
||||
}
|
||||
|
||||
source.push_str("];\n");
|
||||
characters.sort_unstable();
|
||||
characters.dedup();
|
||||
Ok((source, characters))
|
||||
Ok((close(source), characters))
|
||||
}
|
||||
|
||||
/// Write the embedding for both desktop and wasm, reporting optional failures as warnings.
|
||||
@@ -86,7 +142,9 @@ pub fn embed() -> Vec<char> {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED");
|
||||
let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from);
|
||||
let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1");
|
||||
let (source, characters) = match collect(dir.as_deref(), required) {
|
||||
let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let (source, characters) = match collect_into(dir.as_deref(), required, wasm.then_some(out_dir.as_path())) {
|
||||
Ok(embedded) => embedded,
|
||||
Err(error) => {
|
||||
if required {
|
||||
@@ -94,13 +152,22 @@ pub fn embed() -> Vec<char> {
|
||||
} else {
|
||||
println!("cargo::warning=building without craft-i18n: {error}");
|
||||
}
|
||||
("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new())
|
||||
(empty_embedding(wasm), Vec::new())
|
||||
}
|
||||
};
|
||||
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs");
|
||||
let out = out_dir.join("craft_i18n.rs");
|
||||
if let Err(error) = std::fs::write(&out, source) {
|
||||
println!("cargo::error=writing {}: {error}", out.display());
|
||||
}
|
||||
characters
|
||||
}
|
||||
|
||||
/// The embedding of a build without catalogs.
|
||||
fn empty_embedding(deflated: bool) -> String {
|
||||
if deflated {
|
||||
format!("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[];\n{INFLATE_FN}")
|
||||
} else {
|
||||
"pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n".into()
|
||||
}
|
||||
}
|
||||
+101
-3
@@ -23,11 +23,109 @@ pub struct CraftFont {
|
||||
pub style: &'static str,
|
||||
/// ISO 15924 scripts the font is for, e.g. `"Jpan"`.
|
||||
pub scripts: &'static [&'static str],
|
||||
pub bytes: &'static [u8],
|
||||
/// The font file; deflated in a web build, where the data is part of the download (see `deflated`).
|
||||
data: &'static [u8],
|
||||
deflated: bool,
|
||||
}
|
||||
|
||||
impl CraftFont {
|
||||
/// Whether this build carries no data for the font.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
/// The font file's bytes: borrowed as embedded, or inflated from the web build's copy. Data that does not inflate
|
||||
/// gives no bytes (the font is left out), never a panic.
|
||||
pub fn bytes(&self) -> std::borrow::Cow<'static, [u8]> {
|
||||
if self.deflated { std::borrow::Cow::Owned(inflate(self.data)) } else { std::borrow::Cow::Borrowed(self.data) }
|
||||
}
|
||||
|
||||
/// The font as egui takes it, without copying an embedded one.
|
||||
pub fn font_data(&self) -> FontData {
|
||||
match self.bytes() {
|
||||
std::borrow::Cow::Borrowed(bytes) => FontData::from_static(bytes),
|
||||
std::borrow::Cow::Owned(bytes) => FontData::from_owned(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
|
||||
/// Inflates a font the web build embeds deflated. Empty when the data does not inflate.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn inflate(deflated: &[u8]) -> Vec<u8> {
|
||||
use std::io::Read as _;
|
||||
// The largest face is under 1 MB; the bound keeps corrupt data from growing without limit.
|
||||
const MAX_INFLATED_BYTES: u64 = 64 << 20;
|
||||
let mut out = Vec::new();
|
||||
match flate2::read::DeflateDecoder::new(deflated).take(MAX_INFLATED_BYTES + 1).read_to_end(&mut out) {
|
||||
Ok(_) if out.len() as u64 <= MAX_INFLATED_BYTES => out,
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the Phosphor icon font to `fonts`: the font itself on desktop, the web build's deflated copy there (the icon
|
||||
/// font is half a megabyte of the download). Icons draw as missing-glyph boxes if the copy does not inflate.
|
||||
pub(crate) fn add_icon_font(fonts: &mut egui::FontDefinitions) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
egui_phosphor::add_to_fonts(fonts, egui_phosphor::Variant::Regular);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
static PHOSPHOR: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new();
|
||||
let bytes = PHOSPHOR.get_or_init(|| Vec::leak(inflate(include_bytes!(concat!(env!("OUT_DIR"), "/Phosphor.ttf.deflate")))));
|
||||
if bytes.is_empty() {
|
||||
log::warn!("the icon font did not inflate; icons show as boxes");
|
||||
} else {
|
||||
egui_phosphor::add_font_bytes_to_fonts(fonts, "phosphor", bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// egui's default fonts (Hack, Ubuntu Light and egui's icons, in egui's family order). The web build takes them from
|
||||
/// craft-ui's deflated copies instead of egui's `default_fonts` feature, which would embed a second, raw copy, and it
|
||||
/// hands the engine its built-in text fonts from the same copies.
|
||||
pub(crate) fn egui_default_definitions() -> egui::FontDefinitions {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
egui::FontDefinitions::default()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
texturecraft_engine::text_cmds::provide_built_in_fonts(engine_fonts);
|
||||
let mut fonts = craft_ui::fonts::deflated_default_definitions();
|
||||
// craft-ui's Inter: TextureCraft adds its own (`theme::font_definitions`) and its own semibold family.
|
||||
for name in ["Inter-Regular", "Inter-SemiBold"] {
|
||||
fonts.font_data.remove(name);
|
||||
}
|
||||
fonts.families.remove(&FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()));
|
||||
let known: Vec<String> = fonts.font_data.keys().cloned().collect();
|
||||
for list in fonts.families.values_mut() {
|
||||
list.retain(|name| known.contains(name));
|
||||
}
|
||||
fonts
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's built-in text fonts, Ubuntu Light and Hack, copied once from the deflated defaults. Empty when a face
|
||||
/// is unavailable (the text command then reports the font as unusable).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn engine_fonts() -> [&'static [u8]; 2] {
|
||||
let fonts = craft_ui::fonts::deflated_default_definitions();
|
||||
let face = |name: &str| -> &'static [u8] {
|
||||
match fonts.font_data.get(name) {
|
||||
Some(data) => Vec::leak((*data.font).as_ref().to_vec()),
|
||||
None => &[],
|
||||
}
|
||||
};
|
||||
[face("Ubuntu-Light"), face("Hack")]
|
||||
}
|
||||
|
||||
/// Only the web build embeds deflated data.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn inflate(_deflated: &[u8]) -> Vec<u8> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Skip absurdly large files (a corrupt or non-font path must not eat memory).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
@@ -186,8 +284,8 @@ impl UiFonts {
|
||||
|
||||
/// The first available font for `script`: craft-fonts' (embedded), then the system's.
|
||||
fn load(script: Script) -> Option<FontData> {
|
||||
if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.bytes.is_empty()) {
|
||||
return Some(aligned(FontData::from_static(f.bytes)));
|
||||
if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.is_empty()) {
|
||||
return Some(aligned(f.font_data()));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for (path, index) in script.system_files() {
|
||||
|
||||
@@ -9,7 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs"));
|
||||
|
||||
static I18N: LazyLock<craft_i18n::I18n> = LazyLock::new(|| {
|
||||
let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect();
|
||||
let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered);
|
||||
let (i18n, problems) = craft_i18n::I18n::new(craft_i18n_catalogs(), &offered);
|
||||
for problem in problems {
|
||||
log::warn!("translation catalog: {problem}");
|
||||
}
|
||||
@@ -377,7 +377,7 @@ mod tests",
|
||||
let keys = keys();
|
||||
assert!(keys.len() > 300, "found only {} keys", keys.len());
|
||||
let used: BTreeSet<_> = keys.iter().map(String::as_str).collect();
|
||||
for &(locale, common, app) in CRAFT_I18N {
|
||||
for &(locale, common, app) in craft_i18n_catalogs() {
|
||||
let Some(lang) = I18N.from_code(locale) else { continue };
|
||||
let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect();
|
||||
|
||||
|
||||
@@ -7,7 +7,11 @@ use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_render::ibl::{self, EnvImage};
|
||||
|
||||
/// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/hdr/studio_small_09_512.hdr");
|
||||
/// The same file deflated by build.rs: the web build's wasm is under a download budget
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const STUDIO_HDR_DEFLATED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/studio_small_09_512.hdr.deflate"));
|
||||
|
||||
/// Prefiltered levels from mirror (0) to fully rough (last)
|
||||
const LEVELS: u32 = 6;
|
||||
@@ -15,6 +19,23 @@ const LEVELS: u32 = 6;
|
||||
/// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left
|
||||
const TURN: f32 = 4.4;
|
||||
|
||||
/// The bundled file's bytes
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn studio_hdr() -> std::borrow::Cow<'static, [u8]> {
|
||||
std::borrow::Cow::Borrowed(STUDIO_HDR)
|
||||
}
|
||||
|
||||
/// The bundled file's bytes, inflated; none if the copy does not inflate (the studio falls back)
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn studio_hdr() -> std::borrow::Cow<'static, [u8]> {
|
||||
use std::io::Read as _;
|
||||
let mut out = Vec::new();
|
||||
match flate2::read::DeflateDecoder::new(STUDIO_HDR_DEFLATED).take(64 << 20).read_to_end(&mut out) {
|
||||
Ok(_) => std::borrow::Cow::Owned(out),
|
||||
Err(_) => std::borrow::Cow::Owned(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The prefiltered studio
|
||||
pub(crate) struct OrbEnvironment {
|
||||
/// Level `l` holds reflections for roughness `l / (LEVELS - 1)`
|
||||
@@ -27,7 +48,7 @@ impl OrbEnvironment {
|
||||
/// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release)
|
||||
pub(crate) fn get() -> &'static OrbEnvironment {
|
||||
static STUDIO: OnceLock<OrbEnvironment> = OnceLock::new();
|
||||
STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback))
|
||||
STUDIO.get_or_init(|| OrbEnvironment::from_hdr(&studio_hdr()).unwrap_or_else(OrbEnvironment::fallback))
|
||||
}
|
||||
|
||||
fn from_hdr(bytes: &[u8]) -> Option<OrbEnvironment> {
|
||||
|
||||
@@ -301,20 +301,20 @@ pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18);
|
||||
/// adds CJK).
|
||||
pub fn font_definitions() -> egui::FontDefinitions {
|
||||
use std::sync::Arc;
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.bytes.is_empty());
|
||||
let mut fonts = crate::fonts::egui_default_definitions();
|
||||
let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.is_empty());
|
||||
// Inter is drawn a little under its size, as in VectorCraft: its letters are wide.
|
||||
let inter = |bytes: &'static [u8]| Arc::new(egui::FontData::from_static(bytes).tweak(egui::FontTweak { scale: 0.92, ..Default::default() }));
|
||||
let inter = |face: &crate::fonts::CraftFont| Arc::new(face.font_data().tweak(egui::FontTweak { scale: 0.92, ..Default::default() }));
|
||||
let mut semibold = None;
|
||||
if let (Some(regular), Some(bold)) = (face("Regular"), face("SemiBold")) {
|
||||
fonts.font_data.insert("inter".into(), inter(regular.bytes));
|
||||
fonts.font_data.insert("inter-semibold".into(), inter(bold.bytes));
|
||||
fonts.font_data.insert("inter".into(), inter(regular));
|
||||
fonts.font_data.insert("inter-semibold".into(), inter(bold));
|
||||
if let Some(list) = fonts.families.get_mut(&FontFamily::Proportional) {
|
||||
list.insert(0, "inter".into());
|
||||
}
|
||||
semibold = Some("inter-semibold");
|
||||
}
|
||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||
crate::fonts::add_icon_font(&mut fonts);
|
||||
// The semibold family: the regular family with its first face swapped for the weight.
|
||||
let mut list = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
if let (Some(w), Some(first)) = (semibold, list.first_mut()) {
|
||||
|
||||
Reference in new issue
Block a user