# Introduction effects makes video from code. A video is a list of scenes, a scene is a procedure, and the procedure is handed one thing: the time. It draws what the frame looks like at that time, with Skia, from compiled Odin. A command-line renderer turns a project into an MP4; a desktop editor previews it on the GPU and reloads your code when you save. ```odin intro :: proc(s: fx.Shot) { fx.backdrop(.Night) rise := 30 * (1 - fx.ep(s.t, s.start, s.start + 0.6)) if fx.group({o = fx.fade(s), y = rise}) { fx.caption("No browser in the loop.", {160, 440}, 112, fx.theme.nt) } } ``` That is a whole scene: a background, and a headline that rises 30 pixels while it fades in. There is no timeline object, no keyframe store and no retained tree of elements. Every value on screen is computed from `s.t`. ## Why it is built this way **A frame is a pure function of time.** Any frame can be drawn on its own, in any order, on any thread. The renderer gives each core its own stretch of the film, and an agent (or you) can ask for a single frame at 7.6 seconds without rendering the 7.6 seconds before it. **No browser.** Most video-as-code tools render by loading a web page in headless Chrome and taking a screenshot per frame. effects calls Skia directly from native code and writes raw pixels into the encoder's pipe. A frame of interface, text and layers takes about 2 ms on one CPU thread. See [what things cost](/docs/performance/). **Code you can read back.** A project is a directory of plain source files. They diff, they review, and a model can write and correct them. ## What is in the box | Part | What it is | | --- | --- | | `fx` | The library scenes are written with: animation, drawing, groups and grading, post filters, shaders, a little 3D, type, layout, an interface kit, sound, a synth. This is most of these docs. | | `effects` | The command-line renderer: `render`, `still`, `mix`, `bench`, `build`, `beats`. See [the CLI](/docs/cli/). | | `effects-edit` | The desktop editor: GPU preview, timeline, hot reload. See [the editor](/docs/editor/). | | `sk`, `shim` | Odin bindings and a small C layer over Skia. You rarely touch them directly; paths are the exception. | ## Where to go next 1. [Install](/docs/install/) the toolchain and build the two programs. 2. Make [your first video](/docs/first-video/): one file, one scene, one render. 3. Read [scenes and time](/docs/scenes/) to learn how a video is put together. 4. Then use the `fx` reference as you need it. Every page there has players that run the real library in your browser: drag the playhead, change an argument, read the code that drew the frame. If you are an agent, or are setting one up to write videos, read [working as an agent](/docs/agents/) first, and fetch [llms-full.txt](/llms-full.txt) for these docs as one plain-text file. ## What it does not do It is honest to say what is missing. Renders are 8-bit H.264 in BT.709; there is no HDR output. The toolchain runs on Linux. Shaders run on the CPU in final renders, which makes full-screen SkSL the expensive thing in a film. There is no undo in the editor. Text runs with mixed weights or colors inside one paragraph are composed from several text calls rather than one. --- # Install effects is built from source. It runs on Linux (x86-64) and uses [Nix](https://nixos.org/download/) to fetch Skia and the libraries Skia needs, so those do not have to be installed by hand. ## What you need | Tool | Used for | | --- | --- | | `nix` | `build.sh` asks it for Skia, HarfBuzz, ICU, fontconfig and SDL3. | | `odin` | The compiler. Also needed at run time: the renderer compiles your project every time it loads it. | | `ffmpeg`, `ffprobe` | Encoding, and decoding footage and audio. Needed at run time. | | `g++` | Compiles the Skia shim once. | If `odin` and `ffmpeg` are not installed system-wide, a Nix shell provides them: ```bash $ nix shell nixpkgs#odin nixpkgs#ffmpeg ``` Run the renderer and the editor from a shell that has both on its `PATH`. ## Build ```bash $ git clone https://github.com/fipso/effects $ cd effects $ ./build.sh # shim + CLI + editor → build/ ``` The first build compiles Skia with clang and takes a few minutes; later builds take seconds. To rebuild one part, name it: `./build.sh shim`, `./build.sh cli`, `./build.sh edit`. | Output | What it is | | --- | --- | | `build/libskshim.so` | The C layer over Skia, with Skia linked in statically. | | `build/effects` | The command-line renderer. | | `build/effects-edit` | The editor. | The binaries find the shim through an rpath, so they run from anywhere without `LD_LIBRARY_PATH`. They do remember where the repository is (to find `fx` and the bundled fonts), so rebuild after moving it. > **Why clang?** Skia only fully vectorizes its raster pipeline under clang. A full-screen gradient took about 20 ms with a gcc build of Skia and about 5 ms with the clang one, so `nix/skia.nix` rebuilds nixpkgs' Skia with clang, as static libraries. To use a Skia you built yourself, point `SKIA` at the built libraries and `SKIA_SRC` at its source tree before running `build.sh`. ## Check that it works The repository contains one project, `projects/fable`. Draw a frame of it: ```bash $ build/effects still projects/fable 31.6 built fable in 0.41s (-o:none) /…/projects/fable/.effects/stills/0031.60.png ``` Open the PNG. If it shows a frame of the film, everything works: the project compiled, Skia drew, and the fonts loaded. Then open it in the editor: ```bash $ build/effects-edit projects/fable ``` A full render of fable is a long one (3,600 frames, most of them full-screen shaders: about 13 minutes on 8 cores). Render a few seconds of it instead: ```bash $ build/effects render projects/fable --from 30 --to 34 ``` ## If something fails | Symptom | Cause | | --- | --- | | `cannot run odin` | `odin` is not on `PATH` in this shell. | | `build/effects: cannot execute: required file not found` | The Nix store paths the binary was linked against were garbage-collected. Run `./build.sh shim cli` again. | | Text is missing or in the wrong font | A font file was not found; the renderer prints `fx: cannot load font` with the path. | | `ffmpeg failed for …seg000.mp4` | `ffmpeg` is missing, or it was built without libx264. | --- # Your first video A project is a directory of Odin files. It exports one procedure, `effects_video`, that describes the video. This page builds one from nothing. ## One file Make a directory and put this in `main.odin`: ```odin package spot import fx "effects:fx" SCENES := [?]fx.Scene { {name = "intro", start = 0, dur = 3.4, draw = intro}, } @(export) effects_video :: proc() -> ^fx.Video { return fx.video({name = "Spot", scenes = SCENES[:]}) } intro :: proc(s: fx.Shot) { fx.backdrop(.Night) rise := 30 * (1 - fx.ep(s.t, s.start, s.start + 0.6)) if fx.group({o = fx.fade(s), y = rise}) { fx.caption("No browser in the loop.", {160, 440}, 112, fx.theme.nt) } fx.grain(0.035) } ``` Line by line: - The package name can be anything. `effects:fx` is the library; the renderer tells the compiler where it is. - `SCENES` is the timeline: one scene called `intro`, starting at 0, 3.4 seconds long, drawn by the procedure `intro`. The table is a global because `fx.video` copies the slice it is given and the literal has to live long enough to be copied. - `effects_video` is what the renderer looks for. `fx.video` fills in what you leave out: 1920×1080, 60 fps, a black background, and a duration that ends with the last scene. - `intro` draws one frame. `s` is a [`Shot`](/docs/scenes/#shot): `s.t` is the video's time, `s.start` when this scene began. ```odin scenes_first :: proc(s: fx.Shot) { fx.backdrop(.Night) rise := 30 * (1 - fx.ep(s.t, s.start, s.start + 0.6)) if fx.group({o = fx.fade(s), y = rise}) { fx.caption("No browser in the loop.", {160, 440}, 112, fx.theme.nt) } fx.grain(0.035) } ``` ## Look at a frame Before rendering anything, draw single frames: ```bash $ build/effects still projects/spot 0.3 1.5 built spot in 0.38s (-o:none) /…/projects/spot/.effects/stills/0000.30.png /…/projects/spot/.effects/stills/0001.50.png ``` `still` compiles the project without optimization (fast to build) and writes a PNG for every time you name. This is the quickest way to check a change, and the way an agent checks its own work. ## Watch it ```bash $ build/effects-edit projects/spot ``` The editor plays the video on the GPU and shows the scenes on a timeline. Leave it open: every time you save a source file it recompiles (about 0.4 s) and swaps the new code in under the playhead. A compile error is shown over the preview. See [the editor](/docs/editor/). ## A second scene Scenes are drawn in list order and may overlap, which is how one scene fades out over the next: ```odin SCENES := [?]fx.Scene { {name = "intro", start = 0, dur = 3.4, draw = intro}, {name = "claim", start = 3.0, dur = 4, draw = claim}, } claim :: proc(s: fx.Shot) { if fx.group({o = fx.fade(s)}) { fx.backdrop(.Night) arrive := fx.Letters{t0 = s.start + 0.3, step = 0.03, rise = 40} fx.letters("Every frame is a function of time.", {160, 470}, fx.headline(96), fx.theme.nt, arrive) } } ``` The whole scene is inside one group, so its background fades in over the end of `intro`. `letters` is from [type in motion](/docs/type/): each letter rises 40 px, 0.03 s after the one before, starting 0.3 s into the scene. ## Render it ```bash $ build/effects render projects/spot built spot in 3.01s (-o:speed) rendering 420 frames (0.00s–7.00s) at 1920x1080, 60 fps, 5 workers, x264 rendered 420 frames in 6.5s (64.6 fps) /…/projects/spot/.effects/spot.mp4 ``` `render` compiles with optimization, gives every worker thread its own stretch of frames and its own encoder, and joins the pieces without re-encoding. That output is from an 8-core machine that had memory for five workers: seven seconds of 1080p60 in six and a half. Everything a project produces goes into its `.effects/` directory, which you can delete at any time. ## Where things go ```bash projects/spot/ main.odin # effects_video and the scene table intro.odin # one file per scene is a good habit assets/ # fonts, images, footage, audio timing.json # written by the editor when you drag things .effects/ # build output, stills, renders, caches ``` Paths in your code are relative to the project directory. Next: [scenes and time](/docs/scenes/). --- # Scenes and time A video is a list of scenes on a timeline, plus named moments called cues. The renderer asks the video for one frame at a time; the video works out which scenes are on screen at that time and calls them in order. ## The video ```odin @(export) effects_video :: proc() -> ^fx.Video { return fx.video({ name = "Spot", scenes = SCENES[:], cues = CUES[:], audio = "audio/mix.wav", overlay = proc(t: f32) {fx.vignette(0.35); fx.grain(0.035)}, }) } ``` `fx.video` registers the description with the renderer and returns it. It copies the scene, cue and mark lists it is given, registers the bundled fonts, and fills in defaults. | Field | Meaning | Default | | --- | --- | --- | | `name` | Shown in the editor. | | | `width`, `height` | The design size: the coordinate system your scenes draw in. | 1920 × 1080 | | `fps` | Frames per second of a render. | 60 | | `duration` | Length in seconds. | Until the last scene, or the voice-over, ends | | `background` | The color every frame is cleared to. | Opaque black | | `scenes` | The timeline. | | | `cues` | Named times. | | | `marks` | Times the editor draws on its ruler and snaps to: beats, usually. | | | `audio` | One soundtrack from time 0, relative to the project. Short for a single `Sound`. | | | `sounds` | Sounds on the timeline. See [sound](/docs/sound/). | | | `vo` | A `timeline.json` with voice-over word timings. See [voice-over](/docs/voice-over/). | | | `overlay` | `proc(t: f32)` drawn above all scenes. | | | `master` | `proc(t: f32) -> Xf`: a group around all scenes. | | The design size is not the output size. Scenes always draw on the design stage; `effects render --scale 0.5` renders the same picture at 960×540, and the editor fits it to its window. ## Scenes ```odin SCENES := [?]fx.Scene { {name = "intro", start = 0, dur = 3.4, draw = intro}, {name = "dash", start = 3.0, dur = 6, draw = dash}, {name = "outro", vo = "outro", draw = outro}, // start and length from the voice-over } ``` | Field | Meaning | | --- | --- | | `name` | Shown on the editor's timeline, and the key under which a moved scene is saved in `timing.json`. Keep names unique. | | `start`, `dur` | When it begins and how long it lasts, in seconds. A scene is drawn while `start <= t < start + dur`. | | `draw` | The procedure that draws it: `proc(s: fx.Shot)`. | | `vo` | The id of a voice-over scene to take `start` (and `dur`, if you leave it 0) from. | | `color` | Its color on the editor's timeline. | | `data` | A pointer handed to `draw` as `s.data`, for scenes built in a loop. | Scenes are drawn in list order, later ones on top, and they may overlap. Overlap is how transitions work: for half a second both scenes are drawn, and each decides how visible it is. The table has to be a global (or otherwise outlive the call to `fx.video`): the slice is copied, but the array literal it points into must still exist when it is. A scene list can also be built in code. A music edit might make one scene per bass hit, all sharing one `draw` and told apart by `data`. ## Shot A scene's `draw` receives a `Shot`: everything it needs to know about time. ```odin Shot :: struct { t, lt, p: f32, start, dur: f32, data: rawptr, } ``` | Field | Meaning | | --- | --- | | `t` | Video time in seconds. The same number for every scene drawn in this frame. | | `lt` | Local time: seconds since this scene started. `t - start`. | | `p` | Progress through this scene, 0 to 1. `lt / dur`. | | `start`, `dur` | This scene's place on the timeline, after any move made in the editor. | | `data` | The scene's `data`. | ```odin scenes_shot :: proc(s: fx.Shot) { fx.backdrop(.Night) rows := [?]struct { name: string, v, hi: f32, }{{"s.t", s.t, s.dur}, {"s.lt", s.lt, s.dur}, {"s.p", s.p, 1}} for r, i in rows { y := 300 + f32(i) * 200 fx.label(r.name, {200, y}, fx.mono(56), fx.theme.nt, {0, 0.5}) fx.rrect({460, y - 8, 1000, 16}, 8, fx.theme.nb) fx.rrect({460, y - 8, 1000 * r.v / r.hi, 16}, 8, fx.theme.na) fx.label(fmt.tprintf("%.2f", r.v), {1520, y}, fx.mono(56), fx.theme.nm, {0, 0.5}) } } ``` Use `lt` for animation inside a scene, so the scene keeps working when it is moved. Use `t` with `start` when you write a time as an offset from the scene's start (`fx.ep(s.t, s.start, s.start + 0.6)`), and `p` when something should span the whole scene whatever its length. A few procedures read the video's time themselves instead of being handed it, [`letters`](/docs/type/) for one. Their times are video times: write `s.start + 0.3`, not `0.3`. ## Fade ```odin fade :: proc(s: Shot, fi: f32 = 0.4, fo: f32 = 0.4) -> f32 ``` How visible a scene is: 0 when it starts, 1 after `fi` seconds, back to 0 over the last `fo` seconds. It is [`win`](/docs/anim/#windows-and-staggers) over the scene's span, and it usually goes straight into a group's opacity: ```odin if fx.group({o = fx.fade(s)}) { // the scene } ``` ```odin scenes_fade :: proc(s: fx.Shot) { fx.backdrop(.Night) fi, fo := knob("fade in", 0.4, 0.05, 1.5), knob("fade out", 0.4, 0.05, 1.5) o := fx.fade(s, fi, fo) if fx.group({o = o}) { fx.caption("fx.fade(s)", {960, 470}, 190, fx.theme.nt, {0.5, 0.5}) } // the value itself, drawn over the scene's span fx.rrect({260, 860, 1400, 6}, 3, fx.theme.nb) fx.rrect({260, 860, 1400 * s.p, 6}, 3, fx.theme.ns) fx.circle({260 + 1400 * s.p, 863 - 180 * o}, 14, fx.theme.na) } ``` A group that is fully transparent draws nothing and skips its contents, so a faded-out scene costs nothing. ## Cues A cue is a time with a name. Scenes ask for it instead of hard-coding the number, so the moment can be moved in one place, or dragged in the editor, without touching the scenes that use it. ```odin CUES := [?]fx.Cue{{"click", 6.2}, {"drop", 11.56}} dash :: proc(s: fx.Shot) { click := fx.cue("click") pressed := fx.ep(s.t, click, click + 0.12) // … } ``` `fx.cue(name)` returns the cue's time, or 0 (and a message on stderr) when there is none by that name. ## Timing that lives outside the code Scenes, cues and sounds dragged in the editor are saved to `timing.json` in the project directory. The file holds only what differs from the code: ```json { "scenes": { "dash": { "start": 3.2, "dur": 5.6 } }, "cues": { "click": 6.45 }, "sounds": { "boom": 11.5 } } ``` The renderer applies it on top of the code's times every time it loads the project. Delete an entry (or select the item in the editor and press Delete) to go back to the time in code. Keep the file in version control: it is part of the edit. ## Master and overlay Two hooks apply to the whole film. `master` returns an [`Xf`](/docs/group/) for a group wrapped around every scene, the background included: the film's grade, its glow, its lens, a camera move. It is called once per frame with the video time. ```odin master :: proc(t: f32) -> fx.Xf { return {glow = fx.glow(26, 0.9, 0.45), post = fx.lens(0.05, 5), contrast = 0.08} } ``` `overlay` draws above everything, outside the master group: vignette, grain, a watermark, letterbox bars. Grain belongs here rather than inside the master, so it is not blurred into the glow. ```odin scenes_master :: proc(s: fx.Shot) { // what Video.master does for a whole film: one group around every scene master := fx.Xf{glow = fx.glow(knob("glow", 26, 0, 60), 0.9, 0.45), post = fx.lens(0.05, knob("fringe", 5, 0, 16))} if fx.group(master) { fx.backdrop(.Night) p := fx.ep(s.lt, 0.3, 1.6) fx.rrect({360, 520, 1200 * p, 10}, 5, fx.theme.na) fx.caption("the film's look", {360, 330}, 150, fx.theme.nt) } fx.vignette(0.4) // what Video.overlay does: drawn above everything fx.grain(0.04) } ``` ## Reference | Name | What it is | | --- | --- | | `video(v)` | Registers a `Video` with the renderer and returns it. | | `Video` | The description of a film: size, rate, scenes, cues, sounds, hooks. | | `Scene` | A named span on the timeline with a `draw` procedure. | | `Shot` | What `draw` is handed: `t`, `lt`, `p`, `start`, `dur`, `data`. | | `Cue` | A named time. | | `cue(name)` | A cue's time. | | `fade(s, fi, fo)` | A scene's visibility, fading at both ends. | | `video_end(v)`, `scenes_end(v)` | Where the last scene (or the voice-over) ends. | | `stage()` | The design stage as a `Rect`. | | `now()` | The time of the frame being drawn. | --- # Working as an agent effects was built to be driven by a model as much as by a person. This page is written for the agent: what the loop looks like, which commands answer which question, and the mistakes that cost the most time. ## The docs as text - [`/llms.txt`](/llms.txt) lists every page with a one-line summary. - [`/llms-full.txt`](/llms-full.txt) is all of the documentation in one file, with the source of every demo inlined where its player would be. - Every page is also available as Markdown: add `.md` to its address without the trailing slash, as in [`/docs/anim.md`](/docs/anim.md). The library itself is short and commented. When a page and the source disagree, the source is right: `fx/*.odin` in the repository is about 5,000 lines. ## The loop ```bash $ effects build projects/spot # does it compile? errors have file and line $ effects still projects/spot 0.4 2.5 6 # PNGs of the moments you care about $ effects bench projects/spot # ms per frame: is anything too slow? $ effects mix projects/spot # the soundtrack alone, with its peak level $ effects render projects/spot # the film ``` 1. **Write or change a scene.** One procedure, one file. 2. **Build.** `effects build` compiles without drawing anything. An unoptimized build takes about 0.4 s. Read the first error, fix it, build again. 3. **Look.** `effects still …` writes one PNG per time into `.effects/stills/` and prints their paths. Open them. Pick times that matter: just after something appears, mid-transition, the last frame of a scene. Looking at stills is the whole point: a scene that compiles can still be empty, off-screen or unreadable. 4. **Measure.** `effects bench` draws 240 frames spread across the film on one thread and prints the average and the worst frame. If the worst frame is over a second, a full-screen shader is running at full resolution somewhere: see [what things cost](/docs/performance/). 5. **Render** when the stills are right. Use `--from` and `--to` to render a stretch, and `--scale 0.5` for a quick low-resolution pass. A person watching along can keep `effects-edit` open on the same project: it reloads on every save. ## Rules that save time **Compute everything from time.** No state survives between frames, and frames are drawn out of order on many threads. A counter that increments per call, a global that remembers the last position, a random number without a fixed seed: all of these produce a film that flickers or differs from run to run. Use [`rng`, `hash01`](/docs/anim/#random-but-the-same-every-time) for randomness. **Scene and cue tables are globals.** `fx.video` copies the slices, but the literals must still exist when it does. ```odin SCENES := [?]fx.Scene{{name = "intro", start = 0, dur = 3, draw = intro}} // at file scope ``` **Paths are relative to the project.** `"assets/photo.jpg"` means the project's `assets/` directory, wherever the renderer is run from. **The stage is 1920×1080** unless the video says otherwise. Text below about 28 px is small on a phone-sized player. Leave a margin: 160 px on the sides is the house style. **Scopes are groups.** `if fx.group({…}) { … }` ends its group when the block ends. Do not `return` out of the middle of a scene and expect later drawing to happen, and do not call `group_begin` without `end_group`. **Strings built per frame come from the temp allocator.** `fmt.tprintf` is right; it is freed after the frame. Do not keep pointers to it across frames. **Durations are in seconds, angles in degrees, colors are `0xAARRGGBB`.** `fx.rgb(0xdd5b3e)` makes an opaque color from the six-digit form. ## Checking your own work | Question | How to answer it | | --- | --- | | Does it compile? | `effects build ` | | What does second 7.6 look like? | `effects still 7.6` | | Is the text inside the frame? | A still. `fx.measure` returns a text's size if you need to compute it. | | Is a transition smooth? | Stills at several times across it: `effects still p 3.0 3.1 3.2 3.3 3.4`. | | Is it too slow to render? | `effects bench ` | | Is the sound clipping? | `effects mix ` prints the peak in dB. The mix has a soft limiter at -1 dBFS; a peak pinned there means it is working hard. | | Where are the beats? | `effects beats song.wav` prints hits, a tempo guess and drops. | | Did the render come out whole? | `render` counts the frames in the file it wrote and warns when they differ from what it drew. | Stills are drawn from the unoptimized build by default. Add `--release 1` to draw them from the optimized one when a still takes long (shader-heavy frames). ## Things that go wrong | What you see | Why | | --- | --- | | A black or empty still | The time is outside every scene, the scene's group is at opacity 0 at that time, or everything is drawn off-stage. | | Banding in dark gradients | The encoder, not the drawing: gradients are dithered. Render dark, grainy films with `--crf 16 --tune grain`. | | `fx: no cue ` | A scene asks for a cue that is not in the video's `cues`. | | `fx: cannot load font …` | The path is wrong. It is relative to the project directory. | | A shader draws nothing | Its SkSL did not compile. The error is printed once on stderr, starting with `sksl:`. | | The film is longer than expected | `duration` defaults to the end of the last scene or of the voice-over, whichever is later. | | Rendering uses all memory | Each worker is about 1 GB at 1080p. Workers are capped by available memory; pass `--workers n` to go lower. | ## A good first request When asked for a video, start small: one scene with the headline, a still of it, and only then the rest. Decide the film's look once, in a `master` and an `overlay` (see [scenes and time](/docs/scenes/#master-and-overlay)), so every scene inherits it. Give each scene its own file. Keep the timeline in one table at the top of `main.odin` so the structure of the film can be read in one place. --- # What things cost These are measurements, not promises: they come from the machines effects was built on, at 1080p. They are here so you can estimate a render before starting one, and know which choices are cheap and which are not. ## Why the pipeline is short A browser-based renderer draws a frame by loading a page in headless Chrome, running style, layout and paint, taking a screenshot, encoding that as an image, and handing the image to a video encoder that decodes it again. That happens once per frame, in a process built to be an interactive browser. effects compiles your project into a shared library. Each worker thread owns a Skia raster surface and an encoder process. For every frame it calls your scenes, which call Skia, and writes the surface's raw pixels into the encoder's pipe. There is no page, no screenshot and no intermediate image file. ## Frame times On a 16-thread laptop, one thread, 1920×1080: | What is drawn | Time | | --- | --- | | Interface elements: text, rects, layers | about 2 ms a frame | | Each full-screen pass (backdrop gradient, vignette, grain) | about 5 ms | | A product spot with backdrop, vignette and grain on | about 32 ms on average | | Glow (it is Skia's own blur) | about 20 ms | | A post filter that reads each pixel three times | about 50 ms | | A full-screen shader through `shader_scaled` at a third or half resolution | 0.1 to 0.5 s | | A full-screen field of warped noise or a raymarched body at full resolution | about 2 s | In the editor the same frames are drawn on the GPU: about 1 ms for the product spot. ## Render times | Film | Machine | Time | | --- | --- | --- | | 12.4 s product spot, 60 fps (744 frames) | 16-thread laptop, x264 | about 20 s | | 30.6 s showreel, 60 fps, shaders and footage | 16-thread laptop, x264 | 50 s | | The same showreel | 24 threads, NVENC on a Quadro RTX 4000 | 22 s | | 48.6 s edit, 30 fps, footage on every frame | 16-thread laptop, x264 | 62 s, peaking at about 15 GB | | The same edit | 24 threads, NVENC | 22 to 25 s (35 s with x264 there) | | 7 s of type, 60 fps (420 frames) | 8 cores, 5 workers, x264 | 6.5 s | | fable: 60 s, 60 fps, mostly full-screen shaders | 8 cores, x264 | about 13 min | For films made of interface, type and footage, encoding is the bottleneck, not drawing: x264 costs about 50 ms of CPU per frame, NVENC about 15 ms (most of that is the conversion to YUV, which stays on the CPU so both encoders tag and convert colors the same way). Compiling a project takes about 0.4 s unoptimized (what the editor and `still` use) and about 3 s with `-o:speed` (what `render` uses). ## The slow part: shaders on the CPU Final renders rasterize on the CPU, and SkSL on the CPU is the one expensive thing in the library. fable is the honest example: a minute of full-screen shaders takes thirteen minutes on eight cores, while a minute of interface and type would take well under one. What to do about it: - **Draw it small.** [`shader_scaled`](/docs/shade/) renders a shader at a fraction of the resolution and scales it up. Smooth fields (nebulae, gradients, noise) lose nothing at a third. - **Bake what does not move.** [`bake`](/docs/draw/) renders a static layer once and reuses the image on every frame and thread. - **Give layers bounds.** A group that blurs, fades or filters needs a layer; with `Xf.bounds` the layer is as large as its contents instead of as large as the frame. See [groups](/docs/group/). - **Prefer glow to a hand-written bloom.** `Xf.glow` uses Skia's blur, which is far cheaper than a blur written in SkSL. - **Measure.** `effects bench ` prints the average and the worst frame time. The worst frame tells you where to look. ## Memory Each render worker has its own encoder and up to two footage decoders: about 1 GB at 1080p. The default number of workers is the number of cores, capped at what 70% of the available memory allows. `--workers n` sets it by hand. ## Encoder settings `render` uses quality 18 for both encoders (x264's CRF, NVENC's constant QP): the same quality within about 1 dB, with NVENC files about 15% larger. `--encoder auto`, the default, uses NVENC when a test encode succeeds and x264 otherwise. A chunk whose NVENC session fails is drawn again and encoded with x264, so the render still finishes. Near-black films with slow gradients need more bits than the default gives them, or the encoder puts back the banding that dithering removed. Use `--crf 16 --tune grain` for those. --- # Animation Nothing in `fx` keeps time. A scene is handed the time and computes every position, size and opacity from it, so any frame can be drawn on its own, in any order, on any thread. The procedures on this page are the small pieces that turn a time into a number you can draw with. ## Progress Almost every animation starts with the same question: how far is `t` through the stretch from `a` to `b`? ```odin prog :: proc(t, a, b: f32) -> f32 // 0 before a, 1 after b, linear between ep :: proc(t, a, b: f32, e: Ease = ease_out) -> f32 // the same, eased ``` `prog` is the raw answer, clamped to 0..1. `ep` passes it through an ease, and is what you will write most of the time: ```odin rise := 30 * (1 - fx.ep(s.t, s.start, s.start + 0.6)) // 30 px below, settled after 0.6 s ``` `lerp(a, b, p)` and `lerp2(a, b, p)` take a progress and return the value (or point) that far from `a` to `b`. `clamp01(x)` clamps to 0..1. ## Eases An `Ease` is any `proc(p: f32) -> f32` that maps 0..1 to 0..1. These are built in; each dot below travels the same distance over the same 1.6 seconds. ```odin anim_ease :: proc(s: fx.Shot) { fx.backdrop(.Night) eases := [?]struct { name: string, e: fx.Ease, }{ {"ease_linear", fx.ease_linear}, {"ease_out", fx.ease_out}, {"ease_out5", fx.ease_out5}, {"ease_in", fx.ease_in}, {"ease_in_out", fx.ease_in_out}, {"ease_expo", fx.ease_expo}, {"ease_back", fx.ease_back}, } for it, i in eases { y := 204 + f32(i) * 112 p := fx.ep(s.lt, 0.4, 2.0, it.e) // time's progress through [0.4, 2.0], eased fx.label(it.name, {160, y}, fx.mono(32), fx.theme.nm, {0, 0.5}) fx.hline(520, y, 1200, fx.theme.nb, 2) fx.circle({520 + 1200 * p, y}, 22, fx.theme.na) } } ``` | Ease | Shape | | --- | --- | | `ease_linear` | Constant speed. | | `ease_out` | Cubic, fast then settling. The default everywhere. | | `ease_out5` | Quintic: a harder start and a longer settle. | | `ease_in` | Cubic, slow then fast. For things that leave. | | `ease_in2` | Quadratic, a gentler `ease_in`. | | `ease_in_out` | Cubic on both ends. For moves between two rests. | | `ease_expo` | Exponential: most of the way there almost at once. | | `ease_back` | Overshoots by a little and comes back. | Your own ease is one line: `snap :: proc(p: f32) -> f32 {return p < 0.5 ? 0 : 1}`. ## Spring ```odin spring :: proc(p: f32, freq: f32 = 2.2, damping: f32 = 0.45) -> f32 ``` A damped spring that starts at 0 and settles at 1. `p` is a linear progress (use `prog`, not `ep`), `freq` is how many times it swings on the way, `damping` how quickly the swings die. It is not an `Ease` because of its extra arguments, so call it directly. ```odin anim_spring :: proc(s: fx.Shot) { fx.backdrop(.Night) p := fx.prog(s.lt, 0.3, 2.3) k := fx.spring(p, knob("freq", 2.2, 0.5, 6), knob("damping", 0.45, 0.1, 1)) if fx.group({s = k, origin = {960, 500}}) { fx.rrect({760, 300, 400, 400}, 56, fx.theme.na) } fx.label("s = fx.spring(p, freq, damping)", {960, 900}, fx.mono(34), fx.theme.nm, {0.5, 0.5}) } ``` ## Windows and staggers ```odin win :: proc(t, a, b: f32, fi: f32 = 0.4, fo: f32 = 0.4) -> f32 stagger :: proc(t: f32, i: int, a, step, dur: f32, e: Ease = ease_out) -> f32 ``` `win` is a visibility window: 0 before `a`, rising to 1 over `fi` seconds, falling back to 0 over the `fo` seconds before `b`. Use it as an opacity. [`fx.fade(s)`](/docs/scenes/#fade) is `win` over a scene's own span. `stagger` is `ep` for the `i`-th member of a group: each one starts `step` seconds after the one before and takes `dur` to arrive. ```odin anim_stagger :: proc(s: fx.Shot) { fx.backdrop(.Night) step := knob("step", 0.08, 0, 0.3) for i in 0 ..< 12 { k := fx.stagger(s.lt, i, 0.3, step, 0.7, fx.ease_back) h := 560 * k * (0.35 + 0.65 * fx.hash01(7, i)) fx.rrect({294 + f32(i) * 112, 840 - h, 80, h}, 12, i == 8 ? fx.theme.na : fx.theme.nt) } } ``` ## Text and numbers ```odin typed :: proc(text: string, t, t0, t1: f32) -> string count :: proc(t, t0, t1, a, b: f32, e: Ease = ease_out) -> f32 ``` `typed` returns the part of `text` that has been typed by time `t`, always cut at a whole character. `count` is a number running from `a` to `b`; format it however the frame needs. ```odin anim_typed :: proc(s: fx.Shot) { fx.backdrop(.Night) o := fx.win(s.lt, 0.2, 3.8) // in over the first 0.4 s, out over the last if fx.group({o = o, y = 24 * (1 - o)}) { line := fx.typed("$ effects render projects/spot", s.lt, 0.5, 1.8) fx.text(line, 200, 360, fx.mono(64), fx.theme.nt) frames := fx.count(s.lt, 2.0, 3.2, 0, 744) fx.text(fmt.tprintf("%.0f frames", frames), 200, 500, fx.sans(150, 700, -0.035), fx.theme.na) } } ``` ## Keyframes ```odin Key :: struct {t: f32, v: f32} Key2 :: struct {t: f32, p: Vec2} keys :: proc(ks: []Key, t: f32, e: Ease = ease_in_out) -> f32 keys2 :: proc(ks: []Key2, t: f32, e: Ease = ease_in_out) -> Vec2 ``` When a value passes through more than two states, list them. `keys` eases each segment on its own and holds the first and last value outside the range. `keys2` does the same for points. ```odin anim_keys :: proc(s: fx.Shot) { fx.backdrop(.Night) path := [?]fx.Key2{{0.3, {360, 760}}, {1.2, {760, 300}}, {2.2, {1200, 760}}, {3.4, {1560, 320}}} for k in path do fx.ring(k.p, 18, fx.theme.ns, 2) p := fx.keys2(path[:], s.lt) r := fx.keys([]fx.Key{{0.3, 28}, {1.2, 70}, {2.2, 28}, {3.4, 70}}, s.lt) fx.circle(p, r, fx.theme.na) } ``` `bez(p, a, b, c, d)` evaluates a cubic bezier with those four control values at `p`, for curves that keyframes are too coarse for. ## Random, but the same every time A render must produce the same frame every time it is asked, so there is no global random state. ```odin rng :: proc(seed: u32) -> Rng rand :: proc(r: ^Rng) -> f32 // next number in 0..1 hash01 :: proc(seed: u32, i: int) -> f32 // a number in 0..1 for (seed, i), no state wob :: proc(t: f32, seed: f32 = 0) -> f32 // smooth drift in -1..1 ``` Seed an `Rng` at the top of a scene and draw from it in a fixed order, or use `hash01` when you want "the random number of item `i`" without carrying state around (the bar heights in the stagger demo). `wob` is for motion: two slow sines that never quite repeat, good for camera drift and hand-held jitter. ```odin anim_wob :: proc(s: fx.Shot) { fx.backdrop(.Night) amount := knob("amount", 40, 0, 120) for i in 0 ..< 5 { seed := f32(i) c := fx.Vec2{480 + f32(i) * 240, 540} p := c + {fx.wob(s.t, seed), fx.wob(s.t, seed + 0.5)} * amount fx.ring(c, 8, fx.theme.ns, 2) fx.circle(p, 36, i == 2 ? fx.theme.na : fx.theme.nt) } } ``` ## Reference | Procedure | Returns | | --- | --- | | `clamp01(x)` | `x` clamped to 0..1. | | `lerp(a, b, p)`, `lerp2(a, b, p)` | The value or point `p` of the way from `a` to `b`. | | `prog(t, a, b)` | Linear progress of `t` through `[a, b]`, clamped. | | `ep(t, a, b, e)` | Eased progress. | | `win(t, a, b, fi, fo)` | 1 inside `[a, b]`, fading at both ends. | | `stagger(t, i, a, step, dur, e)` | Eased progress for the `i`-th of a set. | | `spring(p, freq, damping)` | Damped oscillation from 0, settling at 1. | | `wob(t, seed)` | Smooth pseudo-random value in -1..1. | | `bez(p, a, b, c, d)` | Point on a cubic bezier. | | `typed(text, t, t0, t1)` | The prefix of `text` typed so far. | | `count(t, t0, t1, a, b, e)` | A number counting from `a` to `b`. | | `keys(ks, t, e)`, `keys2(ks, t, e)` | Value or point between keyframes. | | `rng(seed)`, `rand(&r)`, `hash01(seed, i)` | Deterministic random numbers. | --- # Drawing Drawing in `fx` is immediate: each call paints onto the frame's canvas right away, over whatever was drawn before it, and nothing is kept between frames. Coordinates are stage pixels with `{0, 0}` at the top left (see [the stage](/docs/color/#the-stage)), colors are `0xAARRGGBB` (see [colors](/docs/color/#colors)). To move, fade, blur or clip several calls together, wrap them in a [group](/docs/group/). ## Shapes ```odin rect :: proc(r: Rect, c: Color) rrect :: proc(r: Rect, radius: f32, c: Color) rrect4 :: proc(r: Rect, radii: [4]f32, p: sk.Paint) border :: proc(r: Rect, c: Color, width: f32 = 1, radius: f32 = 0) hline :: proc(x, y, w: f32, c: Color, width: f32 = 1) vline :: proc(x, y, h: f32, c: Color, width: f32 = 1) line :: proc(a, b: Vec2, c: Color, width: f32 = 1) circle :: proc(center: Vec2, r: f32, c: Color) ring :: proc(center: Vec2, r: f32, c: Color, width: f32 = 1) ``` All sizes are in px. A few details that are not in the names: - `rrect4` takes a radius per corner, in the order top-left, top-right, bottom-right, bottom-left, and a paint instead of a color: pass `fx.fill(c)` for a plain one. - `border` draws its line inside `r`, like CSS `box-sizing: border-box`, so a border of any width has the same outer edge as an `rrect` with the same rect and radius. - `hline` and `vline` are rects: `y` is the top edge of an `hline` and `x` the left edge of a `vline`, and `width` grows down or to the right. Being rects, they are crisp when their coordinates are whole pixels. - `line` and `ring` are strokes centered on the segment or the circle, with round ends. ```odin draw_shapes :: proc(s: fx.Shot) { fx.backdrop(.Night) t, a := fx.theme.nt, fx.theme.na k := 0.5 - 0.5 * math.cos(s.p * math.TAU) // 0 → 1 → 0 over the loop fx.rect({160, 170, 300, 200}, t) fx.rrect({580, 170, 300, 200}, 100 * k, t) fx.rrect4({1000, 170, 300, 200}, {100 * k, 0, 100 * k, 0}, fx.fill(a)) fx.border({1420, 170, 300, 200}, t, 4 + 20 * k, 40) fx.line({180, 780}, {440, 620 + 160 * k}, t, 8) fx.hline(580, 700, 300, a, 8) fx.vline(730 - 150 * k, 600, 200, a, 8) fx.circle({1150, 700}, 60 + 40 * k, t) fx.ring({1570, 700}, 100, a, 4 + 20 * k) names := [?]string{"rect", "rrect", "rrect4", "border", "line", "hline, vline", "circle", "ring"} for name, i in names { fx.label(name, {310 + f32(i % 4) * 420, 410 + f32(i / 4) * 430}, fx.mono(32), fx.theme.nm, {0.5, 0}) } } ``` Each of the filled shapes also comes in a form that takes a [paint](#paints) instead of a color, for gradients, strokes, glows and blend modes: ```odin rect_paint :: proc(r: Rect, p: sk.Paint) rrect_paint :: proc(r: Rect, radius: f32, p: sk.Paint) circle_paint :: proc(center: Vec2, r: f32, p: sk.Paint) paint_all :: proc(p: sk.Paint) ``` `paint_all` fills everything that can be drawn on: the whole frame, or the current group's clip. ### Shadows ```odin shadow :: proc(r: Rect, radius: f32 = 0, dy: f32 = 20, blur: f32 = 40, spread: f32 = 0, c: Color = 0x40000000, dx: f32 = 0) ``` A soft shadow under a rounded rect, with the arguments of a CSS `box-shadow`: `dx` and `dy` move it, `blur` is the CSS blur radius in px (the gaussian's sigma is half of it), `spread` grows the shape (or shrinks it, when negative) before it is blurred, and `c` is its color, by default black at 25%. `shadow` draws only the shadow: call it first, then draw the shape itself with the same rect and radius. Two shadows under one shape, a wide faint one and a tight dark one, look more natural than one. ```odin draw_shadow :: proc(s: fx.Shot) { fx.rect(fx.stage(), fx.theme.bg) // shadows need a light surface to fall on lift := 0.5 - 0.5 * math.cos(s.p * math.TAU) // the card rises and comes back down card := fx.Rect{610, 330 - 40 * lift, 700, 420} dy := knob("dy", 24, 0, 120) * (0.4 + lift) blur := knob("blur", 60, 0, 200) * (0.4 + lift) fx.shadow(card, 36, dy, blur, knob("spread", -8, -40, 40), 0x5016160f) fx.rrect(card, 36, fx.theme.sf) fx.border(card, fx.theme.bd, 2, 36) fx.label("shadow", fx.center(card), fx.sans(96, 600, -0.03), fx.theme.ink, {0.5, 0.5}) } ``` ## Paints A paint says how a shape is filled: with a color or a gradient, as a fill or a stroke, blurred, trimmed, added to what is below. It is a plain struct from the `sk` package (`import sk "effects:sk"`), the Odin bindings for Skia, and you rarely fill it in by hand: the procedures here build one and return it, and the modifiers take a paint and return a changed copy, so they nest. ```odin fill :: proc(c: Color) -> sk.Paint stroke :: proc(c: Color, w: f32 = 1) -> sk.Paint linear :: proc(a, b: Vec2, colors: ..Color) -> sk.Paint radial :: proc(center: Vec2, r: f32, colors: ..Color) -> sk.Paint sweep :: proc(center: Vec2, colors: ..Color) -> sk.Paint Stop :: struct {c: Color, at: f32} with_stops :: proc(p: sk.Paint, stops: ..Stop) -> sk.Paint additive :: proc(p: sk.Paint) -> sk.Paint trimmed :: proc(p: sk.Paint, a, b: f32) -> sk.Paint soft :: proc(p: sk.Paint, sigma: f32) -> sk.Paint ``` | Paint | What it does | | --- | --- | | `fill(c)` | A solid fill. | | `stroke(c, w)` | An outline `w` px wide, centered on the shape's edge, with round ends and corners. | | `linear(a, b, colors)` | A gradient from point `a` to point `b` through 2 to 8 evenly spaced colors. Before `a` and after `b` the end colors continue. | | `radial(center, r, colors)` | A gradient from `center` outward to radius `r`. | | `sweep(center, colors)` | A gradient around `center`, starting at 3 o'clock and running clockwise. | | `with_stops(p, stops)` | The gradient `p` with these colors at these positions (`at` in 0..1, ascending) instead of evenly spaced ones. Up to 8 stops. | | `additive(p)` | Adds its light to what is below instead of covering it (the `Plus` blend mode): overlapping strokes get brighter. | | `trimmed(p, a, b)` | Draws only the part from `a` to `b` of the outline's length, both 0..1. Animate `b` from 0 to 1 and a line draws itself. | | `soft(p, sigma)` | Blurs the shape's edges by a gaussian of `sigma` px: glows and soft shadows. | The points of a gradient are in the same coordinates as the shape, not relative to it: a `linear` from `{0, 0}` to `{1920, 0}` runs across the stage, and a shape drawn with it shows the part it covers. Gradients are dithered, so slow, dark ones do not show bands. ```odin draw_paints :: proc(s: fx.Shot) { fx.backdrop(.Night) a, n, t := fx.theme.na, fx.theme.night2, fx.theme.nt k := 0.5 - 0.5 * math.cos(s.p * math.TAU) names := [?]string{"linear", "radial", "sweep", "with_stops"} for name, i in names { r := fx.Rect{120 + f32(i) * 430, 110, 390, 390} c := fx.center(r) p: sk.Paint switch i { case 0: p = fx.linear({r.x, r.y}, {r.x + r.w, r.y + r.h}, n, a, t) // from corner to corner case 1: p = fx.radial(c, 120 + 160 * k, t, a, n) // the radius breathes case 2: p = fx.sweep(c, a, t, n, a) // around c, from 3 o'clock case 3: p = fx.with_stops(fx.linear({r.x, 0}, {r.x + r.w, 0}), {n, 0}, {a, 0.1 + 0.8 * k}, {t, 1}) } fx.rrect_paint(r, 40, p) fx.label(name, {c.x, r.y + r.h + 30}, fx.mono(32), fx.theme.nm, {0.5, 0}) } // any paint fills text too shine := fx.linear({-900 + 1800 * k, 0}, {900 + 1800 * k, 0}, a, t, a) fx.text_paint("text_paint", 120, 650, fx.sans(300, 700, -0.04), shine) } ``` `sk.Paint` has a few fields without a helper. Set them on the returned paint: ```odin p := fx.stroke(fx.theme.nt, 6) p.dash = {24, 16} // 24 px on, 16 px off p.square_cap = true // square ends and mitered corners instead of round ones fx.rrect_paint({700, 700, 500, 200}, 40, p) g := fx.linear({1300, 0}, {1800, 0}, fx.theme.na, fx.theme.nt) g.color = fx.with_alpha(0, 0.4) // with a gradient, only the alpha of color is used: the gradient at 40% fx.rect_paint({1300, 700, 500, 200}, g) ``` | Field | Meaning | | --- | --- | | `color` | `0xAARRGGBB`. With a gradient only its alpha is used. | | `stroke` | Stroke width in px, 0 = fill. | | `blur` | Blur of the shape's edges, sigma in px (`soft`). | | `shader`, `sh`, `stops`, `stop_colors`, `stop_pos` | The gradient (`linear`, `radial`, `sweep`, `with_stops`). | | `dash` | `{on, off}` lengths in px for a dashed stroke, `{0, 0}` = solid. | | `trim` | The part of the outline to draw (`trimmed`). | | `blend` | A blend mode (`sk.Blend`) plus one, 0 = normal. `additive` sets it to `Plus`; the modes are listed under [blend](/docs/group/#blend). | | `square_cap` | Square stroke ends and mitered corners instead of round ones. | ## Paths ```odin draw_path :: proc(path: ^sk.Path, p: sk.Paint) ``` Anything that is not a rectangle or a circle is a path: curves, polygons, outlines parsed from SVG. Paths are made with the `sk` package and drawn with any paint. ```odin path_new :: proc() -> ^Path path_from_svg :: proc(d: cstring) -> ^Path // from an SVG path's d attribute; nil when it does not parse path_free :: proc(p: ^Path) path_move_to :: proc(p: ^Path, x, y: f32) path_line_to :: proc(p: ^Path, x, y: f32) path_quad_to :: proc(p: ^Path, x1, y1, x2, y2: f32) // one control point, then the end path_cubic_to :: proc(p: ^Path, x1, y1, x2, y2, x3, y3: f32) // two control points, then the end path_close :: proc(p: ^Path) path_add_rrect :: proc(p: ^Path, x, y, w, h, r: f32) path_add_circle :: proc(p: ^Path, cx, cy, r: f32) path_bounds :: proc(p: ^Path, out: ^[4]f32) // x, y, w, h path_length :: proc(p: ^Path) -> f32 // in px ``` A path you make is yours to free. Building one every frame is cheap, and with `defer sk.path_free(path)` right after it is made it cannot leak: ```odin draw_path :: proc(s: fx.Shot) { fx.backdrop(.Night) path := sk.path_new() defer sk.path_free(path) // a path you make is yours to free sk.path_move_to(path, 200, 760) sk.path_cubic_to(path, 560, 760, 560, 320, 920, 320) sk.path_cubic_to(path, 1280, 320, 1360, 780, 1720, 520) fx.draw_path(path, fx.stroke(fx.theme.nb, 4)) // the whole path, faint k := fx.ep(s.lt, 0.4, 2.8, fx.ease_in_out) * (1 - fx.ep(s.lt, 3.4, 3.9)) a := fx.theme.na glow := fx.soft(fx.additive(fx.stroke(fx.alpha(a, 0.6), 40)), 20) fx.draw_path(path, fx.trimmed(glow, 0, k)) // a wide, blurred, additive stroke under … fx.draw_path(path, fx.trimmed(fx.stroke(a, 10), 0, k)) // … the line itself } ``` The demo draws the same path three times: once whole and faint, once as a wide, blurred, additive stroke for the glow, and once as the line. Both of the last two are `trimmed` to the same progress. A stroke with round ends that is trimmed to nothing (`b = 0`) still leaves a dot at the start of the path, the size of the stroke: skip the call until the progress is above 0 if the dot should not be there. `trimmed` is not limited to paths. Any shape drawn with a stroke can be trimmed, which makes a progress ring one call (a circle's outline starts at 3 o'clock and runs clockwise): ```odin fx.circle_paint({400, 800}, 120, fx.trimmed(fx.stroke(fx.theme.na, 16), 0, s.p)) ``` A filled SVG outline works the same way. A path's coordinates are its own, so place and scale it with a [group](/docs/group/): ```odin star := sk.path_from_svg("M12 2l3 7 7 .6-5.3 4.6 1.7 7.3L12 17.8 5.6 21.5l1.7-7.3L2 9.6 9 9z") // 24 units wide defer sk.path_free(star) if fx.group({x = 1100, y = 200, s = 20}) { fx.draw_path(star, fx.linear({0, 0}, {24, 24}, fx.theme.na, fx.theme.nt)) } ``` ## Text ```odin text :: proc(s: string, x, y: f32, f: Font, c: Color, max_w: f32 = 0, align := Text_Align.Left) -> Rect label :: proc(s: string, p: Vec2, f: Font, c: Color, anchor := Vec2{0, 0}) -> Rect text_baseline :: proc(s: string, x, y: f32, f: Font, c: Color) -> Rect text_paint :: proc(s: string, x, y: f32, f: Font, p: sk.Paint, max_w: f32 = 0, align := Text_Align.Left) ``` Four ways to put the same text on the frame, differing in how they are positioned: - `text` puts the top-left corner of the text's box at `(x, y)`. With `max_w` above 0 the text wraps at that width and `align` (`.Left`, `.Center`, `.Right`) places the lines inside it; with 0 it stays on one line. - `label` positions an unwrapped text by an anchor: `{0, 0}` puts the box's top-left corner at `p`, `{0.5, 0.5}` centers it on `p`, `{1, 0}` right-aligns it to `p`. This is the one to use for anything centered or right-aligned. - `text_baseline` puts the baseline of one line at `y`, so texts of different sizes stand on the same line. - `text_paint` is `text` with a [paint](#paints) instead of a color (it is in the paints demo above), and returns nothing. The first three return the box they drew into, which is how you put something next to or under a text without measuring it first. For a wrapped `text` the box is `max_w` wide. ```odin draw_text :: proc(s: fx.Shot) { fx.backdrop(.Night) max_w := knob("max_w", 1000, 500, 1500) align := fx.Text_Align(int(s.p * 3) % 3) // .Left, .Center, .Right, a third of the loop each f := fx.sans(92, 500, -0.025) f.lh = 1.2 line := "Every frame is a pure function of time, drawn with Skia from Odin." box := fx.text(line, 210, 410, f, fx.theme.nt, max_w, align) fx.border(fx.inset(box, -32), fx.theme.ns, 2) // text returns the box it filled info := fmt.tprintf("align = .%v box = %.0f × %.0f px", align, box.w, box.h) fx.label(info, {178, 280}, fx.mono(36), fx.theme.nm) } ``` ```odin draw_label :: proc(s: fx.Shot) { fx.backdrop(.Night) p := fx.Vec2{960, 360} turn := s.p * math.TAU anchor := fx.Vec2{0.5 + 0.5 * math.sin(turn), 0.5 - 0.5 * math.cos(2 * turn)} box := fx.label("anchored", p, fx.sans(150, 600, -0.03), fx.theme.nt, anchor) fx.border(box, fx.theme.nb, 2) fx.circle(p, 14, fx.theme.na) // p stays put: the anchor says which part of the box sits on it info := fmt.tprintf("anchor = {{%.2f, %.2f}}", anchor.x, anchor.y) fx.label(info, {960, 620}, fx.mono(34), fx.theme.nm, {0.5, 0}) // text_baseline: three sizes standing on one line x: f32 = 330 fx.hline(270, 900, 1380, fx.theme.na, 2) for size in ([?]f32{48, 96, 170}) { x += fx.text_baseline("Baseline", x, 900, fx.sans(size, 500, -0.02), fx.theme.nt).w + 50 } } ``` > **Note:** A call draws its whole text in one font and one color. For mixed weights or colors in one line, draw the runs one after another using the returned boxes, or use [`kinetic`](/docs/ui/) or a [layout](/docs/layout/) row. ### Fonts ```odin Font :: struct { family: cstring, size: f32, weight: f32, tracking: f32, lh: f32, tabular: bool, italic: bool, underline: bool, upper: bool, max_lines: int, } ``` A `Font` is a value describing how text is set. Nothing is loaded or cached by making one, so build them inline. The theme's helpers `sans`, `mono` and `caps` return one for the [theme's families](/docs/theme/#fonts): `fx.sans(72, 600, -0.03)`. | Field | Meaning | | --- | --- | | `family` | The name a font file was registered under: `"SG"` and `"JBM"` are built in, your own come from `font`. | | `size` | Font size in px. | | `weight` | 100..900, 0 = 400. A variable font is set to exactly this weight; a family of static files uses the nearest one registered. | | `tracking` | Letter spacing in em, like CSS `letter-spacing: 0.1em`: `-0.03` tightens a headline, `0.1` opens up capitals. | | `lh` | Line height as a multiple of `size`, 0 = the font's own. | | `tabular` | Tabular figures: every digit as wide as the others, so a running number does not jitter. | | `italic` | Uses the family's italic file. A family without one gets its upright face slanted instead, which is no substitute: register the italic (see below). | | `underline` | Underlines the text. | | `upper` | Draws the text in capitals, like CSS `text-transform: uppercase`. | | `max_lines` | With `max_w`: the most lines to draw, 0 = unlimited. Text that is cut off ends in `…`. | ```odin draw_font :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme f := fx.sans(150, knob("weight", 500, 300, 700), knob("tracking", -0.03, -0.08, 0.3)) fx.text("Space Grotesk", 150, 90, f, th.nt) row := fx.Font{family = th.sans, size = 60, weight = 500} n := fmt.tprintf("%.2f", fx.count(s.lt, 0, 5, 0, 1111.1, fx.ease_linear)) plain, tab, under, upper, two := row, row, row, row, row tab.tabular, under.underline, upper.upper, two.max_lines = true, true, true, 2 fx.label(n, {1130, 380}, plain, th.nt, {1, 0}) // right-aligned: proportional digits make it jitter fx.label(n, {1130, 500}, tab, th.na, {1, 0}) // tabular digits all have one width fx.text("Underlined", 730, 620, under, th.nt) fx.text("Uppercase", 730, 740, upper, th.nt) fx.text("Two lines at most, and whatever does not fit is cut off", 730, 860, two, th.nt, 700) names := [?]string{"default", "tabular", "underline", "upper", "max_lines = 2"} for name, i in names do fx.label(name, {150, 396 + f32(i) * 120}, fx.mono(32), th.nm) } ``` ```odin font :: proc(family: string, path: string) -> bool ``` `font` registers a font file under a family name, once, when the video is set up. The path is relative to the project directory unless it is absolute. Register several files under one name (weights, italics) and `Font.weight` and `Font.italic` pick among them. It returns false, and prints `fx: cannot load font` with the path, when the file cannot be read. [Theme and fonts](/docs/theme/#your-own-fonts) shows it in a project. ### Measuring ```odin measure :: proc(s: string, f: Font, max_w: f32 = 0) -> Vec2 shape :: proc(s: string, f: Font, max_w: f32 = 0, align := Text_Align.Left) -> ^sk.Text metrics :: proc(t: ^sk.Text) -> sk.Text_Metrics ``` `measure` returns the width and height in px a text takes, without drawing it. `shape` is the step every text procedure starts with: it lays the text out and returns the layout, and `metrics` reads it: | `sk.Text_Metrics` | | | --- | --- | | `width` | Width of the longest line, px. | | `height` | Height of all lines, px. | | `baseline` | Distance from the top of the box to the first line's baseline, px. | | `max_intrinsic` | The width the text would have on one line. | | `lines` | Number of lines. | Layouts are cached per render thread, so drawing the same text with the same font every frame lays it out once, and measuring before drawing costs nothing extra. A layout belongs to the frame it was asked for in: do not keep the pointer. ## Icons ```odin icon :: proc(name: string, x, y, size: f32, c: Color, width: f32 = 1.6) icon_path :: proc(name: string) -> (Icon_Path, bool) Icon_Path :: struct { path: ^sk.Path, filled: bool, } ``` `icon` draws one of the built-in line icons, `size` px wide and high, with its top-left corner at `(x, y)`. The icons are designed on a 24-unit grid and `width` is the stroke in those units, so it scales with the icon: at the default 1.6 a 48 px icon has a 3.2 px line. A name that does not exist draws nothing. All 77 names are on the [theme page](/docs/theme/#icons). `icon_path` returns the icon's 24-unit path for drawing it yourself, with any paint; `filled` says whether it is meant to be filled rather than stroked. The path belongs to the library: do not free it. ```odin draw_icon :: proc(s: fx.Shot) { fx.backdrop(.Night) width := knob("width", 1.6, 0.4, 4) names := [?]string{"search", "mail", "calendar", "bell", "users", "settings"} for name, i in names { x := 190 + f32(i) * 280 fx.icon(name, x, 190, 140, fx.theme.nt, width) fx.label(name, {x + 70, 370}, fx.mono(32), fx.theme.nm, {0.5, 0}) } // icon_path hands out the 24-unit path itself: here the globe draws itself, 15 times larger if ip, ok := fx.icon_path("globe"); ok { k := fx.ep(s.lt, 0.3, 2.6, fx.ease_in_out) * (1 - fx.ep(s.lt, 3.4, 3.9)) if fx.group({x = 780, y = 540, s = 15}) { fx.draw_path(ip.path, fx.trimmed(fx.stroke(fx.theme.na, width), 0, k)) } } } ``` ## Images ```odin load_image :: proc(path: string) -> ^sk.Image image_size :: proc(img: ^sk.Image) -> Vec2 image :: proc(img: ^sk.Image, r: Rect, alpha: f32 = 1, fit := Image_Fit.Cover, focus := Vec2{0.5, 0.5}, zoom: f32 = 1) Image_Fit :: enum { Fill, // stretch to r Contain, Cover, // fill r, cropping the image } ``` `load_image` reads a PNG, JPEG or WebP file, relative to the project directory unless the path is absolute. The file is decoded the first time and the same image is returned from then on, from any thread, so call it right in the scene. When the file cannot be loaded it prints `fx: cannot load image` and returns nil, and `image` draws nothing for nil. `image` draws it into `r`: | Argument | Meaning | | --- | --- | | `alpha` | Opacity, 0..1. | | `fit` | `.Fill` stretches the image to `r`. `.Contain` shows all of it, centered, leaving bars. `.Cover`, the default, fills `r` and crops what does not fit. | | `focus` | With `.Cover`: which part stays in view when the image is cropped, 0..1 on each axis. `{0, 0}` keeps the top-left corner, `{0.5, 0.5}` the middle. | | `zoom` | With `.Cover`: crops further in, 1 = as much of the image as fits. Values below 1 count as 1. | Animating `focus` pans across a picture and animating `zoom` pushes in, the two moves of a photo in a film. `image_size` returns the image's size in its own pixels. ```odin draw_image :: proc(s: fx.Shot) { fx.backdrop(.Night) img := fx.load_image("assets/frame.jpg") // decoded once, then handed out by path pan := 0.5 - 0.5 * math.cos(s.p * math.TAU) // 0 → 1 → 0 fits := [?]fx.Image_Fit{.Fill, .Contain, .Cover} for fit, i in fits { r := fx.Rect{210 + f32(i) * 520, 200, 460, 560} fx.rect(r, fx.theme.night2) fx.image(img, r, fit = fit, focus = {pan, 0.5}, zoom = knob("zoom", 1, 1, 4)) fx.border(r, fx.theme.ns, 2) fx.label(fmt.tprintf(".%v", fit), {r.x + r.w / 2, r.y + r.h + 36}, fx.mono(32), fx.theme.nm, {0.5, 0}) } } ``` For rounded corners, a grade or a blur, draw the image inside a [group](/docs/group/) with `clip` and `radius`, `sat`, `blur` and so on. Frames of a video file are drawn the same way by [`footage`](/docs/footage/). ## Baked layers ```odin bake :: proc(key: string, r: Rect, res: f32, paint: proc(r: Rect, data: rawptr), data: rawptr = nil, alpha: f32 = 1) ``` Some parts of a frame never change: a background gradient, a vignette, a field of a few thousand dots. `bake` draws such a layer once into an image and from then on every frame, on every render thread, draws that image instead. On the CPU a full-screen gradient costs about 5 ms a frame; baked, it costs one image draw. `backdrop` and `vignette` are baked this way. ```odin stars :: proc(r: fx.Rect, data: rawptr) { rng := fx.rng(7) for _ in 0 ..< 4000 { p := fx.Vec2{r.x + fx.rand(&rng) * r.w, r.y + fx.rand(&rng) * r.h} fx.circle(p, 1 + 3 * fx.rand(&rng), fx.alpha(fx.theme.nt, 0.5 * fx.rand(&rng))) } } sky :: proc(s: fx.Shot) { fx.backdrop(.Night) fx.bake("sky/stars", fx.stage(), 1, stars) // 4,000 circles the first time, one image after that } ``` | Argument | Meaning | | --- | --- | | `key` | Names the picture. The image is stored under the key, the size of `r` and `res`, for as long as the program runs. | | `r` | Where the image is drawn, and the area `paint` is asked to fill. | | `res` | The image's resolution as a multiple of `r`'s size in stage px. 1 is one image pixel per stage pixel, 0.5 a quarter of the pixels. | | `paint` | Draws the layer with ordinary `fx` calls, in the same coordinates as if it drew straight to the frame. It is called once. | | `data` | Handed to `paint`, for its parameters. It is read only during that one call. | | `alpha` | Opacity the image is drawn with, 0..1. This can change every frame. | What to keep in mind: - The layer has to be static. `paint` runs once, so anything it reads from the time is frozen at the first frame that asked for it. Animate around a baked layer with `alpha` or a group, not inside it. - The key has to say everything the picture depends on. `vignette` puts its strength in the key. A key that changes every frame bakes, and keeps, a new image every frame. - `res` below 1 is for smooth pictures only (`backdrop` uses 0.5). Gradients are dithered so that slow, dark ones do not band, and a layer baked at less than full size loses that when it is scaled up. If a dark gradient shows bands, bake it at 1 or draw it directly. - `res` counts stage pixels. A render at twice the size (`--scale 2`) still gets the image baked at `res` times 1920×1080, scaled up. - Do not call `bake` from inside a `paint` procedure, and that includes `backdrop` and `vignette`: the cache is locked while `paint` runs, and the second call would wait forever. ## Shaders ```odin shader :: proc(sksl: cstring, r: Rect, uniforms: ..f32) ``` `shader` fills `r` with a picture computed per pixel by an SkSL program (Skia's shading language, close to GLSL). `main` receives the pixel's position in the coordinates `r` is given in (stage px, unless a group around it scales or moves them), and the `uniforms` are passed as floats in the order the program declares them. A program that does not compile draws nothing and prints `fx: shader:` with the compiler's message. ```odin STRIPES :: ` uniform float t; half4 main(float2 p) { float v = 0.5 + 0.5 * sin((p.x + p.y) * 0.02 - t * 4); return half4(v, v * 0.4, v * 0.25, 1); }` fx.shader(STRIPES, {160, 160, 800, 400}, s.t) ``` The editor previews on the GPU, where shaders are fast. Renders are drawn on the CPU, and there a heavy full-screen shader (warped noise, a raymarched body) costs about 2 s per 1080p frame on one thread. [Shaders](/docs/shade/) has `shader_scaled`, which draws such pictures at a fraction of the size, and the ready-made fields built on it. ## Reference | Procedure | Draws or returns | | --- | --- | | `rect(r, c)`, `rect_paint(r, p)` | A rectangle. | | `rrect(r, radius, c)`, `rrect_paint(r, radius, p)` | A rounded rectangle. | | `rrect4(r, radii, p)` | A rounded rectangle with a radius per corner. | | `border(r, c, width, radius)` | A border inside `r`. | | `hline(x, y, w, c, width)`, `vline(x, y, h, c, width)` | A horizontal or vertical line as a rect. | | `line(a, b, c, width)` | A line between two points. | | `circle(center, r, c)`, `circle_paint(center, r, p)` | A circle. | | `ring(center, r, c, width)` | A circle's outline. | | `shadow(r, radius, dy, blur, spread, c, dx)` | A soft shadow under a rounded rect. | | `draw_path(path, p)` | A path from the `sk` package. | | `paint_all(p)` | The paint over everything. | | `fill(c)`, `stroke(c, w)` | A solid fill or stroke paint. | | `linear(a, b, colors)`, `radial(center, r, colors)`, `sweep(center, colors)` | A gradient paint. | | `with_stops(p, stops)` | A gradient with explicit stop positions (`Stop{c, at}`). | | `additive(p)`, `trimmed(p, a, b)`, `soft(p, sigma)` | The paint adding light, drawing part of an outline, blurred. | | `text(s, x, y, f, c, max_w, align)` | Text from its top-left corner, optionally wrapped; returns its box. | | `label(s, p, f, c, anchor)` | Text placed by an anchor; returns its box. | | `text_baseline(s, x, y, f, c)` | One line with its baseline at `y`; returns its box. | | `text_paint(s, x, y, f, p, max_w, align)` | Text filled with a paint. | | `font(family, path)` | Registers a font file; false when it cannot be loaded. | | `measure(s, f, max_w)` | Width and height of a text. | | `shape(s, f, max_w, align)`, `metrics(t)` | A text's layout and its `sk.Text_Metrics`. | | `icon(name, x, y, size, c, width)` | A built-in icon. | | `icon_path(name)` | An icon's `Icon_Path` and whether it exists. | | `load_image(path)`, `image_size(img)` | An image file, loaded once; its size in px. | | `image(img, r, alpha, fit, focus, zoom)` | An image in a rect (`Image_Fit`: `.Fill`, `.Contain`, `.Cover`). | | `bake(key, r, res, paint, data, alpha)` | A static layer, rendered once and reused. | | `shader(sksl, r, uniforms)` | A rect filled by an SkSL program. | Groups (`Xf`, `group`, `frosted`) live in the same source file and have [their own page](/docs/group/). --- # Groups and grading A group is a scope: everything drawn inside it is moved, scaled, faded, blurred, graded or clipped together, as if it were one picture. It is how a card slides in, how a title comes into focus, how a shot is turned black and white, and how a whole film gets its look. There is one struct to learn, `Xf`, and one procedure that takes it. ## The idiom ```odin group :: proc(xf: Xf) -> bool ``` ```odin if fx.group({y = 40 * (1 - k), o = k}) { // drawn 40 px lower and transparent at k = 0, in place and opaque at k = 1 } ``` `group` applies `xf` to everything drawn until the `if` ends, and undoes it there. Fields you leave out do nothing, so a group reads as a list of what changes. The coordinates inside are the ones you would use without the group: you draw the card where it ends up and let the group displace it. It returns false, and the body is skipped, when the group would be invisible (`o` at or below 0.002). So nothing is laid out or drawn for a scene that has not faded in yet. ```odin group_basic :: proc(s: fx.Shot) { fx.backdrop(.Night) k := fx.win(s.lt, 0.3, 3.7, 0.7, 0.5) // 0 → 1, held, back to 0 card := fx.Rect{510, 330, 900, 420} // everything between the braces rises, sharpens and fades in as one picture if fx.group({y = 80 * (1 - k), o = k, blur = 16 * (1 - k)}) { fx.shadow(card, 40, 30, 80, 0, 0x80000000) fx.rrect(card, 40, fx.theme.night2) fx.border(card, fx.theme.nb, 2, 40) fx.circle({650, 540}, 70, fx.theme.na) fx.label("One group", {770, 500}, fx.sans(84, 600, -0.03), fx.theme.nt, {0, 0.5}) fx.label("moves as one", {770, 590}, fx.sans(44), fx.theme.nm, {0, 0.5}) } } ``` > **Note:** The `if` is what ends the group. `group` is declared `@(deferred_out = end_group)`, so Odin calls `end_group` when the scope the call was made in closes. Written as a statement of its own, `fx.group({…})` lasts until the end of the enclosing block. ## Xf ```odin Xf :: struct { x, y: f32, s: Maybe(f32), sx, sy: f32, rot: f32, rx, ry: f32, persp: f32, origin: Vec2, o: Maybe(f32), blur: f32, mblur: Vec2, gray: f32, bright: f32, contrast: f32, sat: Maybe(f32), tint: Color, invert: f32, blend: Maybe(sk.Blend), post: Post, glow: Glow, clip: Maybe(Rect), radius: f32, bounds: Maybe(Rect), } ``` | Field | Unit | What it does | Left out | | --- | --- | --- | --- | | `x`, `y` | px | Moves the contents. | 0 | | `s` | factor | Scales around `origin`. | 1 | | `sx`, `sy` | factor | Extra scale along one axis, multiplied with `s`: squash and stretch. | 1 | | `rot` | degrees | Turns clockwise around `origin`. | 0 | | `rx`, `ry` | degrees | Tilts in 3D around the horizontal and the vertical axis through `origin`. | 0 | | `persp` | px | The viewing distance for the tilt. Smaller is more dramatic. | 1600 | | `origin` | px | The fixed point of `s`, `sx`, `sy`, `rot`, `rx` and `ry`. | `{0, 0}` | | `o` | 0..1 | Opacity of the contents as a whole. | 1 | | `blur` | px | Gaussian blur, sigma. | 0 | | `mblur` | px | Blur along x and along y only, sigma each: motion blur. | `{0, 0}` | | `gray` | 0..1 | Desaturates. | 0 | | `bright` | factor | Multiplies the brightness. | 1 | | `contrast` | −1.. | 0.5 is 50% more contrast, negative flattens, −1 is flat gray. | 0 | | `sat` | factor | Saturation: 0 is gray, 1.4 vivid. | 1 | | `tint` | color | Multiplies every color by this one. | none | | `invert` | 0..1 | Blends toward the negative. | 0 | | `blend` | `sk.Blend` | How the contents land on what is below. | normal | | `post` | `Post` | A pixel filter over the contents. | none | | `glow` | `Glow` | Bloom: the bright parts blurred and added back. | none | | `clip` | px | Nothing is drawn outside this rect. | no clip | | `radius` | px | Corner radius of `clip`. | 0 | | `bounds` | px | A hint about where the contents are, to keep the layer small. | whole frame | `s`, `o`, `sat`, `blend`, `clip` and `bounds` are `Maybe` values because their zero means something (`s = 0` is a real scale, `o = 0` is invisible). You write them like the others, `{s = 0.5, o = k, blend = .Screen}`, except that a rect has to name its type: `clip = fx.Rect{0, 0, 400, 300}`, or a variable that is one. ## Move, scale, turn The transform fields are applied to the contents in a fixed order, whatever order you write them in: scale first, then the turn or tilt, then the move. `x` and `y` are therefore always in the parent's pixels, never scaled or rotated themselves. `origin` is the point that stays where it is while everything else scales and turns around it. It defaults to `{0, 0}`, the top-left corner of the stage (or of the group around this one), which is almost never what you want: pass the center of the thing you are transforming (`fx.center(r)`), or the point it should grow out of. Drag the origin in the demo to see the square swing around it. ```odin group_transform :: proc(s: fx.Shot) { fx.backdrop(.Night) r := fx.Rect{760, 340, 400, 400} origin := fx.Vec2{knob("origin.x", 960, 760, 1160), knob("origin.y", 540, 340, 740)} fx.border(r, fx.theme.ns, 2, 56) // where the square is drawn without the group if fx.group({rot = 360 * s.p, s = knob("s", 1, 0.3, 2), origin = origin}) { fx.rrect(r, 56, fx.theme.nt) fx.label("fx", fx.center(r), fx.sans(220, 700, -0.04), fx.theme.night, {0.5, 0.5}) } fx.circle(origin, 16, fx.theme.na) // it turns and scales around this point } ``` `sx` and `sy` scale one axis on top of `s`. Their zero value means 1, so setting only `sx` leaves the height alone. With the origin at the point of contact they make the squash of an impact or the stretch of a fast move: ```odin group_squash :: proc(s: fx.Shot) { fx.backdrop(.Night) floor, r := f32(840), f32(100) p := math.mod(s.lt, 0.8) / 0.8 // progress through one bounce of 0.8 s h := 4 * p * (1 - p) // its height, 0 → 1 → 0 hit := max(1 - p / 0.14, 1 - (1 - p) / 0.14, 0) // 1 at the moment it touches the floor amount := knob("amount", 0.35, 0, 0.7) y := floor - r - 520 * h // wider and flatter on impact, around the point where it touches if fx.group({sx = 1 + amount * hit, sy = 1 - amount * hit, origin = {960, y + r}}) { fx.circle({960, y}, r, fx.theme.na) } fx.hline(560, floor, 800, fx.theme.ns, 3) } ``` ## 3D tilt `rx` and `ry` turn the contents out of the screen plane, like a CSS `rotateX`/`rotateY` under a `perspective`. A positive `rx` leans the top away from the viewer, a positive `ry` the right edge. `persp` is how far the viewer is from the plane in px: 1600 by default, 400 for a wide-angle look, several thousand for almost no foreshortening. When a group has a tilt, its `rot` turns in the same 3D space, around the axis pointing at the viewer. The contents stay a flat card: there is no depth between the things inside one group. For points and lines in real 3D see [3D](/docs/space/). ```odin group_tilt :: proc(s: fx.Shot) { fx.backdrop(.Night) card := fx.Rect{560, 240, 800, 600} rx, persp := knob("rx", 12, -60, 60), knob("persp", 1600, 400, 6000) ry := 50 * math.sin(s.p * math.TAU) // swings left and right if fx.group({rx = rx, ry = ry, persp = persp, origin = fx.center(card)}) { fx.rrect(card, 36, fx.theme.sf) fx.rect({card.x, card.y + 110, card.w, 2}, fx.theme.bd) fx.label("Revenue", {card.x + 56, card.y + 56}, fx.sans(44, 600), fx.theme.ink, {0, 0.5}) for i in 0 ..< 7 { h := 110 + 300 * fx.hash01(3, i) bar := fx.Rect{card.x + 62 + f32(i) * 100, card.y + 540 - h, 72, h} fx.rrect(bar, 10, i == 5 ? fx.theme.red : fx.theme.ink) } } } ``` ## Opacity and blur `o` fades the group's contents as one picture. That is not the same as making each color translucent: shapes that overlap inside the group do not show through each other. ```odin group_layer :: proc(s: fx.Shot) { fx.backdrop(.Night) o := knob("o", 0.5, 0, 1) pair :: proc(cx: f32, turn: f32, c: fx.Color) { if fx.group({rot = turn, origin = {cx, 480}}) { fx.rrect({cx - 230, 290, 300, 300}, 48, c) fx.circle({cx + 90, 560}, 170, c) } } // left: each shape is translucent on its own, so the overlap shows pair(520, 360 * s.p, fx.alpha(fx.theme.nt, o)) // right: the shapes are drawn opaque into a layer, and the layer is faded if fx.group({o = o}) do pair(1400, 360 * s.p, fx.theme.nt) fx.label("fx.alpha(c, o)", {520, 900}, fx.mono(36), fx.theme.nm, {0.5, 0.5}) fx.label("fx.group({o = o})", {1400, 900}, fx.mono(36), fx.theme.nm, {0.5, 0.5}) } ``` `blur` is a gaussian blur over the contents, `mblur` the same along x and along y separately. A blur that goes to 0 as a title arrives reads as coming into focus; an `mblur` in proportion to the speed of a move reads as a shutter that stayed open. The demo's square moves at up to 1,885 px a second, and its `mblur` is the distance it covers in `shutter` sixtieths of a second. ```odin group_blur :: proc(s: fx.Shot) { fx.backdrop(.Night) k := fx.win(s.lt, 0.2, 3.8, 1.0, 0.6) // blur: a gaussian over everything in the group, here easing to 0 as the word arrives if fx.group({blur = knob("blur", 40, 0, 100) * (1 - k), o = k}) { fx.label("Focus", {960, 320}, fx.sans(260, 700, -0.04), fx.theme.nt, {0.5, 0.5}) } // mblur: blur along one direction, here as long as the square is fast x := 1200 * (0.5 - 0.5 * math.cos(s.lt * math.PI)) // left to right and back in 2 s speed := abs(600 * math.PI * math.sin(s.lt * math.PI)) // px per second shutter := knob("shutter", 1, 0, 3) / 60 // how long the "shutter" is open, in frames if fx.group({x = x, mblur = {speed * shutter, 0}}) { fx.rrect({260, 640, 200, 200}, 44, fx.theme.na) } } ``` ## When a group costs something A group that only moves, scales, turns, tilts and clips is free: it changes the canvas's matrix and clip, and the contents are drawn straight to the frame. Everything else needs a layer: the contents are drawn into an offscreen picture first, which is then filtered and put on the frame. `group` makes a layer exactly when one of these holds: - `o` is below 0.998 - `blur`, `mblur.x` or `mblur.y` is above 0.05 - any of `gray`, `bright`, `contrast`, `sat`, `tint`, `invert` changes the picture - `blend` is set, to any mode - `post` is set - `glow` has an `amount` above 0.003 and a `radius` or `streak` above 0.05 So a group whose opacity has reached 1 and whose blur has reached 0 stops costing anything by itself: `{o = k, blur = 12 * (1 - k)}` is a layer during the entrance and a plain transform afterwards. A layer covers the whole frame unless something limits it. `clip` does, and so does `bounds`: ```odin if fx.group({o = k, blur = 20 * (1 - k), bounds = fx.Rect{560, 340, 800, 400}}) { // a card that lives in that rect } ``` `bounds` tells the renderer where the contents are, in the same coordinates you draw them in, so the layer and its blur only cover that area. The room that `blur`, `mblur`, `post` and `glow` need around it is added for you. It is a hint and not a clip: it positions nothing, and what you draw outside it may or may not be cut off. Use it on small faded or blurred things when there are many of them (the library's own [letter animations](/docs/type/) and layout elements do); leave it out when the group fills the frame anyway. Within a layer the steps run in this order: blur, `post`, `glow`, the grade, then opacity and `blend` as the layer lands on what is below. ## Grading The six grading fields change the colors of everything in the group. Together they are one color matrix, which is cheap wherever it is used, on one picture or on the whole film. ```odin group_grade :: proc(s: fx.Shot) { fx.backdrop(.Night) img := fx.load_image("assets/frame.jpg") k := (0.5 - 0.5 * math.cos(s.p * math.TAU)) * knob("amount", 1, 0, 1) // 0 → 1 → 0 looks := [?]struct {name: string, xf: fx.Xf} { {"gray", {gray = k}}, {"sat", {sat = 1 + 1.5 * k}}, {"bright", {bright = 1 + 1.5 * k}}, {"contrast", {contrast = 0.8 * k}}, {"tint", {tint = fx.mix(0xffffffff, fx.theme.na, k)}}, {"invert", {invert = k}}, } for look, i in looks { r := fx.Rect{150 + f32(i % 3) * 550, 110 + f32(i / 3) * 460, 520, 340} if fx.group(look.xf) do fx.image(img, r, focus = {0.6, 0.3}, zoom = 1.6) fx.label(look.name, {r.x, r.y + r.h + 20}, fx.mono(32), fx.theme.nm) } } ``` | Field | Detail | | --- | --- | | `gray` | 0..1, how far toward black and white. It multiplies with `sat`: the saturation used is `sat * (1 - gray)`. | | `sat` | 1 is unchanged, 0 gray, above 1 more vivid. Brightness is weighed the way the eye does (Rec. 709), so green stays lighter than blue. | | `bright` | Multiplies red, green and blue. 0 means unchanged, like 1; for black use `tint = 0xff000000`. | | `contrast` | Scales the colors away from middle gray by `1 + contrast`. | | `tint` | Multiplies the colors by the tint's red, green and blue: white is no change, `0xffff0000` leaves only the red channel. Its alpha is ignored. | | `invert` | 1 is the negative, 0.5 is flat gray on the way there. | They are applied in that order: saturation, brightness, contrast, tint, invert. A group around all scenes of a video, [`Video.master`](/docs/scenes/), is where a film's overall grade goes. ## Blend `blend` decides how the group, once drawn, is combined with what is already on the frame. The contents are first drawn normally among themselves, then the finished layer lands with the mode. ```odin group_blend :: proc(s: fx.Shot) { fx.backdrop(.Night) modes := [?]sk.Blend{.Plus, .Screen, .Multiply, .Overlay, .Difference, .Exclusion} for mode, i in modes { r := fx.Rect{150 + f32(i % 3) * 550, 110 + f32(i / 3) * 460, 520, 340} fx.rrect_paint(r, 28, fx.linear({r.x, 0}, {r.x + r.w, 0}, fx.theme.night, fx.theme.na, fx.theme.nt)) x := r.x + r.w * (0.5 + 0.32 * math.sin(s.p * math.TAU)) // the circle is drawn into a layer, and the layer lands on the gradient with this mode if fx.group({blend = mode, clip = r, radius = 28}) { fx.circle({x, r.y + r.h / 2}, 120, 0xff3d7bd9) } fx.label(fmt.tprintf(".%v", mode), {r.x, r.y + r.h + 20}, fx.mono(32), fx.theme.nm) } } ``` The modes are Skia's, the enum `sk.Blend` (`import sk "effects:sk"`). In a group literal the short form is enough: `blend = .Screen`. | Kind | Modes | | --- | --- | | Lighten | `.Plus` (add), `.Screen`, `.Lighten`, `.Color_Dodge` | | Darken | `.Multiply`, `.Darken`, `.Color_Burn`, `.Modulate` | | Contrast | `.Overlay`, `.Hard_Light`, `.Soft_Light` | | Compare | `.Difference`, `.Exclusion` | | Color | `.Hue`, `.Saturation`, `.Color`, `.Luminosity` | | Compositing | `.Clear`, `.Src`, `.Dst`, `.Src_Over` (normal), `.Dst_Over`, `.Src_In`, `.Dst_In`, `.Src_Out`, `.Dst_Out`, `.Src_Atop`, `.Dst_Atop`, `.Xor` | `.Plus` is the one for light: glows, sparks and beams that should add up where they overlap. For a single shape, [`additive`](/docs/draw/#paints) does the same on a paint without a layer. The compositing modes are for masks. `.Dst_In` keeps of what is below only the part the group covers, so a picture can be cut to the shape of anything you can draw. The outer group is there to give the picture a layer of its own to be cut out of (setting `blend`, even to the normal mode, makes one): ```odin if fx.group({blend = .Src_Over}) { fx.image(img, {100, 100, 800, 500}) if fx.group({blend = .Dst_In}) { // keep of the image only what the letters cover fx.label("MASK", {500, 350}, fx.sans(300, 700, -0.04), 0xffffffff, {0.5, 0.5}) } } ``` ## Clip `clip` cuts the contents to a rect, with rounded corners when `radius` is set. The rect is in the group's coordinates and goes through the group's transform with the contents, so a clipped card can still slide, scale and tilt as a whole. Clipping needs no layer. ```odin group_clip :: proc(s: fx.Shot) { fx.backdrop(.Night) win := fx.Rect{610, 190, 700, 700} radius := knob("radius", 60, 0, 350) fx.rrect(win, radius, fx.theme.night2) // nothing drawn in the group shows outside win if fx.group({clip = win, radius = radius}) { for i in 0 ..< 13 { y := win.y + f32(i) * 140 - 140 * 7 * s.p // the list scrolls up by seven rows a loop fx.rrect({win.x + 50, y + 20, win.w - 100, 100}, 24, i % 7 == 3 ? fx.theme.na : fx.theme.nb) fx.circle({win.x + 100, y + 70}, 26, i % 7 == 3 ? fx.theme.nt : fx.theme.ns) } } fx.border(win, fx.theme.ns, 2, radius) } ``` A clip is also how an [image](/docs/draw/#images) gets rounded corners, and how something is revealed: animate the clip's width and the contents are wiped in. ## Post filters `post` runs a pixel filter over the group: the contents are drawn into a layer and every pixel of the result is computed from it by a shader. ```odin if fx.group({post = fx.rgb_split(8)}) { fx.caption("split", {960, 540}, 220, fx.theme.nt, {0.5, 0.5}) } ``` The built-in ones (`rgb_split`, `glitch`, `zoom_blur`, `pixelate`, `duotone`, `scanlines`, `halftone`, `dither`, `lens`, `shockwave`, `kaleido`, `warp`, `stretch`) and writing your own are on [Post filters](/docs/post/). On the CPU a filter that reads each pixel three times costs about 0.05 s per 1080p frame, so keep them to the frames that need them. A group has one `post`; nest groups to chain them. Because a group's post runs before its grade, a filter that should see graded colors (a dither over a black-and-white picture) goes on a group around the graded one. ## Glow `glow` is bloom: what is brighter than a threshold is blurred and added back on top, optionally with a wide horizontal streak. ```odin if fx.group({glow = fx.glow(24, 0.8, 0.5)}) { // radius in px, amount, threshold … } ``` It runs after the group's blur and post, and works best on a group that paints its own background. It is made of Skia's own blur and costs about 0.02 s per 1080p frame on the CPU. The `Glow` fields and examples are on [Post filters](/docs/post/). ## Nesting Groups nest, and each one works in the coordinates of the one around it: an inner group's `x` and `origin` are positions inside the outer group, and its opacity multiplies with the outer one's. ```odin if fx.group({x = 1400, y = 500, rot = 360 * s.p}) { // the planet's place, turning once a loop fx.circle({0, 0}, 60, fx.theme.na) // {0, 0} is now {1400, 500} if fx.group({x = 260, rot = -720 * s.p}) { // 260 px out, carried around by the turn fx.circle({0, 0}, 30, fx.theme.nt) fx.circle({70, 0}, 12, fx.theme.nm) // a moon of the moon } } ``` Nesting is also how you choose the order of things one group does in a fixed order: to move first and scale afterwards, put the move in an inner group and the scale in an outer one. A layer inside a layer is a second offscreen picture, so keep the filtered groups as far out as the look allows: one blur around ten cards, not ten blurred cards. ## Without the scope ```odin group_begin :: proc(xf: Xf) -> bool end_group :: proc(ok: bool) ``` `group_begin` is `group` without the automatic end, for when a group starts in one procedure and ends in another. Hand its result to `end_group`, and skip the drawing when it returned false: ```odin ok := fx.group_begin({o = 0.5, bounds = fx.Rect{100, 700, 600, 300}}) if ok { fx.rect({100, 700, 400, 200}, fx.theme.nt) fx.rect({300, 800, 400, 200}, fx.theme.nt) } fx.end_group(ok) ``` ## Frosted glass ```odin frosted :: proc(r: Rect, sigma: f32, radius: f32 = 0) -> bool ``` `frosted` blurs what is already drawn behind `r` by `sigma` px, and then draws the rest of its scope on top, clipped to `r` (with corners rounded by `radius`). It is used like a group and always returns true: ```odin group_frosted :: proc(s: fx.Shot) { fx.backdrop(.Night) colors := [?]fx.Color{fx.theme.na, 0xff3d7bd9, 0xff2f9e6b} for c, i in colors { a := s.p * math.TAU + f32(i) * math.TAU / 3 fx.circle({960 + 420 * math.cos(a), 540 + 240 * math.sin(2 * a)}, 150, c) } glass := fx.Rect{560, 290, 800, 500} // what is already on the canvas behind glass is blurred; the scope draws on top of it if fx.frosted(glass, knob("sigma", 30, 0, 80), 48) { fx.rect(glass, 0x14ffffff) fx.label("Frosted", fx.center(glass), fx.sans(120, 600, -0.03), fx.theme.nt, {0.5, 0.5}) } fx.border(glass, 0x40ffffff, 2, 48) } ``` Only what was drawn before the call is blurred, so the order of the calls is the order of the layers: background first, then the glass, then whatever floats above it. A translucent fill and a hairline border are what make it read as glass. Inside a group that is a layer, "behind" is what that group has drawn so far. ## Reference | Name | What it is | | --- | --- | | `Xf` | What a group does to its contents: transform, opacity, blur, grade, blend, post, glow, clip. | | `group(xf)` | Applies `xf` to what is drawn until the scope ends; false (and nothing drawn) when invisible. | | `group_begin(xf)`, `end_group(ok)` | The same in two calls. | | `frosted(r, sigma, radius)` | Blurs what is behind `r` and draws its scope on top. | | `grade_matrix(xf)` | The 4×5 color matrix (row-major, as `[20]f32`) for an `Xf`'s grading fields, and false when they change nothing. | | `tilt_matrix(origin, rx, ry, rz, persp)` | The 4×4 matrix of a tilt, see [the stage](/docs/color/#tilt-matrix). | --- # Colors, rects and the stage Three small types run through the whole library: a color is a number, a point is two floats, and a rect is a corner and a size. This page covers them, the helpers that go with them, and the stage they are all measured against. ## Colors ```odin Color :: u32 // 0xAARRGGBB ``` A color is a 32-bit number written as eight hex digits: alpha first, then red, green and blue. `0xffdd5b3e` is an opaque orange, `0x80ffffff` white at 50%, `0x24f2f0e6` a hairline at 14%. Colors are not premultiplied: the red, green and blue of a translucent color are the same as those of the opaque one. > **Note:** The alpha comes first and is part of the number. A color copied from CSS as `0xdd5b3e` has an alpha of 0 and draws nothing: write `0xffdd5b3e` or `fx.rgb(0xdd5b3e)`. ```odin rgb :: proc "contextless" (hex: u32) -> Color alpha :: proc(c: Color, a: f32) -> Color with_alpha :: proc(c: Color, a: f32) -> Color mix :: proc(a, b: Color, p: f32) -> Color ``` | Procedure | Returns | | --- | --- | | `rgb(hex)` | The opaque color for a six-digit `0xRRGGBB`. | | `alpha(c, a)` | `c` with its alpha multiplied by `a` (0..1). A color that is already translucent gets more so. This is the one for fading. | | `with_alpha(c, a)` | `c` with its alpha replaced by `a` (0..1), whatever it was. | | `mix(a, b, p)` | The color `p` of the way from `a` to `b`, `p` clamped to 0..1. Alpha, red, green and blue are each interpolated on their own. | The difference between `alpha` and `with_alpha` matters with the theme's colors, several of which are translucent to begin with: the theme's `nm` is the text color at 72%, so `fx.alpha(nm, 0.5)` is 36% and `fx.with_alpha(nm, 0.5)` is 50%. ```odin color_mix :: proc(s: fx.Shot) { fx.backdrop(.Night) a, b := fx.rgb(0x3d7bd9), fx.theme.na p := 0.5 - 0.5 * math.cos(s.p * math.TAU) // 0 → 1 → 0 for i in 0 ..< 9 do fx.rrect({168 + f32(i) * 180, 130, 144, 144}, 28, fx.mix(a, b, f32(i) / 8)) c := fx.mix(a, b, p) fx.circle({240 + 1440 * p, 340}, 28, c) fx.label(fmt.tprintf("fx.mix(a, b, %.2f) = 0x%08x", p, c), {168, 410}, fx.mono(40), fx.theme.nt) // alpha scales the alpha a color already has, with_alpha replaces it nm := fx.theme.nm // 0xb8f2f0e6: the text color at 72% rows := [?]struct {code: string, c: fx.Color} { {"nm", nm}, {fmt.tprintf("fx.alpha(nm, %.2f)", p), fx.alpha(nm, p)}, {fmt.tprintf("fx.with_alpha(nm, %.2f)", p), fx.with_alpha(nm, p)}, } for row, i in rows { x := 168 + f32(i) * 540 fx.rrect({x, 600, 504, 150}, 28, row.c) fx.label(row.code, {x, 780}, fx.mono(32), fx.theme.nm) fx.label(fmt.tprintf("0x%08x", row.c), {x, 830}, fx.mono(32), fx.theme.nt) } } ``` `unpack(c)` goes the other way, to four floats in 0..1 (`RGBA{r, g, b, a}`), which is the form a [shader's uniforms](/docs/post/) take. A few arguments in the library use the color 0 (fully transparent black) to mean "none" or "the theme's default", for example `Xf.tint`. To multiply by black there, write `0xff000000`. ## Points and rects ```odin Vec2 :: [2]f32 Rect :: struct { x, y, w, h: f32, } ``` A `Vec2` is a point or an offset in px. Being an Odin array it does arithmetic by component and has `.x` and `.y`: `c + {40, 0}` is 40 px to the right of `c`, `(a + b) / 2` is halfway between two points, and `fx.lerp2(a, b, p)` any fraction of the way (see [Animation](/docs/anim/#progress)). A `Rect` is its top-left corner and its size, in px. Almost everything that takes up room takes a `Rect`, and the helpers derive one rect from another so that a scene needs few hard numbers: ```odin inset :: proc(r: Rect, d: f32) -> Rect inset4 :: proc(r: Rect, top, right, bottom, left: f32) -> Rect center :: proc(r: Rect) -> Vec2 contains :: proc(r: Rect, p: Vec2) -> bool lerp_rect :: proc(a, b: Rect, p: f32) -> Rect contain :: proc(r: Rect, aw, ah: f32) -> Rect ``` | Procedure | Returns | | --- | --- | | `inset(r, d)` | `r` made smaller by `d` px on every side. A negative `d` grows it: `fx.inset(box, -24)` is a frame with 24 px of padding around `box`. | | `inset4(r, top, right, bottom, left)` | The same with a distance per side, in CSS order. | | `center(r)` | The middle of `r`. | | `contains(r, p)` | Whether point `p` is inside `r`. The left and top edges count as inside, the right and bottom ones do not. | | `lerp_rect(a, b, p)` | The rect `p` of the way from `a` to `b`: position and size are each interpolated. `p` is not clamped, so an ease that overshoots carries through. | | `contain(r, aw, ah)` | The largest rect with the proportions `aw`:`ah` that fits into `r`, centered, like CSS `object-fit: contain`. | `lerp_rect` with an eased progress is how one thing becomes another: a thumbnail growing into a full-screen picture, a highlight moving from one row to the next. ```odin color_rects :: proc(s: fx.Shot) { fx.backdrop(.Night) a, b := fx.Rect{200, 200, 520, 680}, fx.Rect{860, 300, 860, 400} p := fx.ep(s.lt, 0.4, 2.2, fx.ease_in_out) - fx.ep(s.lt, 2.9, 4.7, fx.ease_in_out) fx.border(a, fx.theme.nb, 2) fx.border(b, fx.theme.nb, 2) r := fx.lerp_rect(a, b, p) // every field of a on its way to b fx.rect(r, fx.theme.night2) fx.border(r, fx.theme.nt, 3) pad := fx.inset(r, 40) // 40 px in from every side fx.border(pad, fx.theme.ns, 2) fit := fx.contain(pad, 16, 9) // the largest 16:9 box in pad, centered fx.rect(fit, fx.theme.na) fx.circle(fx.center(r), 12, fx.theme.nt) fx.label("contain(pad, 16, 9)", {fit.x + 16, fit.y + 12}, fx.mono(30), fx.theme.night) fx.label("lerp_rect(a, b, p)", {r.x, r.y - 50}, fx.mono(32), fx.theme.nm) } ``` ## The stage A video is designed on a stage of fixed size, 1920×1080 unless the project says otherwise, and every number you pass to `fx` is in stage px: `{0, 0}` is the top-left corner, x grows to the right, y grows down. ```odin stage :: proc() -> Rect now :: proc() -> f32 canvas :: proc() -> ^sk.Canvas ``` `stage()` returns the stage as a rect, `{0, 0, 1920, 1080}` by default. Deriving positions from it (`fx.center(fx.stage())`, `fx.inset(fx.stage(), 96)`) keeps a scene correct if the size changes. `now()` is the video time of the frame being drawn, in seconds: the same value a scene receives as `s.t`. It is for helpers that are called from scenes and should not need the time handed down to them. ```odin color_stage :: proc(s: fx.Shot) { fx.backdrop(.Night) st := fx.stage() // {0, 0, 1920, 1080}, whatever size the frame is rendered at f := fx.mono(34) fx.border(st, fx.theme.ns, 4) // the edge of the picture fx.label("{0, 0}", {st.x + 36, st.y + 28}, f, fx.theme.nm) fx.label(fmt.tprintf("{{%.0f, %.0f}}", st.w, st.h), {st.w - 36, st.h - 28}, f, fx.theme.nm, {1, 1}) fx.label(fmt.tprintf("fx.now() = %.2f s", fx.now()), {st.w - 36, st.y + 28}, f, fx.theme.nm, {1, 0}) zone := fx.Rect{1140, 560, 480, 300} p := fx.center(st) + {660 * math.sin(s.p * math.TAU), 300 * math.sin(2 * s.p * math.TAU)} inside := fx.contains(zone, p) fx.rect(zone, inside ? fx.alpha(fx.theme.na, 0.25) : fx.theme.night2) fx.border(zone, inside ? fx.theme.na : fx.theme.nb, 2) fx.label("zone", {zone.x + 20, zone.y + 14}, f, fx.theme.nm) fx.circle(p, 20, fx.theme.nt) fx.label(fmt.tprintf("{{%.0f, %.0f}}", p.x, p.y), p + {34, 0}, f, fx.theme.nt, {0, 0.5}) } ``` ### Rendering at other sizes The stage is a design size, not an output size. A renderer that wants more or fewer pixels scales the canvas, and the scene draws exactly as before: ```bash build/effects render projects/spot # 1920×1080 build/effects render projects/spot --scale 2 # 3840×2160 build/effects still projects/spot 2.5 --scale 0.5 ``` The output is the stage times `--scale`, rounded to even pixel counts. Shapes and text are rasterized at the output size, so a render at twice the scale is twice as sharp, not an enlargement. What is made of pixels (an [image](/docs/draw/#images), [footage](/docs/footage/), a [baked layer](/docs/draw/#baked-layers)) is as sharp as its source. The editor's preview and the players on these pages are the same thing: the 1920×1080 stage drawn smaller. A project with another format sets its own stage in `video`, and `stage()` returns that: ```odin fx.video({name = "Story", width = 1080, height = 1920, scenes = SCENES[:]}) ``` ### The canvas `canvas()` is the Skia canvas of the frame, for the calls the `sk` package has and `fx` does not wrap, such as an oval or a clip to a path: ```odin cv := fx.canvas() p := fx.fill(fx.theme.na) sk.canvas_draw_oval(cv, 100, 100, 400, 200, &p) // x, y, w, h of the oval's box sk.canvas_save(cv) sk.canvas_clip_path(cv, star) // a ^sk.Path fx.image(img, {0, 0, 24, 24}) sk.canvas_restore(cv) // every save needs its restore ``` Ask for it where you use it instead of keeping it: inside a [baked layer](/docs/draw/#baked-layers) it is the layer's canvas, not the frame's. The state behind these accessors is the variable `S`, one per render thread. Two of its fields are worth knowing: `fx.S.scale` is the number of output pixels per stage pixel for the frame being drawn (1 for a normal render, 2 with `--scale 2`), and `fx.S.preview` is true when the frame is drawn for the editor's preview instead of a final render. ## Tilt matrix ```odin tilt_matrix :: proc(origin: Vec2, rx, ry, rz, persp: f32) -> [16]f32 ``` The 4×4 matrix, row-major, of a CSS-like perspective tilt: a rotation by `rz`, then `ry`, then `rx` (degrees) around `origin`, seen from `persp` px away (0 or less means 1600). It is what a [group](/docs/group/#3d-tilt) uses for its `rx` and `ry`, and you only need it yourself when you apply a tilt to the canvas directly: ```odin m := fx.tilt_matrix({1500, 540}, 0, 50, 0, 1600) cv := fx.canvas() sk.canvas_save(cv) sk.canvas_concat44(cv, &m) fx.border({1300, 340, 400, 400}, fx.theme.na, 6) sk.canvas_restore(cv) ``` ## Reference | Name | What it is | | --- | --- | | `Color` | A `u32`, `0xAARRGGBB`. | | `rgb(hex)` | Opaque color from `0xRRGGBB`. | | `alpha(c, a)` | `c` with its alpha multiplied by `a`. | | `with_alpha(c, a)` | `c` with its alpha set to `a`. | | `mix(a, b, p)` | The color between `a` and `b`. | | `Vec2` | `[2]f32`, a point or an offset in px. | | `Rect` | `{x, y, w, h}` in px. | | `inset(r, d)`, `inset4(r, top, right, bottom, left)` | `r` shrunk (or, negative, grown). | | `center(r)` | The middle of `r`. | | `contains(r, p)` | Whether `p` is in `r`. | | `lerp_rect(a, b, p)` | The rect between `a` and `b`. | | `contain(r, aw, ah)` | An `aw`:`ah` box fitted into `r`. | | `stage()` | The design stage as a rect. | | `now()` | The frame's video time in seconds. | | `canvas()` | The Skia canvas being drawn to. | | `S` | The per-thread frame state (`Frame_State`) the three above read. | | `tilt_matrix(origin, rx, ry, rz, persp)` | The matrix of a perspective tilt. | --- # Theme and fonts A theme is a set of named colors and two font families. The library's [UI components](/docs/ui/) take all their colors from it, the font helpers take their families from it, and scenes that use its names instead of hex values look like they belong together. There is one, `theme`, and a project can change or replace it. ## The theme ```odin Theme :: struct { // night (dark) surfaces and text night, night2: Color, nt, nm, ns: Color, // text, muted, subtle nb: Color, // hairline na: Color, // accent on night // paper (light) surfaces and text bg, sf, sf2, sf3: Color, bd, bds: Color, // hairline, stronger hairline ink, mut, sub: Color, red, red_soft: Color, ok, ok_soft: Color, warn, warn_soft: Color, sans, mono: cstring, } LIERMANN :: Theme{…} theme := LIERMANN ``` The colors come in two sets, for the two kinds of surface a scene is drawn on: night, a near-black, and paper, a warm off-white. `LIERMANN` is the default: paper surfaces, hairline borders, mono labels and one red. ```odin theme_palette :: proc(s: fx.Shot) { th := fx.theme swatches := [?]struct {name: string, c: fx.Color} { {"night", th.night}, {"night2", th.night2}, {"nt", th.nt}, {"nm", th.nm}, {"ns", th.ns}, {"nb", th.nb}, {"na", th.na}, // the first seven are for night, the rest for paper {"bg", th.bg}, {"sf", th.sf}, {"sf2", th.sf2}, {"sf3", th.sf3}, {"bd", th.bd}, {"bds", th.bds}, {"ink", th.ink}, {"mut", th.mut}, {"sub", th.sub}, {"red", th.red}, {"red_soft", th.red_soft}, {"ok", th.ok}, {"ok_soft", th.ok_soft}, {"warn", th.warn}, {"warn_soft", th.warn_soft}, } fx.rect({0, 0, 660, 1080}, th.night) fx.rect({660, 0, 1260, 1080}, th.bg) for sw, i in swatches { night := i < 7 j := night ? i : i - 7 r := fx.Rect{70 + f32(j % 2) * 280, 60 + f32(j / 2) * 250, 240, 150} if !night do r = {740 + f32(j % 4) * 285, 60 + f32(j / 4) * 250, 240, 150} k := fx.stagger(s.lt, i, 0.2, 0.04, 0.5) fx.rrect(fx.inset(r, 30 * (1 - k)), 20, fx.alpha(sw.c, k)) // each on the surface it is meant for fx.border(r, night ? th.nb : th.bd, 2, 20) fx.label(sw.name, {r.x, r.y + r.h + 14}, fx.mono(32), night ? th.nt : th.ink) } } ``` On night: | Field | `LIERMANN` | Use | | --- | --- | --- | | `night` | `0xff111110` | The dark surface. | | `night2` | `0xff1a1a15` | A raised surface on it: cards, panels. | | `nt` | `0xfff2f0e6` | Text. | | `nm` | `0xb8f2f0e6` | Muted text: the text color at 72%. | | `ns` | `0x7af2f0e6` | Subtle text and marks, 48%. | | `nb` | `0x24f2f0e6` | Hairlines and borders, 14%. | | `na` | `0xffdd5b3e` | The accent. | On paper: | Field | `LIERMANN` | Use | | --- | --- | --- | | `bg` | `0xfff3f2ec` | The page. | | `sf` | `0xfffbfaf7` | A surface on it: windows, cards. | | `sf2` | `0xffedebe3` | A recessed surface: a window's title bar, an avatar. | | `sf3` | `0xffe4e2d8` | A darker one still: the track of a meter. | | `bd` | `0x2116160f` | Hairlines and borders: ink at 13%. | | `bds` | `0x3d16160f` | A stronger hairline, 24%. | | `ink` | `0xff16160f` | Text. | | `mut` | `0xbd16160f` | Muted text, 74%. | | `sub` | `0x8f16160f` | Subtle text, 56%. | | `red` | `0xffb4321f` | The accent on paper, and the `.Red` tone of pills and buttons. | | `red_soft` | `0x14b4321f` | Its wash, 8%: the background of a red pill. | | `ok` | `0xff2f6b47` | The `.Ok` tone. | | `ok_soft` | `0x1a2f6b47` | Its wash, 10%. | | `warn` | `0xff8a6410` | The `.Warn` tone. | | `warn_soft` | `0x1a8a6410` | Its wash, 10%. | The muted, subtle, hairline and soft colors are translucent versions of the text or accent color, so they sit correctly on any of their set's surfaces. That is also why fading one of them is done with [`alpha`](/docs/color/#colors), which multiplies the alpha they have, and not with `with_alpha`. `sans` and `mono` are the family names the [font helpers](#fonts) use: `"SG"` and `"JBM"`. ### Changing it `theme` is an ordinary variable, read every time something is drawn. Change it once, in `effects_video`, before any frame is drawn: ```odin @(export) effects_video :: proc() -> ^fx.Video { fx.theme.na = 0xff62e6d2 // one field … fx.theme.red = 0xff0f8f7d dusk := fx.LIERMANN // … or a whole theme, starting from the default dusk.night, dusk.night2 = 0xff0d0b14, 0xff17142a dusk.nt, dusk.nm, dusk.ns, dusk.nb = 0xffeeeaff, 0xb8eeeaff, 0x7aeeeaff, 0x24eeeaff fx.theme = dusk return fx.video({name = "Spot", scenes = SCENES[:]}) } ``` Start from `LIERMANN` rather than an empty `fx.Theme{}`: a field left out of a new struct is 0, which as a color is fully transparent. Do not change the theme from inside a scene. Frames are drawn on several threads at once and in any order, and they all read the same variable. Two things do not follow the theme. `backdrop` draws fixed night and paper gradients, so a theme with other surface colors needs its own background. And a video's `background` is black unless you set it (`fx.video({background = fx.theme.night, …})`). A project is free to ignore the theme too: `projects/fable` defines its own handful of color constants and uses the theme only for its fonts. ## Fonts ```odin sans :: proc(size: f32, weight: f32 = 400, tracking: f32 = 0) -> Font mono :: proc(size: f32, weight: f32 = 400, tracking: f32 = 0) -> Font caps :: proc(size: f32, tracking: f32 = 0.1, weight: f32 = 400) -> Font ``` Each returns a [`Font`](/docs/draw/#fonts) in one of the theme's two families: `size` in px, `weight` 100..900, `tracking` in em. `sans` is for headlines and running text, `mono` for labels, numbers and code. `caps` is the mono family in capitals with open letter spacing, the style of eyebrows and section labels; note that its second argument is the tracking, not the weight. The result is a plain struct, so set further fields on it when you need them: ```odin f := fx.sans(72, 500, -0.02) f.lh = 1.2 f.tabular = true ``` ```odin theme_fonts :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme weight := knob("weight", 600, 300, 700) k := fx.ep(s.lt, 0.2, 1.0) // each line is set in the font its text names if fx.group({o = k, y = 30 * (1 - k)}) { fx.text(fmt.tprintf("fx.sans(150, %.0f, -0.03)", weight), 130, 110, fx.sans(150, weight, -0.03), th.nt) fx.text("fx.sans(64)", 130, 330, fx.sans(64), th.nm) fx.text("fx.mono(64)", 130, 500, fx.mono(64), th.nt) fx.text("fx.mono(64, 500)", 130, 600, fx.mono(64, 500), th.nt) fx.text("fx.caps(48)", 130, 790, fx.caps(48), th.na) fx.text("fx.caps(48, 0.3, 500)", 130, 880, fx.caps(48, 0.3, 500), th.na) } } ``` Two families are bundled and registered by `video` for every project: | Family | Typeface | Weights | | --- | --- | --- | | `"SG"` | Space Grotesk, a variable font | Any weight from 300 to 700. | | `"JBM"` | JetBrains Mono, two static files | 400 and 500. Other weights use the nearer of the two. | Both are the Latin subsets of their typefaces, enough for Western European languages. `assets/fonts` in the repository also has Space Grotesk's Latin Extended subset, which is not registered. ### Your own fonts ```odin font :: proc(family: string, path: string) -> bool ``` `font` registers a font file under a family name of your choosing. The path is relative to the project directory. Call it once, in `effects_video`; it returns false and prints `fx: cannot load font` when the file cannot be read. `projects/fable` adds a serif this way, five static files under one name: ```odin @(export) effects_video :: proc() -> ^fx.Video { v := fx.video({name = "Fable 5.2", scenes = SCENES[:]}) // Fraunces (SIL Open Font License), the storyteller's voice next to the machine's mono for f in ([?]string{"Light", "LightItalic", "Regular", "Italic", "SemiBoldItalic"}) { fx.font("FR", fmt.tprintf("assets/fonts/Fraunces144pt-%s.ttf", f)) } return v } serif :: proc(size: f32, italic := true, weight: f32 = 300) -> fx.Font { return {family = "FR", size = size, weight = weight, italic = italic, tracking = -0.012, lh = 1.08} } ``` How a family's files are chosen: - Several files under one name make a family. `Font.weight` and `Font.italic` pick the closest file, so `serif(96)` above is Light Italic and `serif(96, false, 400)` is Regular. - A variable font is one file, and `Font.weight` sets its weight axis directly. - Asking for an italic the family does not have gets the upright face slanted by the text engine, and a weight far above the heaviest file gets it thickened. Neither looks like a drawn italic or bold: register the real files. - A family name that was never registered does not fail. The text is drawn in a fallback font, so a typo in the name shows as the wrong typeface. To make the theme's helpers, and with them every UI component, use your fonts, point the theme at them: ```odin fx.font("Inter", "assets/fonts/Inter-Variable.woff2") fx.theme.sans = "Inter" // fx.sans, captions, windows and tables now use it ``` `.ttf` and `.woff2` files both work. ## Icons The library carries a set of 77 line icons, drawn on a 24-unit grid with round stroke ends. [`icon`](/docs/draw/#icons) draws one by name at any size and stroke width; [`icon_path`](/docs/draw/#icons) returns its path. ```odin fx.icon("calendar", 160, 160, 96, fx.theme.nt) // 96 px, top-left corner at {160, 160} fx.icon("check", 300, 160, 96, fx.theme.na, 2.4) // a heavier stroke, in 24ths of the size ``` ```odin theme_icons :: proc(s: fx.Shot) { fx.backdrop(.Night) for d, i in fx.ICON_DEFS { // every icon, down the columns in alphabetical order x, y := 50 + f32(i / 13) * 308, 22 + f32(i % 13) * 80 k := fx.stagger(s.lt, i, 0.1, 0.012, 0.4) if fx.group({o = k, x = -20 * (1 - k)}) { fx.icon(d.name, x, y + 14, 52, fx.theme.nt, 1.6) fx.label(d.name, {x + 68, y + 40}, fx.mono(28), fx.theme.nm, {0, 0.5}) } } } ``` | | Names | | --- | --- | | A–C | `agent`, `arrow`, `backspace`, `bell`, `briefcase`, `broadcast`, `calendar`, `calls`, `chat`, `check`, `chevronDown`, `chevronLeft`, `chevronRight`, `circle`, `clip`, `close`, `contacts`, `copy` | | D–H | `dashboard`, `doc`, `documents`, `edit`, `externalLink`, `eye`, `feed`, `flow`, `funnel`, `globe`, `grid`, `hang`, `hangup`, `history` | | I–M | `info`, `insta`, `instagram`, `kanban`, `key`, `layers`, `linkedin`, `lock`, `mail`, `maximize`, `menu`, `mic`, `microphone`, `microphoneOff`, `moon` | | P–S | `panelLeft`, `paperclip`, `pause`, `phone`, `pipeline`, `play`, `plus`, `refresh`, `screen`, `search`, `send`, `server`, `settings`, `shield`, `signOut`, `sliders`, `spark`, `sparkles`, `stop`, `sun` | | T–W | `trash`, `upload`, `usage`, `users`, `video`, `videoOff`, `volume`, `volumeOff`, `whatsapp`, `workflows` | Names are case-sensitive, and one that is not in the list draws nothing. All icons are stroked except `linkedin`, which is a filled shape and ignores the stroke width. The set is the array `ICON_DEFS`, which is what the demo above loops over: ```odin Icon_Def :: struct { name: string, d: cstring, // SVG path data on a 24×24 grid filled: bool, } ``` For an icon that is not in the set, draw its SVG path yourself, the way `icon` does: scale a group by `size / 24` and stroke the path. ```odin bolt := sk.path_from_svg("M13 2L4 14h7l-1 8 9-12h-7z") defer sk.path_free(bolt) if fx.group({x = 160, y = 160, s = 96.0 / 24}) { fx.draw_path(bolt, fx.stroke(fx.theme.nt, 1.6)) } ``` ## Reference | Name | What it is | | --- | --- | | `Theme` | Named colors for night and paper surfaces, and two font families. | | `LIERMANN` | The default theme. | | `theme` | The theme in use; a variable a project can change. | | `sans(size, weight, tracking)` | A `Font` in the theme's sans family. | | `mono(size, weight, tracking)` | A `Font` in the theme's mono family. | | `caps(size, tracking, weight)` | The mono family in capitals, tracked out. | | `font(family, path)` | Registers a font file under a family name. | | `default_fonts()` | Registers the bundled `"SG"` and `"JBM"` families; `video` calls it. | | `ICON_DEFS`, `Icon_Def` | The built-in icons: name, SVG path data, filled or stroked. | | `icon(name, x, y, size, c, width)`, `icon_path(name)` | Drawing an icon, see [Drawing](/docs/draw/#icons). | --- # Post filters and glow A post filter runs over the finished pixels of a [group](/docs/group/): everything the group drew is handed to a small shader, and what the shader returns is what lands on the stage. That is how you split colors, break a picture into dots, bend it through a lens or send a shockwave through it, things no amount of moving shapes around can do. ```odin if fx.group({post = fx.rgb_split(8)}) { fx.caption("split", {960, 540}, 220, fx.theme.nt, {0.5, 0.5}) } ``` Each procedure on this page returns a `Post`, a value for the `post` field of `Xf`. A group takes one post; nest groups to chain two. Lengths and positions are in stage px, in the group's own coordinates. Most filters return an empty `Post` when their main argument is close to zero, and a group with an empty post is drawn as if it had none. So `post = fx.rgb_split(12 * k)` can stay in the code and costs nothing on the frames where `k` is 0. `duotone`, `scanlines` and `stretch` have no such argument and always run. ## Splitting and breaking ```odin rgb_split :: proc(px: f32, angle: f32 = 0) -> Post glitch :: proc(amount: f32, seed: f32 = 0) -> Post ``` `rgb_split` is chromatic aberration: red is read `px` to one side and blue `px` to the other, along `angle` in degrees (0 is horizontal, 90 vertical). Green stays where it is. A pixel or two reads as a lens, ten or more as a hit. ```odin post_rgb_split :: proc(s: fx.Shot) { fx.backdrop(.Night) px := knob("px", 12, 0, 40) angle := 90 * s.lt // one turn per loop if fx.group({post = fx.rgb_split(px, angle)}) { fx.caption("Aberration", {960, 440}, 250, fx.theme.nt, {0.5, 0.5}) fx.hline(330, 640, 1260, fx.theme.nt, 6) fx.circle({960, 780}, 60, fx.theme.na) } } ``` `glitch` cuts the picture into 6 to 23 horizontal bands, shoves some of them sideways and splits the colors of all of it, and rolls new dice 24 times a second. `amount` runs from 0 to 1: at 1 about 60% of the bands move, by as much as 6% of the stage width, and red and blue are each pulled up to 34 px to their side. It reads the frame's time itself, so there is nothing to animate; `seed` gives a second glitch on the same frame a different pattern. ```odin post_glitch :: proc(s: fx.Shot) { amount := knob("amount", 0.5, 0, 1) if fx.group({post = fx.glitch(amount)}) { fx.backdrop(.Night) fx.rect({0, 300, 1920, 8}, fx.theme.na) fx.caption("NO SIGNAL", {960, 500}, 240, fx.theme.nt, {0.5, 0.5}) fx.label("CH 03 · 00:14:27", {960, 700}, fx.mono(56), fx.theme.nm, {0.5, 0.5}) fx.rect({0, 790, 1920, 8}, fx.theme.na) } } ``` ## Blur and pixels ```odin zoom_blur :: proc(center: Vec2, amount: f32) -> Post pixelate :: proc(px: f32) -> Post ``` `zoom_blur` smears every pixel along the line toward `center`: the rush of a fast zoom. `amount` is the part of that line it smears over, 0 to 1, and 0.15 is already a lot. Pair it with a scale that settles at the same time. ```odin post_zoom_blur :: proc(s: fx.Shot) { rush := 1 - fx.ep(s.lt, 0.2, 1.6, fx.ease_out5) // 1 at the start, settling to 0 amount := knob("amount", 0.2, 0, 0.4) * rush c := fx.Vec2{960, 540} if fx.group({s = 1 + 0.5 * rush, origin = c, post = fx.zoom_blur(c, amount)}) { fx.backdrop(.Night) for i in 0 ..< 60 { p := fx.Vec2{fx.hash01(1, i) * 1920, fx.hash01(2, i) * 1080} fx.circle(p, 4 + 10 * fx.hash01(3, i), i % 5 == 0 ? fx.theme.na : fx.theme.ns) } fx.caption("Arrive", c, 280, fx.theme.nt, {0.5, 0.5}) } } ``` `pixelate` turns the group into squares `px` wide, each in the color at its middle. Below 1.5 it does nothing. ```odin post_pixelate :: proc(s: fx.Shot) { px := knob("px", 28, 1, 96) if fx.group({post = fx.pixelate(px)}) { fx.backdrop(.Night) a := s.p * math.TAU c := fx.Vec2{960 + 520 * math.cos(a), 540 + 230 * math.sin(a)} fx.circle_paint(c, 190, fx.radial(c - {60, 60}, 260, fx.theme.nt, fx.theme.na, fx.theme.night)) fx.caption("8-bit", {960, 540}, 300, fx.theme.nt, {0.5, 0.5}) } } ``` ## Tone and print ```odin duotone :: proc(dark, light: Color) -> Post scanlines :: proc(px: f32 = 4, amount: f32 = 0.25) -> Post halftone :: proc(cell: f32, angle: f32 = 45, amount: f32 = 1) -> Post dither :: proc(px: f32 = 2, dark: Color = 0xff000000, light: Color = 0xffffffff, levels: f32 = 2, amount: f32 = 1) -> Post ``` `duotone` replaces color by brightness: black becomes `dark`, white becomes `light`, everything else a mix of the two. Transparency is kept. It is the quickest way to make footage or a busy picture belong to a palette. ```odin post_duotone :: proc(s: fx.Shot) { picture :: proc() { fx.rect_paint(fx.stage(), fx.linear({0, 0}, {0, 1080}, 0xff16254a, 0xff8a3b5e, 0xfff09a4a, 0xffffe2a0)) fx.circle_paint({960, 700}, 230, fx.radial({960, 700}, 230, 0xfffffbe6, 0xffffd978)) fx.circle({420, 1560}, 760, 0xff203a3a) fx.circle({1420, 1700}, 900, 0xff0f2226) fx.caption("Two inks", {960, 300}, 200, 0xfffff6e0, {0.5, 0.5}) } picture() x := 960 - 760 * math.cos(s.p * math.TAU) // the border wipes across and back if fx.group({clip = fx.Rect{x, 0, 1920 - x, 1080}, post = fx.duotone(fx.theme.night, fx.theme.na)}) { picture() } fx.vline(x - 2, 0, 1080, fx.theme.nt, 4) } ``` `scanlines` darkens the picture in horizontal lines `px` apart, by `amount` (0 to 1) at the darkest row. The default of 4 px suits a full-size render; the demo uses wider lines so they survive the small player. ```odin post_scanlines :: proc(s: fx.Shot) { px := knob("px", 12, 2, 40) amount := knob("amount", 0.5, 0, 1) if fx.group({post = fx.scanlines(px, amount)}) { fx.rect(fx.stage(), 0xff0b1a12) fx.rrect({160, 150, 1600, 780}, 40, 0xff12301f) green: fx.Color = 0xff7dffb0 fx.text(fx.typed("> load \"film\"", s.lt, 0.3, 1.4), 260, 250, fx.mono(96, 500), green) fx.text(fx.typed("3600 frames ready", s.lt, 1.7, 2.6), 260, 420, fx.mono(96, 500), green) if math.mod(s.lt, 0.5) < 0.25 do fx.rect({260, 620, 58, 104}, green) } } ``` `halftone` is print: a grid of dots `cell` px apart, turned by `angle` degrees. Each dot is as big as the picture is bright under it and takes the picture's color there at full strength, on black. `amount` (0 to 1) blends the dots in from the untouched picture, which is how you fade into the effect. ```odin post_halftone :: proc(s: fx.Shot) { cell := knob("cell", 26, 4, 80) angle := knob("angle", 45, 0, 90) if fx.group({post = fx.halftone(cell, angle)}) { fx.rect_paint(fx.stage(), fx.linear({0, 0}, {1920, 1080}, 0xff3a1410, fx.theme.na, 0xffffe2a0)) c := fx.Vec2{560 + 800 * s.p, 560} fx.circle_paint(c, 300, fx.radial(c - {110, 120}, 520, 0xffffffff, 0xff4f8fd0, 0xff0a1020)) fx.caption("PRINT", {1380, 800}, 300, 0xffffffff, {0.5, 0.5}) } } ``` `dither` is an ordered dither (an 8×8 Bayer pattern) in pixels `px` wide. The brightness is cut down to `levels` shades between `dark` and `light`; 2 is one bit, the look of an early Macintosh. `amount` blends it in like `halftone`'s. ```odin post_dither :: proc(s: fx.Shot) { px := knob("px", 6, 1, 16) levels := knob("levels", 2, 2, 6) if fx.group({post = fx.dither(px, fx.theme.night, fx.theme.nt, levels)}) { fx.rect_paint(fx.stage(), fx.linear({0, 0}, {1920, 0}, 0xff000000, 0xffffffff)) c := fx.Vec2{960 + 520 * math.sin(s.p * math.TAU), 470} fx.circle_paint(c, 300, fx.radial(c - {110, 120}, 520, 0xffffffff, 0xff777777, 0xff000000)) fx.rect({0, 800, 1920, 280}, 0xff000000) fx.caption("1-bit", {960, 940}, 190, 0xffffffff, {0.5, 0.5}) } } ``` ## Lenses and waves ```odin lens :: proc(distort: f32 = 0.06, chroma: f32 = 6, vignette: f32 = 0) -> Post shockwave :: proc(center: Vec2, radius, width, strength: f32) -> Post kaleido :: proc(center: Vec2, n: f32 = 6, angle: f32 = 0, zoom: f32 = 1) -> Post warp :: proc(amount: f32, scale: f32 = 240, speed: f32 = 0.4, seed: f32 = 0) -> Post stretch :: proc(edge: f32, horizontal := true, forward := true) -> Post ``` `lens` is a whole camera lens in one filter. `distort` is barrel distortion: above 0 the middle bulges toward you while the corners stay put, below 0 it pinches. `chroma` pulls the colors apart toward the edges, by about that many px in the corners and not at all in the middle. `vignette` (0 to 1) darkens the edges. It is centered on the stage, so it belongs on a group that covers the stage, typically the film's `master` group (see [scenes](/docs/scenes/)). Keep `distort` small: the fable film runs at 0.016. ```odin post_lens :: proc(s: fx.Shot) { distort := knob("distort", 0.08, -0.2, 0.2) chroma := knob("chroma", 12, 0, 40) vignette := knob("vignette", 0.6, 0, 1) if fx.group({post = fx.lens(distort, chroma, vignette)}) { fx.backdrop(.Night, offset = {60 * s.lt, 0}) // the grid drifts, so the bend shows fx.border({120, 90, 1680, 900}, fx.theme.ns, 4, 40) fx.caption("Through glass", {960, 480}, 210, fx.theme.nt, {0.5, 0.5}) fx.label("fx.lens(distort, chroma, vignette)", {960, 680}, fx.mono(40), fx.theme.nm, {0.5, 0.5}) } } ``` `shockwave` is a ring-shaped ripple around `center`. `radius` is where the ring is, `width` how thick, `strength` how many px it pushes the picture outward at its crest (negative pulls inward). The crest splits colors a little and brightens. Animate `radius` outward and let `strength` fall to 0 on the way. ```odin post_shockwave :: proc(s: fx.Shot) { strength := knob("strength", 70, -120, 120) width := knob("width", 130, 20, 400) c := fx.Vec2{960, 540} p := fx.prog(s.lt, 0.3, 2.7) // the ring runs outward and loses its force on the way if fx.group({post = fx.shockwave(c, 1300 * p, width, strength * (1 - p))}) { fx.backdrop(.Night) for i in 0 ..< 7 { fx.label("impact impact impact impact impact", {960, 150 + f32(i) * 130}, fx.sans(90, 600), i == 3 ? fx.theme.nt : fx.theme.ns, {0.5, 0.5}) } } } ``` `kaleido` folds the group into mirrored wedges around `center`. `n` is how many times the pattern repeats around the circle; `angle` (degrees) turns it, `zoom` magnifies it. What would be read from outside the stage is folded back in, so the wedges are always full. Anything drifting through the picture turns into a mandala. ```odin post_kaleido :: proc(s: fx.Shot) { n := math.round(knob("n", 6, 1, 12)) if fx.group({post = fx.kaleido({960, 540}, n, 45 * s.lt)}) { fx.rect(fx.stage(), fx.theme.night) // rows of pills drifting to the right: two columns per loop for i in 0 ..< 24 { col, row := f32(i % 6), f32(i / 6) x := math.mod(col * 400 + row * 130 + 100 * s.lt, 2400) - 240 c := i % 2 == 0 ? fx.theme.na : (row == 1 ? fx.theme.ns : fx.theme.nt) fx.rrect({x, 100 + row * 270, 240, 70}, 35, c) fx.ring({x + 120, 135 + row * 270}, 100, fx.alpha(c, 0.5), 6) } } } ``` `warp` pushes pixels around with flowing noise: heat haze at 5 px, liquid at 40, a melting picture beyond that. `amount` is the push in px, `scale` the size of the swirls in px, `speed` how fast they flow. Like `glitch` it reads the frame's time, and `seed` picks a different flow. ```odin post_warp :: proc(s: fx.Shot) { amount := knob("amount", 50, 0, 200) scale := knob("scale", 240, 40, 800) if fx.group({post = fx.warp(amount, scale)}) { fx.backdrop(.Night) for i in 0 ..< 9 do fx.hline(260, 220 + f32(i) * 80, 1400, i == 4 ? fx.theme.na : fx.theme.nb, 6) fx.caption("Heat haze", {960, 540}, 250, fx.theme.nt, {0.5, 0.5}) } } ``` `stretch` repeats one column of pixels: everything right of `x = edge` becomes the column at the edge, smeared across. With `forward = false` it is everything left of it; with `horizontal = false` the edge is a `y` and rows are smeared down (or, not `forward`, up). ```odin post_stretch :: proc(s: fx.Shot) { // the edge sweeps in from the right, holds, and goes back k := fx.win(s.lt, 0.4, 4.6, 1.4, 1.4) edge := fx.lerp(1920, 850, k) if fx.group({post = fx.stretch(edge)}) { fx.backdrop(.Night) fx.rect({0, 250, 1920, 12}, fx.theme.na) fx.caption("Stretched", {960, 500}, 280, fx.theme.nt, {0.5, 0.5}) fx.label("everything right of the edge is one column of pixels", {960, 730}, fx.sans(48), fx.theme.nm, {0.5, 0.5}) fx.rect({0, 840, 1920, 12}, fx.theme.ns) } fx.vline(edge, 0, 1080, fx.alpha(fx.theme.nt, 0.3), 2) } ``` ## Your own filter ```odin Post :: struct { sksl: cstring, u: [16]f32, // uniforms in declaration order n: int, radius: f32, // how far it samples away from a pixel, in px } post :: proc(sksl: cstring, radius: f32, uniforms: ..f32) -> Post ``` Every filter above is a few lines of SkSL (Skia's shading language, close to GLSL) handed to `post`, and yours can be too. The contract: ```glsl uniform shader src; // the group's pixels; must have this name uniform float amp; // your uniforms, floats only uniform float2 center; // a float2 takes two of the numbers you pass, a float3 three half4 main(float2 p) { // p: this pixel, in stage px return src.eval(p + float2(amp, 0)); // read the group anywhere; colors are premultiplied } ``` - The numbers after `radius` fill the uniforms in the order they are declared. There is room for 16 floats; more are dropped, and uniforms you do not fill are 0. - `radius` is the furthest the shader reads from its own pixel, in px. Skia uses it to keep enough of the picture around the area it is drawing; 0 is right for filters that only read `src.eval(p)`. - Nothing is passed for you. If the filter moves, pass `s.t` as a uniform; if it needs the stage size, pass that. - A shader that does not compile prints Skia's error and the group is drawn unfiltered. `unpack(color)` turns a `Color` into an `RGBA` of four floats in 0..1, which is how colors get into uniforms. The built-in sources are public constants (`fx.RGB_SPLIT`, `fx.LENS`, …) and `fx/post.odin` is short: read it for more examples. ```odin post_custom :: proc(s: fx.Shot) { // every row is read from a little to the left or right of where it is WAVE :: ` uniform shader src; uniform float amp; uniform float len; uniform float t; half4 main(float2 p) { return src.eval(p + float2(amp * sin(p.y / len + t), 0)); }` amp := knob("amp", 40, 0, 160) len := knob("len", 60, 10, 300) // radius = amp: the furthest the shader reads from its own pixel if fx.group({post = fx.post(WAVE, amp, amp, len, s.p * math.TAU)}) { fx.backdrop(.Night) fx.caption("Your own", {960, 420}, 260, fx.theme.nt, {0.5, 0.5}) fx.rrect({460, 640, 1000, 120}, 60, fx.theme.na) } } ``` ## Glow ```odin Glow :: struct { radius: f32, // blur sigma in px amount: f32, // 0 = off; 1 adds the blurred highlights at full strength threshold: f32, // 0..1: only what is brighter glows streak: f32, // horizontal sigma of the streak pass, 0 = none streak_amount: f32, // of amount, default 0.6 } glow :: proc(radius: f32 = 24, amount: f32 = 0.8, threshold: f32 = 0.5, streak: f32 = 0) -> Glow ``` Glow is bloom, and it has its own field on `Xf`: `fx.group({glow = fx.glow()})`. What is brighter than `threshold` is cut out, blurred by `radius` and added back on top, `amount` strong. Each color channel is judged on its own, so a saturated red glows red. It works best on a group that paints its own background, because the glow needs something to land on. ```odin post_glow :: proc(s: fx.Shot) { radius := knob("radius", 30, 0, 120) amount := knob("amount", 1, 0, 3) threshold := knob("threshold", 0.5, 0, 0.95) if fx.group({glow = fx.glow(radius, amount, threshold)}) { fx.backdrop(.Night) // inside: the glow has a background to land on fx.caption("Bloom", {960, 400}, 300, fx.theme.nt, {0.5, 0.5}) // from dim to bright: only what is above the threshold glows for i in 0 ..< 8 { fx.rrect({300 + f32(i) * 170, 690, 130, 130}, 24, fx.mix(fx.theme.night, fx.theme.na, f32(i + 1) / 8)) } x := 300 + 1320 * fx.ep(s.lt, 0.3, 3.4, fx.ease_in_out) fx.circle({x, 900}, 14, 0xffffffff) } } ``` `streak` adds a second pass of the same highlights, blurred `streak` px wide and hardly at all in height: the horizontal flare of an anamorphic lens. Its strength is `streak_amount` of `amount`, 0.6 unless you say otherwise. `glow()` has no argument for that, so write the struct when you need it: ```odin glow = {radius = 20, amount = 0.45, threshold = 0.58, streak = 110, streak_amount = 0.4} ``` > **Note:** A struct literal starts from zeros, not from `glow()`'s defaults: leave `threshold` out of it and everything glows, not only the highlights. ```odin post_streak :: proc(s: fx.Shot) { streak := knob("streak", 140, 0, 400) if fx.group({glow = {radius = 16, amount = 0.9, threshold = 0.6, streak = streak, streak_amount = 0.8}}) { fx.rect(fx.stage(), fx.theme.night) for i in 0 ..< 14 { x := math.mod(fx.hash01(5, i) * 1920 + (40 + 80 * fx.hash01(6, i)) * s.lt * 1920 / 400, 1920) fx.circle({x, 140 + fx.hash01(7, i) * 800}, 5 + 9 * fx.hash01(8, i), i % 4 == 0 ? fx.theme.na : 0xffffffff) } fx.caption("Anamorphic", {960, 540}, 220, fx.theme.nt, {0.5, 0.5}) } } ``` ## Order Inside one group the steps always run in the same order: the group's `blur`, then its `post`, then its `glow`, then its grade (`gray`, `bright`, `contrast`, `sat`, `tint`, `invert`), and last its opacity and blend onto what is below. So a post sees the picture before the grade of its own group. When the filter should work on the graded picture (a dither after a gray grade, a duotone of an inverted image), put the grade on an inner group and the post on a group around it: ```odin if fx.group({post = fx.dither(3)}) { if fx.group({gray = 1, contrast = 0.4}) { fx.footage("assets/clip.mp4", s.lt, fx.stage()) } } ``` Both halves below invert and duotone the same picture. On the left one group does both, so the invert comes last and turns the duotone's colors over. On the right the invert is inside. ```odin post_order :: proc(s: fx.Shot) { picture :: proc(x: f32, t: f32) { fx.rect_paint({x, 0, 960, 1080}, fx.linear({x, 0}, {x, 1080}, 0xff101820, 0xff9aa4b0)) c := fx.Vec2{x + 480 + 160 * math.sin(t * math.TAU / 4), 430} fx.circle_paint(c, 230, fx.radial(c - {80, 90}, 400, 0xffffffff, 0xff8c8c8c, 0xff101010)) } duo := fx.duotone(fx.theme.night, fx.theme.na) // one group: the duotone runs first, then the invert turns its colors over if fx.group({invert = 1, post = duo, clip = fx.Rect{0, 0, 960, 1080}}) do picture(0, s.lt) // two groups: the inner one inverts the picture, the outer one colors the result if fx.group({post = duo, clip = fx.Rect{960, 0, 960, 1080}}) { if fx.group({invert = 1}) do picture(960, s.lt) } fx.rect({0, 860, 1920, 220}, fx.theme.night) fx.label("{invert, post}", {480, 970}, fx.mono(44), fx.theme.nt, {0.5, 0.5}) fx.label("{post} around {invert}", {1440, 970}, fx.mono(44), fx.theme.nt, {0.5, 0.5}) } ``` The same goes for two filters: the inner group's runs first. ## What it costs Where frames are drawn on the GPU (the editor's preview, and this page) none of this is worth thinking about. A render draws on the CPU, and there a post filter is one full pass over the group's pixels for every time it reads `src`. On one thread at 1080p a filter that reads each pixel three times takes about 0.05 s a frame, against roughly 2 ms for a frame of ordinary text and shapes. Glow is made of Skia's own blur and costs about 0.02 s. | Reads per pixel | Filters | | --- | --- | | 1 | `pixelate`, `duotone`, `scanlines`, `kaleido`, `warp`, `stretch`, `halftone` and `dither` at `amount = 1` | | 2 | `halftone` and `dither` while blending in | | 3 | `rgb_split`, `glitch`, `lens`, `shockwave` | | 12 | `zoom_blur` | Keep filters to the frames that need them (let the amount fall to 0 and the filter is gone), and put them on the smallest group that will do. A film-wide `lens` and `glow` on the master group is fine: the fable film has them on nearly every one of its 3,600 frames. ## Reference | Procedure | Returns | | --- | --- | | `rgb_split(px, angle)` | Red and blue pulled `px` apart along `angle` degrees. | | `glitch(amount, seed)` | Shoved bands and split colors, re-rolled 24 times a second. `amount` 0..1. | | `zoom_blur(center, amount)` | Radial blur toward `center`. `amount` 0..1 of the way there. | | `pixelate(px)` | Square pixels `px` wide. | | `duotone(dark, light)` | Brightness mapped onto a gradient from `dark` to `light`. | | `scanlines(px, amount)` | Horizontal lines every `px`, darkening by `amount`. | | `halftone(cell, angle, amount)` | Dots `cell` apart on a grid turned by `angle` degrees, on black. | | `dither(px, dark, light, levels, amount)` | 8×8 ordered dither in `px` pixels, `levels` shades. | | `lens(distort, chroma, vignette)` | Barrel distortion, color fringes of `chroma` px, darkened edges. | | `shockwave(center, radius, width, strength)` | A ring pushing pixels outward by `strength` px. | | `kaleido(center, n, angle, zoom)` | `n` mirrored repeats around `center`. | | `warp(amount, scale, speed, seed)` | Flowing noise displacement of `amount` px. | | `stretch(edge, horizontal, forward)` | The row or column at `edge` smeared over one side. | | `post(sksl, radius, uniforms…)` | A `Post` from your own SkSL. | | `glow(radius, amount, threshold, streak)` | A `Glow` for `Xf.glow`. | | `unpack(color)` | The color as `RGBA{r, g, b, a}` in 0..1, for uniforms. | | `grade_matrix(xf)` | The 4×5 color matrix of an `Xf`'s grade, and whether it changes anything. Groups call it for you. | --- # Shaders Some pictures are not made of shapes: a field of drifting smoke, a glowing body, a tunnel. For those you write a shader, a small program in SkSL (Skia's shading language, close to GLSL) that is run once for every pixel and returns that pixel's color. `fx` draws a shader into a rect like any other shape, and ships three finished ones. > **Note:** On this page the shaders run on your GPU and cost next to nothing. A render draws them on the CPU, where they are the most expensive thing in the library. Read [drawing small](#drawing-small) before you fill a film with them. ## Your own shader ```odin shader :: proc(sksl: cstring, r: Rect, uniforms: ..f32) ``` `shader` fills `r` with what the SkSL program returns. The numbers after the rect fill the program's uniforms in the order they are declared: a `float` takes one, a `float2` two, a `float3` three, a `float4` four. Uniforms you do not fill are 0. Declare float types only. ```glsl uniform float t; // seconds uniform float4 rect; // x, y, w, h of the rect being filled uniform float3 color; // r, g, b in 0..1 half4 main(float2 p) { // p: this pixel float2 u = (p - rect.xy - 0.5 * rect.zw) / rect.w; // centered; 1 = the rect's height float a = smoothstep(0.5, 0.2, length(u)); return half4(half3(color) * a, a); // premultiplied } ``` Three things to know: - **Coordinates.** `p` is in the coordinates you are drawing in (stage px, unless a group has moved you), not relative to the rect. Nothing is passed for you, so the shaders in `fx` all take the rect as a `float4` and start by turning `p` into a centered position measured in rect heights, as above. Do the same and the picture keeps its proportions in any rect. - **Time.** There is no clock in a shader. Pass `s.t` (or `s.lt`) as a uniform and compute everything from it, like the rest of a scene. - **Color.** `main` returns premultiplied color: multiply the color by its alpha. Return alpha 1 for an opaque picture, less and whatever is below shows through. `unpack(color)` gives you a `Color` as four floats in 0..1 for the uniforms. If the program does not compile, Skia's error is printed and nothing is drawn. SkSL is stricter than desktop GLSL in a few places: loops need a fixed count, and the types are spelled `float2`, `float3`, `half4`. ```odin shade_custom :: proc(s: fx.Shot) { RINGS :: ` uniform float t; uniform float4 rect; // x, y, w, h of the rect being filled uniform float3 color; uniform float count; half4 main(float2 p) { // p is in stage px; u is centered on the rect, one unit = its height float2 u = (p - rect.xy - 0.5 * rect.zw) / rect.w; float d = length(u); float wave = 0.5 + 0.5 * sin(6.2831853 * (d * count - t)); float a = wave * smoothstep(0.75, 0.1, d); return half4(half3(color) * a, a); // premultiplied: transparent where a is 0 }` fx.backdrop(.Night) r := fx.stage() c := fx.unpack(fx.theme.na) // the floats fill the uniforms in the order they are declared fx.shader(RINGS, r, s.lt, r.x, r.y, r.w, r.h, c.r, c.g, c.b, knob("count", 6, 1, 24)) fx.caption("fx.shader", {960, 540}, 200, fx.theme.nt, {0.5, 0.5}) } ``` A shader's picture is ordinary drawing. It can sit inside a group that fades or scales it, under text, or under a [post filter](/docs/post/): the fable film folds a `nebula` through `kaleido` for its title. ## Drawing small ```odin shader_scaled :: proc(sksl: cstring, r: Rect, res: f32, uniforms: ..f32) ``` SkSL on the CPU is slow. One thread needs about 2 s for a single 1080p frame of warped noise or a raymarched body, a thousand times what a frame of text and shapes takes. But pictures like that are smooth, and a smooth picture does not need every pixel. `shader_scaled` is `shader` drawn into a smaller image, `res` (0.05 to 1) of the rect's size in each direction, and scaled up to fill the rect. A third of the resolution is a ninth of the pixels: at a third or half, the same pictures cost 0.1 to 0.5 s a frame. The shader notices nothing, it still sees stage coordinates. Use it for anything soft (noise, gradients, glows), and plain `shader` for anything with hard edges or fine lines, which scaling would blur. Drag `res` down to see where this picture starts to fall apart: ```odin shade_scaled :: proc(s: fx.Shot) { SMOKE :: ` uniform float t; uniform float4 rect; uniform float3 dark; uniform float3 light; ` + fx.NOISE_SKSL + ` half4 main(float2 p) { float2 u = (p - rect.xy) / rect.w * 3; float f = fbm(u + 2 * fbm(u * 0.8 + t * 0.12)); return half4(half3(mix(dark, light, smoothstep(0.4, 0.9, f))), 1); }` res := knob("res", 0.25, 0.05, 1) r := fx.stage() a, b := fx.unpack(fx.theme.night), fx.unpack(fx.theme.na) if fx.group({o = fx.fade(s)}) { fx.shader_scaled(SMOKE, r, res, s.lt, r.x, r.y, r.w, r.h, a.r, a.g, a.b, b.r, b.g, b.b) fx.label(fmt.tprintf("drawn at %.0f × %.0f", 1920 * res, 1080 * res), {960, 540}, fx.mono(72, 500), fx.theme.nt, {0.5, 0.5}) } } ``` ## Noise for your shaders ```odin NOISE_SKSL :: `…` // float h12(float2 p); float vn(float2 p); float fbm(float2 p); ``` `NOISE_SKSL` is a piece of SkSL to put in front of your own `main` (constant strings join with `+`, as in the demo above). It defines three functions, all returning 0..1: | Function | Returns | | --- | --- | | `h12(p)` | A hash: an unrelated value for every `p`. | | `vn(p)` | Value noise: smooth, one bump per unit. | | `fbm(p)` | Four layers of `vn` at rising frequency: clouds. | Feeding `fbm` into its own input (`fbm(u + fbm(u))`) is what makes smoke out of clouds. ## Nebula ```odin Nebula :: struct { deep, mid, hot: Color, // background, the filaments, their brightest cores scale: f32, // size of the structures, 0 = 1 (bigger = larger clouds) detail: f32, // 0..1 how wispy, 0 = 0.5 level: f32, // overall brightness, 0 = 1 flow: Vec2, // drift of the whole field, stage heights per second seed: f32, res: f32, // render resolution, 0 = 1/3 } nebula :: proc(r: Rect, t: f32, n: Nebula) ``` Slow filaments of warped noise: a sky, a mind, a field to put things in. `deep` is the background and the picture is opaque. `mid` and `hot` are light added on top of it, so dim them (mix them toward black) for a background that stays behind its text. The field evolves slowly with `t` on its own; `flow` adds a drift of the whole thing, and `seed` gives you a different sky. It is drawn through `shader_scaled` at a third of the resolution unless `res` says otherwise. ```odin shade_nebula :: proc(s: fx.Shot) { if fx.group({o = fx.fade(s, 0.8, 0.8)}) { fx.nebula(fx.stage(), s.lt, { deep = fx.theme.night, mid = fx.theme.na, hot = fx.theme.nt, scale = knob("scale", 1, 0.3, 3), detail = knob("detail", 0.5, 0.05, 1), level = knob("level", 1, 0.2, 2.5), flow = {0.03, -0.01}, }) fx.caption("A field to put things in", {960, 540}, 120, fx.theme.nt, {0.5, 0.5}) } } ``` ## Orb ```odin Orb :: struct { radius: f32, // of the body, in px morph: f32, // 0 = a sphere … 1 = restless spin: f32, // turns of its surface pattern, in radians a, b, c: Color, // the film's colors across the fresnel glow: f32, // halo strength, 0 = 0.6 res: f32, // render resolution, 0 = 0.5 } orb :: proc(r: Rect, t: f32, o: Orb) ``` A raymarched body with an iridescent skin and a halo, centered in `r`. Make `r` a square about three times the radius wide (more if the halo should reach further); around the body the picture is transparent, and the halo fades out before the rect's edge. `a` is the color you see where the surface faces you, `b` and `c` take over toward the rim. `morph` above 1 is allowed and wilder. It is the costliest picture here, a full raymarch per pixel, and is drawn at half resolution by default. Keep its rect no bigger than it needs to be. ```odin shade_orb :: proc(s: fx.Shot) { fx.backdrop(.Night) if fx.group({o = fx.fade(s)}) { // a square about three radii wide, the body in its middle fx.orb({420, 0, 1080, 1080}, s.lt, { radius = 330, morph = knob("morph", 0.7, 0, 1.5), spin = s.lt * 0.7, a = fx.theme.na, b = 0xff9a86ff, c = 0xff62e6d2, glow = knob("glow", 0.6, 0.05, 2), }) } } ``` ## Tunnel ```odin tunnel :: proc(r: Rect, t: f32, color, accent: Color, speed: f32 = 1, twist: f32 = 0.15, ribs: f32 = 12, res: f32 = 0.5) ``` An endless tunnel of rings and ribs flying toward the viewer, opaque, on black. The lines are in `color`; `accent` lights up a flickering panel here and there and the glow at the far end. `speed` is in rings per second, `twist` in turns along the tunnel's length (0 is straight), `ribs` is how many lines run along it. ```odin shade_tunnel :: proc(s: fx.Shot) { speed := knob("speed", 1, 0, 4) twist := knob("twist", 0.15, -1, 1) ribs := knob("ribs", 12, 3, 32) if fx.group({o = fx.fade(s)}) { fx.tunnel(fx.stage(), s.lt, fx.theme.na, fx.theme.nt, speed, twist, ribs) } } ``` ## Reference | Procedure | Draws | | --- | --- | | `shader(sksl, r, uniforms…)` | An SkSL program into `r`, at full resolution. | | `shader_scaled(sksl, r, res, uniforms…)` | The same at `res` of the resolution, scaled up. | | `nebula(r, t, n)` | Filaments of warped noise, opaque. `n` is a `Nebula`. | | `orb(r, t, o)` | A raymarched iridescent body with a halo, transparent around it. `o` is an `Orb`. | | `tunnel(r, t, color, accent, speed, twist, ribs, res)` | A tunnel flying toward the viewer, on black. | | `NOISE_SKSL` | SkSL source of `h12`, `vn` and `fbm`, to prepend to your own. | | `NEBULA`, `ORB`, `TUNNEL` | The SkSL sources of the three pictures, to read or to start from. | --- # 3D space `fx` draws in two dimensions, and this part of it stays that way: there is no mesh, no lighting and no depth buffer. What it gives you is a camera that turns a point in space into a position on the stage and a size, and you draw there with the tools you already have. That is enough for point clouds, constellations, orbits, paths through space and out-of-focus lights, which is most of what motion graphics asks of 3D. ```odin cam := fx.Cam{yaw = 20 * s.t, pitch = -12, dist = 9} if q, ok := fx.project(cam, {1, 0, 0}); ok do fx.circle(q.p, 0.05 * q.s, fx.theme.na) ``` ## The camera ```odin Vec3 :: [3]f32 Cam :: struct { yaw, pitch: f32, dist: f32, target: Vec3, fov: f32, // vertical field of view in degrees, 0 = 50 center: Vec2, // where target lands on the stage, {0, 0} = its middle roll: f32, // degrees } ``` A `Cam` orbits a point. It always looks at `target` from `dist` world units away; `yaw` and `pitch` (degrees) say from where. It is a plain value: build it from the time at the top of the scene and pass it to everything that draws. | Field | Meaning | | --- | --- | | `yaw` | Turn around the vertical axis. At 0 the camera looks along +z with +x to its right. Raising it carries the camera to the left, so the right side of the scene swings away from you. | | `pitch` | Tilt. A negative pitch lifts the camera and looks down on the target, a positive one drops it and looks up. | | `dist` | Distance from the target, in world units. | | `target` | The point in the world the camera looks at. | | `fov` | Vertical field of view in degrees; 0 means 50. Small is a long lens (flat), large a wide one. | | `center` | Where `target` lands on the stage in px; `{0, 0}` means the middle. | | `roll` | Turns the picture, counterclockwise for positive degrees. | World units are whatever you want them to be, y points up, and nothing has a size until the camera gives it one: with the default lens, one world unit at 5 units' distance is about 230 px. ```odin space_cam :: proc(s: fx.Shot) { fx.backdrop(.Night, grid = false) cam := fx.Cam{yaw = knob("yaw", 25, -180, 180), pitch = knob("pitch", -25, -89, 89), dist = knob("dist", 11, 5, 30)} for i in -4 ..= 4 { // a floor at y = 0 fx.line3(cam, {f32(i), 0, -4}, {f32(i), 0, 4}, fx.stroke(fx.theme.ns, 2)) fx.line3(cam, {-4, 0, f32(i)}, {4, 0, f32(i)}, fx.stroke(fx.theme.ns, 2)) } axes := [?]struct { name: string, p: fx.Vec3, }{{"x", {3, 0, 0}}, {"y", {0, 3, 0}}, {"z", {0, 0, 3}}} for a in axes { fx.line3(cam, {}, a.p, fx.stroke(fx.theme.nt, 6)) if q, ok := fx.project(cam, a.p); ok do fx.label(a.name, q.p + {0, -44}, fx.mono(52, 500), fx.theme.nt, {0.5, 0.5}) } // something going round on the floor a := s.p * math.TAU if q, ok := fx.project(cam, {2 * math.cos(a), 0, 2 * math.sin(a)}); ok do fx.circle(q.p, 0.2 * q.s, fx.theme.na) } ``` ## Projecting points ```odin Projected :: struct { p: Vec2, // stage position z: f32, // distance from the camera along its view s: f32, // stage px per world unit at that distance } project :: proc(c: Cam, p: Vec3, near: f32 = 0.05) -> (Projected, bool) line3 :: proc(c: Cam, a, b: Vec3, p: sk.Paint, near: f32 = 0.05) ``` `project` is the whole of the 3D: it answers where a world point is on the stage (`p`), how far from the camera (`z`) and how big things are there (`s`). Multiply a world size by `s` and you have px, so `fx.circle(q.p, 0.07 * q.s, c)` is a ball of radius 0.07 that shrinks with distance. The second result is false when the point is behind the camera (closer than `near`): skip it. `line3` draws a straight line between two world points and clips it at the camera. Its paint is any stroke: `fx.stroke(color, width)`, or that wrapped in `additive` or `soft` (see [drawing](/docs/draw/)). The width is in px and does not change with depth. ```odin space_project :: proc(s: fx.Shot) { fx.backdrop(.Night) cam := fx.Cam{yaw = 45 * s.lt, pitch = 22, dist = knob("dist", 5, 3, 12), fov = knob("fov", 50, 15, 110)} corner :: proc(i: int) -> fx.Vec3 { return {i & 1 == 0 ? -1 : 1, i & 2 == 0 ? -1 : 1, i & 4 == 0 ? -1 : 1} } for i in 0 ..< 8 { // an edge to each corner that differs in one coordinate for bit in ([?]int{1, 2, 4}) { if i & bit == 0 do fx.line3(cam, corner(i), corner(i | bit), fx.stroke(fx.theme.ns, 4)) } } for i in 0 ..< 8 { q, ok := fx.project(cam, corner(i)) if !ok do continue fx.circle(q.p, 0.08 * q.s, fx.theme.na) // q.s is px per world unit there: nearer is bigger fx.label(fmt.tprintf("z %.1f", q.z), q.p + {0, -0.08 * q.s - 34}, fx.mono(36), fx.theme.nt, {0.5, 0.5}) } } ``` Nothing is sorted by depth. Things appear in the order you draw them, which does not matter for lines and for light that adds up (`bokeh`, `spark`, `additive` paints). For opaque shapes that overlap, sort them by `z` yourself, far ones first. Two smaller pieces are public for when you need the numbers in between: ```odin view :: proc(c: Cam, p: Vec3) -> Vec3 // p in the camera's space: x right, y up, z away from the camera focal :: proc(c: Cam) -> f32 // stage px per world unit one unit in front of the camera ``` ## Points to draw ```odin fib_sphere :: proc(i, n: int) -> Vec3 // the i-th of n points spread evenly over the unit sphere gauss3 :: proc(seed: u32, i: int) -> Vec3 // a stable random point from a 3D gaussian (σ = 1) ``` Two ways to get many points without storing any. `fib_sphere` walks a spiral from the top of the unit sphere to the bottom and covers it evenly for any `n`; multiply the result for a bigger sphere. `gauss3` is a cloud: dense in the middle, thinning out, with nearly all points within 3 units. Like [`hash01`](/docs/anim/#random-but-the-same-every-time) it has no state, so point `i` of cloud `seed` is in the same place on every frame. ```odin space_sphere :: proc(s: fx.Shot) { fx.backdrop(.Night) n := int(knob("points", 700, 20, 2500)) cam := fx.Cam{yaw = 45 * s.lt, pitch = knob("pitch", 20, -90, 90), dist = 2.9} for i in 0 ..< n { p := fx.fib_sphere(i, n) // on the unit sphere around the origin c := i % 7 == 0 ? fx.theme.na : fx.theme.nt // focused on the near side, 1.9 away: the far side goes soft fx.bokeh(cam, p, 0.014, c, focus = 1.9, aperture = 0.8) } } ``` ## Depth of field ```odin bokeh :: proc(c: Cam, p: Vec3, r: f32, color: Color, focus: f32, aperture: f32 = 0.6, min_px: f32 = 0.6) ``` `bokeh` draws a dot of world radius `r` the way a lens would see it. At `focus` world units from the camera it is sharp. The further it is from that distance, the bigger and fainter its disc gets, the same light spread over more area, and well out of focus it gets the slightly brighter rim of a real lens. `aperture` is how fast that happens; at 0 everything is sharp. `min_px` keeps distant dots from vanishing: no dot is drawn smaller than that radius. Its light is added to what is below, so overlapping dots brighten each other and their order does not matter. Dots off the stage are skipped. `focus` is a distance like `Projected.z`. To keep the target sharp, set it to `cam.dist`; to pull focus from the front of a cloud to its back, animate it. ```odin space_bokeh :: proc(s: fx.Shot) { fx.backdrop(.Night) focus := knob("focus", 7, 3, 12) aperture := knob("aperture", 1, 0, 3) cam := fx.Cam{yaw = 30 * s.lt, pitch = 10, dist = 7} for i in 0 ..< 500 { p := fx.gauss3(11, i) * 2 // a cloud around the origin, at twice its size h := fx.hash01(12, i) c := h < 0.2 ? fx.theme.na : fx.theme.nt fx.bokeh(cam, p, 0.02 + 0.04 * h * h, fx.alpha(c, 0.8), focus, aperture) } } ``` ## Sparks and paths ```odin spark :: proc(p: Vec2, r: f32, color: Color, a: f32 = 1) spline3 :: proc(pts: []Vec3, p: f32) -> Vec3 lerp3 :: proc(a, b: Vec3, p: f32) -> Vec3 length3 :: proc(v: Vec3) -> f32 ``` `spark` is a soft point of light at a stage position (it is 2D: project first): a bright core that falls off to nothing at radius `r` px, added to what is below. `a` is its strength, 0 to 1. Two on top of each other, a wide one in a color and a small pale one, make a glowing head. `spline3` is a smooth curve through all of `pts` (a Catmull-Rom spline): `p = 0` is the first point, `p = 1` the last, and each stretch between two points takes an equal share of `p`. Draw it as short `line3` pieces, and stop at an animated `p` to make it grow. ```odin space_spline :: proc(s: fx.Shot) { fx.backdrop(.Night) cam := fx.Cam{yaw = 20 + 25 * math.sin(s.p * math.TAU), pitch = 16, dist = 6.4} pts := [?]fx.Vec3{{-3.4, -1.4, 0}, {-1.7, 1.5, 1.6}, {0, -1, -1.6}, {1.7, 1.6, 0.6}, {3.4, -1.2, -0.5}} for p in pts { if q, ok := fx.project(cam, p); ok do fx.ring(q.p, 0.1 * q.s, fx.theme.ns, 3) } // the curve so far, as short straight pieces travel := fx.ep(s.lt, 0.4, 4.6, fx.ease_in_out) o := 1 - fx.ep(s.lt, 5.3, 5.9) SEG :: 90 prev := pts[0] for i in 1 ..= SEG { u := f32(i) / SEG q := fx.spline3(pts[:], travel * u) fx.line3(cam, prev, q, fx.stroke(fx.alpha(fx.theme.na, (0.25 + 0.75 * u) * o), 3 + 6 * u)) prev = q } if head, ok := fx.project(cam, prev); ok { fx.spark(head.p, 110, fx.theme.na, 0.9 * o) fx.spark(head.p, 24, fx.theme.nt, o) } } ``` `lerp3` is `lerp` for points and `length3` the length of a vector. `Vec3` is an Odin array, so the rest of the arithmetic is built in: `a + b`, `p * 2`, `(a - b) * 0.5`. ## Reference | Procedure | Returns or draws | | --- | --- | | `project(cam, p, near)` | Where `p` is on the stage, its distance and its scale; false behind the camera. | | `view(cam, p)` | `p` in the camera's space: x right, y up, z away. | | `focal(cam)` | Stage px per world unit at distance 1. | | `line3(cam, a, b, paint, near)` | A line between two world points, clipped at the camera. | | `bokeh(cam, p, r, color, focus, aperture, min_px)` | A dot with depth of field, its light added. | | `spark(p, r, color, a)` | A soft point of light at a stage position. | | `fib_sphere(i, n)` | The `i`-th of `n` points spread evenly over the unit sphere. | | `gauss3(seed, i)` | A stable random point of a gaussian cloud. | | `spline3(pts, p)` | The point `p` (0..1) of the way along a smooth curve through `pts`. | | `lerp3(a, b, p)`, `length3(v)` | A point between two points; a vector's length. | --- # Type in motion [`text` and `label`](/docs/draw/) draw a line of text as one thing, and a group can move or fade that thing. The procedures here go one level down, to the single letter: lines whose letters arrive one after another, text that decodes itself, and the positions of the glyphs for everything else. For text that arrives word by word, each word at a time of its own, see [`kinetic`](/docs/ui/). ## Letters ```odin Letters :: struct { t0: f32, // when the first letter starts step: f32, // delay between letters dur: f32, // each letter's move, 0 = 0.5 rise: f32, // px it comes up from (negative: drops in) blur: f32, // starts this blurred scale: f32, // starts this much bigger (0.4 = 140%) spin: f32, // starts turned by this many degrees out: f32, // when letters start leaving again (0 = never), mirrored ease: Ease, random: bool, // letters start in a shuffled order } letters :: proc(s: string, p: Vec2, f: Font, c: Color, l: Letters, anchor := Vec2{0, 0}) -> Rect ``` `letters` draws one line of text like `label` does (same position, same `anchor`, and it returns the line's rect), except that every letter makes its own entrance. The `Letters` struct says when and how. The when is in video time, in seconds: the first letter starts at `t0`, each next one `step` later, and each takes `dur` to arrive. Inside a scene that is `t0 = s.start + 0.4`, not `0.4`. `letters` reads the frame's time itself, so there is no time argument. ```odin type_letters :: proc(s: fx.Shot) { fx.backdrop(.Night) l := fx.Letters { t0 = s.start + 0.4, // video time, like everything in a scene step = knob("step", 0.04, 0, 0.15), dur = 0.7, rise = knob("rise", 60, -200, 200), blur = knob("blur", 14, 0, 40), out = s.start + 3.6, } fx.letters("Letter by letter", {960, 540}, fx.sans(210, 600, -0.03), fx.theme.nt, l, {0.5, 0.5}) } ``` The how is where each letter starts from. Everything you set is combined, and every letter fades in as it comes: | Field | The letter starts | | --- | --- | | `rise` | That many px below its place (negative: above, so it drops in). | | `blur` | Blurred by that sigma in px, sharpening as it arrives. | | `scale` | That much bigger: 0.4 is 140% of its size. Negative starts smaller. | | `spin` | Turned by that many degrees. | | `random` | Not a start state: the letters come in a random order (some of them together) instead of left to right. The order is the same on every frame and in every render. | `ease` shapes the move and is `ease_out5` unless you set it. Use `ease_back` for letters that overshoot. ```odin type_options :: proc(s: fx.Shot) { fx.backdrop(.Night) rows := [?]struct { name: string, l: fx.Letters, } { {"rise = 80", {rise = 80}}, {"rise = -80", {rise = -80}}, {"blur = 24", {blur = 24}}, {"scale = 1.2", {scale = 1.2}}, {"spin = 90, rise = 40", {spin = 90, rise = 40}}, {"random = true, blur = 12", {random = true, blur = 12}}, } for row, i in rows { y := 150 + f32(i) * 156 l := row.l l.t0, l.step, l.dur = s.start + 0.4 + f32(i) * 0.12, 0.05, 0.6 l.out = s.start + 4.2 fx.label(row.name, {150, y}, fx.mono(34), fx.theme.nm, {0, 0.5}) fx.letters("Typography", {1040, y}, fx.sans(124, 600, -0.03), i % 2 == 0 ? fx.theme.nt : fx.theme.na, l, {0, 0.5}) } } ``` `out` is the time at which the letters start to leave again, by the same road they came: a letter that rose in sinks out, one that came in blurred blurs away. Leaving is quicker than arriving (each letter takes 0.6 of `dur`, and they follow each other at half of `step`). At 0 the line stays. Things to know: - One line only: there is no wrapping. For a paragraph, call it once per line and offset `t0`. - Kerning is kept. The letters end up where `label` would have drawn the string, so you can swap one for the other. - A letter in motion is drawn in a group of its own, a blurred one if you set `blur`. Once it has arrived it is plain text again, so a long line costs something only while it moves. - The rect it returns is the settled line's, from the first frame on. Use it to place what belongs next to the text. ## Scramble ```odin scramble :: proc(s: string, p: f32, seed: u32 = 1, rate: f32 = 30, hide: int = 0, set := SCRAMBLE_SET) -> string SCRAMBLE_SET :: "abcdefghijklmnopqrstuvwxyz0123456789<>/\\[]{}=+*#%&" ``` `scramble` returns `s` with only the first `p` (0..1) of it readable. The rest is replaced by characters from `set` that change `rate` times a second: a message being decoded. It draws nothing itself, so pass the result to `text` or `label`. Drive `p` with [`prog`](/docs/anim/#progress). Spaces and line breaks are never scrambled, so the shape of the text is there from the start. With `hide` above 0 only that many undecoded characters are shown ahead of the readable part and the rest is blank, which looks like typing with noise at the cursor. `seed` makes two scrambles on the same frame differ. `set` must be plain ASCII. Use a monospaced font. In a proportional one the line changes its width with every new character and jitters. ```odin type_scramble :: proc(s: fx.Shot) { fx.backdrop(.Night) p := fx.prog(s.lt, 0.5, 3.4) // how much of the text is decoded rate := knob("rate", 30, 2, 60) f := fx.mono(84, 500) fx.text(fx.scramble("every frame is a function", p, 1, rate), 190, 240, f, fx.theme.nt) // hide = 3: only three undecoded characters run ahead fx.text(fx.scramble("of time and nothing else", p, 2, rate, 3), 190, 480, f, fx.theme.nt) // its own alphabet fx.text(fx.scramble("0110 1001 1100 0011 1010", p, 3, rate, 0, "01"), 190, 720, f, fx.theme.na) } ``` ## Glyphs ```odin Glyph :: struct { s: string, // the character x, w: f32, // its place in the line (kerning kept) } glyphs :: proc(s: string, f: Font) -> []Glyph ``` `glyphs` is what `letters` is built on: for a one-line text in a font it returns every character with its `x` (from the start of the line) and its width `w`. Draw each with `fx.text(g.s, x0 + g.x, y, f, c)` and you have the line back, with one position per letter to do with as you like: a wave, a color per letter, letters that scatter. A space comes back with `w = 0` (and no position); skip it. The slice lives in the frame's scratch memory, like every string `fx` hands you: use it in the frame, do not keep it. ```odin type_glyphs :: proc(s: fx.Shot) { fx.backdrop(.Night) f := fx.sans(230, 700, -0.02) word := "Wavelength" size := fx.measure(word, f) x0, y0 := 960 - size.x / 2, 500 - size.y / 2 amp := knob("amp", 50, 0, 150) for g, i in fx.glyphs(word, f) { if g.w == 0 do continue // a space y := y0 + amp * math.sin(s.p * 2 * math.TAU - f32(i) * 0.6) fx.text(g.s, x0 + g.x, y, f, i == 4 ? fx.theme.na : fx.theme.nt) // the glyph's place in the line: x and w fx.rect({x0 + g.x + 3, y0 + size.y + 180, g.w - 6, 8}, i == 4 ? fx.theme.na : fx.theme.ns) } } ``` ## Reference | Procedure | Returns | | --- | --- | | `letters(s, p, f, c, l, anchor)` | Draws one line whose letters arrive per `l`; the line's rect. | | `scramble(s, p, seed, rate, hide, set)` | `s` with everything after the first `p` of it replaced by changing characters. | | `glyphs(s, f)` | Each character of a one-line text with its `x` and width. | --- # Cutting to music An edit that follows its music needs two things: the times of the hits, and something that happens on them. This page covers both. A beat here is nothing more than a time in seconds, and a track's beats are a sorted `[]f32`. Everything else turns "how long since the last one" into a number between 0 and 1 that you multiply into a scale, an offset, an opacity or a filter amount. ## Where beats come from In a film the list comes from the music itself. [`onsets`](/docs/sound/) finds the hits in an audio file, and `times` moves them from the file's clock to the video's: ```odin times :: proc(hits: []Onset, from: f32 = 0, at: f32 = 0, to: f32 = max(f32), strength: f32 = 0, level: f32 = 0) -> []f32 ``` The file plays from `from` seconds into it at video time `at`, so a hit at file time `h` lands at `h - from + at`. Only hits inside `[from, to)` of the file are kept, and of those only the ones whose `strength` (how sharp the attack is) and `level` (how loud, 0..1 of the file's loudest) are at least what you ask for. Raise `strength` to keep only the hard hits. The result is allocated with `context.allocator` and nothing frees it, so build the list once and keep it, not once per frame: ```odin KICKS: []f32 kicks_once: sync.Once kicks :: proc() -> []f32 { sync.once_do(&kicks_once, proc() { found := fx.onsets("assets/song.wav", .Bass) // analysed once, cached under .effects/analysis KICKS = fx.times(found, from = 33.5, at = 0) // the song starts 33.5 s in, at the start of the video }) return KICKS } ``` Put the same list in `Video.marks` and the editor draws it on its ruler and snaps scenes to it. Audio analysis reads files, so it does not exist in the browser build. The demos on this page write their beats by hand, usually one every half second (120 bpm). A list is a list: code that works on these works on analysed ones, and a score written in code (see [/docs/music/](/docs/music/)) already has its note times as lists. ## Beat and pulse ```odin beat :: proc(beats: []f32, t: f32) -> (i: int, since: f32) pulse :: proc(beats: []f32, t: f32, dur: f32 = 0.25, e: Ease = ease_out) -> f32 hit :: proc(t, t0, dur: f32, e: Ease = ease_out) -> f32 ``` `beat` finds the last beat at or before `t` with a binary search: `i` is its index and `since` the seconds since it. Before the first beat `i` is -1 and `since` is `t` itself. Use the index to step through things (which card is lit, which shot of a list is showing) and `since` to animate inside the beat. `pulse` is the value you will use most: 1 on each beat, falling to 0 over `dur` seconds along the ease, and 0 before the first beat. With the default `ease_out` it drops quickly and settles gently, like a drum. A `dur` longer than the gap between beats never reaches 0; the next beat sets it back to 1. `hit` is `pulse` for a single moment `t0`: 0 before it, 1 at it, 0 again `dur` later. Use it for the one drop of a piece or for the first frame of a scene (`fx.hit(s.t, s.start, 0.5)`). ```odin edit_pulse :: proc(s: fx.Shot) { fx.backdrop(.Night) beats := [?]f32{0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5} // written by hand here; fx.onsets finds them in a film i, since := fx.beat(beats[:], s.lt) // which beat we are in, and for how long k := fx.pulse(beats[:], s.lt, knob("dur", 0.25, 0.05, 0.5)) // 1 on the beat, 0 after dur for _, j in beats { c := fx.Vec2{400 + f32(j) * 160, 800} fx.circle(c, 18, j == i ? fx.theme.na : fx.theme.nb) } fx.circle({960, 420}, 130 + 90 * k, fx.theme.nt) fx.label(fmt.tprintf("beat %d + %.2f s pulse %.2f", i, since, k), {960, 930}, fx.mono(36), fx.theme.nm, {0.5, 0.5}) } ``` The list must be sorted, as `beat` searches it. `pulse` and `hit` return plain numbers, so combining them is arithmetic: `0.6 * fx.pulse(kicks, t) + 0.4 * fx.pulse(snares, t, 0.12)`. ## Flash ```odin flash :: proc(a: f32, c: Color = 0xffffffff) ``` Covers the stage in color `c` at opacity `a` (0..1). It draws nothing below an opacity of 0.003, so it costs nothing while it is off. Call it last in a scene so it lands on top. Driven by `hit` it is the white frame on a drop; driven by `ep` it is a fade from or to a color. ```odin edit_flash :: proc(s: fx.Shot) { fx.backdrop(.Night) DROP :: 1.5 if s.lt < DROP { fx.label("wait for it", {960, 540}, fx.mono(48), fx.theme.ns, {0.5, 0.5}) } else { fx.caption("the drop", {960, 540}, 260, fx.theme.nt, {0.5, 0.5}) } // a white frame on the hit, gone half a second later fx.flash(fx.hit(s.lt, DROP, 0.5) * knob("amount", 0.9, 0, 1), fx.theme.nt) // the same procedure fades a scene from and to black fx.flash(1 - fx.ep(s.lt, 0, 0.4), 0xff000000) fx.flash(fx.ep(s.lt, 3.5, 3.95, fx.ease_in), 0xff000000) } ``` ## Shake ```odin shake :: proc(t: f32, amount: f32, freq: f32 = 14, seed: f32 = 0) -> Vec2 noise1 :: proc(x: f32, seed: f32 = 0) -> f32 ``` `shake` returns an offset in pixels: up to `amount` in each direction, changing direction `freq` times a second. It is a pure function of `t`, so the same frame always shakes the same way. Give two things different `seed`s to shake them independently. An `amount` of 0 returns `{}` without doing any work, so multiplying the amount by a pulse is cheap while the pulse is 0. Put the offset into a group's `x` and `y` to shake what is drawn inside it: ```odin edit_shake :: proc(s: fx.Shot) { fx.backdrop(.Night) beats := [?]f32{0, 1, 2, 3} k := fx.pulse(beats[:], s.lt, 0.5) // the shake dies away after each beat off := fx.shake(s.t, knob("amount", 40, 0, 120) * k, knob("freq", 14, 2, 40)) if fx.group({x = off.x, y = off.y}) { fx.rrect({560, 290, 800, 500}, 40, fx.theme.nt) fx.caption("shake", {960, 540}, 200, fx.theme.night, {0.5, 0.5}) } } ``` `noise1` is what `shake` is made of: smooth value noise in -1..1, one new random value per whole step of `x`, eased between them. It is jumpier than [`wob`](/docs/anim/#random-but-the-same-every-time), which drifts; use `noise1` for hand-held jitter and flicker, `wob` for slow floating. ## Camera ```odin camera :: proc(zoom: f32 = 1, offset := Vec2{}, rot: f32 = 0) -> Xf ``` Returns the `Xf` of a camera over the whole stage: scaled by `zoom` and rotated by `rot` degrees around the stage's center, then moved by `offset` in stage pixels. Wrap a scene in `fx.group(fx.camera(…))` and everything in it moves together. A punch-in on the beat is `zoom = 1 + 0.1 * pulse`; a hand-held look is a small `shake` as the offset. ```odin edit_camera :: proc(s: fx.Shot) { beats := [?]f32{0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5} i, _ := fx.beat(beats[:], s.lt) k := fx.pulse(beats[:], s.lt, 0.4) zoom := 1 + knob("punch", 0.12, 0, 0.4) * k // a punch-in on every beat tilt := knob("tilt", 2, 0, 10) * k * (i % 2 == 0 ? 1 : -1) // leaning left, then right if fx.group(fx.camera(zoom, fx.shake(s.t, 10 * k), tilt)) { fx.backdrop(.Night) for j in 0 ..< 4 { r := fx.Rect{270 + f32(j) * 360, 340, 300, 400} fx.rrect(r, 28, j == i % 4 ? fx.theme.na : fx.theme.nt) } } } ``` The background has to be inside the group, or it stays still while the picture moves. Rotating or shaking uncovers the corners of the stage, so keep the zoom a little above 1 whenever you do either. To move a whole film instead of one scene, return the camera from [`Video.master`](/docs/scenes/). ## Letterbox ```odin letterbox :: proc(amount: f32 = 1, ratio: f32 = 2.39, c: Color = 0xff000000) ``` Two bars, top and bottom, that crop the stage to the aspect `ratio` (width over height; 2.39 is CinemaScope, 1.85 the flat cinema format). `amount` slides them in from 0 (no bars) to 1 (fully in), so animating it opens or closes the frame. A ratio narrower than the stage's own draws nothing. Call it after the picture; for bars over a whole film, call it in `Video.overlay`. ```odin edit_letterbox :: proc(s: fx.Shot) { fx.image(fx.load_image("assets/frame.jpg"), fx.stage(), zoom = 1 + 0.04 * s.p) // bars slide in, hold, and leave again before the loop amount := fx.ep(s.lt, 0.5, 1.3, fx.ease_in_out) - fx.ep(s.lt, 3.8, 4.6, fx.ease_in_out) fx.letterbox(amount, knob("ratio", 2.39, 1.78, 3.5)) } ``` ## Transitions A transition happens between two scenes that are both on screen for a moment. You make that moment by letting the scenes overlap on the timeline: start the next scene `dur` seconds before this one ends. Each scene then wraps what it draws in a group whose `Xf` comes from `transition`: ```odin transition :: proc(s: Shot, enter, leave: Transition, dur: f32 = 0.4) -> Xf ``` For the first `dur` seconds of the scene it returns the incoming half of `enter`, for the last `dur` seconds the outgoing half of `leave`, and `{}` (no change) in between. `.Cut` on either side means nothing happens there. The two scenes of a pair must name the same kind, this one as its `leave` and the next one as its `enter`, and use the same `dur` as the overlap: ```odin SCENES := [?]fx.Scene { {name = "a", start = 0.0, dur = 2.5, draw = a}, {name = "b", start = 2.0, dur = 2.5, draw = b}, // starts 0.5 s before a ends } a :: proc(s: fx.Shot) { if fx.group(fx.transition(s, .Cut, .Whip_Left, 0.5)) { // everything a draws, background included } } b :: proc(s: fx.Shot) { if fx.group(fx.transition(s, .Whip_Left, .Whip_Up, 0.5)) { // everything b draws } } ``` The demo below does the same inside one procedure, because a demo is a single scene: it builds the `Shot` of each entry by hand, as the renderer does for a scene list, and draws the first scene a second time at the end so the loop closes. ```odin edit_transition :: proc(s: fx.Shot) { D :: 0.5 // every scene starts D before the one before it ends list := [?]struct { name: string, start: f32, enter, leave: fx.Transition, }{{"A", -D, .Whip_Up, .Whip_Left}, {"B", 2 - D, .Whip_Left, .Whip_Up}, {"A", 4 - D, .Whip_Up, .Whip_Left}} for sc in list { // what the renderer does with a scene list: a Shot for each scene that is on shot := fx.Shot{t = s.t, lt = s.t - sc.start, start = sc.start, dur = 2 + D} if shot.lt < 0 || shot.lt >= shot.dur do continue // what a scene does: everything it draws goes inside the transition's group if fx.group(fx.transition(shot, sc.enter, sc.leave, D)) { fx.backdrop(sc.name == "A" ? .Night : .Paper) fx.caption(sc.name, {960, 540}, 520, sc.name == "A" ? fx.theme.nt : fx.theme.ink, {0.5, 0.5}) } } } ``` ```odin Transition :: enum { Cut, Fade, Whip_Left, Whip_Right, Whip_Up, Whip_Down, Zoom, Spin, Glitch, Blur, } ``` | Kind | What happens across the overlap | | --- | --- | | `Cut` | Nothing. The scenes are drawn as they are. | | `Fade` | The incoming scene's opacity goes from 0 to 1 over the outgoing one, which does not change. The incoming scene must come later in the scene list, so it is drawn on top. | | `Whip_Left`, `Whip_Right`, `Whip_Up`, `Whip_Down` | Both scenes slide a full stage width (or height) in that direction, side by side, eased in and out. Each is motion-blurred along the move by 0.35 of the distance it travels per frame, at most 140 px. | | `Zoom` | First half: the outgoing scene rushes toward the viewer (scale 1 to 2.6) under a radial blur. Second half: the incoming one settles from scale 1.9 to 1 as the blur clears. | | `Spin` | First half: the outgoing scene turns a quarter turn clockwise, growing to 1.4 and blurring. Second half: the incoming one arrives from a quarter turn the other way. The corners a turning scene uncovers show the video's `background`. | | `Glitch` | The [`glitch`](/docs/post/) filter (slices and color split) and a sideways jitter of up to 20 px rise to the middle, where the picture switches, and fall again. | | `Blur` | The outgoing scene goes out of focus (blur up to 40), brightening by up to 40% and growing by 6%; the picture switches in the middle and the incoming one comes back into focus. | `Zoom`, `Spin`, `Glitch` and `Blur` are hidden cuts: the outgoing scene is drawn for the first half of the overlap only, the incoming one for the second half only. The whips and `Fade` show both scenes all the way through. Each card below names the transition that brought it in. `dur` is both the overlap and the length of the transition. ```odin edit_transitions :: proc(s: fx.Shot) { kinds := [?]fx.Transition{.Fade, .Whip_Left, .Whip_Right, .Whip_Up, .Whip_Down, .Zoom, .Spin, .Glitch, .Blur} D := knob("dur", 0.4, 0.15, 1.2) EVERY :: 1.4 for k in 0 ..= len(kinds) { enter := kinds[(k + len(kinds) - 1) % len(kinds)] // the same kind as the scene before leaves with leave := kinds[k % len(kinds)] shot := fx.Shot{t = s.t, lt = s.t - (f32(k) * EVERY - D), dur = EVERY + D} if shot.lt < 0 || shot.lt >= shot.dur do continue if fx.group(fx.transition(shot, enter, leave, D)) { paper := k % 3 == 1 if k % 3 == 2 do fx.rect(fx.stage(), fx.theme.na) else do fx.backdrop(paper ? .Paper : .Night) ink := paper ? fx.theme.ink : fx.theme.nt fx.label("came in with", {960, 376}, fx.caps(30, 0.16), fx.alpha(ink, 0.6), {0.5, 0.5}) fx.caption(fmt.tprint(enter), {960, 540}, 220, ink, {0.5, 0.5}) } } } ``` The blurred kinds draw the scene into a layer first, and `Zoom` and `Glitch` also run a pixel filter over it, so the frames inside a transition cost more than the ones around it (a filter that reads each pixel a few times is about 0.05 s per 1080p frame on one CPU thread). Outside its two windows `transition` returns `{}` and the group costs nothing. ```odin trans_xf :: proc(k: Transition, p: f32, incoming: bool, dur: f32) -> Xf ``` `trans_xf` is what `transition` calls: one side of transition `k` at progress `p` (0..1 across the overlap). Call it yourself when the change is not at a scene's edges, for example between two halves of one scene. `dur` is the length in seconds; the whips need it to work out their motion blur. ```odin p := fx.prog(s.lt, 3.0, 3.4) // a spin, 3 s into the scene if p < 1 { if fx.group(fx.trans_xf(.Spin, p, false, 0.4)) do first_half(s) } if p > 0 { if fx.group(fx.trans_xf(.Spin, p, true, 0.4)) do second_half(s) } ``` The outgoing side is the unchanged picture at `p = 0` and the incoming side at `p = 1`, so there is no jump where the transition starts and ends. ## Speed ramps ```odin ramp :: proc(lt: f32, ks: []Key) -> f32 ``` A speed ramp plays a clip fast, drops into slow motion for the moment that matters and speeds up again. `ramp` does the bookkeeping: given how long the clip has been on screen (`lt`) and its playback speed over that time as keyframes, it returns how far into the source the clip is, which is the time to ask the footage for. Each [`Key`](/docs/anim/#keyframes) is `{t, v}`: at clip time `t` the speed is `v` (1 = real time, 2 = double speed, 0 = a freeze frame). Between keys the speed changes linearly; before the first key and after the last it holds their value. With no keys the result is `lt`. ```odin keys := [?]fx.Key{{0.8, 2}, {1.1, 0.15}, {2.6, 0.15}, {2.9, 2}} fx.footage("assets/jump.mp4", 12 + fx.ramp(s.lt, keys[:]), fx.stage()) // the clip starts 12 s into the file ``` There is no footage in the browser, so the "clip" in the demo is a ball whose position depends on source time. The pale copies are the 14 frames before the current one: far apart where the clip runs fast, bunched up in the slow motion. ```odin edit_ramp :: proc(s: fx.Shot) { fx.backdrop(.Night) slow := knob("slow", 0.15, 0, 1) // double speed, slow motion from 1.1 s to 2.6 s, double speed again keys := [?]fx.Key{{0.8, 2}, {1.1, slow}, {2.6, slow}, {2.9, 2}} for j := 14; j >= 0; j -= 1 { // the "clip" is a ball whose place depends on source time; older frames trail behind it src := fx.ramp(s.lt - f32(j) / 30, keys[:]) p := fx.Vec2{-120 + 440 * src, 700 - 420 * abs(math.sin(src * 2.1))} fx.circle(p, 40, j == 0 ? fx.theme.na : fx.alpha(fx.theme.nt, 0.22 - 0.014 * f32(j))) } fx.hline(0, 742, 1920, fx.theme.nb, 2) readout := fmt.tprintf("clip %.2f s source %.2f s", s.lt, fx.ramp(s.lt, keys[:])) fx.label(readout, {960, 900}, fx.mono(36), fx.theme.nm, {0.5, 0.5}) } ``` `ramp` only chooses a time; it does not make new frames. At speed 0.15, footage shot at 30 fps shows a new picture about every seventh frame of a 30 fps video. [/docs/footage/](/docs/footage/) covers `footage` itself. ## Titles ```odin slam :: proc(s: string, p: Vec2, f: Font, c: Color, t, t0: f32, dur: f32 = 0.16, anchor := Vec2{0.5, 0.5}) -> Rect outline :: proc(s: string, p: Vec2, f: Font, c: Color, width: f32 = 2, anchor := Vec2{0.5, 0.5}) -> Rect ``` `slam` draws text that lands at time `t0`: nothing before it, then a copy 1.5 times the size, blurred and fading in, that drops onto its place within `dur` seconds. The default 0.16 s is about ten frames at 60 fps, short enough to read as an impact. `t` is the current time on the same clock as `t0`. The text is placed like [`label`](/docs/draw/) by `p` and `anchor`, except that the default anchor is the center, which is also the point it scales around. It returns the text's rect, or an empty rect before `t0`. `outline` draws the text as a stroke of `width` pixels with no fill, placed the same way. It is a still picture; use it for the hollow copy of a word that is filled on the beat, or for stacked echoes behind a title. ```odin edit_slam :: proc(s: fx.Shot) { fx.backdrop(.Night) words := [?]string{"CUT", "TO", "MUSIC"} beats := [?]f32{0.5, 1.0, 1.5} f := fx.sans(270, 700, -0.03) off := fx.shake(s.t, 24 * fx.pulse(beats[:], s.lt, 0.3)) // every slam shakes the frame out := fx.ep(s.lt, 3.3, 3.8, fx.ease_in) if fx.group({x = off.x, y = off.y, o = 1 - out}) { for w, i in words { p := fx.Vec2{960, 250 + f32(i) * 290} fx.outline(w, p, f, fx.theme.ns, knob("width", 3, 1, 10)) // the empty word waits fx.slam(w, p, f, i == 2 ? fx.theme.na : fx.theme.nt, s.lt, beats[i], knob("dur", 0.16, 0.05, 0.8)) } } } ``` ## Reference | Name | What it is | | --- | --- | | `times(hits, from, at, to, strength, level)` | Onsets of a file as video times, filtered. Allocates; call once. | | `beat(beats, t)` | Index of the last beat at or before `t` (-1 before the first) and the seconds since it. | | `pulse(beats, t, dur, e)` | 1 on each beat, falling to 0 over `dur`. | | `hit(t, t0, dur, e)` | 1 at `t0`, falling to 0 over `dur`; 0 before. | | `noise1(x, seed)` | Smooth value noise in -1..1. | | `shake(t, amount, freq, seed)` | Offset in px, up to `amount` on each axis. | | `camera(zoom, offset, rot)` | `Xf` that zooms and rotates around the stage center and moves by `offset`. | | `flash(a, c)` | The stage covered in `c` at opacity `a`. | | `letterbox(amount, ratio, c)` | Bars cropping the stage to `ratio`, slid in by `amount`. | | `Transition` | `Cut`, `Fade`, `Whip_Left`, `Whip_Right`, `Whip_Up`, `Whip_Down`, `Zoom`, `Spin`, `Glitch`, `Blur`. | | `transition(s, enter, leave, dur)` | `Xf` for a scene that enters and leaves with transitions at its edges. | | `trans_xf(k, p, incoming, dur)` | `Xf` of one side of a transition at progress `p`. | | `ramp(lt, ks)` | Source time of a clip after `lt` seconds at the speeds in `ks`. | | `slam(s, p, f, c, t, t0, dur, anchor)` | Text that drops into place at `t0`. | | `outline(s, p, f, c, width, anchor)` | Text drawn as an outline. | --- # Layout Most of `fx` draws at coordinates you give it. That is right for motion graphics, where the positions are the animation, and for a handful of things whose place you know. It stops being right when sizes depend on content: a button as wide as its label, a paragraph that wraps and pushes down what follows, a list of rows, a sidebar next to a page. For those, `layout` is a small flexbox. You describe a tree of boxes, and it measures the text, shares out the space, places everything and draws it. It is made for mockups of interfaces, and the [interface kit](/docs/ui/) is built on it. ## A first layout ```odin layout :: proc(r: Rect, b: Box = {}) -> bool box :: proc(b: Box) -> bool item :: proc(b: Box) txt :: proc(s: string, f: Font, c: Color, b: Box = {}) glyph :: proc(name: string, size: f32, c: Color, b: Box = {}, width: f32 = 1.6) spacer :: proc(weight: f32 = 1) ``` `layout` opens a tree whose root fills the rect `r`. `box` adds a container; what you call inside its scope becomes its children. Both always return true and are written as `if` statements only for the scope: the box closes, and the layout is computed and drawn, when its block ends. The leaves are `item` (a box without children: a divider, a swatch, a bar), `txt` (text), `glyph` (an icon of the [icon set](/docs/draw/), `size` pixels square, stroked `width` units wide on its 24-unit grid), `picture` (an image, below) and `spacer` (an invisible item that takes the free space along its parent's direction, pushing its neighbours apart). Every one of them is described by a `Box`, a struct with a field for everything an element can have. Fields you leave out are zero, and zero always means "nothing special": a row, as big as its content, no padding, no background. ```odin layout_first :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme body := "Every frame is a pure function of time, so the frames of a video can be drawn in any order, on every core at once." // the root always fills its rect; this one only centers the card if fx.layout(fx.stage(), {justify = .Center, align = .Center}) { card := fx.Box{dir = .Col, w = fx.fixed(knob("width", 1100, 700, 1700)), pad = fx.pads(56), gap = 32, bg = th.sf, radius = 28} if fx.box(card) { if fx.box({dir = .Row, w = fx.grow(), gap = 20, align = .Center}) { fx.glyph("video", 54, th.red) fx.txt("Renders", fx.sans(62, 600, -0.02), th.ink) fx.spacer() fx.txt("3 running", fx.mono(32), th.sub) } fx.item({w = fx.grow(), h = fx.fixed(2), bg = th.bd}) // the card is as tall as its content, so it grows as the text is typed fx.txt(fx.typed(body, s.lt, 0.5, 3.2), fx.sans(42), th.mut, {wrap = true}) } } } ``` The root always has exactly the size of `r`, whatever its content. For a card that is as big as what is in it, make the card a `box` inside a root that only positions it, as above. ## Sizes ```odin Size :: struct { kind: Sizing, // Fit, Grow, Fixed, Percent v: f32, min, max: f32, // 0 = unbounded } fit :: proc "contextless" (min: f32 = 0, max: f32 = 0) -> Size fixed :: proc "contextless" (v: f32) -> Size grow :: proc "contextless" (weight: f32 = 1, min: f32 = 0, max: f32 = 0) -> Size pct :: proc "contextless" (p: f32) -> Size ``` A box has a `w` and an `h`, each one of four kinds: | Size | The element is | | --- | --- | | `fit(min, max)` | As big as its content: its children plus gaps and padding, or its text. This is the default. | | `fixed(v)` | `v` pixels. | | `grow(weight, min, max)` | Along the parent's direction: its content size plus a share of the space the parent has left over, in proportion to `weight`. Across it: as big as the parent's inside. | | `pct(p)` | `p` (0..1) of the parent's inside, which is its size minus its padding. | `min` and `max` bound a `fit` or `grow` size in pixels. ```odin layout_sizes :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme rows := [2][3]struct { name: string, w: fx.Size, } { {{"fixed(300)", fx.fixed(300)}, {"fit()", fx.fit()}, {"grow()", fx.grow()}}, {{"pct(0.25)", fx.pct(0.25)}, {"grow()", fx.grow()}, {"grow(2)", fx.grow(2)}}, } w := 1340 + 380 * math.sin(s.p * math.TAU) // the container breathes; watch who gives way if fx.layout({960 - w / 2, 310, w, 460}, {dir = .Col, pad = fx.pads(28), gap = 20, border = th.ns, border_w = 2, radius = 24}) { for row in rows { if fx.box({dir = .Row, w = fx.grow(), h = fx.grow(), gap = 20}) { for c, i in row { cell := fx.Box{w = c.w, h = fx.grow(), pad = fx.padxy(28, 0), justify = .Center, align = .Center, radius = 14} cell.bg = i == 0 ? th.na : th.nt if fx.box(cell) do fx.txt(c.name, fx.mono(32), th.night) } } } } } ``` Two details are different from CSS and worth knowing: - A growing element starts from its own content size and gets its share of the leftover space on top. Two `grow()` boxes with different content are therefore not the same width. For equal columns use `pct`, or give them equal content. - A `pct` child counts as zero when its parent measures its content, so a `fit` parent does not make room for it. Use `pct` inside parents whose size is fixed or grown. When the children need more room than there is, growing elements and wrapped text shrink in proportion, down to nothing. Fixed and fitted elements keep their size and stick out of the parent. ## Direction, gap, padding, alignment ```odin Dir :: enum u8 {Row, Col} Justify :: enum u8 {Start, Center, End, Between} Align :: enum u8 {Start, Center, End} pads :: proc "contextless" (v: f32) -> [4]f32 // the same on all four sides padxy :: proc "contextless" (x, y: f32) -> [4]f32 // left/right, top/bottom ``` `dir` lays the children out in a row (the default) or a column. `gap` is the space between neighbours, `pad` the space between the box's edge and its children, as `{top, right, bottom, left}`. `justify` places the children along the direction: at the start, centered, at the end, or with the free space shared out between them (`.Between` replaces `gap`). `align` places each child across the direction. There is no "stretch": a child fills the cross direction when its own size there is `grow()`. ```odin layout_align :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme justify := fx.Justify(int(s.lt) % 4) // the next one every second align := fx.Align(int(knob("align", 1, 0, 2) + 0.5)) root := fx.Box{dir = .Row, justify = justify, align = align, gap = knob("gap", 24, 0, 160)} root.pad, root.border, root.border_w, root.radius = fx.pads(36), th.ns, 2, 24 if fx.layout({260, 150, 1400, 560}, root) { for h, i in ([?]f32{200, 340, 130}) { fx.item({w = fx.fixed(240), h = fx.fixed(h), bg = i == 1 ? th.na : th.nt, radius = 16}) } } fx.label(fmt.tprintf("justify = .%v align = .%v", justify, align), {960, 850}, fx.mono(40), th.nm, {0.5, 0.5}) } ``` ## How a box looks | Field | Effect | | --- | --- | | `bg` | Fill color. | | `paint` | A paint instead of `bg`, for a gradient. Its points are stage coordinates, not relative to the box. | | `border`, `border_w` | Outline color and width in px (1 when only the color is set). | | `sides` | Which sides get the border, as a set of `.Top`, `.Right`, `.Bottom`, `.Left`. Empty means all four. A partial border is drawn as straight lines and ignores `radius`. | | `radius` | Corner radius of background, border, shadow and clip. | | `shadow` | A `Shadow{dx, dy, blur, spread, c}` behind the box; drawn when `c` is set. | | `clip` | Cuts the children off at the box's (rounded) edge. | | `float`, `at` | A floating box takes no space in its parent and is drawn above its siblings, with its top-left corner `at` pixels from the parent's top-left corner (padding is not added). | ```odin picture :: proc(img: ^sk.Image, b: Box, fit := Image_Fit.Cover) ``` `picture` puts an image (from [`load_image`](/docs/draw/)) into the tree. An image has no content size here, so give it a `w` and an `h`. A picture is not rounded by its own `radius`; put it in a box with `radius` and `clip`. ```odin layout_look :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme img := fx.load_image("assets/frame.jpg") if fx.layout(fx.stage(), {justify = .Center, align = .Center}) { card := fx.Box{dir = .Col, w = fx.fixed(980), bg = th.sf, border = th.bds, border_w = 2} card.radius, card.clip = knob("radius", 32, 0, 100), true // children are cut to the rounded shape card.shadow = {dy = 30, blur = 80, c = 0xaa000000} card.dy = 12 * math.sin(s.p * math.TAU) if fx.box(card) { fx.picture(img, {w = fx.grow(), h = fx.fixed(450)}) if fx.box({dir = .Col, w = fx.grow(), pad = fx.padxy(44, 30), gap = 8}) { fx.txt("Latent space", fx.sans(60, 600, -0.02), th.ink) fx.txt("Scene 3 of 8", fx.sans(34), th.mut) } foot := fx.Box{dir = .Row, w = fx.grow(), pad = fx.padxy(44, 24), bg = th.sf2, border = th.bds, border_w = 2, sides = {.Top}} if fx.box(foot) { fx.txt("19.00 s", fx.mono(32), th.mut) fx.spacer() fx.txt("1920 × 1080", fx.mono(32), th.mut) } // a float takes no space; `at` is measured from the parent's top-left corner if fx.box({float = true, at = {36, 36}, pad = fx.padxy(18, 8), bg = th.red, radius = 10}) { fx.txt("new", fx.caps(28, 0.12, 500), th.sf) } } } } ``` An element is drawn in this order: shadow, background, border, the `draw` callback, its own text, icon or image, its children, then its floating children. ## Text `txt` takes the text, a [`Font`](/docs/draw/) and a color. Without anything else it is one line, as wide as the text, and it never shrinks. Set `wrap` and it wraps at whatever width the layout gives it; unless you set `w` yourself, a wrapped text grows to fill its parent. `talign` (`.Left`, `.Center`, `.Right`) aligns the lines of wrapped text inside that width. It has no effect on one-line text, which is only as wide as itself: to right-align a single line, put it in a box with `justify = .End` (the percentages in the next demo). Padding belongs to containers. A `Box` given to `txt`, `glyph` or `picture` sets the element's id, size, background, border and animation, but its `pad` is ignored; wrap the element in a `box` to pad it. `glyph` always sets its own `w` and `h`. All the text of one `txt` has one font and one color. For a line with mixed weights or colors, use a row of `txt` elements. ## Custom drawing ```odin draw: proc(r: Rect, data: rawptr) data: rawptr ``` When an element should contain something the layout has no element for (a chart, a progress bar, a shader), give it a `draw` procedure. It is called with the element's final rect, after the background and border and before the children, and may draw anything with the rest of `fx`. `data` is handed to it unchanged. ```odin layout_draw :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme jobs := [?]struct { name: string, speed, done: f32, }{{"fable", 0.36, 0}, {"showreel", 0.2, 0}, {"spot", 0.11, 0}} bar :: proc(r: fx.Rect, data: rawptr) { // called with the element's final rect done := (^f32)(data)^ fx.rrect(r, r.h / 2, fx.theme.sf3) fx.rrect({r.x, r.y, max(r.w * done, r.h), r.h}, r.h / 2, done == 1 ? fx.theme.ok : fx.theme.ink) } if fx.layout({410, 260, 1100, 560}, {dir = .Col, pad = fx.pads(56), justify = .Between, bg = th.sf, radius = 28}) { for &j in jobs { // by reference: the pointer is read when the layout ends j.done = fx.clamp01((s.lt - 0.3) * j.speed) if fx.box({dir = .Row, w = fx.grow(), gap = 32, align = .Center}) { fx.txt(j.name, fx.sans(42, 500), th.ink, {w = fx.fixed(240)}) fx.item({w = fx.grow(), h = fx.fixed(26), draw = bar, data = &j.done}) if fx.box({w = fx.fixed(110), justify = .End}) { // right-aligned in a fixed column fx.txt(fmt.tprintf("%d%%", int(j.done * 100)), fx.mono(34), th.mut) } } } } } ``` The callback runs when the layout's scope ends, not where the element is declared, so whatever `data` points to must still be alive and unchanged then. A pointer to a loop variable is neither; point into the array (`for &j in jobs`), or copy the value with `new_clone(v, context.temp_allocator)`, which lasts until the frame is done. ## Animating elements ```odin o: Maybe(f32), // opacity, nil = 1 dx, dy: f32, // offset in px s: Maybe(f32), // scale, nil = 1 rot: f32, // degrees blur: f32, // gaussian blur sigma gray: f32, // 0..1 desaturate ``` These fields of `Box` animate one element, with its children, around its own center. They are the same as the fields of a [group](/docs/group/), and are applied after the layout is done: a moved, scaled or faded element still occupies the place it was given, and its neighbours do not react. That is what you want for entrances and for emphasis. To animate the layout itself, animate what it is computed from: a `fixed` width, a `gap`, a padding, the text. The tree is rebuilt every frame, so any field can be a function of time. ```odin layout_animate :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme names := [?]string{"s1_prompt", "s2_attention", "s3_latent", "s4_reasoning", "s5_title"} out := fx.ep(s.lt, 3.6, 4.1, fx.ease_in) if fx.layout({460, 120, 1000, 840}, {dir = .Col, pad = fx.pads(48), gap = 20, bg = th.sf, radius = 28, o = 1 - out}) { fx.txt("Scenes", fx.sans(58, 600, -0.02), th.ink) for name, i in names { k := fx.stagger(s.lt, i, 0.3, knob("step", 0.12, 0, 0.4), 0.6) pick := i == 2 ? fx.ep(s.lt, 2.0, 2.3, fx.ease_back) : 0 // one row is picked later row := fx.Box{dir = .Row, w = fx.grow(), h = fx.grow(), pad = fx.padxy(28, 0), gap = 22, align = .Center, radius = 14} row.bg = fx.mix(th.sf2, th.ink, pick) row.o, row.dy, row.blur = k, 50 * (1 - k), 12 * (1 - k) // rises in, sharpening row.s = 1 + 0.06 * pick // and the picked one grows a little, around its own center if fx.box(row) { fx.glyph("play", 34, fx.mix(th.red, th.sf, pick)) fx.txt(name, fx.mono(36), fx.mix(th.ink, th.sf, pick)) } } } } ``` Fading, blurring or graying an element draws it into a layer the size of its rect plus its shadow, so children that stick out of the element are cut off while that lasts. An element with an opacity of 0 is skipped entirely, children included. ## Finding an element again ```odin rect_of :: proc(id: string) -> (Rect, bool) ``` Give an element an `id` and, once the layout has been drawn, `rect_of` returns where it ended up: in stage pixels, after every transform that applied to it, both its own animation and any group around the layout. The second result is false when no element with that id was drawn this frame (an element at opacity 0 is not). This is how a pointer finds a button or a highlight frames a row without the scene knowing any coordinates. Lay out, then ask, then draw on top: ```odin layout_rect_of :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme press := fx.hit(s.lt, 4.2, 0.3) if fx.layout({460, 130, 1000, 820}, {dir = .Col, pad = fx.pads(48), gap = 20, bg = th.sf, radius = 28}) { fx.txt("Projects", fx.sans(58, 600, -0.02), th.ink) for name in ([?]string{"fable", "showreel", "spot"}) { if fx.box({id = name, dir = .Row, w = fx.grow(), h = fx.grow(), pad = fx.padxy(32, 0), align = .Center, bg = th.sf2, radius = 14}) { fx.txt(name, fx.mono(38), th.ink) } } if fx.box({dir = .Row, w = fx.grow(), justify = .End, pad = {12, 0, 0, 0}}) { if fx.box({id = "render", pad = fx.padxy(44, 22), bg = th.ink, radius = 14, s = 1 - 0.08 * press}) { fx.txt("Render", fx.sans(40, 500), th.sf) } } } // the layout is drawn; now its elements can be asked where they ended up first, _ := fx.rect_of("fable") last, _ := fx.rect_of("spot") button, _ := fx.rect_of("render") frame := fx.lerp_rect(first, last, fx.ep(s.lt, 2.1, 2.7, fx.ease_in_out)) fx.border(fx.inset(frame, -10), fx.alpha(th.na, fx.win(s.lt, 1.2, 5.4)), 5, 22) a, b, c := fx.center(first), fx.center(last), fx.center(button) + {70, 26} fx.cursor({{0.5, {1620, 1000}, false}, {1.3, a, false}, {2.0, a, false}, {2.7, b, false}, {3.3, b, false}, {4.2, c, true}}, 0.3, 5.6, 76) } ``` The frame and the pointer are drawn after the layout's scope has ended, which is the only place the rects exist. The pointer is [`cursor`](/docs/ui/#pointer-and-highlight) from the interface kit, which also has a ready-made `highlight`. Ids are remembered until the end of the frame and are shared by all layouts of the frame, so two elements with the same id overwrite each other. For a rotated element the rect is the upright box around it. ```odin layout_reset :: proc() ``` `layout_reset` forgets all ids. The renderer calls it before every frame; you never need to, unless you drive `fx` from a renderer of your own. ## What happens when `fx` is immediate-mode: there are no persistent elements, and a scene describes its whole layout again for every frame. Inside the `layout` scope nothing is measured or drawn yet; `box`, `txt` and the others only add nodes to a tree. When the scope ends, the tree is processed in one go: 1. Widths from the inside out: every element's content width. Text is measured on one line; wrapped text counts as zero. 2. Widths from the outside in: percentages are resolved, free space is shared among growing elements, and overflow is taken back from growing elements and wrapped text. 3. Text is shaped at the width it ended up with. This is where wrapping happens. 4. Heights, in the same two passes, now that every text knows how many lines it has. 5. Positions, then drawing, parents before children. Three things follow from that: - Anything you draw with other `fx` calls inside the scope lands underneath the layout, because the layout is drawn at the end of the scope. Draw into an element with its `draw` callback, and on top of the layout after the scope. - `rect_of` only knows elements of layouts that have already ended in this frame. - Layouts cannot be nested (it is an assertion). Use boxes inside one layout, or several layouts one after the other. Rebuilding the tree every frame is cheap: laid-out text is cached per thread, so text that does not change is not shaped again. Interface elements made of text, rects and layers cost about 2 ms per 1080p frame on one CPU thread. `layout` and `box` end themselves at the end of their scope. If opening and closing a layout in the same block does not suit your code, `layout_begin(r, b)` and `layout_end()` are the same thing as two calls. ## Box | Field | Type | Meaning | | --- | --- | --- | | `id` | `string` | Name for `rect_of`. | | `dir` | `Dir` | `.Row` (default) or `.Col`. | | `w`, `h` | `Size` | `fit()` (default), `fixed`, `grow` or `pct`. | | `pad` | `[4]f32` | Padding: top, right, bottom, left. | | `gap` | `f32` | Space between children along `dir`. | | `justify` | `Justify` | Children along `dir`: `.Start`, `.Center`, `.End`, `.Between`. | | `align` | `Align` | Children across `dir`: `.Start`, `.Center`, `.End`. | | `bg` | `Color` | Background color. | | `paint` | `Maybe(sk.Paint)` | Background paint instead of `bg`. | | `border` | `Color` | Border color. | | `border_w` | `f32` | Border width, 1 if unset. | | `sides` | `Sides` | Sides with a border; empty = all. | | `radius` | `f32` | Corner radius. | | `shadow` | `Shadow` | `{dx, dy, blur, spread, c}`. | | `clip` | `bool` | Clip children to the box. | | `draw`, `data` | `proc(r: Rect, data: rawptr)`, `rawptr` | Custom content and what is passed to it. | | `float`, `at` | `bool`, `Vec2` | Take the box out of the flow and place it from the parent's top-left corner. | | `wrap` | `bool` | Text: wrap at the given width. | | `talign` | `Text_Align` | Text: alignment of wrapped lines. | | `o` | `Maybe(f32)` | Opacity. | | `dx`, `dy` | `f32` | Offset in px. | | `s` | `Maybe(f32)` | Scale around the center. | | `rot` | `f32` | Rotation in degrees around the center. | | `blur` | `f32` | Blur sigma. | | `gray` | `f32` | Desaturation, 0..1. | ## Reference | Name | What it is | | --- | --- | | `layout(r, b)` | Opens a layout in `r`; computed and drawn when its scope ends. | | `layout_begin(r, b)`, `layout_end()` | The same without a scope. | | `box(b)` | A container; its scope holds its children. | | `item(b)` | A box without children. | | `txt(s, f, c, b)` | Text. | | `glyph(name, size, c, b, width)` | An icon. | | `picture(img, b, fit)` | An image. | | `spacer(weight)` | Free space along the parent's direction. | | `fit(min, max)`, `fixed(v)`, `grow(weight, min, max)`, `pct(p)` | Sizes. | | `pads(v)`, `padxy(x, y)` | Padding on all sides, or per axis. | | `rect_of(id)` | Where an element was drawn, in stage pixels. | | `layout_reset()` | Forgets all ids; called by the renderer every frame. | | `Box` | Everything an element can have. | | `Size`, `Sizing` | A width or height and its kind. | | `Dir`, `Justify`, `Align` | Direction and alignment. | | `Side`, `Sides` | Border sides. | | `Shadow` | A box shadow. | --- # Interface kit The kit is what `fx` was first written for: a film that shows a product. It holds the surfaces a mockup sits on, the chrome around it, the small parts an interface is made of, and the pointer and highlight that lead the eye through it. It has one look (paper surfaces, hairline borders, mono labels, a red bracket) and takes its colors and fonts from [`fx.theme`](/docs/theme/), so replacing the theme recolors all of it. The pieces come in two kinds: - **Immediate** ones draw at the stage coordinates you give them: `backdrop`, `vignette`, `grain`, `window`, `phone`, `cursor`, `highlight`, `kinetic`, `caption`. - **Layout** ones are elements of a [layout](/docs/layout/) and may only be called inside `fx.layout`: `sidebar`, `topbar`, `pill`, `button`, `kpi`, `avatar`, `bubble`, `table_head`, `table_row`, `bars`, `meter`. Each takes a `Box` as its last argument, for an id, a size or an animation. > **Note:** The kit has the pixel sizes of a real interface: labels are 13 to 16 px. That is right when a window fills a 1080p frame, and too small for the players on this page, so most demos here draw inside `fx.group({s = 2})` and work on a stage of 960×540. In a film you would do the same to punch in on a detail. A few pieces carry the original product's German strings as defaults (the top bar's title, the default navigation). They are listed where they occur, with how to pass your own. ## Backdrops ```odin Backdrop :: enum {Night, Paper} backdrop :: proc(kind: Backdrop, r: Rect = {}, grid := true, offset := Vec2{}) ``` A surface to put things on: a soft elliptical gradient, lighter in the middle, with an engineering-paper grid of fine lines every 48 px and stronger ones every 240 px. `.Night` is the dark one, `.Paper` the light one. `r` is the area to fill (the whole stage when left out), `grid = false` leaves the lines away, and `offset` shifts the grid in pixels, so a slowly growing offset makes it drift. The gradient is rendered once at half resolution and reused by every frame, so a backdrop costs one image draw plus the grid lines. Its colors are fixed and do not follow the theme. ```odin ui_backdrop :: proc(s: fx.Shot) { drift := fx.Vec2{40 * s.lt, 0} // 240 px in 6 s is one major square, so the loop closes fx.backdrop(.Night, {0, 0, 960, 1080}, offset = drift) fx.backdrop(.Paper, {960, 0, 960, 1080}, offset = drift) fx.caption(".Night", {480, 540}, 150, fx.theme.nt, {0.5, 0.5}) fx.caption(".Paper", {1440, 540}, 150, fx.theme.ink, {0.5, 0.5}) } ``` ```odin grid_lines :: proc(r: Rect, step: f32, c: Color, offset := Vec2{}) ellipse_gradient :: proc(r: Rect, c: Vec2, rx, ry: f32, stops: []Stop) ``` These are the two things a backdrop is made of, for building your own. `grid_lines` draws 1 px lines every `step` px across `r`, horizontal and vertical, shifted by `offset`. `ellipse_gradient` fills `r` with a radial gradient around the point `c` that reaches its last stop `rx` px to the sides and `ry` px above and below, like CSS `radial-gradient(ellipse rx ry at c)`. A [`Stop`](/docs/draw/) is `{color, position}` with the position in 0..1. ```odin ui_surface :: proc(s: fx.Shot) { th := fx.theme fx.rect(fx.stage(), th.night) // a glow that wanders: your own colors, center and radii c := fx.Vec2{960 + 520 * math.sin(s.p * math.TAU), 600 + 140 * math.cos(s.p * math.TAU)} glow := [?]fx.Stop{{fx.alpha(th.na, 0.6), 0}, {fx.alpha(th.na, 0.15), 0.5}, {fx.alpha(th.na, 0), 1}} fx.ellipse_gradient(fx.stage(), c, knob("rx", 1100, 200, 1900), knob("ry", 520, 100, 1000), glow[:]) step := knob("step", 96, 24, 240) fx.grid_lines(fx.stage(), step, th.nb, {0, 2 * step * s.p}) // two squares down per loop fx.caption("a backdrop of your own", {960, 540}, 110, th.nt, {0.5, 0.5}) } ``` A full-screen gradient drawn every frame costs about 5 ms per 1080p frame on one CPU thread. If yours does not move, wrap it in [`bake`](/docs/draw/) as `backdrop` does. ## Vignette and grain ```odin vignette :: proc(strength: f32 = 0.42, r: Rect = {}) grain :: proc(amount: f32 = 0.04) ``` `vignette` darkens the edges of `r` (the stage by default): nothing in the middle, black at opacity `strength` in the corners. It is baked once per strength and reused, which makes it cheap, and also means you should not animate the strength: every new value renders and keeps another image. `grain` lays film grain over the whole stage: a 256 px tile of noise in overlay blend that jumps to a new position 24 times a second. `amount` is its strength; around 0.03 to 0.05 is a fine grain, and above 0.17 the tile is fully opaque. Both belong on top of everything, so the usual place for them is [`Video.overlay`](/docs/scenes/): ```odin overlay = proc(t: f32) {fx.vignette(0.35); fx.grain(0.035)}, ``` ```odin ui_grain :: proc(s: fx.Shot) { // a still from a film, pushed in slowly; in a project these two calls go in Video.overlay fx.image(fx.load_image("assets/frame.jpg"), fx.stage(), zoom = 1.02 + 0.06 * math.sin(s.p * math.PI)) fx.vignette(0.42) fx.grain(knob("grain", 0.04, 0, 0.3)) } ``` Each is a full-screen pass of about 5 ms on the CPU. Grain is fine detail that video encoders like to smooth away; for dark, grainy films render with `--crf 16 --tune grain` (see [/docs/cli/](/docs/cli/)). ## Headlines ```odin headline :: proc(size: f32, weight: f32 = 600) -> Font caption :: proc(s: string, p: Vec2, size: f32 = 84, c: Color = 0, anchor := Vec2{}) -> Rect eyebrow :: proc(s: string, p: Vec2, c: Color = 0, anchor := Vec2{}) -> Rect ``` `headline` is the kit's display face as a [`Font`](/docs/draw/): the theme's sans, semibold, set tight (tracking -0.035, line height 0.98). `caption` draws one line in it, placed like [`label`](/docs/draw/) by `p` and `anchor`. `eyebrow` draws the small line above a headline: 17 px mono capitals, widely spaced. Left at 0, the color of `caption` is `theme.ink` and that of `eyebrow` is `theme.sub`. Both are dark, for paper; on a night backdrop pass `theme.nt` or `theme.ns`. ```odin Word :: struct { w: string, t: f32, // when it rises in accent: bool, br: bool, // line break after this word } kinetic :: proc(words: []Word, x, y: f32, f: Font, c: Color, accent: Color = 0, max_w: f32 = 0, dur: f32 = 0.38) -> Rect ``` `kinetic` sets a headline whose words arrive one at a time. Each word has its own time `t`; starting 0.06 s before it, the word rises 26 px into place, fading in and sharpening, over `dur` seconds. Words marked `accent` take the accent color (`theme.red` when left at 0). The block's top-left corner is at `x, y`, and a line ends after a word with `br`, or automatically where the next word would pass `max_w` (0 means no automatic wrapping). Every word has its final place from the first frame, so nothing moves sideways as later words arrive. The result is the rect of the whole block. ```odin ui_headline :: proc(s: fx.Shot) { fx.backdrop(.Night) th := fx.theme out := fx.ep(s.lt, 4.3, 4.8, fx.ease_in) if fx.group({o = 1 - out}) { // eyebrow is 17 px, made to be seen 1:1; here it is doubled if fx.group({s = 2, origin = {160, 230}}) do fx.eyebrow("Chapter one", {160, 230}, th.ns) words := [?]fx.Word { {w = "Every", t = 0.4}, {w = "frame", t = 0.6}, {w = "is", t = 0.8, br = true}, {w = "a", t = 1.3}, {w = "function", t = 1.5, accent = true}, {w = "of", t = 2.0}, {w = "time.", t = 2.2, accent = true}, } fx.kinetic(words[:], 160, 310, fx.headline(190), th.nt, th.na, dur = knob("dur", 0.38, 0.1, 1.5)) o := fx.ep(s.lt, 2.9, 3.4) fx.caption("caption draws one line in the same face", {160, 800}, 60, fx.alpha(th.nm, o)) } } ``` The times are video times (what `fx.now()` returns), not times within the scene: in a film, add `s.start`. In a demo the two are the same. All words share one font. To mix sizes, call `kinetic` once per size. ### Following a voice-over ```odin vo_text :: proc(id: string, x, y: f32, f: Font, c: Color, accents: []int = nil, breaks: []int = nil, max_w: f32 = 0) -> Rect ``` `vo_text` is `kinetic` with the words and times taken from the video's voice-over: each word of the line `id` appears when it is spoken. `accents` and `breaks` are word indices (from 0) to color and to break after. It returns an empty rect when the line does not exist. ```odin // if timeline.json has a line with the id "intro" that says "Every frame is a function of time." fx.vo_text("intro", 160, 310, fx.headline(190), fx.theme.nt, accents = {4, 6}, breaks = {2}) ``` It needs a voice-over timeline (`Video.vo`, see [/docs/voice-over/](/docs/voice-over/)), which is a file, so there is no demo of it here. ## Windows ```odin window :: proc(r: Rect, url := "", sheet := "", night := false) -> Rect corners :: proc(r: Rect, c: Color, size: f32 = 16, off: f32 = 6, width: f32 = 2) mark :: proc(p: Vec2, size: f32 = 28, c: Color = 0) ``` `window` draws a product window in `r`: a soft shadow, a paper surface, a 42 px chrome bar with three dots, a hairline border and a red bracket at two corners. `url` is shown in a field in the middle of the bar and `sheet` as a small label at its right; either is left out when empty. Set `night` when the window sits on a dark backdrop: the shadow is made darker so it still reads. It returns the body, which is `r` without the bar. That rect is where your content goes, typically as the rect of a `layout`. The window does not clip: keep to the body, or draw inside a group with `clip`. ```odin ui_window :: proc(s: fx.Shot) { fx.backdrop(.Night) k := fx.ep(s.lt, 0.2, 1.1, fx.ease_out5) out := fx.ep(s.lt, 4.3, 4.8, fx.ease_in) // the kit has the sizes of a real interface, so the demos look at it from twice as close if fx.group({s = 2, y = 80 * (1 - k), o = k - out}) { body := fx.window({130, 55, 700, 430}, "app.example.com/renders", "Sheet 01", night = true) fx.mark({body.x + 44, body.y + 48}, 72) fx.caption("The body is yours.", {body.x + 44, body.y + 150}, 56) note := "window draws the chrome bar, the border and the red corners, and returns the rect below the bar." fx.text(note, body.x + 44, body.y + 236, fx.sans(19), fx.theme.mut, 560) } } ``` `corners` draws the two L-shaped brackets on their own, at the top-left and bottom-right of `r`: `off` px outside it, with legs `size` long and `width` thick. `mark` draws the brand mark, an open bracket, `size` px square with its top-left at `p`, in `theme.red` unless you pass a color. ## App chrome ```odin Nav :: struct { icon, label: string, sub: bool, // child of the previous top-level item sep: bool, // a divider instead of an item } Sidebar :: struct { active: string, // label of the highlighted item open: []string, // top-level items whose children are shown items: []Nav, // default: LIERMANN_NAV workspace: string, user: string, role: string, w: f32, // default 250 } sidebar :: proc(sb: Sidebar) topbar :: proc(title := "Weber & Kraus GmbH", role := "Inhaber") ``` Both are layout elements. `sidebar` is a column as tall as its parent and `w` wide: the mark and a wordmark at the top, the navigation, and the workspace and user at the bottom. Put it first in a row. `topbar` is a 52 px bar as wide as its parent, with a panel icon, a title, the role as a pill, and a bell, a language code and a moon icon at the right. Put it first in the column next to the sidebar. The navigation is a flat list of `Nav`. An item with `sub` belongs to the top-level item before it and is only shown while that item's label is in `open`; a top-level item with children gets a chevron that points down while it is open. `sep` draws a divider. `icon` is a name from the [icon set](/docs/draw/). The item whose label equals `active` is drawn inverted. Every item gets the id `nav/