Skip to main content

brep_render/
features.rs

1//! Map kernel feature schemas to the shared [`FormField`] representation.
2//!
3//! Feature definitions come from [`brep_kernel::feature_schema_catalogue`].
4//! Parameters map to scalar, text, vector, choice, boolean, and reference fields;
5//! a boolean operation expands into operation, tool-selection, and merge fields.
6//! Transform start references are not surfaced here.
7
8use crate::style::{FieldKind, FormField};
9use serde_json::Value;
10use std::collections::{HashMap, HashSet};
11use std::sync::OnceLock;
12
13/// The catalogue, built ONCE per process. Every entry is static kernel data
14/// (each feature's `schema()` is a literal), so the first call pays the 40-odd
15/// `json!` constructions and every later read is a pointer. Before this cache
16/// the history tree rebuilt the whole catalogue for EVERY ROW it drew — a
17/// 633-component assembly spent ~1.7 s per frame on it, which is what made an
18/// imported STEP assembly impossible to orbit.
19fn cached_catalogue() -> &'static Value {
20    static CATALOGUE: OnceLock<Value> = OnceLock::new();
21    CATALOGUE.get_or_init(brep_kernel::feature_schema_catalogue)
22}
23
24/// `type` AND `shortName` → position in the catalogue's `features` array. Built
25/// in array order with first-match-wins, so a lookup answers exactly what a
26/// linear `find` over the array did.
27fn schema_index() -> &'static HashMap<String, usize> {
28    static INDEX: OnceLock<HashMap<String, usize>> = OnceLock::new();
29    INDEX.get_or_init(|| {
30        let mut index = HashMap::new();
31        if let Some(list) = cached_catalogue().get("features").and_then(Value::as_array) {
32            for (position, feature) in list.iter().enumerate() {
33                for key in ["type", "shortName"] {
34                    if let Some(name) = feature.get(key).and_then(Value::as_str) {
35                        index.entry(name.to_string()).or_insert(position);
36                    }
37                }
38            }
39        }
40        index
41    })
42}
43
44/// One feature's schema entry, borrowed from the cached catalogue.
45fn schema_entry(feature_type: &str) -> Option<&'static Value> {
46    let position = *schema_index().get(feature_type)?;
47    cached_catalogue().get("features")?.as_array()?.get(position)
48}
49
50/// The kernel-owned feature-schema catalogue (`{ version, features: [...] }`).
51/// A clone of the process-wide cache: callers that only READ it (the palette,
52/// the workbench toolbar, the context bar) pay one clone per call instead of
53/// the whole construction.
54pub fn feature_catalogue() -> Value {
55    cached_catalogue().clone()
56}
57
58/// One feature's full schema entry, by its `type` / `shortName` (e.g. `"P.CU"`,
59/// `"B"`). `None` if the type is not in the catalogue.
60pub fn feature_schema(feature_type: &str) -> Option<Value> {
61    schema_entry(feature_type).cloned()
62}
63
64/// The param keys this feature's dialog should HIDE for the given CURRENT
65/// `values` — the kernel's field-visibility hook ([`brep_kernel::feature_hidden_params`]),
66/// returned as a set so the form engine can skip a field in O(1). Empty when the
67/// feature declares no hook, so every field stays visible. The form engine
68/// recomputes this each frame from the live params, which is what makes fields
69/// appear and disappear as their governing field changes.
70pub fn feature_hidden_params(feature_type: &str, values: &Value) -> HashSet<String> {
71    brep_kernel::feature_hidden_params(feature_type, values)
72        .into_iter()
73        .collect()
74}
75
76/// Human display name for a feature type: the schema `longName` (else the type
77/// itself), with the feature's icon character PREPENDED. Every consumer that
78/// shows a feature name (add-feature palette, history tree, context-bar offers,
79/// dialogs) reads it through here, so the icon appears everywhere with no
80/// per-caller wiring — see [`feature_icon`].
81pub fn feature_long_name(feature_type: &str) -> String {
82    let name = feature_plain_name(feature_type);
83    match feature_icon(feature_type) {
84        Some(glyph) => format!("{glyph} {name}"),
85        None => name,
86    }
87}
88
89/// The same display name WITHOUT the leading glyph — the schema `longName`, else
90/// the type itself.
91///
92/// For the one kind of caller that draws the icon as ARTWORK rather than as a
93/// character: the history tree gives the icon its own column
94/// (`brep_app::panels::tree::TreeRow::glyph`), so its label must not carry the
95/// glyph a second time. Everything that shows a feature name as plain text
96/// keeps reading [`feature_long_name`], which is still where the icon is
97/// prepended.
98pub fn feature_plain_name(feature_type: &str) -> String {
99    schema_entry(feature_type)
100        .and_then(|f| f.get("longName").and_then(Value::as_str).map(String::from))
101        .unwrap_or_else(|| feature_type.to_string())
102}
103
104/// A feature type's SHORT name (`shortName`, e.g. `P.CU`, `S`, `E`), else the
105/// type code itself. This is the BASE for a new feature's id: the engine appends
106/// the part history's persistent global counter to it (`P.CU` → `P.CU7`,
107/// `S` → `S8`) in [`crate::history::History::next_feature_id`].
108pub fn feature_short_name(feature_type: &str) -> String {
109    schema_entry(feature_type)
110        .and_then(|f| f.get("shortName").and_then(Value::as_str).map(String::from))
111        .unwrap_or_else(|| feature_type.to_string())
112}
113
114/// The icon character for a feature type, if one exists. Every kernel
115/// feature type has a FreeCAD-inspired monoline glyph in the font's Private-Use
116/// block U+E030-E059 (edited as `BREP_app/assets/glyphs/*.svg`, which are also
117/// the source of the inline SVG icon catalog — see `BREP_app/src/icons.rs`;
118/// `every_feature_type_has_catalogued_artwork` there checks each of these
119/// codepoints actually HAS a glyph, which this module's own test cannot). The font is
120/// installed as family `"brep_icons"` at the HEAD of egui's fallback chain
121/// ([`crate`]-side `fonts.rs`), so a bare returned `char` renders as the icon.
122///
123/// Matches the SAME alias set the kernel dispatch does (short codes AND the
124/// long-/class-name strings saved files carry — e.g. `"CHAMFER"`, the misspelt
125/// `"DATIUM"`, `"PUSH FACE"`), uppercased, so a type loaded from disk resolves.
126pub fn feature_icon(kind: &str) -> Option<char> {
127    let cp: u32 = match kind.trim().to_ascii_uppercase().as_str() {
128        "D" | "DATUM" | "DATIUM" => 0xE030,
129        "P" | "PLANE" => 0xE031,
130        "P.CU" | "CUBE" => 0xE032,
131        "P.CY" | "CYLINDER" => 0xE033,
132        "P.CO" | "CONE" => 0xE034,
133        "P.S" | "SPHERE" => 0xE035,
134        "P.T" | "TORUS" => 0xE036,
135        "P.PY" | "PYRAMID" => 0xE037,
136        "NS" | "NURBS SOLID" | "NURBSSOLID" => 0xE05F,
137        "IMPORT3D" => 0xE038,
138        "S" | "SKETCH" => 0xE039,
139        "S3D" | "SKETCH3D" | "3D SKETCH" => 0xE0C6,
140        "SP" | "SPLINE" => 0xE03A,
141        "WP" | "WAYPOINT" => 0xE03B,
142        "WELD" => 0xE0D6,
143        "WELD.GROOVE" => 0xE0D8,
144        "WELD.SPOT" => 0xE0D9,
145        "WELD.RSEAM" => 0xE0DA,
146        "WELD.PLUG" => 0xE0DB,
147        "WELD.TACK" => 0xE0DC,
148        "WELD.EDGE" => 0xE0DD,
149        "WELD.CORNER" => 0xE0DE,
150        "WELD.SURF" => 0xE0DF,
151        "GEAR.SPUR" => 0xE0E4,
152        "GEAR.RACK" => 0xE0E5,
153        "GEAR.RING" => 0xE0E6,
154        "GEAR.SPROCKET" => 0xE0E7,
155        "GEAR.HELICAL" => 0xE0E8,
156        "GEAR.HERRINGBONE" => 0xE0E9,
157        "GEAR.SPLINE_STRAIGHT" => 0xE0EA,
158        "GEAR.SPLINE_INV" => 0xE0EB,
159        "GEAR.TIMING_PULLEY" => 0xE0EC,
160        "GEAR.RATCHET" => 0xE0ED,
161        "GEAR.GENEVA" => 0xE0EE,
162        "GEAR.WORM" => 0xE0EF,
163        "GEAR.CYCLO_DISC" => 0xE0F0,
164        "GEAR.CYCLO_RING" => 0xE0F1,
165        "GEAR.CYCLOIDAL" => 0xE0F2,
166        "GEAR.BEVEL" => 0xE0F3,
167        "GEAR.ELLIPTICAL" => 0xE0F4,
168        "GEAR.WORM_WHEEL" => 0xE0F5,
169        "GEAR.CROWN" => 0xE0F6,
170        "GEAR.LANTERN" => 0xE0F7,
171        "GEAR.STAR" => 0xE0F8,
172        "GEAR.BEVELOID" => 0xE0F9,
173        "GEAR.LOBED" => 0xE0FA,
174        "HX" | "HELIX" => 0xE03C,
175        "E" | "EXTRUDE" => 0xE03D,
176        "B" | "BOOLEAN" => 0xE03E,
177        "F" | "FILLET" => 0xE03F,
178        "CH" | "CHAMFER" => 0xE040,
179        "O.S" | "OFFSET SHELL" | "OFFSETSHELL" => 0xE041,
180        "O.F" | "OFFSET FACE" | "OFFSETFACE" => 0xE042,
181        "PF" | "PUSHFACE" | "PUSH FACE" => 0xE043,
182        "DF" | "DELETE FACE" | "DELETEFACE" => 0xE044,
183        "THK" | "THICKEN" => 0xE045,
184        "SM.TAB" => 0xE046,
185        "SM.CF" => 0xE047,
186        "SM.F" | "SM.CLOSED_CORNER" | "SM.CC" => 0xE048,
187        "SM.HEM" => 0xE049,
188        "SM.FILLET" | "SM.CFIL" => 0xE04A,
189        "SM.CHAMFER" | "SM.CCHM" => 0xE04B,
190        "SM.CUTOUT" => 0xE04C,
191        "LOFT" => 0xE04D,
192        "M" | "MIRROR" | "SM.MIRROR" | "SM.MI" => 0xE04E,
193        "SPL" | "SPLIT" => 0xE04F,
194        "R" | "REVOLVE" => 0xE050,
195        "RIB" => 0xE051,
196        "SW" | "SWEEP" => 0xE052,
197        "SWP" | "PATH SWEEP" | "PATHSWEEP" => 0xE053,
198        "H" | "HOLE" => 0xE054,
199        "TU" | "TUBE" => 0xE055,
200        "XFORM" | "TRANSFORM" => 0xE056,
201        "PATTERN" => 0xE057,
202        // The component pattern draws the part Pattern's artwork.
203        "APAT" | "PATTERN COMPONENT" => 0xE057,
204        "ACOMP" | "ASSEMBLY COMPONENT" => 0xE058,
205        "SM.UNFOLD" => 0xE059,
206        "TF" | "TRANSFORM FACE" | "TRANSFORMFACE" => 0xE05D,
207        "RFS" | "REFIT FACES" | "REFITFACES" => 0xE05E,
208        "DFF" | "DEFORM FACE" | "DEFORMFACE" => 0xE0E1,
209        "DRAFT" => 0xE0FB,
210        "SEW" | "SEW TO SOLID" | "SEWTOSOLID" => 0xE0E2,
211        "FILL" | "FILL SURFACE" | "FILLSURFACE" => 0xE0E0,
212        _ => return None,
213    };
214    char::from_u32(cp)
215}
216
217/// A feature type's DEFAULT `inputParams`, built from its schema: one entry per
218/// `inputParamsSchema` param seeded with that param's `default_value` (missing →
219/// `null`). The caller assigns the unique `id` afterwards (the schema's `id`
220/// default is `null`). Additive, engine-owned, and reusable by any "add feature"
221/// path so a new feature's params always track the kernel schema. Unknown types
222/// yield an empty object.
223pub fn feature_default_params(feature_type: &str) -> Value {
224    let mut params = serde_json::Map::new();
225    if let Some(props) = feature_schema(feature_type)
226        .as_ref()
227        .and_then(|s| s.get("inputParamsSchema"))
228        .and_then(Value::as_object)
229    {
230        for (name, spec) in props {
231            let default = spec.get("default_value").cloned().unwrap_or(Value::Null);
232            params.insert(name.clone(), default);
233        }
234    }
235    Value::Object(params)
236}
237
238/// The boolean operation choices (a fixed kernel enum — the schema stores only a
239/// default operation, not the variant set, so the known set rides here).
240const BOOLEAN_OPS: &[&str] = &["NONE", "UNION", "SUBTRACT", "INTERSECT"];
241
242/// Map a feature type's `inputParamsSchema` into the general form fields, in
243/// schema (insertion) order — the kernel builds schemas with serde_json's
244/// `preserve_order`, so grouped fields stay contiguous for the group headers.
245pub fn feature_form_fields(feature_type: &str) -> Vec<FormField> {
246    let Some(schema) = feature_schema(feature_type) else {
247        return Vec::new();
248    };
249    form_fields_from_schema(&schema)
250}
251
252/// The POINT PICK a feature form's button `key` (`pivot#pick`) runs: the vec3
253/// field's own path, its label (the picker's prompt) and the entity kinds its
254/// schema `selectionFilter` admits. `None` for any other key.
255pub fn point_pick_field(feature_type: &str, key: &str) -> Option<(Vec<String>, String, Vec<String>)> {
256    let name = key.strip_suffix(crate::engine_state::POINT_PICK_SUFFIX)?;
257    let schema = feature_schema(feature_type)?;
258    let spec = schema["inputParamsSchema"].get(name)?;
259    if spec["type"] != "vec3" {
260        return None;
261    }
262    let filter: Vec<String> = crate::json_support::string_values(spec.get("selectionFilter")).map(String::from).collect();
263    if filter.is_empty() {
264        return None;
265    }
266    Some((vec![name.to_string()], field_label(spec, name), filter))
267}
268
269/// Plugin numeric bounds are enforced when the user commits a scalar edit.
270/// Keep built-in expression fields on their existing scalar path; neither
271/// kind quantizes an authored value just because its form is displayed.
272pub fn plugin_form_fields_from_schema(schema: &Value) -> Vec<FormField> {
273    let mut fields = form_fields_from_schema(schema);
274    for field in &mut fields {
275        let Some(name) = field.path.first() else { continue };
276        let spec = &schema["inputParamsSchema"][name];
277        if spec["type"] == "number" && (spec.get("min").is_some() || spec.get("max").is_some()) {
278            field.kind = FieldKind::BoundedScalar {
279                min: spec["min"].as_f64().unwrap_or(-f64::MAX),
280                max: spec["max"].as_f64().unwrap_or(f64::MAX),
281                step: spec["step"].as_f64().unwrap_or(0.5),
282            };
283        }
284    }
285    fields
286}
287
288/// Map ANY schema entry carrying an `inputParamsSchema` object into form fields
289/// — the shared engine behind [`feature_form_fields`] AND the assembly
290/// constraint dialogs (whose schemas come from the kernel's
291/// `constraint_schema_catalogue`, same shape, different catalogue). One mapping,
292/// two catalogues (the schema-driven-dialog principle).
293pub fn form_fields_from_schema(schema: &Value) -> Vec<FormField> {
294    let Some(params) = schema
295        .get("inputParamsSchema")
296        .and_then(Value::as_object)
297    else {
298        return Vec::new();
299    };
300
301    let mut fields = Vec::new();
302    for (name, spec) in params {
303        let ty = spec.get("type").and_then(Value::as_str).unwrap_or("");
304        match ty {
305            "number" => fields.push(FormField {
306                path: vec![name.clone()],
307                label: field_label(spec, name),
308                group: "Parameters".into(),
309                kind: FieldKind::Scalar { step: 0.5 },
310            }),
311            "string" => fields.push(FormField {
312                path: vec![name.clone()],
313                label: field_label(spec, name),
314                group: "Parameters".into(),
315                // The `id` is the feature's identity; editing it must cascade to
316                // references, so it is shown read-only for now.
317                kind: FieldKind::Text {
318                    read_only: name == "id",
319                },
320            }),
321            "vec3" => {
322                // A BARE three-component vector param (Transform Face's
323                // `pivot`), as against the `transform` GROUP below: one
324                // labelled row of three expression-capable components, no
325                // rotation and no scale. The kernel reads it with the same
326                // `common::vec3_from_value` the transform components use, so a
327                // component may be a number or an expression either way.
328                let label = field_label(spec, name);
329                fields.push(FormField {
330                    path: vec![name.clone()],
331                    label: label.clone(),
332                    group: "Parameters".into(),
333                    kind: FieldKind::Vec3 { step: 0.5 },
334                });
335                // A vec3 that declares a `selectionFilter` may ALSO be filled
336                // by picking an entity of those kinds in the view: a button
337                // under the row, bound to no value, keyed `<name>#pick`; the
338                // host runs the pick (`EngineState::begin_point_pick`) and the
339                // pick writes the point into this same row.
340                if crate::json_support::string_values(spec.get("selectionFilter")).next().is_some() {
341                    fields.push(FormField {
342                        path: vec![format!("{name}{}", crate::engine_state::POINT_PICK_SUFFIX)],
343                        label: format!("Pick {}", label.to_lowercase()),
344                        group: "Parameters".into(),
345                        kind: FieldKind::Button { label: format!("Pick {} from a vertex, edge or face", label.to_lowercase()) },
346                    });
347                }
348            }
349            "transform" => {
350                // TWO transform param shapes share the `transform` schema type,
351                // discriminated by the schema's own `default_value` (the shape a
352                // fresh feature is seeded with, so it can never lie):
353                //   * the ACOMP rigid instance pose `{translate, rotateEulerDeg}`
354                //     (no scale, degrees, intrinsic XYZ);
355                //   * the modeling `{position, rotationEuler, scale}` triple every
356                //     modeling feature uses — WITHOUT its Scale row when the
357                //     default carries no `scale`, which is how a rigid-motion
358                //     feature (Transform Face) says scale means nothing to it.
359                // The mapping lives HERE (the form-engine altitude) so no dialog
360                // ever special-cases a feature type.
361                let is_rigid_pose = spec
362                    .get("default_value")
363                    .map(|d| d.get("translate").is_some() || d.get("rotateEulerDeg").is_some())
364                    .unwrap_or(false);
365                if is_rigid_pose {
366                    fields.push(vec3_field(name, "translate", "Translate", 0.5));
367                    fields.push(vec3_field(name, "rotateEulerDeg", "Rotation (deg)", 1.0));
368                } else {
369                    fields.push(vec3_field(name, "position", "Position", 0.5));
370                    fields.push(vec3_field(name, "rotationEuler", "Rotation (deg)", 1.0));
371                    let scales = spec
372                        .get("default_value")
373                        .map(|d| d.get("scale").is_some())
374                        .unwrap_or(true);
375                    if scales {
376                        fields.push(vec3_field(name, "scale", "Scale", 0.1));
377                    }
378                }
379            }
380            "color" => fields.push(FormField {
381                path: vec![name.clone()],
382                label: field_label(spec, name),
383                group: "Parameters".into(),
384                kind: FieldKind::Color,
385            }),
386            "boolean" => {
387                // A plain checkbox param (e.g. ACOMP `isFixed`, constraint
388                // `reverse`/`opposeNormals`/`exteriorAngle`). Label from the
389                // schema's `label` when present, else the prettified key.
390                fields.push(FormField {
391                    path: vec![name.clone()],
392                    label: field_label(spec, name),
393                    group: "Parameters".into(),
394                    kind: FieldKind::Bool,
395                });
396            }
397            "boolean_operation" => {
398                fields.push(FormField {
399                    path: vec![name.clone(), "operation".into()],
400                    label: "Operation".into(),
401                    group: "Boolean".into(),
402                    kind: FieldKind::Enum {
403                        variants: BOOLEAN_OPS.iter().map(|s| s.to_string()).collect(),
404                        labels: Vec::new(),
405                    },
406                });
407                fields.push(FormField {
408                    path: vec![name.clone(), "targets".into()],
409                    label: "Tool solids".into(),
410                    group: "Boolean".into(),
411                    kind: FieldKind::Reference {
412                        filter: vec!["SOLID".into()],
413                        multiple: true,
414                    },
415                });
416                fields.push(FormField {
417                    path: vec![name.clone(), "mergeCoplanarFaces".into()],
418                    label: "Merge coplanar faces".into(),
419                    group: "Boolean".into(),
420                    kind: FieldKind::Bool,
421                });
422            }
423            "button" => {
424                // An action button (e.g. Edit Sketch): binds to no value. Its
425                // `key` (the schema key) identifies the click to the host. The
426                // caption is the schema `label` (falling back to the key).
427                let label = field_label(spec, name);
428                fields.push(FormField {
429                    path: vec![name.clone()],
430                    label: label.clone(),
431                    group: "Parameters".into(),
432                    kind: FieldKind::Button { label },
433                });
434            }
435            "reference_selection" => {
436                let filter = crate::json_support::string_values(spec.get("selectionFilter"))
437                    .map(String::from)
438                    .collect();
439                let multiple = spec
440                    .get("multiple")
441                    .and_then(Value::as_bool)
442                    .unwrap_or(false);
443                // `"References"` is a SEMANTIC TAG, not a rendered wrapper: the
444                // history tree inlines this group (each reference renders as its
445                // own self-titled node — no "References" parent), and the context
446                // bar keys on it to find a feature's PRE-FILL fields (top-level
447                // `reference_selection`s, vs a boolean-op `targets` in `Boolean`;
448                // WHETHER a feature is offered is the kernel predicate's call —
449                // `feature_pipeline::context_offer`).
450                // The label is the schema's own, like every other kind: it is
451                // the form row's title AND, carried by the Select intent, the
452                // picker's prompt.
453                fields.push(FormField {
454                    path: vec![name.clone()],
455                    label: field_label(spec, name),
456                    group: "References".into(),
457                    kind: FieldKind::Reference { filter, multiple },
458                });
459            }
460            "options" => {
461                // A single-choice enum: render as a dropdown of the schema's
462                // `options`, using the field's `label` when present (e.g.
463                // flangeLengthReference → "Length reference", inset → "Flange
464                // position") else the prettified key.
465                let variants: Vec<String> = crate::json_support::string_values(spec.get("options"))
466                    .map(String::from)
467                    .collect();
468                // `optionLabels` maps a stored value to the words the box shows;
469                // the value itself is what is saved, so renaming a label never
470                // touches a file.
471                let labels = variants
472                    .iter()
473                    .map(|value| {
474                        spec.get("optionLabels")
475                            .and_then(|labels| labels.get(value))
476                            .and_then(Value::as_str)
477                            .unwrap_or(value)
478                            .to_string()
479                    })
480                    .collect();
481                fields.push(FormField {
482                    path: vec![name.clone()],
483                    label: field_label(spec, name),
484                    group: "Parameters".into(),
485                    kind: FieldKind::Enum { variants, labels },
486                });
487            }
488            // Unmapped kernel param types (vec3-array/etc. arrive as more
489            // features are wired) are skipped rather than mis-rendered.
490            _ => {}
491        }
492    }
493    fields
494}
495
496fn vec3_field(param: &str, sub: &str, label: &str, step: f64) -> FormField {
497    FormField {
498        path: vec![param.to_string(), sub.to_string()],
499        label: label.to_string(),
500        group: "Transform".into(),
501        kind: FieldKind::Vec3 { step },
502    }
503}
504
505/// A field's display label: the schema `label` when set, else the prettified key.
506///
507/// The ONE place a form label is made, for every field kind that has a schema
508/// key. The form row shows it and a reference field's Select carries it into the
509/// picker's prompt. The labels the engine writes itself (a transform's
510/// "Position", a boolean group's "Tool solids") have no schema key to read.
511fn field_label(spec: &Value, name: &str) -> String {
512    spec.get("label")
513        .and_then(Value::as_str)
514        .map(String::from)
515        .unwrap_or_else(|| prettify(name))
516}
517
518/// `sizeX` → `Size X`, `rotationEuler` → `Rotation euler`, `id` → `Id`.
519fn prettify(key: &str) -> String {
520    let mut out = String::new();
521    for (i, ch) in key.chars().enumerate() {
522        if i == 0 {
523            out.extend(ch.to_uppercase());
524        } else if ch.is_ascii_uppercase() {
525            out.push(' ');
526            out.extend(ch.to_lowercase());
527        } else {
528            out.push(ch);
529        }
530    }
531    out
532}
533