BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Screen capture through egui's own screenshot path: `ViewportCommand::Screenshot`
//! in the mutate phase, completed by the matching `Event::Screenshot` in a later
//! frame's input phase (§5). The headless host renders directly instead and
//! answers this command itself; the window and dial-in hosts go through here.
use crate::automation::command::{app_command, parse_args, schema_of, CommandSpec, Ctx, Empty, Outcome};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

/// What to capture: the whole surface, the 3D viewport, or a rect in points.
#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum Region {
    /// `"full"` or `"viewport"`
    Named(String),
    Rect { x: f32, y: f32, w: f32, h: f32 },
}

impl Default for Region {
    fn default() -> Self {
        Region::Named("full".into())
    }
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenshotArgs {
    #[serde(default)]
    pub region: Region,
    /// Render the capture natively at this multiple of the window's pixel
    /// density (1 = the window's own pixels, the default): the same layout in
    /// points, the 3D view, PMI and the ViewCube drawn at `scale` × the
    /// pixels, never an upscale of the window's frame. The window is not
    /// resized. At most one of `scale`, `width` and `height`.
    pub scale: Option<f32>,
    /// The PNG's exact pixel width: the scale is `width` / the region's
    /// width at 1×, and the height follows it (same framing).
    pub width: Option<u32>,
    /// The PNG's exact pixel height (the width follows it).
    pub height: Option<u32>,
}

/// The app `screenshot` command's arguments for a host capture request:
/// the region plus the resolution's `scale` / `width` / `height`.
pub fn screenshot_args(region: Value, resolution: Value) -> Value {
    let mut args = json!({ "region": region });
    if let Value::Object(fields) = resolution {
        for key in ["scale", "width", "height"] {
            if let Some(v) = fields.get(key).filter(|v| !v.is_null()) {
                args[key] = v.clone();
            }
        }
    }
    args
}

/// The most a capture may be scaled: past this a 4K window passes the
/// 16 384 px texture limit anyway, and the pass's buffers grow with its square.
pub const MAX_CAPTURE_SCALE: f32 = 8.0;

/// The render scale a screenshot asks for, from its `scale` / `width` /
/// `height`, given the window's density `ppp`, the last viewport rect and the
/// surface's pixel size at 1×. `1.0` is the window's own capture.
pub fn capture_scale(a: &ScreenshotArgs, ppp: f32, view: Option<egui::Rect>, w: u32, h: u32, max_side: Option<u32>) -> Result<f32, String> {
    let given = [a.scale.is_some(), a.width.is_some(), a.height.is_some()].iter().filter(|g| **g).count();
    if given > 1 {
        return Err("bad_args: give at most one of scale, width and height".into());
    }
    let (_, _, cw, ch, _) = region_px(&a.region, ppp, view, w, h)?;
    let scale = match (a.scale, a.width, a.height) {
        (Some(s), _, _) => s,
        (_, Some(px), _) => px as f32 / cw as f32,
        (_, _, Some(px)) => px as f32 / ch as f32,
        _ => 1.0,
    };
    if !(scale.is_finite() && scale > 0.0 && scale <= MAX_CAPTURE_SCALE) {
        return Err(format!("bad_args: the capture scale must be in (0, {MAX_CAPTURE_SCALE}] (got {scale})"));
    }
    if let Some(side) = max_side {
        let big = ((w.max(h) as f32) * scale).round() as u32;
        if big > side {
            return Err(format!("capture_too_large: {scale}x renders the {w}x{h} px surface at {big} px, past this device's {side} px texture limit"));
        }
    }
    Ok(scale)
}

#[derive(Serialize, schemars::JsonSchema)]
pub struct ScreenshotInfo {
    /// Pixel size of the PNG carried beside this reply.
    pub width: u32,
    pub height: u32,
    pub ppp: f32,
    /// The render scale over the window's density (1 for an ordinary capture);
    /// `ppp` is the density the PNG was drawn at, window ppp × scale.
    pub scale: f32,
    /// The captured rect in egui points.
    pub region: [f32; 4],
    pub png_bytes: usize,
    /// The document the image shows, `{documentId, revision}` as drawn in the
    /// captured frame (null for a capture taken outside an app frame).
    pub document: Option<Value>,
}

/// Resolve a region to a pixel rect on a `w`×`h` image at `ppp`.
pub fn region_px(region: &Region, ppp: f32, view: Option<egui::Rect>, w: u32, h: u32) -> Result<(u32, u32, u32, u32, [f32; 4]), String> {
    let pts = match region {
        Region::Named(n) if n == "full" => [0.0, 0.0, w as f32 / ppp, h as f32 / ppp],
        Region::Named(n) if n == "viewport" => {
            let r = view.ok_or("no viewport rect: the 3D view was not drawn last frame")?;
            [r.min.x, r.min.y, r.width(), r.height()]
        }
        Region::Named(n) => return Err(format!("unknown region `{n}` (full | viewport | {{x,y,w,h}})")),
        Region::Rect { x, y, w, h } => [*x, *y, *w, *h],
    };
    let px = |v: f32| (v * ppp).round().max(0.0) as u32;
    let x0 = px(pts[0]).min(w.saturating_sub(1));
    let y0 = px(pts[1]).min(h.saturating_sub(1));
    let cw = px(pts[2]).clamp(1, w - x0);
    let ch = px(pts[3]).clamp(1, h - y0);
    Ok((x0, y0, cw, ch, pts))
}

/// Encode a captured frame (cropped to `region`) as PNG.
pub fn encode_capture(image: &egui::ColorImage, ppp: f32, view: Option<egui::Rect>, region: &Region) -> Result<(Value, Vec<u8>), String> {
    encode_capture_scaled(image, ppp, 1.0, view, region)
}

/// The pixel crop of `region` on a frame drawn at `scale` × `ppp`: the crop
/// the window's own `w`×`h` px frame would take, scaled, so a 3× capture is
/// exactly 3× the 1× one (rounding the points rect at the scaled density
/// could differ from it by a pixel).
pub fn scaled_region_px(region: &Region, ppp: f32, scale: f32, view: Option<egui::Rect>, w: u32, h: u32) -> Result<(u32, u32, u32, u32, [f32; 4]), String> {
    if scale == 1.0 {
        return region_px(region, ppp, view, w, h);
    }
    let base = |v: u32| (v as f32 / scale).round().max(1.0) as u32;
    let (x0, y0, cw, ch, pts) = region_px(region, ppp, view, base(w), base(h))?;
    let px = |v: u32| (v as f32 * scale).round() as u32;
    let (x0, y0) = (px(x0).min(w.saturating_sub(1)), px(y0).min(h.saturating_sub(1)));
    Ok((x0, y0, px(cw).clamp(1, w - x0), px(ch).clamp(1, h - y0), pts))
}

/// Encode a frame drawn at `scale` × the window's density `ppp`, cropped to
/// `region` (see [`scaled_region_px`]).
pub fn encode_capture_scaled(image: &egui::ColorImage, ppp: f32, scale: f32, view: Option<egui::Rect>, region: &Region) -> Result<(Value, Vec<u8>), String> {
    let (w, h) = (image.width() as u32, image.height() as u32);
    let (x0, y0, cw, ch, pts) = scaled_region_px(region, ppp, scale, view, w, h)?;
    let full = image::RgbaImage::from_raw(w, h, image.as_raw().to_vec()).ok_or("frame buffer size mismatch")?;
    let cropped = image::imageops::crop_imm(&full, x0, y0, cw, ch).to_image();
    let mut out = std::io::Cursor::new(Vec::new());
    cropped.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("png encode: {e}"))?;
    let png = out.into_inner();
    let info = ScreenshotInfo { width: cw, height: ch, ppp: ppp * scale, scale, region: pts, png_bytes: png.len(), document: None };
    Ok((serde_json::to_value(info).map_err(|e| e.to_string())?, png))
}

