BREP_app 0.35.0

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
//! The sketch being edited: corner fillet and chamfer by point id (the same
//! edits the Fillet corner and Chamfer corner tools make on a click), a
//! dimension's value (what typing into its label does), the Issues list (its
//! rows, and what clicking and deleting a row does) and the freedom readout.
use crate::automation::command::{app_command, parse_args, CommandSpec, Ctx, Outcome};
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct FilletCornerArgs {
    /// The corner: the id of the point two lines share (`__brepSketch` lists the
    /// sketch's points through the entity list).
    pub point: Value,
    /// The fillet radius (mm).
    pub radius: f64,
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ChamferCornerArgs {
    /// The corner: the id of the point two lines share.
    pub point: Value,
    /// The distance from the corner along the first line (mm); along both
    /// when no `angle` is given.
    pub distance: f64,
    /// The cut's angle to the first line in degrees (Distance + angle); omit
    /// for an equal-distance chamfer.
    #[serde(default)]
    pub angle: Option<f64>,
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SetDimensionArgs {
    /// The dimension's constraint id (`__brepSketch` lists the dimensions).
    pub constraint: Value,
    /// The value as typed into its label: a number or an expression.
    pub value: String,
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct IssueArgs {
    /// The constraint an Issues row names (`sketch.issues` lists them).
    pub constraint: Value,
    /// Add to the selection instead of replacing it (a Ctrl/Cmd click on the row).
    #[serde(default)]
    pub additive: bool,
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DeleteIssueArgs {
    /// The constraint an Issues row names.
    pub constraint: Value,
}

fn issues_result_schema() -> Value {
    json!({"type":"object","properties":{
        "issues":{"type":"array","items":{"type":"object","properties":{
            "constraint":{"description":"The constraint id the row names."},
            "label":{"type":"string","description":"The row as the list shows it."},
            "problem":{"type":"string","enum":["conflicting","redundant"]},
            "selected":{"type":"boolean"}
        },"required":["constraint","label","problem","selected"],"additionalProperties":false}},
        "constraintCount":{"type":"integer"}
    },"required":["issues","constraintCount"],"additionalProperties":false})
}

fn freedom_result_schema() -> Value {
    json!({"type":"object","properties":{
        "state":{"type":"string","enum":["conflicting","over","under","full"]},
        "label":{"type":"string","description":"The status bar's readout text."},
        "dof":{"type":"integer"},
        "redundant":{"type":"integer"},
        "conflictingConstraints":{"type":"array"},
        "redundantConstraints":{"type":"array"},
        "pointFreedom":{"description":"Each movable point's free directions."},
        "hoverFreedom":{"description":"The hovered entity's freedom line, or null."}
    },"required":["state","label","dof","redundant","conflictingConstraints","redundantConstraints","pointFreedom","hoverFreedom"],"additionalProperties":false})
}

/// The Issues list as the panel shows it: conflicting rows first, then redundant.
fn issue_rows(ctx: &Ctx<'_>) -> Result<Value, String> {
    let engine = ctx.app.docs.engine();
    let Some(session) = engine.sketch_edit_session() else {
        return Err("no sketch is being edited".to_string());
    };
    let diag = &session.diagnostics;
    let issues: Vec<Value> = engine
        .sketch_issue_rows()
        .into_iter()
        .map(|row| {
            let problem = if diag.constraint_conflicting(&row.id) { "conflicting" } else { "redundant" };
            json!({ "constraint": row.id, "label": row.label, "problem": problem, "selected": row.selected })
        })
        .collect();
    Ok(json!({ "issues": issues, "constraintCount": session.doc.constraints.len() }))
}

/// Whether `id` names a row of the Issues list (compared as the solver keys ids).
fn is_issue(ctx: &Ctx<'_>, id: &Value) -> bool {
    let key = brep_render::brep_kernel::sketch_id_key(id);
    ctx.app.docs.engine().sketch_issue_rows().iter().any(|r| brep_render::brep_kernel::sketch_id_key(&r.id) == key)
}

fn issues(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let _: crate::automation::command::NoArgs = parse_args(args)?;
    Ok(Outcome::Done(issue_rows(ctx)?))
}

fn select_issue(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: IssueArgs = parse_args(args)?;
    issue_rows(ctx)?;
    if !is_issue(ctx, &a.constraint) {
        return Err(format!("constraint {} is not in the Issues list", a.constraint));
    }
    ctx.app.docs.engine_mut().sketch_select_entity("constraint", a.constraint, a.additive);
    Ok(Outcome::Done(issue_rows(ctx)?))
}

fn delete_issue(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: DeleteIssueArgs = parse_args(args)?;
    issue_rows(ctx)?;
    if !is_issue(ctx, &a.constraint) {
        return Err(format!("constraint {} is not in the Issues list", a.constraint));
    }
    if !ctx.app.docs.engine_mut().sketch_delete_entity("constraint", a.constraint.clone()) {
        return Err(format!("constraint {} could not be deleted", a.constraint));
    }
    Ok(Outcome::Done(issue_rows(ctx)?))
}

fn freedom(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let _: crate::automation::command::NoArgs = parse_args(args)?;
    let engine = ctx.app.docs.engine();
    let Some(session) = engine.sketch_edit_session() else {
        return Err("no sketch is being edited".to_string());
    };
    let diag = &session.diagnostics;
    let (state, label) = crate::panels::sketch::readout(diag);
    Ok(Outcome::Done(json!({
        "state": state,
        "label": label,
        "dof": diag.dof,
        "redundant": diag.redundant,
        "conflictingConstraints": diag.conflicting_constraints,
        "redundantConstraints": diag.redundant_constraints,
        "pointFreedom": serde_json::to_value(&diag.point_freedom).unwrap_or_default(),
        "hoverFreedom": engine.sketch_hover_freedom_label(),
    })))
}

fn corner_result_schema() -> Value {
    json!({"type":"object","properties":{
        "geometryCount":{"type":"integer"},
        "constraintCount":{"type":"integer"}
    },"required":["geometryCount","constraintCount"],"additionalProperties":false})
}

fn counts(ctx: &Ctx<'_>) -> Value {
    let session = ctx.app.docs.engine().sketch_edit_session();
    json!({
        "geometryCount": session.map_or(0, |s| s.doc.geometries.len()),
        "constraintCount": session.map_or(0, |s| s.doc.constraints.len()),
    })
}

fn fillet_corner(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: FilletCornerArgs = parse_args(args)?;
    if !ctx.app.docs.engine().sketch_mode() {
        return Err("no sketch is being edited".to_string());
    }
    ctx.app.docs.engine_mut().sketch_fillet_corner(&a.point, a.radius)?;
    Ok(Outcome::Done(counts(ctx)))
}

fn chamfer_corner(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: ChamferCornerArgs = parse_args(args)?;
    if !ctx.app.docs.engine().sketch_mode() {
        return Err("no sketch is being edited".to_string());
    }
    ctx.app.docs.engine_mut().sketch_chamfer_corner(&a.point, a.distance, a.angle)?;
    Ok(Outcome::Done(counts(ctx)))
}

fn set_dimension(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: SetDimensionArgs = parse_args(args)?;
    if !ctx.app.docs.engine().sketch_mode() {
        return Err("no sketch is being edited".to_string());
    }
    if !ctx.app.docs.engine_mut().sketch_set_dimension_value(&a.constraint, &a.value) {
        return Err(format!("the dimension {} did not take the value {:?}", a.constraint, a.value));
    }
    Ok(Outcome::Done(counts(ctx)))
}

fn undo(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let _: crate::automation::command::NoArgs = parse_args(args)?;
    if !ctx.app.docs.engine().sketch_mode() {
        return Err("no sketch is being edited".to_string());
    }
    if !ctx.app.docs.engine_mut().sketch_undo() {
        return Err("nothing to undo in the sketch".to_string());
    }
    Ok(Outcome::Done(counts(ctx)))
}

fn redo(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let _: crate::automation::command::NoArgs = parse_args(args)?;
    if !ctx.app.docs.engine().sketch_mode() {
        return Err("no sketch is being edited".to_string());
    }
    if !ctx.app.docs.engine_mut().sketch_redo() {
        return Err("nothing to redo in the sketch".to_string());
    }
    Ok(Outcome::Done(counts(ctx)))
}

pub static COMMANDS: &[CommandSpec] = &[
    app_command!("sketch", "fillet_corner", "Round the corner two lines of the edited sketch share (its point id) with a tangent arc of `radius`: one undoable edit, the arc tangent to both lines with a radius dimension; refuses by name (radius too large, parallel lines, no shared corner) and then changes nothing.", FilletCornerArgs, fillet_corner, Mutate, MUTATE_NOWAIT, corner_result_schema),
    app_command!("sketch", "set_dimension", "Set a dimension of the edited sketch (its constraint id) to `value`, a number or an expression, as typing into its label does; one undoable edit, then the sketch re-solves.", SetDimensionArgs, set_dimension, Mutate, MUTATE_NOWAIT, corner_result_schema),
    app_command!("sketch", "undo_edit", "Undo the edited sketch's last edit (the sketch's own history, which Ctrl+Z drives while a sketch is open).", crate::automation::command::NoArgs, undo, Mutate, MUTATE_NOWAIT, corner_result_schema),
    app_command!("sketch", "redo_edit", "Redo the edited sketch's last undone edit.", crate::automation::command::NoArgs, redo, Mutate, MUTATE_NOWAIT, corner_result_schema),
    app_command!("sketch", "issues", "The edited sketch's Issues list as the entity list shows it: each conflicting, then each redundant constraint, with its row label and whether it is selected.", crate::automation::command::NoArgs, issues, Read, READ, issues_result_schema),
    app_command!("sketch", "select_issue", "Select the constraint an Issues row names, as clicking the row does (`additive`: a Ctrl/Cmd click); refuses a constraint the list does not show. Answers the list after.", IssueArgs, select_issue, Mutate, MUTATE_NOWAIT, issues_result_schema),
    app_command!("sketch", "delete_issue", "Delete the constraint an Issues row names, as the row's ✕ does: one undoable edit, then the sketch re-solves; refuses a constraint the list does not show. Answers the list after.", DeleteIssueArgs, delete_issue, Mutate, MUTATE_NOWAIT, issues_result_schema),
    app_command!("sketch", "freedom", "The edited sketch's freedom readout: the status bar's state and text (conflicting / over-constrained / under-constrained with its DOF / fully constrained), the redundant and conflicting constraints, each movable point's free directions and the hovered entity's freedom line.", crate::automation::command::NoArgs, freedom, Read, READ, freedom_result_schema),
    app_command!("sketch", "chamfer_corner", "Cut the corner two lines of the edited sketch share (its point id) with a straight line: `distance` along both lines, or with `angle` the distance along the first and the cut at that angle to it; one undoable edit with the dimension(s) as constraints; refuses by name and then changes nothing.", ChamferCornerArgs, chamfer_corner, Mutate, MUTATE_NOWAIT, corner_result_schema),
];