mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-19 00:17:13 +00:00
* Disk cache: record the source files each frame reads Part of #3184 (step 1): renders now report which footage files they read, each with its identity (size and modification time) as read. Nothing uses the list yet: images, cache keys and cache behaviour are unchanged. - render: `reads` module with `FileStamp`, `ReadFile`, `ReadFiles` (sorted, deduplicated, bounded; marked incomplete when it can't vouch for every file) and the thread-safe `ReadLog`. `Renderer::reads` collects a frame's files; `FootageSource::recording` lets a source note what it reads. `file_stamp` uses the same identity. - Layer cache entries keep the files their buffer was made of and report them on every hit; derived entries (styles, blend space, flattened) keep their base's. Buffers from the disk cache or the browser store don't know their files yet and mark the list incomplete. - Media pool: every file read notes its identity, taken from the file it opens. Decoded frames, opened movies, GIFs, models and EXR channels keep it with the cache entry, so a frame served from memory reports its file without touching the disk. - Viewer frame worker collects each frame's list and carries it to where the disk entry is written (step 2 stores it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Automation: confined footage passes on the files it reads Part of #3184: ConfinedFootage forwards FootageSource::recording to the source it wraps, so renders of an automation session list their files instead of coming back incomplete. The read tests also render through the viewer's CancellableFootage wrapper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: frame entries keep their source files, comp key from memory Part of #3184 (step 2). Fixes #3175: opening a comp no longer stamps every footage file of the project before its first frame can show. - The comp's content key (`disk_cache::comp_content_key`) is taken from the project in memory alone: no footage or proxy file is stamped, no `VirtualFileId` is asked. `comp_content_key_with` is gone; `frame_key` hashes a new entry version, so entries of the earlier format are never looked up again (LRU evicts them). - Frame entries (formats 2 and 3) store the files the frame read (`EntryFiles`: size and modification time as read; size and content hash through `VirtualFileId` for files from memory; missing files), then the pixels. Formats 0 and 1 read as misses and are deleted. - Check on hit: `get_frame`/`get_frame_f16` look only at the listed files (one metadata call each) on the frame worker. A changed, back or unreadable file, or a damaged entry, is a miss: the entry is deleted and the frame rendered and stored again. - A frame whose file list is incomplete is shown but not stored. The RAM preview keeps each frame's files, so `persist_missing` writes only frames with a complete list. - Remote frame worker: `FrameServer` records each frame's reads (`take_files`); the web worker stores them with the entry and the page checks them through the file table before using it. The browser's media epoch existed only for the old key and is removed. Export does not use frame entries. - The cache indicator still only asks whether an entry exists. Tests: entry format round trip and damage, the check per file, and in the viewer: a changed file re-renders exactly its frames (and a reopen reads the rest from disk); a frame checks only its own files in a project with a large unused sequence and the key looks at no file; missing, unreadable files and damaged entries never serve a stale frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: layer entries keep their source files, no footage salt Part of #3184 (step 3 of 4). Layer buffers on disk (and in the browser's layer store) now carry the files they were made of, like frame entries since step 2, and are checked against exactly those files when used. The project-wide footage salt is gone: nothing stamps every footage file any more. - Layer entry format 4: the buffer's EntryFiles, then the pixels. A hit checks only the listed files (metadata, or the VirtualFileId hook for files from memory; Missing must still be missing); a change, a damaged entry or the old format 0 is a miss and the entry is deleted, so the re-rendered buffer replaces it. A hit reports its file list, so frames made of buffers from disk are complete and get stored again. - Buffers whose files can't all be named are not written. - Layer disk keys: layer_disk_key = hash of the layer entry version, the renderer version and the layer cache key (which names the footage items with their paths and settings, from memory). - PrefetchStore checks on use; an entry made of changed files is dropped and forgotten, so the new buffer is queued over it. FrameServer passes its virtual-file hook to its layer cache. - Removed: footage_salt(_with), file_stamp, footage_stamp, set_disk_salt, set_store_salt, Session::refresh_disk_salt, poll_disk_salt, footage_fingerprint, disk_salt, disk_salt_background, disk_salt_job, DiskSaltJob, the UI's per-frame poll, the salt in FrameServer and in the availability worker (with its cache_enabled plumbing). The disk cache is attached as soon as it is configured. - Docs: architecture.md, web.md. Tests: layer entries check their files (size, time, missing/back, folder, damaged, old format, incomplete); virtual files; prefetch store; media tests with a real pool across restarts (only the changed file is read, projects with the same item ids never share an entry, missing, unreadable and damaged never serve stale buffers); engine tests that the cache is attached at once and edits do no file work (#1926, #3106). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: no-salt worker test, sequence paths in the frame-blend key Part of #3184 (step 3 of 4). - A frame-blended footage frame's layer-cache key now hashes the sequence's file list: with no project-wide salt, two projects whose items share an id and a first frame must not share its disk entry. - Test: a frame worker syncing, patching and rendering a project with an unused 5000-frame sequence asks its file hook only about the file its buffer reads (the salt asked about every file at every sync). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: the comp key covers what its expressions can read With an expression anywhere in the project, every comp's disk key hashed every item of the project, so any edit (another comp, an unused footage item) threw away every comp's frames on disk. The key now covers what the comp can draw plus what the expressions among it can reach (Project::pixel_reach): - without expressions: the items the comp draws, without silent layers, plus the footage its precomp layers swap in (Media Replacement); - with expressions: every layer of the comps they reach, their markers, the comps and footage they name with string literals (comp("Name"), footage("Name")) together with which items have those names now, and the footage named like a reached source (its data is read by name); - the whole project when an expression computes a name, uses the object model's constructors or internals, dynamic code, computed keys or writes, or text the scanner can't read for sure (regex literals, template strings, escapes): expression_reach errs towards reaching more. Markers count only where an expression can read them (#1083). Memory only, no file is looked at. Tests: scanner and reach unit tests in the project crate; engine tests for the key (own-comp expressions keep the key through edits elsewhere, comp("Other") follows Other and not a third comp, a second comp taking the name counts, a computed name counts every item, markers read from another comp); a ui-egui test that the disk frames outside an expression layer are carried when the comp it names changes. Part of #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: Reload Footage drops the entries of its files, docs File > Reload Footage now deletes the frame and layer entries whose file lists name the reloaded item's files (DiskCache::drop_files), so a file replaced by one with the same size and modification time, which the check on hit can't tell apart, is read again. The index knows keys, not files: the writer thread reads the files section at the start of each frame and layer entry (not the pixels) after the writes queued before it, and deletes the entries that list one of the files. Until it is done, an entry made of one of them is a miss and frames aren't linked to new keys. The entries are gone for good, so they don't come back after a restart. Automatic reloads don't drop anything: they follow a changed stamp, which the check on hit catches. The browser needs nothing (its file identities are content hashes). Removed: disk_cache::seal, which steps 2 and 3 left without callers (the tests use seal_format). Updated the module, seal_format and forget_media docs, and docs/architecture.md / docs/web.md describe the final design: what is cached, keys from memory, file lists checked on hit, nothing scans the project, incomplete lists stay in memory, Reload Footage drops entries, edits keep the frames they can't change. Tests: render unit tests (same size and time passes the check but not the drop; other files' entries stay; an entry queued before the drop is dropped; a layer entry too; written again afterwards it is used; the drop survives a restart; a pending drop is a miss), and an engine test through file.reloadFootage. Closes #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: file stamps keep the whole modification time A file's modification time was nanoseconds since 1970 as u64: a time before 1970 read as "no time" (two such files of one size looked alike) and times after 2554 were truncated. It is now i128 nanoseconds, negative before the epoch; None only means the file system has no time. The content-key hash writes a presence tag and the full value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Automation: a refused footage read leaves the render's file list incomplete Footage outside the read roots shows nothing and was noted as no file at all, so a picture made without it had a complete, empty list and could be kept on disk for a later session with other roots. A refused read during `recording` now marks the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: a buffer kept by another worker comes with its own files LayerCache::insert returns the files of the buffer it keeps, and Renderer::keep notes them in the render's log and returns them, so a render that uses another worker's buffer lists that buffer's files (a file changed between the two reads then has two identities and the list is incomplete). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: sampleImage and text fonts note the files they read EvalCtx carries the render's read log. A sampleImage render records its footage reads, keeps them with its per-thread cached buffer and notes them in the evaluating render's log on every use. Text notes the font files it is drawn with, with the identity their bytes were read with; a family that isn't installed, a fallback or missing glyph, or a font from memory leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: frame entries store the whole modification time A frame entry's file list stores a file's modification time as i128 nanoseconds since 1970 (negative before), as the file stamps now keep it; the frame entry format version goes to frame-entry-files-2 so entries in the old layout are not read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: layer entries store the whole modification time Layer entries share the frame entries' file list layout, which now stores the full i128 modification time: the layer entry format version goes to layer-entry-files-2. The module doc names the font files text is drawn with among an entry's source files, and what keeps a list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Layer cache: buffers that read other layers are keyed by the switches passed down A layer whose effect reads another layer (Gradient Wipe, Set Matte, Blend…) gets that layer drawn by its own renderer. Through a precomp layer, Switches Affect Nested Comps, the switches inherited from the precomp layers above and motion blur on change those pixels, but the key held only the layers' own switches: a buffer made with the setting on was reused (from memory or the disk cache) with it off. Such layers now derive their key with what the renderer passes down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Layer cache: masked buffers are keyed by the mask motion blur gate A mask with Mask Motion Blur On blurs even when the layer's own switch is off, as long as the render's gate is open (Render Settings motion blur, and with Switches Affect Nested Comps the precomp layers above). The key held the layer's own motion blur state only, so a buffer blurred with the gate open was reused with it closed (and the other way round), also from the disk cache. Masked layer, input and footprint keys now tell a closed gate apart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: cached buffers list what their expressions and substituted characters read - Buffers made under `Renderer::recorded` (layer content, a Time effect's input, an adjustment layer's footprint) evaluate their masks, shapes and effects with the context that notes into the buffer's own read log, so a file an expression reads (`sampleImage`, also at shutter times mask motion blur adds and the cache key doesn't see) is in the buffer's files. - A styled layer served from the cache lists the files of the cached body and passes too, so the buffers made of it (flattened, blending space) don't get a complete list when one of them came with an incomplete one. - A character put in by Character Offset or Character Value without a relayout notes the font it is drawn with; a fallback face (or none) leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: text lists the font file of a run that draws no glyph; tests clean their temp dirs An empty first paragraph draws no glyph, but in a box its face sets the first baseline that places every later line. The read list took faces only from glyphs, so it could be complete without that file. Note each style run's resolved face as well. The font-reads and confine tests use tempfile::tempdir(): a fresh directory per run, removed on panic too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: Reload Footage closes the gaps around its drop (#3184) - A reload while the disk cache is off is kept on the session (pending_disk_drops) and applied when the cache is switched on, before anything is read from it. - Each render takes the cache's drop generation before it reads (frame worker; layer cache at the miss). An entry listing a file dropped after that is refused under the queue's lock, so a render that was under way during the reload can't store pixels from before it. Such a frame is shown with an incomplete file list, so persist_missing skips it too. The per-file record is bounded (past it, everything older is refused). - An entry read while its drop was pending is a miss even when the writer ends the sweep between the read and the check (a stale hit found under load): the pending drops and the generation are taken before the entry is read. - Test: a reopened project serves its frame from disk with no source file opened or decoded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: RAM frames keep the drop generation their render started at Reload Footage empties the RAM preview, but an idle pass of persist_missing may already hold a frame from before the reload. It took the cache's drop generation when it ran, after the drop, so the old pixels could be written back and, with the file's size and time unchanged, served again after a restart. Each RAM frame now keeps the disk cache its render started with and that cache's drop generation then. persist_missing writes a frame only to that cache, with that generation, and skips it once one of its files was dropped since; a frame rendered without that cache is not written from there. Tests use tempfile directories (the layer drop test, the frame_files folders under target/). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Doc comments for the functions this PR touches * Disk cache: cap the free-space reserve at 10 GB, skip encodes the limit refuses The reserve the cache leaves free on its disk was max(2 GB, 5% of the disk) (#2551). On a 4 TB disk with 190 GB free that is 200 GB, so a cache set to 20 GB had a limit of 0: every write was refused, the cache never held anything, and only a log warning said so. The reserve is now clamp(5% of the disk, 2 GB, 10 GB). It is there to keep the cache from filling the disk, not to keep a share of a large disk free: 10 GB leaves the system room to work on any disk, a small disk still keeps 2 GB, and a 100 GB disk keeps 5 GB as before. After Effects has only a maximum cache size and no reserve; a clamp keeps the floor for small disks, where a fixed 10 GB would take most of the space. Writes the limit refuses cost no work: DiskCache::accepts_writes (one atomic read) is checked before a frame is converted (put_disk_frame) and before frames and layers are compressed (put_frame, put_frame_f16, put_layer). The frame workers spent about 8 ms per frame and 14 ms per layer on encodes that were then refused. persist_missing returns at once at limit 0 instead of converting the RAM frames on every idle pass. Settings > Disk shows the limit in effect in MB under Maximum Disk Cache Size, with a note when free disk space lowers it (settings.disk.cacheLimit). * Disk cache: refuse writes below 64 MB of room, show this disk's reserve Review follow-ups to the reserve fix: - accepts_writes also refuses while free disk space leaves less than 64 MB of room (a limit the setting asks for is always used): a few frames would fill it, and the rest would be compressed only to be refused. - While writes are refused the idle passes ask for no repaint, so the UI keeps a frame coming every 5 s: the free space is read again and the RAM frames are written once there is room. - Settings > Disk names the space kept free on this disk (the reserve the last reading applied; the rule from MIN/MAX_DISK_RESERVE when it is unknown), and the "no room" note follows accepts_writes. - The settings.disk.cacheLimit automation label is machine-readable and the same in every language: limitMb, maxMb, reserveMb, spaceLimited, writes. - cargo fmt. * Disk cache: follow 3D model sources in the comp's reach The reach walk followed comp, footage and solid sources but not LayerSource::Model. An expression reading a model layer's source (thisComp.layer("Model").source.name) left the model item out of the comp's content key, so renaming the model kept the key and the old frames on disk were served. Every source item is followed now (LayerSource::item), which also counts the model when no expression reads it (Advanced 3D draws it). The same omission is fixed in the RAM preview's content walk (frames.rs) and in the layer key's walk of referenced layers (cache/dependencies.rs). * Disk cache: a render's drop generation travels with its reads; no disk entries for Expression Selectors Drop generation per render: the layer cache recovered a buffer's drop generation from the latest miss of its key, so a second render of the key that started after File > Reload Footage lent its generation to a render still running from before, and that render's buffer (the file as it was) was written after the sweep. Now Renderer::recorded starts each buffer's read log at the store's drop generation before anything is read (ReadLog::starting_at); ReadFiles carries the earliest generation through merges, so derived buffers (styles, the blend-space copy, the flattened layer) and frames that use a buffer from memory carry it too. LayerCache::insert keeps a buffer made of a file dropped since its reads began neither on disk nor in memory; a list that doesn't say counts as made before every drop. DiskCache::dropped_since takes the list's own generation too. missed_at keeps only the miss time. Expression Selectors: the layer key evaluates a text Expression Selector's amount for the first character only, so a per-character dependency such as textIndex == 1 ? 0 : footage("ref.png").width was not in the key, and after the footage item's width changed a reopened session reused the old layer entry. A text layer with an Expression Selector now marks its reads unkeyed (ReadFiles::is_unkeyed), which merges like the generation; such buffers stay in memory and are never written to disk. Frame entries are unaffected: the comp's frame key hashes what the expressions name. The equality and hash of ReadFiles ignore both new fields. * Disk cache: never serve a RAM layer buffer made before a drop of its files A render that passed the drop check could sit in put_layer's encode while Reload Footage cleared the layer cache and dropped the file, then publish its old pixels to memory after the purge; get, and a fresh render's insert, then served them. The disk-hit promotion went through the same insert_mem. Every way the cache hands out a RAM buffer (get, the kept-first path of insert, an existing entry in insert_mem) now checks the entry's files against the store's drops from their own generation (ReadFiles::since): an entry made before a drop of one of its files is forgotten and the lookup misses, so a fresh render's buffer replaces it. insert_mem also re-checks a buffer just before publishing it. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
631 lines
26 KiB
Rust
631 lines
26 KiB
Rust
//! Motion tracking runtime: the analysis job (background thread with progress and cancel, or
|
||
//! blocking for the CLI / agents / wasm), writing track results into the tracker's Track Point
|
||
//! properties, and applying tracks (Transform, Stabilize, Corner Pin) to layers.
|
||
//!
|
||
//! The algorithms are in `effectcraft-track`; the property layout in
|
||
//! `effectcraft_project::tracking`.
|
||
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use std::sync::{Arc, Mutex};
|
||
|
||
use effectcraft_geom::{Mat3, vec2};
|
||
use effectcraft_project::tracking::{LowConfidence, TrackChannel, TrackKind, TrackerOptions, TrackerSettings};
|
||
use effectcraft_project::{Comp, ItemId, Keyframe, Layer, LayerId, Project, PropGroup, Uid, Value};
|
||
use effectcraft_raster::Image;
|
||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
|
||
use effectcraft_time::Tick;
|
||
use effectcraft_track as trk;
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
use crate::{Event, Session};
|
||
|
||
/// Tracker panel ▸ Analyze buttons.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub enum Direction {
|
||
#[default]
|
||
Forward,
|
||
Backward,
|
||
FrameForward,
|
||
FrameBackward,
|
||
}
|
||
|
||
impl Direction {
|
||
pub fn from_name(s: &str) -> Option<Direction> {
|
||
let n = s.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||
Some(match n.as_str() {
|
||
"forward" | "fwd" => Direction::Forward,
|
||
"backward" | "back" | "bwd" => Direction::Backward,
|
||
"frameforward" | "oneframeforward" | "1frameforward" => Direction::FrameForward,
|
||
"framebackward" | "oneframebackward" | "1framebackward" => Direction::FrameBackward,
|
||
_ => return None,
|
||
})
|
||
}
|
||
pub fn forward(self) -> bool {
|
||
matches!(self, Direction::Forward | Direction::FrameForward)
|
||
}
|
||
}
|
||
|
||
/// Track options for the algorithms.
|
||
pub fn track_options(o: &TrackerOptions) -> trk::TrackOptions {
|
||
trk::TrackOptions {
|
||
channel: match o.channel {
|
||
TrackChannel::Rgb => trk::Channel::Rgb,
|
||
TrackChannel::Luminance => trk::Channel::Luminance,
|
||
TrackChannel::Saturation => trk::Channel::Saturation,
|
||
},
|
||
blur: o.blur,
|
||
enhance: o.enhance,
|
||
subpixel: o.subpixel,
|
||
adapt_every_frame: o.adapt_every_frame,
|
||
threshold: o.threshold,
|
||
action: match o.action {
|
||
LowConfidence::Continue => trk::ConfidenceAction::Continue,
|
||
LowConfidence::Stop => trk::ConfidenceAction::Stop,
|
||
LowConfidence::Extrapolate => trk::ConfidenceAction::Extrapolate,
|
||
LowConfidence::Adapt => trk::ConfidenceAction::Adapt,
|
||
},
|
||
track_shape: o.track_shape,
|
||
}
|
||
}
|
||
|
||
/// A track point's regions and attach offset read from its properties at a layer time.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct PointValues {
|
||
pub uid: Uid,
|
||
pub spec: trk::PointSpec,
|
||
pub attach_offset: [f64; 2],
|
||
}
|
||
|
||
pub fn point_values(tp: &PropGroup, lt: Tick) -> PointValues {
|
||
let v = |m: &str, d: [f64; 2]| tp.get(m).map(|p| p.value_at(lt).as_vec2()).unwrap_or(d);
|
||
PointValues {
|
||
uid: tp.uid,
|
||
spec: trk::PointSpec {
|
||
center: v("featureCenter", [0.0; 2]),
|
||
feature_size: v("featureSize", [32.0; 2]),
|
||
search_offset: v("searchOffset", [0.0; 2]),
|
||
search_size: v("searchSize", [64.0; 2]),
|
||
},
|
||
attach_offset: v("attachPointOffset", [0.0; 2]),
|
||
}
|
||
}
|
||
|
||
/// Attach points of a frame from the feature centres, given the start frame's centres and attach
|
||
/// points: two-point transforms rotate and scale the offsets with the track, Parallel Corner Pin
|
||
/// maps them through the 3-point affine, Perspective Corner Pin through the 4-point homography.
|
||
pub fn attach_points(kind: TrackKind, rot_scale: bool, ref_c: &[[f64; 2]], ref_a: &[[f64; 2]], cur: &[[f64; 2]]) -> Vec<[f64; 2]> {
|
||
let translate = || cur.iter().zip(ref_c.iter().zip(ref_a)).map(|(c, (r, a))| [c[0] + a[0] - r[0], c[1] + a[1] - r[1]]).collect::<Vec<_>>();
|
||
let through = |h: Option<trk::Homography>| match h {
|
||
Some(h) => ref_a.iter().map(|a| h.apply(*a)).collect(),
|
||
None => translate(),
|
||
};
|
||
match kind {
|
||
TrackKind::Perspective if cur.len() >= 4 => {
|
||
let h = trk::Homography::from_points([ref_c[0], ref_c[1], ref_c[2], ref_c[3]], [cur[0], cur[1], cur[2], cur[3]]);
|
||
through(h)
|
||
}
|
||
TrackKind::Affine if cur.len() >= 3 => through(trk::Homography::affine_from_points([ref_c[0], ref_c[1], ref_c[2]], [cur[0], cur[1], cur[2]])),
|
||
_ if rot_scale && cur.len() >= 2 => {
|
||
let Some(s) = trk::Homography::similarity_from_points([ref_c[0], ref_c[1]], [cur[0], cur[1]]) else { return translate() };
|
||
let m = s.0;
|
||
cur.iter()
|
||
.zip(ref_c.iter().zip(ref_a))
|
||
.map(|(c, (r, a))| {
|
||
let d = [a[0] - r[0], a[1] - r[1]];
|
||
[c[0] + m[0][0] * d[0] + m[0][1] * d[1], c[1] + m[1][0] * d[0] + m[1][1] * d[1]]
|
||
})
|
||
.collect()
|
||
}
|
||
_ => translate(),
|
||
}
|
||
}
|
||
|
||
/// Live analysis progress (serde for agents / the control channel).
|
||
#[derive(Clone, Debug, Default, Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct TrackProgress {
|
||
pub done: u64,
|
||
pub total: u64,
|
||
pub elapsed: f64,
|
||
/// Analysed frames per second.
|
||
pub fps: f64,
|
||
pub finished: bool,
|
||
pub cancelled: bool,
|
||
/// Stopped by "If Confidence is Below … ▸ Stop Tracking".
|
||
pub low_confidence_stop: bool,
|
||
pub error: Option<String>,
|
||
/// Comp time (seconds) of the last analysed frame.
|
||
pub time: f64,
|
||
}
|
||
|
||
/// One analysed frame.
|
||
#[derive(Clone, Debug)]
|
||
pub struct FrameResult {
|
||
pub comp_time: Tick,
|
||
pub layer_time: Tick,
|
||
/// Per point: (point group uid, result, attach point).
|
||
pub points: Vec<(Uid, trk::PointResult, [f64; 2])>,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
pub struct TrackShared {
|
||
pub cancel: AtomicBool,
|
||
pub state: Mutex<TrackProgress>,
|
||
pub frames: Mutex<Vec<FrameResult>>,
|
||
}
|
||
|
||
pub(crate) fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||
}
|
||
|
||
/// A running (or finished, not yet polled) analysis.
|
||
pub struct TrackJob {
|
||
pub shared: Arc<TrackShared>,
|
||
thread: Option<std::thread::JoinHandle<()>>,
|
||
pub comp: ItemId,
|
||
pub layer: LayerId,
|
||
pub tracker: Uid,
|
||
pub direction: Direction,
|
||
}
|
||
|
||
impl TrackJob {
|
||
pub fn is_finished(&self) -> bool {
|
||
lock(&self.shared.state).finished
|
||
}
|
||
pub fn progress(&self) -> TrackProgress {
|
||
lock(&self.shared.state).clone()
|
||
}
|
||
pub fn cancel(&self) {
|
||
self.shared.cancel.store(true, Ordering::Relaxed);
|
||
}
|
||
}
|
||
|
||
/// What the worker needs, detached from the session.
|
||
pub(crate) struct Work {
|
||
pub project: Arc<Project>,
|
||
pub footage: Arc<dyn FootageSource>,
|
||
pub expr: Option<Arc<dyn ExprHost>>,
|
||
pub cache: Arc<LayerCache>,
|
||
pub comp: ItemId,
|
||
pub layer: LayerId,
|
||
pub settings: TrackerSettings,
|
||
pub points: Vec<PointValues>,
|
||
/// Comp times to analyse; the first is the start frame.
|
||
pub times: Vec<Tick>,
|
||
}
|
||
|
||
/// The layer's source frame at comp time `t` at 100 % (layer pixels + offset = image pixels).
|
||
/// Footage at its native size is used straight from the footage source (no copy unless its
|
||
/// Cineon Settings convert it).
|
||
pub(crate) fn source_frame(
|
||
r: &Renderer,
|
||
project: &Project,
|
||
cid: ItemId,
|
||
comp: &Comp,
|
||
layer: &Layer,
|
||
t: Tick,
|
||
expr: Option<&dyn ExprHost>,
|
||
) -> Option<(Arc<Image>, [f64; 2])> {
|
||
let ctx = EvalCtx { project, comp_id: cid, comp, time: t, expr, footage: None, property_overrides: &[], media_overrides: &[], reads: None };
|
||
if let effectcraft_project::LayerSource::Footage { item } = &layer.source
|
||
&& let Some(effectcraft_project::ItemKind::Footage(f)) = project.item(*item).map(|i| &i.kind)
|
||
&& f.has_video
|
||
&& let Some(img) = r.footage.frame(*item, f, ctx.source_time(layer))
|
||
&& img.width == f.width
|
||
&& img.height == f.height
|
||
{
|
||
return Some((effectcraft_render::cineon_frame(img, f), [0.0; 2]));
|
||
}
|
||
let buf = r.layer_source(&ctx, layer)?;
|
||
if (buf.scale - 1.0).abs() > 1e-9 && buf.scale > 0.0 {
|
||
// Footage decoded at another size: bring it to layer pixels.
|
||
let w = (buf.img.width as f64 / buf.scale).round().max(1.0) as u32;
|
||
let h = (buf.img.height as f64 / buf.scale).round().max(1.0) as u32;
|
||
let off = [buf.offset[0] / buf.scale, buf.offset[1] / buf.scale];
|
||
return Some((Arc::new(effectcraft_raster::resample(&buf.img, w, h)), off));
|
||
}
|
||
Some((Arc::new(buf.img), buf.offset))
|
||
}
|
||
|
||
pub(crate) async fn run_work(w: Work, shared: &TrackShared) {
|
||
let t0 = web_time::Instant::now();
|
||
// A browser job worker's GPU (deferred readbacks): frames render in passes.
|
||
let accel = crate::offload::job_accel();
|
||
let accel = accel.as_deref();
|
||
let fail = |msg: &str| {
|
||
let mut s = lock(&shared.state);
|
||
s.error = Some(msg.to_string());
|
||
s.finished = true;
|
||
};
|
||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), crate::offload::analysis_opts(accel));
|
||
r.expr = w.expr.as_deref();
|
||
r.cache = Some(&w.cache);
|
||
let r = &r;
|
||
let wr = &w;
|
||
let frame_at =
|
||
|t: Tick| crate::offload::in_passes(accel, move |a| source_frame(&r.with_accel(a), &wr.project, wr.comp, comp, layer, t, wr.expr.as_deref()));
|
||
{
|
||
let mut s = lock(&shared.state);
|
||
s.total = w.times.len().saturating_sub(1) as u64;
|
||
}
|
||
let Some(first) = frame_at(w.times[0]).await else { return fail("the layer has no pixels to track") };
|
||
let specs: Vec<trk::PointSpec> = w.points.iter().map(|p| p.spec).collect();
|
||
let mut tracker = trk::Tracker::new(track_options(&w.settings.options), &specs, &trk::Frame { img: &first.0, offset: first.1 });
|
||
let ref_c: Vec<[f64; 2]> = specs.iter().map(|s| s.center).collect();
|
||
let ref_a: Vec<[f64; 2]> = w.points.iter().map(|p| [p.spec.center[0] + p.attach_offset[0], p.spec.center[1] + p.attach_offset[1]]).collect();
|
||
let rot_scale = w.settings.rotation || w.settings.scale;
|
||
// The start frame keeps its regions and gets keys too.
|
||
lock(&shared.frames).push(FrameResult {
|
||
comp_time: w.times[0],
|
||
layer_time: layer.layer_time(w.times[0]),
|
||
points: w
|
||
.points
|
||
.iter()
|
||
.zip(&ref_a)
|
||
.map(|(p, a)| (p.uid, trk::PointResult { center: p.spec.center, confidence: 100.0, rotation: 0.0, scale: 1.0, status: trk::Status::Tracked }, *a))
|
||
.collect(),
|
||
});
|
||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]).await } else { None };
|
||
for k in 1..w.times.len() {
|
||
if shared.cancel.load(Ordering::Relaxed) {
|
||
lock(&shared.state).cancelled = true;
|
||
break;
|
||
}
|
||
let Some(cur) = next.take() else {
|
||
lock(&shared.state).error = Some(format!("no frame at {:.3} s", w.times[k].seconds()));
|
||
break;
|
||
};
|
||
// Track this frame while the next one renders.
|
||
let (res, nf) = crate::offload::join_fetch(
|
||
accel.is_some(),
|
||
|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }),
|
||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||
)
|
||
.await;
|
||
next = nf;
|
||
if res.iter().any(|p| p.status == trk::Status::Stopped) {
|
||
lock(&shared.state).low_confidence_stop = true;
|
||
break;
|
||
}
|
||
let centers: Vec<[f64; 2]> = res.iter().map(|p| p.center).collect();
|
||
let attach = attach_points(w.settings.kind, rot_scale, &ref_c, &ref_a, ¢ers);
|
||
lock(&shared.frames).push(FrameResult {
|
||
comp_time: w.times[k],
|
||
layer_time: layer.layer_time(w.times[k]),
|
||
points: w.points.iter().zip(res).zip(attach).map(|((p, r), a)| (p.uid, r, a)).collect(),
|
||
});
|
||
let mut s = lock(&shared.state);
|
||
s.done = k as u64;
|
||
s.elapsed = t0.elapsed().as_secs_f64();
|
||
s.fps = if s.elapsed > 0.0 { k as f64 / s.elapsed } else { 0.0 };
|
||
s.time = w.times[k].seconds();
|
||
crate::offload::report(s.done, s.total);
|
||
}
|
||
let mut s = lock(&shared.state);
|
||
s.elapsed = t0.elapsed().as_secs_f64();
|
||
s.finished = true;
|
||
}
|
||
|
||
/// Set (or add) a key at layer time `t`.
|
||
pub(crate) fn key(g: &mut PropGroup, m: &str, t: Tick, v: Value) {
|
||
if let Some(p) = g.get_mut(m) {
|
||
effectcraft_keyframe::set_key(&mut p.keys, Keyframe::new(t, v));
|
||
}
|
||
}
|
||
|
||
/// Write analysed frames into the tracker's points.
|
||
fn write_frames(p: &mut Project, job: &TrackJob, frames: &[FrameResult]) {
|
||
let Some(comp) = p.comp_mut(job.comp) else { return };
|
||
let Some(layer) = comp.layer_mut(job.layer) else { return };
|
||
for f in frames {
|
||
for (uid, r, a) in &f.points {
|
||
let Some(tp) = layer.props.find_group_mut(*uid) else { continue };
|
||
key(tp, "featureCenter", f.layer_time, Value::Vec2(r.center));
|
||
key(tp, "confidence", f.layer_time, Value::Scalar(r.confidence));
|
||
key(tp, "attachPoint", f.layer_time, Value::Vec2(*a));
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Session {
|
||
/// Whether a track analysis is running.
|
||
pub fn is_tracking(&self) -> bool {
|
||
self.track_job.as_ref().is_some_and(|j| !j.is_finished()) || self.offloaded(crate::offload::JobKind::Track).is_some()
|
||
}
|
||
|
||
/// Live progress of the running (or just finished) analysis.
|
||
pub fn track_progress(&self) -> Option<TrackProgress> {
|
||
self.track_job.as_ref().map(|j| j.progress()).or_else(|| self.offloaded(crate::offload::JobKind::Track).map(|j| j.progress.track()))
|
||
}
|
||
|
||
/// Cancel the running analysis (results so far are kept).
|
||
pub fn stop_track(&mut self) -> bool {
|
||
if self.cancel_offloaded(crate::offload::JobKind::Track) {
|
||
return true;
|
||
}
|
||
match &self.track_job {
|
||
Some(j) if !j.is_finished() => {
|
||
j.cancel();
|
||
true
|
||
}
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
/// Start analysing. `wait`: block until done (wasm32 always does). One undo step covers the
|
||
/// whole analysis.
|
||
pub(crate) fn start_track(&mut self, work: Work, tracker: Uid, direction: Direction, wait: bool) -> Result<(), String> {
|
||
if self.is_tracking() {
|
||
return Err("a track analysis is already running".into());
|
||
}
|
||
self.poll_track();
|
||
if !wait && self.offloads() {
|
||
let Work { comp, layer, settings, points, times, .. } = work;
|
||
return self.offload_analysis(crate::offload::WorkerJob::Track { comp, layer, tracker, direction, settings, points, times });
|
||
}
|
||
let wait = wait || cfg!(target_arch = "wasm32");
|
||
let levels = self.prefs.general.undo_levels as usize;
|
||
self.history.record("Analyze Track", self.project.clone(), levels);
|
||
let shared = Arc::new(TrackShared::default());
|
||
let (comp, layer) = (work.comp, work.layer);
|
||
let thread = if wait {
|
||
crate::offload::run_or_queue({
|
||
let sh = shared.clone();
|
||
async move { run_work(work, &sh).await }
|
||
});
|
||
None
|
||
} else {
|
||
let sh = shared.clone();
|
||
Some(
|
||
std::thread::Builder::new()
|
||
.name("track-analyze".into())
|
||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||
.map_err(|e| e.to_string())?,
|
||
)
|
||
};
|
||
self.track_job = Some(TrackJob { shared, thread, comp, layer, tracker, direction });
|
||
self.poll_track();
|
||
Ok(())
|
||
}
|
||
|
||
/// Write new results into the project and move the CTI to the last analysed frame; drop the
|
||
/// job once it finished. Frontends call this every frame while tracking.
|
||
pub fn poll_track(&mut self) -> bool {
|
||
let Some(job) = &self.track_job else { return false };
|
||
let frames = std::mem::take(&mut *lock(&job.shared.frames));
|
||
let finished = job.is_finished();
|
||
let changed = !frames.is_empty();
|
||
if changed {
|
||
write_frames(Arc::make_mut(&mut self.project), job, &frames);
|
||
if self.state.active_comp == Some(job.comp)
|
||
&& let Some(last) = frames.last()
|
||
{
|
||
self.state.times.insert(job.comp, last.comp_time);
|
||
}
|
||
self.bump();
|
||
}
|
||
if finished && let Some(mut job) = self.track_job.take() {
|
||
if let Some(t) = job.thread.take() {
|
||
let _ = t.join();
|
||
}
|
||
let st = job.progress();
|
||
let msg = match (&st.error, st.cancelled, st.low_confidence_stop) {
|
||
(Some(e), _, _) => format!("Tracking stopped: {e}"),
|
||
(None, true, _) => format!("Tracking stopped after {} frame(s)", st.done),
|
||
(None, false, true) => format!("Tracking stopped: confidence below threshold after {} frame(s)", st.done),
|
||
_ => format!("Tracked {} frame(s) in {:.1} s", st.done, st.elapsed),
|
||
};
|
||
self.events.push(Event::Toast { message: msg, error: st.error.is_some() });
|
||
}
|
||
changed || finished
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- apply
|
||
|
||
/// Apply Dimensions.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||
pub enum Dims {
|
||
#[default]
|
||
XY,
|
||
X,
|
||
Y,
|
||
}
|
||
|
||
impl Dims {
|
||
pub fn from_name(s: &str) -> Option<Dims> {
|
||
match s.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
|
||
"xy" | "xandy" | "both" => Some(Dims::XY),
|
||
"x" | "xonly" => Some(Dims::X),
|
||
"y" | "yonly" => Some(Dims::Y),
|
||
_ => None,
|
||
}
|
||
}
|
||
fn mix(self, old: [f64; 3], new: [f64; 2]) -> [f64; 3] {
|
||
match self {
|
||
Dims::XY => [new[0], new[1], old[2]],
|
||
Dims::X => [new[0], old[1], old[2]],
|
||
Dims::Y => [old[0], new[1], old[2]],
|
||
}
|
||
}
|
||
}
|
||
|
||
fn apply_m(m: &Mat3, p: [f64; 2]) -> [f64; 2] {
|
||
let q = m.apply(vec2(p[0], p[1]));
|
||
[q.x, q.y]
|
||
}
|
||
|
||
/// Parent space of a layer (comp space when unparented), as a 2D matrix from comp space.
|
||
fn comp_to_parent(ctx: &EvalCtx, layer: &Layer) -> Mat3 {
|
||
match layer.parent.and_then(|p| ctx.comp.layer(p)) {
|
||
Some(p) => ctx.layer_to_comp(p).0.inverse().unwrap_or(Mat3::IDENTITY),
|
||
None => Mat3::IDENTITY,
|
||
}
|
||
}
|
||
|
||
/// Per analysed time: (source layer time, attach points in source layer space).
|
||
pub fn attach_track(tracker: &PropGroup) -> Vec<(Tick, Vec<[f64; 2]>)> {
|
||
let pts: Vec<&PropGroup> = tracker.track_points().collect();
|
||
let Some(first) = pts.first().and_then(|g| g.get("attachPoint")) else { return vec![] };
|
||
first.keys.iter().map(|k| (k.time, pts.iter().map(|g| g.get("attachPoint").map(|p| p.value_at(k.time).as_vec2()).unwrap_or([0.0; 2])).collect())).collect()
|
||
}
|
||
|
||
/// Apply a tracker (Tracker panel ▸ Apply). Returns the number of keyframed frames.
|
||
pub fn apply(p: &mut Project, cid: ItemId, src: LayerId, tracker: Uid, dims: Dims) -> Result<usize, String> {
|
||
let comp = p.comp(cid).ok_or("no composition")?.clone();
|
||
let source = comp.layer(src).ok_or("no source layer")?.clone();
|
||
let (tg, settings) = source.tracker(tracker).ok_or("no such tracker")?;
|
||
let settings = settings.clone();
|
||
let track = attach_track(tg);
|
||
if track.is_empty() {
|
||
return Err("analyze the track first".into());
|
||
}
|
||
let target_id = match settings.kind {
|
||
TrackKind::Stabilize => src,
|
||
TrackKind::Raw => return Err("a Raw track has nothing to apply".into()),
|
||
_ => settings.target.ok_or("set a Motion Target first (Edit Target…)")?,
|
||
};
|
||
let target = comp.layer(target_id).ok_or("the motion target layer is gone")?.clone();
|
||
let ctx0 = EvalCtx::new(p, cid, &comp, Tick::ZERO);
|
||
let t_first = source.comp_time(track[0].0);
|
||
let rot_scale = settings.point_count() >= 2 && track[0].1.len() >= 2;
|
||
let (ang0, len0) = if rot_scale { effectcraft_track::angle_and_length(track[0].1[0], track[0].1[1]) } else { (0.0, 1.0) };
|
||
// (target layer time, values) to write.
|
||
let mut pos_keys = vec![];
|
||
let mut anchor_keys = vec![];
|
||
let mut rot_keys = vec![];
|
||
let mut scale_keys = vec![];
|
||
let mut corner_keys = vec![];
|
||
let ttr = target.transform().ok_or("the target has no transform")?;
|
||
let c0 = ctx0.at(t_first);
|
||
let rot0 = c0.f(&target, ttr, "rotation", 0.0);
|
||
let scale0 = c0.v3(&target, ttr, "scale", [100.0; 3]);
|
||
let mut prev_ang = 0.0;
|
||
// Stabilize: the feature stays where it was on the first tracked frame.
|
||
let stab_pos = {
|
||
let (m, _) = c0.layer_to_comp(&source);
|
||
apply_m(&comp_to_parent(&c0, &source), apply_m(&m, track[0].1[0]))
|
||
};
|
||
for (lt, pts) in &track {
|
||
let ct = source.comp_time(*lt);
|
||
let ctx = ctx0.at(ct);
|
||
let tt = target.layer_time(ct);
|
||
let (ang, len) = if rot_scale { effectcraft_track::angle_and_length(pts[0], pts[1]) } else { (ang0, len0) };
|
||
let dang = effectcraft_track::unwrap_degrees(prev_ang, ang - ang0);
|
||
prev_ang = dang;
|
||
let ratio = if len0 > 1e-9 { len / len0 } else { 1.0 };
|
||
match settings.kind {
|
||
TrackKind::Stabilize => {
|
||
if settings.position {
|
||
let old = ctx.v3(&target, ttr, "anchor", [0.0; 3]);
|
||
anchor_keys.push((tt, dims.mix(old, pts[0])));
|
||
let oldp = ctx.position(&target, ttr);
|
||
pos_keys.push((tt, dims.mix(oldp, stab_pos)));
|
||
}
|
||
if settings.rotation && rot_scale {
|
||
rot_keys.push((tt, rot0 - dang));
|
||
}
|
||
if settings.scale && rot_scale {
|
||
scale_keys.push((tt, [scale0[0] / ratio, scale0[1] / ratio, scale0[2]]));
|
||
}
|
||
}
|
||
TrackKind::Transform => {
|
||
let (m, _) = ctx.layer_to_comp(&source);
|
||
if settings.position {
|
||
let c = apply_m(&m, pts[0]);
|
||
let pp = apply_m(&comp_to_parent(&ctx, &target), c);
|
||
pos_keys.push((tt, dims.mix(ctx.position(&target, ttr), pp)));
|
||
}
|
||
if settings.rotation && rot_scale {
|
||
rot_keys.push((tt, rot0 + dang));
|
||
}
|
||
if settings.scale && rot_scale {
|
||
scale_keys.push((tt, [scale0[0] * ratio, scale0[1] * ratio, scale0[2]]));
|
||
}
|
||
}
|
||
TrackKind::Affine | TrackKind::Perspective => {
|
||
let (ms, _) = ctx.layer_to_comp(&source);
|
||
// Corner Pin's corners are effect points: in the target's effect space.
|
||
let inv = ctx.effect_to_comp(&target).inverse().ok_or("the target layer's transform is not invertible")?;
|
||
let n = pts.len();
|
||
if n < 3 {
|
||
return Err("corner pin tracks need 3 or 4 track points".into());
|
||
}
|
||
let lr =
|
||
if settings.kind == TrackKind::Affine || n < 4 { [pts[1][0] + pts[2][0] - pts[0][0], pts[1][1] + pts[2][1] - pts[0][1]] } else { pts[3] };
|
||
// Track Points 1–4: upper left, upper right, lower left, lower right.
|
||
let map = |q: [f64; 2]| apply_m(&inv, apply_m(&ms, q));
|
||
corner_keys.push((tt, [map(pts[0]), map(pts[1]), map(pts[2]), map(lr)]));
|
||
}
|
||
TrackKind::Raw => {}
|
||
}
|
||
}
|
||
let n = track.len();
|
||
let size = effectcraft_render::effect_bounds(p, &comp, &target).0;
|
||
let mut ids_next = p.next_id;
|
||
let layer = p.comp_mut(cid).and_then(|c| c.layer_mut(target_id)).ok_or("no target layer")?;
|
||
if !corner_keys.is_empty() {
|
||
let spec = effectcraft_effects::find("ec.distort.cornerpin").ok_or("Corner Pin is not available")?;
|
||
let fx = layer.props.sub_mut("effects").ok_or("the target layer can't have effects")?;
|
||
let same = fx.groups().filter(|g| g.match_id == spec.id).count();
|
||
let name = if same == 0 { spec.name.to_string() } else { format!("{} {}", spec.name, same + 1) };
|
||
let mut g = effectcraft_effects::instantiate(spec, &mut effectcraft_project::build::Ids(&mut ids_next), &name, size);
|
||
for (t, c) in &corner_keys {
|
||
for (m, v) in ["ul", "ur", "ll", "lr"].iter().zip(c) {
|
||
key(&mut g, m, *t, Value::Vec2(*v));
|
||
}
|
||
}
|
||
fx.children.push(g.into());
|
||
}
|
||
let tr = layer.transform_mut().ok_or("no transform")?;
|
||
for (t, v) in anchor_keys {
|
||
key(tr, "anchor", t, Value::Vec3(v));
|
||
}
|
||
let separated = tr.get("positionX").is_some();
|
||
for (t, v) in pos_keys {
|
||
if separated {
|
||
key(tr, "positionX", t, Value::Scalar(v[0]));
|
||
key(tr, "positionY", t, Value::Scalar(v[1]));
|
||
} else {
|
||
key(tr, "position", t, Value::Vec3(v));
|
||
}
|
||
}
|
||
for (t, v) in rot_keys {
|
||
key(tr, "rotation", t, Value::Scalar(v));
|
||
}
|
||
for (t, v) in scale_keys {
|
||
key(tr, "scale", t, Value::Vec3(v));
|
||
}
|
||
p.next_id = ids_next;
|
||
Ok(n)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn attach_points_follow_the_track() {
|
||
let rc = [[0.0, 0.0], [10.0, 0.0]];
|
||
let ra = [[0.0, 5.0], [10.0, 5.0]];
|
||
// Rotated 90° and doubled.
|
||
let cur = [[100.0, 100.0], [100.0, 120.0]];
|
||
let a = attach_points(TrackKind::Transform, true, &rc, &ra, &cur);
|
||
assert!((a[0][0] - 90.0).abs() < 1e-9 && (a[0][1] - 100.0).abs() < 1e-9, "{a:?}");
|
||
let a = attach_points(TrackKind::Transform, false, &rc, &ra, &cur);
|
||
assert_eq!(a[0], [100.0, 105.0]);
|
||
let h = trk::Homography([[1.1, 0.1, 5.0], [0.05, 0.9, -3.0], [0.001, 0.0005, 1.0]]);
|
||
let rc4 = [[0.0, 0.0], [100.0, 0.0], [0.0, 100.0], [100.0, 100.0]];
|
||
let ra4 = [[10.0, 10.0], [90.0, 10.0], [10.0, 90.0], [90.0, 90.0]];
|
||
let cur4: Vec<[f64; 2]> = rc4.iter().map(|p| h.apply(*p)).collect();
|
||
let a = attach_points(TrackKind::Perspective, false, &rc4, &ra4, &cur4);
|
||
for (got, want) in a.iter().zip(ra4.iter().map(|p| h.apply(*p))) {
|
||
assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6);
|
||
}
|
||
}
|
||
}
|