fn screenshot(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: ScreenshotArgs = parse_args(args)?;
    let queue = ctx.app.automation.clone();
    // The window's own density: inside a scaled pass the context's is the
    // pass's, `scale` × the window's.
    let ppp = ctx.egui.pixels_per_point() / queue.pass_scale();
    let size = ctx.egui.content_rect().size() * ppp;
    let max_side = Some(ctx.egui.input(|i| i.max_texture_side) as u32);
    let scale = capture_scale(&a, ppp, ctx.app.view_rect(), size.x.round() as u32, size.y.round() as u32, max_side)?;
    let token = queue.next_token();
    if scale == 1.0 {
        ctx.egui.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(token)));
    } else if !queue.request_scaled_capture(token, scale) {
        return Err("unsupported: this host cannot render a scaled capture (scale, width and height are native desktop and headless only); capture at scale 1".into());
    }
    let document = Some(ctx.app.docs.view().handle().to_string());
    Ok(Outcome::AwaitScreenshot { token, region: a.region, document, ppp, scale })
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct IllustrationArgs {
    /// begin | view | end. Normally orchestrated by illustration_capture_many.
    pub action: String,
    pub document_id: Option<u64>,
    pub view: Option<Value>,
}

fn illustration_presentation(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: IllustrationArgs = parse_args(args)?;
    if let Some(id) = a.document_id {
        let index = ctx.app.docs.iter().position(|d| d.id() == id).ok_or("illustration document is no longer open")?;
        ctx.app.docs.activate(index);
    }
    let id = ctx.app.docs.active_id();
    let engine = ctx.app.docs.engine_mut();
    match a.action.as_str() {
        "begin" => { engine.illustration_begin()?; Ok(Outcome::Done(json!({"document_id":id}))) },
        "view" => engine.illustration_apply(&a.view.unwrap_or(json!({}))).map(Outcome::Done),
        "end" => { engine.illustration_end()?; Ok(Outcome::Done(json!({"restored":true,"document_id":id}))) },
        _ => Err("action must be begin, view or end".into()),
    }
}

pub static COMMANDS: &[CommandSpec] = &[
    app_command!("capture", "illustration_presentation", "Internal presentation loan for illustration_capture_many: preserves camera, full selection, display settings, saved-view state and display transforms without editing history or creating documents.", IllustrationArgs, illustration_presentation, Mutate, MUTATE_NOWAIT, schema_of::<Empty>),
    app_command!("capture", "screenshot", "Capture the composited frame (egui chrome and the 3D view) as PNG: region `full` (default), `viewport`, or `{x,y,w,h}` in egui points. `scale` (or an exact `width` / `height` in pixels) renders it natively at that multiple of the window's density, with the same layout, camera, PMI and ViewCube positions, without resizing the window. The PNG rides beside the JSON reply.", ScreenshotArgs, screenshot, Mutate, READ, schema_of::<ScreenshotInfo>),
];

#[allow(dead_code)]
fn _unused(_: Value) -> Value {
    json!({})
}