Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

5.5 KB
Raw Blame
//! `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"))
}