mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
PA13, PA14: raea playable, and playables in the public engine (#264)
* PA13, PA14: raea playable, and playables in the public engine
Playables move from the private tree into the public engine (Shane 11-28: "public totally part of the engine"):
sdk/playable (raea/playable for authors, the browser host, check.ts, parity.ts, tony.ts), examples/playables and
docs/playables.feature, with raea/playable and @raea/playable back in sdk/tsconfig.base.json.
`raea playable GAME.tsx -o DIR` (apps/playable) replaces the Bun pipeline (playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts). It lints the source, renders each composition through `raea run` for its shapes and 3D kinds, bundles the
game and the host once with raea's own bundler, and writes each network's page or ZIP against its 5 MB cap.
engine/bundle gains `minify`, `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, .bin as a
Uint8Array) and package-folder aliases (`three/=DIR`). brick-rush writes all nine targets in 7 s (1,384 KB a page);
mobile-ads' tiles and gates export; all play in WebKit, the Google and TikTok packages included.
check.ts lets a network's own page tags through; parity.ts draws in WebKit (chrome.ts is gone), 6.8/255 on
brick-rush frame 300. The craft guide motion/playable.md is `raea guide playable`. bench/live-3d skips brick-rush with
its real reason (PA18).
* tools/layers.toml: raea-app-playable in apps (PA13)
* Fonts travel with a playable, and an end card in a brand's type
An imported .ttf, .otf, .woff or .woff2 (and .jpeg) is its path in a native render (runtime/bundle rewrite.rs,
engine/bundle script.rs) and a data URL in a playable (inline.rs), so an @font-face names the same file either way.
<EndCard> takes font, color and button. Made for the real-brand playables in mobile-ads (ACANA, OLIPOP, HelloFresh),
which carry their brands' own type; the guide and docs/playables.feature say how.
* The preview page tells raea's review its ad events (PA16)
Inside a frame, the preview network posts {raeaPlayable: kind} to its parent on install and end, so the review can show
them beside the game.
* PA16 status: the review plays playables (raea-platform #99), on a host of their own
* The preview page tells the review when it's ready, seen or hidden, and the first touch (PA16)
Beside install and end, the preview build inside a frame posts ready (the game started), viewable and hidden (its page
shown or put away) and touch (the player took over from the game's own hand), so the review and the desktop show them.
* PA16 status: built in cloud (raea-platform #99, #101) and desktop (raea-feed #124), and raea show --playable
* raea playable says what the source can't have even when the game won't render for the lint
A fetch or a URL often stops the walk's render too, and the lint answered with the render's end ("lint.ts ended with
exit 1") and dropped the refusals it had found. Now the source's refusals are the answer, and a render that fails
for another reason is named by its error line.
* PA16 status: play.raea.io is live, checked with the ACANA export
* skills: raea-skills main ae81d0f (#135 notes hook, #136 and #137 the playable guide and raea playable in cli.md)
tools/skills.sh gen with a raea built at this branch and the feed app at main: every reference and guide copy matches it.
* raea-cli: export-game and playable dispatched in a line each, as the verbs around them, so the crate stays at the size gate's 2000 lines
* dupes: the playable's copies folded into what they copied
spec is raea-runtime-bundle's own (now pub), inline.rs's base64 is the base64 crate as raea's other crates use it,
the store and card JSON are json!, and the bundle FFI reads minify and inline as it reads z3 and stamps. tools/dupes.sh:
293 exact, 57 near, as allowed.
---------
Co-authored-by: shinyobjectz <[email protected]>
This commit is contained in:
1 parent
ea5640de8f
commit
28af820668
48 files changed
+1853
-23
No files matched your search
Generated
+14
@@ -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",
|
||||
|
||||
@@ -239,6 +239,7 @@ members = [
|
||||
"apps/capcut",
|
||||
"apps/layers",
|
||||
"apps/play",
|
||||
"apps/playable",
|
||||
"tools/sdk-props",
|
||||
"tools/hands-audit",
|
||||
]
|
||||
|
||||
@@ -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"] }
|
||||
@@ -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<T> = Result<T, String>;
|
||||
|
||||
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 [email protected]`),
|
||||
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
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 [email protected]` in it".into())
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
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<String> {
|
||||
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"))
|
||||
}
|
||||
@@ -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<Comp>,
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
pub refusals: Vec<String>,
|
||||
}
|
||||
|
||||
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", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
|
||||
];
|
||||
|
||||
/// The game's source and its compositions, judged
|
||||
pub fn lint(game: &Path) -> R<Found> {
|
||||
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
|
||||
let mut refusals = Vec::new();
|
||||
let mut notes = Vec::new();
|
||||
// a URL the SVG namespace names is a name, not a request
|
||||
let src_no_ns = src.replace("http://www.w3.org", "");
|
||||
for (re, why) in SOURCE_RULES {
|
||||
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
|
||||
refusals.push(why.to_string());
|
||||
}
|
||||
}
|
||||
if !src.contains("raea/playable") {
|
||||
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
|
||||
}
|
||||
let walked = match walk(game) {
|
||||
Ok(w) => w,
|
||||
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| Comp {
|
||||
id: c["id"].as_str().unwrap_or("").into(),
|
||||
width: c["width"].as_u64().unwrap_or(0) as u32,
|
||||
height: c["height"].as_u64().unwrap_or(0) as u32,
|
||||
fps: c["fps"].as_f64().unwrap_or(30.0),
|
||||
frames: c["frames"].as_u64().unwrap_or(0),
|
||||
})
|
||||
.collect();
|
||||
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
|
||||
if comps.is_empty() {
|
||||
refusals.push("no composition registered (registerRoot)".into());
|
||||
}
|
||||
if comps.len() == 1 {
|
||||
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
|
||||
}
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
|
||||
}
|
||||
|
||||
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
|
||||
/// out of this one; its answer is the JSON it prints
|
||||
fn walk(game: &Path) -> R<Value> {
|
||||
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
|
||||
if !walk.is_file() {
|
||||
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
|
||||
}
|
||||
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
|
||||
let entry = work.join("lint.ts");
|
||||
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
let run = run?;
|
||||
let out = String::from_utf8_lossy(&run.stdout);
|
||||
if !run.status.success() {
|
||||
let err = String::from_utf8_lossy(&run.stderr);
|
||||
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
|
||||
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
|
||||
return Err(format!("the game didn't render for the lint: {why}"));
|
||||
}
|
||||
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
|
||||
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
|
||||
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
|
||||
use super::R;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
|
||||
|
||||
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
|
||||
pub const CAP: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// What one network got: the file and its size
|
||||
pub struct Written {
|
||||
pub network: String,
|
||||
pub file: PathBuf,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
|
||||
/// the store links, the end card's words
|
||||
pub fn preamble(network: &str, store: &str, card: &str) -> String {
|
||||
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
|
||||
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
|
||||
let title = title.replace('&', "&").replace('<', "<");
|
||||
format!(
|
||||
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
|
||||
script.replace("</script", "<\\/script")
|
||||
)
|
||||
}
|
||||
|
||||
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let mut w = zip::ZipWriter::new(f);
|
||||
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for (name, text) in entries {
|
||||
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
|
||||
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
w.finish().map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, head, body, script);
|
||||
let file = match network {
|
||||
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
|
||||
"google" => {
|
||||
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
|
||||
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
|
||||
let f = out.join(format!("{name}-google.zip"));
|
||||
zip(&f, &[("index.html".into(), html(&head, ""))])?;
|
||||
f
|
||||
}
|
||||
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
|
||||
"tiktok" => {
|
||||
let o = match orientation {
|
||||
"portrait" => 1,
|
||||
"landscape" => 2,
|
||||
_ => 0,
|
||||
};
|
||||
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
|
||||
let f = out.join(format!("{name}-tiktok.zip"));
|
||||
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
|
||||
f
|
||||
}
|
||||
// a ZIP holding a folder and a page of the same name
|
||||
"mintegral" => {
|
||||
let f = out.join(format!("{name}-mintegral.zip"));
|
||||
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
|
||||
f
|
||||
}
|
||||
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
|
||||
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
|
||||
let f = out.join(format!("{name}-{network}.html"));
|
||||
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
|
||||
f
|
||||
}
|
||||
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
|
||||
};
|
||||
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Written { network: network.into(), file, bytes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_script_cannot_end_its_page_early() {
|
||||
let p = super::page("t", "", "", "a('</script>')");
|
||||
assert_eq!(p.matches("</script").count(), 1, "{p}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preamble_names_the_network_as_a_string() {
|
||||
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ mkdir -p "$OUT"
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
expected() { case $1 in
|
||||
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
|
||||
examples/playables/brick-rush.tsx) echo "a playable: it needs the playable host's raea_playable (sdk/playable)" ;;
|
||||
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
|
||||
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea app"
|
||||
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
|
||||
order: 7
|
||||
order: 8
|
||||
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea bundle"
|
||||
summary: "Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone."
|
||||
order: 6
|
||||
order: 7
|
||||
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea export"
|
||||
summary: "The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them."
|
||||
order: 5
|
||||
order: 6
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ Render, play and package what you wrote.
|
||||
| [`raea render`](render.md) | Render a composition to an MP4, a PNG or a folder of frames, on the GPU and headless. |
|
||||
| [`raea play`](play.md) | Play a game live in a window, or headless with scripted keys, snapshots and a timing report. |
|
||||
| [`raea export-game`](export-game.md) | Package a game as a program of its own: a Mac app or a command-line program. |
|
||||
| [`raea playable`](playable.md) | Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad. |
|
||||
| [`raea export`](export.md) | The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them. |
|
||||
| [`raea bundle`](bundle.md) | Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone. |
|
||||
| [`raea app`](app.md) | Run, check headless and package a desktop app written as one TSX file on @raea/ui. |
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: "raea playable"
|
||||
summary: "Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad."
|
||||
order: 5
|
||||
sources: ["apps/playable/src/lib.rs"]
|
||||
---
|
||||
|
||||
`raea playable` turns a raea game into a playable ad: a short game served in place of a video ad inside other apps,
|
||||
ending on a card that opens the store. The same file renders with `raea render` as the video ad, because a game that
|
||||
nobody touches plays itself. Each network gets the page or ZIP it takes, with its own start, pause and store calls,
|
||||
checked against its 5 MB cap. Nothing in the page loads anything: pictures, sounds and the 3D renderer travel inside it.
|
||||
|
||||
```sh
|
||||
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
|
||||
raea playable game.tsx -o out/playable --networks applovin,google,preview --cta "Play free"
|
||||
```
|
||||
|
||||
Before it bundles, the export refuses what a playable can't have: files read from disk at render time (`staticFile`;
|
||||
import the file instead), URLs and network calls, modules that need the native engine, `<Video>` and `<Audio>`, and 3D
|
||||
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
|
||||
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
|
||||
|
||||
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
|
||||
project (`raea add [email protected]`).
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--android` | `URL` | The Google Play page the store tap opens on Android. |
|
||||
| `--cta` | `TEXT` | The button's words on the host's own end card, `Play now` by default. A game's `<EndCard cta>` sets its own. |
|
||||
| `--ios` | `URL` | The App Store page the store tap opens on iPhone and iPad. |
|
||||
| `--networks` | `LIST` | The networks to write, split by commas: `applovin`, `unity`, `google`, `meta`, `moloco`, `mintegral`, `tiktok`, `liftoff`, `preview`. All of them by default. |
|
||||
| `--orientation` | `portrait\|landscape\|both` | What Google's `ad.orientation` tag and TikTok's `config.json` are told; `both` by default. The game plays whichever of its compositions is nearest the screen's shape either way. |
|
||||
| `--title` | `TEXT` | The title on the host's own end card, shown at the last frame when the game never shows an `<EndCard>`. |
|
||||
| `-o` | `DIR` | The folder the pages and ZIPs go in, named GAME-NETWORK.html or .zip. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea run"
|
||||
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
|
||||
order: 8
|
||||
order: 9
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
@spec
|
||||
Feature: raea games as playable ads, exported for every ad network from the TSX that renders the video ad
|
||||
Shane, 2026-10-29: "lets build a playables feature and explore how we can optimize or help raea agents build for
|
||||
playables specifically as well as explore the export options included with it". A playable ad is a 15-60 second
|
||||
mini-game served in place of a video ad, inside other apps' WebViews; it ends on a card that opens the store. Bevy
|
||||
stays the engine for games (docs/web-export.md is raea's own web build); a playable is an export of a game, drawn by
|
||||
a light web renderer on the same scene contract, because Bevy's renderer doesn't fit an ad (PA0b). The code is
|
||||
sdk/playable (raea/playable for authors, the browser host, the export tools); the example is
|
||||
examples/playables/brick-rush.tsx.
|
||||
|
||||
Background:
|
||||
Given the networks that take advertiser playables in 2026, read from each network's own spec on 10-29
|
||||
| network | package | cap | install call | also |
|
||||
| AppLovin | one HTML, all inlined (base64/122) | 5 MB | mraid.open(url) | MRAID 2.0; timer starts at the first touch |
|
||||
| Unity Ads | one index.html, inlined, minified | 5 MB | mraid.open(url) | MRAID 3.0 injected by the webview; start on ready + viewable, pause when not; both orientations |
|
||||
| Google | ZIP, index.html, at most 512 files | 5 MB | ExitApi.exit() | exitapi.js and <meta name="ad.orientation"> in the head; billed per engagement |
|
||||
| Meta | one HTML with data URIs, or ZIP | 5 MB | FbPlayableAd.onCTAClick() | no mraid.js; ZIP at most 100 files (blogs that say 2 MB are out of date) |
|
||||
| Moloco | one HTML with data URIs, no ZIP | 5 MB | FbPlayableAd.onCTAClick() | mraid.js banned |
|
||||
| Mintegral | ZIP: a folder and a page of one name | 5 MB | window.install() | gameReady() when loaded, gameStart from the network, gameEnd() when over |
|
||||
| TikTok | ZIP, index.html + config.json | 5 MB zipped | window.openAppStore() | their playable-sdk.js before the game's script; {"playable_orientation": 0/1/2}; no mraid.js |
|
||||
| Liftoff | one HTML, or ZIP with one folder | 5 MB | Liftoff.open() | relative paths only |
|
||||
And every network refuses a network request, a redirect without a tap, and sound before the first touch
|
||||
And ironSource's own network closed on 2026-04-30 (its traffic is Unity LevelPlay's)
|
||||
|
||||
Rule: Settled questions
|
||||
|
||||
Scenario: PA0a. What a raea playable is
|
||||
Given a game written as any raea game is: React TSX, its state a pure fold of input (useGameState), its 3D the
|
||||
SDK's components (which render data-3d elements, the contract the native engine reads)
|
||||
Then the same file renders with `raea render` as the video ad (no one touches it, so it plays itself) and exports
|
||||
with `raea playable` as a playable for each network
|
||||
And it imports raea/playable for the store: <EndCard show={over}> when the game is over, <InstallButton> anywhere,
|
||||
or install() from a tap; outside an export install() does nothing
|
||||
And it registers a portrait and a landscape composition when it can (the host plays the one nearest the screen;
|
||||
a single one is letterboxed, and Unity, AppLovin, Moloco and Mintegral want both)
|
||||
|
||||
Scenario: PA0b. Bevy's renderer stays out of ads; a light web renderer draws them (measured 10-29)
|
||||
Given brick-rush's scene (24 cuboids, paddle, ball, a shadowed directional light) in plain Bevy 0.20 for
|
||||
wasm32 (opt-level z, fat LTO, wasm-opt -Oz), next to the three.js export of the same game
|
||||
| build | wasm | one HTML (base64) | zipped |
|
||||
| Bevy, default features | 23.3 MB | 31.3 MB | 7.4 MB |
|
||||
| Bevy, the features raea-render turns on | 21.5 MB | 28.7 MB | 6.9 MB |
|
||||
| Bevy, only what the scene needs (WebGL2) | 12.3 MB | 16.5 MB | 3.7 MB |
|
||||
| Bevy, only what the scene needs (WebGPU) | 10.8 MB | 14.6 MB | 3.1 MB |
|
||||
| Bevy logic only (App, ECS, Transform; no renderer) | 0.55 MB | 0.74 MB | 0.2 MB |
|
||||
| sdk/playable: React + three.js + the game | - | 0.79 MB | 0.22 MB |
|
||||
And stored gzipped inside the page (DecompressionStream, in every WebView since 2023) the stripped WebGL2 build
|
||||
is 4.99 MB as base64: under 5 MB with nothing left for raea's own crates, the game or its assets (brotli: 3.4 MB,
|
||||
but older WebViews can't decompress brotli)
|
||||
And first frame served from localhost: Bevy 1.9 s, three.js 0.66 s; at 4x CPU throttle 3.2 s and 1.5 s
|
||||
Then the renderer (wgpu, naga, bevy_pbr) is about 95% of Bevy on the web: logic alone is small
|
||||
And the industry does the same: Unity Playworks (ex-Luna) never ships Unity's WebGL build; it converts the game's
|
||||
C# to JavaScript and runs it on its own ~650 KB playable engine; PlayCanvas's engine is ~1.2 MB
|
||||
And so a playable is drawn by a light WebGL2 renderer on raea's scene contract, its look held to the native
|
||||
engine's by a parity check (PA9), its shading moving toward Bevy's own (PA10, PA11); Bevy's logic may come along
|
||||
as wasm (PA12); Bevy wasm stays the path for raea's uncapped web export (docs/web-export.md)
|
||||
And WebGPU is on by default in iOS 26's WKWebView and reported in Android WebView, but a playable targets WebGL2
|
||||
for reach
|
||||
|
||||
Rule: Built 10-29
|
||||
|
||||
@done
|
||||
Scenario: PA1. The browser host
|
||||
Then sdk/playable/src/host/main.tsx mounts the registered composition nearest the screen's shape on a stage
|
||||
scaled uniformly into the screen, steps a Clock 1/fps at a time off requestAnimationFrame with the person's
|
||||
input recorded per frame as live entries (input.ts: keys, the primary pointer, every finger, in composition
|
||||
px), and draws the page's data-3d parts with three.js under the page (scene.ts), the page's background behind
|
||||
the 3D becoming its clear colour
|
||||
And it starts when the network says the ad is viewable, pauses while it isn't, stops stepping when the game's
|
||||
EndCard shows, and at the composition's last frame shows its own EndCard
|
||||
And the status: brick-rush plays in headless mobile Chrome in portrait and landscape; a drag moves the paddle; three
|
||||
misses show "So close!"; a tap on the card fires end then install (tools/check.ts, PLAY_SECONDS=25)
|
||||
|
||||
@done
|
||||
Scenario: PA2. Each network's start, pause, store and end calls
|
||||
Then sdk/playable/src/network.ts is built with the network's name (__RAEA_NETWORK__) and the store links, and maps
|
||||
whenReady, install and end onto the table in the Background (MRAID's ready/viewableChange; Mintegral's
|
||||
gameReady, gameStart, gameEnd; the store call per network; preview does nothing)
|
||||
|
||||
@done
|
||||
Scenario: PA3. raea/playable for authors
|
||||
Then install(), end(), <EndCard> (the whole card opens the store; end() when it first shows) and <InstallButton>,
|
||||
plain page elements, so a native render draws them as the playable does
|
||||
|
||||
@done
|
||||
Scenario: PA4. The lint: what a playable can't have, refused before it is bundled
|
||||
Then `raea playable` (apps/playable lint.rs, with sdk/playable/src/export/walk.ts run by `raea run`) renders each
|
||||
composition at 12 frames through its length and refuses a 3D kind the host doesn't draw (PLAYABLE_KINDS in
|
||||
host/kinds.ts), staticFile, URLs, fetch/XHR/WebSocket, modules that need
|
||||
the native engine, and <Video>/<Audio> until PA6; it notes a missing raea/playable import and a single
|
||||
orientation
|
||||
|
||||
@done
|
||||
Scenario: PA5. One export, every network's package
|
||||
Then `raea playable GAME.tsx -o DIR [--networks ...] [--ios URL] [--android URL] [--title T] [--cta T]
|
||||
[--orientation O]` lints, bundles one minified script (PA13) and writes each network's page or ZIP, its settings
|
||||
in a preamble before the script, checked against its cap
|
||||
And the status: brick-rush exports for all nine targets (eight networks and preview) at 916 KB per HTML and 292 KB
|
||||
per ZIP (786 and 218 before PA10's tone-mapping table)
|
||||
|
||||
@done
|
||||
Scenario: PA7. A playable played as a phone shows it
|
||||
Then sdk/playable/tools/check.ts PAGE.html OUT [WxH] opens it at a phone's size with touch (WebKit since PA7b),
|
||||
drags across it, saves screenshots, reads the console and the ad events back, and fails on an exception or a
|
||||
network request; CPU_THROTTLE=4 for a slow phone, PLAY_SECONDS to play to the end and tap the card
|
||||
|
||||
Rule: Made viable again 11-28
|
||||
The 11-06 public-first squash took raea/playable and @raea/playable out of the public sdk/tsconfig.base.json (as it
|
||||
did raea/body and raea/gen), so every export failed at the lint with "Cannot find module 'raea/playable'"
|
||||
|
||||
@done
|
||||
Scenario: PA4b. The tools resolve the SDK's names themselves
|
||||
Then sdk/playable/tools/alias.ts resolves raea, raea/<module> and @raea/<package> from sdk/tsconfig.base.json's
|
||||
paths as engine/bundle's script.rs does, plus raea/playable and @raea/playable/*, as a Bun plugin for the bundle
|
||||
And the lint's walk (tools/walk.ts) runs bundled after the game instead of imported by Bun's runtime, whose own
|
||||
tsconfig paths ("raea/*") catch raea/playable before any plugin
|
||||
And a game's own components in a project with no SDK tsconfig bundle as they render (mobile-ads' gates did not)
|
||||
And the status 11-28: brick-rush exports for all nine targets (1,431 KB per HTML, 471 KB per ZIP); mobile-ads'
|
||||
tiles (1,393 KB) and gates (1,395 KB) export for AppLovin, Google and preview
|
||||
|
||||
@done
|
||||
Scenario: PA7b. The check plays in WebKit
|
||||
Given iOS ad WebViews are WebKit, and raea doesn't test in Chrome (Shane 11-15)
|
||||
Then tools/check.ts plays the page in Playwright's WebKit (playwright-core 1.64.1, the app's version) at a phone's
|
||||
size with real pointer input held over frames, fails on an exception, a network request, an empty page, or an
|
||||
end-card tap with no install event; parity.ts draws its still in WebKit too, and tools/chrome.ts is gone
|
||||
And a network's own page tags (Google's exitapi.js, TikTok's playable-sdk.js) are stopped but not failed: the ad
|
||||
view serves them
|
||||
And the status 11-28: brick-rush, tiles and gates play to their end cards, events ["end","install"], no requests
|
||||
|
||||
Rule: Next
|
||||
|
||||
Scenario: PA6. Sound in a playable
|
||||
Given networks keep sound off until the first touch and most players never turn it on
|
||||
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
|
||||
URLs after input.onFirstTouch, inside the size budget
|
||||
|
||||
Scenario: PA8. Fonts inlined
|
||||
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
|
||||
Then the export inlines the subset of each font the page uses, as the native render draws it
|
||||
|
||||
@done @needs:PA1
|
||||
Scenario: PA9. The playable is held to the native render
|
||||
Then a parity check renders the same composition frame with `raea render` and in the playable host (headless
|
||||
Chrome, scripted input none, so both play themselves), and compares the 3D's colours where both drew a part
|
||||
And it fails when they drift past a bar, so the light renderer can't quietly lose the look
|
||||
And the status: sdk/playable/tools/parity.ts GAME.tsx COMPOSITION FRAME OUT [BAR] renders the frame with `raea render
|
||||
--frame`, opens a preview build at the composition's size with #still=FRAME&comp=ID (the host draws that one frame
|
||||
and stops), and compares the pixels the native frame drew over its background: coverage, mean colours, brightness
|
||||
and mean difference (0-255), exiting 1 over BAR (default 16); native.png, playable.png and diff.png are kept
|
||||
|
||||
@done @needs:PA9
|
||||
Scenario: PA10. The lighting conversion
|
||||
Given the SDK's 3D layer hands lights to the renderer in its own units (r3f intensities converted from Bevy's lux,
|
||||
lumens and cd/m²) and Bevy draws with its camera exposure and TonyMcMapface tone mapping
|
||||
Then the host converts them so PA9's colours match
|
||||
And the status: host/scene.ts turns the SDK's intensities back into Bevy's units (lux 8000, lumens 9e5 over 4π,
|
||||
ambient 400 × π) times Bevy's camera exposure (1 / (1.2 · 2^9.7)); host/tonemap.ts draws the 3D into a half-float
|
||||
target and maps it through TonyMcMapface, Bevy's own 48³ table (tools/tony.ts reads bevy_core_pipeline's ktx2)
|
||||
resampled to 32³ sRGB bytes (98 KB; the 48³ table scored 5.3 for 311 KB more), sampled as tonemapping.wesl does;
|
||||
where nothing was drawn it stays transparent over the page's own background
|
||||
And the numbers on brick-rush (mean difference / 255, brightness): portrait frame 90 went from 50.2 and 0.688x
|
||||
(three.js's units, no exposure) to 5.4 and 0.992x; landscape frame 300 is 9.1 and 0.971x. three.js's built-in
|
||||
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
|
||||
the shading itself (the bricks' side faces a touch darker), PA11's job
|
||||
|
||||
@needs:PA9
|
||||
Scenario: PA11. Bevy's own shading in the light renderer
|
||||
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
|
||||
export time, and the light renderer draws with them instead of three.js's own materials
|
||||
And the 10-29 trial: Bevy 0.20's shaders are WESL, composed by bevy_shader with wesl 0.6 (defs as feature flags,
|
||||
Int/UInt defs in a virtual `constants` package, `bevy_pbr/bevy_core_pipeline` folded to `bevy_core_pipeline`). A
|
||||
standalone program doing the same over the registry sources, then naga 30 (validate, GLSL ES 3.00 for WebGL),
|
||||
with WebGL2's defs (WEBGL2, NO_ARRAY_TEXTURES_SUPPORT, NO_CUBE_ARRAY_TEXTURES_SUPPORT, SIXTEEN_BYTE_ALIGNMENT,
|
||||
AVAILABLE_STORAGE_BUFFER_BINDINGS=0, MAX_CASCADES_PER_LIGHT=1, PER_OBJECT_BUFFER_BATCH_SIZE=93 for the 176-byte
|
||||
Mesh in 16 KB) and the mesh pipeline's for a plain forward StandardMaterial mesh with TonyMcMapface in the shader:
|
||||
| shader | GLSL ES 3.00 | gzip | in Chrome's WebGL2 |
|
||||
| bevy_pbr::render::pbr frag | 1,703 lines, 88 KB | 16 KB | compiles (29 ms) |
|
||||
| bevy_pbr::render::mesh vert | 175 lines, 6.8 KB | 1.7 KB| compiles; the pair links (551 ms) |
|
||||
| bevy_pbr::prepass (shadows) | 150 lines, 5.5 KB, vertex | | translated, not linked yet |
|
||||
And what that leaves: nothing has been drawn with them. The program binds 7 textures (4 material maps, the point
|
||||
and directional shadow maps, the Tony LUT) and 11 uniform blocks the host would fill as Bevy's render world does:
|
||||
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
|
||||
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
|
||||
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
|
||||
|
||||
Scenario: PA12. Bevy systems in a playable
|
||||
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
|
||||
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
|
||||
playable, its world drawn by the light renderer
|
||||
|
||||
@done
|
||||
Scenario: PA13. `raea playable`
|
||||
Then the export is a raea CLI verb (apps/playable) on raea's own bundler, in process: engine/bundle gained
|
||||
`minify` (Rolldown's minifier), `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, a .bin as a
|
||||
Uint8Array) and package-folder aliases (`--alias three/=DIR`, three.js from the project's node_modules, else
|
||||
raea's own)
|
||||
And the lint's walk runs as `raea run` in a process of its own; tools/playable.sh, bundle.ts, lint.ts, walk.ts,
|
||||
alias.ts and chrome.ts are gone, and Bun is needed only for check.ts, parity.ts and tony.ts
|
||||
And the status 11-28: brick-rush writes all nine targets in 7 s (1,384 KB per HTML, 464 KB per ZIP), mobile-ads'
|
||||
tiles (1,345 KB) and gates (1,347 KB) export, and all play in WebKit, the Google and TikTok packages included;
|
||||
a game with staticFile is refused with the reason first
|
||||
And fonts travel as pictures do: an imported .ttf, .otf, .woff or .woff2 is its path in a native render and a data
|
||||
URL in a playable, named in an @font-face; <EndCard> takes font, color and button for a brand's own card
|
||||
|
||||
Scenario: PA14. Agents writing playables
|
||||
Then the raea skill says how a playable is shaped (hook, a hand until the first touch, a fail moment, the end card
|
||||
within 30-60 s, both orientations), what the lint refuses, and how to check one (tools/check.ts)
|
||||
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
|
||||
SKILL.md routes "a playable ad" to it
|
||||
|
||||
Scenario: PA15. A 2D playable carries no three.js
|
||||
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
|
||||
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
|
||||
|
||||
Scenario: PA16. Playables in the review (raea cloud and the desktop)
|
||||
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
|
||||
in raea cloud and in desktop v3, and a playable is one HTML page that loads nothing
|
||||
Then a "playable" kind is drawn by that player: the preview page in a sandboxed iframe (allow-scripts only) inside
|
||||
a phone frame, portrait and landscape, restarted from the stage's own button
|
||||
And the host's ad events (ready, viewable, end, install) show beside it, so a reviewer sees the store tap fire
|
||||
And each network's package, its size against the cap, is a download under it, and pins and notes work as on a video
|
||||
And `raea show GAME.tsx --playable` exports the preview and shows it as that kind (`raea show PAGE.html` for a page
|
||||
already exported); host/show.ts refuses .html today
|
||||
# Status 11-28: built. Cloud: raea-platform #99 (merged into #97's oux-audit-1128) and #101: the playable kind
|
||||
# (a delivered .html), its 9:16 card, the phone either way up with Restart, the events (ready, viewable,
|
||||
# hidden, first touch, end card, store opened), and the network packages folded under it as downloads, red
|
||||
# past 5 MB. Shane 11-28: the page plays on a domain of its own: play.raea.io, live 11-28 (#105, #106:
|
||||
# PLAY_HOST, harness/play.ts: sandbox allow-scripts, 'wasm-unsafe-eval', network off, no-transform, framed by
|
||||
# app.raea.cloud, api.raea.cloud and the desktop's local port). Checked live: the ACANA export uploaded, played
|
||||
# from play.raea.io in a sandboxed frame in WebKit, ready and touch posted, the bytes as exported.
|
||||
# Desktop: raea-feed #124: `raea show PAGE.html` posts a play item with a page, /host/playable serves it under
|
||||
# the same policy, Playable.tsx draws it with pins. `raea show GAME.tsx --playable` exports the preview first
|
||||
# (engine/cli show.ts, native.ts). Checked: the real ACANA export served under the policy runs clean in WebKit.
|
||||
|
||||
Scenario: PA17. Video ad and playable side by side
|
||||
Then one shown game is both: its `raea render` (the video ad, played by its own hand) and its playable, one
|
||||
project in the review, so a creative test brief gets both formats from one file
|
||||
|
||||
Scenario: PA18. brick-rush plays live in the native engine
|
||||
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
|
||||
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
|
||||
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
|
||||
|
||||
@@ -20,6 +20,8 @@ rolldown = "=1.2.12"
|
||||
# CSS imports and CSS modules (A2): @imports inlined, nesting and newer syntax lowered for Stylo
|
||||
lightningcss = { version = "=1.0.0-alpha.72", features = ["bundler"] }
|
||||
anyhow = "1"
|
||||
# imported files carried in a playable's script as data (inline.rs)
|
||||
base64 = "0.22"
|
||||
# the Z3 compile (z3.rs, a live bundle's TSX): oxc as Rolldown 1.2.12 uses it
|
||||
oxc = { version = "=0.152.0", features = ["transformer", "codegen", "semantic", "ast_visit"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! A bundle that carries its files (docs/playables.feature PA13): a picture, sound or model a module imports becomes a
|
||||
//! data URL in the script, and a `.bin` table its bytes, so the one page loads nothing (an ad network refuses a page
|
||||
//! that makes a request). Ahead of the script resolver, which otherwise hands media back as their paths.
|
||||
use rolldown_common::ModuleType;
|
||||
use rolldown_plugin::{HookLoadArgs, HookLoadOutput, HookLoadReturn, HookUsage, Plugin, SharedLoadPluginContext};
|
||||
use std::borrow::Cow;
|
||||
use std::path::Path;
|
||||
|
||||
/// The files carried, by extension, with their media type
|
||||
const TYPES: &[(&str, &str)] = &[
|
||||
("png", "image/png"),
|
||||
("jpg", "image/jpeg"),
|
||||
("jpeg", "image/jpeg"),
|
||||
("webp", "image/webp"),
|
||||
("gif", "image/gif"),
|
||||
("svg", "image/svg+xml"),
|
||||
("mp3", "audio/mpeg"),
|
||||
("m4a", "audio/mp4"),
|
||||
("ogg", "audio/ogg"),
|
||||
("wav", "audio/wav"),
|
||||
("glb", "model/gltf-binary"),
|
||||
("woff2", "font/woff2"),
|
||||
("woff", "font/woff"),
|
||||
("ttf", "font/ttf"),
|
||||
("otf", "font/otf"),
|
||||
];
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Inline;
|
||||
|
||||
/// Standard base64, padded (the base64 crate, as raea's other crates use it)
|
||||
pub fn base64(bytes: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
}
|
||||
|
||||
impl Plugin for Inline {
|
||||
fn name(&self) -> Cow<'static, str> {
|
||||
Cow::Borrowed("raea:inline")
|
||||
}
|
||||
|
||||
fn register_hook_usage(&self) -> HookUsage {
|
||||
HookUsage::Load
|
||||
}
|
||||
|
||||
async fn load(&self, _ctx: SharedLoadPluginContext, args: &HookLoadArgs<'_>) -> HookLoadReturn {
|
||||
let path = args.id.split(['?', '#']).next().unwrap_or(args.id);
|
||||
let Some(ext) = Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) else { return Ok(None) };
|
||||
let code = if ext == "bin" {
|
||||
let b = std::fs::read(path)?;
|
||||
format!("export default Uint8Array.from(atob({:?}), (c) => c.charCodeAt(0));\n", base64(&b))
|
||||
} else if let Some((_, mime)) = TYPES.iter().find(|(e, _)| *e == ext) {
|
||||
let b = std::fs::read(path)?;
|
||||
format!("export default {:?};\n", format!("data:{mime};base64,{}", base64(&b)))
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(HookLoadOutput { code: code.into(), module_type: Some(ModuleType::Js), ..Default::default() }))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn base64_pads_as_the_standard_does() {
|
||||
assert_eq!(super::base64(b""), "");
|
||||
assert_eq!(super::base64(b"f"), "Zg==");
|
||||
assert_eq!(super::base64(b"fo"), "Zm8=");
|
||||
assert_eq!(super::base64(b"foo"), "Zm9v");
|
||||
assert_eq!(super::base64(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub mod edit;
|
||||
pub mod inline;
|
||||
pub mod script;
|
||||
pub mod stamp;
|
||||
pub mod z3;
|
||||
@@ -41,6 +42,10 @@ pub struct Options {
|
||||
pub edit: Option<edit::Edit>,
|
||||
/// each element the edit's own files write stamped with its place in the code (stamp.rs; the app's editor asks)
|
||||
pub stamps: bool,
|
||||
/// minified (a playable's page, which ad networks cap at 5 MB)
|
||||
pub minify: bool,
|
||||
/// imported pictures, sounds, models and .bin tables carried in the script (inline.rs), not named by path
|
||||
pub inline: bool,
|
||||
}
|
||||
|
||||
/// `entry` bundled into one browser script and its CSS.
|
||||
@@ -61,6 +66,7 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
|
||||
// no `//#region <path>` before each module: its path names the work folder (raea-motion-b<pid>), so every
|
||||
// process's bundle differed and the incremental bake saw every function change (lightspeed T3)
|
||||
experimental: Some(ExperimentalOptions { attach_debug_info: Some(AttachDebugInfo::None), ..Default::default() }),
|
||||
minify: o.minify.then_some(rolldown_common::RawMinifyOptions::Bool(true)),
|
||||
..Default::default()
|
||||
};
|
||||
let stamps = if o.stamps {
|
||||
@@ -84,6 +90,9 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
|
||||
s.spawn(move || {
|
||||
rt.block_on(async move {
|
||||
let mut plugins = vec![Pluginable::new_shared(css)];
|
||||
if o.inline {
|
||||
plugins.push(Pluginable::new_shared(inline::Inline));
|
||||
}
|
||||
if let Some(s) = stamps {
|
||||
plugins.push(Pluginable::new_shared(s));
|
||||
}
|
||||
@@ -320,7 +329,7 @@ pub mod ffi {
|
||||
1
|
||||
}
|
||||
|
||||
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool}); returns JSON, {"js","css"} or {"error"}, to
|
||||
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool, "minify": bool, "inline": bool}); returns JSON, {"js","css"} or {"error"}, to
|
||||
/// be freed with raea_bundle_free
|
||||
///
|
||||
/// # Safety
|
||||
@@ -344,7 +353,8 @@ pub mod ffi {
|
||||
js: path(&e["js"]),
|
||||
work: std::path::absolute(&entry).ok().and_then(|p| p.parent().map(|d| d.to_path_buf())).unwrap_or_default(),
|
||||
});
|
||||
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false) };
|
||||
let (minify, inline) = (opts["minify"].as_bool().unwrap_or(false), opts["inline"].as_bool().unwrap_or(false));
|
||||
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false), minify, inline };
|
||||
match super::bundle_with(std::path::Path::new(&entry), o) {
|
||||
Ok(b) => serde_json::json!({"js": b.js, "css": b.css}),
|
||||
Err(e) => serde_json::json!({"error": e}),
|
||||
|
||||
@@ -23,7 +23,8 @@ pub struct Script {
|
||||
pub motion: PathBuf,
|
||||
/// sdk/shell/src/index.ts
|
||||
pub shell: PathBuf,
|
||||
/// `--alias SPEC=PATH`
|
||||
/// `--alias SPEC=PATH`; a SPEC ending in `/` (`three/=DIR`) is a package and every subpath of it, resolved from DIR
|
||||
/// (a folder whose node_modules holds it) wherever it's imported, so the bundle has one copy
|
||||
pub aliases: HashMap<String, PathBuf>,
|
||||
/// `--node-stub a,b`
|
||||
pub stubs: Vec<String>,
|
||||
@@ -36,8 +37,9 @@ const NODE: &[&str] = &[
|
||||
];
|
||||
const STUB: &str = "\0raea-node-stub:";
|
||||
|
||||
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models.
|
||||
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
|
||||
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models and fonts
|
||||
/// (an @font-face's url(), so a playable can carry the same font: inline.rs).
|
||||
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -46,7 +48,12 @@ pub struct ScriptResolve(pub Script);
|
||||
impl ScriptResolve {
|
||||
/// `spec` as the engine's node_modules resolves it (Rolldown's resolver, from a file in sdk/react/js)
|
||||
async fn from_engine(&self, ctx: &PluginContext, spec: &str) -> anyhow::Result<Option<HookResolveIdOutput>> {
|
||||
let importer = self.0.js.join("_raea.js");
|
||||
self.from_dir(ctx, spec, &self.0.js).await
|
||||
}
|
||||
|
||||
/// `spec` as `dir`'s node_modules resolves it
|
||||
async fn from_dir(&self, ctx: &PluginContext, spec: &str, dir: &Path) -> anyhow::Result<Option<HookResolveIdOutput>> {
|
||||
let importer = dir.join("_raea.js");
|
||||
let opts = rolldown_plugin::PluginContextResolveOptions { skip_self: true, ..Default::default() };
|
||||
match ctx.resolve(spec, Some(&importer.to_string_lossy()), Some(opts)).await? {
|
||||
Ok(r) => Ok(Some(HookResolveIdOutput::from_id(r.id.as_str()))),
|
||||
@@ -84,6 +91,9 @@ impl Plugin for ScriptResolve {
|
||||
if let Some(p) = s.aliases.get(spec) {
|
||||
return Ok(path_id(p));
|
||||
}
|
||||
if let Some((_, dir)) = s.aliases.iter().find(|(k, _)| k.strip_suffix('/').is_some_and(|pkg| spec == pkg || spec.starts_with(k.as_str()))) {
|
||||
return self.from_dir(ctx, spec, dir).await;
|
||||
}
|
||||
match spec {
|
||||
"bun:test" | "vitest" | "@jest/globals" => return Ok(path_id(&s.js.join("shims/test.ts"))),
|
||||
"@raea/shell" => return Ok(path_id(&s.shell)),
|
||||
|
||||
@@ -133,7 +133,7 @@ import { version } from "react";
|
||||
aliases: [("~lib".to_string(), d.join("lib/aliased.ts"))].into_iter().collect(),
|
||||
stubs: vec!["fs".into()],
|
||||
};
|
||||
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false };
|
||||
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false, ..Default::default() };
|
||||
let b = raea_bundle::bundle_with(&d.join("work/entry.ts"), o).expect("bundles");
|
||||
for want in ["MOTION_INDEX", "MOTION_ECS", "MOTION_PRELUDE", "TEST_SHIM:", "ZLIB_SHIM", "ALIASED", "ENGINE_REACT", "isn't available in raea's V8", "\"ON\""] {
|
||||
assert!(b.js.contains(want), "{want} in the bundle: {}", b.js);
|
||||
@@ -141,7 +141,7 @@ import { version } from "react";
|
||||
assert!(!b.js.contains("OTHER_REACT"), "one React: the engine's");
|
||||
// a Node built-in raea doesn't carry, not listed as a stub: the bundle fails, naming it
|
||||
w("work/bad.ts", "import { createServer } from \"http\";\nconsole.log(createServer);\n");
|
||||
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false }).expect_err("http isn't carried");
|
||||
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false, ..Default::default() }).expect_err("http isn't carried");
|
||||
assert!(e.contains("\"http\" is a Node built-in") && e.contains("--node-stub http"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
@@ -85,6 +85,8 @@ raea-app-media = { path = "../../apps/media" }
|
||||
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
|
||||
raea-app-targets = { path = "../../apps/targets" }
|
||||
raea-app-game = { path = "../../apps/game" }
|
||||
# `raea playable`: a game as a playable ad for each network (docs/playables.feature PA13)
|
||||
raea-app-playable = { path = "../../apps/playable" }
|
||||
raea-app-capcut = { path = "../../apps/capcut" }
|
||||
raea-app-layers = { path = "../../apps/layers" }
|
||||
raea-app-play = { path = "../../apps/play", features = ["ml"] }
|
||||
|
||||
@@ -147,7 +147,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
|
||||
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_make::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
|
||||
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_denoise_bench::USAGE));
|
||||
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE));
|
||||
}
|
||||
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
|
||||
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
|
||||
@@ -228,9 +228,9 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
// `export capcut EDIT.tsx` (a CapCut draft) and `render ... -o OUT.mov --alpha` (a transparent movie): apps/capcut
|
||||
if let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }
|
||||
// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)
|
||||
if args.first().map(String::as_str) == Some("export-game") {
|
||||
return raea_app_game::export(args);
|
||||
}
|
||||
if args[0] == "export-game" { return raea_app_game::export(args); }
|
||||
// `playable GAME.tsx -o DIR`: the game as a playable ad, a page or ZIP per network (apps/playable, docs/playables.feature)
|
||||
if args[0] == "playable" { return raea_app_playable::cli(args); }
|
||||
// `add PKG... [--dev] | remove NAME... | install [--offline] [--in DIR]`: npm packages for the project (its
|
||||
// package.json and raea.lock, a pnpm-style node_modules from one verified store; install scripts never run), which
|
||||
// a composition, an app screen or a legacy-app panel imports (io/npm)
|
||||
|
||||
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
|
||||
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
|
||||
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
|
||||
assert!(missing.is_empty(), "not in raea help: {missing:?}");
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
|
||||
assert!(help.contains(usage), "{usage}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// record: playable-brick-rush
|
||||
// A playable ad's shape in raea (docs/playables.feature): a hand shows the move until the first touch, the player drags
|
||||
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
|
||||
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
|
||||
// one touches it: the paddle follows the ball, and the same file is the video ad.
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { Sphere } from "raea/3d";
|
||||
import { LinearRgba, Srgba } from "raea/color";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Cuboid, Mesh3d } from "raea/mesh";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { EndCard } from "raea/playable";
|
||||
|
||||
const FPS = 30;
|
||||
const COLS = 6, ROWS = 4, LIVES = 3;
|
||||
const W = 6, TOP = 6; // field: x in [-W/2, W/2], y from 0 (paddle) to TOP
|
||||
const FOV = 0.733; // radians, vertical
|
||||
const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
|
||||
|
||||
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
|
||||
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
|
||||
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
|
||||
|
||||
/** The camera's distance that fits the whole field on a screen of this aspect */
|
||||
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
|
||||
|
||||
/** A pointer's x on screen, in field units at the paddle's depth */
|
||||
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
|
||||
if (!input.pointer) return undefined;
|
||||
const d = distance(width / height);
|
||||
const halfH = Math.tan(FOV / 2) * d;
|
||||
return ((input.pointer.x / width) * 2 - 1) * halfH * (width / height);
|
||||
}
|
||||
|
||||
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
|
||||
if (s.over) return s;
|
||||
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
|
||||
const want = touched ? fieldX(input, width, height) ?? s.px : s.bx; // before the first touch, the paddle plays itself
|
||||
const px = Math.max(-W / 2 + 0.7, Math.min(W / 2 - 0.7, s.px + Math.max(-0.35, Math.min(0.35, want - s.px))));
|
||||
let { bx, by, vx, vy, hit, missed, lives } = s;
|
||||
bx += vx; by += vy;
|
||||
if (bx < -W / 2 + 0.12 || bx > W / 2 - 0.12) vx = -vx;
|
||||
if (by > TOP) vy = -Math.abs(vy);
|
||||
if (by < 0.15 && by > -0.2 && vy < 0 && Math.abs(bx - px) < 0.8) { vy = Math.abs(vy); vx += (bx - px) * 0.05; hit = frame; }
|
||||
if (by < -1.2) { lives -= 1; missed = frame; bx = px; by = 0.6; vx = 0.06; vy = 0.1; }
|
||||
const alive = s.alive.slice(), broke = s.broke.slice();
|
||||
for (let i = 0; i < alive.length; i++) {
|
||||
if (!alive[i]) continue;
|
||||
const [x, y] = brickPos(i);
|
||||
if (Math.abs(bx - x) < W / COLS / 2 && Math.abs(by - y) < 0.22) { alive[i] = false; broke[i] = frame; vy = -vy; break; }
|
||||
}
|
||||
const over = !alive.some(Boolean) ? "won" : lives <= 0 ? "lost" : "";
|
||||
return { px, bx, by, vx, vy, alive, broke, hit, missed, lives, touched, over };
|
||||
};
|
||||
|
||||
const steps = new Map<string, ReturnType<typeof stepFor>>();
|
||||
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
|
||||
|
||||
function BrickRush() {
|
||||
const { width, height } = useVideoConfig();
|
||||
const g = useGameState(INITIAL, stepOf(width, height));
|
||||
const now = useCurrentFrame();
|
||||
const last = g.broke.reduce((m, b) => Math.max(m, b), -99);
|
||||
const kick = Math.max(0, 1 - (now - last) / 8);
|
||||
const shake = kick * kick * 0.08 * Math.sin(now * 2.7);
|
||||
const squash = Math.max(0, 1 - (now - g.hit) / 6);
|
||||
const flash = Math.max(0, 1 - (now - g.missed) / 12);
|
||||
const d = distance(width / height);
|
||||
const s = width / 1080; // page sizes scale with the composition
|
||||
return (
|
||||
<AbsoluteFill style={{ background: `rgb(${16 + 90 * flash}, 20, 34)` }}>
|
||||
<Camera3d transform={Transform.fromXyz(shake, TOP / 2 + shake, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
|
||||
<AmbientLight brightness={180} />
|
||||
<DirectionalLight transform={Transform.fromXyz(2, 8, 6).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />
|
||||
<Mesh3d transform={Transform.fromXyz(g.px, 0, 0).withScale([1 + 0.25 * squash, 1 - 0.35 * squash, 1])} name="paddle">
|
||||
<Cuboid half_size={[0.7, 0.1, 0.2]} />
|
||||
<StandardMaterial base_color="#f0ebd8" perceptual_roughness={0.4} />
|
||||
</Mesh3d>
|
||||
<Mesh3d transform={Transform.fromXyz(g.bx, g.by, 0)} name="ball">
|
||||
<Sphere radius={0.14} />
|
||||
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.6)} />
|
||||
</Mesh3d>
|
||||
{g.alive.map((on, i) => {
|
||||
const [x, y] = brickPos(i);
|
||||
const t = (now - g.broke[i]) / 10;
|
||||
if (!on && t > 1) return null;
|
||||
const pop = on ? 1 : 1 + 0.6 * t;
|
||||
return (
|
||||
<Mesh3d key={i} transform={Transform.fromXyz(x, y, on ? 0 : t * 0.8).withScale([pop, on ? 1 : 1 - t, on ? 1 : 1 - t])} name={`brick-${i}`}>
|
||||
<Cuboid half_size={[(W / COLS - 0.08) / 2, 0.2, 0.2]} />
|
||||
<StandardMaterial base_color={on ? COLORS[Math.floor(i / COLS)] : "#ffffff"} perceptual_roughness={0.5} />
|
||||
</Mesh3d>
|
||||
);
|
||||
})}
|
||||
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
|
||||
{"♥".repeat(Math.max(0, g.lives))}
|
||||
</div>
|
||||
{!g.touched ? (
|
||||
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
|
||||
{`👆 Drag to play`}
|
||||
</div>
|
||||
) : null}
|
||||
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => (
|
||||
<>
|
||||
<Composition id="brick-rush-portrait" component={BrickRush} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 45} />
|
||||
<Composition id="brick-rush-landscape" component={BrickRush} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 45} />
|
||||
</>
|
||||
));
|
||||
@@ -24,12 +24,13 @@ pub fn bundle_module(ts: &Path, out: &Path, body: &str) -> R<()> {
|
||||
/// A path as an entry's import specifier. On Windows a canonical path is a verbatim one (\\?\C:\...), which Rolldown
|
||||
/// can't resolve as an import (`raea run` on windows-latest, PT20); dunce drops the prefix where the plain path means the
|
||||
/// same file, and changes nothing elsewhere.
|
||||
fn spec(p: &Path) -> String {
|
||||
pub fn spec(p: &Path) -> String {
|
||||
dunce::simplified(p).display().to_string()
|
||||
}
|
||||
|
||||
/// `entry` (TypeScript source) bundled into `out` by raea-bundle's library (engine/bundle/src/script.rs's resolution); `extra`
|
||||
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b).
|
||||
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b), and --minify 1 and --inline 1 (a page that
|
||||
/// carries its files: engine/bundle inline.rs).
|
||||
pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
|
||||
let out = &std::path::absolute(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let work = std::env::temp_dir().join(format!("raea-cli-e{}-{:?}", std::process::id(), std::thread::current().id()));
|
||||
@@ -41,6 +42,7 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
|
||||
// in process by raea-bundle's library: the engine's resolution (engine/bundle/src/script.rs) and the flags
|
||||
{
|
||||
let (mut defines, mut aliases, mut stubs) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());
|
||||
let (mut minify, mut inline) = (false, false);
|
||||
let mut it = extra.iter();
|
||||
while let Some(flag) = it.next() {
|
||||
let Some(v) = it.next() else { break };
|
||||
@@ -56,6 +58,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
|
||||
}
|
||||
}
|
||||
"--node-stub" => stubs.extend(v.split(',').filter(|s| !s.is_empty()).map(|s| Value::from(s))),
|
||||
"--minify" => minify = *v != "0",
|
||||
"--inline" => inline = *v != "0",
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -64,6 +68,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
|
||||
"script": {"js": js, "motion": root.join("sdk/raea/src"), "shell": root.join("sdk/shell/src/index.ts"),
|
||||
"aliases": aliases, "stubs": stubs},
|
||||
"defines": defines,
|
||||
"minify": minify,
|
||||
"inline": inline,
|
||||
});
|
||||
let r = inproc::bundle(&work.join("entry.ts"), opts);
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
|
||||
@@ -35,7 +35,9 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
|
||||
/// Files an edit imports as their path, as engine/bundle's script.rs MEDIA: media, models, and fonts (an @font-face's
|
||||
/// url(), which a playable carries as a data URL)
|
||||
pub const MEDIA_EXTS: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
|
||||
|
||||
/// The edit's source with its imports pointed at the bundle's copy of the SDK (its package name, a subpath such as /3d,
|
||||
/// or a relative path into raea/motion/src), and media imported as modules turned into their paths (spec: "Media
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Playable ads: raea/playable and `raea playable`
|
||||
|
||||
A playable ad is a short game served in place of a video ad inside other apps (AppLovin, Unity, Google, Meta,
|
||||
Moloco, Mintegral, TikTok, Liftoff). It ends on a card that opens the store. In raea it is a game written the usual
|
||||
way (`games`), and the same file is both ads: `raea render` makes the video ad, because nobody touches it and it plays
|
||||
itself, and `raea playable` makes the playable for each network.
|
||||
|
||||
## The shape
|
||||
|
||||
- **It plays itself until the first touch.** Before anyone touches it, the step plays (a hand, a ghost finger, the
|
||||
computer making the best move each second). The first touch hands control over, and the hand goes. This is also
|
||||
what the video ad shows.
|
||||
- **The move is clear in two seconds.** One gesture: drag, tap a group, swipe a lane. Show it with the hand, not
|
||||
words. A line of instructions is the rut.
|
||||
- **A fail moment comes early.** Somewhere between 10 and 30 seconds the player nearly wins or just loses ("So
|
||||
close!", a tower one short). That is what sends people to the store.
|
||||
- **The card comes within 30 to 60 seconds.** End on `<EndCard>` when the game is over, won or lost, and never later
|
||||
than the composition's last frame (the host shows its own card there).
|
||||
- **Both orientations.** Register a portrait composition (1080x1920) and a landscape one (1920x1080) from the same
|
||||
game. The host plays the one nearest the screen's shape; with one only, the other is letterboxed. Unity, AppLovin,
|
||||
Moloco and Mintegral want both.
|
||||
- **Words stay big.** A phone shows the composition scaled down: titles at 80 px and more, nothing under 36 px at
|
||||
1080 wide.
|
||||
|
||||
## The store
|
||||
|
||||
```tsx
|
||||
import { EndCard, InstallButton, install } from "raea/playable";
|
||||
|
||||
<EndCard show={g.over !== ""} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle="Can you clear the wall?" cta="Try again" />
|
||||
```
|
||||
|
||||
- `<EndCard show>` covers the game, and a tap anywhere on it opens the store (`end()` is called when it first shows).
|
||||
`title`, `subtitle`, `icon` (an imported picture), `cta`, `background`, `font`, `color` and `button` set it; what
|
||||
you put inside it (a logo, a product) goes between the words and the button.
|
||||
- `<InstallButton>` is a button anywhere in the game; `install()` opens the store from your own tap handler.
|
||||
- Outside an export (a render, a preview) they draw but do nothing. The store links come from the export's `--ios` and
|
||||
`--android`.
|
||||
|
||||
## Input
|
||||
|
||||
- Read the pointer and touches from the frame's input as in any game: `input.pointer` (`x`, `y` in composition px,
|
||||
`down`) and `input.touches`. Keys work too, for testing in a browser.
|
||||
- The host samples input once a frame. A tap shorter than a frame can be missed, so act on the press (`down` becoming
|
||||
true), not on a quick down-and-up within one frame.
|
||||
|
||||
## What a playable can't have
|
||||
|
||||
`raea playable` refuses these before it bundles:
|
||||
|
||||
- `staticFile()`. Import the file instead (`import icon from "./icon.png"`), and the export carries it in the page.
|
||||
- Any URL, `fetch`, XHR or WebSocket. Networks refuse a page that makes a request.
|
||||
- Modules that need the native engine: raea/native, raea/ml, raea/character, raea/physics, raea/media,
|
||||
raea/matchmove and raea/modelling.
|
||||
- `<Video>` and `<Audio>`, until sound comes to playables.
|
||||
- 3D outside what the host draws: meshes (box, sphere, plane, cylinder, cone, torus, capsule, circle, ring), the
|
||||
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
|
||||
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
|
||||
|
||||
A font is carried the same way: import it (`import arvo from "./Arvo-Bold.ttf"`) and name it in an `@font-face` in a
|
||||
`<style>`, ``src: url(${arvo})``. A font named but not imported isn't there on a phone, which draws its own sans-serif.
|
||||
`<EndCard>` takes `font`, `color` and `button` (a style for its button), so a brand's card is in the brand's type.
|
||||
|
||||
## Export and check
|
||||
|
||||
```sh
|
||||
raea add [email protected] # once per project: the playable's 3D renderer
|
||||
raea render game.tsx -o out/video-ad.mp4 # the video ad
|
||||
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
|
||||
```
|
||||
|
||||
It prints each network's file and its size against the 5 MB cap; a page is usually 1.3 to 1.5 MB, most of it
|
||||
three.js. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
|
||||
`--orientation` sets what Google and TikTok are told.
|
||||
|
||||
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
|
||||
raea's own checkout, `bun sdk/playable/tools/check.ts PAGE.html OUT` plays it in WebKit, as an iPhone's ad view does,
|
||||
and fails on an error, a request, or a card that opens nothing.
|
||||
|
||||
## How it fails
|
||||
|
||||
| What you see | Why | What to change |
|
||||
|---|---|---|
|
||||
| nothing moves until it's touched | the step only reads input | let the step play itself when nobody has touched it |
|
||||
| the hand keeps playing after a touch | `touched` isn't kept in the state | set it in the step on the first press, and stop the hand from then |
|
||||
| a tap does nothing | the press lasted less than a frame, or the step waits for the release | act on `down` |
|
||||
| the page is refused for a request | a URL or `staticFile` in the source, or a font from the web | import the file; take the URL out |
|
||||
| it's letterboxed on a phone | one orientation registered | register the other shape |
|
||||
| the video ad shows the end card early | the self-play loses too fast | tune the self-play so it nearly wins |
|
||||
@@ -0,0 +1,13 @@
|
||||
src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/tony.ts from Bevy's copy of it.
|
||||
|
||||
Tony McMapface
|
||||
Copyright (c) 2023 Tomasz Stachowiak
|
||||
https://github.com/h3r2tic/tony-mc-mapface
|
||||
Licensed under MIT.
|
||||
|
||||
Bevy's copy: bevy_core_pipeline's tonemapping/luts/tony_mc_mapface.ktx2
|
||||
https://github.com/bevyengine/bevy
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
|
||||
repository's licence.
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"lockfileVersion": 2,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "@raea/playable",
|
||||
"dependencies": {
|
||||
"react": "file:../raea/node_modules/react",
|
||||
"react-dom": "file:../raea/node_modules/react-dom",
|
||||
"scheduler": "file:../raea/node_modules/scheduler",
|
||||
"three": "0.180.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3",
|
||||
"@types/react-dom": "19.2.0",
|
||||
"@types/three": "0.180.0",
|
||||
"playwright-core": "1.64.1",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
|
||||
|
||||
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
|
||||
|
||||
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
|
||||
|
||||
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
|
||||
|
||||
"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-brtBs0MnE9SMx7px208g39lRmC5uHZs96caOJfTjFcYSLHNamvaSMfJNagChVNkup2SdtOxKX1FDBkRSJe1ZAg=="],
|
||||
|
||||
"@types/stats.js": ["@types/[email protected]", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],
|
||||
|
||||
"@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": "*", "@webgpu/types": "*", "fflate": "~0.8.2", "meshoptimizer": "~0.22.0" } }, "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg=="],
|
||||
|
||||
"@types/webxr": ["@types/[email protected]", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],
|
||||
|
||||
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
|
||||
|
||||
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
|
||||
"fflate": ["[email protected]", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
|
||||
|
||||
"meshoptimizer": ["[email protected]", "", {}, "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg=="],
|
||||
|
||||
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
|
||||
|
||||
"react": ["react@file:../raea/node_modules/react", {}],
|
||||
|
||||
"react-dom": ["react-dom@file:../raea/node_modules/react-dom", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }],
|
||||
|
||||
"scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],
|
||||
|
||||
"three": ["[email protected]", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],
|
||||
|
||||
"undici-types": ["[email protected]", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="],
|
||||
|
||||
"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
|
||||
"react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@raea/playable",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"description": "raea games as playable ads: the install call and end card authors use (raea/playable), and the browser host a playable export runs the game in (a fixed-step clock, touch input, the 3D drawn by three.js), docs/playables.feature.",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./host": "./src/host/main.tsx"
|
||||
},
|
||||
"//": "React is the SDK's own copy (sdk/raea), linked, so a game and the host share one React",
|
||||
"dependencies": {
|
||||
"react": "file:../raea/node_modules/react",
|
||||
"react-dom": "file:../raea/node_modules/react-dom",
|
||||
"scheduler": "file:../raea/node_modules/scheduler",
|
||||
"three": "0.180.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3",
|
||||
"@types/react-dom": "19.2.0",
|
||||
"@types/three": "0.180.0",
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// The two pieces of page every playable has: a button that opens the store, and the end card shown when the game is
|
||||
// over. Plain page elements, so a raea render draws them as the playable does.
|
||||
import { useEffect, type CSSProperties, type ReactNode } from "react";
|
||||
import { end, install } from "./network";
|
||||
|
||||
export interface InstallButtonProps {
|
||||
children?: ReactNode;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
|
||||
const BUTTON: CSSProperties = {
|
||||
border: "none",
|
||||
borderRadius: 999,
|
||||
padding: "0.7em 1.6em",
|
||||
fontFamily: "Inter, system-ui, sans-serif",
|
||||
fontWeight: 800,
|
||||
fontSize: 40,
|
||||
color: "#101422",
|
||||
background: "#ffd166",
|
||||
boxShadow: "0 6px 0 rgba(0,0,0,0.25)",
|
||||
cursor: "pointer",
|
||||
};
|
||||
|
||||
/** Opens the store when tapped (install()). */
|
||||
export function InstallButton({ children = "Install", style }: InstallButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onPointerUp={(e) => {
|
||||
e.stopPropagation();
|
||||
install();
|
||||
}}
|
||||
style={{ ...BUTTON, ...style }}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export interface EndCardProps {
|
||||
/** shown once the game is over (a state the game's fold reaches); end() is called when it first shows */
|
||||
show: boolean;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
/** the app's icon: an imported picture (`import icon from "./icon.png"`), which the export carries in the page */
|
||||
icon?: string;
|
||||
cta?: string;
|
||||
background?: string;
|
||||
/** the card's type (a brand's font, carried by importing it in an @font-face), Inter by default */
|
||||
font?: string;
|
||||
/** the text's colour, white by default */
|
||||
color?: string;
|
||||
/** the button's look over the default yellow pill: a brand's colours and type */
|
||||
button?: CSSProperties;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** The card the playable ends on: the whole card opens the store when tapped, as networks expect. */
|
||||
export function EndCard({ show, title, subtitle, icon, cta = "Play now", background = "rgba(10, 12, 24, 0.82)", font = "Inter, system-ui, sans-serif", color = "#ffffff", button, children }: EndCardProps) {
|
||||
useEffect(() => {
|
||||
if (show) end();
|
||||
}, [show]);
|
||||
if (!show) return null;
|
||||
return (
|
||||
<div
|
||||
onPointerUp={() => install()}
|
||||
style={{
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 28,
|
||||
background,
|
||||
color,
|
||||
fontFamily: font,
|
||||
textAlign: "center",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
{icon ? <img src={icon} alt="" style={{ width: 180, height: 180, borderRadius: 40 }} /> : null}
|
||||
{title ? <div style={{ fontSize: 64, fontWeight: 900, lineHeight: 1.05, padding: "0 40px" }}>{title}</div> : null}
|
||||
{subtitle ? <div style={{ fontSize: 34, opacity: 0.8, padding: "0 40px" }}>{subtitle}</div> : null}
|
||||
{children}
|
||||
<InstallButton style={button}>{cta}</InstallButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// `raea playable`'s lint, the part that renders (docs/playables.feature PA4): run by `raea run` on an entry that imports
|
||||
// the game first, so its compositions are registered. Each composition is rendered at 12 frames through its length,
|
||||
// and every 3D kind it draws is held to what the playable host draws (kinds.ts). Returns its shapes and the kinds.
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { Clock, getCompositions } from "raea";
|
||||
import { PLAYABLE_KINDS } from "../host/kinds";
|
||||
|
||||
export default function walk() {
|
||||
const kinds: Record<string, number> = {};
|
||||
const comps = getCompositions().map((c) => {
|
||||
const step = Math.max(1, Math.floor(c.durationInFrames / 12));
|
||||
for (let f = 0; f < c.durationInFrames; f += step) {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(Clock, { frame: f, fps: c.fps, width: c.width, height: c.height, durationInFrames: c.durationInFrames }, createElement(c.component, c.defaultProps)),
|
||||
);
|
||||
for (const m of html.matchAll(/data-3d="([A-Za-z0-9]+)"/g)) kinds[m[1]] = (kinds[m[1]] ?? 0) + 1;
|
||||
}
|
||||
return { id: c.id, width: c.width, height: c.height, fps: c.fps, frames: c.durationInFrames };
|
||||
});
|
||||
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)) };
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
// raw tables, carried in the page by `raea playable` (engine/bundle inline.rs: a .bin import is a Uint8Array)
|
||||
declare module "*.bin" {
|
||||
const bytes: Uint8Array;
|
||||
export default bytes;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// A person's input as raea's FrameInput, in composition px: keys held, the primary pointer and every finger down.
|
||||
// The stage is the composition scaled uniformly into the screen, so each point is mapped back through its box.
|
||||
import type { FrameInput } from "raea";
|
||||
|
||||
/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
|
||||
function on<K extends keyof WindowEventMap>(type: K, f: (e: WindowEventMap[K]) => void) {
|
||||
window.addEventListener(type, f);
|
||||
}
|
||||
|
||||
export class Input {
|
||||
private keys = new Set<string>();
|
||||
private pointer?: { x: number; y: number; down: boolean };
|
||||
private touches = new Map<number, { x: number; y: number }>();
|
||||
/** set on the first touch, click or key: networks keep sound off until then */
|
||||
touched = false;
|
||||
private firstTouch: (() => void)[] = [];
|
||||
|
||||
constructor(private stage: HTMLElement, private size: () => { width: number; height: number }) {
|
||||
const at = (e: PointerEvent) => {
|
||||
const r = this.stage.getBoundingClientRect();
|
||||
const { width, height } = this.size();
|
||||
return { x: ((e.clientX - r.left) / r.width) * width, y: ((e.clientY - r.top) / r.height) * height };
|
||||
};
|
||||
const first = () => {
|
||||
if (this.touched) return;
|
||||
this.touched = true;
|
||||
for (const f of this.firstTouch) f();
|
||||
};
|
||||
on("pointerdown", (e) => {
|
||||
first();
|
||||
const p = at(e);
|
||||
this.pointer = { ...p, down: true };
|
||||
this.touches.set(e.pointerId, p);
|
||||
});
|
||||
on("pointermove", (e) => {
|
||||
const p = at(e);
|
||||
if (e.isPrimary) this.pointer = { ...p, down: this.pointer?.down ?? false };
|
||||
if (this.touches.has(e.pointerId)) this.touches.set(e.pointerId, p);
|
||||
});
|
||||
const up = (e: PointerEvent) => {
|
||||
if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
|
||||
this.touches.delete(e.pointerId);
|
||||
};
|
||||
on("pointerup", up);
|
||||
on("pointercancel", up);
|
||||
on("keydown", (e) => {
|
||||
first();
|
||||
this.keys.add(e.key);
|
||||
});
|
||||
on("keyup", (e) => this.keys.delete(e.key));
|
||||
on("blur", () => this.keys.clear());
|
||||
}
|
||||
|
||||
/** Runs `f` on the first touch, click or key */
|
||||
onFirstTouch(f: () => void) {
|
||||
if (this.touched) f();
|
||||
else this.firstTouch.push(f);
|
||||
}
|
||||
|
||||
/** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
|
||||
now(): FrameInput & { live: true } {
|
||||
return {
|
||||
keys: [...this.keys],
|
||||
...(this.pointer ? { pointer: { ...this.pointer } } : {}),
|
||||
...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
|
||||
live: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// The 3D kinds a playable's host draws (scene.ts, through sdk/r3f/src/three), apart from the renderer so the export's
|
||||
// lint reads them without three.js (`raea playable`, docs/playables.feature PA4).
|
||||
|
||||
/** The kinds a playable draws; the export's lint refuses any other */
|
||||
export const PLAYABLE_KINDS: ReadonlySet<string> = new Set([
|
||||
"Canvas3D", "Group", "Mesh",
|
||||
"Box", "Sphere", "Plane", "Cylinder", "Cone", "Torus", "Capsule", "Circle", "Ring",
|
||||
"MeshStandardMaterial", "MeshPhysicalMaterial", "MeshBasicMaterial",
|
||||
"PerspectiveCamera", "OrthographicCamera",
|
||||
"AmbientLight", "DirectionalLight", "PointLight", "SpotLight", "HemisphereLight",
|
||||
"Fog", "ToneMapping", "Shadows", "AntiAliasing",
|
||||
]);
|
||||
@@ -0,0 +1,168 @@
|
||||
// The browser host a playable export runs a raea game in (docs/playables.feature PA1): the game's registered
|
||||
// composition (the one nearest the screen's shape, so a portrait and a landscape one can both ship) put on a stage
|
||||
// scaled uniformly into the screen, a Clock stepped 1/fps at a time off requestAnimationFrame with the person's input
|
||||
// recorded per frame, and its 3D drawn by three.js under the page. It starts when the network says the ad is
|
||||
// viewable, pauses while it isn't, and ends on the game's own EndCard or, at the composition's last frame, on one of
|
||||
// its own.
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import * as THREE from "three";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { EndCard } from "../cards";
|
||||
import { network, onAdEvent, whenReady } from "../network";
|
||||
import { Input } from "./input";
|
||||
import { Scene3d } from "./scene";
|
||||
import { UNDER, backgroundUnder3d } from "@raea/r3f/three/page";
|
||||
import { Tonemap } from "./tonemap";
|
||||
|
||||
declare const __RAEA_PLAYABLE__: { title?: string; cta?: string } | undefined;
|
||||
const config = typeof __RAEA_PLAYABLE__ === "object" && __RAEA_PLAYABLE__ ? __RAEA_PLAYABLE__ : {};
|
||||
|
||||
|
||||
function pick(comps: RegisteredComposition[]): RegisteredComposition {
|
||||
const screen = innerWidth / Math.max(1, innerHeight);
|
||||
return comps.reduce((a, b) => (Math.abs(Math.log((b.width / b.height) / screen)) < Math.abs(Math.log((a.width / a.height) / screen)) ? b : a));
|
||||
}
|
||||
|
||||
/** The 3D is drawn under the page, so the page elements holding it are cleared and the innermost solid background
|
||||
* among them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
|
||||
function boot() {
|
||||
const comps = getCompositions();
|
||||
if (!comps.length) throw new Error("raea playable: the game registered no composition (registerRoot)");
|
||||
// a still (tools/parity.ts): one composition at one frame, no one playing, as `raea render --frame` draws it
|
||||
const still = network === "preview" ? new URLSearchParams(location.hash.slice(1)) : undefined;
|
||||
const fixed = still?.has("still") ? comps.find((c) => c.id === still.get("comp")) ?? comps[0] : undefined;
|
||||
let comp = fixed ?? pick(comps);
|
||||
|
||||
document.head.insertAdjacentHTML("beforeend", `<style>html,body{margin:0;height:100%;overflow:hidden;background:#000;touch-action:none;user-select:none;-webkit-user-select:none}[${UNDER}]{background:transparent!important}#raea-stage{position:absolute;transform-origin:0 0;overflow:hidden}#raea-stage>canvas,#raea-page{position:absolute;inset:0;width:100%;height:100%}</style>`);
|
||||
const stage = document.createElement("div");
|
||||
stage.id = "raea-stage";
|
||||
const canvas = document.createElement("canvas");
|
||||
const page = document.createElement("div");
|
||||
page.id = "raea-page";
|
||||
stage.append(canvas, page);
|
||||
document.body.append(stage);
|
||||
|
||||
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||
const tonemap = new Tonemap(renderer);
|
||||
const scene = new Scene3d();
|
||||
|
||||
const layout = () => {
|
||||
if (comps.length > 1 && !fixed) comp = pick(comps);
|
||||
const s = Math.min(innerWidth / comp.width, innerHeight / comp.height);
|
||||
Object.assign(stage.style, {
|
||||
width: `${comp.width}px`,
|
||||
height: `${comp.height}px`,
|
||||
left: `${(innerWidth - comp.width * s) / 2}px`,
|
||||
top: `${(innerHeight - comp.height * s) / 2}px`,
|
||||
transform: `scale(${s})`,
|
||||
});
|
||||
// the canvas is drawn at the screen's pixels, not the composition's
|
||||
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * s);
|
||||
renderer.setSize(comp.width, comp.height, false);
|
||||
tonemap.resize();
|
||||
scene.fit(comp.width, comp.height);
|
||||
};
|
||||
layout();
|
||||
addEventListener("resize", layout);
|
||||
|
||||
const input = new Input(stage, () => comp);
|
||||
const root = createRoot(page);
|
||||
const timeline: InputTimeline = {};
|
||||
let frame = 0;
|
||||
let timedOut = false;
|
||||
let running = false;
|
||||
let visible = true;
|
||||
let last = 0;
|
||||
let acc = 0;
|
||||
let over = false;
|
||||
let shown = false;
|
||||
let firstDrawn = false;
|
||||
// the ad events so far, for tools/check.ts to read back
|
||||
const events: string[] = ((globalThis as { __raeaAdEvents?: string[] }).__raeaAdEvents = []);
|
||||
// the preview page inside raea's review (a sandboxed frame) tells the review each event, which shows them beside it
|
||||
const tell = (kind: string) => {
|
||||
if (network === "preview" && window.parent !== window) window.parent.postMessage({ raeaPlayable: kind }, "*");
|
||||
};
|
||||
onAdEvent((e) => {
|
||||
events.push(e.kind);
|
||||
if (e.kind === "end") over = true;
|
||||
tell(e.kind);
|
||||
});
|
||||
// the player took over from the game's own hand
|
||||
input.onFirstTouch(() => tell("touch"));
|
||||
|
||||
const draw = () => {
|
||||
const C = comp.component;
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
|
||||
<C {...comp.defaultProps} />
|
||||
<EndCard show={timedOut} title={config.title} cta={config.cta} />
|
||||
</Clock>,
|
||||
),
|
||||
);
|
||||
scene.sync(page, frame / comp.fps);
|
||||
const clear = backgroundUnder3d(page);
|
||||
// the page's own background colour behind the 3D, untouched by the tone curve as natively
|
||||
stage.style.background = clear ?? "#000000";
|
||||
canvas.style.visibility = scene.any ? "visible" : "hidden";
|
||||
if (scene.any) tonemap.render(scene.scene, scene.camera);
|
||||
// a preview build says when its first frame was drawn (tools/check.ts reads it: startup on a slow phone)
|
||||
if (!firstDrawn && network === "preview") console.info(`raea playable: first frame at ${Math.round(performance.now())} ms`);
|
||||
firstDrawn = true;
|
||||
};
|
||||
|
||||
const tick = (now: number) => {
|
||||
requestAnimationFrame(tick);
|
||||
if (!running || !visible) {
|
||||
last = now;
|
||||
return;
|
||||
}
|
||||
const step = 1000 / comp.fps;
|
||||
acc += Math.min(250, now - last);
|
||||
last = now;
|
||||
let stepped = false;
|
||||
// the game stops stepping once it is over (its EndCard showed, or time ran out): the card stays on the last frame
|
||||
while (acc >= step && !over) {
|
||||
acc -= step;
|
||||
timeline[frame] = input.now();
|
||||
if (frame + 1 >= comp.durationInFrames) {
|
||||
timedOut = true;
|
||||
break;
|
||||
}
|
||||
frame++;
|
||||
stepped = true;
|
||||
}
|
||||
if (stepped || (timedOut && !shown)) {
|
||||
shown = timedOut;
|
||||
draw();
|
||||
}
|
||||
};
|
||||
|
||||
if (fixed) {
|
||||
frame = Math.min(Number(still!.get("still")), comp.durationInFrames - 1);
|
||||
draw();
|
||||
(globalThis as { __raeaStill?: boolean }).__raeaStill = true;
|
||||
return;
|
||||
}
|
||||
draw();
|
||||
whenReady(
|
||||
() => {
|
||||
running = true;
|
||||
last = performance.now();
|
||||
tell("ready");
|
||||
},
|
||||
(on) => {
|
||||
if (on !== visible) tell(on ? "viewable" : "hidden");
|
||||
visible = on;
|
||||
},
|
||||
);
|
||||
requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
|
||||
else boot();
|
||||
@@ -0,0 +1,5 @@
|
||||
// The page's 3D drawn by three.js: raea's three.js host (sdk/r3f/src/three, shared with <Raea> in React Three Fiber),
|
||||
// held to what a playable may carry: a kind outside PLAYABLE_KINDS (kinds.ts) is refused by the export's lint
|
||||
// (`raea playable`, docs/playables.feature PA4).
|
||||
export { Scene3d } from "@raea/r3f/three/scene";
|
||||
export { PLAYABLE_KINDS } from "./kinds";
|
||||
@@ -0,0 +1,65 @@
|
||||
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
|
||||
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
|
||||
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
|
||||
// page's background shows through as it does under the native engine's 3D.
|
||||
import * as THREE from "three";
|
||||
import tony from "./tony.bin";
|
||||
|
||||
const N = Math.round(Math.cbrt(tony.length / 3));
|
||||
|
||||
const FRAG = /* glsl */ `
|
||||
precision highp float;
|
||||
precision highp sampler3D;
|
||||
uniform sampler2D scene;
|
||||
uniform sampler3D lut;
|
||||
in vec2 vUv;
|
||||
out vec4 color;
|
||||
void main() {
|
||||
vec4 c = texture(scene, vUv);
|
||||
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
|
||||
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
|
||||
// the table holds sRGB-encoded bytes, already the screen's values
|
||||
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
|
||||
}`;
|
||||
|
||||
const VERT = /* glsl */ `
|
||||
in vec3 position;
|
||||
in vec2 uv;
|
||||
out vec2 vUv;
|
||||
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
|
||||
|
||||
export class Tonemap {
|
||||
private target: THREE.WebGLRenderTarget;
|
||||
private quad: THREE.Mesh;
|
||||
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
||||
|
||||
constructor(private renderer: THREE.WebGLRenderer) {
|
||||
renderer.toneMapping = THREE.NoToneMapping;
|
||||
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
|
||||
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
|
||||
const rgba = new Uint8Array(N * N * N * 4);
|
||||
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
|
||||
const lut = new THREE.Data3DTexture(rgba, N, N, N);
|
||||
lut.minFilter = lut.magFilter = THREE.LinearFilter;
|
||||
lut.unpackAlignment = 1;
|
||||
lut.needsUpdate = true;
|
||||
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
|
||||
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
|
||||
}
|
||||
|
||||
/** The target sized to the canvas's drawing buffer */
|
||||
resize() {
|
||||
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
|
||||
this.target.setSize(s.x, s.y);
|
||||
}
|
||||
|
||||
render(scene: THREE.Scene, camera: THREE.Camera) {
|
||||
const r = this.renderer;
|
||||
r.setRenderTarget(this.target);
|
||||
r.setClearColor(0x000000, 0);
|
||||
r.clear();
|
||||
r.render(scene, camera);
|
||||
r.setRenderTarget(null);
|
||||
r.render(this.quad, this.camera);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
// raea/playable: what a game written for a playable ad uses (docs/playables.feature PA3). The same TSX renders as a
|
||||
// video ad with `raea render` (where install() does nothing) and exports as a playable with `raea playable`.
|
||||
export { install, end, isEnded, network, storeUrl, onAdEvent, type Network, type StoreLinks } from "./network";
|
||||
export { EndCard, InstallButton, type EndCardProps, type InstallButtonProps } from "./cards";
|
||||
@@ -0,0 +1,138 @@
|
||||
// The ad network a playable export is built for, and the three things every network wants from it in its own words:
|
||||
// when the ad may start (and must pause), how the store opens, and that the game ended (docs/playables.feature PA2).
|
||||
// The export names the network at build time (__RAEA_NETWORK__); a game's own code only calls install() and end().
|
||||
|
||||
export type Network = "applovin" | "unity" | "google" | "meta" | "moloco" | "mintegral" | "tiktok" | "liftoff" | "preview";
|
||||
|
||||
export interface StoreLinks {
|
||||
ios?: string;
|
||||
android?: string;
|
||||
}
|
||||
|
||||
declare const __RAEA_NETWORK__: Network | undefined;
|
||||
declare const __RAEA_STORE__: StoreLinks | undefined;
|
||||
|
||||
interface Mraid {
|
||||
getState(): string;
|
||||
isViewable(): boolean;
|
||||
addEventListener(event: string, f: (...a: unknown[]) => void): void;
|
||||
open(url?: string): void;
|
||||
}
|
||||
|
||||
type Win = typeof globalThis & {
|
||||
mraid?: Mraid;
|
||||
ExitApi?: { exit(): void };
|
||||
FbPlayableAd?: { onCTAClick(): void };
|
||||
Liftoff?: { open(): void };
|
||||
install?: () => void;
|
||||
openAppStore?: () => void;
|
||||
gameReady?: () => void;
|
||||
gameEnd?: () => void;
|
||||
gameStart?: () => void;
|
||||
gameClose?: () => void;
|
||||
};
|
||||
|
||||
const w = globalThis as Win;
|
||||
|
||||
/** The network this build is for: "preview" outside an export (a raea render, a browser tab) */
|
||||
export const network: Network = typeof __RAEA_NETWORK__ === "string" ? __RAEA_NETWORK__ : "preview";
|
||||
const store: StoreLinks = typeof __RAEA_STORE__ === "object" && __RAEA_STORE__ ? __RAEA_STORE__ : {};
|
||||
|
||||
const MRAID: readonly Network[] = ["applovin", "unity", "liftoff"];
|
||||
|
||||
/** The store link for this device: iOS's on iPhone/iPad, Android's otherwise */
|
||||
export function storeUrl(): string | undefined {
|
||||
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;
|
||||
const ios = /iPhone|iPad|iPod|Macintosh/.test(ua) && !/Android/.test(ua);
|
||||
return (ios ? store.ios : store.android) ?? store.android ?? store.ios;
|
||||
}
|
||||
|
||||
const listeners: ((e: { kind: "install" | "end" }) => void)[] = [];
|
||||
/** Called on install() and end(), for the preview page's log and tests */
|
||||
export function onAdEvent(f: (e: { kind: "install" | "end" }) => void): void {
|
||||
listeners.push(f);
|
||||
}
|
||||
|
||||
let ended = false;
|
||||
|
||||
/** Open the store, the network's way. Call it only from a player's tap (every network rejects an automatic redirect). */
|
||||
export function install(): void {
|
||||
for (const f of listeners) f({ kind: "install" });
|
||||
if (!ended) end();
|
||||
const url = storeUrl();
|
||||
switch (network) {
|
||||
case "applovin":
|
||||
case "unity":
|
||||
if (w.mraid) w.mraid.open(url);
|
||||
return;
|
||||
case "liftoff":
|
||||
if (w.Liftoff) w.Liftoff.open();
|
||||
else w.mraid?.open();
|
||||
return;
|
||||
case "google":
|
||||
w.ExitApi?.exit();
|
||||
return;
|
||||
case "meta":
|
||||
case "moloco":
|
||||
w.FbPlayableAd?.onCTAClick();
|
||||
return;
|
||||
case "mintegral":
|
||||
w.install?.();
|
||||
return;
|
||||
case "tiktok":
|
||||
w.openAppStore?.();
|
||||
return;
|
||||
case "preview":
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/** The game is over (won, lost or out of time): Mintegral's gameEnd; the host shows the end card. Called once. */
|
||||
export function end(): void {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
for (const f of listeners) f({ kind: "end" });
|
||||
if (network === "mintegral") w.gameEnd?.();
|
||||
}
|
||||
|
||||
/** Whether end() was called */
|
||||
export function isEnded(): boolean {
|
||||
return ended;
|
||||
}
|
||||
|
||||
/** Calls `start` once the ad may begin, then `visible(false|true)` as it is hidden and shown again (Unity, AppLovin:
|
||||
* start only after MRAID's ready and while viewable, pause while not). Mintegral is told the game is ready and
|
||||
* starts it with its own gameStart. */
|
||||
export function whenReady(start: () => void, visible: (on: boolean) => void): void {
|
||||
let started = false;
|
||||
const go = () => {
|
||||
if (started) return;
|
||||
started = true;
|
||||
start();
|
||||
};
|
||||
if (MRAID.includes(network) && w.mraid) {
|
||||
const m = w.mraid;
|
||||
const onReady = () => {
|
||||
m.addEventListener("viewableChange", (on) => {
|
||||
if (on) go();
|
||||
visible(!!on);
|
||||
});
|
||||
if (m.isViewable()) go();
|
||||
};
|
||||
if (m.getState() === "loading") m.addEventListener("ready", onReady);
|
||||
else onReady();
|
||||
return;
|
||||
}
|
||||
if (network === "mintegral") {
|
||||
w.gameStart = go;
|
||||
w.gameClose = () => visible(false);
|
||||
w.gameReady?.();
|
||||
// Mintegral's preview tool calls gameStart; a page opened by hand starts on its own
|
||||
if (!w.gameReady) go();
|
||||
return;
|
||||
}
|
||||
if (typeof document !== "undefined") {
|
||||
document.addEventListener("visibilitychange", () => visible(document.visibilityState === "visible"));
|
||||
}
|
||||
go();
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// A playable played in headless WebKit, as an iPhone's ad WebView would show it (docs/playables.feature PA7): the page
|
||||
// opened at a phone's size, a drag held long enough for the host's per-frame input to see it, its console,
|
||||
// exceptions and any network request it tried read back, and screenshots saved.
|
||||
// `bun tools/check.ts PAGE.html OUT_DIR [WxH]`; exits 1 on a page error, a request, or a page that never drew.
|
||||
// PLAY_SECONDS=N plays on, then taps the end card (and the check fails if no install event came back).
|
||||
// WebKit, not Chrome: iOS ad WebViews are WebKit, and raea doesn't test in Chrome.
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { webkit } from "playwright-core";
|
||||
|
||||
const [page, outDir, size = "390x844"] = process.argv.slice(2);
|
||||
if (!page || !outDir) throw new Error("usage: bun tools/check.ts PAGE.html OUT_DIR [WxH]");
|
||||
const [W, H] = size.split("x").map(Number);
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const browser = await webkit.launch();
|
||||
const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 2, hasTouch: true, isMobile: true });
|
||||
const p = await ctx.newPage();
|
||||
const logs: string[] = [];
|
||||
const problems: string[] = [];
|
||||
p.on("console", (m) => logs.push(`${m.type()}: ${m.text()}`));
|
||||
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
|
||||
// the scripts a network's own page tags load, which its ad view serves (apps/playable pages.rs): Google's exit API and
|
||||
// TikTok's playable SDK. They're stopped here like any request, but they aren't the game's.
|
||||
const NETWORK_TAGS = ["https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js", "https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js"];
|
||||
await ctx.route("**/*", (r) => {
|
||||
const u = r.request().url();
|
||||
if (u.startsWith("file:") || u.startsWith("data:") || u.startsWith("blob:")) return r.continue();
|
||||
if (!NETWORK_TAGS.includes(u)) problems.push(`network request: ${u}`);
|
||||
return r.abort();
|
||||
});
|
||||
await p.goto(page.startsWith("http") ? page : `file://${resolve(page)}`);
|
||||
await p.waitForTimeout(1500);
|
||||
const shot = (name: string) => p.screenshot({ path: resolve(outDir, `${name}.png`) });
|
||||
|
||||
// real input: WebKit makes the pointer events the host reads (host/input.ts), each press held over several frames
|
||||
// (the host samples input once a frame, so a press shorter than a frame is lost)
|
||||
const press = async (type: "down" | "move" | "up", x: number, y: number) => {
|
||||
await p.mouse.move(x, y);
|
||||
if (type === "down") await p.mouse.down();
|
||||
if (type === "up") await p.mouse.up();
|
||||
};
|
||||
|
||||
await shot("0-start");
|
||||
await press("down", W * 0.3, H * 0.75);
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
await press("move", W * (0.3 + 0.04 * i), H * 0.75);
|
||||
await p.waitForTimeout(80);
|
||||
}
|
||||
await press("up", W * 0.7, H * 0.75);
|
||||
await shot("1-played");
|
||||
await p.waitForTimeout(2500);
|
||||
await shot("2-later");
|
||||
const more = Number(process.env.PLAY_SECONDS ?? 0);
|
||||
if (more > 0) {
|
||||
await p.waitForTimeout(more * 1000);
|
||||
await shot("3-end");
|
||||
await press("down", W / 2, H / 2);
|
||||
await p.waitForTimeout(150);
|
||||
await press("up", W / 2, H / 2);
|
||||
await p.waitForTimeout(300);
|
||||
}
|
||||
|
||||
const state = (await p.evaluate(() => ({
|
||||
canvas: !!document.querySelector("#raea-stage canvas"),
|
||||
parts: document.querySelectorAll("[data-3d]").length,
|
||||
page: document.querySelector("#raea-page")?.childElementCount ?? 0,
|
||||
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
|
||||
}))) as { canvas: boolean; parts: number; page: number; events: unknown[] };
|
||||
console.log(`page: ${JSON.stringify(state)}`);
|
||||
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty");
|
||||
if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
|
||||
for (const l of logs) console.log(l);
|
||||
for (const pr of problems) console.log(`PROBLEM: ${pr}`);
|
||||
await browser.close();
|
||||
process.exit(problems.length ? 1 : 0);
|
||||
@@ -0,0 +1,72 @@
|
||||
// A playable held to the native render (docs/playables.feature PA9): one composition frame drawn by `raea render` and
|
||||
// by the playable host (a preview build opened at the composition's size, no one playing, so both play themselves),
|
||||
// compared where the native frame drew something over its background. The playable is drawn in WebKit, as an
|
||||
// iPhone's ad view draws it (raea doesn't test in Chrome).
|
||||
// `bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]` prints the numbers, writes native.png, playable.png
|
||||
// and diff.png, and exits 1 when the mean colour difference over the drawn pixels is over BAR (0-255, default 16).
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { webkit } from "playwright-core";
|
||||
|
||||
const [game, comp, at, outArg, barArg = "16"] = process.argv.slice(2);
|
||||
if (!game || !comp || !at || !outArg) throw new Error("usage: bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]");
|
||||
const out = resolve(outArg);
|
||||
mkdirSync(out, { recursive: true });
|
||||
const name = game.split("/").pop()!.replace(/\.tsx$/, "");
|
||||
|
||||
const run = async (cmd: string[]) => {
|
||||
const p = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" });
|
||||
const [o, e] = [await new Response(p.stdout).text(), await new Response(p.stderr).text()];
|
||||
if ((await p.exited) !== 0) throw new Error(`${cmd.join(" ")} failed:\n${o}\n${e}`);
|
||||
return o;
|
||||
};
|
||||
|
||||
// the native frame, and the composition's size from the registry the playable reads
|
||||
await run(["raea", "render", resolve(game), "-o", `${out}/native.png`, "--composition", comp, "--frame", at]);
|
||||
await run(["raea", "playable", resolve(game), "-o", out, "--networks", "preview"]);
|
||||
const size = (await run(["ffprobe", "-v", "error", "-select_streams", "v", "-show_entries", "stream=width,height", "-of", "csv=p=0", `${out}/native.png`])).trim();
|
||||
const [W, H] = size.split(",").map(Number);
|
||||
|
||||
const browser = await webkit.launch();
|
||||
const p = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
|
||||
const problems: string[] = [];
|
||||
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
|
||||
await p.route("**/*", (r) => {
|
||||
const u = r.request().url();
|
||||
if (/^(file|data|blob):/.test(u)) return r.continue();
|
||||
problems.push(`network request: ${u}`);
|
||||
return r.abort();
|
||||
});
|
||||
await p.goto(`file://${out}/${name}-preview.html#still=${at}&comp=${comp}`);
|
||||
await p.waitForFunction(() => (globalThis as { __raeaStill?: unknown }).__raeaStill, null, { timeout: 10_000 }).catch(() => problems.push("the still never drew"));
|
||||
await p.screenshot({ path: `${out}/playable.png` });
|
||||
await browser.close();
|
||||
|
||||
const raw = async (png: string) => new Uint8Array(await new Response(Bun.spawn(["ffmpeg", "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { stdout: "pipe" }).stdout).arrayBuffer());
|
||||
const [a, b] = [await raw(`${out}/native.png`), await raw(`${out}/playable.png`)];
|
||||
if (a.length !== b.length) throw new Error(`parity: sizes differ (${a.length} vs ${b.length} bytes)`);
|
||||
await run(["ffmpeg", "-v", "error", "-y", "-i", `${out}/native.png`, "-i", `${out}/playable.png`, "-filter_complex", "blend=all_mode=difference", `${out}/diff.png`]);
|
||||
|
||||
// the drawn pixels: those of the native frame away from its background (the corner's colour)
|
||||
const bg = [a[0], a[1], a[2]];
|
||||
let n = 0, diff = 0, covered = 0;
|
||||
const sumA = [0, 0, 0], sumB = [0, 0, 0];
|
||||
for (let i = 0; i < a.length; i += 3) {
|
||||
if (Math.abs(a[i] - bg[0]) + Math.abs(a[i + 1] - bg[1]) + Math.abs(a[i + 2] - bg[2]) < 24) continue;
|
||||
n++;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
diff += Math.abs(a[i + k] - b[i + k]) / 3;
|
||||
sumA[k] += a[i + k];
|
||||
sumB[k] += b[i + k];
|
||||
}
|
||||
if (Math.abs(b[i] - bg[0]) + Math.abs(b[i + 1] - bg[1]) + Math.abs(b[i + 2] - bg[2]) >= 24) covered++;
|
||||
}
|
||||
const hex = (s: number[]) => "#" + s.map((v) => Math.round(v / n).toString(16).padStart(2, "0")).join("");
|
||||
const luma = (s: number[]) => 0.2126 * s[0] + 0.7152 * s[1] + 0.0722 * s[2];
|
||||
const mean = diff / Math.max(1, n);
|
||||
const bar = Number(barArg);
|
||||
console.log(`${comp} frame ${at}: ${n} drawn pixels (${((100 * n) / (a.length / 3)).toFixed(1)}% of the frame), the playable covers ${((100 * covered) / Math.max(1, n)).toFixed(1)}% of them`);
|
||||
console.log(`mean colour native ${hex(sumA)} playable ${hex(sumB)}, brightness ${(luma(sumB) / luma(sumA)).toFixed(3)}x`);
|
||||
console.log(`mean difference ${mean.toFixed(1)} / 255 (bar ${bar}): ${mean <= bar ? "ok" : "OVER"}`);
|
||||
for (const p of problems) console.log(`PROBLEM: ${p}`);
|
||||
process.exit(mean <= bar && !problems.length ? 0 : 1);
|
||||
@@ -0,0 +1,56 @@
|
||||
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
|
||||
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
|
||||
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
|
||||
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
|
||||
import { readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
|
||||
const [nArg = "32", out = "src/host/tony.bin"] = process.argv.slice(2);
|
||||
const N = Number(nArg);
|
||||
const reg = `${homedir()}/.cargo/registry/src`;
|
||||
const src = readdirSync(reg).map((d) => `${reg}/${d}/bevy_core_pipeline-0.20.0/src/tonemapping/luts/tony_mc_mapface.ktx2`).find((f) => Bun.file(f).size > 0);
|
||||
if (!src) throw new Error("tony: bevy_core_pipeline 0.20.0 isn't in ~/.cargo/registry (build raea once)");
|
||||
const ktx = new DataView(await Bun.file(src).arrayBuffer());
|
||||
const u32 = (o: number) => ktx.getUint32(o, true);
|
||||
const [format, D, superc] = [u32(12), u32(20), u32(44)];
|
||||
if (format !== 123 || D !== 48 || superc !== 2) throw new Error(`tony: expected 48³ E5B9G9R9 with zstd, got format ${format}, ${D}³, supercompression ${superc}`);
|
||||
// the one level's index: offset and length (u64s, small enough for a Number)
|
||||
const off = Number(ktx.getBigUint64(80, true)), len = Number(ktx.getBigUint64(88, true));
|
||||
const data = Bun.zstdDecompressSync(new Uint8Array(ktx.buffer, off, len));
|
||||
const px = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
|
||||
/** E5B9G9R9: three 9-bit mantissas over one shared 5-bit exponent (bias 15) */
|
||||
function texel(x: number, y: number, z: number): [number, number, number] {
|
||||
const v = px.getUint32(((z * D + y) * D + x) * 4, true);
|
||||
const s = 2 ** ((v >>> 27) - 15 - 9);
|
||||
return [(v & 511) * s, ((v >>> 9) & 511) * s, ((v >>> 18) & 511) * s];
|
||||
}
|
||||
/** the table at p in [0, 1]³, trilinear as the GPU's sampler reads it (texel centres at (i + 0.5) / D) */
|
||||
function sample(p: [number, number, number]): number[] {
|
||||
const f = p.map((c) => Math.min(D - 1, Math.max(0, c * D - 0.5)));
|
||||
const i0 = f.map(Math.floor), t = f.map((c, k) => c - i0[k]);
|
||||
const i1 = i0.map((c) => Math.min(D - 1, c + 1));
|
||||
const out = [0, 0, 0];
|
||||
for (let corner = 0; corner < 8; corner++) {
|
||||
const pick = [corner & 1, (corner >> 1) & 1, (corner >> 2) & 1];
|
||||
const w = pick.reduce((m, b, k) => m * (b ? t[k] : 1 - t[k]), 1);
|
||||
const c = texel(pick[0] ? i1[0] : i0[0], pick[1] ? i1[1] : i0[1], pick[2] ? i1[2] : i0[2]);
|
||||
for (let k = 0; k < 3; k++) out[k] += w * c[k];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const srgb = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
|
||||
|
||||
// Bevy reads the table at uv = e * (D - 1) / D + 0.5 / D for e = x / (x + 1) in [0, 1]: texel i holds e = i / (D - 1).
|
||||
// The new table keeps that layout at its own size, so the host samples it the same way with N for D.
|
||||
const at = (e: number) => e * (D - 1) / D + 0.5 / D;
|
||||
const bytes = new Uint8Array(N * N * N * 3);
|
||||
for (let z = 0; z < N; z++)
|
||||
for (let y = 0; y < N; y++)
|
||||
for (let x = 0; x < N; x++) {
|
||||
const c = sample([at(x / (N - 1)), at(y / (N - 1)), at(z / (N - 1))]);
|
||||
const o = ((z * N + y) * N + x) * 3;
|
||||
for (let k = 0; k < 3; k++) bytes[o + k] = Math.round(255 * srgb(Math.min(1, Math.max(0, c[k]))));
|
||||
}
|
||||
await Bun.write(out, bytes);
|
||||
console.log(`tony: ${N}³ from ${D}³, ${bytes.length} bytes to ${out}`);
|
||||
@@ -0,0 +1 @@
|
||||
{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["bun"] } }
|
||||
@@ -51,6 +51,7 @@
|
||||
"raea/blender/shot": ["./blender/src/shot.tsx"],
|
||||
"raea/godot": ["./godot/src/index.ts"],
|
||||
"raea/godot/shot": ["./godot/src/shot.tsx"],
|
||||
"raea/playable": ["./playable/src/index.ts"],
|
||||
"raea/pick": ["./render/src/pick.ts"],
|
||||
"raea/playtest": ["./app/src/playtest.ts"],
|
||||
"raea/ragdoll": ["./character/src/ragdoll.ts"],
|
||||
@@ -112,6 +113,8 @@
|
||||
"@raea/ui/canvas": ["./ui/src/canvas.ts"],
|
||||
"@raea/physics": ["./physics/src/index.ts"],
|
||||
"@raea/physics/*": ["./physics/src/*"],
|
||||
"@raea/playable": ["./playable/src/index.ts"],
|
||||
"@raea/playable/*": ["./playable/src/*"],
|
||||
"@raea/web": ["./web/src/index.tsx"],
|
||||
"@raea/web/*": ["./web/src/*"],
|
||||
"@raea/room": ["./room/src/index.ts"],
|
||||
|
||||
+1
-1
Submodule skills updated: 5b6bd192bd...ae81d0fdb3.
@@ -231,6 +231,7 @@ raea-app-game = "apps"
|
||||
raea-app-capcut = "apps"
|
||||
raea-app-layers = "apps"
|
||||
raea-app-play = "apps"
|
||||
raea-app-playable = "apps"
|
||||
raea-page-host = "runtime"
|
||||
raea-rune-host = "runtime"
|
||||
raea-rune-page = "runtime"
|
||||
|
||||
@@ -25,7 +25,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbs
|
||||
|
||||
// the index's groups, in the order a reader meets them; every verb is in one
|
||||
const GROUPS: [string, string, string[]][] = [
|
||||
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "export", "bundle", "app", "run"]],
|
||||
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "playable", "export", "bundle", "app", "run"]],
|
||||
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "spec", "component", "part", "add", "brand", "library", "index"]],
|
||||
["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "bench", "world", "solid", "next", "doctor", "hook", "traces"]],
|
||||
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
|
||||
|
||||
Reference in new issue
Block a user