diff --git a/assets/locales/pending/gear-insert.json b/assets/locales/pending/gear-insert.json new file mode 100644 index 00000000000..84b975d4ec1 --- /dev/null +++ b/assets/locales/pending/gear-insert.json @@ -0,0 +1,250 @@ +{ + "ar": { + "cmd.gear_edit": "تحرير ترس", + "cmd.gear_insert": "إدراج ترس", + "gear.backlash": "الخلوص بين الأسنان", + "gear.backlash_thicker": "يزيد الخلوص من سماكة الأسنان", + "gear.base_diameter": "قطر دائرة الأساس", + "gear.bore_diameter": "قطر ثقب المحور", + "gear.bore_offset": "إزاحة ثقب المحور", + "gear.clearance": "الخلوص (× المعامل)", + "gear.double_helical": "حلزوني مزدوج", + "gear.face_width": "عرض السن", + "gear.flank_points": "دقة الشكل (نقاط لكل جانب)", + "gear.helix_angle": "زاوية الحلزون", + "gear.internal": "ترس داخلي", + "gear.module": "المقياس", + "gear.pitch_diameter": "قطر دائرة الخطوة", + "gear.preset_helical": "حلزوني", + "gear.preset_herringbone": "رأس السهم", + "gear.preset_ring": "حلقي", + "gear.preset_spur": "مستقيم", + "gear.presets": "البدء من", + "gear.pressure_angle": "زاوية الضغط", + "gear.profile_shift": "إزاحة المنحنى", + "gear.reset": "إعادة ضبط", + "gear.rim_thickness": "سماكة الحلقة", + "gear.root_diameter": "قطر دائرة الجذر", + "gear.teeth": "عدد الأسنان", + "gear.tip_diameter": "القطر الخارجي", + "help.gear.edit": "يعدّل ترسًا أدرجته: غيّر المقياس أو عدد الأسنان أو زاوية الضغط أو العرض أو الحلزون أو الخلوص أو التدوير أو الثقب فيُعاد بناء الترس في مكانه. استخدمه بدل الحذف وإعادة الإدراج ليحتفظ باقي التصميم بمراجعه.", + "help.gear.insert": "يدرج ترسًا أسطوانيًا مستقيم أو حلزوني الأسنان بمنحنى ملتف، خارجيًا أو داخليًا، كمكوّن جديد. تحدد المقياس وعدد الأسنان وزاوية الضغط وعرض السن، ويمكنك إضافة زاوية حلزون أو أسنان حلزونية مزدوجة أو ثقب محور أو حلقة داخلية؛ تُرسم الأسنان وتُمسح كأي ميزة أخرى." + }, + "de": { + "cmd.gear_edit": "Zahnrad bearbeiten", + "cmd.gear_insert": "Zahnrad einfügen", + "gear.backlash": "Flankenspiel", + "gear.backlash_thicker": "Flankenspiel macht die Zähne dicker", + "gear.base_diameter": "Grundkreisdurchmesser", + "gear.bore_diameter": "Wellenbohrung (Durchmesser)", + "gear.bore_offset": "Versatz der Wellenbohrung", + "gear.clearance": "Kopfspiel (× Modul)", + "gear.double_helical": "Doppelschräg", + "gear.face_width": "Zahnbreite", + "gear.flank_points": "Profilgenauigkeit (Punkte je Flanke)", + "gear.helix_angle": "Schrägungswinkel", + "gear.internal": "Innenzahnrad", + "gear.module": "Modul", + "gear.pitch_diameter": "Teilkreisdurchmesser", + "gear.preset_helical": "Schräg", + "gear.preset_herringbone": "Pfeil", + "gear.preset_ring": "Hohlrad", + "gear.preset_spur": "Gerade", + "gear.presets": "Ausgangspunkt", + "gear.pressure_angle": "Eingriffswinkel", + "gear.profile_shift": "Profilverschiebung", + "gear.reset": "Zurücksetzen", + "gear.rim_thickness": "Kranzdicke", + "gear.root_diameter": "Fußkreisdurchmesser", + "gear.teeth": "Zähnezahl", + "gear.tip_diameter": "Kopfkreisdurchmesser", + "help.gear.edit": "Bearbeitet ein eingefügtes Zahnrad: Modul, Zähnezahl, Eingriffswinkel, Breite, Schrägung, Kopfspiel, Verrundung oder Bohrung ändern, und das Zahnrad wird an Ort und Stelle neu aufgebaut. Nutzen Sie es statt Löschen und erneut Einfügen, damit der Rest des Entwurfs seine Bezüge behält.", + "help.gear.insert": "Fügt ein Evolventen-Stirnrad (gerad- oder schrägverzahnt), außen- oder innenverzahnt, als neues Bauteil ein. Sie geben Modul, Zähnezahl, Eingriffswinkel und Zahnbreite an und können einen Schrägungswinkel, Doppelschrägverzahnung, eine Wellenbohrung oder einen Innenkranz hinzufügen; die Zähne werden wie jedes andere Feature skizziert und gesweept." + }, + "en": { + "cmd.gear_edit": "Edit Gear", + "cmd.gear_insert": "Insert Gear", + "gear.backlash": "Backlash", + "gear.backlash_thicker": "Backlash thickens the teeth", + "gear.base_diameter": "Base diameter", + "gear.bore_diameter": "Axle hole diameter", + "gear.bore_offset": "Axle hole offset", + "gear.clearance": "Clearance (× module)", + "gear.double_helical": "Double helical", + "gear.face_width": "Face width", + "gear.flank_points": "Profile accuracy (points per flank)", + "gear.helix_angle": "Helix angle", + "gear.internal": "Internal gear", + "gear.module": "Module", + "gear.pitch_diameter": "Pitch diameter", + "gear.preset_helical": "Helical", + "gear.preset_herringbone": "Herringbone", + "gear.preset_ring": "Ring", + "gear.preset_spur": "Spur", + "gear.presets": "Start from", + "gear.pressure_angle": "Pressure angle", + "gear.profile_shift": "Profile shift", + "gear.reset": "Reset", + "gear.rim_thickness": "Ring thickness", + "gear.root_diameter": "Root diameter", + "gear.teeth": "Teeth", + "gear.tip_diameter": "Outside diameter", + "help.gear.edit": "Edits a gear you inserted: change the module, tooth count, pressure angle, width, helix, clearance, rounding or bore, and the gear is rebuilt in place. Use it instead of deleting and inserting again, so the rest of the design keeps its references.", + "help.gear.insert": "Inserts an involute spur or helical gear, external or internal, as a new component. You give the module, tooth count, pressure angle and face width, and can add a helix angle, double helical teeth, an axle hole or an internal ring; the teeth are sketched and swept like any other feature." + }, + "he": { + "cmd.gear_edit": "עריכת גלגל שיניים", + "cmd.gear_insert": "הוספת גלגל שיניים", + "gear.backlash": "מרווח שיניים", + "gear.backlash_thicker": "המרווח מעבה את השיניים", + "gear.base_diameter": "קוטר מעגל הבסיס", + "gear.bore_diameter": "קוטר חור הציר", + "gear.bore_offset": "היסט חור הציר", + "gear.clearance": "מרווח ראש (× מודול)", + "gear.double_helical": "סליל כפול", + "gear.face_width": "רוחב שן", + "gear.flank_points": "דיוק הפרופיל (נקודות לכל צד)", + "gear.helix_angle": "זווית סליל", + "gear.internal": "גלגל שיניים פנימי", + "gear.module": "מודול", + "gear.pitch_diameter": "קוטר מעגל ההילוך", + "gear.preset_helical": "סלילי", + "gear.preset_herringbone": "שברון", + "gear.preset_ring": "טבעת", + "gear.preset_spur": "ישר", + "gear.presets": "התחל מ", + "gear.pressure_angle": "זווית לחץ", + "gear.profile_shift": "הסטת פרופיל", + "gear.reset": "איפוס", + "gear.rim_thickness": "עובי טבעת", + "gear.root_diameter": "קוטר מעגל השורש", + "gear.teeth": "מספר שיניים", + "gear.tip_diameter": "הקוטר החיצוני", + "help.gear.edit": "עורך גלגל שיניים שהוספת: משנים מודול, מספר שיניים, זווית לחץ, רוחב, סליל, מרווח, עיגול או חור, והגלגל נבנה מחדש במקומו. השתמשו בו במקום למחוק ולהוסיף שוב, כדי ששאר התכנון ישמור על ההפניות שלו.", + "help.gear.insert": "מוסיף גלגל שיניים בעל פרופיל אבולוטי, ישר או סלילי, חיצוני או פנימי, כרכיב חדש. מזינים מודול, מספר שיניים, זווית לחץ ורוחב שן, ואפשר להוסיף זווית סליל, שיניים סליליות כפולות, חור ציר או טבעת פנימית; השיניים משורטטות ונסחפות כמו כל תכונה אחרת." + }, + "ja": { + "cmd.gear_edit": "歯車を編集", + "cmd.gear_insert": "歯車を挿入", + "gear.backlash": "バックラッシ", + "gear.backlash_thicker": "バックラッシュで歯を厚くする", + "gear.base_diameter": "基礎円直径", + "gear.bore_diameter": "軸穴の直径", + "gear.bore_offset": "軸穴のオフセット", + "gear.clearance": "頂げき(×モジュール)", + "gear.double_helical": "やまば歯", + "gear.face_width": "歯幅", + "gear.flank_points": "プロファイル精度(歯面あたりの点数)", + "gear.helix_angle": "ねじれ角", + "gear.internal": "内歯車", + "gear.module": "モジュール", + "gear.pitch_diameter": "ピッチ円直径", + "gear.preset_helical": "はすば", + "gear.preset_herringbone": "やまば", + "gear.preset_ring": "内歯車", + "gear.preset_spur": "平歯車", + "gear.presets": "開始形状", + "gear.pressure_angle": "圧力角", + "gear.profile_shift": "転位", + "gear.reset": "リセット", + "gear.rim_thickness": "リムの厚さ", + "gear.root_diameter": "歯底円直径", + "gear.teeth": "歯数", + "gear.tip_diameter": "歯先円直径", + "help.gear.edit": "挿入した歯車を編集します。モジュール、歯数、圧力角、幅、ねじれ、クリアランス、丸め、穴を変更すると、その場で歯車が作り直されます。削除して入れ直す代わりに使うと、設計の他の部分の参照が保たれます。", + "help.gear.insert": "インボリュート平歯車またははすば歯車(外歯または内歯)を新しいコンポーネントとして挿入します。モジュール、歯数、圧力角、歯幅を指定し、ねじれ角、やまば歯、軸穴、内歯のリムを追加できます。歯形はスケッチされ、ほかのフィーチャーと同じようにスイープされます。" + }, + "ko": { + "cmd.gear_edit": "기어 편집", + "cmd.gear_insert": "기어 삽입", + "gear.backlash": "백래시", + "gear.backlash_thicker": "백래시로 이를 두껍게", + "gear.base_diameter": "기초원 지름", + "gear.bore_diameter": "축 구멍 지름", + "gear.bore_offset": "축 구멍 오프셋", + "gear.clearance": "틈새 (× 모듈)", + "gear.double_helical": "이중 헬리컬", + "gear.face_width": "이 너비", + "gear.flank_points": "프로파일 정확도 (측면당 점 수)", + "gear.helix_angle": "비틀림각", + "gear.internal": "내접 기어", + "gear.module": "모듈", + "gear.pitch_diameter": "피치원 지름", + "gear.preset_helical": "헬리컬", + "gear.preset_herringbone": "헤링본", + "gear.preset_ring": "링", + "gear.preset_spur": "스퍼", + "gear.presets": "시작 형태", + "gear.pressure_angle": "압력각", + "gear.profile_shift": "전위", + "gear.reset": "초기화", + "gear.rim_thickness": "림 두께", + "gear.root_diameter": "이뿌리원 지름", + "gear.teeth": "잇수", + "gear.tip_diameter": "이끝원 지름", + "help.gear.edit": "삽입한 기어를 편집합니다. 모듈, 잇수, 압력각, 너비, 비틀림, 간극, 라운딩, 구멍을 바꾸면 기어가 그 자리에서 다시 만들어집니다. 삭제 후 다시 삽입하는 대신 사용하면 나머지 설계가 참조를 유지합니다.", + "help.gear.insert": "인벌루트 평기어 또는 헬리컬 기어(외접 또는 내접)를 새 컴포넌트로 삽입합니다. 모듈, 잇수, 압력각, 이 너비를 지정하고 비틀림각, 이중 헬리컬 이, 축 구멍, 내접 기어의 림을 추가할 수 있습니다. 잇날은 스케치되어 다른 피처처럼 스윕됩니다." + }, + "vi": { + "cmd.gear_edit": "Sửa bánh răng", + "cmd.gear_insert": "Chèn bánh răng", + "gear.backlash": "Độ hở răng", + "gear.backlash_thicker": "Khe hở làm răng dày hơn", + "gear.base_diameter": "Đường kính vòng cơ sở", + "gear.bore_diameter": "Đường kính lỗ trục", + "gear.bore_offset": "Độ lệch lỗ trục", + "gear.clearance": "Khe hở đỉnh (× mô-đun)", + "gear.double_helical": "Răng chữ V", + "gear.face_width": "Bề rộng răng", + "gear.flank_points": "Độ chính xác biên dạng (số điểm mỗi sườn)", + "gear.helix_angle": "Góc nghiêng răng", + "gear.internal": "Bánh răng trong", + "gear.module": "Mô-đun", + "gear.pitch_diameter": "Đường kính vòng chia", + "gear.preset_helical": "Nghiêng", + "gear.preset_herringbone": "Chữ V", + "gear.preset_ring": "Vành trong", + "gear.preset_spur": "Thẳng", + "gear.presets": "Bắt đầu từ", + "gear.pressure_angle": "Góc áp lực", + "gear.profile_shift": "Dịch chỉnh", + "gear.reset": "Đặt lại", + "gear.rim_thickness": "Độ dày vành", + "gear.root_diameter": "Đường kính chân răng", + "gear.teeth": "Số răng", + "gear.tip_diameter": "Đường kính đỉnh răng", + "help.gear.edit": "Chỉnh sửa bánh răng đã chèn: đổi mô-đun, số răng, góc áp lực, bề rộng, góc nghiêng, khe hở, bo tròn hoặc lỗ trục, và bánh răng được dựng lại tại chỗ. Dùng thay cho xóa rồi chèn lại để phần còn lại của thiết kế giữ nguyên các tham chiếu.", + "help.gear.insert": "Chèn bánh răng trụ thân khai, răng thẳng hoặc răng nghiêng, ăn khớp ngoài hoặc ăn khớp trong, thành một thành phần mới. Bạn nhập mô-đun, số răng, góc áp lực và bề rộng răng, rồi có thể thêm góc nghiêng răng, răng chữ V, lỗ trục hoặc vành bánh răng trong; răng được phác thảo rồi quét như mọi tính năng khác." + }, + "zh": { + "cmd.gear_edit": "编辑齿轮", + "cmd.gear_insert": "插入齿轮", + "gear.backlash": "齿侧间隙", + "gear.backlash_thicker": "齿隙使齿变厚", + "gear.base_diameter": "基圆直径", + "gear.bore_diameter": "轴孔直径", + "gear.bore_offset": "轴孔偏移", + "gear.clearance": "顶隙(×模数)", + "gear.double_helical": "人字齿", + "gear.face_width": "齿宽", + "gear.flank_points": "齿形精度(每侧点数)", + "gear.helix_angle": "螺旋角", + "gear.internal": "内齿轮", + "gear.module": "模数", + "gear.pitch_diameter": "节圆直径", + "gear.preset_helical": "斜齿", + "gear.preset_herringbone": "人字齿", + "gear.preset_ring": "内齿圈", + "gear.preset_spur": "直齿", + "gear.presets": "起始类型", + "gear.pressure_angle": "压力角", + "gear.profile_shift": "变位", + "gear.reset": "重置", + "gear.rim_thickness": "齿圈厚度", + "gear.root_diameter": "齿根圆直径", + "gear.teeth": "齿数", + "gear.tip_diameter": "齿顶圆直径", + "help.gear.edit": "编辑已插入的齿轮:修改模数、齿数、压力角、宽度、螺旋角、顶隙、圆角或轴孔,齿轮会就地重建。用它代替删除后重新插入,这样设计的其余部分会保持其引用。", + "help.gear.insert": "将渐开线直齿轮或斜齿轮(外齿或内齿)作为新零部件插入。指定模数、齿数、压力角和齿宽后,还可加入螺旋角、人字齿、轴孔或内齿圈;齿形会被草绘并像其他特征一样扫掠。" + } +} diff --git a/crates/doc/src/component_removal.rs b/crates/doc/src/component_removal.rs index 211b2a0fce1..7a65802c1cc 100644 --- a/crates/doc/src/component_removal.rs +++ b/crates/doc/src/component_removal.rs @@ -188,6 +188,7 @@ impl Document { } self.assembly.rigid_groups.retain(|g| !inside.contains(&g.component)); self.parts.retain(|c, _| !removed_components.contains(c)); + self.gears.retain(|c, _| !removed_components.contains(c)); self.links.retain(|c, _| !removed_components.contains(c)); self.remove_configuration_components(&components); let mut removed = diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 9524d130098..017e52f5c21 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -5533,6 +5533,64 @@ pub struct StandardPart { pub thread: Option, } +/// An involute spur gear inserted as a component: what to rebuild its teeth from. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SpurGear { + /// Module (mm). + pub module: f64, + /// Number of teeth. + pub teeth: u32, + /// Pressure angle (degrees). + pub pressure_angle: f64, + /// Thickness along +Z (mm). + pub face_width: f64, + /// Profile shift coefficient. + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub profile_shift: f64, + /// Backlash (mm). + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub backlash: f64, + /// Points along each flank. + pub flank_points: u32, + /// Clearance coefficient (0.25 unless saved otherwise). + #[serde(default = "default_gear_clearance", skip_serializing_if = "is_default_gear_clearance")] + pub clearance: f64, + /// The backlash thickens the teeth instead of thinning them. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub backlash_thicker: bool, + /// An internal gear: a ring with its teeth pointing inward. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub internal: bool, + /// Ring thickness outside the tooth roots of an internal gear (mm). + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub rim_thickness: f64, + /// Diameter of the axle hole through an external gear (mm); 0 for none. + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub bore_diameter: f64, + /// How far the axle hole's centre is from the gear's along +X (mm). + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub bore_offset: f64, + /// Helix angle on the pitch circle (degrees); 0 for straight teeth, positive for right-hand. + #[serde(default, skip_serializing_if = "is_zero_f64")] + pub helix_angle: f64, + /// Two mirrored helical halves. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub double_helical: bool, +} + +fn is_zero_f64(v: &f64) -> bool { + *v == 0.0 +} + +/// The clearance every gear saved before it could be set was built with. +fn default_gear_clearance() -> f64 { + 0.25 +} + +fn is_default_gear_clearance(v: &f64) -> bool { + *v == 0.25 +} + /// A component whose contents come from a design or STEP source file: where that file /// is, and the Import feature in the component that holds its bodies (Update Links replaces /// them; Break Link keeps them and forgets the file). @@ -5779,6 +5837,9 @@ pub struct Document { /// Components that are standard parts (by component id): what to rebuild them from. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub parts: std::collections::BTreeMap, + /// Components that are spur gears (by component id): what to rebuild their teeth from. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub gears: std::collections::BTreeMap, /// Components linked to another design file (by component id). #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub links: std::collections::BTreeMap, @@ -6223,6 +6284,7 @@ impl Document { plastic: Default::default(), configs: Default::default(), parts: Default::default(), + gears: Default::default(), links: Default::default(), linked_bodies_left_out: false, body_components: Default::default(), diff --git a/crates/doc/src/format/pending/spur-gears.rs b/crates/doc/src/format/pending/spur-gears.rs new file mode 100644 index 00000000000..ec81b9042aa --- /dev/null +++ b/crates/doc/src/format/pending/spur-gears.rs @@ -0,0 +1,5 @@ +//! A design saves `gears`: for each component made by Insert Gear (`gear.insert`), its module, +//! tooth count, pressure angle, face width, profile shift, backlash and flank points, and for an internal gear its ring thickness or for an external one its axle hole diameter and offset, and its helix angle and whether it is double helical, its clearance (0.25 when not saved), and whether the backlash thickens the teeth, so the +//! teeth can be rebuilt when a value changes (`gear.edit`). An older design has no gears and +//! opens unchanged. The last release opens a design with gears with a warning about the newer +//! format and keeps the `gears` it cannot read. diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index 98b5380713b..c2deb1acd56 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -775,6 +775,7 @@ fn same_geometry_inputs(a: &Document, b: &Document) -> bool { sheet, plastic, parts, + gears, links, // What a file keeps of its links; a design in memory holds their bodies either way. linked_bodies_left_out: _, @@ -833,6 +834,7 @@ fn same_geometry_inputs(a: &Document, b: &Document) -> bool { && *sheet == b.sheet && *plastic == b.plastic && *parts == b.parts + && *gears == b.gears && *links == b.links && *configs == b.configs && *favorites == b.favorites diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index e0e7bb9b8f1..cabb721d753 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -752,6 +752,9 @@ fn build_to( if let Some(part) = source.parts.get(old) { scratch.doc_mut().parts.insert(*new, part.clone()); } + if let Some(gear) = source.gears.get(old) { + scratch.doc_mut().gears.insert(*new, gear.clone()); + } if let Some(look) = source.appearances.components.get(old) { scratch.doc_mut().appearances.components.insert(*new, look.clone()); } diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index e653be3c38c..56c58ba5cec 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -537,6 +537,7 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio o.parent = to_root(o.parent); } part.parts.retain(|c, _| sc.children.contains(c)); + part.gears.retain(|c, _| sc.children.contains(c)); part.links.retain(|c, _| sc.children.contains(c)); part.body_components = part.body_components.iter().filter(|(_, c)| sc.subtree.contains(c)).map(|(b, c)| (b.clone(), to_root(*c))).collect(); let moved = part.body_components.clone(); @@ -634,6 +635,8 @@ fn clear_history(s: &mut Session, sc: &Scope) { d.body_components.retain(|_, c| !sc.subtree.contains(c)); d.body_offsets.retain(|b, _| !sc.bodies.contains(b)); d.parts.retain(|c, _| !children.contains(c)); + // The component keeps its link but not the gear's teeth: Edit Gear would delete the link with them. + d.gears.retain(|c, _| !children.contains(c) && *c != comp); d.links.retain(|c, _| !children.contains(c)); d.appearances.components.retain(|c, _| !children.contains(c)); d.canvases.retain(|c| !sc.subtree.contains(&c.component)); diff --git a/crates/engine/src/cmd/gear_profile.rs b/crates/engine/src/cmd/gear_profile.rs new file mode 100644 index 00000000000..1a01b4ef09a --- /dev/null +++ b/crates/engine/src/cmd/gear_profile.rs @@ -0,0 +1,308 @@ +//! The outline of an involute spur gear, as a closed polyline in the gear's own plane. +//! +//! Pure geometry from the public involute equations (ISO 53 proportions: addendum `m (1 + x)`, +//! dedendum `m (1.25 - x)`, profile shift `x`). The gear is centred on the origin with the +//! middle of one tooth on +x. Each flank is sampled, so the tooth is a polyline whose points +//! all lie on the true involute. + +use std::f64::consts::{PI, TAU}; + +/// What defines a spur gear. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GearSpec { + /// Module (mm): pitch diameter divided by tooth count. + pub module: f64, + /// Number of teeth. + pub teeth: u32, + /// Pressure angle (radians). + pub pressure_angle: f64, + /// Profile shift coefficient `x` (0 for a standard gear). + pub shift: f64, + /// Backlash (mm) taken from the tooth thickness on the pitch circle. + pub backlash: f64, + /// Points along each flank, from the start of the involute to the tip. + pub flank_points: u32, + /// An internal gear: the teeth point inward from a ring (profile shift is not used). + pub internal: bool, + /// Clearance coefficient `c`: the root lies `m (1 + c - x)` inside the pitch circle (0.25 standard). + pub clearance: f64, + /// The backlash makes the teeth thicker instead of thinner (for a mate that carries the clearance). + pub thicker: bool, +} + +impl GearSpec { + pub fn new(module: f64, teeth: u32, pressure_angle_deg: f64) -> Self { + Self { + module, + teeth, + pressure_angle: pressure_angle_deg.to_radians(), + shift: 0.0, + backlash: 0.0, + flank_points: 8, + internal: false, + clearance: 0.25, + thicker: false, + } + } + pub fn pitch_radius(&self) -> f64 { + self.module * f64::from(self.teeth) / 2.0 + } + pub fn base_radius(&self) -> f64 { + self.pitch_radius() * self.pressure_angle.cos() + } + /// The tooth tips: outside an external gear, inside an internal one. + pub fn tip_radius(&self) -> f64 { + if self.internal { + return self.pitch_radius() - self.module; + } + self.pitch_radius() + self.module * (1.0 + self.shift) + } + /// The tooth roots: inside an external gear, outside an internal one. + pub fn root_radius(&self) -> f64 { + if self.internal { + return self.pitch_radius() + self.module * (1.0 + self.clearance); + } + self.pitch_radius() - self.module * (1.0 + self.clearance - self.shift) + } +} + +fn inv(a: f64) -> f64 { + a.tan() - a +} + +/// Half the angle one tooth spans at radius `r` (radians), or `None` below the base circle. +fn half_tooth_angle(g: &GearSpec, r: f64) -> Option { + let rb = g.base_radius(); + if r < rb { + return None; + } + let backlash = if g.thicker { -g.backlash } else { g.backlash }; + let thickness = g.module * (PI / 2.0 + 2.0 * g.shift * g.pressure_angle.tan()) - backlash; + let at_base = thickness / (2.0 * g.pitch_radius()) + inv(g.pressure_angle); + Some(at_base - inv((rb / r).clamp(-1.0, 1.0).acos())) +} + +/// The closed outline, counter-clockwise, without repeating the first point. For an internal +/// gear it is the edge of the hole in the ring: the tooth space of a ring gear has the shape of +/// an external tooth, so it is built as one, with the clearance on the tip side and the +/// backlash widening the space. +pub fn outline(g: &GearSpec) -> Result, String> { + if !g.backlash.is_finite() || g.backlash < 0.0 || g.backlash >= g.module * PI / 2.0 { + return Err("the backlash must be from 0 up to a quarter of the circular pitch".into()); + } + if !g.clearance.is_finite() || !(0.0..=0.6).contains(&g.clearance) { + return Err("the clearance must be from 0 to 0.6 of the module".into()); + } + if !g.internal { + return build(g, g.tip_radius(), g.root_radius()); + } + if g.shift != 0.0 { + return Err("profile shift is for external gears".into()); + } + let space = GearSpec { internal: false, backlash: -g.backlash, ..*g }; + build(&space, g.root_radius(), g.tip_radius()) +} + +fn build(g: &GearSpec, ra: f64, rf: f64) -> Result, String> { + let finite = g.module.is_finite() && g.pressure_angle.is_finite() && g.shift.is_finite() && g.backlash.is_finite(); + if !finite || g.module <= 0.0 { + return Err("the module must be a positive number".into()); + } + if g.teeth < 6 || g.teeth > 1000 { + return Err("the tooth count must be between 6 and 1000".into()); + } + if !(g.pressure_angle > 0.0 && g.pressure_angle <= 35f64.to_radians()) { + return Err("the pressure angle must be above 0 and at most 35 degrees".into()); + } + if g.flank_points < 2 || g.flank_points > 64 { + return Err("a flank needs between 2 and 64 points".into()); + } + let rb = g.base_radius(); + if !(rf > 0.0) { + return Err("the root circle is inside the axis: use more teeth or a smaller profile shift".into()); + } + let tip_half = half_tooth_angle(g, ra).ok_or("the tip circle is inside the base circle")?; + if tip_half <= 0.0 { + return Err("the teeth come to a point before the tip: use more teeth, a smaller pressure angle or less profile shift".into()); + } + // The involute starts on the base circle, or on the root circle when that is larger. + let start = rb.max(rf); + let step = (ra - start) / f64::from(g.flank_points - 1); + let mut flank = Vec::with_capacity(g.flank_points as usize + 1); + // Below the base circle the flank runs straight along the radius to the root circle. + if rf < rb { + let base_half = half_tooth_angle(g, rb).ok_or("the base circle is inconsistent")?; + flank.push((rf, base_half)); + } + for i in 0..g.flank_points { + let r = if i + 1 == g.flank_points { ra } else { start + step * f64::from(i) }; + let half = half_tooth_angle(g, r).ok_or("a flank point is inside the base circle")?; + flank.push((r, half)); + } + let pitch = TAU / f64::from(g.teeth); + // A thicker tooth must still leave room for its neighbour at the root. + if flank.iter().any(|&(_, h)| h >= pitch / 2.0) { + return Err("the teeth would run into each other: use less backlash or profile shift".into()); + } + let mut out = Vec::with_capacity(g.teeth as usize * flank.len() * 2); + for t in 0..g.teeth { + let c = pitch * f64::from(t); + let at = |r: f64, a: f64| [r * (c + a).cos(), r * (c + a).sin()]; + // Up the right flank, then down the left; the chord between two teeth is the root. + out.extend(flank.iter().map(|&(r, h)| at(r, -h))); + out.extend(flank.iter().rev().map(|&(r, h)| at(r, h))); + } + if out.iter().any(|p| !p[0].is_finite() || !p[1].is_finite()) { + return Err("the gear outline is not finite".into()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn radius(p: &[f64; 2]) -> f64 { + p[0].hypot(p[1]) + } + + #[test] + fn a_standard_gear_has_the_textbook_circles() { + let g = GearSpec::new(2.0, 20, 20.0); + assert!((g.pitch_radius() - 20.0).abs() < 1e-12); + assert!((g.base_radius() - 20.0 * 20f64.to_radians().cos()).abs() < 1e-12); + assert!((g.tip_radius() - 22.0).abs() < 1e-12); + assert!((g.root_radius() - 17.5).abs() < 1e-12); + } + + #[test] + fn every_point_lies_between_the_root_and_tip_circles() { + let g = GearSpec::new(2.0, 24, 20.0); + let pts = outline(&g).unwrap(); + let (lo, hi) = (g.root_radius().min(g.base_radius()) - 1e-9, g.tip_radius() + 1e-9); + assert!(pts.iter().all(|p| (lo..=hi).contains(&radius(p)))); + assert!((pts.iter().map(radius).fold(0.0, f64::max) - g.tip_radius()).abs() < 1e-9); + } + + #[test] + fn the_outline_repeats_every_tooth_pitch() { + let g = GearSpec::new(1.5, 18, 20.0); + let pts = outline(&g).unwrap(); + let per = pts.len() / 18; + let turn = TAU / 18.0; + for (i, p) in pts.iter().enumerate().skip(per) { + let q = pts[i - per]; + let (c, s) = (turn.cos(), turn.sin()); + let rot = [q[0] * c - q[1] * s, q[0] * s + q[1] * c]; + assert!((rot[0] - p[0]).abs() < 1e-9 && (rot[1] - p[1]).abs() < 1e-9); + } + } + + #[test] + fn the_tooth_is_half_a_pitch_thick_on_the_pitch_circle() { + // Standard gear, no backlash: thickness on the pitch circle is pi m / 2. + let g = GearSpec::new(2.0, 30, 20.0); + let half = half_tooth_angle(&g, g.pitch_radius()).unwrap(); + assert!((2.0 * half * g.pitch_radius() - PI * g.module / 2.0).abs() < 1e-9); + } + + #[test] + fn backlash_thins_the_tooth_by_that_amount() { + let mut g = GearSpec::new(2.0, 30, 20.0); + g.backlash = 0.1; + let half = half_tooth_angle(&g, g.pitch_radius()).unwrap(); + assert!((2.0 * half * g.pitch_radius() - (PI * g.module / 2.0 - 0.1)).abs() < 1e-9); + } + + #[test] + fn flank_points_lie_on_the_involute_of_the_base_circle() { + // A point at radius r on the flank is at angle inv(acos(rb / r)) past the base-circle start. + let g = GearSpec::new(2.0, 24, 20.0); + let pts = outline(&g).unwrap(); + let rb = g.base_radius(); + let p = pts[3]; + let r = radius(&p); + let start = half_tooth_angle(&g, rb).unwrap(); + let expect = -(start - inv((rb / r).acos())); + assert!((p[1].atan2(p[0]) - expect).abs() < 1e-9); + } + + #[test] + fn an_internal_gear_has_its_teeth_pointing_inward() { + let mut g = GearSpec::new(2.0, 40, 20.0); + g.internal = true; + assert!((g.tip_radius() - 38.0).abs() < 1e-12 && (g.root_radius() - 42.5).abs() < 1e-12); + let pts = outline(&g).unwrap(); + let (lo, hi) = (g.tip_radius() - 1e-9, g.root_radius() + 1e-9); + assert!(pts.iter().all(|p| (lo..=hi).contains(&radius(p)))); + assert!((pts.iter().map(radius).fold(f64::MAX, f64::min) - g.tip_radius()).abs() < 1e-9); + assert!((pts.iter().map(radius).fold(0.0, f64::max) - g.root_radius()).abs() < 1e-9); + } + + #[test] + fn an_internal_gear_space_is_as_wide_as_the_external_tooth_it_meshes_with() { + // On the pitch circle the ring's space equals the external tooth, plus the backlash. + let ext = GearSpec::new(2.0, 40, 20.0); + let space = |backlash: f64| { + let v = GearSpec { backlash: -backlash, ..ext }; + 2.0 * half_tooth_angle(&v, v.pitch_radius()).unwrap() * v.pitch_radius() + }; + assert!((space(0.0) - PI * 2.0 / 2.0).abs() < 1e-9); + assert!((space(0.1) - (PI + 0.1)).abs() < 1e-9); + } + + #[test] + fn clearance_moves_the_roots_and_the_thicker_direction_widens_the_teeth() { + let mut g = GearSpec::new(2.0, 24, 20.0); + g.clearance = 0.4; + assert!((g.root_radius() - (24.0 - 2.0 * 1.4)).abs() < 1e-12); + g.internal = true; + assert!((g.root_radius() - (24.0 + 2.0 * 1.4)).abs() < 1e-12); + g.internal = false; + g.backlash = 0.2; + let thin = half_tooth_angle(&g, g.pitch_radius()).unwrap(); + g.thicker = true; + let thick = half_tooth_angle(&g, g.pitch_radius()).unwrap(); + assert!((2.0 * thin * g.pitch_radius() - (PI - 0.2)).abs() < 1e-9); + assert!((2.0 * thick * g.pitch_radius() - (PI + 0.2)).abs() < 1e-9); + } + + #[test] + fn hostile_parameters_are_refused_not_panics() { + for (m, z, a) in [ + (0.0, 20, 20.0), + (-1.0, 20, 20.0), + (f64::NAN, 20, 20.0), + (f64::INFINITY, 20, 20.0), + (2.0, 0, 20.0), + (2.0, 5, 20.0), + (2.0, 5000, 20.0), + (2.0, 20, 0.0), + (2.0, 20, 90.0), + (2.0, 20, f64::NAN), + ] { + assert!(outline(&GearSpec::new(m, z, a)).is_err(), "{m} {z} {a}"); + } + let mut g = GearSpec::new(2.0, 20, 20.0); + g.shift = 50.0; + assert!(outline(&g).is_err()); + g.shift = f64::NAN; + assert!(outline(&g).is_err()); + g.shift = 0.0; + g.backlash = 1e9; + assert!(outline(&g).is_err()); + g.backlash = -0.1; + assert!(outline(&g).is_err()); + g.backlash = 0.0; + g.internal = true; + g.shift = 0.5; + assert!(outline(&g).is_err()); + } + + #[test] + fn a_gear_too_small_for_its_pressure_angle_still_gives_a_clean_outline() { + let g = GearSpec::new(1.0, 8, 25.0); + let pts = outline(&g).unwrap(); + assert!(pts.iter().all(|p| p[0].is_finite() && p[1].is_finite())); + } +} diff --git a/crates/engine/src/cmd/gears.rs b/crates/engine/src/cmd/gears.rs new file mode 100644 index 00000000000..919feb2092d --- /dev/null +++ b/crates/engine/src/cmd/gears.rs @@ -0,0 +1,432 @@ +//! Involute spur gears (#6796): a tooth outline from `gear_profile`, sketched and extruded like +//! any other feature, so the gear stays an ordinary component. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_doc::SpurGear; +use solidcraft_kernel::api::Vec2; +use solidcraft_sketch::CurveKind; + +use super::CommandSpec; +use super::gear_profile::{GearSpec, outline}; +use crate::params::{bad, num, str_}; +use crate::schema::gears::{GearEditParams, GearInsertParams, InsertedGear}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{Result, Session}; + +const EDIT_CONTRACT: TypedContract = TypedContract::new(); +const INSERT_CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("gear.edit", "Edit Gear", crate::checked!("gear.edit", edit_atomic)) + .icon("gear") + .contract(&EDIT_CONTRACT) + .output(output_schema_for::) + .params("component: id|name of an inserted gear; module?, teeth?, pressure_angle?, face_width?, profile_shift?, backlash?, flank_points?, clearance?, backlash_direction?, internal?, rim_thickness?, bore_diameter?, bore_offset?, helix_angle?, double_helical? (the values given replace the saved ones) → rebuilds the teeth in place; component, occurrence, name, diameters"), + CommandSpec::new("gear.insert", "Insert Gear", crate::checked!("gear.insert", insert_atomic)) + .at("SOLID", "INSERT") + .icon("gear") + .contract(&INSERT_CONTRACT) + .output(output_schema_for::) + .params("module (mm), teeth (6..1000), pressure_angle? (deg, default 20), face_width? (mm), profile_shift?, backlash? (mm), flank_points? (2..64, default 8: the profile accuracy), clearance? (0..0.6 of the module, default 0.25: how far the roots lie below the dedendum line), backlash_direction? (thinner, the default: the backlash comes off the teeth; thicker: it is added, for a mate that carries the clearance), internal? (bool: a ring with its teeth inward; no profile shift), rim_thickness? (mm, internal only, default 2 × module), bore_diameter? (mm, external only: an axle hole), bore_offset? (mm: the hole's centre along +X), helix_angle? (deg, -45..45, default 0: teeth twisted over the face width, positive right-hand), double_helical? (bool, external only: two mirrored halves), name? → component, occurrence, name, pitch/base/tip/root diameters"), +]; + +/// A number parameter that may be left out; one that is present but not a usable number is refused. +fn optional(p: &Value, k: &str, cmd: &str) -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(_) => num(p, k).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a finite number below 1e9"))), + } +} + +/// What a gear needs besides its tooth outline. +#[derive(Clone, Copy)] +struct Extent { + width: f64, + /// Internal gears: ring thickness outside the tooth roots. + rim: f64, + /// External gears: diameter of the axle hole, 0 for none. + bore: f64, + /// External gears: how far the axle hole's centre is from the gear's along +X. + bore_offset: f64, + /// Helix angle on the pitch circle (degrees): 0 for straight teeth, positive for a right-hand helix. + helix: f64, + /// Two mirrored helical halves, so the thrust of one cancels the other. + double: bool, +} + +/// How far a helical gear's profile turns over `length` along its axis (degrees). +fn twist_over(g: &GearSpec, helix_deg: f64, length: f64) -> f64 { + (length * helix_deg.to_radians().tan() / g.pitch_radius()).to_degrees() +} + +fn spec(p: &Value, cmd: &str) -> Result<(GearSpec, Extent)> { + let module = num(p, "module").ok_or_else(|| bad(cmd, "`module` is required (a positive number of mm)"))?; + let teeth = p + .get("teeth") + .and_then(Value::as_u64) + .and_then(|t| u32::try_from(t).ok()) + .ok_or_else(|| bad(cmd, "`teeth` is required (a whole number, 6 to 1000)"))?; + let mut g = GearSpec::new(module, teeth, optional(p, "pressure_angle", cmd)?.unwrap_or(20.0)); + g.shift = optional(p, "profile_shift", cmd)?.unwrap_or(0.0); + g.backlash = optional(p, "backlash", cmd)?.unwrap_or(0.0); + g.clearance = optional(p, "clearance", cmd)?.unwrap_or(0.25); + g.thicker = match p.get("backlash_direction") { + None | Some(Value::Null) => false, + Some(Value::String(d)) if d == "thinner" => false, + Some(Value::String(d)) if d == "thicker" => true, + Some(_) => return Err(bad(cmd, "`backlash_direction` must be `thinner` or `thicker`")), + }; + match p.get("flank_points") { + None | Some(Value::Null) => {} + Some(v) => match v.as_u64() { + Some(n) => g.flank_points = u32::try_from(n).unwrap_or(u32::MAX), + None => return Err(bad(cmd, "`flank_points` must be a whole number")), + }, + } + g.internal = match p.get("internal") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`internal` must be true or false")), + }; + let width = optional(p, "face_width", cmd)?.unwrap_or(module * 10.0); + if !(width > 0.0) { + return Err(bad(cmd, "`face_width` must be above 0")); + } + // 0 means none: it is what a gear that is not internal, or has no axle hole, saves. + let rim = optional(p, "rim_thickness", cmd)?.filter(|r| *r != 0.0); + let bore = optional(p, "bore_diameter", cmd)?; + if g.internal && bore.is_some_and(|b| b != 0.0) { + return Err(bad(cmd, "`bore_diameter` is for external gears")); + } + if !g.internal && rim.is_some() { + return Err(bad(cmd, "`rim_thickness` is for internal gears")); + } + let rim = if g.internal { rim.unwrap_or(module * 2.0) } else { 0.0 }; + if g.internal && !(rim > 0.0) { + return Err(bad(cmd, "`rim_thickness` must be above 0")); + } + let bore = bore.unwrap_or(0.0); + let bore_offset = optional(p, "bore_offset", cmd)?.unwrap_or(0.0); + // The hole must leave a rim of material inside the root circle. + let room = 0.9 * g.root_radius().min(g.base_radius()); + if bore < 0.0 || (bore > 0.0 && bore / 2.0 + bore_offset.abs() >= room) { + let limit = if g.base_radius() < g.root_radius() { "base" } else { "root" }; + return Err(bad( + cmd, + format!( + "the axle hole, with its offset, must stay inside 90% of the gear's {limit} circle (a radius of {room:.3} mm from the gear's centre)" + ), + )); + } + if bore == 0.0 && bore_offset != 0.0 { + return Err(bad(cmd, "`bore_offset` needs a `bore_diameter`")); + } + let helix = optional(p, "helix_angle", cmd)?.unwrap_or(0.0); + if helix.abs() > 45.0 { + return Err(bad(cmd, "`helix_angle` must be from -45 to 45 degrees")); + } + let double = match p.get("double_helical") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`double_helical` must be true or false")), + }; + if double && helix == 0.0 { + return Err(bad(cmd, "`double_helical` needs a `helix_angle`")); + } + if double && g.internal { + return Err(bad(cmd, "`double_helical` is for external gears")); + } + // The sweep that twists the teeth turns at most four times. + if twist_over(&g, helix, width).abs() > 1440.0 { + return Err(bad(cmd, "the teeth would turn more than four times over the face width: use a smaller helix angle or a thinner gear")); + } + Ok((g, Extent { width, rim, bore, bore_offset, helix, double })) +} + +fn insert_atomic(s: &mut Session, p: &Value) -> Result { + let mut computed = s.scratch(); + let result = insert(&mut computed, p)?; + computed.undo.clear(); + computed.active_component = s.active_component; + computed.active_occurrence_path = s.active_occurrence_path.clone(); + computed.active_sketch = s.active_sketch.filter(|id| computed.doc.feature(*id).is_some()); + s.accept_computed(computed)?; + Ok(result) +} + +/// A sketch on the XY plane holding the tooth outline (`teeth`), a circle round the centre, or both. +fn sketch_profile(s: &mut Session, g: &GearSpec, teeth: bool, circle: Option<(f64, f64)>, cmd: &str) -> Result { + let sketch = s.execute("sketch.create", &json!({"plane": "XY"}))?["sketch"].as_u64().unwrap_or(0); + // Each flank is one spline through its points, each tip and root one line: 4 edges a tooth. + // All go in with one sketch edit: a command per curve would copy the design for each. + let points = if teeth { outline(g).map_err(|e| bad(cmd, e))? } else { Vec::new() }; + let flank = (points.len() / (g.teeth as usize * 2)).max(1); + super::sketch::edit(s, &json!({}), cmd, false, |sk, _| { + let mut ids = Vec::with_capacity(points.len()); + for q in &points { + ids.push(sk.add_point(Vec2::new(q[0], q[1]), None).map_err(|e| bad(cmd, e.to_string()))?); + } + let chunks: Vec<&[usize]> = ids.chunks(flank).collect(); + for (i, chunk) in chunks.iter().enumerate() { + let kind = CurveKind::Spline { pts: chunk.to_vec(), control: false, degree: 3, periodic: false, nurbs: None, handles: Vec::new() }; + sk.add_curve(kind, None).map_err(|e| bad(cmd, e.to_string()))?; + // After a right flank comes the tip; after a left flank, the root. + let (from, to) = (chunk[chunk.len() - 1], chunks[(i + 1) % chunks.len()][0]); + sk.add_line_pts(from, to, None).map_err(|e| bad(cmd, e.to_string()))?; + } + if let Some((r, x)) = circle { + sk.add_circle(Vec2::new(x, 0.0), r, None, None).map_err(|e| bad(cmd, e.to_string()))?; + } + Ok(()) + })?; + s.execute("sketch.finish", &json!({}))?; + Ok(sketch) +} + +/// Turn a profile sketch into material: straight for a spur gear; for a helical one, a sweep along +/// the gear's axis that turns the profile. A double helical gear is one half and its mirror. +fn solidify(s: &mut Session, g: &GearSpec, e: &Extent, profile: u64, operation: &str) -> Result<()> { + if e.helix == 0.0 { + let distance = format!("{} mm", e.width); + s.execute("solid.extrude", &json!({"sketch": profile, "distance": distance, "direction": "positive", "operation": operation}))?; + return Ok(()); + } + let length = if e.double { e.width / 2.0 } else { e.width }; + // The path runs up +Z from the middle of the profile. + let path = s.execute("sketch.create", &json!({"plane": "YZ"}))?["sketch"].as_u64().unwrap_or(0); + let line = s.execute("sketch.line", &json!({"points": [[0, 0], [0, length]]}))?; + let curve = line["created"]["curves"][0].clone(); + s.execute("sketch.finish", &json!({}))?; + let twist = format!("{} deg", twist_over(g, e.helix, length)); + let swept = + s.execute("solid.sweep", &json!({"sketch": profile, "path_sketch": path, "path": [curve], "twist": twist, "operation": operation}))?; + if e.double { + let body = swept["bodies"][0].clone(); + let plane = json!({"origin": [0, 0, length], "normal": [0, 0, 1]}); + s.execute("solid.mirror", &json!({"bodies": [body], "plane": plane, "combine": true}))?; + } + Ok(()) +} + +/// The gear's teeth as sketch and extrusion in the active component. An external gear is its tooth +/// outline, with an axle hole cut through it. An internal gear is the ring's disc with the tooth +/// outline cut through it. Helical teeth are a twisted sweep in place of the extrusion. +fn build(s: &mut Session, g: &GearSpec, e: &Extent, cmd: &str) -> Result<()> { + let straight = Extent { helix: 0.0, double: false, ..*e }; + if g.internal { + let disc = sketch_profile(s, g, false, Some((g.root_radius() + e.rim, 0.0)), cmd)?; + solidify(s, g, &straight, disc, "new")?; + let teeth = sketch_profile(s, g, true, None, cmd)?; + solidify(s, g, e, teeth, "cut")?; + } else { + let teeth = sketch_profile(s, g, true, None, cmd)?; + solidify(s, g, e, teeth, "new")?; + if e.bore > 0.0 { + let hole = sketch_profile(s, g, false, Some((e.bore / 2.0, e.bore_offset)), cmd)?; + solidify(s, g, &straight, hole, "cut")?; + } + } + Ok(()) +} + +fn record(g: &GearSpec, e: &Extent) -> SpurGear { + SpurGear { + module: g.module, + teeth: g.teeth, + pressure_angle: g.pressure_angle.to_degrees(), + face_width: e.width, + profile_shift: g.shift, + backlash: g.backlash, + flank_points: g.flank_points, + clearance: g.clearance, + backlash_thicker: g.thicker, + internal: g.internal, + rim_thickness: e.rim, + bore_diameter: e.bore, + bore_offset: e.bore_offset, + helix_angle: e.helix, + double_helical: e.double, + } +} + +fn reply(g: &GearSpec, comp: u64, occ: u64, name: String) -> Result { + let out = InsertedGear { + component: comp, + occurrence: occ, + name, + pitch_diameter: 2.0 * g.pitch_radius(), + base_diameter: 2.0 * g.base_radius(), + tip_diameter: 2.0 * g.tip_radius(), + root_diameter: 2.0 * g.root_radius(), + }; + serde_json::to_value(out).map_err(|e| bad("gear.insert", e.to_string())) +} + +/// Pitch, base, tip and root diameters (mm) for the values a gear form holds, or `None` when they +/// make no gear. The form shows these as the values change. +pub fn gear_diameters(module: f64, teeth: u32, pressure_angle_deg: f64, shift: f64, clearance: f64, internal: bool) -> Option<[f64; 4]> { + let mut g = GearSpec::new(module, teeth, pressure_angle_deg); + g.clearance = clearance; + g.shift = if internal { 0.0 } else { shift }; + g.internal = internal; + let d = [2.0 * g.pitch_radius(), 2.0 * g.base_radius(), 2.0 * g.tip_radius(), 2.0 * g.root_radius()]; + d.iter().all(|v| v.is_finite() && *v > 0.0).then_some(d) +} + +fn gear_name(internal: bool, module: f64, teeth: u32) -> String { + format!("{} Gear M{module} Z{teeth}", if internal { "Internal" } else { "Spur" }) +} + +fn insert(s: &mut Session, p: &Value) -> Result { + let cmd = "gear.insert (Insert Gear)"; + let (g, ext) = spec(p, cmd)?; + outline(&g).map_err(|e| bad(cmd, e))?; + let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| gear_name(g.internal, g.module, g.teeth)); + let active = s.active_component; + let c = s.execute("component.create", &json!({"name": name, "grounded": false}))?; + let (comp, occ) = (c["component"].as_u64().unwrap_or(0), c["occurrence"].as_u64().unwrap_or(0)); + build(s, &g, &ext, cmd)?; + s.doc_mut().gears.insert(comp, record(&g, &ext)); + s.execute("component.activate", &json!({"component": active}))?; + reply(&g, comp, occ, name) +} + +fn edit_atomic(s: &mut Session, p: &Value) -> Result { + let mut computed = s.scratch(); + let result = edit(&mut computed, p)?; + // Nothing was rebuilt: the document and its revision stay as they are. + if computed.revision == s.revision && Arc::ptr_eq(&computed.doc, &s.doc) { + return Ok(result); + } + computed.undo.clear(); + computed.active_component = s.active_component; + computed.active_occurrence_path = s.active_occurrence_path.clone(); + computed.active_sketch = s.active_sketch.filter(|id| computed.doc.feature(*id).is_some()); + s.accept_computed(computed)?; + Ok(result) +} + +/// The command values a saved gear stands for. +fn saved_values(was: &SpurGear) -> Value { + json!({ + "module": was.module, "teeth": was.teeth, "pressure_angle": was.pressure_angle, "face_width": was.face_width, + "profile_shift": was.profile_shift, "backlash": was.backlash, "flank_points": was.flank_points, + "internal": was.internal, "rim_thickness": was.rim_thickness, "bore_diameter": was.bore_diameter, + "bore_offset": was.bore_offset, "helix_angle": was.helix_angle, "double_helical": was.double_helical, + "clearance": was.clearance, + "backlash_direction": if was.backlash_thicker { "thicker" } else { "thinner" }, + }) +} + +/// The kinds of feature building this gear makes, in timeline order: built in a throwaway copy of +/// the session. A component whose features read differently holds something that is not the gear's. +fn own_feature_kinds(s: &Session, g: &GearSpec, e: &Extent, cmd: &str) -> Result> { + let mut probe = s.scratch(); + let c = probe.execute("component.create", &json!({"name": "probe", "grounded": false}))?; + let comp = c["component"].as_u64().unwrap_or(0); + build(&mut probe, g, e, cmd)?; + Ok(probe.doc.features.iter().filter(|f| f.component == comp).map(|f| f.kind.type_name()).collect()) +} + +/// Change a gear's values and rebuild its teeth in place; the component, its placement and its +/// joints stay. +fn edit(s: &mut Session, p: &Value) -> Result { + let cmd = "gear.edit"; + let key = match p.get("component") { + Some(Value::Number(n)) => n.to_string(), + Some(Value::String(x)) => x.clone(), + _ => return Err(bad(cmd, "`component` must be an id or a name")), + }; + let comp = s.doc.find_component(&key).ok_or_else(|| bad(cmd, format!("no component `{key}`")))?; + let was = s.doc.gears.get(&comp).cloned().ok_or_else(|| bad(cmd, "that component is not a gear"))?; + // The values given replace the saved ones. + let mut merged = saved_values(&was); + for k in [ + "module", + "teeth", + "pressure_angle", + "face_width", + "profile_shift", + "backlash", + "flank_points", + "internal", + "rim_thickness", + "bore_diameter", + "bore_offset", + "helix_angle", + "double_helical", + "clearance", + "backlash_direction", + ] { + if let Some(v) = p.get(k).filter(|v| !v.is_null()) { + merged[k] = v.clone(); + } + } + // Turning a gear inside out drops what only the other kind has, unless it is given too. + let absent = |k: &str| p.get(k).is_none_or(Value::is_null); + if merged["internal"] == json!(true) && absent("profile_shift") { + merged["profile_shift"] = json!(0); + } + if merged["internal"] == json!(true) && absent("double_helical") { + merged["double_helical"] = json!(false); + } + if merged["internal"] == json!(true) && absent("bore_diameter") { + merged["bore_diameter"] = json!(0); + } else if merged["internal"] != json!(true) && absent("rim_thickness") { + merged["rim_thickness"] = json!(0); + } + let (g, ext) = spec(&merged, cmd)?; + outline(&g).map_err(|e| bad(cmd, e))?; + // The values it already has are no edit: nothing is rebuilt and no undo step is made. + if record(&g, &ext) == was { + let name = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone()).unwrap_or_default(); + let occ = s.doc.occurrences.iter().find(|o| o.component == comp).map(|o| o.id).unwrap_or(0); + return reply(&g, comp, occ, name); + } + let own: Vec<(u64, &'static str)> = s.doc.features.iter().filter(|f| f.component == comp).map(|f| (f.id, f.kind.type_name())).collect(); + let ids: Vec = own.iter().map(|(id, _)| *id).collect(); + // The gear's own features are all this deletes. Anything else made in the component (a sketch, + // a cut) would go with them and take its dependents along, so refuse instead: the features + // must be the kinds, in the order, that building the saved gear makes, and nothing outside the + // component may build on them. + let (was_g, was_ext) = spec(&saved_values(&was), cmd)?; + let expected = own_feature_kinds(s, &was_g, &was_ext, cmd)?; + if own.iter().map(|(_, k)| *k).ne(expected.iter().copied()) { + return Err(bad(cmd, "this gear's component holds features that are not the gear's own; edit it by hand, or insert a new gear")); + } + if s.doc.features.iter().any(|f| f.component != comp && f.kind.input_sketches().iter().any(|sk| ids.contains(sk))) { + return Err(bad(cmd, "another feature is built on this gear's sketches; edit it by hand, or insert a new gear")); + } + s.refresh(); + let before: Vec<(u64, String)> = s.model.results.iter().filter_map(|r| r.error.clone().map(|e| (r.id, e))).collect(); + for id in ids.iter().rev() { + // A sketch goes with its extrude, so one already gone is no failure; any other is. + if s.doc.feature(*id).is_none() { + continue; + } + let gone = s.doc_mut().delete_feature(*id).map_err(|e| bad(cmd, format!("could not remove the old teeth: {e}")))?; + if let Some(extra) = gone.iter().find(|g| !ids.contains(g)) { + return Err(bad(cmd, format!("removing the old teeth would also remove feature {extra}, which is not the gear's own"))); + } + } + let active = s.active_component; + s.execute("component.activate", &json!({"component": comp}))?; + build(s, &g, &ext, cmd)?; + s.doc_mut().gears.insert(comp, record(&g, &ext)); + // A name the user chose stays; the default one follows the values. + let name = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone()).unwrap_or_default(); + let name = if name == gear_name(was.internal, was.module, was.teeth) { gear_name(g.internal, g.module, g.teeth) } else { name }; + if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) { + c.name = name.clone(); + } + s.execute("component.activate", &json!({"component": active}))?; + s.refresh(); + // An error the design already had elsewhere is not this edit's. + if let Some(e) = s.model.results.iter().find_map(|r| r.error.clone().filter(|e| !before.contains(&(r.id, e.clone())))) { + return Err(crate::EngineError::Other(e)); + } + let occ = s.doc.occurrences.iter().find(|o| o.component == comp).map(|o| o.id).unwrap_or(0); + reply(&g, comp, occ, name) +} diff --git a/crates/engine/src/cmd/gears_tests.rs b/crates/engine/src/cmd/gears_tests.rs new file mode 100644 index 00000000000..b9b75898d24 --- /dev/null +++ b/crates/engine/src/cmd/gears_tests.rs @@ -0,0 +1,425 @@ +//! `gear.insert`: the gear's size, volume and build time. + +use std::f64::consts::PI; + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn volume(s: &mut Session) -> f64 { + let m = run(s, "inspect.measure", json!({})); + m["bodies"].as_array().map(|b| b.iter().filter_map(|x| x["volume_mm3"].as_f64()).sum()).unwrap_or(0.0) +} + +#[test] +fn a_gear_is_solid_between_its_root_and_tip_circles() { + let mut s = Session::default(); + let r = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + assert!((r["pitch_diameter"].as_f64().unwrap_or(0.0) - 40.0).abs() < 1e-9); + let v = volume(&mut s); + let (root, tip) = (17.5f64, 22.0f64); + assert!(v > PI * root * root * 10.0 && v < PI * tip * tip * 10.0, "{v}"); + // The pitch circle cuts a tooth and a gap equally: the area is about that of the pitch circle. + assert!((v / 10.0 - PI * 20.0 * 20.0).abs() < 0.06 * PI * 400.0, "{v}"); +} + +#[test] +fn hostile_gear_parameters_are_refused_and_leave_the_design_alone() { + let mut s = Session::default(); + for p in [ + json!({"module": 0, "teeth": 20}), + json!({"module": -2, "teeth": 20}), + json!({"module": 2, "teeth": 3}), + json!({"module": 2, "teeth": 100000}), + json!({"module": 2, "teeth": 20, "pressure_angle": 90}), + json!({"module": 2, "teeth": 20, "face_width": 0}), + json!({"module": 2, "teeth": 20, "flank_points": 100000}), + json!({"module": 2, "teeth": 20, "profile_shift": 1e9}), + json!({"module": 1e300, "teeth": 20}), + ] { + assert!(s.execute("gear.insert", &p).is_err(), "{p}"); + } + assert_eq!(volume(&mut s), 0.0); +} + +#[test] +fn a_gear_with_many_teeth_builds_with_the_right_size() { + // Four edges a tooth keep the extrude cheap (#6796): a 120-tooth gear is still solid at its pitch circle. + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 1, "teeth": 120, "face_width": 5})); + let v = volume(&mut s); + assert!((v / 5.0 - PI * 60.0 * 60.0).abs() < 0.03 * PI * 3600.0, "{v}"); +} + +fn tip_diameter(r: &Value) -> f64 { + r["tip_diameter"].as_f64().unwrap_or(0.0) +} + +#[test] +fn editing_a_gear_rebuilds_its_teeth_in_place() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + let comp = g["component"].clone(); + let before = volume(&mut s); + let e = run(&mut s, "gear.edit", json!({"component": comp, "teeth": 30})); + // The same component and occurrence, a bigger gear: 30 teeth of module 2 is Ø60 pitch. + assert_eq!((&e["component"], &e["occurrence"]), (&g["component"], &g["occurrence"])); + assert!((e["pitch_diameter"].as_f64().unwrap_or(0.0) - 60.0).abs() < 1e-9); + assert!(tip_diameter(&e) > tip_diameter(&g)); + let after = volume(&mut s); + assert!((after / 10.0 - PI * 30.0 * 30.0).abs() < 0.06 * PI * 900.0, "{before} {after}"); + // The default name follows the values. + assert_eq!(e["name"], "Spur Gear M2 Z30"); + // One undo takes the edit back. + run(&mut s, "edit.undo", json!({})); + assert!((volume(&mut s) - before).abs() < 1e-6 * before); + assert_eq!(s.doc.gears[&comp.as_u64().unwrap_or(0)].teeth, 20); +} + +#[test] +fn editing_a_gear_to_the_values_it_has_changes_nothing() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10, "helix_angle": 15, "bore_diameter": 6})); + let comp = g["component"].as_u64().unwrap_or(0); + let (undo, features, revision) = (s.undo.len(), s.doc.features.len(), s.revision); + let ids: Vec = s.doc.features.iter().map(|f| f.id).collect(); + // The form sends every value; sending the saved ones, or none, is no edit. + for p in + [json!({"component": comp}), json!({"component": comp, "module": 2, "teeth": 20, "face_width": 10, "helix_angle": 15, "bore_diameter": 6})] + { + let e = run(&mut s, "gear.edit", p); + assert_eq!(e["component"].as_u64(), Some(comp)); + assert!((e["pitch_diameter"].as_f64().unwrap_or(0.0) - 40.0).abs() < 1e-9); + } + assert_eq!(s.undo.len(), undo, "no undo step"); + assert_eq!(s.doc.features.len(), features); + assert_eq!(s.doc.features.iter().map(|f| f.id).collect::>(), ids, "the features are not rebuilt"); + assert_eq!(s.revision, revision, "the document is untouched"); + // A real change still edits. + run(&mut s, "gear.edit", json!({"component": comp, "teeth": 21})); + assert_eq!(s.undo.len(), undo + 1); +} + +#[test] +fn the_form_diameters_are_the_ones_the_command_reports() { + let mut s = Session::default(); + for (internal, shift) in [(false, 0.3), (true, 0.0)] { + let r = run(&mut s, "gear.insert", json!({"module": 2.5, "teeth": 24, "pressure_angle": 22, "profile_shift": shift, "internal": internal})); + let d = crate::cmd::gear_diameters(2.5, 24, 22.0, shift, 0.25, internal).expect("diameters"); + for (got, key) in d.iter().zip(["pitch_diameter", "base_diameter", "tip_diameter", "root_diameter"]) { + assert!((got - r[key].as_f64().unwrap_or(f64::NAN)).abs() < 1e-9, "{internal} {key}"); + } + } + assert!(crate::cmd::gear_diameters(f64::NAN, 20, 20.0, 0.0, 0.25, false).is_none()); +} + +#[test] +fn a_gear_keeps_its_values_through_save_and_reopen() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 1.5, "teeth": 24, "pressure_angle": 25, "face_width": 8, "backlash": 0.05})); + let comp = g["component"].as_u64().unwrap_or(0); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json().to_string()).unwrap()); + assert_eq!(reopened.doc.gears.get(&comp), s.doc.gears.get(&comp)); + // The reopened design edits the same gear. + let e = run(&mut reopened, "gear.edit", json!({"component": comp, "face_width": 12})); + assert_eq!(e["component"].as_u64(), Some(comp)); + assert_eq!(reopened.doc.gears[&comp].teeth, 24); + assert_eq!(reopened.doc.gears[&comp].backlash, 0.05); +} + +#[test] +fn a_bad_gear_edit_is_refused_and_leaves_the_gear_alone() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20})); + let comp = g["component"].clone(); + let before = volume(&mut s); + for p in [json!({"teeth": 2}), json!({"module": -1}), json!({"pressure_angle": 90}), json!({"face_width": 0}), json!({"profile_shift": 1e9})] { + let mut p = p; + p["component"] = comp.clone(); + assert!(s.execute("gear.edit", &p).is_err(), "{p}"); + } + assert!(s.execute("gear.edit", &json!({"component": 999, "teeth": 30})).is_err()); + assert!(s.execute("gear.edit", &json!({"component": "nothing"})).is_err()); + assert_eq!(volume(&mut s), before); + assert_eq!(s.doc.gears[&comp.as_u64().unwrap_or(0)].teeth, 20); +} + +#[test] +fn deleting_a_gear_forgets_its_values() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20})); + run(&mut s, "component.delete", json!({"component": g["component"]})); + assert!(s.doc.gears.is_empty()); +} + +#[test] +fn an_internal_gear_is_a_ring_with_its_teeth_inside() { + let mut s = Session::default(); + let r = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 40, "face_width": 8, "internal": true})); + assert_eq!(r["name"], "Internal Gear M2 Z40"); + // Tips of the ring's teeth are inside the pitch circle, the roots outside it. + assert!((r["tip_diameter"].as_f64().unwrap_or(0.0) - 76.0).abs() < 1e-9); + assert!((r["root_diameter"].as_f64().unwrap_or(0.0) - 85.0).abs() < 1e-9); + // The default ring is two modules thick outside the roots: outer radius 42.5 + 4. The pitch circle cuts a tooth and a gap equally. + let v = volume(&mut s); + assert!((v / 8.0 - PI * (46.5 * 46.5 - 40.0 * 40.0)).abs() < 0.06 * PI * 46.5 * 46.5, "{v}"); +} + +#[test] +fn an_external_gear_takes_an_axle_hole_and_edit_can_turn_it_into_a_ring() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + let solid = volume(&mut s); + run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "bore_diameter": 10})); + // The axle hole takes a cylinder 10 mm across and 10 mm long out of the gear. + assert!((solid - volume(&mut s) - PI * 5.0 * 5.0 * 10.0).abs() < 1.0, "{solid}"); + run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "bore_diameter": 0})); + assert!((volume(&mut s) - solid).abs() < 1e-6); + // Inside out: the saved axle hole is dropped and the name follows. + let r = run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "internal": true, "teeth": 40})); + assert_eq!(r["name"], "Internal Gear M2 Z40"); + // One ring: its area is the pitch-circle annulus out to the default rim (outer radius 46.5), not zero and not a disc. + let bodies = run(&mut s, "inspect.measure", json!({}))["bodies"].as_array().map_or(0, Vec::len); + assert_eq!(bodies, 1); + let v = volume(&mut s); + assert!((v / 10.0 - PI * (46.5 * 46.5 - 40.0 * 40.0)).abs() < 0.06 * PI * 46.5 * 46.5, "{v}"); +} + +#[test] +fn turning_a_shifted_gear_into_a_ring_drops_the_shift_and_a_fraction_of_flank_points_is_refused() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "profile_shift": 0.3})); + run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "internal": true, "teeth": 40})); + assert!(s.doc.gears.values().all(|g| g.internal && g.profile_shift == 0.0)); + let before = s.doc.gears.clone(); + for bad in [json!(2.5), json!(-3), json!("8")] { + assert!(s.execute("gear.insert", &json!({"module": 2, "teeth": 20, "flank_points": bad})).is_err()); + } + assert_eq!(s.doc.gears, before); +} + +#[test] +fn edit_gear_refuses_when_the_component_holds_features_that_are_not_the_gears() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + run(&mut s, "component.activate", json!({"component": g["component"]})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.finish", json!({})); + let features = s.doc.features.len(); + assert!(s.execute("gear.edit", &json!({"component": g["component"], "teeth": 24})).is_err()); + assert_eq!(s.doc.features.len(), features); + assert_eq!(s.doc.gears[&g["component"].as_u64().unwrap_or(0)].teeth, 20); +} + +#[test] +fn edit_gear_refuses_a_swapped_feature_though_the_count_still_matches() { + let mut s = Session::default(); + let g = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + let comp = g["component"].as_u64().unwrap_or(0); + // Take the gear's last feature out and put a user's sketch in its place: same count. + let last = s.doc.features.iter().rev().find(|f| f.component == comp).map(|f| f.id).unwrap_or(0); + assert!(s.doc_mut().delete_feature(last).is_ok()); + run(&mut s, "component.activate", json!({"component": comp})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.finish", json!({})); + let features = s.doc.features.len(); + assert!(s.execute("gear.edit", &json!({"component": comp, "teeth": 24})).is_err()); + assert_eq!(s.doc.features.len(), features); +} + +#[test] +fn turning_a_double_helical_gear_into_a_ring_drops_the_flag_but_an_explicit_true_is_refused() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "helix_angle": 20, "double_helical": true})); + run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "internal": true, "teeth": 40})); + assert!(s.doc.gears.values().all(|g| g.internal && !g.double_helical)); + let before = s.doc.gears.clone(); + assert!(s.execute("gear.edit", &json!({"component": "Internal Gear M2 Z40", "double_helical": true})).is_err()); + assert_eq!(s.doc.gears, before); +} + +#[test] +fn an_internal_or_bored_gear_keeps_its_values_through_save_and_reopen() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 30, "internal": true, "rim_thickness": 5})); + run(&mut s, "gear.insert", json!({"module": 1, "teeth": 24, "bore_diameter": 6})); + let saved = s.doc.gears.clone(); + let text = serde_json::to_string(&saved).unwrap_or_default(); + let back: std::collections::BTreeMap = serde_json::from_str(&text).unwrap_or_default(); + assert_eq!(back, saved); + assert!(saved.values().any(|g| g.internal && g.rim_thickness == 5.0)); + assert!(saved.values().any(|g| !g.internal && g.bore_diameter == 6.0)); +} + +#[test] +fn hostile_internal_and_bore_values_are_refused_and_leave_the_design_alone() { + let mut s = Session::default(); + for p in [ + json!({"module": 2, "teeth": 40, "internal": true, "profile_shift": 0.5}), + json!({"module": 2, "teeth": 40, "internal": true, "bore_diameter": 5}), + json!({"module": 2, "teeth": 40, "internal": true, "rim_thickness": -1}), + json!({"module": 2, "teeth": 40, "rim_thickness": 3}), + json!({"module": 2, "teeth": 40, "bore_diameter": -1}), + json!({"module": 2, "teeth": 40, "bore_diameter": 1e9}), + json!({"module": 2, "teeth": 40, "bore_diameter": 80}), + json!({"module": 2, "teeth": 40, "internal": "yes"}), + json!({"module": 2, "teeth": 40, "backlash": -1}), + ] { + assert!(s.execute("gear.insert", &p).is_err(), "{p}"); + } + assert_eq!(volume(&mut s), 0.0); +} + +fn bodies(s: &mut Session) -> Vec { + run(s, "inspect.measure", json!({}))["bodies"].as_array().cloned().unwrap_or_default() +} + +#[test] +fn a_helical_gear_has_the_volume_of_its_straight_twin_and_the_same_height() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10, "name": "Straight"})); + let straight = volume(&mut s); + run(&mut s, "gear.edit", json!({"component": "Straight", "helix_angle": 20})); + let b = bodies(&mut s); + assert_eq!(b.len(), 1); + // Turning the outline as it goes up keeps every slice's area. + assert!((volume(&mut s) - straight).abs() < 0.005 * straight, "{straight}"); + assert!((b[0]["bbox"]["max"][2].as_f64().unwrap_or(0.0) - 10.0).abs() < 1e-6); + // And back to straight teeth. + run(&mut s, "gear.edit", json!({"component": "Straight", "helix_angle": 0})); + assert!((volume(&mut s) - straight).abs() < 1e-6); +} + +#[test] +fn a_double_helical_gear_is_one_body_of_two_mirrored_halves() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10, "name": "Straight"})); + let straight = volume(&mut s); + run(&mut s, "gear.edit", json!({"component": "Straight", "helix_angle": 25, "double_helical": true})); + let b = bodies(&mut s); + assert_eq!(b.len(), 1, "{b:?}"); + assert!((volume(&mut s) - straight).abs() < 0.005 * straight); + assert!((b[0]["bbox"]["max"][2].as_f64().unwrap_or(0.0) - 10.0).abs() < 1e-6); + assert!(b[0]["bbox"]["min"][2].as_f64().unwrap_or(1.0).abs() < 1e-6); +} + +#[test] +fn an_internal_gear_can_be_helical_and_an_axle_hole_can_sit_off_centre() { + let mut s = Session::default(); + let flat = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 40, "face_width": 8, "internal": true, "name": "Ring"})); + assert!(flat["component"].is_u64()); + let ring = volume(&mut s); + run(&mut s, "gear.edit", json!({"component": "Ring", "helix_angle": 15})); + assert!((volume(&mut s) - ring).abs() < 0.01 * ring, "{ring}"); + + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + let solid = volume(&mut s); + run(&mut s, "gear.edit", json!({"component": "Spur Gear M2 Z20", "bore_diameter": 6, "bore_offset": 6})); + assert!((solid - volume(&mut s) - PI * 3.0 * 3.0 * 10.0).abs() < 1.0); + // The hole is on +X, so what is left is heavier on -X. + let b = bodies(&mut s); + assert!(b[0]["center_of_mass"][0].as_f64().unwrap_or(0.0) < -0.1, "{b:?}"); +} + +#[test] +fn helical_and_offset_values_are_kept_through_save_and_refused_when_hostile() { + let mut s = Session::default(); + run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "helix_angle": -15, "double_helical": true, "bore_diameter": 5, "bore_offset": 2})); + let saved = s.doc.gears.clone(); + let text = serde_json::to_string(&saved).unwrap_or_default(); + let back: std::collections::BTreeMap = serde_json::from_str(&text).unwrap_or_default(); + assert_eq!(back, saved); + assert!(saved.values().any(|g| g.helix_angle == -15.0 && g.double_helical && g.bore_offset == 2.0)); + + let mut s = Session::default(); + for p in [ + json!({"module": 2, "teeth": 20, "helix_angle": 60}), + json!({"module": 2, "teeth": 20, "helix_angle": "x"}), + json!({"module": 2, "teeth": 20, "double_helical": true}), + json!({"module": 2, "teeth": 20, "double_helical": 1, "helix_angle": 10}), + json!({"module": 2, "teeth": 40, "internal": true, "helix_angle": 10, "double_helical": true}), + json!({"module": 2, "teeth": 20, "bore_offset": 3}), + json!({"module": 2, "teeth": 20, "bore_diameter": 4, "bore_offset": 20}), + json!({"module": 2, "teeth": 20, "face_width": 1e6, "helix_angle": 45}), + ] { + assert!(s.execute("gear.insert", &p).is_err(), "{p}"); + } + assert_eq!(volume(&mut s), 0.0); +} + +fn root_diameter(r: &Value) -> f64 { + r["root_diameter"].as_f64().unwrap_or(0.0) +} + +#[test] +fn clearance_sets_how_deep_the_roots_lie_and_defaults_to_the_standard() { + let mut s = Session::default(); + let std = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10})); + let deep = run(&mut s, "gear.insert", json!({"module": 2, "teeth": 20, "face_width": 10, "clearance": 0.4})); + // Root radius is pitch radius minus module times (1 + clearance): 20 - 2.5 and 20 - 2.8. + assert!((root_diameter(&std) - 35.0).abs() < 1e-9, "{}", root_diameter(&std)); + assert!((root_diameter(&deep) - 34.4).abs() < 1e-9, "{}", root_diameter(&deep)); + let comp = deep["component"].as_u64().unwrap_or(0); + assert_eq!(s.doc.gears[&comp].clearance, 0.4); + // An edit can change it back, and a gear saved before clearance existed reads as 0.25. + let back = run(&mut s, "gear.edit", json!({"component": comp, "clearance": 0.25})); + assert!((root_diameter(&back) - 35.0).abs() < 1e-9); + let old: solidcraft_doc::SpurGear = + serde_json::from_value(json!({"module": 2.0, "teeth": 20, "pressure_angle": 20.0, "face_width": 10.0, "flank_points": 8})) + .expect("an older gear reads"); + assert_eq!((old.clearance, old.backlash_thicker), (0.25, false)); + let saved = serde_json::to_value(&s.doc.gears[&comp]).expect("saves"); + assert!(saved.get("clearance").is_none(), "defaults are not written: {saved}"); +} + +#[test] +fn the_backlash_direction_thins_or_thickens_the_teeth() { + let mut s = Session::default(); + let v = |s: &mut Session, extra: Value| { + let mut p = json!({"module": 2, "teeth": 24, "face_width": 10}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + run(s, "gear.insert", p); + let x = volume(s); + run(s, "edit.undo", json!({})); + x + }; + let none = v(&mut s, json!({})); + let thin = v(&mut s, json!({"backlash": 0.2})); + let explicit = v(&mut s, json!({"backlash": 0.2, "backlash_direction": "thinner"})); + let thick = v(&mut s, json!({"backlash": 0.2, "backlash_direction": "thicker"})); + assert!(thin < none && none < thick, "{thin} {none} {thick}"); + assert!((thin - explicit).abs() < 1e-9); + // Equal and opposite on the pitch circle: the two are as far from the plain gear as each other. + assert!(((none - thin) - (thick - none)).abs() < 0.05 * (none - thin), "{thin} {none} {thick}"); +} + +#[test] +fn hostile_clearance_and_direction_values_are_refused() { + let mut s = Session::default(); + let ok = json!({"module": 2, "teeth": 20, "face_width": 10}); + for extra in [ + json!({"clearance": -0.1}), + json!({"clearance": 0.7}), + json!({"clearance": 1e300}), + json!({"backlash_direction": "sideways"}), + json!({"backlash_direction": 3}), + json!({"backlash": 3.1, "backlash_direction": "thicker"}), + ] { + let mut p = ok.clone(); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + assert!(s.execute("gear.insert", &p).is_err(), "{extra}"); + } + assert!(s.doc.gears.is_empty(), "a refused gear leaves nothing behind"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index a2e1c9ca55a..b0db6f59d89 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -155,6 +155,7 @@ pub(crate) use file::up_form; pub(crate) use file::usable_path; pub use file::use_import_cache_dir; pub use frame::member_section_view; +pub use gears::gear_diameters; pub(crate) use inspect::color_param; pub use join_pieces::Addition; pub use join_pieces::addition; @@ -214,6 +215,8 @@ mod frame_end_cap; mod frame_gusset; mod frame_rotate_member; mod free_occurrences; +mod gear_profile; +mod gears; mod hole_callout; pub(crate) mod inspect; mod interference; @@ -262,6 +265,8 @@ pub(crate) use measure_shape::Shape; pub(crate) use point_cloud::filters as point_cloud_filters; pub(crate) use script::step_params; #[cfg(test)] +mod gears_tests; +#[cfg(test)] mod kernel_heal_tests; mod panels; mod parameter_sweep; @@ -760,6 +765,7 @@ fn gather_command_specs() -> Vec<&'static CommandSpec> { v.extend(motion_simulate::load_case::COMMANDS.iter()); v.extend(panels::COMMANDS.iter()); v.extend(config::COMMANDS.iter()); + v.extend(gears::COMMANDS.iter()); v.extend(parts::COMMANDS.iter()); v.extend(pulleys::COMMANDS.iter()); v.extend(shaft_spline::COMMANDS.iter()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1f45ac913e4..9c25629de59 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5569,6 +5569,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool { sheet, plastic, parts, + gears, links, configs, favorites, @@ -5621,6 +5622,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool { && *sheet == b.sheet && *plastic == b.plastic && *parts == b.parts + && *gears == b.gears && *links == b.links && *configs == b.configs && *favorites == b.favorites diff --git a/crates/engine/src/schema/gears.rs b/crates/engine/src/schema/gears.rs new file mode 100644 index 00000000000..9e97eca7a15 --- /dev/null +++ b/crates/engine/src/schema/gears.rs @@ -0,0 +1,133 @@ +//! Contract and reply type for `gear.insert` in `cmd/gears.rs`: involute spur gears (#6796). + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Insert an involute spur gear, external or internal, as a new component: a tooth outline sketched on +/// the XY plane and extruded along +Z. One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct GearInsertParams { + /// Module in millimetres: pitch diameter divided by tooth count. Above 0. + pub module: f64, + /// Number of teeth, 6 to 1000. + pub teeth: u32, + /// Pressure angle in degrees, above 0 and at most 35 (default 20). + #[serde(default)] + pub pressure_angle: Option, + /// Thickness of the gear along +Z in millimetres. Above 0 (default: the module times 10). + #[serde(default)] + pub face_width: Option, + /// Profile shift coefficient (default 0). + #[serde(default)] + pub profile_shift: Option, + /// Backlash in millimetres taken from the tooth thickness on the pitch circle (default 0). + #[serde(default)] + pub backlash: Option, + /// Points along each tooth flank, 2 to 64 (default 8). More points follow the involute + /// more closely and build more slowly. + #[serde(default)] + pub flank_points: Option, + /// Clearance coefficient from 0 to 0.6 of the module (default 0.25): the roots lie `module × (1 + clearance - profile_shift)` inside the pitch circle. + #[serde(default)] + pub clearance: Option, + /// `thinner` (default): the backlash is taken off the teeth. `thicker`: it is added to them, for a mate that carries the whole clearance. + #[serde(default)] + pub backlash_direction: Option, + /// An internal gear: a ring whose teeth point inward (default false). Profile shift is not used. + #[serde(default)] + pub internal: Option, + /// Internal gears only: ring thickness outside the tooth roots in millimetres (default: twice the module). + #[serde(default)] + pub rim_thickness: Option, + /// External gears only: diameter of an axle hole through the centre in millimetres (default: none). + #[serde(default)] + pub bore_diameter: Option, + /// External gears only: how far the axle hole's centre is from the gear's centre along +X, in + /// millimetres (default 0). The hole, with this offset, must stay inside 90% of the root circle. + #[serde(default)] + pub bore_offset: Option, + /// Helix angle on the pitch circle in degrees, from -45 to 45 (default 0: straight teeth). + /// The teeth turn over the face width; a positive angle is a right-hand helix. + #[serde(default)] + pub helix_angle: Option, + /// External helical gears only: two mirrored halves, each half the face width (default false). + #[serde(default)] + pub double_helical: Option, + /// The component's name (default: `Spur Gear M2 Z20`, or `Internal Gear M2 Z40`). + #[serde(default)] + pub name: Option, +} + +/// Change an inserted gear's values and rebuild its teeth in place; the component, its placement +/// and its joints stay. One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct GearEditParams { + /// The gear's component, by id or name. + pub component: serde_json::Value, + /// New module in millimetres. + #[serde(default)] + pub module: Option, + /// New number of teeth, 6 to 1000. + #[serde(default)] + pub teeth: Option, + /// New pressure angle in degrees. + #[serde(default)] + pub pressure_angle: Option, + /// New thickness along +Z in millimetres. + #[serde(default)] + pub face_width: Option, + /// New profile shift coefficient. + #[serde(default)] + pub profile_shift: Option, + /// New backlash in millimetres. + #[serde(default)] + pub backlash: Option, + /// New clearance coefficient from 0 to 0.6 of the module : the roots lie `module × (1 + clearance - profile_shift)` inside the pitch circle. + #[serde(default)] + pub clearance: Option, + /// `thinner`: the backlash is taken off the teeth. `thicker`: it is added to them, for a mate that carries the whole clearance. + #[serde(default)] + pub backlash_direction: Option, + /// New points per flank, 2 to 64. + #[serde(default)] + pub flank_points: Option, + /// Make it an internal gear (true) or an external one (false). + #[serde(default)] + pub internal: Option, + /// New ring thickness outside the tooth roots of an internal gear, in millimetres. + #[serde(default)] + pub rim_thickness: Option, + /// New diameter of the axle hole through an external gear in millimetres; 0 removes it. + #[serde(default)] + pub bore_diameter: Option, + /// New offset of the axle hole along +X in millimetres. + #[serde(default)] + pub bore_offset: Option, + /// New helix angle in degrees; 0 makes the teeth straight. + #[serde(default)] + pub helix_angle: Option, + /// Make it a double helical gear (true) or not (false). + #[serde(default)] + pub double_helical: Option, +} + +/// What `gear.insert` and `gear.edit` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct InsertedGear { + /// The new component's id. + pub component: u64, + /// Its occurrence's id. + pub occurrence: u64, + /// The component's name. + pub name: String, + /// Pitch diameter in millimetres. + pub pitch_diameter: f64, + /// Base circle diameter in millimetres. + pub base_diameter: f64, + /// Tooth tip diameter in millimetres: the outside of an external gear, the inside of an internal one. + pub tip_diameter: f64, + /// Tooth root diameter in millimetres. + pub root_diameter: f64, +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index db8968cb01b..b89bc77967d 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -106,6 +106,7 @@ pub mod forms_prototype; pub mod frame; pub mod frame_plate; pub mod free_occurrences; +pub mod gears; pub mod gusset; pub mod hole_callout; pub mod hole_stacks; diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 9bba0340ca5..98108ac9ba7 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -95,6 +95,8 @@ pub const DOCUMENTED: &[&str] = &[ "frame.plate", "frame.rotate_member", "frame.trim", + "gear.edit", + "gear.insert", "inspect.accessibility", "inspect.center_of_mass", "inspect.colored_components", diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 648fb2bde09..6c06be2ac24 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1386,6 +1386,9 @@ fn viewport_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); } + if let Some(component) = crate::dialogs_gear::selected(app) { + v.push(cmd(app, "gear.edit", "Edit Gear").with(json!({"component":component}))); + } v.push(Item::sep()); v.push(act("ui.clear", "Clear Selection", "close").key("Esc")); } @@ -1480,6 +1483,9 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { if let Some(component) = crate::dialogs_part_size::component_for_bodies(app, bodies) { v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); } + if let Some(component) = crate::dialogs_gear::of_bodies(app, bodies) { + v.push(cmd(app, "gear.edit", "Edit Gear").with(json!({"component":component}))); + } v.push(Item::sep()); if !browser { v.push(act("ui.findBrowser", "Find in Browser", "list").with(json!({ "body": b }))); @@ -1905,6 +1911,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { if doc.parts.contains_key(&id) { v.push(cmd(app, "parts.resize", "Edit").with(json!({"component":id}))); } + if doc.gears.contains_key(&id) { + v.push(cmd(app, "gear.edit", "Edit Gear").with(json!({"component":id}))); + } // What a double-click on the row does comes first. let activate = act("ui.activate", "Activate", "component").with(json!({ "component": id })).on(!active); let edits = crate::edit_in_place::edits_on_double_click(app, id); @@ -2576,6 +2585,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { app.start("parts.resize"); } } + "gear.edit" => { + if let Some(component) = id_of(&p, "component") { + crate::dialogs_gear::open(app, component); + } else { + app.start("gear.edit"); + } + } "ui.appBarEdit" => crate::app_bar_custom::run(app, &p), "ui.appBarCustomize" | "ui.appBarReset" => app.start(&item.id), "ui.repeat" => { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 29dbdfd93e6..25c968d3714 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -607,6 +607,8 @@ crate::dialog_descriptor::dialog_descriptors! { InsertDrawing(crate::dialogs_insert_drawing::Place), /// Insert Airfoil: how the picked section goes in (`dialogs_insert_airfoil`). InsertAirfoil(crate::dialogs_insert_airfoil::Airfoil), + /// Insert Gear and Edit Gear (`dialogs_gear`). + Gear(crate::dialogs_gear::Gear), /// Shaft Spline: a splined shaft, its hub or both (`dialogs_shaft_spline`). ShaftSpline(Box), /// Insert Design: how the picked design comes in (`dialogs_insert_design`). @@ -1580,6 +1582,7 @@ impl Dialog { .or_else(|| crate::dialogs_motion::start(app, id)) .or_else(|| crate::dialogs_parts::start(app, id)) .or_else(|| crate::dialogs_part_size::start(app, id)) + .or_else(|| crate::dialogs_gear::start(app, id)) .or_else(|| crate::dialogs_pulley::start(app, id)) .or_else(|| crate::sketch_text::start(app, id)) .or_else(|| crate::sketch_text_move::start(app, id)) @@ -1903,6 +1906,8 @@ impl Dialog { Kind::Surface(_) => return true, Kind::SketchModify(k) => return k.previews(), Kind::Plastic(k) => return k.previews(), + // Web previews run on the window thread: a helical gear's sweep can outlast a frame. + Kind::Gear(g) => return !(cfg!(target_arch = "wasm32") && g.helix_angle != 0.0), Kind::Frame(_) | Kind::EndCap(_) | Kind::Dogbone(_) @@ -3893,6 +3898,7 @@ fn title(k: &Kind) -> &'static str { Kind::ViewNavigator(_) => "CUSTOM VIEW NAVIGATOR", Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::title(p), Kind::InsertAirfoil(_) => crate::dialogs_insert_airfoil::title(), + Kind::Gear(g) => crate::dialogs_gear::title(g), Kind::ShaftSpline(_) => crate::dialogs_shaft_spline::title(), Kind::InsertDesign(_) => crate::dialogs_insert_design::title(), Kind::Plastic(k) => k.title(), @@ -9246,6 +9252,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::UrdfExport(_) | Kind::ViewDxf { .. } | Kind::ViewNavigator(_) | Kind::InsertDesign(_) => return Ok(Vec::new()), Kind::InsertDrawing(p) => return crate::dialogs_insert_drawing::commands(p), Kind::InsertAirfoil(a) => return crate::dialogs_insert_airfoil::commands(a), + Kind::Gear(g) => return crate::dialogs_gear::commands(g), Kind::ShaftSpline(k) => return crate::dialogs_shaft_spline::commands_with(app, k, &d.inputs), Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra), Kind::Frame(k) => return crate::dialogs_frame::commands(app, k, &d.inputs, &d.extra), diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 002548585e7..feb701a3b57 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -24,6 +24,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> { Kind::ViewNavigator(_) => Some("view.navigator"), Kind::InsertDrawing(p) => Some(if p.command.ends_with("dxf") { "sketch.insert_dxf" } else { "sketch.insert_svg" }), Kind::InsertAirfoil(_) => Some("sketch.insert_airfoil"), + Kind::Gear(g) => Some(crate::dialogs_gear::command_id(g)), Kind::ShaftSpline(_) => Some(crate::dialogs_shaft_spline::COMMAND), Kind::InsertDesign(_) => Some("component.insert_design"), Kind::Sketch => Some("sketch.create"), @@ -608,6 +609,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: Kind::ViewNavigator(form) => crate::view_gizmo::rows(app, ui, form, &d.inputs), Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::rows(app, ui, p), Kind::InsertAirfoil(a) => crate::dialogs_insert_airfoil::rows(ui, a), + Kind::Gear(g) => crate::dialogs_gear::rows(ui, g), Kind::ShaftSpline(k) => { // A face taken by a row it does not belong in goes to its own row (a bore out of Shaft, a shaft out // of Bore, a start face out of a round face's row). After any change of the picks the row that diff --git a/crates/ui-egui/src/dialogs_gear.rs b/crates/ui-egui/src/dialogs_gear.rs new file mode 100644 index 00000000000..be77ec1f079 --- /dev/null +++ b/crates/ui-egui/src/dialogs_gear.rs @@ -0,0 +1,556 @@ +//! Insert Gear and Edit Gear: the gear's size, teeth and shape in one form, and OK runs +//! `gear.insert` or `gear.edit` (#6796). Edit Gear starts from the selected gear's saved values. + +use serde_json::{Value, json}; +use solidcraft_engine::doc::SpurGear; + +use crate::SolveApp; +use crate::dialogs::{Kind, form_row}; +use crate::selection::SelInput; + +/// The values the form edits. `component` is the gear being edited, or `None` for a new one. +/// `teeth` is a number field's value: it is rounded when OK runs. +#[derive(Clone, Debug, PartialEq)] +pub struct Gear { + pub component: Option, + /// The values the gear had when the form opened on it: what Reset goes back to. A new gear has none. + original: Option>, + pub internal: bool, + pub module: f64, + pub teeth: f64, + pub pressure_angle: f64, + pub face_width: f64, + pub profile_shift: f64, + pub backlash: f64, + pub backlash_thicker: bool, + pub clearance: f64, + pub flank_points: f64, + pub rim_thickness: f64, + pub bore_diameter: f64, + pub bore_offset: f64, + pub helix_angle: f64, + pub double_helical: bool, +} + +impl Gear { + /// A new gear: module 2, 20 teeth, the engine's own defaults for the rest. + fn new() -> Self { + Self { + component: None, + original: None, + internal: false, + module: 2.0, + teeth: 20.0, + pressure_angle: 20.0, + face_width: 20.0, + profile_shift: 0.0, + backlash: 0.0, + backlash_thicker: false, + clearance: 0.25, + flank_points: 8.0, + rim_thickness: 4.0, + bore_diameter: 0.0, + bore_offset: 0.0, + helix_angle: 0.0, + double_helical: false, + } + } + + fn saved(component: u64, g: &SpurGear) -> Self { + let mut gear = Self::saved_values(component, g); + gear.original = Some(Box::new(gear.clone())); + gear + } + + fn saved_values(component: u64, g: &SpurGear) -> Self { + Self { + component: Some(component), + original: None, + internal: g.internal, + module: g.module, + teeth: f64::from(g.teeth), + pressure_angle: g.pressure_angle, + face_width: g.face_width, + profile_shift: g.profile_shift, + backlash: g.backlash, + backlash_thicker: g.backlash_thicker, + clearance: g.clearance, + flank_points: f64::from(g.flank_points), + rim_thickness: if g.rim_thickness > 0.0 { g.rim_thickness } else { g.module * 2.0 }, + bore_diameter: g.bore_diameter, + bore_offset: g.bore_offset, + helix_angle: g.helix_angle, + double_helical: g.double_helical, + } + } +} + +/// The starting points the form offers: each sets what makes the kind of gear and leaves the size +/// (module, pressure angle, face width) as it is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Preset { + Spur, + Helical, + Herringbone, + Ring, +} + +impl Gear { + /// Back to what the form opened with: the saved values of the gear being edited, or the defaults. + pub fn reset(&mut self) { + *self = match self.original.take() { + // The copy stays, so a second Reset goes to the same place. + Some(o) => Self { original: Some(o.clone()), ..*o }, + None => Self::new(), + }; + } + + /// Make this a spur, helical, herringbone or ring gear; the axle hole and clearance stay. + pub fn preset(&mut self, p: Preset) { + (self.internal, self.helix_angle, self.double_helical) = (false, 0.0, false); + match p { + Preset::Spur => self.teeth = 20.0, + Preset::Helical => (self.teeth, self.helix_angle) = (20.0, 20.0), + Preset::Herringbone => (self.teeth, self.helix_angle, self.double_helical) = (20.0, 20.0, true), + Preset::Ring => { + self.internal = true; + self.teeth = 40.0; + self.rim_thickness = self.module * 2.0; + (self.bore_diameter, self.bore_offset) = (0.0, 0.0); + } + } + } +} + +/// Insert Gear always opens a new form; Edit Gear needs one gear selected, and tells the user +/// when there is none. +pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { + match id { + "gear.insert" => Some((Kind::Gear(Gear::new()), vec![])), + "gear.edit" => { + let component = selected(app)?; + Some((Kind::Gear(Gear::saved(component, app.session.doc.gears.get(&component)?)), vec![])) + } + _ => None, + } +} + +/// The component a selection stands for, if it is a gear. +pub fn selected(app: &SolveApp) -> Option { + crate::dialogs_part_size::selected_component_where(app, |doc, c| doc.gears.contains_key(&c)) +} + +/// The component the picked bodies belong to, if it is a gear. +pub fn of_bodies(app: &SolveApp, bodies: &[String]) -> Option { + crate::dialogs_part_size::component_for_bodies_where(app, bodies, |doc, c| doc.gears.contains_key(&c)) +} + +/// Edit Gear for a component picked in a menu: the form opens on exactly that gear. +pub fn open(app: &mut SolveApp, component: u64) { + app.session.selection.clear(); + app.tree.picked_components = vec![component]; + app.start("gear.edit"); +} + +pub fn command_id(g: &Gear) -> &'static str { + if g.component.is_some() { "gear.edit" } else { "gear.insert" } +} + +pub fn title(g: &Gear) -> &'static str { + if g.component.is_some() { "EDIT GEAR" } else { "INSERT GEAR" } +} + +fn number(ui: &mut egui::Ui, label_key: &str, handle: &str, v: &mut f64, range: std::ops::RangeInclusive, speed: f64, suffix: &str) { + form_row(ui, solidcraft_ui_text::tr(label_key), |ui| { + let r = crate::ui_kit::number_field(ui, v, range, speed, suffix); + crate::scenario::publish_handle(handle, r.rect.center()); + }); +} + +pub fn rows(ui: &mut egui::Ui, g: &mut Gear) { + { + ui.label(solidcraft_ui_text::tr("gear.presets")); + ui.horizontal_wrapped(|ui| { + for (key, handle, p) in [ + ("gear.preset_spur", "dialog:gear:preset_spur", Preset::Spur), + ("gear.preset_helical", "dialog:gear:preset_helical", Preset::Helical), + ("gear.preset_herringbone", "dialog:gear:preset_herringbone", Preset::Herringbone), + ("gear.preset_ring", "dialog:gear:preset_ring", Preset::Ring), + ] { + let r = crate::ui_kit::button(ui, solidcraft_ui_text::tr(key), crate::ui_kit::Button::Normal); + crate::scenario::publish_handle(handle, r.rect.center()); + if r.clicked() { + g.preset(p); + } + } + let r = crate::ui_kit::button(ui, solidcraft_ui_text::tr("gear.reset"), crate::ui_kit::Button::Normal); + crate::scenario::publish_handle("dialog:gear:reset", r.rect.center()); + if r.clicked() { + g.reset(); + } + }); + } + form_row(ui, "", |ui| { + let r = crate::ui_kit::checkbox(ui, solidcraft_ui_text::tr("gear.internal"), &mut g.internal); + crate::scenario::publish_handle("dialog:gear:internal", r.rect.center()); + }); + number(ui, "gear.module", "dialog:gear:module", &mut g.module, 0.001..=1000.0, 0.1, " mm"); + number(ui, "gear.teeth", "dialog:gear:teeth", &mut g.teeth, 6.0..=1000.0, 1.0, ""); + number(ui, "gear.pressure_angle", "dialog:gear:pressure_angle", &mut g.pressure_angle, 0.1..=35.0, 0.5, "\u{b0}"); + number(ui, "gear.face_width", "dialog:gear:face_width", &mut g.face_width, 0.001..=1e6, 0.5, " mm"); + if !g.internal { + number(ui, "gear.profile_shift", "dialog:gear:profile_shift", &mut g.profile_shift, -2.0..=2.0, 0.05, ""); + } + number(ui, "gear.backlash", "dialog:gear:backlash", &mut g.backlash, 0.0..=100.0, 0.01, " mm"); + if g.backlash > 0.0 { + form_row(ui, "", |ui| { + let r = crate::ui_kit::checkbox(ui, solidcraft_ui_text::tr("gear.backlash_thicker"), &mut g.backlash_thicker); + crate::scenario::publish_handle("dialog:gear:backlash_thicker", r.rect.center()); + }); + } + number(ui, "gear.clearance", "dialog:gear:clearance", &mut g.clearance, 0.0..=0.6, 0.01, ""); + number(ui, "gear.flank_points", "dialog:gear:flank_points", &mut g.flank_points, 2.0..=64.0, 1.0, ""); + number(ui, "gear.helix_angle", "dialog:gear:helix_angle", &mut g.helix_angle, -45.0..=45.0, 0.5, "\u{b0}"); + if g.internal { + number(ui, "gear.rim_thickness", "dialog:gear:rim_thickness", &mut g.rim_thickness, 0.001..=1e6, 0.5, " mm"); + } else { + form_row(ui, "", |ui| { + // Two mirrored helical halves need a helix angle to mirror. + ui.add_enabled_ui(g.helix_angle != 0.0, |ui| { + let r = crate::ui_kit::checkbox(ui, solidcraft_ui_text::tr("gear.double_helical"), &mut g.double_helical); + crate::scenario::publish_handle("dialog:gear:double_helical", r.rect.center()); + }); + }); + number(ui, "gear.bore_diameter", "dialog:gear:bore_diameter", &mut g.bore_diameter, 0.0..=1e6, 0.5, " mm"); + if g.bore_diameter > 0.0 { + number(ui, "gear.bore_offset", "dialog:gear:bore_offset", &mut g.bore_offset, -1e6..=1e6, 0.5, " mm"); + } + } + ui.separator(); + diameters(ui, g); +} + +/// The profile's diameters, from the values as they are now. They follow the form, so they show +/// before anything is inserted. +fn diameters(ui: &mut egui::Ui, g: &Gear) { + let teeth = g.teeth.round().clamp(0.0, 1e6) as u32; + let Some(d) = solidcraft_engine::cmd::gear_diameters(g.module, teeth, g.pressure_angle, g.profile_shift, g.clearance, g.internal) else { + return; + }; + for (key, handle, v) in [ + ("gear.pitch_diameter", "dialog:gear:pitch_diameter", d[0]), + ("gear.base_diameter", "dialog:gear:base_diameter", d[1]), + ("gear.tip_diameter", "dialog:gear:tip_diameter", d[2]), + ("gear.root_diameter", "dialog:gear:root_diameter", d[3]), + ] { + form_row(ui, solidcraft_ui_text::tr(key), |ui| { + let r = ui.label(format!("{v:.3} mm")); + crate::scenario::publish_handle(handle, r.rect.center()); + }); + } +} + +/// The command OK runs. Every value is sent, so an edit replaces what was saved. A value the +/// form cannot hold is refused here; the engine checks the rest and says what is wrong. +pub fn commands(g: &Gear) -> Result, String> { + let finite = [ + g.module, + g.teeth, + g.pressure_angle, + g.face_width, + g.profile_shift, + g.backlash, + g.clearance, + g.flank_points, + g.rim_thickness, + g.bore_diameter, + g.bore_offset, + g.helix_angle, + ] + .iter() + .all(|v| v.is_finite()); + if !finite { + return Err("every gear value must be a number".into()); + } + let mut p = json!({ + "module": g.module, + "teeth": g.teeth.round().clamp(0.0, 1e6) as u32, + "pressure_angle": g.pressure_angle, + "face_width": g.face_width, + "backlash": g.backlash, + "backlash_direction": if g.backlash_thicker { "thicker" } else { "thinner" }, + "clearance": g.clearance, + "flank_points": g.flank_points.round().clamp(0.0, 1e6) as u32, + "helix_angle": g.helix_angle, + "internal": g.internal, + }); + if g.internal { + p["rim_thickness"] = json!(g.rim_thickness); + p["bore_diameter"] = json!(0); + } else { + p["profile_shift"] = json!(g.profile_shift); + p["double_helical"] = json!(g.double_helical && g.helix_angle != 0.0); + p["bore_diameter"] = json!(g.bore_diameter); + p["bore_offset"] = json!(if g.bore_diameter > 0.0 { g.bore_offset } else { 0.0 }); + p["rim_thickness"] = json!(0); + } + if g.internal { + p["double_helical"] = json!(false); + p["bore_offset"] = json!(0); + } + if let Some(c) = g.component { + p["component"] = json!(c); + } + Ok(vec![(command_id(g).to_string(), p)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scenario::{Harness, handle_at}; + + fn gear(h: &Harness) -> Option<(u64, SpurGear)> { + h.app.session.doc.gears.iter().next().map(|(c, g)| (*c, g.clone())) + } + + /// The Insert Gear form builds a gear from the values set in it, in one undo step. + #[test] + fn the_insert_form_builds_a_helical_gear_with_an_axle_hole() { + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(3); + let Some(Kind::Gear(g)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no gear form: {:?}", h.app.status) }; + assert_eq!((g.module, g.teeth, g.component), (2.0, 20.0, None)); + assert!(handle_at("dialog:gear:module").is_some() && handle_at("dialog:gear:helix_angle").is_some(), "the fields are drawn"); + assert!(handle_at("dialog:gear:rim_thickness").is_none(), "an external gear has no ring"); + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + (g.module, g.teeth, g.face_width, g.helix_angle, g.bore_diameter) = (1.5, 24.0, 8.0, 15.0, 5.0); + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let (_, saved) = gear(&h).expect("a gear is saved"); + assert_eq!((saved.module, saved.teeth, saved.face_width, saved.helix_angle, saved.bore_diameter), (1.5, 24, 8.0, 15.0, 5.0)); + h.app.run("edit.undo", json!({})).unwrap(); + h.settle(); + assert!(h.app.session.doc.gears.is_empty(), "one undo removes the gear"); + } + + /// The form carries clearance, the backlash direction and the profile accuracy + /// to the gear, and Edit Gear brings them back. + #[test] + fn the_form_sets_clearance_backlash_direction_and_accuracy() { + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(3); + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + (g.module, g.teeth, g.backlash, g.backlash_thicker) = (2.0, 24.0, 0.1, true); + (g.clearance, g.flank_points) = (0.3, 12.0); + } + h.frames(2); + for k in ["clearance", "flank_points", "backlash_thicker"] { + assert!(handle_at(&format!("dialog:gear:{k}")).is_some(), "{k}"); + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let (component, saved) = gear(&h).expect("a gear is saved"); + assert_eq!((saved.clearance, saved.flank_points, saved.backlash_thicker), (0.3, 12, true)); + h.app.tree.picked_components = vec![component]; + h.app.start("gear.edit"); + h.frames(3); + let Some(Kind::Gear(g)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no gear form") }; + assert_eq!((g.clearance, g.flank_points, g.backlash_thicker), (0.3, 12.0, true)); + } + + /// Wait, within a bound, for the preview of the form's values to be computed. + #[track_caller] + fn wait_preview(h: &mut Harness) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + h.frames(2); + while h.app.preview.busy || !(h.app.preview.active || h.app.preview.error.is_some()) { + assert!(std::time::Instant::now() < deadline, "the gear preview did not finish"); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.frame(); + } + h.frames(2); + } + + /// The form previews the gear before anything is inserted, follows the values, and leaves the + /// design and its history alone when it is cancelled. + #[test] + fn the_form_previews_the_gear_and_cancel_changes_nothing() { + let mut h = Harness::new(); + let (doc, undo) = (h.app.session.doc.clone(), h.app.session.undo.len()); + h.app.start("gear.insert"); + wait_preview(&mut h); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.previews()), "the gear form previews"); + assert!(h.app.preview.active && h.app.preview.error.is_none(), "a preview is up: {:?}", h.app.preview.error); + assert!(h.app.session.doc.gears.is_empty() && h.app.session.undo.len() == undo, "nothing is inserted"); + let first = h.app.preview.bounds; + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + g.teeth = 40.0; + } + wait_preview(&mut h); + assert!(h.app.preview.active && h.app.preview.bounds != first, "the preview follows the values"); + // A value that makes no gear says so in the form, not in a preview. + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + g.bore_diameter = 1000.0; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + h.frames(2); + while !(h.app.preview.error.is_some() || !h.app.preview.active) { + assert!(std::time::Instant::now() < deadline, "a refused value shows no gear"); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.frame(); + } + crate::dialogs::cancel(&mut h.app); + h.settle(); + assert!(!h.app.preview.active, "cancel takes the preview away"); + assert_eq!((h.app.session.doc.clone(), h.app.session.undo.len()), (doc, undo)); + } + + /// The presets set the kind of gear and keep the size; Reset goes back to what the form opened with. + #[test] + fn presets_set_the_kind_and_reset_goes_back_to_what_the_form_opened_with() { + let mut g = Gear::new(); + g.module = 3.0; + g.bore_diameter = 6.0; + g.preset(Preset::Herringbone); + assert_eq!((g.module, g.teeth, g.helix_angle, g.double_helical, g.internal, g.bore_diameter), (3.0, 20.0, 20.0, true, false, 6.0)); + g.preset(Preset::Ring); + assert_eq!((g.internal, g.teeth, g.rim_thickness, g.helix_angle, g.double_helical, g.bore_diameter), (true, 40.0, 6.0, 0.0, false, 0.0)); + g.preset(Preset::Helical); + assert_eq!((g.internal, g.helix_angle, g.double_helical), (false, 20.0, false)); + g.preset(Preset::Spur); + assert_eq!((g.internal, g.helix_angle, g.teeth), (false, 0.0, 20.0)); + g.reset(); + assert_eq!(g, Gear::new(), "a new gear resets to the defaults"); + // An edit form resets to the gear as it was saved, still on that gear. + let saved = SpurGear { + module: 1.5, + teeth: 30, + pressure_angle: 25.0, + face_width: 8.0, + profile_shift: 0.0, + backlash: 0.05, + flank_points: 12, + clearance: 0.3, + backlash_thicker: false, + internal: false, + rim_thickness: 0.0, + bore_diameter: 5.0, + bore_offset: 0.0, + helix_angle: 15.0, + double_helical: false, + }; + let mut e = Gear::saved(7, &saved); + let opened = e.clone(); + e.preset(Preset::Ring); + e.module = 9.0; + e.reset(); + assert_eq!(e, opened); + assert_eq!((e.component, e.teeth, e.helix_angle, e.flank_points), (Some(7), 30.0, 15.0, 12.0)); + } + + /// The buttons are on the form, and a preset's gear builds. + #[test] + fn the_form_offers_the_presets_and_reset_and_a_preset_builds() { + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(3); + for k in ["preset_spur", "preset_helical", "preset_herringbone", "preset_ring", "reset"] { + assert!(handle_at(&format!("dialog:gear:{k}")).is_some(), "{k}"); + } + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + g.preset(Preset::Herringbone); + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let (_, saved) = gear(&h).expect("a gear is saved"); + assert_eq!((saved.helix_angle, saved.double_helical), (20.0, true)); + } + + /// Edit Gear starts from the selected gear's saved values and rebuilds it in place. + #[test] + fn the_edit_form_starts_from_the_saved_values_and_rebuilds_in_place() { + let mut h = Harness::new(); + h.app.run("gear.insert", json!({"module": 2, "teeth": 40, "internal": true, "face_width": 6})).unwrap(); + h.settle(); + let (component, _) = gear(&h).expect("a gear"); + h.app.tree.picked_components = vec![component]; + h.app.start("gear.edit"); + h.frames(3); + let Some(Kind::Gear(g)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no gear form: {:?}", h.app.status) }; + assert_eq!((g.component, g.internal, g.teeth, g.face_width), (Some(component), true, 40.0, 6.0)); + assert!(handle_at("dialog:gear:rim_thickness").is_some(), "an internal gear shows its ring"); + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + (g.teeth, g.rim_thickness) = (36.0, 5.0); + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let (c, saved) = gear(&h).expect("still a gear"); + assert_eq!((c, saved.teeth, saved.rim_thickness, saved.internal), (component, 36, 5.0, true)); + } + + /// The form shows the profile's diameters before anything is inserted. + #[test] + fn the_form_shows_the_diameters_as_the_values_change() { + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(3); + for k in ["pitch", "base", "tip", "root"] { + assert!(handle_at(&format!("dialog:gear:{k}_diameter")).is_some(), "{k}"); + } + assert!(h.app.session.doc.gears.is_empty(), "nothing is inserted to show them"); + } + + /// A menu opens Edit Gear on exactly the gear it was opened for, and the ribbon offers both commands. + #[test] + fn a_menu_opens_the_form_on_the_gear_it_was_opened_for() { + assert!(crate::workspace::SECTIONS.iter().any(|s| s.ids.contains(&"gear.insert") && s.ids.contains(&"gear.edit"))); + let mut h = Harness::new(); + h.app.run("gear.insert", json!({"module": 2, "teeth": 20, "name": "First"})).unwrap(); + h.app.run("gear.insert", json!({"module": 3, "teeth": 30, "name": "Second"})).unwrap(); + h.settle(); + let second = h.app.session.doc.gears.iter().find(|(_, g)| g.teeth == 30).map(|(c, _)| *c).expect("the second gear"); + open(&mut h.app, second); + h.frames(3); + let Some(Kind::Gear(g)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no gear form: {:?}", h.app.status) }; + assert_eq!((g.component, g.module, g.teeth), (Some(second), 3.0, 30.0)); + } + + /// A value the form cannot hold is refused, and Cancel adds nothing. + #[test] + fn a_bad_value_is_refused_and_cancel_adds_nothing() { + let good = Gear::new(); + assert!(commands(&good).is_ok()); + for bad in [Gear { module: f64::NAN, ..Gear::new() }, Gear { helix_angle: f64::INFINITY, ..Gear::new() }] { + assert!(commands(&bad).is_err()); + } + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(2); + h.step(&json!({"key": "Escape"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none() && h.app.session.doc.gears.is_empty()); + } + + /// The engine's refusal shows in the form, and nothing is added. + #[test] + fn the_engines_refusal_stays_in_the_form() { + let mut h = Harness::new(); + h.app.start("gear.insert"); + h.frames(2); + if let Some(Kind::Gear(g)) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + (g.helix_angle, g.double_helical, g.face_width) = (0.0, true, 5.0); + g.bore_diameter = 500.0; + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.settle(); + assert!(h.app.session.doc.gears.is_empty()); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.error.is_some()), "the form shows why"); + } +} diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs index 7a477714aba..29bbf9078df 100644 --- a/crates/ui-egui/src/dialogs_part_size.rs +++ b/crates/ui-egui/src/dialogs_part_size.rs @@ -65,12 +65,16 @@ impl std::fmt::Debug for Resize { /// Resolve a whole definition, including bodies displayed through an occurrence path. pub fn component_for_bodies(app: &SolveApp, bodies: &[String]) -> Option { + component_for_bodies_where(app, bodies, |doc, c| doc.parts.contains_key(&c)) +} + +pub(crate) fn component_for_bodies_where(app: &SolveApp, bodies: &[String], wanted: impl Fn(&Document, u64) -> bool) -> Option { let state = crate::open_meshing::session_world(&app.session); let mut component = None; for name in bodies { let body = state.bodies.iter().find(|b| b.name == *name)?; let id = app.session.doc.model_body_component(body); - if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + if !wanted(&app.session.doc, id) || component.is_some_and(|c| c != id) { return None; } component = Some(id); @@ -79,9 +83,14 @@ pub fn component_for_bodies(app: &SolveApp, bodies: &[String]) -> Option { } pub fn selected_component(app: &SolveApp) -> Option { + selected_component_where(app, |doc, c| doc.parts.contains_key(&c)) +} + +/// The one component the selection stands for, if `wanted` accepts it. +pub fn selected_component_where(app: &SolveApp, wanted: impl Fn(&Document, u64) -> bool) -> Option { if !app.session.has_selection() { let [id] = app.tree.picked_components.as_slice() else { return None }; - return app.session.doc.parts.contains_key(id).then_some(*id); + return wanted(&app.session.doc, *id).then_some(*id); } let mut bodies = Vec::new(); let mut component = None; @@ -91,7 +100,7 @@ pub fn selected_component(app: &SolveApp) -> Option { Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => bodies.push(body.clone()), Sel::Occurrence { path } => { let id = app.session.occurrence_placement(path).ok()?.component; - if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + if !wanted(&app.session.doc, id) || component.is_some_and(|c| c != id) { return None; } component = Some(id); @@ -100,7 +109,7 @@ pub fn selected_component(app: &SolveApp) -> Option { } } if !bodies.is_empty() { - let id = component_for_bodies(app, &bodies)?; + let id = component_for_bodies_where(app, &bodies, &wanted)?; if component.is_some_and(|c| c != id) { return None; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c11ca4ffd04..6d8b5e694b3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -79,6 +79,7 @@ pub mod dialogs_dogbone; pub mod dialogs_end_cap; pub mod dialogs_frame; pub mod dialogs_frame_plate; +pub mod dialogs_gear; pub mod dialogs_gusset; mod dialogs_hole; pub mod dialogs_insert_airfoil; diff --git a/crates/ui-egui/src/render_workspace_setups.rs b/crates/ui-egui/src/render_workspace_setups.rs index 471d58a74c0..2572859157d 100644 --- a/crates/ui-egui/src/render_workspace_setups.rs +++ b/crates/ui-egui/src/render_workspace_setups.rs @@ -499,6 +499,7 @@ pub(super) fn same_model_source(app: &SolveApp, document: &std::sync::Weak