diff --git a/Cargo.lock b/Cargo.lock index 44dd9c59..85393071 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13956,6 +13956,18 @@ dependencies = [ "winit", ] +[[package]] +name = "raea-app-playable" +version = "0.1.0" +dependencies = [ + "dunce", + "raea-io-home", + "raea-runtime-bundle", + "regex", + "serde_json", + "zip", +] + [[package]] name = "raea-app-registry" version = "0.1.0" @@ -14240,6 +14252,7 @@ name = "raea-bundle" version = "0.1.0" dependencies = [ "anyhow", + "base64 0.22.1", "dunce", "lightningcss", "oxc", @@ -14292,6 +14305,7 @@ dependencies = [ "raea-app-media", "raea-app-notes", "raea-app-play", + "raea-app-playable", "raea-app-scene", "raea-app-solid", "raea-app-sound", diff --git a/Cargo.toml b/Cargo.toml index d6a26193..87068116 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -239,6 +239,7 @@ members = [ "apps/capcut", "apps/layers", "apps/play", + "apps/playable", "tools/sdk-props", "tools/hands-audit", ] diff --git a/apps/playable/Cargo.toml b/apps/playable/Cargo.toml new file mode 100644 index 00000000..24d127b6 --- /dev/null +++ b/apps/playable/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "raea-app-playable" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)" + +[dependencies] +dunce = "1" +# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process) +raea-runtime-bundle = { path = "../../runtime/bundle" } +# where raea's files are: an install's share/raea, else this checkout +raea-io-home = { path = "../../io/home" } +regex = "1" +serde_json = "1" +zip = { version = "9", default-features = false, features = ["deflate-flate2"] } diff --git a/apps/playable/src/lib.rs b/apps/playable/src/lib.rs new file mode 100644 index 00000000..83459f5b --- /dev/null +++ b/apps/playable/src/lib.rs @@ -0,0 +1,102 @@ +//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX +//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with +//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried +//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap. +mod lint; +mod pages; + +use std::path::{Path, PathBuf}; + +type R = Result; + +pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]"; +pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad"; + +/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own +pub(crate) use raea_runtime_bundle::spec; + +fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str) +} + +/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add three@0.185.0`), +/// else the copy beside sdk/playable or sdk/r3f in raea's own files +fn three_dir(game: &Path, home: &Path) -> R { + let mut d = game.parent(); + while let Some(dir) = d { + if dir.join("node_modules/three/package.json").is_file() { + return Ok(dir.to_path_buf()); + } + d = dir.parent(); + } + ["sdk/playable", "sdk/r3f"] + .iter() + .map(|p| home.join(p)) + .find(|d| d.join("node_modules/three/package.json").is_file()) + .ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add three@0.185.0` in it".into()) +} + +/// The game and the host in one minified script that carries its files +fn bundle(game: &Path, home: &Path) -> R { + let host = home.join("sdk/playable/src/host/main.tsx"); + if !host.is_file() { + return Err(format!("{}: raea's playable host isn't there", host.display())); + } + let three = three_dir(game, home)?; + let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id())); + let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host)); + let alias = format!("three/={}", three.display()); + let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]); + let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string())); + let _ = std::fs::remove_file(&out); + js +} + +pub fn cli(args: &[String]) -> R { + let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?; + let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?; + let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?); + let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec()); + if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) { + return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", "))); + } + let orientation = flag(args, "--orientation").unwrap_or("both"); + if !["portrait", "landscape", "both"].contains(&orientation) { + return Err("--orientation is portrait, landscape or both".into()); + } + let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string(); + let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string(); + let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string(); + + let mut report = Vec::new(); + let found = lint::lint(&game)?; + report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") })); + for c in &found.comps { + let shape = if c.height > c.width { "portrait" } else { "landscape" }; + report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0))); + } + report.extend(found.notes.iter().map(|n| format!("note: {n}"))); + if !found.refusals.is_empty() { + // the reasons first: the CLI marks an error's first line REFUSED + let mut why = found.refusals.clone(); + why.extend(report); + return Err(why.join("\n")); + } + + let js = bundle(&game, &raea_io_home::home())?; + std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + let mut over = false; + for net in networks { + let script = format!("{}\n{js}", pages::preamble(net, &store, &card)); + let w = pages::write(net, &name, &script, &out, orientation)?; + let ok = w.bytes <= pages::CAP; + over |= !ok; + report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" })); + } + if over { + report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024)); + return Err(report.join("\n")); + } + report.push(format!("APPLIED {name} exported as a playable to {}", out.display())); + Ok(report.join("\n")) +} diff --git a/apps/playable/src/lint.rs b/apps/playable/src/lint.rs new file mode 100644 index 00000000..84a05d19 --- /dev/null +++ b/apps/playable/src/lint.rs @@ -0,0 +1,104 @@ +//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files +//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts, +//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw. +use super::R; +use serde_json::Value; +use std::path::Path; + +/// One composition the game registers +pub struct Comp { + pub id: String, + pub width: u32, + pub height: u32, + pub fps: f64, + pub frames: u64, +} + +/// What the lint found: refusals stop the export, notes don't +pub struct Found { + pub comps: Vec, + pub kinds: Vec, + pub notes: Vec, + pub refusals: Vec, +} + +const SOURCE_RULES: &[(&str, &str)] = &[ + (r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"), + (r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"), + (r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"), + (r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"), + (r"<(Video|Audio)\b", "