diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs index 701ee881..4a44381a 100644 --- a/crates/doc/src/publish.rs +++ b/crates/doc/src/publish.rs @@ -226,6 +226,8 @@ format_settings!( PngSequenceSettings, PublishFormat::PngSequence, false, { range: FrameRange = FrameRange::default(), scale: f32 = 1.0, + /// The stage colour behind each frame; off: transparent (#536). + background: bool = true, } ); format_settings!( @@ -234,6 +236,8 @@ format_settings!( /// The movie frame (0-based, every scene in order). frame: u32 = 0, scale: f32 = 1.0, + /// The stage colour behind it; off: transparent (#536). + background: bool = true, } ); format_settings!( diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs index 6be0a5f9..459b85b1 100644 --- a/crates/engine/src/anim_tests.rs +++ b/crates/engine/src/anim_tests.rs @@ -495,3 +495,34 @@ fn shared_apng_container_preserves_exact_wire_bytes() { assert!(apng_file(3, 2, 0, &[]).is_err()); assert!(apng_file(3, 2, 0, &[(&second, (1, 1))]).is_err()); } + +/// #536: Export Frame as PNG and Export PNG Sequence keep the stage colour by default, and +/// with `background: false` write real alpha: the empty stage is clear and the artwork opaque. +#[test] +fn png_frames_export_transparent_when_asked() { + let dir = tmp("png-alpha"); + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 200, "fill": "#ff0000", "stroke": null})); + // (corner pixel's alpha, the rectangle's middle pixel's alpha), at scale 0.5. + let alphas = |bytes: &[u8]| { + let px = anicraft_doc::decode_png(bytes).expect("a PNG"); + let a = |x: u32, y: u32| px.rgba[((y * px.width + x) * 4 + 3) as usize]; + (a(1, 1), a(100, 100)) + }; + for background in [true, false] { + let path = dir.join(format!("frame-{background}.png")); + run(&mut s, "file.export_png", json!({"path": path.display().to_string(), "scale": 0.5, "background": background})); + let (corner, art) = alphas(&std::fs::read(&path).unwrap()); + assert_eq!(art, 255, "the artwork is opaque either way"); + assert_eq!(corner == 255, background, "the empty stage: the stage colour, or clear"); + let seq = dir.join(format!("seq-{background}")); + run(&mut s, "file.export_png_sequence", json!({"dir": seq.display().to_string(), "scale": 0.5, "background": background})); + let (corner, _) = alphas(&std::fs::read(seq.join("frame_00001.png")).unwrap()); + assert_eq!(corner == 255, background, "the sequence too"); + } + // Left out, it is the stage colour, as before. + let path = dir.join("frame-default.png"); + run(&mut s, "file.export_png", json!({"path": path.display().to_string(), "scale": 0.5})); + assert_eq!(alphas(&std::fs::read(&path).unwrap()).0, 255); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 5b834a0c..4c6968b7 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { save(s, p) }, }, - CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame? (in the current scene), scale?}", mutates: false, run: export_png }, + CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame? (in the current scene), scale?, background? (default true: the stage colour; false: transparent)}", mutates: false, run: export_png }, CommandSpec { id: "file.import", label: "Import to Stage…", @@ -61,7 +61,7 @@ pub fn specs() -> Vec { label: "Export PNG Sequence…", menu: "File/Export", shortcut: None, - params: "{dir, from?, to? (movie frames: every scene in order), scale?}", + params: "{dir, from?, to? (movie frames: every scene in order), scale?, background? (default true: the stage colour; false: transparent)}", mutates: false, run: export_sequence, }, @@ -261,8 +261,18 @@ pub(crate) fn scale_param(p: &Value) -> Result { /// Renders movie frame `frame` (scenes in order) of `doc` to PNG bytes. pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result> { + render_png_on(doc, frame, scale, true) +} + +/// [`render_png`] with the stage colour behind the frame, or (`background` false) nothing: a +/// transparent PNG with real alpha (#536). +pub fn render_png_on(doc: &Document, frame: u32, scale: f32, background: bool) -> Result> { let dl = anicraft_doc::evaluate(doc, frame); - let (pm, _) = render(&dl, &View::stage(doc, scale))?; + let mut view = View::stage(doc, scale); + if !background { + view.background = None; + } + let (pm, _) = render(&dl, &view)?; Ok(pm.encode_png()?) } @@ -270,7 +280,8 @@ fn export_png(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); // `frame` is within the current scene; the renderer takes movie frames. - let bytes = render_png(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?)?; + let background = opt_bool(p, "background")?.unwrap_or(true); + let bytes = render_png_on(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?, background)?; crate::vfs::write(&path, &bytes)?; Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame})) } @@ -767,6 +778,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("'to' must not be before 'from'".into())); } let scale = scale_param(p)?; + let background = opt_bool(p, "background")?.unwrap_or(true); crate::vfs::create_dir_all(&dir)?; // Frames are independent: render and encode them in parallel (each render is itself // row-parallel; rayon balances both levels), a batch at a time so memory stays bounded. @@ -777,7 +789,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { let mut files = 0usize; let frames: Vec = (from..=to).collect(); for batch in frames.chunks(64) { - let pngs = batch.par_iter().map(|&f| render_png(doc, f, scale)).collect::>>()?; + let pngs = batch.par_iter().map(|&f| render_png_on(doc, f, scale, background)).collect::>>()?; for (f, png) in batch.iter().zip(pngs) { crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?; files += 1; diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs index 6b206131..412b66a2 100644 --- a/crates/engine/src/publish.rs +++ b/crates/engine/src/publish.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { label: "Publish Settings", menu: "", shortcut: None, - params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale, background (png_sequence); frame, scale, background (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", mutates: true, run: settings_set, }, @@ -248,6 +248,7 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) let q = &prof.png_sequence; let n = range_params(&mut p, q.range, last); p.insert("scale".into(), json!(q.scale)); + p.insert("background".into(), json!(q.background)); ("file.export_png_sequence", n, vec![out]) } PublishFormat::Png => { @@ -255,6 +256,7 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) scene = sc; p.insert("frame".into(), json!(local)); p.insert("scale".into(), json!(prof.png.scale)); + p.insert("background".into(), json!(prof.png.background)); ("file.export_png", 1, vec![out]) } PublishFormat::Svg => { @@ -564,8 +566,8 @@ fn option_keys(f: PublishFormat) -> &'static [&'static str] { PublishFormat::Video => &["from", "to", "scale", "audio"], PublishFormat::Lottie => &["from", "to", "background"], PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], - PublishFormat::PngSequence => &["from", "to", "scale"], - PublishFormat::Png => &["frame", "scale"], + PublishFormat::PngSequence => &["from", "to", "scale", "background"], + PublishFormat::Png => &["frame", "scale", "background"], PublishFormat::Svg => &["frame"], PublishFormat::Audio => &["from", "to", "rate", "bits"], } @@ -685,12 +687,14 @@ fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { PublishFormat::PngSequence => { set_range(&mut prof.png_sequence.range, p)?; set_scale(&mut prof.png_sequence.scale, p)?; + set_bool(&mut prof.png_sequence.background, p, "background")?; } PublishFormat::Png => { if let Some(fr) = opt_u32(p, "frame")? { prof.png.frame = fr.min(crate::MAX_FRAME); } set_scale(&mut prof.png.scale, p)?; + set_bool(&mut prof.png.background, p, "background")?; } PublishFormat::Svg => { if let Some(fr) = opt_u32(p, "frame")? { diff --git a/docs/guide/exporting-and-publish.md b/docs/guide/exporting-and-publish.md index 273d1433..a7c1a554 100644 --- a/docs/guide/exporting-and-publish.md +++ b/docs/guide/exporting-and-publish.md @@ -47,8 +47,10 @@ exported frames of its kind. ### Stills and sequences -* **PNG image** and **PNG sequence** have real transparency where the stage has nothing, and - can be scaled up to 800 %. The sequence writes `frame_00001.png` and on into its folder. +* **PNG image** and **PNG sequence** show the stage colour behind the artwork. Turn off + **Stage colour as background** in Publish Settings (or pass `background: false`) for real + transparency where the stage has nothing. Both can be scaled up to 800 %. The sequence writes + `frame_00001.png` and on into its folder. * **SVG image** writes one frame as a standalone vector drawing that matches the stage: shapes, strokes, gradients, masks (as clip paths), filters (as SVG filters) and blend modes. Bitmaps are embedded. @@ -151,8 +153,8 @@ work. Your choices are saved in the document, and every change can be undone. | Video | Frames, Scale, Include sound | | Lottie | Frames, Stage colour as background | | Sprite sheet | Frames, Scale, Columns, Padding, Stage colour as background | -| PNG sequence | Frames, Scale | -| PNG image | Frame (or **Playhead**), Scale | +| PNG sequence | Frames, Scale, Stage colour as background | +| PNG image | Frame (or **Playhead**), Scale, Stage colour as background | | SVG image | Frame (or **Playhead**) | | Audio | Frames, Sample rate, Bit depth | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 3068d543..6d2ebf55 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -21,7 +21,7 @@ This page is generated from the command registry, so it always matches the versi - **Save as Template…** `file.save_as_template` Parameters: `{folder (the user templates folder), name, category? (default “My Templates”), confirm? (to replace a template of that name)} → {path, thumbnail}: the document as it is, kept as //.anicraft with a picture of its first frame; the open document is unchanged` - **Export Frame as PNG…** `file.export_png` · File › Export - Parameters: `{path, frame? (in the current scene), scale?}` + Parameters: `{path, frame? (in the current scene), scale?, background? (default true: the stage colour; false: transparent)}` - **Import to Stage…** `file.import` · File › Import · **Ctrl+R** (macOS **⌘R**) · changes the document Parameters: `{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}` - **Export Frame as SVG…** `file.export_svg` · File › Export @@ -31,7 +31,7 @@ This page is generated from the command registry, so it always matches the versi - **Export Sprite Sheet…** `file.export_sprite_sheet` · File › Export Parameters: `{path (.png; the frame map goes beside it as .json), from?, to? (movie frames), scale?, columns?, padding?, background?, confirm?}` - **Export PNG Sequence…** `file.export_png_sequence` · File › Export - Parameters: `{dir, from?, to? (movie frames: every scene in order), scale?}` + Parameters: `{dir, from?, to? (movie frames: every scene in order), scale?, background? (default true: the stage colour; false: transparent)}` - **Export SVG Sequence…** `file.export_svg_sequence` · File › Export Parameters: `{dir, from?, to? (movie frames: every scene in order), confirm?} → one frame_00001.svg per frame (vectors, gradients and masks kept)` - **Export Animated GIF…** `file.export_gif` · File › Export @@ -322,7 +322,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Close Envelope** `modify.envelope_close` · changes the document Parameters: `{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}` - **Publish Settings** `publish.settings_set` · changes the document - Parameters: `{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}` + Parameters: `{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale, background (png_sequence); frame, scale, background (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}` - **Open Recent** `file.open_recent` Parameters: `{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing` - **Recent Files** `file.recent_list` diff --git a/src/publish_panel.rs b/src/publish_panel.rs index 238202b2..cae52dc5 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -525,11 +525,13 @@ fn options(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) { PublishFormat::PngSequence => { range_row(app, ui, f, p.png_sequence.range); scale_row(app, ui, f, p.png_sequence.scale); + check(app, ui, f, "background", p.png_sequence.background, tr!("Stage colour as background"), tr!("Off: transparent")); form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("The output is a folder; the frames in it are frame_00001.png and on."))); } PublishFormat::Png => { frame_row(app, ui, f, p.png.frame); scale_row(app, ui, f, p.png.scale); + check(app, ui, f, "background", p.png.background, tr!("Stage colour as background"), tr!("Off: transparent")); } PublishFormat::Svg => frame_row(app, ui, f, p.svg.frame), PublishFormat::Audio => {