Compare commits

...
1 Commits
Author SHA1 Message Date
shinyobjectz 8ecf1b8b1e A playable carries Bevy's world as wasm for a game whose rules are raea/ecs systems
PA12: runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh: 253 KB, 105 KB gzipped,
no imports) into sdk/playable/src/host/ecs.wasm, with the hash of what it was built from beside it, which apps/playable's
test checks. The lint's walk sees a World made; the export carries the module and its entry loads host/ecs.ts before
the game, so raea/ecs's calls (native.ts ecsCall: the engine's bridge, else the page's) reach Bevy's tables in the page
as they do in the engine. A page that can't make the module keeps raea/ecs's TypeScript tables.

World.copy() is a game's next state (copied with its systems, stepped on its own), and a native store nothing holds
frees its world, so a game's let-go states don't keep theirs. examples/playables/star-catch.tsx is a game whose rules
are three systems on a World; conformance/ecs-wasm.test.ts runs one world's life on the wasm and on the TypeScript
tables and finds them equal. The playable guide shows the pattern.
2026-12-03 11:39:23 -08:00
18 changed files with 512 additions and 47 deletions

No files matched your search

+61 -14
View File
@@ -41,6 +41,14 @@ fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it")) .ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
} }
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
fn ecs_wasm(home: &Path) -> R<String> {
use base64::Engine;
let f = home.join("sdk/playable/src/host/ecs.wasm");
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
Ok(base64::engine::general_purpose::STANDARD.encode(b))
}
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph /// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
#[derive(Clone, Copy, PartialEq, Debug)] #[derive(Clone, Copy, PartialEq, Debug)]
enum Sounds { enum Sounds {
@@ -49,11 +57,24 @@ enum Sounds {
Tone, Tone,
} }
/// The bundle's entry: the game, then the host started with three.js as its 3D drawer only for a game with 3D (PA15: /// What a page carries beside the game and the host, as the lint found the game needs it
/// a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a #[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// three.js, for a game with a 3D kind (PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
ecs: bool,
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with three.js as its 3D drawer only for a game with 3D (PA15: a
/// 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6) /// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, with_3d: bool, sounds: Sounds) -> String { fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let mut e = format!("import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx"))); let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d { if with_3d {
e.push_str(&format!("import {{ three3d }} from {:?};\n", spec(&host.join("three.ts")))); e.push_str(&format!("import {{ three3d }} from {:?};\n", spec(&host.join("three.ts"))));
} }
@@ -74,7 +95,8 @@ fn entry(game: &Path, host: &Path, with_3d: bool, sounds: Sounds) -> String {
} }
/// The game and the host in one minified script that carries its files /// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path, with_3d: bool, sounds: Sounds) -> R<String> { fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
let Carry { with_3d, sounds, .. } = carry;
let host = home.join("sdk/playable/src/host"); let host = home.join("sdk/playable/src/host");
if !host.join("main.tsx").is_file() { if !host.join("main.tsx").is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display())); return Err(format!("{}: raea's playable host isn't there", host.display()));
@@ -88,7 +110,7 @@ fn bundle(game: &Path, home: &Path, with_3d: bool, sounds: Sounds) -> R<String>
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]); flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
} }
let flags: Vec<&str> = flags.iter().map(String::as_str).collect(); let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, with_3d, sounds), &out, &flags); let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string())); let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out); let _ = std::fs::remove_file(&out);
js js
@@ -132,7 +154,9 @@ pub fn cli(args: &[String]) -> R<String> {
let is = |k: &str| found.sound[k].as_bool() == Some(true); let is = |k: &str| found.sound[k].as_bool() == Some(true);
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None }; let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
let js = bundle(&game, &raea_io_home::home(), !found.kinds.is_empty(), sounds)?; let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
let home = raea_io_home::home();
let js = bundle(&game, &home, carry)?;
// its generated sounds, made (or found made) beside the game and carried in the page (PA6) // its generated sounds, made (or found made) beside the game and carried in the page (PA6)
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default(); let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
let made = sound::make(&game, &assets)?; let made = sound::make(&game, &assets)?;
@@ -140,7 +164,11 @@ pub fn cli(args: &[String]) -> R<String> {
Sounds::None => "sound: none".into(), Sounds::None => "sound: none".into(),
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024), _ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
}); });
let js = format!("{}{js}", made.script); // Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
let js = format!("{ecs}{}{js}", made.script);
// the faces the native page draws with, for the families the game names (PA8) // the faces the native page draws with, for the families the game names (PA8)
let style = fonts::style(&js); let style = fonts::style(&js);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
@@ -173,26 +201,45 @@ pub fn cli(args: &[String]) -> R<String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Sounds, entry}; use super::{Carry, Sounds, entry};
use std::path::Path; use std::path::Path;
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
}
#[test] #[test]
fn a_2d_game_starts_with_no_drawer() { fn a_2d_game_starts_with_no_drawer() {
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), false, Sounds::None); let e = e(false, Sounds::None, false);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound"), "{e}"); assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
} }
#[test] #[test]
fn a_3d_game_starts_with_three() { fn a_3d_game_starts_with_three() {
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), true, Sounds::None); let e = e(true, Sounds::None, false);
assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}"); assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}");
} }
#[test] #[test]
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() { fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
let media = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), false, Sounds::Media); let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}"); assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), true, Sounds::Tone); let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(three3d, sound(tone));"), "{tone}"); assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(three3d, sound(tone));"), "{tone}");
} }
#[test]
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
let e = e(false, Sounds::None, true);
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
}
#[test]
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
} }
+4 -2
View File
@@ -22,6 +22,8 @@ pub struct Found {
pub refusals: Vec<String>, pub refusals: Vec<String>,
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make) /// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
pub sound: Value, pub sound: Value,
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
pub ecs: bool,
} }
const SOURCE_RULES: &[(&str, &str)] = &[ const SOURCE_RULES: &[(&str, &str)] = &[
@@ -50,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
let walked = match walk(game) { let walked = match walk(game) {
Ok(w) => w, 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 // 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, sound: Value::Null }), Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
let comps: Vec<Comp> = walked["comps"] let comps: Vec<Comp> = walked["comps"]
@@ -75,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
for k in strings("refused") { for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable")); refusals.push(format!("3D kind {k} isn't drawn in a playable"));
} }
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone() }) Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
} }
/// 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 /// 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
+11
View File
@@ -205,10 +205,21 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals. 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 That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
@done
Scenario: PA12. Bevy systems in a playable Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b) 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 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 playable, its world drawn by the light renderer
And the status (12-03): runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh,
253 KB, 105 KB gzipped, no imports) into sdk/playable/src/host/ecs.wasm, with the hash of its sources beside it
(apps/playable's test fails when runtime/ecs changes and it isn't rebuilt). The lint's walk sees a World made;
the export carries the wasm and its entry loads host/ecs.ts before the game, so raea/ecs's calls (native.ts
ecsCall) reach Bevy's world in the page as they reach it in the engine. World.copy() is a game's next state, and
a store nothing holds frees its world. examples/playables/star-catch.tsx (spawn, aim and catch systems on a
World) exports at 1,824 KB, plays to its end card in WebKit in both orientations with instant and held taps
(7,724 calls answered), and its frame 150 holds the same stars, basket and score as `raea render --frame`
(shading 17.0/255 over the 3D pixels, 0.19% of the frame past 8%: PA11's). conformance/ecs-wasm.test.ts runs
one world's life on the wasm and on the TypeScript tables and finds them equal
@done @done
Scenario: PA13. `raea playable` Scenario: PA13. `raea playable`
+143
View File
@@ -0,0 +1,143 @@
// A playable whose rules are raea/ecs systems (docs/playables.feature PA12): stars fall, a basket catches them, and
// every rule (where a star starts, how it falls, what the basket catches, the score) runs on a World. Natively the
// World's tables are Bevy's, in raea's engine; in the playable they're Bevy's too, carried in the page as wasm, so the
// game plays the same in both. Each frame's state is the World copied and stepped once, with where the person points
// written into it as a resource. Rendered with `raea render`, no one touches it: the basket follows the lowest star.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { createWorld, type World } from "raea/ecs";
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 W = 6, TOP = 8; // field: x in [-W/2, W/2], y from 0 (the basket) to TOP
const FOV = 0.733; // radians, vertical
const GOAL = 10, MISSES = 3;
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
/** The game's rules: a World with a basket, the score and misses as resources, and its systems */
function rules(): World {
const w = createWorld();
w.spawn("basket", { x: 0 });
for (const r of ["score", "missed"]) w.resource(r, 0);
for (const r of ["caught", "lost"]) w.resource(r, -99);
// a star every 20 frames, where the frame number puts it
w.system((world, f) => {
if (f % 20 === 0) world.spawn("star", { x: (((f * 7919) % 97) / 97 - 0.5) * (W - 1), y: TOP, v: 0.05 + ((f * 31) % 7) * 0.006 });
});
// the basket eases toward where the person points, or toward the lowest star before they touch
w.system((world) => {
const [b] = world.query("basket");
const x = world.get(b).x as number;
let want = world.resource<number>("aim");
if (typeof want !== "number") {
const low = world.query("star").map((id) => world.get(id)).sort((a, c) => (a.y as number) - (c.y as number))[0];
want = low ? (low.x as number) : 0;
}
world.set(b, { x: clamp(x + clamp(want - x, -0.3, 0.3), -W / 2 + 0.8, W / 2 - 0.8) });
});
// each star falls; the basket catches one at its height, and one past it is missed
w.system((world, f) => {
const bx = world.get(world.query("basket")[0]).x as number;
for (const id of world.query("star")) {
const s = world.get(id);
const y = (s.y as number) - (s.v as number);
if (y < 0.35 && y > -0.15 && Math.abs((s.x as number) - bx) < 0.85) {
world.despawn(id);
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
world.resource("caught", f);
} else if (y < -1) {
world.despawn(id);
world.resource("missed", (world.resource<number>("missed") ?? 0) + 1);
world.resource("lost", f);
} else world.set(id, { y });
}
});
return w;
}
interface Game { w: World; touched: boolean; over: "" | "won" | "lost" }
/** 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 basket's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
const p = input.touches?.[0] ?? input.pointer;
if (!p) return undefined;
const halfH = Math.tan(FOV / 2) * distance(width / height);
return ((p.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 w = s.w.copy();
const x = touched ? fieldX(input, width, height) : undefined;
if (x !== undefined) w.resource("aim", x);
w.step(frame);
const over = (w.resource<number>("score") ?? 0) >= GOAL ? "won" : (w.resource<number>("missed") ?? 0) >= MISSES ? "lost" : "";
return { w, 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}`)!;
let first: Game | null = null;
function StarCatch() {
const { width, height } = useVideoConfig();
first ??= { w: rules(), touched: false, over: "" };
const g = useGameState(first, stepOf(width, height));
const now = useCurrentFrame();
const bx = g.w.get(g.w.query("basket")[0]).x as number;
const score = g.w.resource<number>("score") ?? 0;
const missed = g.w.resource<number>("missed") ?? 0;
const pop = Math.max(0, 1 - (now - (g.w.resource<number>("caught") ?? -99)) / 8);
const flash = Math.max(0, 1 - (now - (g.w.resource<number>("lost") ?? -99)) / 12);
const d = distance(width / height);
const s = width / 1080;
return (
<AbsoluteFill style={{ background: `rgb(${12 + 80 * flash}, 16, ${40 + 20 * pop})` }}>
<Camera3d transform={Transform.fromXyz(0, TOP / 2, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={200} />
<DirectionalLight transform={Transform.fromXyz(2, 10, 6).lookingAt([0, 0, 0])} illuminance={9000} />
<Mesh3d transform={Transform.fromXyz(bx, 0, 0).withScale([1 + 0.2 * pop, 1 - 0.3 * pop, 1])} name="basket">
<Cuboid half_size={[0.8, 0.15, 0.3]} />
<StandardMaterial base_color="#2ec4b6" perceptual_roughness={0.45} />
</Mesh3d>
{g.w.query("star").map((id) => {
const st = g.w.get(id);
return (
<Mesh3d key={id} transform={Transform.fromXyz(st.x as number, st.y as number, 0)} name={`star-${id}`}>
<Sphere radius={0.22} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.7)} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{`★ ${score} / ${GOAL}`}
</div>
<div style={{ position: "absolute", right: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#ef476f" }}>
{"✕".repeat(missed)}
</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 catch"}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Ten stars!" : "So close!"} subtitle={g.over === "won" ? "The night sky is waiting" : "Can you catch ten?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="star-catch-portrait" component={StarCatch} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 40} />
<Composition id="star-catch-landscape" component={StarCatch} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 40} />
</>
));
+3
View File
@@ -20,6 +20,9 @@ use serde_json::{Map, Value, json};
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
#[cfg(target_arch = "wasm32")]
mod wasm;
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events. /// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
struct BWorld { struct BWorld {
w: World, w: World,
+63
View File
@@ -0,0 +1,63 @@
//! The ecs.* calls as a wasm module (docs/playables.feature PA12): a playable carries Bevy's own world, so a game on
//! raea/ecs keeps the tables, queries and parent/child it has natively. sdk/playable/ecs/build.sh builds it as a
//! cdylib for wasm32-unknown-unknown; the page's host/ecs.ts calls `raea_call` the way raea's V8 calls `__raea_call`.
//! Strings cross as UTF-8 in memory the page asks for with `raea_alloc`; the answer is `o` and the value's JSON, or
//! `e` and the message, where `raea_call` returns (its address in the high 32 bits, its length in the low), until the
//! next call.
use std::cell::RefCell;
thread_local! {
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
/// `len` bytes the page writes a call's name or arguments into, freed by `raea_free`
#[unsafe(no_mangle)]
pub extern "C" fn raea_alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len.max(1));
let p = v.as_mut_ptr();
std::mem::forget(v);
p
}
/// # Safety
/// `p` came from `raea_alloc(len)` and isn't used after
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_free(p: *mut u8, len: usize) {
// SAFETY: raea_alloc made it with this capacity
drop(unsafe { Vec::from_raw_parts(p, 0, len.max(1)) });
}
/// # Safety
/// each pointer holds that many bytes of UTF-8 the page wrote (raea_alloc's)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_call(
name: *const u8,
name_len: usize,
args: *const u8,
args_len: usize,
) -> u64 {
// SAFETY: the page wrote these bytes where raea_alloc said
let (name, args) = unsafe {
(
std::slice::from_raw_parts(name, name_len),
std::slice::from_raw_parts(args, args_len),
)
};
let answer = match (
std::str::from_utf8(name),
serde_json::from_slice::<serde_json::Value>(args),
) {
(Ok(n), Ok(a)) => super::call(n, &a).map(|v| v.to_string()),
_ => Err("a call's name and arguments are UTF-8 JSON".into()),
};
OUT.with(|o| {
let mut o = o.borrow_mut();
*o = match answer {
Ok(v) => format!("o{v}"),
Err(e) => format!("e{e}"),
}
.into_bytes();
((o.as_ptr() as u64) << 32) | o.len() as u64
})
}
+43 -28
View File
@@ -4,7 +4,7 @@
// same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under // same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under
// plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere. // plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere.
import { hasNative, native } from "./native"; import { ecsCall, hasEcs } from "./native";
export type Value = number | string | boolean; export type Value = number | string | boolean;
export type Cols = Record<string, Value>; export type Cols = Record<string, Value>;
@@ -52,76 +52,83 @@ interface Store {
free(): void; free(): void;
} }
/** A store's tables freed when nothing holds it any more: a game's kept states are let go (games.ts KEEP), and the
* engine's (or a playable's wasm) worlds aren't collected with them. Freeing one twice is harmless. */
const unheld = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((world) => ecsCall("ecs.free", { world })) : null;
class NativeStore implements Store { class NativeStore implements Store {
constructor(readonly world: number) {} constructor(readonly world: number) {
unheld?.register(this, world, this);
}
static create(): NativeStore { static create(): NativeStore {
return new NativeStore(native("ecs.new", {}).world); return new NativeStore(ecsCall("ecs.new", {}).world);
} }
spawn(kind: string, cols: Cols) { spawn(kind: string, cols: Cols) {
return native("ecs.spawn", { world: this.world, kind, cols }).id; return ecsCall("ecs.spawn", { world: this.world, kind, cols }).id;
} }
spawnComponents(components: Components, parent?: number) { spawnComponents(components: Components, parent?: number) {
return native("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id; return ecsCall("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
} }
insert(id: number, components: Components) { insert(id: number, components: Components) {
native("ecs.insert", { world: this.world, id, components }); ecsCall("ecs.insert", { world: this.world, id, components });
} }
remove(id: number, names: string[]) { remove(id: number, names: string[]) {
native("ecs.remove", { world: this.world, id, names }); ecsCall("ecs.remove", { world: this.world, id, names });
} }
components(id: number) { components(id: number) {
return native("ecs.components", { world: this.world, id }) as Components; return ecsCall("ecs.components", { world: this.world, id }) as Components;
} }
find(f: Find) { find(f: Find) {
return native("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids; return ecsCall("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
} }
setParent(id: number, parent: number | null) { setParent(id: number, parent: number | null) {
native("ecs.parent", { world: this.world, id, parent }); ecsCall("ecs.parent", { world: this.world, id, parent });
} }
parent(id: number) { parent(id: number) {
return native("ecs.parent", { world: this.world, id }) as number | null; return ecsCall("ecs.parent", { world: this.world, id }) as number | null;
} }
children(id: number) { children(id: number) {
return native("ecs.children", { world: this.world, id }); return ecsCall("ecs.children", { world: this.world, id });
} }
resource(name: string, value?: unknown) { resource(name: string, value?: unknown) {
return native("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value }); return ecsCall("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
} }
send(name: string, value: unknown) { send(name: string, value: unknown) {
native("ecs.send", { world: this.world, name, value }); ecsCall("ecs.send", { world: this.world, name, value });
} }
events(name: string) { events(name: string) {
return native("ecs.events", { world: this.world, name }); return ecsCall("ecs.events", { world: this.world, name });
} }
clearEvents() { clearEvents() {
native("ecs.clear_events", { world: this.world }); ecsCall("ecs.clear_events", { world: this.world });
} }
set(id: number, cols: Cols) { set(id: number, cols: Cols) {
native("ecs.set", { world: this.world, id, cols }); ecsCall("ecs.set", { world: this.world, id, cols });
} }
get(id: number) { get(id: number) {
return native("ecs.get", { world: this.world, id }); return ecsCall("ecs.get", { world: this.world, id });
} }
despawn(id: number) { despawn(id: number) {
native("ecs.despawn", { world: this.world, id }); ecsCall("ecs.despawn", { world: this.world, id });
} }
query(kind: string, where: Where) { query(kind: string, where: Where) {
return native("ecs.query", { world: this.world, kind, where }).ids; return ecsCall("ecs.query", { world: this.world, kind, where }).ids;
} }
column(kind: string, col: string) { column(kind: string, col: string) {
return native("ecs.column", { world: this.world, kind, col }); return ecsCall("ecs.column", { world: this.world, kind, col });
} }
count(kind: string) { count(kind: string) {
return native("ecs.count", { world: this.world, kind }); return ecsCall("ecs.count", { world: this.world, kind });
} }
rows() { rows() {
return native("ecs.rows", { world: this.world }); return ecsCall("ecs.rows", { world: this.world });
} }
clone() { clone() {
return new NativeStore(native("ecs.clone", { world: this.world }).world); return new NativeStore(ecsCall("ecs.clone", { world: this.world }).world);
} }
free() { free() {
native("ecs.free", { world: this.world }); unheld?.unregister(this);
ecsCall("ecs.free", { world: this.world });
} }
} }
@@ -276,7 +283,9 @@ export class World {
/** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */ /** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */
constructor(store?: Store) { constructor(store?: Store) {
this.native = store ? store instanceof NativeStore : hasNative(); this.native = store ? store instanceof NativeStore : hasEcs();
// a playable's export reads this to carry Bevy's world (sdk/playable export/walk.ts, PA12)
(globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed = true;
this.store = store ?? (this.native ? NativeStore.create() : new JsStore()); this.store = store ?? (this.native ? NativeStore.create() : new JsStore());
} }
@@ -367,7 +376,7 @@ export class World {
* hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web), * hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web),
* the same list as runtime/calls ecs.scene makes. */ * the same list as runtime/calls ecs.scene makes. */
scene(): unknown[] { scene(): unknown[] {
if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world }); if (this.store instanceof NativeStore) return ecsCall("ecs.scene", { world: this.store.world });
const store = this.store; const store = this.store;
const out: unknown[] = []; const out: unknown[] = [];
for (const id of store.find({ with: ["Mesh"] })) { for (const id of store.find({ with: ["Mesh"] })) {
@@ -394,6 +403,12 @@ export class World {
this.store.clearEvents(); this.store.clearEvents();
for (const s of this.systems) s(this, frame); for (const s of this.systems) s(this, frame);
} }
/** A copy of the world as it is now, with its systems: a game's next state (`useGameState`), stepped on its own. */
copy(): World {
const w = new World(this.store.clone());
w.systems = this.systems;
return w;
}
/** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */ /** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */
at(frame: number): World { at(frame: number): World {
if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`); if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`);
@@ -442,7 +457,7 @@ function compose(p: number[], c: number[]): number[] {
export function createWorld(opts: { native?: boolean } = {}): World { export function createWorld(opts: { native?: boolean } = {}): World {
if (opts.native === false) return new World(new JsStore()); if (opts.native === false) return new World(new JsStore());
if (opts.native === true && !hasNative()) throw new Error("createWorld({ native: true }) needs the raea engine"); if (opts.native === true && !hasEcs()) throw new Error("createWorld({ native: true }) needs the raea engine");
return new World(); return new World();
} }
+17 -1
View File
@@ -20,12 +20,28 @@ export function hasNative(): boolean {
/** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */ /** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */
export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] { export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
const call = bridge(); return through(bridge(), name, args);
}
function through<K extends NativeName>(call: NativeCall | null, name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`); if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`);
const out = call(name, JSON.stringify(args)); const out = call(name, JSON.stringify(args));
return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"]; return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"];
} }
/** raea/ecs's calls: the engine's, else a playable's (Bevy's world as wasm, sdk/playable host/ecs.ts, PA12) */
function ecsBridge(): NativeCall | null {
return bridge() ?? (globalThis as { __raeaEcs?: NativeCall }).__raeaEcs ?? null;
}
/** Whether raea/ecs's calls are here: in the engine, or in a playable that carries Bevy's world. */
export function hasEcs(): boolean {
return ecsBridge() !== null;
}
/** One of raea/ecs's calls (an `ecs.*` name), wherever its world is. */
export function ecsCall<K extends NativeName & `ecs.${string}`>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
return through(ecsBridge(), name, args);
}
/** Print a line from a headless run (raea run). */ /** Print a line from a headless run (raea run). */
export function print(...parts: unknown[]): void { export function print(...parts: unknown[]): void {
const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" "); const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ");
+19
View File
@@ -57,6 +57,25 @@ import { EndCard, InstallButton, install } from "raea/playable";
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone 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. mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
## Rules on raea/ecs
A game whose rules are systems on a raea/ecs `World` keeps Bevy's world in the playable: the export sees a World made
and carries runtime/ecs as wasm (about 250 KB in the page), loaded before the game, so the tables, queries, parents and
`scene()` answer as they do in `raea render`. Keep the World as the game's state: each step copies it, writes the
input in as a resource, and runs its systems once.
```tsx
const step = (s: Game, input: FrameInput, frame: number): Game => {
const w = s.w.copy(); // the next state, with the World's systems
if (input.pointer) w.resource("aim", input.pointer.x);
w.step(frame);
return { w, over: (w.resource<number>("score") ?? 0) >= 10 };
};
```
Draw its entities with the elements the host draws (`<Mesh3d>` with a `<Cuboid>` or `<Sphere>`), not `<Entities>`,
whose Manifold shapes need the engine. examples/playables/star-catch.tsx is the whole pattern.
## Sound ## Sound
A playable is silent until the person touches it, as every network requires, and then plays what the video ad A playable is silent until the person touches it, as every network requires, and then plays what the video ad
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# raea/ecs's world as wasm for a playable (docs/playables.feature PA12): runtime/ecs built for wasm32-unknown-unknown
# as a cdylib, size-optimised (wasm-opt -Oz when it's here), into sdk/playable/src/host/ecs.wasm, with the hash of what
# it was built from beside it (ecs.wasm.from). apps/playable's test fails when runtime/ecs changes and this isn't run.
# usage: bash sdk/playable/ecs/build.sh [TARGET_DIR]
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
target=${1:-$root/target}
out=$root/sdk/playable/src/host
cargo rustc --manifest-path "$root/Cargo.toml" -p raea-runtime-ecs --lib --crate-type cdylib --target wasm32-unknown-unknown \
--profile release --target-dir "$target" \
--config 'profile.release.opt-level="z"' --config 'profile.release.lto=true' --config 'profile.release.codegen-units=1' \
--config 'profile.release.panic="abort"' --config 'profile.release.strip=true' --config 'profile.release.debug=false'
wasm=$target/wasm32-unknown-unknown/release/raea_runtime_ecs.wasm
if command -v wasm-opt > /dev/null; then wasm-opt -Oz --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals "$wasm" -o "$out/ecs.wasm"; else cp "$wasm" "$out/ecs.wasm"; fi
bash "$root/sdk/playable/ecs/from.sh" > "$out/ecs.wasm.from"
echo "ecs.wasm: $(wc -c < "$out/ecs.wasm" | tr -d ' ') bytes, $(gzip -9c "$out/ecs.wasm" | wc -c | tr -d ' ') gzipped"
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# what ecs.wasm is built from (build.sh): runtime/ecs's sources and manifest, and the Bevy it's on (Cargo.lock's line)
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
{ cat "$root"/runtime/ecs/Cargo.toml "$root"/runtime/ecs/src/*.rs; grep -A1 '^name = "bevy_ecs"$' "$root/Cargo.lock"; } | shasum -a 256 | cut -c1-64
+3 -1
View File
@@ -31,5 +31,7 @@ export default function walk() {
const params = { ...(a.options ?? {}), seconds: a.seconds }; const params = { ...(a.options ?? {}), seconds: a.seconds };
return { src: a.src, model: a.kind, prompt: a.prompt, seed: typeof a.options?.seed === "number" ? a.options.seed : 1, params }; return { src: a.src, model: a.kind, prompt: a.prompt, seed: typeof a.options?.seed === "number" ? a.options.seed : 1, params };
}); });
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)), sound: { tone, media: media || assets.length > 0, assets } }; // a raea/ecs World made (as the game's module loaded, or as it rendered): the page carries Bevy's world (PA12)
const ecs = (globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed === true;
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)), sound: { tone, media: media || assets.length > 0, assets }, ecs };
} }
+51
View File
@@ -0,0 +1,51 @@
// raea/ecs's world in a playable (docs/playables.feature PA12): Bevy's own ECS (runtime/ecs, built to ecs.wasm by
// sdk/playable/ecs/build.sh), which the export carries as __raeaEcsWasm for a game that makes a World. The entry
// imports this before the game, so a World made as the game's module loads is already Bevy's. Calls go through
// __raeaEcs as raea's V8 sends them through __raea_call (sdk/app native.ts ecsCall); a page where the module can't be
// made keeps raea/ecs's TypeScript tables, which behave the same.
type Exports = {
memory: WebAssembly.Memory;
raea_alloc(len: number): number;
raea_free(p: number, len: number): void;
/** where the answer is: its address in the high 32 bits, its length in the low */
raea_call(np: number, nl: number, ap: number, al: number): bigint;
};
/** What ran, for tools/check.ts: the calls the world answered */
export type EcsStats = { calls: number; bytes: number };
const g = globalThis as { __raeaEcsWasm?: string; __raeaEcs?: (name: string, json: string) => string; __raeaEcsStats?: EcsStats; __raea_call?: unknown };
if (g.__raeaEcsWasm && typeof g.__raea_call !== "function") {
try {
const s = atob(g.__raeaEcsWasm);
const bin = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++) bin[i] = s.charCodeAt(i);
// synchronous, as raea/ecs's calls are: WebKit compiles a module of any size on the page's thread
const x = new WebAssembly.Instance(new WebAssembly.Module(bin), {}).exports as unknown as Exports;
const enc = new TextEncoder();
const dec = new TextDecoder();
const stats: EcsStats = (g.__raeaEcsStats = { calls: 0, bytes: bin.length });
const put = (text: string): [number, number] => {
const b = enc.encode(text);
const p = x.raea_alloc(b.length);
new Uint8Array(x.memory.buffer, p, b.length).set(b);
return [p, b.length];
};
g.__raeaEcs = (name, json) => {
const [np, nl] = put(name);
const [ap, al] = put(json);
const at = x.raea_call(np, nl, ap, al);
x.raea_free(np, nl);
x.raea_free(ap, al);
const out = dec.decode(new Uint8Array(x.memory.buffer, Number(at >> 32n), Number(at & 0xffffffffn)));
stats.calls++;
if (out[0] !== "o") throw new Error(`${name}: ${out.slice(1)}`);
return out.slice(1);
};
} catch (e) {
console.warn("raea playable: Bevy's world didn't load, so raea/ecs keeps its TypeScript tables", e);
}
}
delete g.__raeaEcsWasm;
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
2e6fac7b3f0fba3852f43ff79bba2546e489eb6afabfb55c70dbe42828d4c72c
+3 -1
View File
@@ -78,7 +78,9 @@ const state = (await p.evaluate(() => ({
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [], events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
// a game with sound (PA6): what played after the first touch (host/sound.ts) // a game with sound (PA6): what played after the first touch (host/sound.ts)
sound: (globalThis as { __raeaSound?: { events: number; clips: number; decoded: number; failed: number } }).__raeaSound ?? null, sound: (globalThis as { __raeaSound?: { events: number; clips: number; decoded: number; failed: number } }).__raeaSound ?? null,
}))) as { canvas: boolean; parts: number; page: number; events: unknown[]; sound: { events: number; clips: number; decoded: number; failed: number } | null }; // a game on raea/ecs: the calls Bevy's world (the page's wasm) answered (PA12)
ecs: (globalThis as { __raeaEcsStats?: { calls: number; bytes: number } }).__raeaEcsStats ?? null,
}))) as { canvas: boolean; parts: number; page: number; events: unknown[]; sound: { events: number; clips: number; decoded: number; failed: number } | null; ecs: { calls: number; bytes: number } | null };
console.log(`page: ${JSON.stringify(state)}`); console.log(`page: ${JSON.stringify(state)}`);
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty"); 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"); if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
+24
View File
@@ -0,0 +1,24 @@
// raea/ecs on a playable's Bevy world (docs/playables.feature PA12): the world the page carries as wasm (sdk/playable
// host/ecs.ts, runtime/ecs built by sdk/playable/ecs/build.sh) answers a world's life as raea/ecs's TypeScript tables
// do: spawns, queries, columns, parents, scene(), resources, events, copies stepped on their own and at(frame).
// Each run is its own process, so the page's bridge never reaches another test.
import { expect, test } from "bun:test";
import { join } from "node:path";
const run = (wasm: boolean) => {
const r = Bun.spawnSync([process.execPath, join(import.meta.dir, "ecs-wasm/run.ts")], { env: { ...process.env, WASM: wasm ? "1" : "0" }, stderr: "pipe" });
expect(r.stderr.toString()).not.toMatch(/didn't load|Error/);
expect(r.exitCode).toBe(0);
return JSON.parse(r.stdout.toString()) as Record<string, unknown>;
};
test("a playable's Bevy world (wasm) and raea/ecs's TypeScript tables live the same life", () => {
const bevy = run(true);
const ts = run(false);
expect(bevy.native).toBe(true);
expect(ts.native).toBe(false);
const { native: _a, ...b } = bevy;
const { native: _b, ...t } = ts;
expect(b).toEqual(t);
expect(b.after).toEqual({ score: 12, stars: 0, first: 12, caught: 12, basket: { id: expect.any(Number), kind: "basket", x: 0 } });
});
+44
View File
@@ -0,0 +1,44 @@
// One world's life, printed as JSON: on a playable's Bevy world (the page's ecs.wasm, loaded as its host loads it)
// when run with WASM=1, else on raea/ecs's TypeScript tables. ecs-wasm.test.ts runs it both ways and compares.
import { readFileSync } from "node:fs";
import { join } from "node:path";
if (process.env.WASM === "1") {
(globalThis as { __raeaEcsWasm?: string }).__raeaEcsWasm = readFileSync(join(import.meta.dir, "../../../playable/src/host/ecs.wasm")).toString("base64");
await import("../../../playable/src/host/ecs.ts");
}
const { createWorld } = await import("raea/ecs");
const w = createWorld();
const out: Record<string, unknown> = { native: w.native };
for (let i = 0; i < 12; i++) w.spawn("star", { x: i - 6, y: 10 + (i % 3), side: i % 2 ? "odd" : "even" });
const basket = w.spawn("basket", { x: 0 });
w.resource("score", 0);
w.system((world, f) => {
for (const id of world.query("star")) {
const y = (world.get(id).y as number) - 1;
if (y < 0) {
world.despawn(id);
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
world.send("caught", { id, f });
} else world.set(id, { y });
}
});
out.query = w.query("star", [["side", "==", "odd"], ["x", ">", -3]]);
out.column = w.column("star", "y");
const parent = w.add({ Transform: { x: 1, y: 0, z: 0 }, Mesh: { shape: "box" } });
const child = w.add({ Transform: { x: 0, y: 2, z: 0 }, Mesh: { shape: "ball" } }, { parent });
out.children = w.children(parent).length === 1 && w.parent(child) === parent;
out.find = w.find({ with: ["Mesh"], where: [["Transform.y", ">", 1]] }).length;
out.scene = w.scene();
// a game's next state: copied, stepped on its own, the first left as it was
let s = w;
const caught: unknown[] = [];
for (let f = 0; f < 14; f++) {
s = s.copy();
s.step(f);
caught.push(...s.events("caught"));
}
out.after = { score: s.resource("score"), stars: s.count("star"), first: w.count("star"), caught: caught.length, basket: s.get(basket) };
out.at = w.at(11).resource("score");
console.log(JSON.stringify(out));