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.

MV1-MV3: random, interpolateColors and OffthreadVideo from raea (#176)

shinyobjectz666acf6050c6
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index af4aadbf..e7fd361f 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -31,7 +31,7 @@ The composition, the app, and the specs and notes an agent writes.
| Import | What it's for | Exports |
| --- | --- | --- |
-| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 20 components, 9 hooks, 62 functions, 11 values, 107 types |
+| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 64 functions, 11 values, 108 types |
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 4 functions, 3 classes, 17 values, 17 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 5 functions, 24 types |
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
diff --git a/docs/manual/reference/sdk/raea.md b/docs/manual/reference/sdk/raea.md
index 7611e005..48ed5f13 100644
--- a/docs/manual/reference/sdk/raea.md
+++ b/docs/manual/reference/sdk/raea.md
@@ -38,7 +38,7 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
```
-`raea` exports 20 components, 9 hooks, 62 functions, 11 values, 107 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
+`raea` exports 21 components, 9 hooks, 64 functions, 11 values, 108 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
## Components
@@ -199,6 +199,18 @@ component, whose box it can't reach, or a part with a mask, is placed inside a f
| `keys` | `Partial<Record<NudgeProp, NudgeKey[]>>` | any of the above over time: its keys, each [frame, value, ease?], in frames from where this part's time starts (its <Sequence>'s first frame), by the names in NUDGE_KEYED ("mask.x", "chroma.strength", "crop.left" for what is inside a mask, a key or a crop). A keyed property's still value is ignored. |
| `children` | `ReactNode` | the part it places: an element, or a component, which moves inside a full-frame layer |
+### `OffthreadVideo`
+
+`<Video>` under the name a project moving from another React video tool may use for it, with its props.
+
+| Prop | Type | What it does |
+| --- | --- | --- |
+| `framing` | `"face"` | ours: frame the take on the largest face |
+| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
+| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
+
+Also takes the props of [`MediaProps`](video.md#mediaprops).
+
### `Overlay`
Its children only in a render asked for the overlay `name`.
@@ -541,6 +553,17 @@ function interpolate(x: number, input: readonly number[], output: readonly numbe
Used in: [manual: turntable](https://github.com/shinyobjectz/raea/blob/main/docs/manual/examples/turntable.tsx), [manual: hello](https://github.com/shinyobjectz/raea/blob/main/docs/manual/examples/hello.tsx).
+### `interpolateColors`
+
+`interpolate` for CSS colours: `input` mapped through `inputRange` to a colour between the two of `outputRange` it
+falls between, mixed in sRGB with alpha, as `rgba(r, g, b, a)` (channels rounded to whole numbers). Any CSS colour
+the canvas parses: a name, #rgb, #rrggbb(aa), rgb(a)() or hsl(a)(). Held at the end colours outside the range;
+`options` can change that and add an easing, as `interpolate`'s.
+
+```ts
+function interpolateColors(input: number, inputRange: readonly number[], outputRange: readonly string[], options?: InterpolateOptions): string
+```
+
### `isGeneratedAsset`
Whether a value is a generated asset (what sao, tokensynthNote and lyria return), not a file path.
@@ -652,6 +675,16 @@ a slow push-in on footage: scale 1 to 1 + `amount` (0.04) across `frames` (90),
function pushIn(o?: { amount?: number; frames?: number; }): Move
```
+### `random`
+
+A number in [0, 1) from a seed, a string or a number: the same on every frame, every run and every machine, so a
+scatter seeded `random("star" + i)` holds still while the frames change. A number seeds as its text (1 and "1" give
+the same). `null` is `Math.random()`, which raea seeds per frame. `hash01` is the same for integers only.
+
+```ts
+function random(seed: string | number | null): number
+```
+
### `regionBand`
Works out the vertical band each name stands for, given perception and the composition size.
@@ -1441,6 +1474,14 @@ A number, dragged on a slider when it has both ends.
| `cost` | `ControlCost` | how a change reaches the picture: "live" unless said |
| `about` | `string` | one line on what it changes, for the panel's tooltip and an agent reading the code |
+### `OffthreadVideoProps`
+
+`<OffthreadVideo>`'s props: `<Video>`'s.
+
+```ts
+type OffthreadVideoProps = VideoProps
+```
+
### `PanelAction`
One action: what it does (for the agent), its arguments by name with a few words each, and what it does to the
diff --git a/docs/move-in.feature b/docs/move-in.feature
new file mode 100644
index 00000000..759041bf
--- /dev/null
+++ b/docs/move-in.feature
@@ -0,0 +1,52 @@
+@spec
+Feature: A project moving to raea from another React video tool keeps its names and its CLI habits (#175, #176)
+ Public #176 and #175 (@Ragulsundaram, moving a project to raea, 11-18): everything else they use was there
+ (Sequence, Series, Loop, Freeze, spring, measureSpring, delayRender, staticFile), and these were missing. Each
+ scenario says what the name does, as the issue describes it; raea's code is its own, and `random`'s numbers are
+ raea's.
+
+ @done
+ Scenario: MV1. random(seed): a number in [0, 1) from a string or a number seed, the same on every frame and run
+ Given `random("r" + i)` in a composition
+ Then it is the same on frames 0 and 99, on a second run and on another machine, in [0, 1), and
+ `random("a") !== random("b")`; a number seeds as its text, and `random(null)` is `Math.random()`
+ And 11-20, built: sdk/raea/src/random-colors.ts, exported from `raea`; FNV-1a over the UTF-16 units and murmur3's
+ finaliser. sdk/raea/conformance/random-colors.test.ts pins three values (a change to the hash moves every
+ seeded scatter) and checks 2,000 seeds are in range and 1,000 are distinct with a mean within 0.05 of 0.5.
+
+ @done
+ Scenario: MV2. interpolateColors(input, inputRange, outputRange): interpolate for CSS colours, as rgba()
+ Given `interpolateColors(5, [0, 10], ["#ff0000", "#0000ff"])`
+ Then it is "rgba(128, 0, 128, 1)", the ends give the end colours exactly, and outside the range it holds them
+ And names, #rgb(a), rgb(a)() and hsl(a)() parse (@raea/ui's canvas parser), alpha mixes, and a colour that
+ doesn't parse throws naming it
+ And 11-20, built: sdk/raea/src/random-colors.ts on `interpolate` per channel, clamped unless `options` says
+ otherwise; the conformance test checks the issue's values, alpha, three keyframes and the error.
+
+ @done
+ Scenario: MV3. <OffthreadVideo> is <Video>
+ Given `<OffthreadVideo src={staticFile("a.mp4")} />`
+ Then it draws what `<Video>` with the same props draws
+ And 11-20, built: the same component under both names (the conformance test checks they're one value).
+
+ Scenario: MV4. Props from the command line: --props, getInputProps() and a Composition's calculateMetadata
+ Given a composition with `defaultProps={{n: 1}}` and `calculateMetadata: ({props}) => ({durationInFrames:
+ props.frames})`
+ When it is rendered with `--props '{"n": 2, "frames": 90}'`, or `--props props.json`
+ Then it draws 2, `getInputProps().n` is 2 anywhere in the tree, and the render is 90 frames
+ And the props reach every place a composition is run (render, play, check, the app's preview), and the render's
+ manifest keeps them, so a check of the file knows what it was rendered with
+ And `--input` stays a game's input timeline
+ And the flag goes in with its manual entry and the CLI reference check in the same change (a new flag in the
+ shared build fails every lane's manual reference until it lands)
+
+ Scenario: MV5. --scale S draws a composition at S times its size, laid out at its own
+ Given a 1000x1000 composition with a 200x200 box at (0, 0)
+ When it is rendered with `--scale 0.5`
+ Then the file is 500x500 and the box covers (0, 0) to (100, 100), its edges drawn at the output's size (text,
+ borders and images at 500 px, not a 1000 px frame scaled down)
+ And above 1 for stills (a 2x still of a 1080p composition is 3840x2160)
+ And 3D cameras render at the scaled size, screen-space effects (bloom's radius, outlines, grain) keep their look,
+ media decode at the size drawn, and the manifest says the scale, so `raea check` judges text sizes and safe
+ areas at the composition's size
+ And the flag goes in with its manual entry, as MV4's
diff --git a/sdk/raea/conformance/random-colors.test.ts b/sdk/raea/conformance/random-colors.test.ts
new file mode 100644
index 00000000..7c5133ea
--- /dev/null
+++ b/sdk/raea/conformance/random-colors.test.ts
@@ -0,0 +1,56 @@
+// Names a project moving from another React video tool uses (#176, docs/move-in.feature MV1-MV3): random,
+// interpolateColors and OffthreadVideo, each as the issue describes it.
+import { describe, expect, test } from "bun:test";
+import { OffthreadVideo, Video, interpolateColors, random } from "../src";
+
+describe("random(seed)", () => {
+ test("the same seed gives the same number, in [0, 1)", () => {
+ expect(random("a")).toBe(random("a"));
+ expect(random(7)).toBe(random(7));
+ expect(random("a")).not.toBe(random("b"));
+ for (let i = 0; i < 2000; i++) {
+ const v = random("r" + i);
+ expect(v >= 0 && v < 1).toBe(true);
+ }
+ });
+ test("seeds a letter apart spread over the range", () => {
+ const vs = Array.from({ length: 1000 }, (_, i) => random("star" + i));
+ const mean = vs.reduce((a, b) => a + b, 0) / vs.length;
+ expect(Math.abs(mean - 0.5)).toBeLessThan(0.05);
+ expect(new Set(vs).size).toBe(vs.length);
+ });
+ test("a number seeds as its text; null is Math.random", () => {
+ expect(random(1)).toBe(random("1"));
+ const v = random(null);
+ expect(v >= 0 && v < 1).toBe(true);
+ expect(() => random({} as unknown as string)).toThrow(TypeError);
+ });
+ test("pinned values, so a change to the hash (which moves every seeded scatter) is seen", () => {
+ expect(random("a")).toBe(0.10352621669881046);
+ expect(random(0)).toBe(0.3942956554237753);
+ expect(random("star1")).toBe(0.8393113499041647);
+ });
+});
+
+describe("interpolateColors", () => {
+ test("halfway from red to blue, and the ends exactly", () => {
+ expect(interpolateColors(5, [0, 10], ["#ff0000", "#0000ff"])).toBe("rgba(128, 0, 128, 1)");
+ expect(interpolateColors(0, [0, 10], ["#ff0000", "#0000ff"])).toBe("rgba(255, 0, 0, 1)");
+ expect(interpolateColors(10, [0, 10], ["#ff0000", "#0000ff"])).toBe("rgba(0, 0, 255, 1)");
+ });
+ test("held at the end colours outside the range", () => {
+ expect(interpolateColors(-5, [0, 10], ["red", "blue"])).toBe("rgba(255, 0, 0, 1)");
+ expect(interpolateColors(50, [0, 10], ["red", "blue"])).toBe("rgba(0, 0, 255, 1)");
+ });
+ test("names, rgba() and hsl(), alpha mixed too, through more than two keyframes", () => {
+ expect(interpolateColors(1, [0, 2], ["rgba(0, 0, 0, 0)", "rgba(255, 255, 255, 1)"])).toBe("rgba(128, 128, 128, 0.5)");
+ expect(interpolateColors(15, [0, 10, 20], ["white", "hsl(120, 100%, 50%)", "black"])).toBe("rgba(0, 128, 0, 1)");
+ });
+ test("a colour that doesn't parse is named", () => {
+ expect(() => interpolateColors(0, [0, 1], ["#ff0000", "nonsense"])).toThrow(/"nonsense" isn't a CSS colour/);
+ });
+});
+
+test("OffthreadVideo is Video", () => {
+ expect(OffthreadVideo).toBe(Video);
+});
diff --git a/sdk/raea/src/index.tsx b/sdk/raea/src/index.tsx
index d93df9a3..64ee407c 100644
--- a/sdk/raea/src/index.tsx
+++ b/sdk/raea/src/index.tsx
@@ -41,6 +41,8 @@ export {
type VolumeProp,
} from "@raea/video/media";
export { word, useWords, findPhrase, type WordOptions } from "@raea/video/words";
+// names a project moving from another React video tool uses (#176)
+export { random, interpolateColors, OffthreadVideo, type OffthreadVideoProps } from "./random-colors";
export {
song, songAt, useSong, SongPlot,
type Song, type SongMap, type SongMoment, type SongEvent, type SongEventKind, type SongSection, type SongBar, type SongHit,
diff --git a/sdk/raea/src/random-colors.ts b/sdk/raea/src/random-colors.ts
new file mode 100644
index 00000000..3cad2103
--- /dev/null
+++ b/sdk/raea/src/random-colors.ts
@@ -0,0 +1,52 @@
+// Three names a project moving to raea from another React video tool uses (#176, docs/move-in.feature MV1-MV3): a
+// seeded `random`, `interpolateColors`, and `<OffthreadVideo>` for `<Video>`.
+import { interpolate, type InterpolateOptions } from "@raea/math/interpolate";
+import { Video, type VideoProps } from "@raea/video/media";
+import { parseColor } from "@raea/ui/canvas";
+
+/**
+ * A number in [0, 1) from a seed, a string or a number: the same on every frame, every run and every machine, so a
+ * scatter seeded `random("star" + i)` holds still while the frames change. A number seeds as its text (1 and "1" give
+ * the same). `null` is `Math.random()`, which raea seeds per frame. `hash01` is the same for integers only.
+ */
+export function random(seed: string | number | null): number {
+ if (seed === null) return Math.random();
+ if (typeof seed !== "string" && typeof seed !== "number") throw new TypeError(`random: the seed is a string or a number, not ${typeof seed}`);
+ const text = String(seed);
+ // FNV-1a over the UTF-16 units, then murmur3's finaliser so seeds a letter apart land far apart
+ let h = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ h ^= h >>> 16;
+ h = Math.imul(h, 0x85ebca6b);
+ h ^= h >>> 13;
+ h = Math.imul(h, 0xc2b2ae35);
+ h ^= h >>> 16;
+ return (h >>> 0) / 4294967296;
+}
+
+/**
+ * `interpolate` for CSS colours: `input` mapped through `inputRange` to a colour between the two of `outputRange` it
+ * falls between, mixed in sRGB with alpha, as `rgba(r, g, b, a)` (channels rounded to whole numbers). Any CSS colour
+ * the canvas parses: a name, #rgb, #rrggbb(aa), rgb(a)() or hsl(a)(). Held at the end colours outside the range;
+ * `options` can change that and add an easing, as `interpolate`'s.
+ */
+export function interpolateColors(input: number, inputRange: readonly number[], outputRange: readonly string[], options?: InterpolateOptions): string {
+ if (!Array.isArray(outputRange)) throw new TypeError("interpolateColors: the output keyframes must be an array of colours");
+ const colours = outputRange.map((c) => {
+ const rgba = parseColor(String(c));
+ if (!rgba) throw new TypeError(`interpolateColors: ${JSON.stringify(c)} isn't a CSS colour (a name, #rrggbb, rgb() or hsl())`);
+ return rgba;
+ });
+ const opts: InterpolateOptions = { extrapolateLeft: "clamp", extrapolateRight: "clamp", ...options };
+ const [r, g, b, a] = [0, 1, 2, 3].map((k) => interpolate(input, inputRange, colours.map((c) => c[k]), opts));
+ const byte = (v: number) => Math.round(Math.min(255, Math.max(0, v)));
+ return `rgba(${byte(r)}, ${byte(g)}, ${byte(b)}, ${Number(Math.min(1, Math.max(0, a)).toFixed(4))})`;
+}
+
+/** `<Video>` under the name a project moving from another React video tool may use for it, with its props. */
+export const OffthreadVideo = Video;
+/** `<OffthreadVideo>`'s props: `<Video>`'s. */
+export type OffthreadVideoProps = VideoProps;
diff --git a/tools/manual-ref/sdk.ts b/tools/manual-ref/sdk.ts
index 6bea86ee..f625fcb8 100644
--- a/tools/manual-ref/sdk.ts
+++ b/tools/manual-ref/sdk.ts
@@ -14,7 +14,7 @@ const ROOT = path.resolve(import.meta.dir, "../..")
const ts = createRequire(path.join(ROOT, "sdk/shell/package.json"))("typescript") as typeof import("typescript")
const SRC = path.join(ROOT, "sdk/raea/src")
const REPO = "https://github.com/shinyobjectz/raea/blob/main"
-const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-[a-z-]+\.ts)$/
+const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^random-colors\.ts|^page-layout\.ts|^dom-[a-z-]+\.ts)$/
const [mode = "check", dirArg] = process.argv.slice(2)
if (mode !== "gen" && mode !== "check") throw new Error("usage: sdk.ts gen|check [DIR]")
const out = path.resolve(dirArg ?? path.join(ROOT, "docs/manual/reference/sdk"))
diff --git a/tools/taxonomy.list b/tools/taxonomy.list
index 08ac52e3..576b5462 100644
--- a/tools/taxonomy.list
+++ b/tools/taxonomy.list
@@ -6,6 +6,7 @@
web Audio HTML's <audio>: sound in step with the frame
web Img HTML's <img>: the renderer holds the frame until it has loaded
web Video HTML's <video>: a clip in step with the frame
+raea OffthreadVideo <Video> under the name a project moving in from another React video tool uses (docs/move-in.feature MV3)
web OffscreenCanvas the web's OffscreenCanvas: a canvas no page shows, its 2D context measured and read back (layout-reads LR6)
web Tone Tone.js as a namespace (import * as Tone), as its users write it
web Loop Tone.js's Loop: a callback every interval in transport time