mirror of
https://github.com/bherbruck/solidcraft.git
synced 2026-11-08 04:52:10 +00:00
Compare commits
59 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7001949c49 | |||
| 777f960999 | |||
| d4f923a3e6 | |||
| bbb98928fb | |||
| 8e2b0cd60d | |||
| afd81380ab | |||
| 3a5195b0a0 | |||
| ee6b85605a | |||
| aa1fe28ddf | |||
| 5b0eb08473 | |||
| 9df8837d43 | |||
| 409ab1ed45 | |||
| 5e03fe2f4b | |||
| 37a586dd61 | |||
| a79f40a711 | |||
| b5728f284b | |||
| 5965439a15 | |||
| 586a358ed4 | |||
| 7770f8982d | |||
| 72ad6383ef | |||
| 0537623a75 | |||
| 65d288227e | |||
| fedb3bcdb1 | |||
| 097b8b7550 | |||
| af7ca3a8a2 | |||
| 27ddb725c7 | |||
| a06bdf5cfc | |||
| 33fdcdb3a0 | |||
| c07ab5f8f9 | |||
| fea32f8aac | |||
| 4927214976 | |||
| b621819c0c | |||
| ec552a5300 | |||
| e0cc740cc3 | |||
| 5de48e916d | |||
| 80af7bbe3e | |||
| 191e983423 | |||
| 2b9445b049 | |||
| 7ddf48ca16 | |||
| d2f6848377 | |||
| 0b6d6fecd8 | |||
| fa691707c2 | |||
| b9a55c74e2 | |||
| 2bb9c81069 | |||
| cedb51b8ea | |||
| 66d13059dd | |||
| 800ea40c0d | |||
| 20442eecd3 | |||
| 22d1cd7032 | |||
| 6a0dc18655 | |||
| e006dbf1af | |||
| 8241a750fa | |||
| 41779cf7bb | |||
| b01b9689c8 | |||
| 4426da6f5d | |||
| 5ead82e627 | |||
| c29b0d2f13 | |||
| 480fd8d517 | |||
| 4c09fa5355 |
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "معامل المرونة الاتجاهي",
|
||||
"cmd.material_properties_validate": "التحقق من بيانات المادة الفيزيائية",
|
||||
"cmd.mesh_convert": "تحويل الشبكة",
|
||||
"cmd.model_body_features": "سرد ميزات الجسم",
|
||||
"cmd.model_edges": "قائمة الحواف",
|
||||
"cmd.model_faces": "قائمة الأوجه",
|
||||
"cmd.model_threads": "قائمة الأسنان اللولبية",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "أسفل الوسط",
|
||||
"prefs.bottom_right": "أسفل اليمين",
|
||||
"prefs.browser": "المستعرض",
|
||||
"prefs.browser_body_features": "الميزات تحت الأجسام",
|
||||
"prefs.browser_body_features_note": "يمكن فتح كل جسم في المستعرض لعرض ميزات المخطط الزمني التي بنته، بترتيب المخطط الزمني.",
|
||||
"prefs.browser_components_open": "المكوّنات مفتوحة من البداية",
|
||||
"prefs.browser_components_open_note": "يبدأ كل مكوّن في المستعرض مفتوحًا كما كان من قبل، بدلًا من أن يبقى مغلقًا حتى تفتحه.",
|
||||
"prefs.browser_eye_left": "أيقونة الإظهار بجانب سهم الطي",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "السجل",
|
||||
"prefs.history_bar_groups": "طي شريط السجل في مجموعات",
|
||||
"prefs.history_bar_groups_note": "في سجل طويل، تُطوى سلسلة ميزات المكوّن الواحد في شريحة واحدة، وتبدأ مجلدات الميزات مطوية. تدخل مجموعة STEP المُدرجة في مجلد Group. عند الإيقاف تظهر كل ميزة، وتبدأ المجلدات مفتوحة، ولا يُنشأ أي مجلد.",
|
||||
"prefs.history_folder_kind_icon": "أيقونة المجلد من ميزاته",
|
||||
"prefs.history_folder_kind_icon_note": "مجلد السجل الذي تكون ميزاته كلها من نوع واحد يعرض أيقونتها.",
|
||||
"prefs.history_group_joints": "تجميع المفاصل في السجل",
|
||||
"prefs.history_group_joints_note": "يظهر مفصلان أو أكثر كزر واحد مع عددها، والنقر عليه يُظهر كل مفصل. عند الإيقاف يظهر كل مفصل على حدة.",
|
||||
"prefs.history_origin_bodies": "إظهار الأصل والأجسام في الأعلى",
|
||||
|
||||
+3
-751
File diff suppressed because it is too large
Load Diff
@@ -1018,7 +1018,6 @@
|
||||
"cmd.material_properties_directional": "Richtungsabhängiger Elastizitätsmodul",
|
||||
"cmd.material_properties_validate": "Physikalische Materialdaten prüfen",
|
||||
"cmd.mesh_convert": "Netz konvertieren",
|
||||
"cmd.model_body_features": "Körper-Features auflisten",
|
||||
"cmd.model_edges": "Kanten auflisten",
|
||||
"cmd.model_faces": "Flächen auflisten",
|
||||
"cmd.model_threads": "Gewinde auflisten",
|
||||
@@ -2306,8 +2305,6 @@
|
||||
"prefs.bottom_centre": "Unten mittig",
|
||||
"prefs.bottom_right": "Unten rechts",
|
||||
"prefs.browser": "Browser",
|
||||
"prefs.browser_body_features": "Features unter Körpern",
|
||||
"prefs.browser_body_features_note": "Jeder Körper im Browser lässt sich aufklappen und zeigt die Features der Zeitleiste, die ihn erzeugt haben, in deren Reihenfolge.",
|
||||
"prefs.browser_components_open": "Komponenten zu Beginn aufgeklappt",
|
||||
"prefs.browser_components_open_note": "Jede Komponente im Browser ist wie bisher von Anfang an aufgeklappt, statt zugeklappt zu bleiben, bis du sie aufklappst.",
|
||||
"prefs.browser_eye_left": "Auge neben dem Aufklapppfeil",
|
||||
@@ -2432,8 +2429,6 @@
|
||||
"prefs.history": "Verlauf",
|
||||
"prefs.history_bar_groups": "Verlaufsleiste in Gruppen falten",
|
||||
"prefs.history_bar_groups_note": "In einem langen Verlauf wird eine Folge von Features einer Komponente zu einem Chip gefaltet, und Merkmalsordner beginnen gefaltet. Eine eingefügte STEP-Baugruppe kommt in einen Group-Ordner. Aus zeigt jedes Feature, öffnet Ordner und legt keinen Ordner an.",
|
||||
"prefs.history_folder_kind_icon": "Ordnersymbol aus seinen Features",
|
||||
"prefs.history_folder_kind_icon_note": "Ein Ordner im Verlauf, dessen Features alle von einer Art sind, zeigt deren Symbol.",
|
||||
"prefs.history_group_joints": "Gelenke im Verlauf gruppieren",
|
||||
"prefs.history_group_joints_note": "Zwei oder mehr Gelenke erscheinen als eine Schaltfläche mit ihrer Anzahl; ein Klick zeigt jedes einzeln. Aus zeigt jedes Gelenk einzeln.",
|
||||
"prefs.history_origin_bodies": "Ursprung und Körper oben zeigen",
|
||||
|
||||
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "Directional Elastic Modulus",
|
||||
"cmd.material_properties_validate": "Validate Physical Material Data",
|
||||
"cmd.mesh_convert": "Convert Mesh",
|
||||
"cmd.model_body_features": "List Body Features",
|
||||
"cmd.model_edges": "List Edges",
|
||||
"cmd.model_faces": "List Faces",
|
||||
"cmd.model_threads": "List Threads",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "Bottom center",
|
||||
"prefs.bottom_right": "Bottom right",
|
||||
"prefs.browser": "Browser",
|
||||
"prefs.browser_body_features": "Features under bodies",
|
||||
"prefs.browser_body_features_note": "Each body in the browser folds open on the timeline features that built it, in timeline order.",
|
||||
"prefs.browser_components_open": "Components start open",
|
||||
"prefs.browser_components_open_note": "Every component in the browser starts open, as before, instead of closed until you open it.",
|
||||
"prefs.browser_eye_left": "Eye beside the fold arrow",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "History",
|
||||
"prefs.history_bar_groups": "Fold the History bar into groups",
|
||||
"prefs.history_bar_groups_note": "In a long history, a run of one component's features folds into one chip, and feature folders start folded. An inserted STEP assembly goes into a Group folder. Off shows each feature, starts folders open and makes no folder.",
|
||||
"prefs.history_folder_kind_icon": "Folder icon from its features",
|
||||
"prefs.history_folder_kind_icon_note": "A History folder whose features are all of one kind shows their icon.",
|
||||
"prefs.history_group_joints": "Group joints in the History",
|
||||
"prefs.history_group_joints_note": "Two or more joints show as one button with their count, and a click shows each one. Off shows each joint.",
|
||||
"prefs.history_origin_bodies": "Show origin and bodies at the top",
|
||||
|
||||
@@ -1000,7 +1000,6 @@
|
||||
"cmd.material_properties_directional": "Module d'élasticité directionnel",
|
||||
"cmd.material_properties_validate": "Valider les données du matériau physique",
|
||||
"cmd.mesh_convert": "Convertir le maillage",
|
||||
"cmd.model_body_features": "Lister les fonctions du corps",
|
||||
"cmd.model_edges": "Lister les arêtes",
|
||||
"cmd.model_faces": "Lister les faces",
|
||||
"cmd.model_threads": "Lister les filetages",
|
||||
@@ -2165,8 +2164,6 @@
|
||||
"prefs.bottom_centre": "Bas centre",
|
||||
"prefs.bottom_right": "Bas droite",
|
||||
"prefs.browser": "Navigateur",
|
||||
"prefs.browser_body_features": "Fonctions sous les corps",
|
||||
"prefs.browser_body_features_note": "Chaque corps du navigateur se déplie sur les fonctions de l'historique qui l'ont construit, dans l'ordre de l'historique.",
|
||||
"prefs.browser_components_open": "Composants dépliés au départ",
|
||||
"prefs.browser_components_open_note": "Chaque composant du navigateur commence déplié, comme avant, au lieu de rester replié jusqu'à ce que vous le dépliiez.",
|
||||
"prefs.browser_eye_left": "Œil à côté de la flèche de dépliage",
|
||||
|
||||
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "מודול אלסטיות כיווני",
|
||||
"cmd.material_properties_validate": "אימות נתוני חומר פיזיקלי",
|
||||
"cmd.mesh_convert": "המרת רשת משולשים",
|
||||
"cmd.model_body_features": "הצגת פיצ'רים של גוף",
|
||||
"cmd.model_edges": "רשימת מקצועות",
|
||||
"cmd.model_faces": "רשימת פאות",
|
||||
"cmd.model_threads": "רשימת הברגות",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "למטה במרכז",
|
||||
"prefs.bottom_right": "למטה מימין",
|
||||
"prefs.browser": "עץ התכן",
|
||||
"prefs.browser_body_features": "פיצ'רים מתחת לגופים",
|
||||
"prefs.browser_body_features_note": "כל גוף בדפדפן נפתח ומציג את הפיצ'רים מציר הזמן שבנו אותו, לפי סדר ציר הזמן.",
|
||||
"prefs.browser_components_open": "רכיבים פתוחים מההתחלה",
|
||||
"prefs.browser_components_open_note": "כל רכיב בעץ התכן מתחיל פתוח, כמו קודם, במקום סגור עד שתפתח אותו.",
|
||||
"prefs.browser_eye_left": "סמל העין ליד חץ הקיפול",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "ציר הזמן",
|
||||
"prefs.history_bar_groups": "קיפול סרגל ציר הזמן לקבוצות",
|
||||
"prefs.history_bar_groups_note": "בציר זמן ארוך, רצף פיצ'רים של רכיב אחד מתקפל לשבב אחד, ותיקיות פיצ'רים מתחילות מקופלות. מכלול STEP שהוכנס נכנס לתיקיית Group. כשהאפשרות כבויה, כל פיצ'ר מוצג, התיקיות מתחילות פתוחות ולא נוצרת תיקייה.",
|
||||
"prefs.history_folder_kind_icon": "סמל התיקייה לפי התכונות שבה",
|
||||
"prefs.history_folder_kind_icon_note": "תיקייה בהיסטוריה שכל התכונות בה מאותו סוג מציגה את הסמל שלהן.",
|
||||
"prefs.history_group_joints": "קיבוץ מפרקים בציר הזמן",
|
||||
"prefs.history_group_joints_note": "שני מפרקים או יותר מוצגים ככפתור אחד עם מספרם, ולחיצה מציגה כל אחד מהם. כשהאפשרות כבויה, כל מפרק מוצג בנפרד.",
|
||||
"prefs.history_origin_bodies": "הצגת הראשית והגופים למעלה",
|
||||
|
||||
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "方向別弾性率",
|
||||
"cmd.material_properties_validate": "物理材料データを検証",
|
||||
"cmd.mesh_convert": "メッシュを変換",
|
||||
"cmd.model_body_features": "ボディのフィーチャーを一覧表示",
|
||||
"cmd.model_edges": "エッジを一覧表示",
|
||||
"cmd.model_faces": "面を一覧表示",
|
||||
"cmd.model_threads": "ねじを一覧表示",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "下中央",
|
||||
"prefs.bottom_right": "右下",
|
||||
"prefs.browser": "ブラウザー",
|
||||
"prefs.browser_body_features": "ボディの下にフィーチャー",
|
||||
"prefs.browser_body_features_note": "ブラウザーの各ボディを展開すると、そのボディを作ったタイムラインのフィーチャーがタイムライン順に表示されます。",
|
||||
"prefs.browser_components_open": "コンポーネントを最初から展開",
|
||||
"prefs.browser_components_open_note": "ブラウザーのすべてのコンポーネントを以前と同じく最初から展開して表示します。オフの場合は展開するまで折りたたまれています。",
|
||||
"prefs.browser_eye_left": "折りたたみ矢印の隣の目のアイコン",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "履歴",
|
||||
"prefs.history_bar_groups": "履歴バーをグループにまとめる",
|
||||
"prefs.history_bar_groups_note": "長い履歴では、1つのコンポーネントの連続したフィーチャーを1つのチップにまとめ、フィーチャーフォルダは閉じた状態で始まります。挿入したSTEPアセンブリはGroupフォルダに入ります。オフにすると、各フィーチャーを表示し、フォルダは開いた状態で始まり、フォルダは作成されません。",
|
||||
"prefs.history_folder_kind_icon": "中のフィーチャーのアイコンをフォルダーに使う",
|
||||
"prefs.history_folder_kind_icon_note": "中のフィーチャーがすべて同じ種類の履歴フォルダーは、そのアイコンで表示されます。",
|
||||
"prefs.history_group_joints": "履歴でジョイントをまとめる",
|
||||
"prefs.history_group_joints_note": "2つ以上のジョイントを、数を添えた1つのボタンにまとめます。クリックすると各ジョイントを表示します。オフにすると各ジョイントを個別に表示します。",
|
||||
"prefs.history_origin_bodies": "原点とボディを先頭に表示",
|
||||
|
||||
@@ -2006,8 +2006,6 @@
|
||||
"prefs.history": "이력",
|
||||
"prefs.history_bar_groups": "이력 막대를 그룹으로 접기",
|
||||
"prefs.history_bar_groups_note": "긴 이력에서는 한 컴포넌트의 연속된 특성을 하나의 칩으로 접고, 특성 폴더는 접힌 상태로 시작합니다. 삽입한 STEP 어셈블리는 Group 폴더에 들어갑니다. 끄면 각 특성을 표시하고, 폴더를 펼친 상태로 시작하며, 폴더를 만들지 않습니다.",
|
||||
"prefs.history_folder_kind_icon": "폴더 아이콘을 안의 피처에서 가져오기",
|
||||
"prefs.history_folder_kind_icon_note": "피처가 모두 같은 종류인 기록 폴더는 그 피처의 아이콘을 표시합니다.",
|
||||
"prefs.history_group_joints": "이력에서 조인트 묶기",
|
||||
"prefs.history_group_joints_note": "조인트가 두 개 이상이면 개수가 표시된 버튼 하나로 묶고, 클릭하면 각 조인트를 표시합니다. 끄면 각 조인트를 하나씩 표시합니다.",
|
||||
"prefs.history_origin_bodies": "원점과 바디를 맨 위에 표시",
|
||||
|
||||
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "Mô đun đàn hồi theo hướng",
|
||||
"cmd.material_properties_validate": "Xác thực dữ liệu thuộc tính vật liệu",
|
||||
"cmd.mesh_convert": "Chuyển đổi lưới",
|
||||
"cmd.model_body_features": "Liệt kê tính năng của thân",
|
||||
"cmd.model_edges": "Danh sách các cạnh",
|
||||
"cmd.model_faces": "Danh sách các bề mặt",
|
||||
"cmd.model_threads": "Danh sách các đoạn ren",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "Giữa phía dưới",
|
||||
"prefs.bottom_right": "Góc dưới bên phải",
|
||||
"prefs.browser": "Cây thư mục",
|
||||
"prefs.browser_body_features": "Tính năng dưới thân",
|
||||
"prefs.browser_body_features_note": "Mỗi thân trong trình duyệt có thể mở ra để hiện các tính năng trên dòng thời gian đã tạo nên nó, theo thứ tự dòng thời gian.",
|
||||
"prefs.browser_components_open": "Thành phần mở sẵn",
|
||||
"prefs.browser_components_open_note": "Mọi thành phần trong trình duyệt đều mở sẵn như trước, thay vì đóng cho đến khi bạn mở.",
|
||||
"prefs.browser_eye_left": "Biểu tượng mắt cạnh mũi tên thu gọn",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "Lịch sử",
|
||||
"prefs.history_bar_groups": "Thu gọn thanh Lịch sử thành nhóm",
|
||||
"prefs.history_bar_groups_note": "Trong lịch sử dài, một chuỗi tính năng của cùng một thành phần được thu gọn thành một thẻ, và thư mục tính năng bắt đầu ở dạng thu gọn. Cụm lắp ráp STEP được chèn vào sẽ nằm trong thư mục Group. Khi tắt, mỗi tính năng đều hiện, thư mục bắt đầu ở dạng mở và không tạo thư mục nào.",
|
||||
"prefs.history_folder_kind_icon": "Biểu tượng thư mục theo các tính năng bên trong",
|
||||
"prefs.history_folder_kind_icon_note": "Thư mục Lịch sử có các tính năng cùng một loại sẽ hiện biểu tượng của chúng.",
|
||||
"prefs.history_group_joints": "Nhóm các khớp nối trong Lịch sử",
|
||||
"prefs.history_group_joints_note": "Từ hai khớp nối trở lên hiện thành một nút kèm số lượng, nhấp vào để hiện từng khớp nối. Khi tắt, mỗi khớp nối hiện riêng.",
|
||||
"prefs.history_origin_bodies": "Hiển thị gốc tọa độ và thân khối ở trên cùng",
|
||||
|
||||
@@ -1207,7 +1207,6 @@
|
||||
"cmd.material_properties_directional": "方向弹性模量",
|
||||
"cmd.material_properties_validate": "验证物理材料数据",
|
||||
"cmd.mesh_convert": "转换网格",
|
||||
"cmd.model_body_features": "列出实体特征",
|
||||
"cmd.model_edges": "列出边",
|
||||
"cmd.model_faces": "列出面",
|
||||
"cmd.model_threads": "列出螺纹",
|
||||
@@ -2519,8 +2518,6 @@
|
||||
"prefs.bottom_centre": "底部居中",
|
||||
"prefs.bottom_right": "右下角",
|
||||
"prefs.browser": "浏览器",
|
||||
"prefs.browser_body_features": "实体下显示特征",
|
||||
"prefs.browser_body_features_note": "浏览器中的每个实体都可展开,按时间线顺序显示构建它的时间线特征。",
|
||||
"prefs.browser_components_open": "组件初始展开",
|
||||
"prefs.browser_components_open_note": "浏览器中的每个组件都像以前一样初始展开,而不是在您展开前保持折叠。",
|
||||
"prefs.browser_eye_left": "折叠箭头旁的眼睛图标",
|
||||
@@ -2645,8 +2642,6 @@
|
||||
"prefs.history": "历史",
|
||||
"prefs.history_bar_groups": "将历史栏折叠为分组",
|
||||
"prefs.history_bar_groups_note": "在较长的历史中,同一组件的连续特征折叠为一个标签,特征文件夹开始时为折叠状态。插入的 STEP 装配体放入 Group 文件夹。关闭后显示每个特征,文件夹开始时为展开状态,且不创建文件夹。",
|
||||
"prefs.history_folder_kind_icon": "文件夹使用其中特征的图标",
|
||||
"prefs.history_folder_kind_icon_note": "历史中特征全部属于同一类型的文件夹显示该类型的图标。",
|
||||
"prefs.history_group_joints": "在历史中将关节分组",
|
||||
"prefs.history_group_joints_note": "两个或更多关节显示为一个带数量的按钮,单击即可显示每个关节。关闭后逐个显示每个关节。",
|
||||
"prefs.history_origin_bodies": "在顶部显示原点和实体",
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
//! Which timeline features built each body (#11945): the data behind `model.body_features` and
|
||||
//! the Browser's optional features-under-bodies tree.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::params::{bad, str_};
|
||||
use crate::schema::inspect::{BodyFeature, BodyFeatures, ModelBodyFeatures};
|
||||
use crate::{Result, Session};
|
||||
|
||||
impl Session {
|
||||
/// The features that built each body of the evaluated model, by the body's model name, in
|
||||
/// timeline order: the feature that created it, every later feature that changed its
|
||||
/// geometry, and the features of the bodies a feature consumed while it made or changed this
|
||||
/// one (a Combine's tools, a body joined in). A piece a cut split off keeps the features of
|
||||
/// the body it was cut from. Features behind the history marker, which built nothing yet,
|
||||
/// are not listed.
|
||||
///
|
||||
/// Decided on exact body identity (a body a feature passed through unchanged is the same
|
||||
/// record), never on a mesh.
|
||||
pub fn body_features(&self) -> BTreeMap<String, Vec<u64>> {
|
||||
let order: HashMap<u64, usize> = self.doc.features.iter().enumerate().map(|(i, f)| (f.id, i)).collect();
|
||||
// Each body before the feature being looked at: its geometry, its creator and its features.
|
||||
let mut before: HashMap<String, (solidcraft_doc::kernel::Body, u64, Vec<u64>)> = HashMap::new();
|
||||
for r in &self.model.results {
|
||||
let id = r.id;
|
||||
let after = &r.state.bodies;
|
||||
let names: HashSet<&str> = after.iter().map(|b| b.name.as_str()).collect();
|
||||
// What the feature consumed: bodies there before and gone after.
|
||||
let consumed: Vec<u64> =
|
||||
before.iter().filter(|(name, _)| !names.contains(name.as_str())).flat_map(|(_, (_, _, list))| list.iter().copied()).collect();
|
||||
let mut next: HashMap<String, (solidcraft_doc::kernel::Body, u64, Vec<u64>)> = HashMap::with_capacity(after.len());
|
||||
for b in after {
|
||||
let list = match before.get(&b.name) {
|
||||
// Passed through unchanged.
|
||||
Some((old, creator, list)) if old.same(&b.body) && *creator == b.feature => list.clone(),
|
||||
// Changed: it keeps what built it so far.
|
||||
Some((_, creator, list)) if *creator == b.feature => touched(list.clone(), &consumed, id, &order),
|
||||
// Made by this feature.
|
||||
_ if b.feature == id => touched(Vec::new(), &consumed, id, &order),
|
||||
// A piece of a body made earlier (a split): what built the bodies of its creator.
|
||||
_ => {
|
||||
let inherited =
|
||||
before.values().filter(|(_, creator, _)| *creator == b.feature).flat_map(|(_, _, list)| list.iter().copied()).collect();
|
||||
touched(inherited, &consumed, id, &order)
|
||||
}
|
||||
};
|
||||
next.insert(b.name.clone(), (b.body.clone(), b.feature, list));
|
||||
}
|
||||
before = next;
|
||||
}
|
||||
// The model as it stands (a sketch shown live keeps its last results).
|
||||
self.model
|
||||
.state()
|
||||
.bodies
|
||||
.iter()
|
||||
.map(|b| (b.name.clone(), before.get(&b.name).map(|(_, _, list)| list.clone()).unwrap_or_else(|| vec![b.feature])))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `list` with the features of what was consumed and the feature `id` added, once each, in
|
||||
/// timeline order.
|
||||
fn touched(mut list: Vec<u64>, consumed: &[u64], id: u64, order: &HashMap<u64, usize>) -> Vec<u64> {
|
||||
list.extend(consumed.iter().copied());
|
||||
list.push(id);
|
||||
list.sort_by_key(|f| order.get(f).copied().unwrap_or(usize::MAX));
|
||||
list.dedup();
|
||||
list
|
||||
}
|
||||
|
||||
/// `model.body_features`: the features that built each body, or one body (a placed copy's name
|
||||
/// means the body it shows).
|
||||
pub(super) fn model_body_features(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "model.body_features";
|
||||
let all = s.body_features();
|
||||
let wanted = match str_(p, "body") {
|
||||
Some(name) => {
|
||||
let st = s.world_state()?;
|
||||
let b = st.body(name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?;
|
||||
Some((b.name.clone(), b.definition_name().to_string()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let feature = |id: &u64| BodyFeature { id: *id, name: s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_default() };
|
||||
let bodies = match wanted {
|
||||
Some((shown, definition)) => {
|
||||
vec![BodyFeatures { body: shown, features: all.get(&definition).map(|l| l.iter().map(feature).collect()).unwrap_or_default() }]
|
||||
}
|
||||
None => s
|
||||
.model
|
||||
.state()
|
||||
.bodies
|
||||
.iter()
|
||||
.map(|b| BodyFeatures { body: b.name.clone(), features: all.get(&b.name).map(|l| l.iter().map(feature).collect()).unwrap_or_default() })
|
||||
.collect(),
|
||||
};
|
||||
serde_json::to_value(ModelBodyFeatures { bodies, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
@@ -19,11 +19,9 @@ use crate::params::{bad, bool_, expr, str_};
|
||||
use crate::schema::browser::{
|
||||
BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,
|
||||
BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,
|
||||
BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, Isolated, PlaneFrame, RedefineAttachment,
|
||||
RedefineSketchParams, RedefineSketchResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn, ViewApplyParams,
|
||||
ViewDeleteParams, ViewDeleted, ViewListParams, ViewListResult, ViewRenameParams, ViewRenamed, ViewSaveParams, ViewSaved, VisibilityState,
|
||||
BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, Isolated, RepairDone, RepairFace, RepairHole,
|
||||
RepairParams, RepairResult, RepairSewn, VisibilityState,
|
||||
};
|
||||
use crate::schema::view_navigation::CameraReply;
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -37,12 +35,6 @@ const MOVE_CONTRACT: TypedContract<BrowserMoveParams> = TypedContract::new();
|
||||
const ORDER_CONTRACT: TypedContract<BrowserOrderParams> = TypedContract::new();
|
||||
const VISIBILITY_CONTRACT: TypedContract<BrowserVisibilityParams> = TypedContract::new();
|
||||
const FOLD_CONTRACT: TypedContract<BrowserFoldParams> = TypedContract::new();
|
||||
const REDEFINE_SKETCH_CONTRACT: TypedContract<RedefineSketchParams> = TypedContract::new();
|
||||
const VIEW_SAVE_CONTRACT: TypedContract<ViewSaveParams> = TypedContract::new();
|
||||
const VIEW_RENAME_CONTRACT: TypedContract<ViewRenameParams> = TypedContract::new();
|
||||
const VIEW_DELETE_CONTRACT: TypedContract<ViewDeleteParams> = TypedContract::new();
|
||||
const VIEW_LIST_CONTRACT: TypedContract<ViewListParams> = TypedContract::new();
|
||||
const VIEW_APPLY_CONTRACT: TypedContract<ViewApplyParams> = TypedContract::new();
|
||||
|
||||
/// A reply as JSON: the commands here build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
@@ -64,10 +56,8 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.params(
|
||||
"body: its name (a part the modelling kernel refuses, or an open part that should be a solid); gap?: expr (default 0.2 mm, at most 1 mm: free edges that pair up within it are sewn, each sewn edge carrying its own gap as its tolerance); patch_holes?: bool (default false: loops of free edges left are patched, in the plane of the faces around them where those are that plane, else tangent to them, and sewn in; otherwise the reply offers the patches); name? → the feature, and repair: what changed face by face (rebuilt and refused faces, sewn gaps, holes with their surface.patch), faces and largest edge tolerance before and after, closed, modelling, volume. Refused with why when nothing applies",
|
||||
),
|
||||
CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", crate::checked!("sketch.redefine", redefine_sketch))
|
||||
CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch)
|
||||
.icon("plane")
|
||||
.contract(&REDEFINE_SKETCH_CONTRACT)
|
||||
.output(output_schema_for::<RedefineSketchResult>)
|
||||
.params("sketch: id or name; plane: as sketch.create; frame?: as sketch.create; author_path?: exact owner occurrence ids; explicitly rebinds or freezes the plane while preserving geometry and dimension names"),
|
||||
CommandSpec::new("browser.group", "New Group", crate::checked!("browser.group", group))
|
||||
.icon("folder")
|
||||
@@ -94,33 +84,13 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&UNITS_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<DocumentUnitsResult>)
|
||||
.params("units: mm|cm|m|in|ft (display and unit-less parameters; values keep their meaning)"),
|
||||
CommandSpec::new("view.save", "New Named View", crate::checked!("view.save", view_save))
|
||||
CommandSpec::new("view.save", "New Named View", view_save)
|
||||
.icon("camera")
|
||||
.contract(&VIEW_SAVE_CONTRACT)
|
||||
.output(output_schema_for::<ViewSaved>)
|
||||
.params("name?; camera: {target: [x,y,z], yaw, pitch, distance, fov?} (replaces a view of the same name)"),
|
||||
CommandSpec::new("view.rename", "Rename Named View", crate::checked!("view.rename", view_rename))
|
||||
.icon("rename")
|
||||
.contract(&VIEW_RENAME_CONTRACT)
|
||||
.output(output_schema_for::<ViewRenamed>)
|
||||
.params("view: name, name"),
|
||||
CommandSpec::new("view.delete", "Delete Named View", crate::checked!("view.delete", view_delete))
|
||||
.icon("delete")
|
||||
.contract(&VIEW_DELETE_CONTRACT)
|
||||
.output(output_schema_for::<ViewDeleted>)
|
||||
.params("view: name"),
|
||||
CommandSpec::new("view.list", "List Named Views", crate::checked!("view.list", view_list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&VIEW_LIST_CONTRACT)
|
||||
.output(output_schema_for::<ViewListResult>)
|
||||
.doc_only(),
|
||||
CommandSpec::new("view.apply", "Restore Named View", crate::checked!("view.apply", view_apply))
|
||||
.icon("camera")
|
||||
.noundo()
|
||||
.contract(&VIEW_APPLY_CONTRACT)
|
||||
.output(output_schema_for::<CameraReply>)
|
||||
.params(
|
||||
CommandSpec::new("view.rename", "Rename Named View", view_rename).icon("rename").params("view: name, name"),
|
||||
CommandSpec::new("view.delete", "Delete Named View", view_delete).icon("delete").params("view: name"),
|
||||
CommandSpec::new("view.list", "List Named Views", view_list).icon("list").noundo().doc_only(),
|
||||
CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().params(
|
||||
"view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?, roll?} (radians, mm, about the up axis; yaw: heading of the line of sight, 0 along +Y (Front), π/2 along +X (Left), π (Back), −π/2 (Right); pitch: the eye's elevation, within ±π/2, π/2 = Top; roll defaults to 0, turns the picture clockwise, must be finite and is clamped to ±π; the View angles readout shows these in degrees; up is refused: the up axis comes from the design settings) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step",
|
||||
),
|
||||
CommandSpec::new("browser.order", "Order Browser Items", crate::checked!("browser.order", order))
|
||||
@@ -1079,47 +1049,14 @@ fn document_units(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
reply(kept)
|
||||
}
|
||||
|
||||
/// A camera `view.save` keeps, as the handler reads it (and `ViewCamera`, its contract type): a
|
||||
/// [`solidcraft_doc::NamedView`] of finite numbers with a positive distance, or the message the
|
||||
/// handler refuses it with.
|
||||
pub(crate) fn saved_view_form(c: &Value) -> std::result::Result<solidcraft_doc::NamedView, String> {
|
||||
let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| format!("bad camera: {e}"))?;
|
||||
let ok = [v.target.x, v.target.y, v.target.z, v.yaw, v.pitch, v.distance, v.fov].iter().all(|x| x.is_finite()) && v.distance > 0.0;
|
||||
if ok { Ok(v) } else { Err("the camera must be finite with a positive distance".into()) }
|
||||
}
|
||||
|
||||
/// The camera `view.apply` turns to for a `camera` it is given, as the handler reads it (and
|
||||
/// `ApplyCamera`, its contract type), or the message the handler refuses it with.
|
||||
pub(crate) fn applied_camera_form(c: &Value) -> std::result::Result<crate::render::Camera, String> {
|
||||
if c.get("up").is_some() {
|
||||
return Err("camera `up` is not supported: the up axis comes from the design settings".into());
|
||||
}
|
||||
let roll = match c.get("roll") {
|
||||
Some(value) => value.as_f64().filter(|r| r.is_finite()).ok_or("camera `roll` must be a finite number in radians")?,
|
||||
None => 0.0,
|
||||
};
|
||||
let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| format!("bad camera: {e}"))?;
|
||||
// Past a pole the same view has other angles; the orbit would snap it back (#6032).
|
||||
if !(v.pitch.abs() <= std::f64::consts::FRAC_PI_2 + 1e-9) {
|
||||
return Err("camera `pitch` must be within ±π/2 radians (±90°)".into());
|
||||
}
|
||||
let cam = crate::render::Camera { roll: roll.clamp(-std::f64::consts::PI, std::f64::consts::PI), ..camera_of(&v) };
|
||||
if !usable_camera(&cam) {
|
||||
return Err("the camera must be finite with a positive distance".into());
|
||||
}
|
||||
Ok(cam)
|
||||
}
|
||||
|
||||
/// A camera the viewport can be put at: finite, with a positive distance and a field of view of
|
||||
/// at least 0.
|
||||
fn usable_camera(cam: &crate::render::Camera) -> bool {
|
||||
cam.is_valid() && cam.fov.is_finite() && cam.fov >= 0.0
|
||||
}
|
||||
|
||||
fn view_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "view.save";
|
||||
let c = p.get("camera").ok_or_else(|| bad(cmd, "`camera` is required"))?;
|
||||
let mut v = saved_view_form(c).map_err(|e| bad(cmd, e))?;
|
||||
let mut v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;
|
||||
let ok = [v.target.x, v.target.y, v.target.z, v.yaw, v.pitch, v.distance, v.fov].iter().all(|x| x.is_finite()) && v.distance > 0.0;
|
||||
if !ok {
|
||||
return Err(bad(cmd, "the camera must be finite with a positive distance"));
|
||||
}
|
||||
let n = s.doc.named_views.len();
|
||||
v.name = match str_(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(n) if n.len() <= 128 => n.to_string(),
|
||||
@@ -1133,7 +1070,7 @@ fn view_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut();
|
||||
d.named_views.retain(|x| x.name != name);
|
||||
d.named_views.push(v);
|
||||
reply(cmd, ViewSaved { view: name, param_warnings: Vec::new() })
|
||||
Ok(json!({ "view": name }))
|
||||
}
|
||||
|
||||
fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1141,7 +1078,23 @@ fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cam = match (str_(p, "view"), p.get("camera")) {
|
||||
(Some(_), Some(_)) => return Err(bad(cmd, "give `view` or `camera`, not both")),
|
||||
(None, None) => return Err(bad(cmd, "`view` (a name) or `camera` is required")),
|
||||
(None, Some(c)) => applied_camera_form(c).map_err(|e| bad(cmd, e))?,
|
||||
(None, Some(c)) => {
|
||||
if c.get("up").is_some() {
|
||||
return Err(bad(cmd, "camera `up` is not supported: the up axis comes from the design settings"));
|
||||
}
|
||||
let roll = match c.get("roll") {
|
||||
Some(value) => {
|
||||
value.as_f64().filter(|r| r.is_finite()).ok_or_else(|| bad(cmd, "camera `roll` must be a finite number in radians"))?
|
||||
}
|
||||
None => 0.0,
|
||||
};
|
||||
let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;
|
||||
// Past a pole the same view has other angles; the orbit would snap it back (#6032).
|
||||
if !(v.pitch.abs() <= std::f64::consts::FRAC_PI_2 + 1e-9) {
|
||||
return Err(bad(cmd, "camera `pitch` must be within ±π/2 radians (±90°)"));
|
||||
}
|
||||
crate::render::Camera { roll: roll.clamp(-std::f64::consts::PI, std::f64::consts::PI), ..camera_of(&v) }
|
||||
}
|
||||
// Standard view names come first, as in the browser's Named Views folder.
|
||||
(Some(name), None) => match crate::render::StandardView::parse(name) {
|
||||
Some(sv) => {
|
||||
@@ -1153,11 +1106,11 @@ fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => s.doc.named_views.iter().find(|v| v.name == name).map(camera_of).ok_or_else(|| bad(cmd, format!("no named view `{name}`")))?,
|
||||
},
|
||||
};
|
||||
if !usable_camera(&cam) {
|
||||
if !cam.is_valid() || !cam.fov.is_finite() || cam.fov < 0.0 {
|
||||
return Err(bad(cmd, "the camera must be finite with a positive distance"));
|
||||
}
|
||||
s.camera = Some(cam);
|
||||
reply(cmd, CameraReply { camera: cam, param_warnings: Vec::new() })
|
||||
Ok(json!({ "camera": cam }))
|
||||
}
|
||||
|
||||
/// The orbit camera of a named view (Z up, no roll).
|
||||
@@ -1181,18 +1134,17 @@ fn view_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = s.doc_mut().named_views.get_mut(i) {
|
||||
v.name = name.to_string();
|
||||
}
|
||||
reply(cmd, ViewRenamed { view: name.to_string(), param_warnings: Vec::new() })
|
||||
Ok(json!({ "view": name }))
|
||||
}
|
||||
|
||||
fn view_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "view.delete";
|
||||
let i = view_index(s, p, cmd)?;
|
||||
let i = view_index(s, p, "view.delete")?;
|
||||
let v = s.doc_mut().named_views.remove(i);
|
||||
reply(cmd, ViewDeleted { deleted: v.name, param_warnings: Vec::new() })
|
||||
Ok(json!({ "deleted": v.name }))
|
||||
}
|
||||
|
||||
fn view_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
reply("view.list", ViewListResult { views: s.doc.named_views.clone(), param_warnings: Vec::new() })
|
||||
Ok(json!({ "views": s.doc.named_views }))
|
||||
}
|
||||
|
||||
/// The keys whose strings name bodies, alone or in a list (`body`, `targets`…), at any depth of a
|
||||
@@ -1541,17 +1493,17 @@ fn redefine_sketch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
let attachment = s.doc.feature(id).and_then(|feature| match &feature.kind {
|
||||
FeatureKind::Sketch { plane, .. } => Some(if super::sketch::face::anchor(plane).is_some() {
|
||||
RedefineAttachment::ExactFace
|
||||
"exact_face"
|
||||
} else if solidcraft_doc::sheet::plane_sheet_face(plane).is_some() {
|
||||
RedefineAttachment::SheetFace
|
||||
"sheet_face"
|
||||
} else {
|
||||
RedefineAttachment::Fixed
|
||||
"fixed"
|
||||
}),
|
||||
_ => None,
|
||||
});
|
||||
let note = frame.and_then(|f| super::sketch::frame_note(Some(f), &placement)).map(str::to_string);
|
||||
let frame = frame.and_then(PlaneFrame::from_name);
|
||||
reply(cmd, RedefineSketchResult { sketch: id, attachment, frame, note, created: None, param_warnings: Vec::new() })
|
||||
let mut out = json!({ "sketch": id,"attachment":attachment });
|
||||
super::sketch::frame_reply(&mut out, frame, &placement);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -4,70 +4,37 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::{FeatureKind, PlaneRef};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, name_or_id_values, vec3};
|
||||
use crate::schema::timeline_clipboard::{CopyParams, CopyResult, PasteError, PasteParams, PasteResult, Pasted};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();
|
||||
const PASTE_CONTRACT: TypedContract<PasteParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("timeline.copy", "Copy Features", crate::checked!("timeline.copy", copy))
|
||||
.icon("copy")
|
||||
.noundo()
|
||||
.contract(©_CONTRACT)
|
||||
.output(output_schema_for::<CopyResult>)
|
||||
.params("features: [ids or names] (in timeline order on paste)"),
|
||||
CommandSpec::new("timeline.paste", "Paste Features", crate::checked!("timeline.paste", paste))
|
||||
.icon("paste")
|
||||
.contract(&PASTE_CONTRACT)
|
||||
.output(output_schema_for::<PasteResult>)
|
||||
.params(
|
||||
"translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \
|
||||
CommandSpec::new("timeline.copy", "Copy Features", copy).icon("copy").noundo().params("features: [ids or names] (in timeline order on paste)"),
|
||||
CommandSpec::new("timeline.paste", "Paste Features", paste).icon("paste").params(
|
||||
"translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \
|
||||
component_path?: its placement (default: the active one, else its only one); the copies go at the marker, each where \
|
||||
its original is in the world (copies into their own component keep its coordinates); body transfers are left out; \
|
||||
from_design?: true to paste sketch features from the host's cross-design clipboard snapshot",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// A command's reply as JSON: they build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// The `features` of `timeline.copy`: named or numbered, both kinds in one list, 1…1000 of them.
|
||||
/// The reader the command's contract uses too.
|
||||
pub(crate) fn copy_keys(p: &Value) -> Result<&[Value]> {
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "timeline.copy";
|
||||
// The features are named or numbered, and both kinds can sit in one list.
|
||||
let keys = name_or_id_values(cmd, p, "features")?;
|
||||
if keys.is_empty() || keys.len() > 1000 {
|
||||
return Err(bad(cmd, "`features` must list 1…1000 features"));
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// A `component_path` of `timeline.paste`: 0 to 64 occurrence ids. The reader both pastes and the
|
||||
/// command's contract use.
|
||||
pub(crate) fn component_path_form(v: &Value) -> Option<Vec<u64>> {
|
||||
v.as_array().filter(|a| a.len() <= 64).and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "timeline.copy";
|
||||
let keys = copy_keys(p)?;
|
||||
let ids = keys.iter().map(|key| super::edit::feature_id(s, Some(key), cmd)).collect::<Result<Vec<_>>>()?;
|
||||
// Keep timeline order so sketches come before the features that use them.
|
||||
let copied: Vec<solidcraft_doc::Feature> = s.doc.features.iter().filter(|f| ids.contains(&f.id)).cloned().collect();
|
||||
let names: Vec<String> = copied.iter().map(|f| f.name.clone()).collect();
|
||||
s.clipboard = copied;
|
||||
s.foreign_copy = Some(std::sync::Arc::new(crate::ForeignCopy::of_features(s)));
|
||||
reply(cmd, CopyResult { copied: names, param_warnings: Vec::new() })
|
||||
Ok(json!({"copied": names}))
|
||||
}
|
||||
|
||||
/// Origin planes become explicit planes so a translation can move them.
|
||||
@@ -119,7 +86,12 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let given_path = match p.get("component_path") {
|
||||
None => None,
|
||||
Some(v) => Some(component_path_form(v).ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?),
|
||||
Some(v) => Some(
|
||||
v.as_array()
|
||||
.filter(|a| a.len() <= 64)
|
||||
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
.ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?,
|
||||
),
|
||||
};
|
||||
let mut sketches: BTreeMap<u64, u64> = BTreeMap::new();
|
||||
let mut bodies: BTreeMap<String, String> = BTreeMap::new();
|
||||
@@ -258,15 +230,15 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_name = doc.feature(id).map(|x| x.name.clone()).unwrap_or_default();
|
||||
sketches.insert(f.id, id);
|
||||
names.insert(f.name.clone(), new_name.clone());
|
||||
made.push(Pasted { id, name: new_name, from: f.name.clone() });
|
||||
made.push(json!({"id": id, "name": new_name, "from": f.name}));
|
||||
}
|
||||
s.refresh();
|
||||
let errors: Vec<PasteError> = made
|
||||
let errors: Vec<Value> = made
|
||||
.iter()
|
||||
.map(|m| m.id)
|
||||
.filter_map(|id| s.model.result(id).and_then(|r| r.error.clone()).map(|error| PasteError { feature: id, error }))
|
||||
.filter_map(|m| m["id"].as_u64())
|
||||
.filter_map(|id| s.model.result(id).and_then(|r| r.error.clone()).map(|e| json!({"feature": id, "error": e})))
|
||||
.collect();
|
||||
reply(cmd, PasteResult { pasted: made, errors, notices, param_warnings: Vec::new() })
|
||||
Ok(json!({"pasted": made, "errors": errors, "notices":notices}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::{Document, Feature, FeatureKind, Mat, PlaneRef};
|
||||
|
||||
use crate::params::{bad, vec3};
|
||||
use crate::schema::timeline_clipboard::{PasteResult, Pasted};
|
||||
use crate::{Result, Sel, Session};
|
||||
|
||||
const CMD: &str = "timeline.paste";
|
||||
@@ -187,7 +186,11 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let path = match p.get("component_path") {
|
||||
Some(v) => super::clipboard::component_path_form(v).ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?,
|
||||
Some(v) => v
|
||||
.as_array()
|
||||
.filter(|a| a.len() <= 64)
|
||||
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
.ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?,
|
||||
None if component == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(component)),
|
||||
None => super::component::placing::placement_of(s, &s.design_document(), component, None, "component_path", CMD)?.0,
|
||||
};
|
||||
@@ -246,7 +249,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
ids.insert(feature.id, id);
|
||||
names.insert(feature.name.clone(), name.clone());
|
||||
made.push(Pasted { id, name: name.clone(), from: feature.name.clone() });
|
||||
made.push(json!({"id": id, "name": name, "from": feature.name}));
|
||||
}
|
||||
parameters(scratch.doc_mut(), ©.doc, ©.features, &mut mapped)?;
|
||||
let source_values = copy.doc.param_values().0;
|
||||
@@ -304,6 +307,5 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
scratch.selection = ids.values().map(|id| Sel::Feature { id: *id }).collect();
|
||||
s.accept_computed(scratch);
|
||||
serde_json::to_value(PasteResult { pasted: made, errors: Vec::new(), notices: Vec::new(), param_warnings: Vec::new() })
|
||||
.map_err(|e| bad(CMD, e.to_string()))
|
||||
Ok(json!({"pasted": made, "errors": [], "notices": []}))
|
||||
}
|
||||
|
||||
@@ -13,23 +13,12 @@ use solidcraft_doc::{Feature, FeatureKind, Mat, Occurrence};
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_, string_list, vec3};
|
||||
use crate::schema::component::{
|
||||
ActivateParams, ActivateResult, ChildEntry, CompactPlacement, ComponentNode, CreateParams, CreateResult, DeleteParams, DeleteResult,
|
||||
EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, FromBodiesParams, FromBodiesResult, ListParams, ListResult,
|
||||
MoveFeaturesParams, MoveFeaturesResult, MoveSketchesToPartsParams, MoveSketchesToPartsResult, NamesOrCount, OccurrenceAlignParams,
|
||||
OccurrenceAlignResult, PlacementEntry, PlacementInfo, PropertiesParams, PropertiesResult, RenameParams, RenameResult, ReparentItemsParams,
|
||||
ReparentItemsResult, UnlockParams, UnlockResult,
|
||||
EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, MoveSketchesToPartsParams,
|
||||
MoveSketchesToPartsResult, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const ACTIVATE_CONTRACT: TypedContract<ActivateParams> = TypedContract::new();
|
||||
const CREATE_CONTRACT: TypedContract<CreateParams> = TypedContract::new();
|
||||
const DELETE_CONTRACT: TypedContract<DeleteParams> = TypedContract::new();
|
||||
const FROM_BODIES_CONTRACT: TypedContract<FromBodiesParams> = TypedContract::new();
|
||||
const LIST_CONTRACT: TypedContract<ListParams> = TypedContract::new();
|
||||
const PROPERTIES_CONTRACT: TypedContract<PropertiesParams> = TypedContract::new();
|
||||
const RENAME_CONTRACT: TypedContract<RenameParams> = TypedContract::new();
|
||||
const UNLOCK_CONTRACT: TypedContract<UnlockParams> = TypedContract::new();
|
||||
const EDIT_IN_PLACE_CONTRACT: TypedContract<EditInPlaceParams> = TypedContract::new();
|
||||
const FINISH_EDIT_CONTRACT: TypedContract<FinishEditParams> = TypedContract::new();
|
||||
const MOVE_FEATURES_CONTRACT: TypedContract<MoveFeaturesParams> = TypedContract::new();
|
||||
@@ -78,23 +67,14 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("component.show_history", "Show Component History", show_history)
|
||||
.icon("eye").doc_only()
|
||||
.params("component: id or name; puts a component's features back in the History bar after Hide Component History (#10393)"),
|
||||
CommandSpec::new("component.create", "New Component", crate::checked!("component.create", new_component))
|
||||
CommandSpec::new("component.create", "New Component", new_component)
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("component")
|
||||
.contract(&CREATE_CONTRACT)
|
||||
.output(output_schema_for::<CreateResult>)
|
||||
.params("name?, parent?: component id or name (default: the active one); parent_path?: exact parent placement; activate?: bool (default true); grounded?: bool (default: true for the design's first part, false otherwise)"),
|
||||
CommandSpec::new("component.from_bodies", "Create Components from Bodies", crate::checked!("component.from_bodies", from_bodies))
|
||||
CommandSpec::new("component.from_bodies", "Create Components from Bodies", from_bodies)
|
||||
.icon("component")
|
||||
.contract(&FROM_BODIES_CONTRACT)
|
||||
.output(output_schema_for::<FromBodiesResult>)
|
||||
.params("bodies: [names] → one new component per body, named after it"),
|
||||
CommandSpec::new("component.activate", "Activate Component", crate::checked!("component.activate", activate))
|
||||
.icon("activate")
|
||||
.noundo()
|
||||
.contract(&ACTIVATE_CONTRACT)
|
||||
.output(output_schema_for::<ActivateResult>)
|
||||
.params("component: id or name (0 or \"root\" for the design); occurrence?, path?: exact placement used to author shared geometry"),
|
||||
CommandSpec::new("component.activate", "Activate Component", activate).icon("activate").noundo().params("component: id or name (0 or \"root\" for the design); occurrence?, path?: exact placement used to author shared geometry"),
|
||||
CommandSpec::new("component.edit_in_place", "Edit in Place", crate::checked!("component.edit_in_place", edit_in_place))
|
||||
.icon("edit")
|
||||
.noundo()
|
||||
@@ -119,41 +99,22 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
fails while the design has unsaved changes (run file.save first) or something is open in it; asked during the agent's \
|
||||
turn it finishes once the turn ends (queued: true); elsewhere nothing changes",
|
||||
),
|
||||
CommandSpec::new("component.list", "List Components", crate::checked!("component.list", list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&LIST_CONTRACT)
|
||||
.output(output_schema_for::<ListResult>)
|
||||
.params(
|
||||
"compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \
|
||||
identity transforms; children as occurrence ids); bodies?: bool (with compact: body names, not their count)",
|
||||
),
|
||||
CommandSpec::new("component.properties", "Component Physical Properties", crate::checked!("component.properties", properties::component))
|
||||
CommandSpec::new("component.list", "List Components", list).icon("list").noundo().params(
|
||||
"compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \
|
||||
identity transforms; children as occurrence ids); bodies?: bool (with compact: body names, not their count)",
|
||||
),
|
||||
CommandSpec::new("component.properties", "Component Physical Properties", properties::component)
|
||||
.icon("measure").noundo()
|
||||
.contract(&PROPERTIES_CONTRACT)
|
||||
.output(output_schema_for::<PropertiesResult>)
|
||||
.params("component?: id or name (default active); descendants?: bool (default true); about?: [x, y, z] (mm). Measures the first placement, or all placements for root, including pending moves; material-aware mass and center of mass in world coordinates; volume, density, mass, center of mass and inertia_g_mm2 (the inertia tensor about the body's center of mass, world axes, from its tessellation) only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total.first_moment_g_mm (mass × center of mass), inertia_g_mm2 about the total center of mass, principal_moments_g_mm2 (smallest first) and principal_axes (unit, right-handed); with about, total.inertia_about {point, inertia_g_mm2}"),
|
||||
CommandSpec::new("occurrence.properties", "Occurrence Physical Properties", properties::occurrence)
|
||||
.icon("measure").noundo()
|
||||
.params("occurrence: id or name; path?: [occurrence ids] (required if nested under multiple instances); descendants?: bool (default true); about?: [x, y, z] (mm). Physical properties of this placement in world coordinates, including pending moves; volume, density, mass, center of mass and inertia_g_mm2 only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total inertia as in component.properties"),
|
||||
CommandSpec::new("component.rename", "Rename Component", crate::checked!("component.rename", rename))
|
||||
.icon("rename")
|
||||
.contract(&RENAME_CONTRACT)
|
||||
.output(output_schema_for::<RenameResult>)
|
||||
.params("component, name"),
|
||||
CommandSpec::new("component.delete", "Delete Component", crate::checked!("component.delete", delete))
|
||||
.icon("delete")
|
||||
.contract(&DELETE_CONTRACT)
|
||||
.output(output_schema_for::<DeleteResult>)
|
||||
.params("component: deletes it, its subcomponents, occurrences and features"),
|
||||
CommandSpec::new("component.unlock", "Unlock Contents", crate::checked!("component.unlock", unlock))
|
||||
.icon("rigid_group")
|
||||
.contract(&UNLOCK_CONTRACT)
|
||||
.output(output_schema_for::<UnlockResult>)
|
||||
.params(
|
||||
"component: removes the rigid joints that hold its contents together (an imported assembly's rigid group), so its parts \
|
||||
move and take joints one by one → joints (the ids removed)",
|
||||
),
|
||||
CommandSpec::new("component.rename", "Rename Component", rename).icon("rename").params("component, name"),
|
||||
CommandSpec::new("component.delete", "Delete Component", delete).icon("delete").params("component: deletes it, its subcomponents, occurrences and features"),
|
||||
CommandSpec::new("component.unlock", "Unlock Contents", unlock).icon("rigid_group").params(
|
||||
"component: removes the rigid joints that hold its contents together (an imported assembly's rigid group), so its parts \
|
||||
move and take joints one by one → joints (the ids removed)",
|
||||
),
|
||||
CommandSpec::new("component.move_bodies", "Move Bodies to Component", move_bodies).icon("move").params(
|
||||
"bodies: [names], component; component_path?: its placement to place them by (default: its only one, else the active \
|
||||
one; a component placed more than once gets them in every instance); from_path?: the placement of their component they \
|
||||
@@ -242,11 +203,6 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
|
||||
const ALIGN_CONTRACT: TypedContract<OccurrenceAlignParams> = TypedContract::new();
|
||||
|
||||
/// A typed reply as the JSON a handler returns.
|
||||
pub(super) fn reply<T: serde::Serialize>(value: T) -> Result<Value> {
|
||||
serde_json::to_value(value).map_err(|e| crate::EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
fn key(v: Option<&Value>) -> Option<String> {
|
||||
match v {
|
||||
Some(Value::Number(n)) => Some(n.to_string()),
|
||||
@@ -332,14 +288,7 @@ pub(super) fn new_component(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let name = s.doc.components.iter().find(|c| c.id == id).map(|c| c.name.clone()).unwrap_or_default();
|
||||
let occ = s.doc.occurrence_of(id);
|
||||
reply(CreateResult {
|
||||
component: id,
|
||||
name,
|
||||
parent,
|
||||
occurrence: occ.map(|o| o.id),
|
||||
grounded: occ.is_some_and(|o| o.grounded),
|
||||
param_warnings: Vec::new(),
|
||||
})
|
||||
Ok(json!({"component": id, "name": name, "parent": parent, "occurrence": occ.map(|o| o.id), "grounded": occ.is_some_and(|o| o.grounded)}))
|
||||
}
|
||||
|
||||
fn from_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -385,7 +334,7 @@ fn activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.active_component = id;
|
||||
s.active_occurrence_path = path;
|
||||
s.revision += 1;
|
||||
reply(ActivateResult { active: id, param_warnings: Vec::new() })
|
||||
Ok(json!({ "active": id }))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -393,20 +342,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
// Compact: what a large assembly needs to be found around in, without every name and matrix.
|
||||
let compact = bool_(p, "compact").unwrap_or(false);
|
||||
let names = |v: Vec<&str>| if compact { NamesOrCount::Count(v.len()) } else { NamesOrCount::Names(v.into_iter().map(str::to_string).collect()) };
|
||||
let names = |v: Vec<&str>| if compact { json!(v.len()) } else { json!(v) };
|
||||
let body_names = !compact || bool_(p, "bodies").unwrap_or(false);
|
||||
let placement = |o: &Occurrence| {
|
||||
if !compact {
|
||||
return PlacementEntry::Full(PlacementInfo::from(o));
|
||||
return json!(o);
|
||||
}
|
||||
let moved = o.transform.iter().flatten().zip(solidcraft_doc::IDENTITY.iter().flatten()).any(|(a, b)| (a - b).abs() > 1e-12);
|
||||
PlacementEntry::Compact(CompactPlacement {
|
||||
id: o.id,
|
||||
name: o.name.clone(),
|
||||
parent: o.parent,
|
||||
grounded: o.grounded,
|
||||
transform: moved.then_some(o.transform),
|
||||
})
|
||||
let mut v = json!({"id": o.id, "name": o.name, "parent": o.parent, "grounded": o.grounded});
|
||||
if o.transform.iter().flatten().zip(solidcraft_doc::IDENTITY.iter().flatten()).any(|(a, b)| (a - b).abs() > 1e-12) {
|
||||
v["transform"] = json!(o.transform);
|
||||
}
|
||||
v
|
||||
};
|
||||
// Each component's bodies, features, occurrences and children, grouped once rather than
|
||||
// searched for every component (thousands of each in a design with many components).
|
||||
@@ -430,37 +376,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sketches = named(|k| matches!(k, FeatureKind::Sketch { .. }));
|
||||
let construction = named(|k| matches!(k, FeatureKind::ConstructionPlane { .. }));
|
||||
let features = named(|k| !matches!(k, FeatureKind::Sketch { .. } | FeatureKind::ConstructionPlane { .. }));
|
||||
let occurrences: Vec<PlacementEntry> = occurrences_of.get(&id).into_iter().flatten().map(|o| placement(o)).collect();
|
||||
let children: Vec<ChildEntry> = children_of
|
||||
.get(&id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|o| if compact { ChildEntry::Id(o.id) } else { ChildEntry::Full(PlacementInfo::from(*o)) })
|
||||
.collect();
|
||||
let bodies =
|
||||
if body_names { NamesOrCount::Names(bodies.into_iter().map(str::to_string).collect()) } else { NamesOrCount::Count(bodies.len()) };
|
||||
ComponentNode {
|
||||
id,
|
||||
name: name.to_string(),
|
||||
parent,
|
||||
bodies,
|
||||
features: names(features),
|
||||
sketches: names(sketches),
|
||||
construction: names(construction),
|
||||
occurrences,
|
||||
children,
|
||||
}
|
||||
let occurrences: Vec<Value> = occurrences_of.get(&id).into_iter().flatten().map(|o| placement(o)).collect();
|
||||
let children: Vec<Value> = children_of.get(&id).into_iter().flatten().map(|o| if compact { json!(o.id) } else { json!(o) }).collect();
|
||||
let bodies = if body_names { json!(bodies) } else { json!(bodies.len()) };
|
||||
json!({"id": id, "name": name, "parent": parent, "bodies": bodies, "features": names(features), "sketches": names(sketches),
|
||||
"construction": names(construction), "occurrences": occurrences, "children": children})
|
||||
};
|
||||
let mut out = vec![node(0, &doc.name, None)];
|
||||
for c in &doc.components {
|
||||
out.push(node(c.id, &c.name, Some(c.parent)));
|
||||
}
|
||||
reply(ListResult {
|
||||
active: s.active_component,
|
||||
components: out,
|
||||
pending_moves: s.pending_moves.keys().copied().collect(),
|
||||
param_warnings: Vec::new(),
|
||||
})
|
||||
Ok(json!({"active": s.active_component, "components": out, "pending_moves": s.pending_moves.keys().collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -485,7 +411,7 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A sketch projecting a body of one of those placements keeps it.
|
||||
super::sketch_project::follow_placed_renames(d, &st, &placed, None);
|
||||
}
|
||||
reply(RenameResult { component: id, name: name.to_string(), param_warnings: Vec::new() })
|
||||
Ok(json!({"component": id, "name": name}))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -502,7 +428,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if gone.contains(&s.active_component) {
|
||||
s.active_component = 0;
|
||||
}
|
||||
reply(DeleteResult { deleted: gone, features: removed.features, param_warnings: Vec::new() })
|
||||
Ok(json!({"deleted": gone, "features": removed.features}))
|
||||
}
|
||||
|
||||
fn unlock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -522,7 +448,7 @@ fn unlock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
doc.assembly.links.retain(|l| !gone.contains(&l.a) && !gone.contains(&l.b));
|
||||
s.visibility.hidden_joints.retain(|h| !gone.contains(h));
|
||||
reply(UnlockResult { component: id, joints: gone, param_warnings: Vec::new() })
|
||||
Ok(json!({"component": id, "joints": gone}))
|
||||
}
|
||||
|
||||
fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -9,7 +9,6 @@ use solidcraft_geom::Aabb3;
|
||||
use solidcraft_geom::inertia::{self, Tensor3};
|
||||
|
||||
use crate::params::bad;
|
||||
use crate::schema::component::{BodyProperties, BoundingBox, InertiaAbout, PhysicalProperties, PropertiesResult, TotalProperties};
|
||||
use crate::{Result, Session};
|
||||
|
||||
fn descendants(p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -85,8 +84,10 @@ pub(super) fn component(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
doc.components.iter().find(|c| c.id == id).map(|c| c.name.clone()).ok_or_else(|| bad(cmd, "no active component"))?
|
||||
};
|
||||
let properties = measure(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
|
||||
super::reply(PropertiesResult { component: id, name, properties, param_warnings: Vec::new() })
|
||||
let mut out = properties(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
|
||||
out["component"] = json!(id);
|
||||
out["name"] = json!(name);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -199,12 +200,7 @@ fn measure_placed(body: &solidcraft_doc::ModelBody, transform: Mat) -> Result<Pl
|
||||
})
|
||||
}
|
||||
|
||||
/// [`measure`] as the JSON `occurrence.properties` adds its own keys to.
|
||||
fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<Value> {
|
||||
super::reply(measure(s, doc, selected, descendants, about, cmd)?)
|
||||
}
|
||||
|
||||
fn measure(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<PhysicalProperties> {
|
||||
let state = s.model.state();
|
||||
let mut bodies = Vec::new();
|
||||
let (mut volume, mut area, mut mass) = (0.0, 0.0, 0.0);
|
||||
@@ -296,20 +292,13 @@ fn measure(s: &Session, doc: &Document, selected: &[u64], descendants: bool, abo
|
||||
faces += measured.faces;
|
||||
edges += measured.edges;
|
||||
vertices += measured.vertices;
|
||||
bodies.push(BodyProperties {
|
||||
name: body.name.to_string(),
|
||||
component,
|
||||
path: path.clone(),
|
||||
material: doc.body_material(&body.name),
|
||||
closed,
|
||||
density_g_cm3: closed.then_some(density),
|
||||
mass_g: closed.then_some(body_mass),
|
||||
volume_mm3: closed.then_some(measured.volume),
|
||||
area_mm2: measured.area,
|
||||
center_of_mass: closed.then_some(measured.centroid),
|
||||
inertia_g_mm2: body_inertia,
|
||||
bbox: BoundingBox { min: measured.bbox.min, max: measured.bbox.max },
|
||||
});
|
||||
bodies.push(json!({"name": body.name, "component": component, "path": path,
|
||||
"material": doc.body_material(&body.name),
|
||||
"closed": closed, "density_g_cm3": closed.then_some(density),
|
||||
"mass_g": closed.then_some(body_mass), "volume_mm3": closed.then_some(measured.volume),
|
||||
"area_mm2": measured.area, "center_of_mass": closed.then_some(measured.centroid),
|
||||
"inertia_g_mm2": body_inertia,
|
||||
"bbox": {"min": measured.bbox.min, "max": measured.bbox.max}}));
|
||||
}
|
||||
}
|
||||
if let Some(w) = &watch {
|
||||
@@ -332,36 +321,19 @@ fn measure(s: &Session, doc: &Document, selected: &[u64], descendants: bool, abo
|
||||
});
|
||||
let at_centre = at_centre.filter(|i| i.iter().flatten().all(|x| x.is_finite()));
|
||||
let principal = at_centre.and_then(|i| inertia::principal(&i, EQUAL_MOMENTS));
|
||||
let bbox = (!bodies.is_empty()).then_some(BoundingBox { min: bounds.min, max: bounds.max });
|
||||
let inertia_about = about.map(|point| {
|
||||
let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": bounds.min, "max": bounds.max}) };
|
||||
let mut out = json!({"path": selected, "coordinate_frame": "world", "descendants": descendants,
|
||||
"placement_count": placement_count, "body_count": bodies.len(), "bodies": bodies,
|
||||
"total": {"open_bodies_skipped": skipped, "volume_mm3": volume, "area_mm2": area, "mass_g": mass,
|
||||
"center_of_mass": centroid, "first_moment_g_mm": moment, "inertia_g_mm2": at_centre,
|
||||
"principal_moments_g_mm2": principal.map(|(moments, _)| moments), "principal_axes": principal.map(|(_, axes)| axes),
|
||||
"bbox": bbox, "faces": faces, "edges": edges, "vertices": vertices}});
|
||||
if let Some(point) = about {
|
||||
let shifted =
|
||||
centroid.zip(at_centre).map(|(c, i)| inertia::shifted(&i, mass, point - c)).filter(|i| i.iter().flatten().all(|x| x.is_finite()));
|
||||
InertiaAbout { point, inertia_g_mm2: shifted }
|
||||
});
|
||||
Ok(PhysicalProperties {
|
||||
path: selected.to_vec(),
|
||||
coordinate_frame: "world".to_string(),
|
||||
descendants,
|
||||
placement_count,
|
||||
body_count: bodies.len(),
|
||||
bodies,
|
||||
total: TotalProperties {
|
||||
open_bodies_skipped: skipped,
|
||||
volume_mm3: volume,
|
||||
area_mm2: area,
|
||||
mass_g: mass,
|
||||
center_of_mass: centroid,
|
||||
first_moment_g_mm: moment,
|
||||
inertia_g_mm2: at_centre,
|
||||
principal_moments_g_mm2: principal.map(|(moments, _)| moments),
|
||||
principal_axes: principal.map(|(_, axes)| axes),
|
||||
bbox,
|
||||
faces,
|
||||
edges,
|
||||
vertices,
|
||||
inertia_about,
|
||||
},
|
||||
})
|
||||
out["total"]["inertia_about"] = json!({"point": point, "inertia_g_mm2": shifted});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The tessellating work a properties command did on this thread, for tests: placed copies
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Atomic timeline ownership changes, preserving the selected world geometry.
|
||||
use super::*;
|
||||
use crate::schema::component::{BodyComponent, FromBodiesResult};
|
||||
use solidcraft_doc::BodyName;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -129,10 +128,10 @@ pub(super) fn from_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (name, component) in bodies.into_iter().zip(targets) {
|
||||
let feature = transfer(&mut scratch, &name, component, &frames, cmd)?;
|
||||
features.push(feature);
|
||||
made.push(BodyComponent { component, body: name, feature });
|
||||
made.push(json!({"component":component,"body":name,"feature":feature}));
|
||||
}
|
||||
finish(s, &mut scratch, &features, cmd)?;
|
||||
super::reply(FromBodiesResult { components: made, param_warnings: Vec::new() })
|
||||
Ok(json!({"components":made}))
|
||||
}
|
||||
|
||||
/// A placement path parameter (`component_path`: the target's placement to place by,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use solidcraft_geom::prelude::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::{Loop2, Seg2, Vec2};
|
||||
use solidcraft_doc::expr::Kind;
|
||||
use solidcraft_doc::frame::{self, Anchor, MemberProfile, Profile, ProfileSpec};
|
||||
@@ -17,23 +17,12 @@ use super::features::{add_feature, check_expr, sketch_id};
|
||||
use super::sketch::edit;
|
||||
use super::{CommandSpec, in_sketch, not_in_sketch};
|
||||
use crate::params::{bad, bool_, expr, num, str_, string_list, vec2};
|
||||
use crate::schema::features::FeatureResult;
|
||||
use crate::schema::frame::{
|
||||
CreatedIds, FrameMemberParams, ProfileInsertParams, ProfileInsertResult, ProfileKindInfo, ProfileListParams, ProfileListResult, ProfileOut,
|
||||
ProfilePropertiesParams, ProfilePropertiesResult, ProfileSection,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "frame_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
const MEMBER_CONTRACT: TypedContract<FrameMemberParams> = TypedContract::new();
|
||||
const LIST_CONTRACT: TypedContract<ProfileListParams> = TypedContract::new();
|
||||
const PROPERTIES_CONTRACT: TypedContract<ProfilePropertiesParams> = TypedContract::new();
|
||||
const INSERT_CONTRACT: TypedContract<ProfileInsertParams> = TypedContract::new();
|
||||
|
||||
/// The profile parameter, as every frame command documents it.
|
||||
macro_rules! profile_doc {
|
||||
() => {
|
||||
@@ -42,40 +31,20 @@ macro_rules! profile_doc {
|
||||
}
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("frame.member", "Frame Member", crate::checked!("frame.member", member))
|
||||
.at("WELDMENTS", "CREATE")
|
||||
.icon("frame_member")
|
||||
.enabled(not_in_sketch)
|
||||
.contract(&MEMBER_CONTRACT)
|
||||
.output(output_schema_for::<FeatureResult>)
|
||||
.params(concat!(
|
||||
CommandSpec::new("frame.member", "Frame Member", member).at("WELDMENTS", "CREATE").icon("frame_member").enabled(not_in_sketch).params(concat!(
|
||||
"sketch: the frame sketch (id or name; 2D or 3D); lines?: [curve ids] (one member each; default: every straight line drawn in the sketch: not construction, not projected or otherwise linked, not of no length); ",
|
||||
profile_doc!(),
|
||||
" | profile_sketch: a sketch whose profile is the section, in its own x and y around its origin, with profiles?: picks as solid.extrude takes them (default: its material, nested loops alternating, so two circles make a tube); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point that sits on each line, default origin); angle?: angle expr (the profile turned about the line; default 0: its y as near world up as the line allows, a vertical member's x along world X); mirror?: bool (the profile mirrored across its y axis); name?; body_name? (what the members are named after, then numbered: `Rail`, `Rail (2)`…; default the profile's description, `Rect Tube 40x40x3`, or the profile sketch's name); names?: {line id: name} (names to keep, as Edit Feature keeps them). One body per line, from its start to its end; each member keeps its name when other lines are added or deleted. Returns the feature and the bodies it made"
|
||||
)),
|
||||
CommandSpec::new("frame.profile.list", "Profile Library", crate::checked!("frame.profile.list", list))
|
||||
.icon("library")
|
||||
CommandSpec::new("frame.profile.list", "Profile Library", list).icon("library")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&LIST_CONTRACT)
|
||||
.output(output_schema_for::<ProfileListResult>)
|
||||
.params("Returns kinds: [{kind, label, required, optional, example}]: the built-in profiles, each SolidCraft's own parametric definition"),
|
||||
CommandSpec::new("frame.profile.properties", "Profile Properties", crate::checked!("frame.profile.properties", properties))
|
||||
.icon("measure")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&PROPERTIES_CONTRACT)
|
||||
.output(output_schema_for::<ProfilePropertiesResult>)
|
||||
.params(concat!(
|
||||
CommandSpec::new("frame.profile.properties", "Profile Properties", properties).icon("measure").noundo().doc_only().params(concat!(
|
||||
profile_doc!(),
|
||||
"; density?: kg/m³ (adds mass_per_m, kg/m). Returns profile (every default filled in), area (mm²), centroid [x,y] (mm, from the bounding box centre), ixx, iyy, ixy (mm⁴ about the centroid), width, height"
|
||||
)),
|
||||
CommandSpec::new("frame.profile.insert", "Insert Profile", crate::checked!("frame.profile.insert", insert))
|
||||
.icon("import")
|
||||
.enabled(in_sketch)
|
||||
.contract(&INSERT_CONTRACT)
|
||||
.output(output_schema_for::<ProfileInsertResult>)
|
||||
.params(concat!(
|
||||
CommandSpec::new("frame.profile.insert", "Insert Profile", insert).icon("import").enabled(in_sketch).params(concat!(
|
||||
profile_doc!(),
|
||||
"; at?: [x,y] (sketch mm, default the origin); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point placed on `at`: its origin, the default and a built-in profile's centre, its bounding box's centre, its centroid, or a corner or edge middle of its bounding box); angle?: radians, counter-clockwise; fixed?: bool (default true: the curves are locked, so solving the sketch keeps the shape); sketch?: id|name (default: the sketch being edited). Returns the section as frame.profile.properties does",
|
||||
created_doc!()
|
||||
@@ -104,32 +73,29 @@ fn profile(s: &Session, cmd: &str, p: &Value) -> Result<Profile> {
|
||||
resolve(s, cmd, &profile_spec(cmd, p)?)
|
||||
}
|
||||
|
||||
/// A frame command's reply, built from its schema's type so the two can't drift apart.
|
||||
fn frame_reply(cmd: &str, r: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let kinds = frame::profile_kinds().iter().map(ProfileKindInfo::from).collect();
|
||||
frame_reply("frame.profile.list", ProfileListResult { kinds, param_warnings: Vec::new() })
|
||||
Ok(json!({"kinds": frame::profile_kinds()}))
|
||||
}
|
||||
|
||||
/// The profile's section as the commands report it.
|
||||
fn section(cmd: &str, profile: &Profile, density: Option<f64>) -> Result<ProfileSection> {
|
||||
fn section_json(cmd: &str, profile: &Profile, density: Option<f64>) -> Result<Value> {
|
||||
let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let s = frame::section(®ion);
|
||||
Ok(ProfileSection {
|
||||
profile: ProfileOut(profile.filled()),
|
||||
area: s.area,
|
||||
centroid: s.centroid,
|
||||
ixx: s.ixx,
|
||||
iyy: s.iyy,
|
||||
ixy: s.ixy,
|
||||
width: s.width,
|
||||
height: s.height,
|
||||
let mut out = json!({
|
||||
"profile": profile.filled(),
|
||||
"area": s.area,
|
||||
"centroid": s.centroid,
|
||||
"ixx": s.ixx,
|
||||
"iyy": s.iyy,
|
||||
"ixy": s.ixy,
|
||||
"width": s.width,
|
||||
"height": s.height,
|
||||
});
|
||||
if let (Some(rho), Some(o)) = (density, out.as_object_mut()) {
|
||||
// mm² × 1e-6 m²/mm² × kg/m³ = kg/m.
|
||||
mass_per_m: density.map(|rho| s.area * 1e-6 * rho),
|
||||
})
|
||||
o.insert("mass_per_m".into(), json!(s.area * 1e-6 * rho));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn properties(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -143,7 +109,7 @@ fn properties(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(cmd, "`density` must be a positive number of kg/m³ (at most 1e6)"))?,
|
||||
),
|
||||
};
|
||||
frame_reply(cmd, ProfilePropertiesResult { section: section(cmd, &profile, density)?, param_warnings: Vec::new() })
|
||||
section_json(cmd, &profile, density)
|
||||
}
|
||||
|
||||
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -169,16 +135,15 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let placed = frame::placed(®ion, frame::anchor_point(std::slice::from_ref(®ion), anchor), at, angle);
|
||||
let section = section(cmd, &profile, None)?;
|
||||
let section = section_json(cmd, &profile, None)?;
|
||||
let (created, info) = edit(s, p, cmd, false, |sk, _| {
|
||||
let before = sk.clone();
|
||||
for l in std::iter::once(&placed.outer).chain(&placed.holes) {
|
||||
add_loop(sk, l, fixed, cmd)?;
|
||||
}
|
||||
serde_json::from_value::<CreatedIds>(super::sketch_created(Some(&before), sk)).map_err(|e| bad(cmd, e.to_string()))
|
||||
Ok(super::sketch_created(Some(&before), sk))
|
||||
})?;
|
||||
let sketch = serde_json::from_value(info).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
frame_reply(cmd, ProfileInsertResult { created, section, sketch, param_warnings: Vec::new() })
|
||||
Ok(json!({"created": created, "section": section, "sketch": info}))
|
||||
}
|
||||
|
||||
/// Draw the closed loop `l` (lines and arcs) into the sketch, each segment sharing its end
|
||||
|
||||
@@ -12,15 +12,13 @@ use solidcraft_sketch::CurveKind;
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_, string_list};
|
||||
use crate::schema::inspect::{
|
||||
BodyFeaturesParams, BodyListParams, FaceCylinder, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads,
|
||||
ModelThreadsParams,
|
||||
BodyListParams, FaceCylinder, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads, ModelThreadsParams,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const BODY_LIST_CONTRACT: TypedContract<BodyListParams> = TypedContract::new();
|
||||
const THREADS_CONTRACT: TypedContract<ModelThreadsParams> = TypedContract::new();
|
||||
const BODY_FEATURES_CONTRACT: TypedContract<BodyFeaturesParams> = TypedContract::new();
|
||||
|
||||
#[path = "appearance_chain.rs"]
|
||||
mod appearance_chain;
|
||||
@@ -28,9 +26,6 @@ mod appearance_chain;
|
||||
#[path = "appearance_gestures.rs"]
|
||||
pub(super) mod appearance_gestures;
|
||||
|
||||
#[path = "body_features.rs"]
|
||||
mod body_features;
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("inspect.colored_components", "Component Colors", colored_components)
|
||||
.at("SOLID", "INSPECT").icon("colored_components").noundo()
|
||||
@@ -70,15 +65,6 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.noundo()
|
||||
.contract(&THREADS_CONTRACT)
|
||||
.output(output_schema_for::<ModelThreads>),
|
||||
CommandSpec::new("model.body_features", "List Body Features", crate::checked!("model.body_features", body_features::model_body_features))
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
.contract(&BODY_FEATURES_CONTRACT)
|
||||
.output(output_schema_for::<ModelBodyFeatures>)
|
||||
.params(
|
||||
"body?: name (a placed copy's name means the body it shows; default every body) → bodies: [{body, features: [{id, name}]}], \
|
||||
in timeline order the feature that created each body, every later one that changed it, and those of bodies consumed into it. Read-only",
|
||||
),
|
||||
CommandSpec::new("material.assign", "Physical Material", physical_material)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("material")
|
||||
|
||||
+102
-219
@@ -15,24 +15,11 @@ use solidcraft_geom::Aabb3;
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, num, str_, vec3};
|
||||
use crate::schema::joints::{
|
||||
AsBuiltJointParams, CamLift, ContactStop, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams, DriveJointResult,
|
||||
EditJointResult, FloatingChain, HeldValue, InspectJointParams, InspectJointResult, JointAddedResult, JointDeleted, JointFrame, JointLimitsParams,
|
||||
JointProblem, LinkInfo, ListJointsParams, ListJointsResult, ListedJoint, ListedOrigin, LoopStop, NamedValue, OccurrenceDof, SolveJointsParams,
|
||||
SolveReport, SolveResult, ValueUnit,
|
||||
};
|
||||
use crate::schema::joints::EditJointResult;
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const EDIT_CONTRACT: TypedContract<crate::schema::joints::EditJointParams> = TypedContract::new();
|
||||
const CREATE_CONTRACT: TypedContract<CreateJointParams> = TypedContract::new();
|
||||
const AS_BUILT_CONTRACT: TypedContract<AsBuiltJointParams> = TypedContract::new();
|
||||
const DRIVE_CONTRACT: TypedContract<DriveJointParams> = TypedContract::new();
|
||||
const LIMITS_CONTRACT: TypedContract<JointLimitsParams> = TypedContract::new();
|
||||
const DELETE_CONTRACT: TypedContract<DeleteJointParams> = TypedContract::new();
|
||||
const LIST_CONTRACT: TypedContract<ListJointsParams> = TypedContract::new();
|
||||
const INSPECT_CONTRACT: TypedContract<InspectJointParams> = TypedContract::new();
|
||||
const SOLVE_CONTRACT: TypedContract<SolveJointsParams> = TypedContract::new();
|
||||
|
||||
#[path = "joints_inspect.rs"]
|
||||
mod inspect;
|
||||
@@ -41,13 +28,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params(
|
||||
"name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size; z?: [x,y,z] the frame's z instead of the face's normal, along the edge when it runs that way, x chosen from z: an edge or corner picked as it is, kept as a point where it can't be found by name) | point: [x,y,z], z?: [x,y,z]; a circle's z?: [x,y,z] (a round edge's centre with the way out of it: its end by name when that is the frame it shows, else a point there); body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",
|
||||
),
|
||||
CommandSpec::new("joint.create", "Joint", crate::checked!("joint.create", joint))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("joint")
|
||||
.key("J")
|
||||
.contract(&CREATE_CONTRACT)
|
||||
.output(output_schema_for::<JointAddedResult>)
|
||||
.params(
|
||||
CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params(
|
||||
"type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \
|
||||
(ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"<face name>\"; z? for a point, end?, x? as joint.origin} | origin name); \
|
||||
values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \
|
||||
@@ -59,22 +40,12 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \
|
||||
expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors",
|
||||
),
|
||||
CommandSpec::new("joint.as_built", "As-Built Joint", crate::checked!("joint.as_built", as_built))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("as_built")
|
||||
.contract(&AS_BUILT_CONTRACT)
|
||||
.output(output_schema_for::<JointAddedResult>)
|
||||
.params(
|
||||
CommandSpec::new("joint.as_built", "As-Built Joint", as_built).at("SOLID", "ASSEMBLE").icon("as_built").params(
|
||||
"type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; one on a or b is kept on its face or hole there, so the joint follows it as the design changes; \
|
||||
name?; limits?: [[min, max] | null…]; quiet?: bool",
|
||||
),
|
||||
CommandSpec::new("joint.rigid_group", "Rigid Group", rigid_group).at("SOLID", "ASSEMBLE").icon("rigid_group").params("occurrences: [ids or names] (move together, as they are)"),
|
||||
CommandSpec::new("joint.drive", "Drive Joints", crate::checked!("joint.drive", drive))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("drive")
|
||||
.contract(&DRIVE_CONTRACT)
|
||||
.output(output_schema_for::<DriveJointResult>)
|
||||
.params(
|
||||
CommandSpec::new("joint.drive", "Drive Joints", drive).at("SOLID", "ASSEMBLE").icon("drive").params(
|
||||
"joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; a value driven drops the expression joint.create gave it; clamped to the limits; the other joints of a \
|
||||
closed loop follow, and the motion stops where the loop can no longer close → stopped_by_loop); quiet?: bool (leave out dof \
|
||||
and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; requested: the values asked for, in the same form; \
|
||||
@@ -112,11 +83,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params(
|
||||
"a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is, also when the link replaces another (at the current pose)",
|
||||
),
|
||||
CommandSpec::new("joint.limits", "Joint Limits", crate::checked!("joint.limits", limits))
|
||||
.icon("joint")
|
||||
.contract(&LIMITS_CONTRACT)
|
||||
.output(output_schema_for::<SolveResult>)
|
||||
.params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),
|
||||
CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),
|
||||
CommandSpec::new("joint.edit", "Edit Joint", crate::checked!("joint.edit", edit))
|
||||
.icon("edit")
|
||||
.contract(&EDIT_CONTRACT)
|
||||
@@ -127,26 +94,12 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
its limits and expressions (a relation's values start again where its parts are); an edit that places it again (not a rename alone) \
|
||||
meets a loop it closes as joint.create does, turning an angle a half turn where only that meets it",
|
||||
),
|
||||
CommandSpec::new("joint.delete", "Delete Joint", crate::checked!("joint.delete", delete))
|
||||
.icon("delete")
|
||||
.contract(&DELETE_CONTRACT)
|
||||
.output(output_schema_for::<DeleteJointResult>)
|
||||
.params("joint: id|name (or origin: name, link: index)"),
|
||||
CommandSpec::new("joint.list", "List Joints", crate::checked!("joint.list", list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&LIST_CONTRACT)
|
||||
.output(output_schema_for::<ListJointsResult>)
|
||||
.params(
|
||||
CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"),
|
||||
CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params(
|
||||
"→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \
|
||||
(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",
|
||||
),
|
||||
CommandSpec::new("joint.inspect", "Inspect Joint", crate::checked!("joint.inspect", inspect::inspect))
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
.contract(&INSPECT_CONTRACT)
|
||||
.output(output_schema_for::<InspectJointResult>)
|
||||
.params(
|
||||
CommandSpec::new("joint.inspect", "Inspect Joint", inspect::inspect).icon("inspect").noundo().params(
|
||||
"joint?: id|name (default: every joint) → joints: [{id, name, type, suppressed, visible, flip, offset (mm), angle (deg), values: as joint.list \
|
||||
gives them, dofs, expressions?: {offset?, angle?, values?}, a, b: {occurrence, occurrence_name, component, component_name, path \
|
||||
(occurrence names from the top, `/` between), snap (as saved: type, pick, face, end, edge, corner, x, point, z, in the component's \
|
||||
@@ -155,11 +108,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
unverified?: a name saved before exact names}], resolves, frame?: {origin, z, x} in the world, error?: why the origin is lost}, \
|
||||
links: [{index, role: driver|driven, …as joint.list}], errors, conflicts}] (reads only: nothing changes)",
|
||||
),
|
||||
CommandSpec::new("joint.solve", "Solve Joints", crate::checked!("joint.solve", solve_cmd))
|
||||
.icon("compute")
|
||||
.contract(&SOLVE_CONTRACT)
|
||||
.output(output_schema_for::<SolveResult>)
|
||||
.params("re-place the occurrences from the joints → conflicts, errors, dof"),
|
||||
CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),
|
||||
CommandSpec::new("inspect.interference", "Interference", crate::checked!("inspect.interference", super::interference::interference))
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::interference::InterferenceParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::interference::InterferenceResult>)
|
||||
@@ -279,57 +228,30 @@ fn response_analysis(p: &Value) -> joints::Analysis {
|
||||
}
|
||||
|
||||
/// A solve's answer; `quiet: true` in the command's params leaves out the per-occurrence lists.
|
||||
fn solve_report(sol: &joints::Solution, p: &Value) -> SolveReport {
|
||||
let problems = |list: &[(u64, String, String)]| -> Vec<JointProblem> {
|
||||
list.iter().map(|(joint, name, why)| JointProblem { joint: *joint, name: name.clone(), why: why.clone() }).collect()
|
||||
};
|
||||
let quiet = bool_(p, "quiet").unwrap_or(false);
|
||||
SolveReport {
|
||||
conflicts: problems(&sol.conflicts),
|
||||
errors: problems(&sol.errors),
|
||||
dof: (!quiet).then(|| sol.dof.iter().map(|(o, d)| OccurrenceDof { occurrence: *o, dof: *d }).collect()),
|
||||
fixed: (!quiet).then(|| sol.fixed.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`solve_report`] as JSON, for the commands that add to it.
|
||||
fn sol_json(sol: &joints::Solution, p: &Value) -> Value {
|
||||
serde_json::to_value(solve_report(sol, p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A command's reply as JSON: the joint commands that have output schemas build their replies from
|
||||
/// the types those describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
let mut out = json!({
|
||||
"conflicts": sol.conflicts.iter().map(|(id, n, w)| json!({"joint": id, "name": n, "why": w})).collect::<Vec<_>>(),
|
||||
"errors": sol.errors.iter().map(|(id, n, w)| json!({"joint": id, "name": n, "why": w})).collect::<Vec<_>>(),
|
||||
});
|
||||
if !bool_(p, "quiet").unwrap_or(false) {
|
||||
out["dof"] = sol.dof.iter().map(|(o, d)| json!({"occurrence": o, "dof": d})).collect();
|
||||
out["fixed"] = json!(sol.fixed);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A joint's values as `joint.list` gives them: degrees for angles, mm for distances, each with
|
||||
/// its name and limits. The numbers are rounded for reading (#10747); the joint keeps full
|
||||
/// precision.
|
||||
pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec<Value> {
|
||||
named_value_list(j, q).into_iter().map(|v| serde_json::to_value(v).unwrap_or_default()).collect()
|
||||
}
|
||||
|
||||
/// [`named_values`], typed.
|
||||
pub(crate) fn named_value_list(j: &Joint, q: &[f64]) -> Vec<NamedValue> {
|
||||
j.kind
|
||||
.dofs()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, n)| {
|
||||
let (v, angle) = (q.get(i).copied().unwrap_or(0.0), j.kind.is_angle(i));
|
||||
NamedValue {
|
||||
name: (*n).to_string(),
|
||||
value: expr::round_reported(if angle { v.to_degrees() } else { v }),
|
||||
unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },
|
||||
limits: j.limits.get(i).copied().flatten().map(|(a, b)| {
|
||||
if angle {
|
||||
[expr::round_reported(a.to_degrees()), expr::round_reported(b.to_degrees())]
|
||||
} else {
|
||||
[expr::round_reported(a), expr::round_reported(b)]
|
||||
}
|
||||
}),
|
||||
}
|
||||
json!({"name": n, "value": expr::round_reported(if angle { v.to_degrees() } else { v }), "unit": if angle { "deg" } else { "mm" },
|
||||
"limits": j.limits.get(i).copied().flatten().map(|(a, b)| if angle { [expr::round_reported(a.to_degrees()), expr::round_reported(b.to_degrees())] } else { [expr::round_reported(a), expr::round_reported(b)] })})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -337,14 +259,9 @@ pub(crate) fn named_value_list(j: &Joint, q: &[f64]) -> Vec<NamedValue> {
|
||||
/// A joint's values as the solver places it (after motion links, so a screw's travel follows its
|
||||
/// turn), named as `joint.list` gives them.
|
||||
pub(crate) fn effective_values(s: &Session, id: u64) -> Option<Vec<Value>> {
|
||||
effective_value_list(s, id).map(|list| list.into_iter().map(|v| serde_json::to_value(v).unwrap_or_default()).collect())
|
||||
}
|
||||
|
||||
/// [`effective_values`], typed.
|
||||
fn effective_value_list(s: &Session, id: u64) -> Option<Vec<NamedValue>> {
|
||||
let j = s.doc.assembly.joints.iter().find(|j| j.id == id)?;
|
||||
let vals = joints::joint_values(&s.doc.assembly);
|
||||
Some(named_value_list(j, vals.get(&id).map(Vec::as_slice).unwrap_or(&j.values)))
|
||||
Some(named_values(j, vals.get(&id).map(Vec::as_slice).unwrap_or(&j.values)))
|
||||
}
|
||||
|
||||
fn occurrence_name(s: &Session, id: u64) -> String {
|
||||
@@ -376,7 +293,7 @@ pub(crate) fn cannot_move(s: &Session, sol: &joints::Solution, id: u64) -> Optio
|
||||
|
||||
/// Joint chains joined to nothing grounded, which the solver places none of: each chain's
|
||||
/// occurrences and joints, by name.
|
||||
fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<FloatingChain> {
|
||||
fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<Value> {
|
||||
let placed = |o: u64| o == 0 || sol.world.contains_key(&o);
|
||||
let errors: BTreeSet<u64> = sol.errors.iter().map(|e| e.0).collect();
|
||||
let mut next: BTreeMap<u64, Vec<(u64, &Joint)>> = BTreeMap::new();
|
||||
@@ -402,10 +319,8 @@ fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<FloatingChain> {
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(FloatingChain {
|
||||
occurrences: occs.iter().map(|o| occurrence_name(s, *o)).collect(),
|
||||
joints: js.iter().map(|(_, n)| (*n).to_string()).collect(),
|
||||
});
|
||||
out.push(json!({"occurrences": occs.iter().map(|o| occurrence_name(s, *o)).collect::<Vec<_>>(),
|
||||
"joints": js.iter().map(|(_, n)| *n).collect::<Vec<_>>()}));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -839,27 +754,21 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {
|
||||
let mut q = j.values.clone();
|
||||
q.resize(j.kind.dofs().len(), 0.0);
|
||||
joints::clamp(&j, &mut q);
|
||||
let round = |v: f64| (v * 1e6).round() / 1e6;
|
||||
// As the reply shows them: a value that is not a number reads as null, and null is null.
|
||||
let same = |a: f64, b: f64| a == b || (a.is_nan() && b.is_nan());
|
||||
let warnings: Vec<String> = named_value_list(&j, &q)
|
||||
let round = |v: &Value| v.as_f64().map(|x| (x * 1e6).round() / 1e6).unwrap_or(f64::NAN);
|
||||
let warnings: Vec<String> = named_values(&j, &q)
|
||||
.iter()
|
||||
.zip(named_value_list(&j, &j.values))
|
||||
.filter(|(now, was)| !same(now.value, was.value))
|
||||
.zip(named_values(&j, &j.values))
|
||||
.filter(|(now, was)| now["value"] != was["value"])
|
||||
.map(|(now, was)| {
|
||||
let unit = match now.unit {
|
||||
ValueUnit::Deg => "deg",
|
||||
ValueUnit::Mm => "mm",
|
||||
};
|
||||
let [lo, hi] = now.limits.unwrap_or([f64::NAN; 2]);
|
||||
let unit = now["unit"].as_str().unwrap_or("");
|
||||
format!(
|
||||
"{} {} starts at {} {unit}, inside its limits [{}, {}], not at {} {unit}: the part moved there as it was joined",
|
||||
j.name,
|
||||
now.name,
|
||||
round(now.value),
|
||||
round(lo),
|
||||
round(hi),
|
||||
round(was.value)
|
||||
now["name"].as_str().unwrap_or(""),
|
||||
round(&now["value"]),
|
||||
round(&now["limits"][0]),
|
||||
round(&now["limits"][1]),
|
||||
round(&was["value"])
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -873,7 +782,13 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {
|
||||
if sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) {
|
||||
sol = resolve(s);
|
||||
}
|
||||
reply("joint.create", JointAddedResult { solved: solve_report(&sol, p), joint: id, name, warnings, param_warnings: Vec::new() })
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["joint"] = json!(id);
|
||||
out["name"] = json!(name);
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sets of angle values a new loop-closing joint tries a half turn round, at most.
|
||||
@@ -1172,48 +1087,41 @@ fn drive(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(index) = index { super::motion::drive_joint_index(s, id, q, index)? } else { super::motion::drive_joint(s, id, q, given)? }
|
||||
};
|
||||
let sol = solution(s, &BTreeMap::new(), response_analysis(p));
|
||||
// How motion stopped, as `motion::drive_with_contact` says: an object, or null.
|
||||
let stop = |key: &str| r.get(key).filter(|v| v.is_object()).cloned();
|
||||
let stopped_by_contact =
|
||||
stop("stopped_by_contact").map(serde_json::from_value::<ContactStop>).transpose().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let stopped_by_loop = stop("stopped_by_loop").map(serde_json::from_value::<LoopStop>).transpose().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let mut out = DriveJointResult {
|
||||
solved: solve_report(&sol, p),
|
||||
joint: id,
|
||||
values: effective_value_list(s, id),
|
||||
continuous: (bool_(p, "continuous") == Some(true)).then_some(true),
|
||||
stopped_by_contact,
|
||||
stopped_by_loop,
|
||||
moved: super::motion::moved(&before, &super::motion::positions(s)).next().is_some(),
|
||||
requested: None,
|
||||
held: None,
|
||||
reason: None,
|
||||
unconnected: None,
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["joint"] = json!(id);
|
||||
out["values"] = json!(effective_values(s, id));
|
||||
if bool_(p, "continuous") == Some(true) {
|
||||
out["continuous"] = json!(true);
|
||||
}
|
||||
out["stopped_by_contact"] = r["stopped_by_contact"].clone();
|
||||
out["stopped_by_loop"] = r["stopped_by_loop"].clone();
|
||||
let moved = super::motion::moved(&before, &super::motion::positions(s)).next().is_some();
|
||||
out["moved"] = json!(moved);
|
||||
if let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == id) {
|
||||
out.requested = Some(named_value_list(j, &requested));
|
||||
out["requested"] = json!(named_values(j, &requested));
|
||||
let held = if hold { Vec::new() } else { held_values(s, j, &requested, &driven, &r) };
|
||||
if let Some(first) = held.first()
|
||||
&& !out.moved
|
||||
&& !moved
|
||||
{
|
||||
out.reason = Some(first.why.clone());
|
||||
out["reason"] = first["why"].clone();
|
||||
}
|
||||
if !held.is_empty() {
|
||||
out.held = Some(held);
|
||||
out["held"] = json!(held);
|
||||
}
|
||||
}
|
||||
if let Some((why, unconnected)) = cannot_move(s, &sol, id) {
|
||||
out.reason = Some(why);
|
||||
out.unconnected = unconnected;
|
||||
out["reason"] = json!(why);
|
||||
if let Some(o) = unconnected {
|
||||
out["unconnected"] = json!(o);
|
||||
}
|
||||
}
|
||||
reply(cmd, out)
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The driven values of `j` that ended up other than `requested`, each with why: a motion link
|
||||
/// sets it from another coordinate (a screw's travel follows its turn), a limit holds it, or
|
||||
/// contact or a closed loop stopped the motion short. Degrees and mm, as `values` (#9742).
|
||||
fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &Value) -> Vec<HeldValue> {
|
||||
fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &Value) -> Vec<Value> {
|
||||
let now = joints::joint_values(&s.doc.assembly).remove(&j.id).unwrap_or_else(|| j.values.clone());
|
||||
let names = j.kind.dofs();
|
||||
let mut out = Vec::new();
|
||||
@@ -1251,13 +1159,7 @@ fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
out.push(HeldValue {
|
||||
name: name.to_string(),
|
||||
requested: shown(want),
|
||||
value: shown(got),
|
||||
unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },
|
||||
why,
|
||||
});
|
||||
out.push(json!({"name": name, "requested": shown(want), "value": shown(got), "unit": if angle { "deg" } else { "mm" }, "why": why}));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1520,19 +1422,14 @@ fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// A cam's follower travel over a turn of the cam: b's lowest and highest values and their
|
||||
/// difference, in degrees (`angle`) or mm.
|
||||
fn lift_json(l: &MotionLink, angle: bool) -> Value {
|
||||
serde_json::to_value(lift_info(l, angle)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`lift_json`], typed: `None` for a table that is not whole.
|
||||
fn lift_info(l: &MotionLink, angle: bool) -> Option<CamLift> {
|
||||
// A table that is not whole (a hand-edited file) moves nothing, and says so.
|
||||
if l.lift.len() != cam::CAM_SAMPLES {
|
||||
return None;
|
||||
return Value::Null;
|
||||
}
|
||||
let unit = |v: f64| if angle { v.to_degrees() } else { v };
|
||||
let (lo, hi) = l.lift.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
let (lo, hi) = (unit(lo + l.offset), unit(hi + l.offset));
|
||||
Some(CamLift { min: lo, max: hi, rise: hi - lo, unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm } })
|
||||
json!({"min": lo, "max": hi, "rise": hi - lo, "unit": if angle { "deg" } else { "mm" }})
|
||||
}
|
||||
|
||||
/// A cam's profile: a sketch's closed profile (kept by its outer loop's curve ids, so the sketch's
|
||||
@@ -1688,7 +1585,7 @@ fn limits(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
joints::clamp(j, &mut q);
|
||||
j.values = q;
|
||||
let sol = resolve(s);
|
||||
reply(cmd, SolveResult { solved: solve_report(&sol, p), param_warnings: Vec::new() })
|
||||
Ok(sol_json(&sol, p))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1814,10 +1711,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if doc.assembly.origins.len() == before {
|
||||
return Err(bad(cmd, format!("no joint origin `{name}`")));
|
||||
}
|
||||
return reply(
|
||||
cmd,
|
||||
DeleteJointResult { deleted: JointDeleted::Origin { deleted_origin: name.to_string(), joints: used }, param_warnings: Vec::new() },
|
||||
);
|
||||
return Ok(json!({"deleted_origin": name, "joints": used}));
|
||||
}
|
||||
if let Some(i) = num(p, "link") {
|
||||
let i = i.max(0.0) as usize;
|
||||
@@ -1826,83 +1720,72 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "no such motion link"));
|
||||
}
|
||||
doc.assembly.links.remove(i);
|
||||
return reply(cmd, DeleteJointResult { deleted: JointDeleted::Link { deleted_link: i }, param_warnings: Vec::new() });
|
||||
return Ok(json!({"deleted_link": i}));
|
||||
}
|
||||
let id = joint_id(s, p.get("joint"), cmd)?;
|
||||
delete_joints(s.doc_mut(), &[id]);
|
||||
let sol = resolve(s);
|
||||
reply(cmd, DeleteJointResult { deleted: JointDeleted::Joint { solved: solve_report(&sol, p), deleted: id }, param_warnings: Vec::new() })
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["deleted"] = json!(id);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.model.state();
|
||||
let sol = joints::solve(&s.doc, &st);
|
||||
let vals = joints::joint_values(&s.doc.assembly);
|
||||
let js: Vec<ListedJoint> = s
|
||||
let js: Vec<Value> = s
|
||||
.doc
|
||||
.assembly
|
||||
.joints
|
||||
.iter()
|
||||
.map(|j| {
|
||||
let world = |o: &JointOrigin| {
|
||||
s.doc.origin_world(&st, o).ok().map(|m| JointFrame { origin: [m[3][0], m[3][1], m[3][2]], z: [m[2][0], m[2][1], m[2][2]] })
|
||||
};
|
||||
ListedJoint {
|
||||
id: j.id,
|
||||
name: j.name.clone(),
|
||||
kind: j.kind,
|
||||
a: j.a.occurrence,
|
||||
b: j.b.occurrence,
|
||||
values: named_value_list(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default()),
|
||||
flip: j.flip,
|
||||
offset: j.offset,
|
||||
suppressed: j.suppressed,
|
||||
visible: s.joint_visible(j.id),
|
||||
frame_a: world(&j.a),
|
||||
frame_b: world(&j.b),
|
||||
expressions: (!j.exprs.is_empty()).then(|| j.exprs.clone()),
|
||||
let named = named_values(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default());
|
||||
let world = |o: &JointOrigin| s.doc.origin_world(&st, o).ok().map(|m| json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]]}));
|
||||
let mut out = json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named,
|
||||
"flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)});
|
||||
if !j.exprs.is_empty() {
|
||||
out["expressions"] = json!(j.exprs);
|
||||
}
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
let out = ListJointsResult {
|
||||
solved: solve_report(&sol, p),
|
||||
joints: js,
|
||||
links: s.doc.assembly.links.iter().map(|l| link_info(s, &st, l)).collect(),
|
||||
origins: s.doc.assembly.origins.iter().map(|o| ListedOrigin { name: o.name.clone(), occurrence: o.origin.occurrence }).collect(),
|
||||
floating: floating_chains(s, &sol),
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
reply("joint.list", out)
|
||||
let links: Vec<Value> = s.doc.assembly.links.iter().map(|l| link_json(s, &st, l)).collect();
|
||||
let origins: Vec<Value> = s.doc.assembly.origins.iter().map(|o| json!({"name": o.name, "occurrence": o.origin.occurrence})).collect();
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["joints"] = json!(js);
|
||||
out["links"] = json!(links);
|
||||
out["origins"] = json!(origins);
|
||||
out["floating"] = json!(floating_chains(s, &sol));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A motion link as `joint.list` and `joint.inspect` give it: ratio per degree, offset in b's
|
||||
/// units, a coupling's definition (and why it can't be worked out), a cam's lift in place of a ratio.
|
||||
fn link_info(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> LinkInfo {
|
||||
fn link_json(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> Value {
|
||||
let angle = is_angle(s, l.b, l.ib);
|
||||
let offset = if angle { l.offset.to_degrees() } else { l.offset };
|
||||
let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);
|
||||
// A cam's follower follows its table, not a ratio: its travel instead.
|
||||
let cam = matches!(l.coupling, Some(Coupling::Cam(_)));
|
||||
LinkInfo {
|
||||
a: l.a,
|
||||
ia: l.ia,
|
||||
b: l.b,
|
||||
ib: l.ib,
|
||||
ratio: (!cam).then_some(ratio),
|
||||
offset,
|
||||
unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },
|
||||
coupling: l.coupling.clone(),
|
||||
error: match &l.coupling {
|
||||
Some(_) => joints::coupling_values(&s.doc, st, l).and_then(|r| r.err()).map(|e| e.to_string()),
|
||||
None => None,
|
||||
},
|
||||
lift: cam.then(|| lift_info(l, angle)),
|
||||
let mut v = json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});
|
||||
if let Some(c) = &l.coupling {
|
||||
v["coupling"] = json!(c);
|
||||
if let Some(Err(e)) = joints::coupling_values(&s.doc, st, l) {
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
}
|
||||
// A cam's follower follows its table, not a ratio: its travel instead.
|
||||
if matches!(l.coupling, Some(Coupling::Cam(_)))
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.remove("ratio");
|
||||
o.insert("lift".into(), lift_json(l, angle));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sol = resolve(s);
|
||||
reply("joint.solve", SolveResult { solved: solve_report(&sol, p), param_warnings: Vec::new() })
|
||||
Ok(sol_json(&sol, p))
|
||||
}
|
||||
|
||||
/// Index pairs `(i, j)`, `i < j`, whose boxes overlap or touch (sort and sweep along X), at most
|
||||
|
||||
@@ -3,17 +3,13 @@
|
||||
//! persistent name refers to), whether each origin is found today and why not, its kind, offset,
|
||||
//! angle, flip, limits, values, expressions and the motion links it takes part in. Reads only.
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef};
|
||||
use solidcraft_doc::naming::legacy_name;
|
||||
use solidcraft_doc::persistent_name::{Base, EdgeName, FaceName, Role};
|
||||
use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState};
|
||||
|
||||
use super::{component_of, joint_id, link_info, named_value_list, occurrence_name, reply};
|
||||
use crate::schema::joints::{
|
||||
EdgeReference, FaceReference, InspectJointResult, InspectedJoint, JointLink, JointSide, LinkRole, MadeBy, Reference, ReferenceRole, Referent,
|
||||
SweptFrom, WorldFrame,
|
||||
};
|
||||
use super::{component_of, joint_id, link_json, named_values, occurrence_name};
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -25,7 +21,7 @@ pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.model.state();
|
||||
let sol = joints::solve(&s.doc, &st);
|
||||
let vals = joints::joint_values(&s.doc.assembly);
|
||||
let out: Vec<InspectedJoint> = ids
|
||||
let out: Vec<Value> = ids
|
||||
.iter()
|
||||
.filter_map(|id| s.doc.assembly.joints.iter().find(|j| j.id == *id))
|
||||
.map(|j| {
|
||||
@@ -33,42 +29,50 @@ pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
joint_json(s, &st, &sol, j, q)
|
||||
})
|
||||
.collect();
|
||||
reply(cmd, InspectJointResult { joints: out, param_warnings: Vec::new() })
|
||||
Ok(json!({ "joints": out }))
|
||||
}
|
||||
|
||||
fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> InspectedJoint {
|
||||
let links: Vec<JointLink> = s
|
||||
fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> Value {
|
||||
let links: Vec<Value> = s
|
||||
.doc
|
||||
.assembly
|
||||
.links
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, l)| l.a == j.id || l.b == j.id)
|
||||
.map(|(i, l)| JointLink { index: i, role: if l.b == j.id { LinkRole::Driven } else { LinkRole::Driver }, link: link_info(s, st, l) })
|
||||
.map(|(i, l)| {
|
||||
let mut v = link_json(s, st, l);
|
||||
v["index"] = json!(i);
|
||||
v["role"] = json!(if l.b == j.id { "driven" } else { "driver" });
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let why = |list: &[(u64, String, String)]| list.iter().filter(|(id, ..)| *id == j.id).map(|(.., why)| why.clone()).collect::<Vec<_>>();
|
||||
InspectedJoint {
|
||||
id: j.id,
|
||||
name: j.name.clone(),
|
||||
kind: j.kind,
|
||||
suppressed: j.suppressed,
|
||||
visible: s.joint_visible(j.id),
|
||||
flip: j.flip,
|
||||
offset: j.offset,
|
||||
angle: j.angle.to_degrees(),
|
||||
values: named_value_list(j, q),
|
||||
dofs: j.kind.dofs().iter().map(|d| (*d).to_string()).collect(),
|
||||
a: side_json(s, st, &j.a),
|
||||
b: side_json(s, st, &j.b),
|
||||
links,
|
||||
errors: why(&sol.errors),
|
||||
conflicts: why(&sol.conflicts),
|
||||
expressions: (!j.exprs.is_empty()).then(|| j.exprs.clone()),
|
||||
let mut v = json!({
|
||||
"id": j.id,
|
||||
"name": j.name,
|
||||
"type": j.kind,
|
||||
"suppressed": j.suppressed,
|
||||
"visible": s.joint_visible(j.id),
|
||||
"flip": j.flip,
|
||||
"offset": j.offset,
|
||||
"angle": j.angle.to_degrees(),
|
||||
"values": named_values(j, q),
|
||||
"dofs": j.kind.dofs(),
|
||||
"a": side_json(s, st, &j.a),
|
||||
"b": side_json(s, st, &j.b),
|
||||
"links": links,
|
||||
"errors": why(&sol.errors),
|
||||
"conflicts": why(&sol.conflicts),
|
||||
});
|
||||
if !j.exprs.is_empty() {
|
||||
v["expressions"] = json!(j.exprs);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One of a joint's origins: what it sits on, what it refers to, and where it is now.
|
||||
fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> JointSide {
|
||||
fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value {
|
||||
let component = component_of(s, o.occurrence);
|
||||
let component_name = if component == 0 {
|
||||
"root".to_string()
|
||||
@@ -76,24 +80,24 @@ fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> JointSide {
|
||||
s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default()
|
||||
};
|
||||
let occurrence_name = if o.occurrence == 0 { "root".to_string() } else { occurrence_name(s, o.occurrence) };
|
||||
let mut v = JointSide {
|
||||
occurrence: o.occurrence,
|
||||
occurrence_name,
|
||||
component,
|
||||
component_name,
|
||||
path: occurrence_path(&s.doc, o.occurrence),
|
||||
snap: o.snap.clone(),
|
||||
references: references(&s.doc, &o.snap),
|
||||
resolves: false,
|
||||
frame: None,
|
||||
error: None,
|
||||
};
|
||||
let mut v = json!({
|
||||
"occurrence": o.occurrence,
|
||||
"occurrence_name": occurrence_name,
|
||||
"component": component,
|
||||
"component_name": component_name,
|
||||
"path": occurrence_path(&s.doc, o.occurrence),
|
||||
"snap": o.snap,
|
||||
"references": references(&s.doc, &o.snap),
|
||||
});
|
||||
match s.doc.origin_world(st, o) {
|
||||
Ok(m) => {
|
||||
v.resolves = true;
|
||||
v.frame = Some(WorldFrame { origin: [m[3][0], m[3][1], m[3][2]], z: [m[2][0], m[2][1], m[2][2]], x: [m[0][0], m[0][1], m[0][2]] });
|
||||
v["resolves"] = json!(true);
|
||||
v["frame"] = json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]], "x": [m[0][0], m[0][1], m[0][2]]});
|
||||
}
|
||||
Err(e) => {
|
||||
v["resolves"] = json!(false);
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
Err(e) => v.error = Some(e.to_string()),
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -114,36 +118,36 @@ fn occurrence_path(doc: &Document, occurrence: u64) -> String {
|
||||
}
|
||||
|
||||
/// Every persistent name the snap holds, with what it refers to.
|
||||
fn references(doc: &Document, snap: &Snap) -> Vec<Reference> {
|
||||
fn references(doc: &Document, snap: &Snap) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
let mut face = |role: ReferenceRole, name: &Option<String>| {
|
||||
let mut face = |role: &str, name: &Option<String>| {
|
||||
if let Some(n) = name {
|
||||
out.push(Reference { role, to: Referent::Face(face_ref(doc, n)) });
|
||||
out.push(with_role(role, face_ref(doc, n)));
|
||||
}
|
||||
};
|
||||
match snap {
|
||||
Snap::FaceCenter { face: f, x, .. } => {
|
||||
face(ReferenceRole::Face, f);
|
||||
face("face", f);
|
||||
if let Some(XRef::Face { face: n, .. }) = x {
|
||||
face(ReferenceRole::X, &Some(n.clone()));
|
||||
face("x", &Some(n.clone()));
|
||||
}
|
||||
}
|
||||
Snap::CircleCenter { face: f, end, x, .. } => {
|
||||
face(ReferenceRole::Face, f);
|
||||
face(ReferenceRole::End, end);
|
||||
face("face", f);
|
||||
face("end", end);
|
||||
if let Some(XRef::Face { face: n, .. }) = x {
|
||||
face(ReferenceRole::X, &Some(n.clone()));
|
||||
face("x", &Some(n.clone()));
|
||||
}
|
||||
}
|
||||
Snap::Edge { edge, face: f, corner, .. } => {
|
||||
if let Some(e) = edge {
|
||||
out.push(Reference { role: ReferenceRole::Edge, to: Referent::Edge(edge_ref(doc, e)) });
|
||||
out.push(with_role("edge", edge_ref(doc, e)));
|
||||
}
|
||||
if let Some(n) = f {
|
||||
out.push(Reference { role: ReferenceRole::Face, to: Referent::Face(face_ref(doc, n)) });
|
||||
out.push(with_role("face", face_ref(doc, n)));
|
||||
}
|
||||
if let Some(e) = corner {
|
||||
out.push(Reference { role: ReferenceRole::Corner, to: Referent::Edge(edge_ref(doc, e)) });
|
||||
out.push(with_role("corner", edge_ref(doc, e)));
|
||||
}
|
||||
}
|
||||
Snap::Frame { .. } | Snap::Point { .. } => {}
|
||||
@@ -151,14 +155,19 @@ fn references(doc: &Document, snap: &Snap) -> Vec<Reference> {
|
||||
out
|
||||
}
|
||||
|
||||
fn with_role(role: &str, mut v: Value) -> Value {
|
||||
v["role"] = json!(role);
|
||||
v
|
||||
}
|
||||
|
||||
/// What a face's persistent name refers to: `F<feature>:<role>` names the feature that made the
|
||||
/// face, and a side `side:<curve>` (or a later profile's `side:s<k>.<curve>`) the sketch curve
|
||||
/// it was swept from. Names of another form are given as they are.
|
||||
fn face_ref(doc: &Document, name: &str) -> FaceReference {
|
||||
let mut v = FaceReference { name: name.to_string(), unverified: None, role_in_feature: None, feature: None, sketch: None };
|
||||
fn face_ref(doc: &Document, name: &str) -> Value {
|
||||
let mut v = json!({ "name": name });
|
||||
let bare = match legacy_name(name) {
|
||||
Some(n) => {
|
||||
v.unverified = Some(true);
|
||||
v["unverified"] = json!(true);
|
||||
n
|
||||
}
|
||||
None => name,
|
||||
@@ -166,36 +175,38 @@ fn face_ref(doc: &Document, name: &str) -> FaceReference {
|
||||
let Ok(face) = FaceName::parse(bare) else { return v };
|
||||
let Some(fid) = face.made_by().map(|id| id.0) else { return v };
|
||||
let stem = face.stem().to_string();
|
||||
v.role_in_feature = Some(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem).to_string());
|
||||
v["role_in_feature"] = json!(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem));
|
||||
let Some(f) = doc.feature(fid) else {
|
||||
v.feature = Some(MadeBy::Gone { id: fid, error: format!("feature {fid} is gone") });
|
||||
v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")});
|
||||
return v;
|
||||
};
|
||||
v.feature = Some(MadeBy::Feature { id: f.id, name: f.name.clone(), kind: f.kind.type_name().to_string() });
|
||||
v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()});
|
||||
// A side swept from a sketch curve (a later profile's too, `side:s<k>.<curve>`).
|
||||
if let Base::Made { role: Role::Side { curve, .. }, .. } = &face.base {
|
||||
let found = f.kind.input_sketches().into_iter().find_map(|id| {
|
||||
// design-only: a joint names a curve of one of the design's sketches.
|
||||
let sk = doc.sketch(id).ok()?;
|
||||
let c = sk.curves.iter().find(|c| c.id == *curve)?;
|
||||
let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").and_then(Value::as_str).map(str::to_string));
|
||||
let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null);
|
||||
let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
Some(SweptFrom::Curve { id, name, curve: curve.clone(), curve_type })
|
||||
Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type}))
|
||||
});
|
||||
v.sketch = Some(
|
||||
found.unwrap_or_else(|| SweptFrom::Missing { curve: curve.clone(), error: format!("no sketch of {} has a curve `{curve}`", f.name) }),
|
||||
);
|
||||
v["sketch"] = found.unwrap_or_else(|| json!({"curve": curve, "error": format!("no sketch of {} has a curve `{curve}`", f.name)}));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// An edge's persistent name (`<face A>|<face B>`, `~k` for one of several between them) with
|
||||
/// what each of its faces refers to.
|
||||
fn edge_ref(doc: &Document, name: &str) -> EdgeReference {
|
||||
fn edge_ref(doc: &Document, name: &str) -> Value {
|
||||
let bare = legacy_name(name).unwrap_or(name);
|
||||
let faces: Vec<FaceReference> = match EdgeName::parse(bare) {
|
||||
let faces: Vec<Value> = match EdgeName::parse(bare) {
|
||||
Ok(e) => e.faces.iter().map(|f| face_ref(doc, &f.to_string())).collect(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
EdgeReference { name: name.to_string(), faces, unverified: legacy_name(name).is_some().then_some(true) }
|
||||
let mut v = json!({"name": name, "faces": faces});
|
||||
if legacy_name(name).is_some() {
|
||||
v["unverified"] = json!(true);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -85,10 +85,8 @@ mod point_cloud;
|
||||
mod script;
|
||||
mod section;
|
||||
pub mod settings;
|
||||
pub(crate) use clipboard::{component_path_form, copy_keys};
|
||||
pub(crate) use measure_sel::{measure_items, shape_of};
|
||||
pub(crate) use measure_shape::Shape;
|
||||
pub(crate) use script::step_params;
|
||||
#[cfg(test)]
|
||||
mod kernel_heal_tests;
|
||||
mod panels;
|
||||
@@ -112,7 +110,7 @@ mod sketch;
|
||||
pub(crate) use sketch::author_path_for_rebind;
|
||||
pub(crate) use sketch::collapse_reason;
|
||||
pub(crate) use sketch::created as sketch_created;
|
||||
pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form, point_arg_form};
|
||||
pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form};
|
||||
mod canvas_sketch;
|
||||
mod sketch_3d;
|
||||
mod sketch_canvas;
|
||||
|
||||
@@ -16,10 +16,8 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, plac
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::schema::motion::{
|
||||
ContactCheck, ContactCollision, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetChange,
|
||||
ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, ExplodeCreateParams, ExplodeCreated, ExplodeDeleteParams,
|
||||
ExplodeDeleted, ExplodeListParams, ExplodeMoveInfo, ExplodeShowParams, ExplodeShown, ExplodeViews, ExplodedViewInfo, FindLimitsParams,
|
||||
FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo,
|
||||
MotionStudyParams, MotionStudySaved,
|
||||
ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams,
|
||||
MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, MotionStudyParams, MotionStudySaved,
|
||||
};
|
||||
use crate::schema::motion_play::{
|
||||
DriveReport, ExportParams, PartPose, PlayParams, Pose, StudyExport, StudyExported, StudyPlayed, StudySample, UnmovedJoint,
|
||||
@@ -55,10 +53,6 @@ const CONTACT_EDIT_CONTRACT: TypedContract<ContactEditParams> = TypedContract::n
|
||||
const STUDY_CONTRACT: TypedContract<MotionStudyParams> = TypedContract::new();
|
||||
const STUDY_DELETE_CONTRACT: TypedContract<MotionStudyDeleteParams> = TypedContract::new();
|
||||
const STUDY_LIST_CONTRACT: TypedContract<MotionListParams> = TypedContract::new();
|
||||
const EXPLODE_CREATE_CONTRACT: TypedContract<ExplodeCreateParams> = TypedContract::new();
|
||||
const EXPLODE_SHOW_CONTRACT: TypedContract<ExplodeShowParams> = TypedContract::new();
|
||||
const EXPLODE_LIST_CONTRACT: TypedContract<ExplodeListParams> = TypedContract::new();
|
||||
const EXPLODE_DELETE_CONTRACT: TypedContract<ExplodeDeleteParams> = TypedContract::new();
|
||||
const PLAY_CONTRACT: TypedContract<PlayParams> = TypedContract::new();
|
||||
const EXPORT_CONTRACT: TypedContract<ExportParams> = TypedContract::new();
|
||||
|
||||
@@ -181,32 +175,16 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&STUDY_DELETE_CONTRACT)
|
||||
.output(output_schema_for::<MotionStudyDeleted>)
|
||||
.params("study"),
|
||||
CommandSpec::new("explode.create", "Exploded View", crate::checked!("explode.create", explode_create))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("explode")
|
||||
.enabled(has_parts_to_explode)
|
||||
.contract(&EXPLODE_CREATE_CONTRACT)
|
||||
.output(output_schema_for::<ExplodeCreated>)
|
||||
.params(
|
||||
"name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \
|
||||
moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",
|
||||
),
|
||||
CommandSpec::new("explode.show", "Show Exploded View", crate::checked!("explode.show", explode_show))
|
||||
CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params(
|
||||
"name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \
|
||||
moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",
|
||||
),
|
||||
CommandSpec::new("explode.show", "Show Exploded View", explode_show)
|
||||
.icon("explode")
|
||||
.noundo()
|
||||
.contract(&EXPLODE_SHOW_CONTRACT)
|
||||
.output(output_schema_for::<ExplodeShown>)
|
||||
.params("view: id|name (or none: back to the assembled placement) — shown only; the design keeps its placements"),
|
||||
CommandSpec::new("explode.list", "List Exploded Views", crate::checked!("explode.list", explode_list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&EXPLODE_LIST_CONTRACT)
|
||||
.output(output_schema_for::<ExplodeViews>),
|
||||
CommandSpec::new("explode.delete", "Delete Exploded View", crate::checked!("explode.delete", explode_delete))
|
||||
.icon("delete")
|
||||
.contract(&EXPLODE_DELETE_CONTRACT)
|
||||
.output(output_schema_for::<ExplodeDeleted>)
|
||||
.params("view"),
|
||||
CommandSpec::new("explode.list", "List Exploded Views", explode_list).icon("list").noundo(),
|
||||
CommandSpec::new("explode.delete", "Delete Exploded View", explode_delete).icon("delete").params("view"),
|
||||
];
|
||||
|
||||
const MAX_ITEMS: usize = 10_000;
|
||||
@@ -1255,8 +1233,7 @@ fn explode_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name =
|
||||
str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Exploded View", s.doc.assembly.exploded.iter().map(|v| v.name.as_str())));
|
||||
s.doc_mut().assembly.exploded.push(ExplodedView { id, name: name.clone(), moves: moves.clone() });
|
||||
let moves = moves.iter().map(ExplodeMoveInfo::from).collect();
|
||||
typed_reply(cmd, ExplodeCreated { view: id, name, moves, param_warnings: Vec::new() })
|
||||
Ok(json!({"view": id, "name": name, "moves": moves.iter().map(|(o, t)| json!({"occurrence": o, "translate": t})).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1265,7 +1242,7 @@ fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.pending_moves.clear();
|
||||
s.exploded.clear();
|
||||
s.revision += 1;
|
||||
return typed_reply(cmd, ExplodeShown { view: None, name: None, param_warnings: Vec::new() });
|
||||
return Ok(json!({"view": null}));
|
||||
}
|
||||
let i = view_index(s, p, cmd)?;
|
||||
let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?;
|
||||
@@ -1277,7 +1254,7 @@ fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.exploded.clone_from(&moves);
|
||||
s.pending_moves = moves;
|
||||
s.revision += 1;
|
||||
typed_reply(cmd, ExplodeShown { view: Some(v.id), name: Some(v.name), param_warnings: Vec::new() })
|
||||
Ok(json!({"view": v.id, "name": v.name}))
|
||||
}
|
||||
|
||||
/// Whether the pending moves are an exploded view shown (`explode.show`), which places the
|
||||
@@ -1310,14 +1287,13 @@ fn exploded_at(moves: &[(u64, Mat, Vec3)], amount: f64) -> std::collections::BTr
|
||||
}
|
||||
|
||||
fn explode_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let views = s.doc.assembly.exploded.iter().map(ExplodedViewInfo::from).collect();
|
||||
typed_reply("explode.list", ExplodeViews { views, param_warnings: Vec::new() })
|
||||
Ok(json!({"views": s.doc.assembly.exploded}))
|
||||
}
|
||||
|
||||
fn explode_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = view_index(s, p, "explode.delete")?;
|
||||
let v = s.doc_mut().assembly.exploded.remove(i);
|
||||
typed_reply("explode.delete", ExplodeDeleted { deleted: v.name, param_warnings: Vec::new() })
|
||||
Ok(json!({"deleted": v.name}))
|
||||
}
|
||||
|
||||
/// World position of a point of an occurrence (tests).
|
||||
|
||||
@@ -11,30 +11,15 @@ use solidcraft_doc::{Document, Feature, FeatureKind, Param, expr};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, str_};
|
||||
use crate::schema::timeline_clipboard::{AddParams, AddResult, ExportScriptParams, ExportScriptResult, Script, ScriptAbout, ScriptStep};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const ADD_CONTRACT: TypedContract<AddParams> = TypedContract::new();
|
||||
const EXPORT_SCRIPT_CONTRACT: TypedContract<ExportScriptParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("timeline.add", "Add Recorded Feature", crate::checked!("timeline.add", add))
|
||||
.icon("new")
|
||||
.contract(&ADD_CONTRACT)
|
||||
.output(output_schema_for::<AddResult>)
|
||||
.params(
|
||||
CommandSpec::new("timeline.add", "Add Recorded Feature", add).icon("new").params(
|
||||
"feature: a feature as the design file and timeline.inspect hold it ({type, name?, id?, …}; the name is kept even when another \
|
||||
feature has it, the id is kept and refused when another feature has it, so later steps can refer to them); params?: [{name, expression, unit?, comment?}] (the model parameters its sketch \
|
||||
dimensions use); the feature goes at the marker → feature, name, error, warning",
|
||||
),
|
||||
CommandSpec::new("timeline.export_script", "Export Command Script", crate::checked!("timeline.export_script", export_script))
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&EXPORT_SCRIPT_CONTRACT)
|
||||
.output(output_schema_for::<ExportScriptResult>)
|
||||
.params(
|
||||
CommandSpec::new("timeline.export_script", "Export Command Script", export_script).icon("export").noundo().doc_only().params(
|
||||
"path?: write the script to this file → script: {commands: [...]} that rebuilds the design (solidcraft-cli eval/run), \
|
||||
steps, omitted: what the script leaves out (appearances, folders, views, configurations, print-face assignments); components and assemblies \
|
||||
are not supported yet",
|
||||
@@ -71,14 +56,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.refresh();
|
||||
let name = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
let r = s.model.result(id);
|
||||
let reply = AddResult {
|
||||
feature: id,
|
||||
name,
|
||||
error: r.and_then(|r| r.error.clone()),
|
||||
warning: r.and_then(|r| r.warning.clone()),
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
Ok(json!({"feature": id, "name": name, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone())}))
|
||||
}
|
||||
|
||||
/// timeline.add keeps accepting legacy name-keyed pattern and mirror seeds and construction
|
||||
@@ -161,8 +139,7 @@ fn recorded_feature(cmd: &str, raw: &Map<String, Value>) -> Result<Feature> {
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// The model parameters of a `timeline.add` step. The reader the command's contract uses too.
|
||||
pub(crate) fn step_params(cmd: &str, v: Option<&Value>) -> Result<Vec<Param>> {
|
||||
fn step_params(cmd: &str, v: Option<&Value>) -> Result<Vec<Param>> {
|
||||
let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
|
||||
let list = v.as_array().filter(|a| a.len() <= MAX_STEP_PARAMS).ok_or_else(|| bad(cmd, "`params` must be a list of parameters"))?;
|
||||
let text = |p: &Value, k: &str| match p.get(k) {
|
||||
@@ -187,15 +164,15 @@ fn export_script(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "timeline.export_script";
|
||||
let (commands, omitted) = script_steps(&s.doc)?;
|
||||
let steps = commands.len();
|
||||
let script = Script {
|
||||
about: ScriptAbout {
|
||||
design: s.doc.name.clone(),
|
||||
format: solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT),
|
||||
replay: "solidcraft-cli eval script.json (timeline.add steps need a build that reads this design format)".into(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
let script = json!({
|
||||
"about": {
|
||||
"design": s.doc.name,
|
||||
"format": solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT),
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"replay": "solidcraft-cli eval script.json (timeline.add steps need a build that reads this design format)",
|
||||
},
|
||||
commands,
|
||||
};
|
||||
"commands": commands,
|
||||
});
|
||||
let path = str_(p, "path");
|
||||
if let Some(path) = path {
|
||||
let text = serde_json::to_string_pretty(&script).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
@@ -203,12 +180,11 @@ fn export_script(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if p.get("path").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(cmd, "`path` must be a file path"));
|
||||
}
|
||||
let path = path.map(str::to_string);
|
||||
serde_json::to_value(ExportScriptResult { omitted, path, script, steps, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
|
||||
Ok(json!({"script": script, "steps": steps, "omitted": omitted, "path": path}))
|
||||
}
|
||||
|
||||
fn step(command: &str, params: Value) -> Value {
|
||||
serde_json::to_value(ScriptStep { command: command.to_string(), params }).unwrap_or_default()
|
||||
json!({"command": command, "params": params})
|
||||
}
|
||||
|
||||
fn not_supported(what: &str) -> EngineError {
|
||||
|
||||
@@ -13,10 +13,6 @@ use crate::schema::sketch::{
|
||||
EditResult, EqualMade, EqualParams, EqualResult, ExitParams, FinishResult, FixOutcome, FixParams, FixResult, HorizontalVerticalParams,
|
||||
MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentParams,
|
||||
};
|
||||
use crate::schema::sketch_shapes::{
|
||||
ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, Created, DrawResult, LineParams,
|
||||
PointParams, PointResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session, SketchEntry, Snapshot};
|
||||
|
||||
@@ -57,13 +53,6 @@ const MIDPOINT_CONTRACT: TypedContract<MidpointParams> = TypedContract::new();
|
||||
const CONCENTRIC_CONTRACT: TypedContract<ConcentricParams> = TypedContract::new();
|
||||
const COLLINEAR_CONTRACT: TypedContract<CollinearParams> = TypedContract::new();
|
||||
const SYMMETRY_CONTRACT: TypedContract<SymmetryParams> = TypedContract::new();
|
||||
const LINE_CONTRACT: TypedContract<LineParams> = TypedContract::new();
|
||||
const POINT_CONTRACT: TypedContract<PointParams> = TypedContract::new();
|
||||
const CIRCLE_CENTER_CONTRACT: TypedContract<CircleCenterParams> = TypedContract::new();
|
||||
const CIRCLE_TWO_POINT_CONTRACT: TypedContract<CircleTwoPointParams> = TypedContract::new();
|
||||
const CIRCLE_THREE_POINT_CONTRACT: TypedContract<CircleThreePointParams> = TypedContract::new();
|
||||
const ARC_THREE_POINT_CONTRACT: TypedContract<ArcThreePointParams> = TypedContract::new();
|
||||
const ARC_CENTER_POINT_CONTRACT: TypedContract<ArcCenterPointParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.create", "Create Sketch", create_sketch)
|
||||
@@ -84,13 +73,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.enabled(in_sketch)
|
||||
.contract(&EXIT_CONTRACT).output(output_schema_for::<CancelResult>)
|
||||
.params("Leaves the sketch without keeping what changed since it was created or opened for editing: the design goes back to how it was then (a new sketch is removed), as one step that Undo brings back. Refused when the undo history no longer leads back to that point (use Undo instead). restore_marker?: bool (default true); false transfers the temporary marker to another editor"),
|
||||
CommandSpec::new("sketch.line", "Line", crate::checked!("sketch.line", draw_line))
|
||||
CommandSpec::new("sketch.line", "Line", draw_line)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("line")
|
||||
.key("L")
|
||||
.enabled(in_sketch)
|
||||
.contract(&LINE_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension")
|
||||
.enabled(in_sketch)
|
||||
@@ -116,39 +103,31 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("rect_center")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("center, corner: [x,y] (a coordinate may be an expression over the design's parameters: the point follows them); construction?: bool. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.circle.center", "Center Diameter Circle", crate::checked!("sketch.circle.center", circle_center))
|
||||
CommandSpec::new("sketch.circle.center", "Center Diameter Circle", circle_center)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("circle")
|
||||
.key("C")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CIRCLE_CENTER_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!(
|
||||
"center: [x,y] or point ref (a coordinate may be an expression over the design's parameters: the centre follows them), radius | diameter: number or expression (an expression naming a parameter is a dimension driven by it; with `through` a point ref, that and the point both fix the radius); through?: point ref (a point the circle passes through, kept on it: where the tool's second click snapped); construction?: bool",
|
||||
connect_doc!(),
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.circle.two_point", "2-Point Circle", crate::checked!("sketch.circle.two_point", circle_two))
|
||||
CommandSpec::new("sketch.circle.two_point", "2-Point Circle", circle_two)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("circle2")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CIRCLE_TWO_POINT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("p0, p1: diameter ends; construction?: bool", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.circle.three_point", "3-Point Circle", crate::checked!("sketch.circle.three_point", circle_three))
|
||||
CommandSpec::new("sketch.circle.three_point", "3-Point Circle", circle_three)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("circle3")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CIRCLE_THREE_POINT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("p0, p1, p2: [x,y] or point ref (a referenced point stays on the circle); construction?: bool", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.arc.three_point", "3-Point Arc", crate::checked!("sketch.arc.three_point", arc_three)).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).contract(&ARC_THREE_POINT_CONTRACT).output(output_schema_for::<DrawResult>).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc); construction?: bool", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.arc.center_point", "Center Point Arc", crate::checked!("sketch.arc.center_point", arc_center))
|
||||
CommandSpec::new("sketch.arc.three_point", "3-Point Arc", arc_three).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc); construction?: bool", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.arc.center_point", "Center Point Arc", arc_center)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("arc_center")
|
||||
.enabled(in_sketch)
|
||||
.contract(&ARC_CENTER_POINT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("center, start, end (counter-clockwise from start; clockwise?: bool for clockwise) | center, start, sweep: signed degrees; construction?: bool", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.polygon.inscribed", "Inscribed Polygon", polygon_inscribed)
|
||||
.at("SKETCH", "CREATE")
|
||||
@@ -175,7 +154,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("slot_overall")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.point", "Point", crate::checked!("sketch.point", draw_point)).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).contract(&POINT_CONTRACT).output(output_schema_for::<PointResult>).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
|
||||
"entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|major|minor|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them (between the perpendiculars through them, or a tenth of their distance past) is the distance between them; pulled further past an end, up or down from it horizontal, sideways vertical. Two midpoints: placing text above or below their bounding box measures horizontally, beside it vertically, anywhere else (inside it or past its corners) the distance between them. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An ellipse: a half-axis, the distance from the centre to an axis end (major or minor; with auto, text_at pulled across the major axis gives the major half-axis, pulled out past an end of it the minor one, the minor without text_at; previous_axis?: major|minor, the half-axis an earlier placement chose, kept while text_at is near the boundary between them; the reply's axis names the one chosen; with auto, when a driving dimension already holds one half-axis (or its whole axis), the other one, wherever text_at is; without its major axis line the major half-axis goes to the ellipse's own major end, without its minor axis line the minor half-axis is the minor radius); any other type, radius among them, the minor radius; an ellipse's axis line with auto: its length, the whole axis, wherever text_at is; half_axes?: bool (default true; false: with auto, the minor radius wherever text_at is, as before half-axes, which the Dimension tool sends with Draw ellipses with their axes off). An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends the Sketch preference, on by default): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
|
||||
),
|
||||
@@ -634,7 +613,7 @@ pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, c
|
||||
if let Some(at) = v.get("at").and_then(vec2) {
|
||||
return Ok(PArg::At(at));
|
||||
}
|
||||
Err(bad(cmd, POINT_ARG_MUST))
|
||||
Err(bad(cmd, "a point must be [x, y], a point id like \"l1.end\", or {at, ref}"))
|
||||
}
|
||||
|
||||
pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result<PArg> {
|
||||
@@ -643,39 +622,6 @@ pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Valu
|
||||
|
||||
const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters";
|
||||
|
||||
/// What a point argument must be, when it is none of the forms [`parg`] reads.
|
||||
const POINT_ARG_MUST: &str = "a point must be [x, y], a point id like \"l1.end\", or {at, ref}";
|
||||
|
||||
/// Whether `v` is a point argument [`parg`] reads, looking only at the JSON: what the design
|
||||
/// decides (an unknown point id, an expression naming no parameter) stays the handler's. `snaps`:
|
||||
/// the command also reads the forms `sketch_project::snap_points` rewrites first (`{vertex}`,
|
||||
/// `{on_edge}`). The error is the handler's message.
|
||||
pub(crate) fn point_arg_form(v: &Value, snaps: bool) -> std::result::Result<(), &'static str> {
|
||||
if snaps && (v.get("vertex").and_then(vec3).is_some() || v.get("on_edge").and_then(vec3).is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
if vec2(v).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some([x, y]) = v.as_array().map(Vec::as_slice)
|
||||
&& (x.is_string() || y.is_string())
|
||||
{
|
||||
// The coordinates `expr_point` reads: a finite number, or text that isn't blank.
|
||||
let coordinate = |c: &Value| match c {
|
||||
Value::Number(n) => n.as_f64().and_then(crate::params::finite).is_some(),
|
||||
Value::String(e) => !e.trim().is_empty() && e.len() <= 4096,
|
||||
_ => false,
|
||||
};
|
||||
return if coordinate(x) && coordinate(y) { Ok(()) } else { Err(POINT_MUST) };
|
||||
}
|
||||
let named = match v {
|
||||
Value::String(_) => true,
|
||||
Value::Object(o) => o.get("ref").is_some_and(Value::is_string),
|
||||
_ => false,
|
||||
};
|
||||
if named || v.get("at").and_then(vec2).is_some() { Ok(()) } else { Err(POINT_ARG_MUST) }
|
||||
}
|
||||
|
||||
/// A point given as `[x, y]` with a coordinate typed as text: where it is now and, when a
|
||||
/// coordinate names a parameter, the expressions that place it (none: a plain point).
|
||||
pub(super) fn expr_point(doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result<Option<(Vec2, Option<PointExprs>)>> {
|
||||
@@ -762,16 +708,14 @@ pub(crate) fn created(before: Option<&Sketch>, after: &Sketch) -> Value {
|
||||
let curves: Vec<&str> = after.curves.iter().map(|x| x.id.as_str()).filter(new).collect();
|
||||
let (dims, cons): (Vec<_>, Vec<_>) = after.constraints.iter().filter(|c| new(&c.id.as_str())).partition(|c| c.kind.is_dimension());
|
||||
let ids = |v: Vec<&solidcraft_sketch::Constraint>| v.into_iter().map(|c| c.id.clone()).collect::<Vec<_>>();
|
||||
let wires: Vec<String> = after.wires.iter().map(|x| x.id.as_str()).filter(new).map(str::to_string).collect();
|
||||
let owned = |v: Vec<&str>| v.into_iter().map(str::to_string).collect::<Vec<_>>();
|
||||
let out = Created { points: owned(points), curves: owned(curves), constraints: ids(cons), dimensions: ids(dims), wires };
|
||||
serde_json::to_value(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The reply of a line, circle or arc: what `result` gives, built from [`DrawResult`].
|
||||
fn draw_reply(out: (Vec<String>, Vec<String>), info: Value) -> Result<Value> {
|
||||
let reply = DrawResult { curves: out.0, constraints: out.1, sketch: info, created: None, param_warnings: Vec::new() };
|
||||
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
|
||||
let mut out = json!({"points": points, "curves": curves, "constraints": ids(cons), "dimensions": ids(dims)});
|
||||
let wires: Vec<&str> = after.wires.iter().map(|x| x.id.as_str()).filter(new).collect();
|
||||
if !wires.is_empty()
|
||||
&& let Some(o) = out.as_object_mut()
|
||||
{
|
||||
o.insert("wires".into(), json!(wires));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn result(sk_out: (Vec<String>, Vec<String>), info: Value) -> Value {
|
||||
@@ -882,23 +826,17 @@ pub(super) fn plane_frame(p: &Value, cmd: &str) -> Result<Option<&'static str>>
|
||||
}
|
||||
}
|
||||
|
||||
/// The note a reply carries when a world plane went into a moved or turned component
|
||||
/// (`placement`: that component's) for an explicit plane read in `frame`, where it differs from
|
||||
/// the component's own.
|
||||
pub(super) fn frame_note(frame: Option<&str>, placement: &solidcraft_doc::Mat) -> Option<&'static str> {
|
||||
(frame == Some("world") && !solidcraft_doc::is_identity(placement)).then_some(
|
||||
"the plane was read in world coordinates and the component is moved or turned, so it is stored at that world place in the component; frame: \"component\" reads it in the component's own coordinates",
|
||||
)
|
||||
}
|
||||
|
||||
/// The reply's `frame` for an explicit plane, with a note when a world plane went into a moved
|
||||
/// or turned component (`placement`: that component's), where it differs from the component's own.
|
||||
pub(super) fn frame_reply(out: &mut Value, frame: Option<&str>, placement: &solidcraft_doc::Mat) {
|
||||
let Some(o) = out.as_object_mut() else { return };
|
||||
let Some(frame) = frame else { return };
|
||||
o.insert("frame".into(), json!(frame));
|
||||
if let Some(note) = frame_note(Some(frame), placement) {
|
||||
o.insert("note".into(), json!(note));
|
||||
if frame == "world" && !solidcraft_doc::is_identity(placement) {
|
||||
o.insert(
|
||||
"note".into(),
|
||||
json!("the plane was read in world coordinates and the component is moved or turned, so it is stored at that world place in the component; frame: \"component\" reads it in the component's own coordinates"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1316,7 +1254,7 @@ fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mark_construction(sk, &curves, p);
|
||||
Ok((ids_of(sk, &curves), cons))
|
||||
})?;
|
||||
draw_reply((curves, cons), info)
|
||||
Ok(result((curves, cons), info))
|
||||
}
|
||||
|
||||
/// A relation the new line `c` has with the curve it starts from (drawn exactly so): tangent
|
||||
@@ -1719,7 +1657,7 @@ fn circle_center(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok((ids_of(sk, &[ci]), cons))
|
||||
})?;
|
||||
draw_reply(out, info)
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
fn circle_two(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1734,7 +1672,7 @@ fn circle_two(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mark_construction(sk, &[ci], p);
|
||||
Ok((ids_of(sk, &[ci]), Vec::new()))
|
||||
})?;
|
||||
draw_reply(out, info)
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
/// Circle through three points.
|
||||
@@ -1769,7 +1707,7 @@ fn circle_three(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok((ids_of(sk, &[ci]), cons))
|
||||
})?;
|
||||
draw_reply(out, info)
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
fn arc_three(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1796,7 +1734,7 @@ fn arc_three(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok((ids_of(sk, &[ci]), cons))
|
||||
})?;
|
||||
draw_reply(out, info)
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
fn arc_center(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1863,7 +1801,7 @@ fn arc_center(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mark_construction(sk, &[ci], p);
|
||||
Ok((ids_of(sk, &[ci]), Vec::new()))
|
||||
})?;
|
||||
draw_reply(out, info)
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
fn polygon(s: &mut Session, p: &Value, cmd: &str, center: Vec2, r_vertex: f64, start: f64, n: usize, inscribed: bool) -> Result<Value> {
|
||||
@@ -2029,7 +1967,7 @@ fn draw_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
};
|
||||
let ((), info) = edit(s, p, cmd, false, |_, _| Ok(()))?;
|
||||
return point_reply(pid, Vec::new(), info);
|
||||
return Ok(json!({"point": pid, "constraints": [], "sketch": info}));
|
||||
}
|
||||
let ((pid, cons), info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
let i = match expr_point(doc, p.get("point").unwrap_or(&Value::Null), cmd)? {
|
||||
@@ -2040,13 +1978,7 @@ fn draw_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cons = connect_points(sk, i, p)?;
|
||||
Ok((sk.points.get(i).map(|q| q.id.clone()).unwrap_or_default(), cons))
|
||||
})?;
|
||||
point_reply(pid, cons, info)
|
||||
}
|
||||
|
||||
/// The reply of `sketch.point`, built from [`PointResult`].
|
||||
fn point_reply(point: String, constraints: Vec<String>, sketch: Value) -> Result<Value> {
|
||||
let reply = PointResult { point, constraints, sketch, created: None, param_warnings: Vec::new() };
|
||||
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
|
||||
Ok(json!({"point": pid, "constraints": cons, "sketch": info}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -1534,7 +1534,7 @@ mod blend_tests {
|
||||
assert_eq!(ids(&r["created"]["curves"]), vec![sp.clone()], "{r}");
|
||||
assert_eq!(ids(&r["created"]["points"]).len(), 8, "{r}");
|
||||
assert!(ids(&r["created"]["constraints"]).is_empty() && ids(&r["created"]["dimensions"]).is_empty(), "{r}");
|
||||
run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "ids": "chord"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "id": "chord"}));
|
||||
// Drop the two references: what is left is the blend and its chord, one closed region.
|
||||
run(&mut s, "sketch.delete", json!({"entities": [a, b]}));
|
||||
let id = s.active_sketch.unwrap();
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::HashMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec2;
|
||||
use solidcraft_io::{DxfEntity, DxfLayer, Geom2, MAX_DRAWING_BYTES};
|
||||
use solidcraft_io::{Geom2, MAX_DRAWING_BYTES};
|
||||
use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch};
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -29,7 +29,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.params("path | text: SVG or DXF (by `format`: \"svg\" | \"dxf\", default by the file name, else SVG); returns min, max, width and height in the file's own size"),
|
||||
CommandSpec::new("sketch.export_dxf", "Save As DXF", export_dxf).icon("sketch_dxf")
|
||||
.noundo()
|
||||
.params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned); units?: \"design\" | \"in\" | \"inch\" | \"mm\" | \"cm\" | \"m\" | \"ft\" (default mm); layer?: profile layer name (default \"0\"); layers?: \"single\" | \"roles\" (default \"single\": all on `layer`; \"roles\": outer on \"OUTLINE\", holes on \"CUT\"); join?: bool (default false: R12 LINE/ARC; true: closed loops as LWPOLYLINE with arc bulges)"),
|
||||
.params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned)"),
|
||||
];
|
||||
|
||||
/// The sketch import command for a drawing file name, regardless of extension case.
|
||||
@@ -290,248 +290,39 @@ fn insert_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
insert(s, p, "sketch.insert_svg", true)
|
||||
}
|
||||
|
||||
fn sorted_curve_ids<'a>(ids: &'a [String]) -> Vec<&'a str> {
|
||||
let mut v: Vec<&'a str> = ids.iter().map(String::as_str).collect();
|
||||
v.sort_unstable();
|
||||
v
|
||||
}
|
||||
|
||||
fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.export_dxf";
|
||||
let id = sketch_store::target(s, p, cmd)?;
|
||||
let st = s.model.state();
|
||||
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;
|
||||
let sk = &ss.sketch;
|
||||
|
||||
let units_val = p.get("units").filter(|v| !v.is_null());
|
||||
if let Some(v) = units_val
|
||||
&& !v.is_string()
|
||||
{
|
||||
return Err(bad(cmd, "`units` must be a string"));
|
||||
let mut geom = Vec::new();
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
if c.construction {
|
||||
continue;
|
||||
}
|
||||
let pt = |k: usize| sk.point(k).unwrap_or_default();
|
||||
match &c.kind {
|
||||
CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
|
||||
CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
|
||||
CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
|
||||
_ => {
|
||||
let poly = sk.polyline(i);
|
||||
geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
|
||||
}
|
||||
}
|
||||
}
|
||||
let units_param = str_(p, "units").map(str::to_ascii_lowercase);
|
||||
let (insunits, scale) = match units_param.as_deref() {
|
||||
None => (4, 1.0),
|
||||
Some("design") => {
|
||||
let doc_units = solidcraft_doc::expr::length_unit_or_mm(&s.doc.units);
|
||||
match doc_units.to_ascii_lowercase().as_str() {
|
||||
"in" | "inch" => (1, 1.0 / 25.4),
|
||||
"ft" => (2, 1.0 / 304.8),
|
||||
"cm" => (5, 0.1),
|
||||
"m" => (6, 0.001),
|
||||
_ => (4, 1.0),
|
||||
}
|
||||
}
|
||||
Some("in" | "inch") => (1, 1.0 / 25.4),
|
||||
Some("ft") => (2, 1.0 / 304.8),
|
||||
Some("mm") => (4, 1.0),
|
||||
Some("cm") => (5, 0.1),
|
||||
Some("m") => (6, 0.001),
|
||||
Some(other) => {
|
||||
return Err(bad(cmd, format!("unsupported unit `{other}` (use \"design\", \"mm\", \"in\", \"cm\", \"m\", or \"ft\")")));
|
||||
}
|
||||
};
|
||||
|
||||
let layer_val = p.get("layer").filter(|v| !v.is_null());
|
||||
if let Some(v) = layer_val
|
||||
&& !v.is_string()
|
||||
{
|
||||
return Err(bad(cmd, "`layer` must be a string"));
|
||||
}
|
||||
let custom_layer = str_(p, "layer").map(str::trim).filter(|s| !s.is_empty());
|
||||
|
||||
let layers_val = p.get("layers").filter(|v| !v.is_null());
|
||||
if let Some(v) = layers_val
|
||||
&& !v.is_string()
|
||||
{
|
||||
return Err(bad(cmd, "`layers` must be \"single\" or \"roles\""));
|
||||
}
|
||||
let roles_layers = match str_(p, "layers").map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("single") => false,
|
||||
Some("roles") => true,
|
||||
Some(_) => return Err(bad(cmd, "`layers` must be \"single\" or \"roles\"")),
|
||||
};
|
||||
|
||||
let join = match p.get("join").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(bad(cmd, "`join` must be true or false")),
|
||||
};
|
||||
|
||||
let path_val = p.get("path").filter(|v| !v.is_null());
|
||||
if let Some(v) = path_val
|
||||
&& !v.is_string()
|
||||
{
|
||||
return Err(bad(cmd, "`path` must be a string"));
|
||||
}
|
||||
|
||||
let is_default = units_val.is_none() && layer_val.is_none() && layers_val.is_none() && !join;
|
||||
|
||||
let (text, entity_count) = if is_default {
|
||||
let mut geom = Vec::new();
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
if c.construction {
|
||||
continue;
|
||||
}
|
||||
let pt = |k: usize| sk.point(k).unwrap_or_default();
|
||||
match &c.kind {
|
||||
CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
|
||||
CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
|
||||
CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
|
||||
_ => {
|
||||
let poly = sk.polyline(i);
|
||||
geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
|
||||
}
|
||||
}
|
||||
}
|
||||
let count = geom.len();
|
||||
(solidcraft_io::write_dxf(&geom), count)
|
||||
} else if !join {
|
||||
let hole_keys: std::collections::HashSet<Vec<&str>> =
|
||||
ss.profiles.iter().flat_map(|p| p.hole_curves.iter().map(|h| sorted_curve_ids(h))).collect();
|
||||
|
||||
let mut outline_ids = std::collections::HashSet::new();
|
||||
let mut cut_ids = std::collections::HashSet::new();
|
||||
if roles_layers {
|
||||
for prof in &ss.profiles {
|
||||
for holes in &prof.hole_curves {
|
||||
for id in holes {
|
||||
cut_ids.insert(id.as_str());
|
||||
}
|
||||
}
|
||||
if !hole_keys.contains(&sorted_curve_ids(&prof.outer_curves)) {
|
||||
for id in &prof.outer_curves {
|
||||
outline_ids.insert(id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let base_layer = custom_layer.unwrap_or("0");
|
||||
let mut entities = Vec::new();
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
if c.construction {
|
||||
continue;
|
||||
}
|
||||
let layer = if roles_layers {
|
||||
if cut_ids.contains(c.id.as_str()) {
|
||||
"CUT"
|
||||
} else if outline_ids.contains(c.id.as_str()) {
|
||||
"OUTLINE"
|
||||
} else {
|
||||
base_layer
|
||||
}
|
||||
} else {
|
||||
base_layer
|
||||
};
|
||||
let pt = |k: usize| sk.point(k).unwrap_or_default() * scale;
|
||||
match &c.kind {
|
||||
CurveKind::Line { a, b } => entities.push((layer, Geom2::Line(pt(*a), pt(*b)))),
|
||||
CurveKind::Circle { c, r } => entities.push((layer, Geom2::Circle(pt(*c), *r * scale))),
|
||||
CurveKind::Arc { c, a, b } => entities.push((layer, Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) })),
|
||||
_ => {
|
||||
let poly = sk.polyline(i);
|
||||
for w in poly.windows(2) {
|
||||
entities.push((layer, Geom2::Line(w[0] * scale, w[1] * scale)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let count = entities.len();
|
||||
(solidcraft_io::write_dxf_entities(&entities, insunits), count)
|
||||
} else {
|
||||
// join: true -> emit closed loops as LWPOLYLINE with bulges for arcs
|
||||
let hole_keys: std::collections::HashSet<Vec<&str>> =
|
||||
ss.profiles.iter().flat_map(|p| p.hole_curves.iter().map(|h| sorted_curve_ids(h))).collect();
|
||||
|
||||
let mut outline_ids = std::collections::HashSet::new();
|
||||
let mut cut_ids = std::collections::HashSet::new();
|
||||
for prof in &ss.profiles {
|
||||
for id in &prof.outer_curves {
|
||||
outline_ids.insert(id.as_str());
|
||||
}
|
||||
for holes in &prof.hole_curves {
|
||||
for id in holes {
|
||||
cut_ids.insert(id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
let base_layer = custom_layer.unwrap_or("0");
|
||||
let mut entities = Vec::new();
|
||||
for prof in &ss.profiles {
|
||||
if hole_keys.contains(&sorted_curve_ids(&prof.outer_curves)) {
|
||||
continue;
|
||||
}
|
||||
let outer_layer = if roles_layers { "OUTLINE" } else { base_layer };
|
||||
let shape = solidcraft_io::loop_lwpolyline_scaled(&prof.region.outer, scale);
|
||||
entities.push(DxfEntity { layer: outer_layer.into(), shape });
|
||||
|
||||
for hole in &prof.region.holes {
|
||||
let hole_layer = if roles_layers { "CUT" } else { base_layer };
|
||||
let shape = solidcraft_io::loop_lwpolyline_scaled(hole, scale);
|
||||
entities.push(DxfEntity { layer: hole_layer.into(), shape });
|
||||
}
|
||||
}
|
||||
// Preserve any non-profile open curves as disconnected entities so nothing is lost
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
if c.construction || outline_ids.contains(c.id.as_str()) || cut_ids.contains(c.id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let pt = |k: usize| sk.point(k).unwrap_or_default() * scale;
|
||||
match &c.kind {
|
||||
CurveKind::Line { a, b } => {
|
||||
entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Line(pt(*a), pt(*b)) })
|
||||
}
|
||||
CurveKind::Circle { c, r } => {
|
||||
entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Circle { c: pt(*c), r: *r * scale } })
|
||||
}
|
||||
CurveKind::Arc { c, a, b } => {
|
||||
let center = pt(*c);
|
||||
let pa = pt(*a);
|
||||
let pb = pt(*b);
|
||||
let r = center.dist(pa);
|
||||
let a0 = (pa - center).angle().to_degrees().rem_euclid(360.0);
|
||||
let a1 = (pb - center).angle().to_degrees().rem_euclid(360.0);
|
||||
entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Arc { c: center, r, a0, a1 } });
|
||||
}
|
||||
_ => {
|
||||
let poly = sk.polyline(i);
|
||||
let points: Vec<Vec2> = poly.into_iter().map(|p| p * scale).collect();
|
||||
entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Polyline { points } });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut layer_names = std::collections::BTreeSet::new();
|
||||
if roles_layers {
|
||||
layer_names.insert("OUTLINE".to_string());
|
||||
layer_names.insert("CUT".to_string());
|
||||
}
|
||||
for e in &entities {
|
||||
layer_names.insert(e.layer.clone());
|
||||
}
|
||||
let layers: Vec<DxfLayer> = layer_names
|
||||
.iter()
|
||||
.map(|name| match name.as_str() {
|
||||
"OUTLINE" => DxfLayer::new(name, 7),
|
||||
"CUT" => DxfLayer::new(name, 4),
|
||||
_ => DxfLayer::new(name, 7),
|
||||
})
|
||||
.collect();
|
||||
let count = entities.len();
|
||||
(solidcraft_io::write_dxf_drawing_units(&layers, &entities, insunits)?, count)
|
||||
};
|
||||
|
||||
let text = solidcraft_io::write_dxf(&geom);
|
||||
if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty()) {
|
||||
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
return Ok(json!({"path": path, "entities": entity_count}));
|
||||
return Ok(json!({"path": path, "entities": geom.len()}));
|
||||
}
|
||||
Ok(json!({"dxf": text, "entities": entity_count}))
|
||||
Ok(json!({"dxf": text, "entities": geom.len()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use solidcraft_geom::prelude::*;
|
||||
use solidcraft_io::Geom2;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -704,197 +495,4 @@ mod tests {
|
||||
assert!(s.execute("sketch.insert_svg", &p).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_dxf_default_is_byte_identical_to_before() {
|
||||
let mut s = Session::default();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [40, 30]})).unwrap();
|
||||
s.execute("sketch.circle.center", &json!({"center": [15, 15], "radius": 5})).unwrap();
|
||||
|
||||
let out = s.execute("sketch.export_dxf", &json!({})).unwrap();
|
||||
let text = out["dxf"].as_str().unwrap();
|
||||
|
||||
// Build expected R12 DXF exactly as before
|
||||
let st = s.model.state();
|
||||
let ss = st.sketch(1).unwrap();
|
||||
let sk = &ss.sketch;
|
||||
let mut geom = Vec::new();
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
if c.construction {
|
||||
continue;
|
||||
}
|
||||
let pt = |k: usize| sk.point(k).unwrap_or_default();
|
||||
match &c.kind {
|
||||
solidcraft_sketch::CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
|
||||
solidcraft_sketch::CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
|
||||
solidcraft_sketch::CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
|
||||
_ => {
|
||||
let poly = sk.polyline(i);
|
||||
geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
|
||||
}
|
||||
}
|
||||
}
|
||||
let expected = solidcraft_io::write_dxf(&geom);
|
||||
assert_eq!(text, expected, "default output must be byte-identical to previous write_dxf output");
|
||||
|
||||
// Null options must be treated as omitted (default behavior)
|
||||
for null_params in [
|
||||
json!({"units": null}),
|
||||
json!({"layer": null}),
|
||||
json!({"layers": null}),
|
||||
json!({"join": null}),
|
||||
json!({"path": null}),
|
||||
json!({"units": null, "layer": null, "layers": null, "join": null, "path": null}),
|
||||
] {
|
||||
let out_null = s.execute("sketch.export_dxf", &null_params).unwrap();
|
||||
assert_eq!(out_null["dxf"].as_str().unwrap(), expected, "null options must behave identically to default options");
|
||||
assert_eq!(out_null["entities"], out["entities"]);
|
||||
}
|
||||
|
||||
// Hostile inputs
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"units": 123})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"units": "unknown_unit"})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"layer": 456})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"layers": 123})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"layers": "all"})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"join": "true"})).is_err());
|
||||
assert!(s.execute("sketch.export_dxf", &json!({"path": 123})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_dxf_layers_present() {
|
||||
let mut s = Session::default();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [50, 50]})).unwrap();
|
||||
s.execute("sketch.circle.center", &json!({"center": [25, 25], "radius": 10})).unwrap();
|
||||
|
||||
// 1. Single custom layer
|
||||
let out_cut = s.execute("sketch.export_dxf", &json!({"layer": "CUT"})).unwrap();
|
||||
let dxf_cut = out_cut["dxf"].as_str().unwrap();
|
||||
assert!(dxf_cut.contains("\n8\nCUT\n"));
|
||||
assert!(!dxf_cut.contains("\n8\n0\n"));
|
||||
|
||||
// 2. Roles layers (OUTLINE for outer profile, CUT for holes)
|
||||
let out_roles = s.execute("sketch.export_dxf", &json!({"layers": "roles"})).unwrap();
|
||||
let dxf_roles = out_roles["dxf"].as_str().unwrap();
|
||||
assert!(dxf_roles.contains("\n8\nOUTLINE\n"));
|
||||
assert!(dxf_roles.contains("\n8\nCUT\n"));
|
||||
|
||||
// 3. Roles layers with join: true
|
||||
let out_joined_roles = s.execute("sketch.export_dxf", &json!({"join": true, "layers": "roles"})).unwrap();
|
||||
assert_eq!(out_joined_roles["entities"], 2);
|
||||
let dxf_joined = out_joined_roles["dxf"].as_str().unwrap();
|
||||
assert!(dxf_joined.contains("AcDbPolyline"));
|
||||
assert!(dxf_joined.contains("\n 8\nOUTLINE\n") || dxf_joined.contains("\n8\nOUTLINE\n"));
|
||||
assert!(dxf_joined.contains("\n 8\nCUT\n") || dxf_joined.contains("\n8\nCUT\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_dxf_join_does_not_duplicate_holes() {
|
||||
let mut s = Session::default();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [100, 80]})).unwrap();
|
||||
s.execute("sketch.circle.center", &json!({"center": [30, 40], "radius": 5})).unwrap();
|
||||
s.execute("sketch.circle.center", &json!({"center": [70, 40], "radius": 8})).unwrap();
|
||||
|
||||
// With join: true, layers: "roles": exactly 3 entities (1 outer outline, 2 hole cuts)
|
||||
let out_roles = s.execute("sketch.export_dxf", &json!({"join": true, "layers": "roles"})).unwrap();
|
||||
assert_eq!(out_roles["entities"], 3, "expected 1 outer outline and 2 hole cuts, got {}", out_roles["entities"]);
|
||||
let dxf_roles = out_roles["dxf"].as_str().unwrap();
|
||||
let lwpolyline_count = dxf_roles.lines().filter(|l| l.trim() == "LWPOLYLINE").count();
|
||||
assert_eq!(lwpolyline_count, 3, "expected exactly 3 LWPOLYLINE entities in DXF");
|
||||
|
||||
// Without roles (single layer): still exactly 3 entities
|
||||
let out_single = s.execute("sketch.export_dxf", &json!({"join": true})).unwrap();
|
||||
assert_eq!(out_single["entities"], 3, "entities without roles must also be exactly 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_dxf_join_closed_lwpolyline_with_bulge() {
|
||||
let mut s = Session::default();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
// Quarter-pie shape: center at (0, 0), arc from (10, 0) to (0, 10), and lines to (0, 0)
|
||||
s.execute("sketch.line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.execute("sketch.arc.center_point", &json!({"center": [0, 0], "start": [10, 0], "end": [0, 10]})).unwrap();
|
||||
s.execute("sketch.line", &json!({"points": [[0, 10], [0, 0]]})).unwrap();
|
||||
|
||||
let out = s.execute("sketch.export_dxf", &json!({"join": true})).unwrap();
|
||||
let dxf = out["dxf"].as_str().unwrap();
|
||||
assert!(dxf.contains("LWPOLYLINE"));
|
||||
// 70: bit 1 (closed) + bit 128 (plinegen) = 129
|
||||
assert!(dxf.contains("\n 70\n129\n") || dxf.contains("\n70\n129\n"));
|
||||
// Bulge: 90° arc has sweep = pi/2, bulge = tan(sweep / 4) = tan(pi / 8) = sqrt(2) - 1 ≈ 0.414213562373
|
||||
let expected_bulge = (std::f64::consts::FRAC_PI_2 / 4.0).tan();
|
||||
let has_bulge = dxf
|
||||
.lines()
|
||||
.zip(dxf.lines().skip(1))
|
||||
.any(|(k, v)| k.trim() == "42" && (v.trim().parse::<f64>().unwrap_or(0.0).abs() - expected_bulge).abs() < 1e-6);
|
||||
assert!(has_bulge, "DXF must contain group 42 bulge approx {expected_bulge}");
|
||||
|
||||
// Re-import the joined DXF into a new sketch and verify round-trip profile area
|
||||
s.execute("sketch.finish", &json!({})).unwrap();
|
||||
let r = s.execute("sketch.insert_dxf", &json!({"text": dxf, "at": [100, 0]})).unwrap();
|
||||
let id = r["sketch"].as_u64().unwrap();
|
||||
let ss = s.model.state().sketch(id).unwrap().clone();
|
||||
assert_eq!(ss.profiles.len(), 1);
|
||||
let expected_area = std::f64::consts::PI * 100.0 / 4.0; // quarter circle of radius 10
|
||||
assert!((ss.profiles[0].area - expected_area).abs() < 1e-4, "area was {}", ss.profiles[0].area);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_dxf_inch_design_round_trip() {
|
||||
let mut s = Session::default();
|
||||
s.doc_mut().units = "in".to_string();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
// A 2 in by 3 in rectangle in an inch design (stored internally as 50.8 mm by 76.2 mm)
|
||||
s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [50.8, 76.2]})).unwrap();
|
||||
|
||||
// 1. Export with units: "design"
|
||||
let out = s.execute("sketch.export_dxf", &json!({"units": "design"})).unwrap();
|
||||
let dxf = out["dxf"].as_str().unwrap();
|
||||
// $INSUNITS must be 1 (inches)
|
||||
assert!(dxf.contains("\n$INSUNITS\n70\n1\n"));
|
||||
// Sizes in inches: 2.0 and 3.0
|
||||
assert!(dxf.contains("2.000000000"));
|
||||
assert!(dxf.contains("3.000000000"));
|
||||
|
||||
// Round-trip through read_dxf: reads $INSUNITS=1, scales by 25.4 to mm
|
||||
let geom = solidcraft_io::read_dxf(dxf).unwrap();
|
||||
let mut widths = Vec::new();
|
||||
let mut heights = Vec::new();
|
||||
for g in &geom {
|
||||
if let Geom2::Line(a, b) = g {
|
||||
let dx = (b.x - a.x).abs() / 25.4;
|
||||
let dy = (b.y - a.y).abs() / 25.4;
|
||||
if dx > 0.1 {
|
||||
widths.push(dx);
|
||||
}
|
||||
if dy > 0.1 {
|
||||
heights.push(dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
for w in widths {
|
||||
assert!((w - 2.0).abs() < 1e-8, "width in inches was {w}");
|
||||
}
|
||||
for h in heights {
|
||||
assert!((h - 3.0).abs() < 1e-8, "height in inches was {h}");
|
||||
}
|
||||
|
||||
// 2. Export with join: true and explicit units: "in"
|
||||
let out_join = s.execute("sketch.export_dxf", &json!({"join": true, "units": "in"})).unwrap();
|
||||
let dxf_join = out_join["dxf"].as_str().unwrap();
|
||||
assert!(dxf_join.contains("LWPOLYLINE"));
|
||||
assert!(dxf_join.contains("\n$INSUNITS\n 70\n1\n") || dxf_join.contains("\n$INSUNITS\n70\n1\n"));
|
||||
|
||||
let geom_join = solidcraft_io::read_dxf(dxf_join).unwrap();
|
||||
assert_eq!(geom_join.len(), 4);
|
||||
for g in &geom_join {
|
||||
if let Geom2::Line(a, b) = g {
|
||||
let len_in = a.dist(*b) / 25.4;
|
||||
assert!((len_in - 2.0).abs() < 1e-8 || (len_in - 3.0).abs() < 1e-8, "edge length {len_in}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use solidcraft_doc::BrowserEntry;
|
||||
|
||||
use super::canvas::CanvasPlane;
|
||||
use super::check::{located, whole};
|
||||
use super::check::whole;
|
||||
use super::types::{FeatureCommon, LengthExpr, feature_common, present};
|
||||
|
||||
/// Repair a part the modelling kernel refuses, or an open part that should be a solid: faces
|
||||
@@ -1108,469 +1107,6 @@ pub struct BodyRenamed {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- Named views and Redefine Sketch (#12499) ----
|
||||
//
|
||||
// As above: each key reads as its handler reads it and fails with the handler's message. A key
|
||||
// the handler can't do without is optional in the type and required in the schema, so the
|
||||
// handler's own message is what a call that leaves it out gets. Whether a view or a sketch
|
||||
// exists, and whether a plane or a face can be found, stays the handler's to check.
|
||||
|
||||
fn view_required(schema: &mut Schema) {
|
||||
require(schema, &["view"]);
|
||||
}
|
||||
|
||||
fn view_and_name_required(schema: &mut Schema) {
|
||||
require(schema, &["view", "name"]);
|
||||
}
|
||||
|
||||
fn camera_required(schema: &mut Schema) {
|
||||
require(schema, &["camera"]);
|
||||
}
|
||||
|
||||
fn sketch_and_plane_required(schema: &mut Schema) {
|
||||
require(schema, &["sketch", "plane"]);
|
||||
}
|
||||
|
||||
/// A named view, as `view.rename` and `view.delete` read `view`: text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ViewKey(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for ViewKey {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(n) => Ok(ViewKey(n)),
|
||||
_ => Err(D::Error::custom(whole("`view` must be a view name"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ViewKey {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ViewKey".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A named view's name.", "type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
fn some_view<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ViewKey>, D::Error> {
|
||||
ViewKey::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// The name `view.save` gives a view: at most 128 bytes once surrounding spaces are cut; nothing
|
||||
/// left means the next free "Named View" number.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SavedViewName(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for SavedViewName {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(n) if n.trim().len() > MAX_NAME_BYTES => Err(D::Error::custom(whole("`name` is too long"))),
|
||||
Value::String(n) => Ok(SavedViewName(n)),
|
||||
_ => Err(D::Error::custom("must be text")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SavedViewName {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SavedViewName".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A name of at most 128 bytes once surrounding spaces are cut.", "type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// The point a saved camera looks at, as the schemas of the view commands give it.
|
||||
fn target_schema() -> Value {
|
||||
json!({
|
||||
"description": "The point the camera looks at, in mm: [x, y, z].",
|
||||
"type": "array",
|
||||
"items": {"type": "number"},
|
||||
"minItems": 3,
|
||||
"maxItems": 3
|
||||
})
|
||||
}
|
||||
|
||||
/// The camera `view.save` keeps, as the handler reads it: finite numbers and a positive
|
||||
/// distance. A `name` inside it is replaced by the call's `name`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ViewCamera(pub solidcraft_doc::NamedView);
|
||||
|
||||
impl<'de> Deserialize<'de> for ViewCamera {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
crate::cmd::browser::saved_view_form(&Value::deserialize(d)?).map(ViewCamera).map_err(|why| D::Error::custom(whole(why)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ViewCamera {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ViewCamera".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "An orbit camera. Angles are in radians, about the up axis.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"target": target_schema(),
|
||||
"yaw": {"description": "Turn about the up axis; 0 looks along +Y, from the front.", "type": "number"},
|
||||
"pitch": {"description": "Elevation of the eye above the ground plane.", "type": "number"},
|
||||
"distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0},
|
||||
"fov": {"description": "Vertical field of view; 0 is orthographic. Default: 0.", "type": "number", "default": 0.0}
|
||||
},
|
||||
"required": ["target", "yaw", "pitch", "distance"]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the camera as a named view of the design. One undo step. A view of the same name is
|
||||
/// replaced.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = camera_required)]
|
||||
pub struct ViewSaveParams {
|
||||
// Optional in the type and required in the schema (`camera_required`): left out, the handler
|
||||
// refuses it with its own message.
|
||||
/// The camera to keep: `{target: [x, y, z], yaw, pitch, distance, fov?}`, finite, with a
|
||||
/// distance above 0.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ViewCamera")]
|
||||
pub camera: Option<ViewCamera>,
|
||||
/// The view's name, at most 128 bytes once surrounding spaces are cut. Default: "Named View"
|
||||
/// and the first number no view's name has. A value that is not text is reported, though the
|
||||
/// handler would read it as left out.
|
||||
#[serde(default)]
|
||||
pub name: Option<SavedViewName>,
|
||||
}
|
||||
|
||||
/// What `view.save` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ViewSaved {
|
||||
/// The name the view was kept under.
|
||||
pub view: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Rename a named view. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = view_and_name_required)]
|
||||
pub struct ViewRenameParams {
|
||||
// Required in the schema (`view_and_name_required`), optional in the type, as `group` above.
|
||||
/// The view to rename, by name.
|
||||
#[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ViewKey")]
|
||||
pub view: Option<ViewKey>,
|
||||
/// The new name, 1 to 128 characters once surrounding spaces are cut; no other view may
|
||||
/// have it.
|
||||
#[serde(default, deserialize_with = "some_new_name", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "NewName")]
|
||||
pub name: Option<NewName>,
|
||||
}
|
||||
|
||||
/// What `view.rename` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ViewRenamed {
|
||||
/// The view's name now, without surrounding spaces.
|
||||
pub view: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Delete a named view. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = view_required)]
|
||||
pub struct ViewDeleteParams {
|
||||
// Required in the schema (`view_required`), optional in the type.
|
||||
/// The view to delete, by name.
|
||||
#[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ViewKey")]
|
||||
pub view: Option<ViewKey>,
|
||||
}
|
||||
|
||||
/// What `view.delete` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ViewDeleted {
|
||||
/// The name of the view that is gone.
|
||||
pub deleted: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// `view.list` takes no parameters.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ViewListParams {}
|
||||
|
||||
/// A named view, as `view.list` gives it. Only its schema is described here: the reply carries
|
||||
/// the design's own [`solidcraft_doc::NamedView`] values.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ViewEntry {
|
||||
/// The view's name.
|
||||
pub name: String,
|
||||
/// The point the camera looks at, in mm.
|
||||
pub target: [f64; 3],
|
||||
/// Turn about the up axis, in radians.
|
||||
pub yaw: f64,
|
||||
/// Elevation of the eye, in radians.
|
||||
pub pitch: f64,
|
||||
/// From the target to the eye, in mm.
|
||||
pub distance: f64,
|
||||
/// Vertical field of view in radians; 0 is orthographic.
|
||||
pub fov: f64,
|
||||
}
|
||||
|
||||
/// What `view.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ViewListResult {
|
||||
/// The design's named views, in the order they were made.
|
||||
#[schemars(with = "Vec<ViewEntry>")]
|
||||
pub views: Vec<solidcraft_doc::NamedView>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The camera `view.apply` turns to, as the handler reads it: `up` is refused, `roll` is finite,
|
||||
/// the pitch within ±π/2 and the rest finite with a positive distance.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ApplyCamera(pub solidcraft_render::Camera);
|
||||
|
||||
impl<'de> Deserialize<'de> for ApplyCamera {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
crate::cmd::browser::applied_camera_form(&Value::deserialize(d)?).map(ApplyCamera).map_err(|why| D::Error::custom(whole(why)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ApplyCamera {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ApplyCamera".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "An orbit camera. Angles are in radians, about the up axis, which comes from the design settings.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"target": target_schema(),
|
||||
"yaw": {"description": "Turn about the up axis; 0 looks along +Y (Front), π/2 along +X (Left), π (Back), -π/2 (Right).", "type": "number"},
|
||||
"pitch": {"description": "Elevation of the eye above the ground plane, within ±π/2; π/2 is Top.", "type": "number", "minimum": -std::f64::consts::FRAC_PI_2, "maximum": std::f64::consts::FRAC_PI_2},
|
||||
"distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0},
|
||||
"fov": {"description": "Vertical field of view; 0 is orthographic. Default: 0.", "type": "number", "minimum": 0, "default": 0.0},
|
||||
"roll": {"description": "Turn about the viewing direction, clockwise; a finite number, clamped to ±π. Default: 0.", "type": "number", "default": 0.0}
|
||||
},
|
||||
"required": ["target", "yaw", "pitch", "distance"],
|
||||
"not": {"required": ["up"]}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the viewport (and the MCP screenshot) to a standard view, a named view or a camera. View
|
||||
/// state only: not saved with the design and not an undo step. Give `view` or `camera`, not both.
|
||||
/// (A `view` that is not text is read as absent when a `camera` is given, as the handler does.)
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ViewApplyKeys {
|
||||
/// A standard view: front, back, top, bottom, left, right, iso or home (the model framed
|
||||
/// from there), or a named view's name. Not with `camera`.
|
||||
#[serde(default)]
|
||||
pub view: Option<String>,
|
||||
/// A camera to turn to. Not with `view`.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ApplyCamera")]
|
||||
pub camera: Option<ApplyCamera>,
|
||||
}
|
||||
|
||||
/// `view.apply`'s parameters: [`ViewApplyKeys`] with the two forms told apart.
|
||||
///
|
||||
/// The handler reads `view` as text and takes anything else as absent, and reads `camera` only
|
||||
/// when `view` is not text, so the same holds here: a `view` that is not text is not looked at
|
||||
/// when a `camera` is given, and one of neither is left to the handler's message.
|
||||
#[derive(Debug)]
|
||||
pub struct ViewApplyParams(pub ViewApplyKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ViewApplyParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if value.get("view").is_some_and(Value::is_string) {
|
||||
if value.get("camera").is_some() {
|
||||
return Err(D::Error::custom(whole("give `view` or `camera`, not both")));
|
||||
}
|
||||
} else if let Some(keys) = value.as_object_mut() {
|
||||
keys.remove("view");
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ViewApplyParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ViewApplyParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ViewApplyParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let mut schema = ViewApplyKeys::json_schema(generator);
|
||||
schema.insert("anyOf".into(), json!([{"required": ["view"]}, {"required": ["camera"]}]));
|
||||
schema.insert("not".into(), json!({"required": ["view", "camera"]}));
|
||||
schema
|
||||
}
|
||||
}
|
||||
|
||||
/// A sketch by id or name, as `sketch.redefine` reads `sketch`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SketchKey(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for SketchKey {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => Ok(SketchKey(n.to_string())),
|
||||
Value::String(s) => Ok(SketchKey(s)),
|
||||
_ => Err(D::Error::custom(whole("`sketch` must be an id or name"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SketchKey {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SketchKey".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A sketch's feature id (a number) or its name.", "type": ["number", "string"]})
|
||||
}
|
||||
}
|
||||
|
||||
fn some_sketch<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SketchKey>, D::Error> {
|
||||
SketchKey::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// The coordinates an explicit plane `{origin, x_dir, y_dir}` is given in: `world` or
|
||||
/// `component`, the component's own. (No doc on the variants: they would make the schema a
|
||||
/// `oneOf` of constants instead of a plain `enum`.)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PlaneFrame {
|
||||
World,
|
||||
Component,
|
||||
}
|
||||
|
||||
impl PlaneFrame {
|
||||
/// The frame a handler names, as `world` or `component`.
|
||||
pub fn from_name(name: &str) -> Option<PlaneFrame> {
|
||||
match name {
|
||||
"world" => Some(PlaneFrame::World),
|
||||
"component" => Some(PlaneFrame::Component),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PlaneFrame {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(f) if f == "world" => Ok(PlaneFrame::World),
|
||||
Value::String(f) if f == "component" => Ok(PlaneFrame::Component),
|
||||
_ => Err(D::Error::custom(whole("`frame` must be \"world\" or \"component\""))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The occurrence ids of the placement a sketch is authored in, from the outermost down, as
|
||||
/// `sketch.redefine` reads `author_path`: at most 64 nonzero whole numbers.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AuthorPath(pub Vec<u64>);
|
||||
|
||||
impl<'de> Deserialize<'de> for AuthorPath {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Array(path) if path.len() <= MAX_PATH => path
|
||||
.iter()
|
||||
.map(|id| id.as_u64().filter(|id| *id != 0).ok_or_else(|| D::Error::custom(whole("invalid author_path id"))))
|
||||
.collect::<Result<_, _>>()
|
||||
.map(AuthorPath),
|
||||
_ => Err(D::Error::custom(whole("author_path must contain at most64 ids"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for AuthorPath {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"AuthorPath".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Occurrence ids, outermost first: at most 64 whole numbers above 0.",
|
||||
"type": "array",
|
||||
"items": {"type": "integer", "minimum": 1},
|
||||
"maxItems": MAX_PATH
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Move a sketch to another plane, keeping its geometry and its dimension names: an origin or
|
||||
/// construction plane, an explicit plane, or a planar face of the model. A face it follows is
|
||||
/// refused where the sketch's own geometry would depend on later features. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = sketch_and_plane_required)]
|
||||
pub struct RedefineSketchParams {
|
||||
// Optional in the type and required in the schema (`sketch_and_plane_required`): left out,
|
||||
// the handler refuses it with its own message.
|
||||
/// The sketch to move, by feature id or name.
|
||||
#[serde(default, deserialize_with = "some_sketch", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SketchKey")]
|
||||
pub sketch: Option<SketchKey>,
|
||||
/// The new plane, as `sketch.create` takes it. A picked face is read as it reads one.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "CanvasPlane")]
|
||||
pub plane: Option<CanvasPlane>,
|
||||
/// Move the plane this far along its normal (mm or a length expression). Default: 0.
|
||||
#[serde(default)]
|
||||
pub offset: Option<LengthExpr>,
|
||||
/// The placement the sketch is authored in, as occurrence ids from the outermost down. Default: the
|
||||
/// sketch's saved one, else the active occurrence, else the component's only placement; a
|
||||
/// component sketch in a design with several placements needs it.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "AuthorPath")]
|
||||
pub author_path: Option<AuthorPath>,
|
||||
/// For an explicit plane `{origin, x_dir, y_dir}`: whether it is in the world's or the
|
||||
/// component's own coordinates. Default: world. A named plane or a face takes none.
|
||||
#[serde(default)]
|
||||
pub frame: Option<PlaneFrame>,
|
||||
}
|
||||
|
||||
/// How a redefined sketch is attached to its plane: `exact_face` (to a face of a body, which it
|
||||
/// follows), `sheet_face` (to a face of a sheet part) or `fixed` (where it is: an origin,
|
||||
/// construction or explicit plane).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RedefineAttachment {
|
||||
ExactFace,
|
||||
SheetFace,
|
||||
Fixed,
|
||||
}
|
||||
|
||||
/// What `sketch.redefine` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct RedefineSketchResult {
|
||||
/// The sketch's feature id.
|
||||
pub sketch: u64,
|
||||
/// How it is attached now.
|
||||
pub attachment: Option<RedefineAttachment>,
|
||||
/// For an explicit plane: the coordinates it was read in.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub frame: Option<PlaneFrame>,
|
||||
/// For a world plane put into a component that is moved or turned: how it was stored.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
/// What the session reports for every sketch command: the ids of the points, curves,
|
||||
/// constraints and dimensions the sketch gained, `{points, curves, constraints, dimensions}`.
|
||||
/// The handler leaves it out; the session adds it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "browser_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -3,13 +3,10 @@ use serde_json::{Value, json};
|
||||
use super::{
|
||||
BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,
|
||||
BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,
|
||||
BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, RedefineSketchParams, RedefineSketchResult,
|
||||
RepairParams, RepairResult, ViewApplyParams, ViewDeleteParams, ViewDeleted, ViewListParams, ViewListResult, ViewRenameParams, ViewRenamed,
|
||||
ViewSaveParams, ViewSaved, VisibilityState,
|
||||
BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult, VisibilityState,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::view_navigation::CameraReply;
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
#[test]
|
||||
@@ -333,413 +330,3 @@ fn browser_commands_reply_with_their_schemas() {
|
||||
let error = s.execute("browser.visibility", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`itms`"), "{error}");
|
||||
}
|
||||
|
||||
// ---- Named views and Redefine Sketch (#12499) ----
|
||||
|
||||
const CAMERA: fn() -> Value = || json!({"target": [1, 2, 3], "yaw": 0.5, "pitch": -0.6, "distance": 150});
|
||||
|
||||
#[test]
|
||||
fn view_schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ViewSaveParams>(), &["camera", "name"]);
|
||||
assert_keys(input_schema_for::<ViewRenameParams>(), &["name", "view"]);
|
||||
assert_keys(input_schema_for::<ViewDeleteParams>(), &["view"]);
|
||||
assert_keys(input_schema_for::<ViewListParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ViewApplyParams>(), &["camera", "view"]);
|
||||
assert_keys(input_schema_for::<RedefineSketchParams>(), &["author_path", "frame", "offset", "plane", "sketch"]);
|
||||
}
|
||||
|
||||
/// Each call has one problem the handler already refuses: strict gives its message. The session
|
||||
/// has a sketch (`1`) and no named view, so a view that must exist is looked for in the second
|
||||
/// test.
|
||||
#[test]
|
||||
fn view_strict_keeps_todays_errors() {
|
||||
let long = "n".repeat(129);
|
||||
let deep: Vec<u64> = (1..=65).collect();
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("view.save", json!({})),
|
||||
("view.save", json!({"name": "A"})),
|
||||
("view.save", json!({"camera": null})),
|
||||
("view.save", json!({"camera": "front"})),
|
||||
("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0}})),
|
||||
("view.save", json!({"camera": {"target": [0, 0], "yaw": 0, "pitch": 0, "distance": 5}})),
|
||||
("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 0}})),
|
||||
("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": -3}})),
|
||||
("view.save", json!({"camera": CAMERA(), "name": long})),
|
||||
("view.rename", json!({})),
|
||||
("view.rename", json!({"name": "B"})),
|
||||
("view.rename", json!({"view": 5, "name": "B"})),
|
||||
("view.rename", json!({"view": null, "name": "B"})),
|
||||
("view.rename", json!({"view": "Nope", "name": "B"})),
|
||||
("view.delete", json!({})),
|
||||
("view.delete", json!({"view": 5})),
|
||||
("view.delete", json!({"view": null})),
|
||||
("view.delete", json!({"view": "Nope"})),
|
||||
("view.apply", json!({})),
|
||||
("view.apply", json!({"view": 5})),
|
||||
("view.apply", json!({"view": null})),
|
||||
("view.apply", json!({"view": "Nope"})),
|
||||
("view.apply", json!({"view": "top", "camera": CAMERA()})),
|
||||
("view.apply", json!({"view": "top", "camera": null})),
|
||||
("view.apply", json!({"camera": null})),
|
||||
("view.apply", json!({"camera": "front"})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "up": "y"}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "up": null}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": "x"}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": null}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 1.6, "distance": 80}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": -1.6, "distance": 80}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 0}})),
|
||||
("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "fov": -0.5}})),
|
||||
("sketch.redefine", json!({})),
|
||||
("sketch.redefine", json!({"plane": "XZ"})),
|
||||
("sketch.redefine", json!({"sketch": true, "plane": "XZ"})),
|
||||
("sketch.redefine", json!({"sketch": null, "plane": "XZ"})),
|
||||
("sketch.redefine", json!({"sketch": [1], "plane": "XZ"})),
|
||||
("sketch.redefine", json!({"sketch": 999, "plane": "XZ"})),
|
||||
("sketch.redefine", json!({"sketch": 1})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": null})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": true})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": 1.5})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": -1})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": {"x_dir": [1, 0, 0]}})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": {"x_dir": [1, 0, 0], "y_dir": [2, 0, 0]}})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": {"origin": "1 mm", "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": {"face": "x"}})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": {"face": [1, 2, 3], "body": "Box"}})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": "local"})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": 3})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": "world"})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": "1"})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": null})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": [0]})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": ["a"]})),
|
||||
("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": deep})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The calls that need a named view to get as far as their message.
|
||||
#[test]
|
||||
fn view_strict_keeps_todays_errors_for_views() {
|
||||
let long = "n".repeat(129);
|
||||
let cases = [
|
||||
("view.rename", json!({"view": "Front 2", "name": ""})),
|
||||
("view.rename", json!({"view": "Front 2", "name": " "})),
|
||||
("view.rename", json!({"view": "Front 2", "name": 5})),
|
||||
("view.rename", json!({"view": "Front 2", "name": null})),
|
||||
("view.rename", json!({"view": "Front 2", "name": long})),
|
||||
("view.rename", json!({"view": "Front 2"})),
|
||||
("view.rename", json!({"view": "Front 2", "name": "Other"})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let run = |level: ParamCheck| {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
for name in ["Front 2", "Other"] {
|
||||
s.execute("view.save", &json!({"camera": CAMERA(), "name": name})).unwrap_or_else(|e| panic!("{e}"));
|
||||
}
|
||||
s.execute(id, &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = run(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(run(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What the handlers refuse is refused by the types with the same message, and what they take
|
||||
/// is taken: the check names no problem for any call that works today, in the forms that read
|
||||
/// different keys (`view` or `camera`) and in each form of `plane`.
|
||||
#[test]
|
||||
fn the_check_reads_each_key_as_the_handler_does() {
|
||||
let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
let none = Vec::<String>::new();
|
||||
let cam = |extra: Value| {
|
||||
let mut c = CAMERA();
|
||||
c["distance"] = json!(80);
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
c[k] = v.clone();
|
||||
}
|
||||
c
|
||||
};
|
||||
// view.apply: a view, or a camera.
|
||||
assert_eq!(issues("view.apply", json!({"view": "top"})), none);
|
||||
assert_eq!(issues("view.apply", json!({"view": "Anything"})), none);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({}))})), none);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"fov": 0.5, "roll": 1.0}))})), none);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"roll": 100}))})), none, "a roll past π is clamped");
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"pitch": std::f64::consts::FRAC_PI_2}))})), none);
|
||||
// `view` is read as text only: where `camera` is the form, one that is not text is not looked at.
|
||||
assert_eq!(issues("view.apply", json!({"view": null, "camera": cam(json!({}))})), none);
|
||||
assert_eq!(issues("view.apply", json!({"view": 5, "camera": cam(json!({}))})), none);
|
||||
assert_eq!(issues("view.apply", json!({"view": "top", "camera": cam(json!({}))})), ["give `view` or `camera`, not both"]);
|
||||
assert_eq!(issues("view.apply", json!({"view": "top", "camera": null})), ["give `view` or `camera`, not both"]);
|
||||
assert_eq!(
|
||||
issues("view.apply", json!({"camera": cam(json!({"up": "z"}))})),
|
||||
["camera `up` is not supported: the up axis comes from the design settings"]
|
||||
);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"roll": "x"}))})), ["camera `roll` must be a finite number in radians"]);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"pitch": 2}))})), ["camera `pitch` must be within ±π/2 radians (±90°)"]);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"distance": 0}))})), ["the camera must be finite with a positive distance"]);
|
||||
assert_eq!(issues("view.apply", json!({"camera": cam(json!({"fov": -1}))})), ["the camera must be finite with a positive distance"]);
|
||||
assert!(issues("view.apply", json!({"camera": {"yaw": 1}}))[0].starts_with("bad camera: missing field `target`"));
|
||||
// Neither: the handler's own message (the type leaves it to the handler).
|
||||
assert_eq!(issues("view.apply", json!({})), none);
|
||||
// view.save.
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA()})), none);
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": " "})), none);
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": null})), none);
|
||||
// Not text: the handler reads it as left out; the check reports it.
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": 5})).len(), 1);
|
||||
assert_eq!(
|
||||
issues("view.save", json!({"camera": {"name": "old", "target": [1, 2, 3], "yaw": 0, "pitch": 7, "distance": 1, "fov": 0.3}, "name": "N"})),
|
||||
none
|
||||
);
|
||||
assert_eq!(issues("view.save", json!({"camera": cam(json!({"distance": -1}))})), ["the camera must be finite with a positive distance"]);
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": "n".repeat(129)})), ["`name` is too long"]);
|
||||
assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": format!(" {} ", "n".repeat(128))})), none);
|
||||
// view.rename and view.delete.
|
||||
assert_eq!(issues("view.rename", json!({"view": "a", "name": "b"})), none);
|
||||
assert_eq!(issues("view.rename", json!({"view": 1, "name": "b"})), ["`view` must be a view name"]);
|
||||
assert_eq!(issues("view.rename", json!({"view": "a", "name": ""})), ["`name` must be 1…128 characters"]);
|
||||
assert_eq!(issues("view.delete", json!({"view": null})), ["`view` must be a view name"]);
|
||||
assert_eq!(issues("view.list", json!({})), none);
|
||||
assert_eq!(issues("view.list", json!({"views": 1})).len(), 1);
|
||||
// sketch.redefine: each form of the plane, and `frame` and `author_path` as given.
|
||||
let plane = |p: Value| issues("sketch.redefine", json!({"sketch": "S", "plane": p}));
|
||||
for p in [
|
||||
json!("XY"),
|
||||
json!("front"),
|
||||
json!("Plane1"),
|
||||
json!(7),
|
||||
json!({"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}),
|
||||
json!({"origin": [1, 2, 3], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}),
|
||||
json!({"origin": null, "x_dir": {"x": 1, "y": 0, "z": 0}, "y_dir": [0, 1, 0]}),
|
||||
json!({"face": [1, 2, 3]}),
|
||||
json!({"face": [1, 2, 3], "body": "Box", "index": 2, "path": [1, 2], "fixed": true}),
|
||||
] {
|
||||
assert_eq!(plane(p.clone()), none, "{p}");
|
||||
}
|
||||
assert_eq!(plane(json!(1.5)).len(), 1);
|
||||
assert_eq!(plane(json!(null)), ["`plane` must be XY, XZ, YZ, a construction plane name or id, or an object"]);
|
||||
assert_eq!(plane(json!({"x_dir": [1, 0, 0]})), ["plane needs y_dir"]);
|
||||
let with = |extra: Value| {
|
||||
let mut p = json!({"sketch": 1, "plane": "XZ"});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
issues("sketch.redefine", p)
|
||||
};
|
||||
assert_eq!(with(json!({"offset": 5})), none);
|
||||
assert_eq!(with(json!({"offset": "w / 2"})), none);
|
||||
assert_eq!(with(json!({"frame": null})), none);
|
||||
assert_eq!(with(json!({"frame": "component", "author_path": [1, 2]})), none);
|
||||
assert_eq!(with(json!({"author_path": []})), none);
|
||||
assert_eq!(with(json!({"frame": "x"})), ["`frame` must be \"world\" or \"component\""]);
|
||||
assert_eq!(with(json!({"author_path": [0]})), ["invalid author_path id"]);
|
||||
assert_eq!(with(json!({"author_path": null})), ["author_path must contain at most64 ids"]);
|
||||
assert_eq!(issues("sketch.redefine", json!({"sketch": 2.5, "plane": "XZ"})), none);
|
||||
assert_eq!(issues("sketch.redefine", json!({"sketch": {}, "plane": "XZ"})), ["`sketch` must be an id or name"]);
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need, and no more.
|
||||
#[test]
|
||||
fn the_view_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
let cam = |extra: Value| {
|
||||
let mut c = CAMERA();
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
c[k] = v.clone();
|
||||
}
|
||||
c
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<ViewSaveParams>(),
|
||||
&[
|
||||
(json!({"camera": CAMERA()}), true),
|
||||
(json!({"camera": cam(json!({"fov": 0.4})), "name": "N"}), true),
|
||||
(json!({"name": "N"}), false),
|
||||
(json!({"camera": cam(json!({"distance": 0}))}), false),
|
||||
(json!({"camera": {"yaw": 0}}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ViewApplyParams>(),
|
||||
&[
|
||||
(json!({"view": "top"}), true),
|
||||
(json!({"camera": cam(json!({"roll": 0.3, "fov": 0.5}))}), true),
|
||||
(json!({}), false),
|
||||
(json!({"view": "top", "camera": CAMERA()}), false),
|
||||
(json!({"camera": cam(json!({"up": "z"}))}), false),
|
||||
(json!({"camera": cam(json!({"pitch": 2}))}), false),
|
||||
(json!({"camera": cam(json!({"fov": -1}))}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ViewRenameParams>(),
|
||||
&[(json!({"view": "a", "name": "b"}), true), (json!({"view": "a"}), false), (json!({"name": "b"}), false)],
|
||||
);
|
||||
takes(input_schema_for::<ViewDeleteParams>(), &[(json!({"view": "a"}), true), (json!({}), false), (json!({"view": 1}), false)]);
|
||||
takes(input_schema_for::<ViewListParams>(), &[(json!({}), true), (json!({"x": 1}), false)]);
|
||||
takes(
|
||||
input_schema_for::<RedefineSketchParams>(),
|
||||
&[
|
||||
(json!({"sketch": 3, "plane": "XZ"}), true),
|
||||
(
|
||||
json!({"sketch": "S", "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "frame": "component", "offset": "2 mm", "author_path": [1]}),
|
||||
true,
|
||||
),
|
||||
(json!({"sketch": "S", "plane": {"face": [1, 2, 3]}}), true),
|
||||
(json!({"plane": "XZ"}), false),
|
||||
(json!({"sketch": 3}), false),
|
||||
(json!({"sketch": 3, "plane": "XZ", "frame": "x"}), false),
|
||||
(json!({"sketch": 3, "plane": "XZ", "author_path": [0]}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Every form of the six commands, in Warn: each real reply matches its output schema and
|
||||
/// carries no warning, and the replies are the JSON the handlers have always returned.
|
||||
#[test]
|
||||
fn view_and_redefine_replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value, schema: schemars::Schema| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let schema = schema.as_value();
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
assert!(conforms(schema, schema, &r), "{id} {p}: {r} doesn't match {schema}");
|
||||
r
|
||||
};
|
||||
let saved = run("view.save", json!({"camera": CAMERA()}), output_schema_for::<ViewSaved>());
|
||||
assert_eq!(saved, json!({"view": "Named View1"}));
|
||||
let saved = run(
|
||||
"view.save",
|
||||
json!({"camera": {"target": [1, 2, 3], "yaw": 0, "pitch": 0.2, "distance": 9, "fov": 0.4}, "name": " Detail "}),
|
||||
output_schema_for::<ViewSaved>(),
|
||||
);
|
||||
assert_eq!(saved, json!({"view": "Detail"}));
|
||||
run("view.save", json!({"camera": CAMERA(), "name": null}), output_schema_for::<ViewSaved>());
|
||||
let listed = run("view.list", json!({}), output_schema_for::<ViewListResult>());
|
||||
assert_eq!(listed["views"].as_array().map(Vec::len), Some(3), "{listed}");
|
||||
assert_eq!(listed["views"][1]["name"], "Detail", "{listed}");
|
||||
let schema = output_schema_for::<ViewListResult>();
|
||||
let entry = &listed["views"][0];
|
||||
assert!(entry["target"].is_array() && entry["fov"] == 0.0 && entry["distance"] == 150.0, "{listed}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &listed));
|
||||
let renamed = run("view.rename", json!({"view": "Named View1", "name": " Overview "}), output_schema_for::<ViewRenamed>());
|
||||
assert_eq!(renamed, json!({"view": "Overview"}));
|
||||
let deleted = run("view.delete", json!({"view": "Overview"}), output_schema_for::<ViewDeleted>());
|
||||
assert_eq!(deleted, json!({"deleted": "Overview"}));
|
||||
let empty = run("view.list", json!({}), output_schema_for::<ViewListResult>());
|
||||
assert_eq!(empty["views"].as_array().map(Vec::len), Some(2), "{empty}");
|
||||
|
||||
let camera = output_schema_for::<CameraReply>;
|
||||
for view in ["front", "back", "top", "iso", "home"] {
|
||||
run("view.apply", json!({"view": view}), camera());
|
||||
}
|
||||
let named = run("view.apply", json!({"view": "Detail"}), camera());
|
||||
assert!((named["camera"]["pitch"].as_f64().unwrap_or_default() - 0.2).abs() < 1e-12, "{named}");
|
||||
let turned =
|
||||
run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "fov": 0.5, "roll": 1.0}}), camera());
|
||||
assert_eq!(turned["camera"]["roll"], 1.0, "{turned}");
|
||||
let clamped = run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "roll": 100}}), camera());
|
||||
assert!((clamped["camera"]["roll"].as_f64().unwrap_or_default() - std::f64::consts::PI).abs() < 1e-12, "{clamped}");
|
||||
run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": std::f64::consts::FRAC_PI_2, "distance": 80}}), camera());
|
||||
|
||||
// Redefine Sketch: a sketch, moved to a named plane, offset, an explicit plane in each frame,
|
||||
// and a face of a body.
|
||||
let sketch = |s: &mut Session| s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();
|
||||
let sk = sketch(&mut s);
|
||||
let mut run = |id: &str, p: Value| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let schema = output_schema_for::<RedefineSketchResult>();
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id} {p}: {r}");
|
||||
assert!(r["created"].is_object(), "the session adds `created`: {r}");
|
||||
let mut r = r;
|
||||
r.as_object_mut().map(|o| o.remove("created"));
|
||||
r
|
||||
};
|
||||
let r = run("sketch.redefine", json!({"sketch": sk, "plane": "XZ"}));
|
||||
assert_eq!(r, json!({"sketch": sk, "attachment": "fixed"}));
|
||||
let r = run("sketch.redefine", json!({"sketch": sk.to_string(), "plane": "YZ", "offset": "5 mm", "frame": null}));
|
||||
assert_eq!(r, json!({"sketch": sk, "attachment": "fixed"}));
|
||||
let explicit = json!({"origin": [1, 2, 3], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]});
|
||||
let r = run("sketch.redefine", json!({"sketch": sk, "plane": explicit}));
|
||||
assert_eq!(r, json!({"sketch": sk, "attachment": "fixed", "frame": "world"}));
|
||||
let r = run("sketch.redefine", json!({"sketch": sk, "plane": explicit, "frame": "component"}));
|
||||
assert_eq!(r, json!({"sketch": sk, "attachment": "fixed", "frame": "component"}));
|
||||
}
|
||||
|
||||
/// A face of a body that comes before the sketch: the sketch follows it, or stays where the face
|
||||
/// is now with `fixed`.
|
||||
#[test]
|
||||
fn redefine_sketch_onto_a_face_matches_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let sk = s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();
|
||||
let mut run = |p: Value| {
|
||||
let r = s.execute("sketch.redefine", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
let schema = output_schema_for::<RedefineSketchResult>();
|
||||
assert!(r.get("param_warnings").is_none() && conforms(schema.as_value(), schema.as_value(), &r), "{p}: {r}");
|
||||
r
|
||||
};
|
||||
let r = run(json!({"sketch": sk, "plane": {"face": [5, 5, 10]}}));
|
||||
assert_eq!(r["attachment"], "exact_face", "{r}");
|
||||
let r = run(json!({"sketch": sk, "plane": {"face": [5, 5, 10], "body": "Box", "index": 0, "fixed": true}}));
|
||||
assert_eq!(r["attachment"], "fixed", "{r}");
|
||||
}
|
||||
|
||||
/// A moved component: a world plane put into it says so in `note`, which the schema describes.
|
||||
#[test]
|
||||
fn redefine_sketch_note_matches_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let part = run("component.create", json!({"name": "Part", "grounded": false}));
|
||||
let sk = run("sketch.create", json!({"plane": "XY"}))["sketch"].clone();
|
||||
run("occurrence.move", json!({"occurrence": part["occurrence"], "translate": [10, 0, 0]}));
|
||||
let r = run("sketch.redefine", json!({"sketch": sk, "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "author_path": [part["occurrence"]]}));
|
||||
let schema = output_schema_for::<RedefineSketchResult>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
assert_eq!(r["frame"], "world", "{r}");
|
||||
assert!(r["note"].as_str().is_some_and(|n| n.contains("world coordinates")), "{r}");
|
||||
}
|
||||
|
||||
/// A misspelt key still runs in Warn, and says so, with a reply that matches; Strict refuses it.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_for_each_view_command() {
|
||||
let mut s = Session::default();
|
||||
s.execute("view.save", &json!({"camera": CAMERA(), "name": "V"})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let sk = s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();
|
||||
s.param_check = ParamCheck::Warn;
|
||||
let cases: Vec<(&str, Value, &str, schemars::Schema)> = vec![
|
||||
("view.apply", json!({"view": "top", "camra": 1}), "camra", output_schema_for::<CameraReply>()),
|
||||
("view.list", json!({"view": "V"}), "view", output_schema_for::<ViewListResult>()),
|
||||
("view.rename", json!({"view": "V", "name": "W", "nmae": 1}), "nmae", output_schema_for::<ViewRenamed>()),
|
||||
("view.save", json!({"camera": CAMERA(), "name": "X", "nmae": 1}), "nmae", output_schema_for::<ViewSaved>()),
|
||||
("sketch.redefine", json!({"sketch": sk, "plane": "XZ", "frme": "world"}), "frme", output_schema_for::<RedefineSketchResult>()),
|
||||
("view.delete", json!({"view": "X", "vew": 1}), "vew", output_schema_for::<ViewDeleted>()),
|
||||
];
|
||||
for (id, p, key, schema) in cases {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(r["param_warnings"].to_string().contains(key), "{id}: {r}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r}");
|
||||
}
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let error = s.execute("view.apply", &json!({"view": "top", "camra": 1})).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`camra`"), "{error}");
|
||||
}
|
||||
|
||||
/// The commands run exactly as before with the check off, whatever the call (the types only
|
||||
/// describe).
|
||||
#[test]
|
||||
fn the_view_commands_still_read_their_calls_as_before_with_the_check_off() {
|
||||
let mut s = Session::default();
|
||||
s.execute("view.save", &json!({"camera": CAMERA(), "name": 5})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(s.execute("view.list", &json!({"x": 1})).unwrap_or_else(|e| panic!("{e}"))["views"][0]["name"], "Named View1");
|
||||
s.execute("view.apply", &json!({"view": 5, "camera": CAMERA()})).unwrap_or_else(|e| panic!("{e}"));
|
||||
}
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
//! Contracts and result types for the commands in `cmd/component.rs`.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_doc::Occurrence;
|
||||
|
||||
use super::check::{located, whole};
|
||||
use super::component_link::{ComponentRef, component_key, require};
|
||||
use super::types::{IdOrName, Point3, PointExpr3, not_blank_pattern, present};
|
||||
use crate::params;
|
||||
|
||||
@@ -478,658 +473,6 @@ pub struct ReparentItemsResult {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// component.create, from_bodies, activate, list, properties, rename, delete and unlock (#12504).
|
||||
//
|
||||
// The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
// reads it and fails with the handler's message. Whether a component, an occurrence or a body
|
||||
// exists stays the handler's to check. A key the handler refuses when it is left out is optional
|
||||
// in the type and required in the schema, so that the handler's message, not the check's "is
|
||||
// required", is what a caller sees.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `message`, the handler's, for a value that is not a boolean (`null` included).
|
||||
fn flag<'de, D: Deserializer<'de>>(d: D, message: &str) -> Result<Option<bool>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Bool(b) => Ok(Some(b)),
|
||||
_ => Err(D::Error::custom(whole(message))),
|
||||
}
|
||||
}
|
||||
|
||||
fn grounded_flag<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
flag(d, "grounded must be true or false")
|
||||
}
|
||||
|
||||
fn descendants_flag<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
flag(d, "`descendants` must be a boolean")
|
||||
}
|
||||
|
||||
/// A placement path as `component.create` reads `parent_path`: up to 63 occurrence ids (none
|
||||
/// is the design itself).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParentPath(pub Vec<u64>);
|
||||
|
||||
impl<'de> Deserialize<'de> for ParentPath {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?
|
||||
.as_array()
|
||||
.filter(|a| a.len() < 64)
|
||||
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
.map(ParentPath)
|
||||
.ok_or_else(|| D::Error::custom(whole("parent_path must list up to 63 occurrence ids")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ParentPath {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ParentPath".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "An exact placement path: up to 63 occurrence ids from the root down; empty for the design itself.",
|
||||
"type": "array",
|
||||
"items": {"type": "integer", "minimum": 0, "maximum": u64::MAX},
|
||||
"maxItems": 63
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parent<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
|
||||
component_key(d, "parent")
|
||||
}
|
||||
|
||||
fn component<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
|
||||
component_key(d, "component")
|
||||
}
|
||||
|
||||
fn component_required(schema: &mut Schema) {
|
||||
require(schema, "component");
|
||||
}
|
||||
|
||||
/// Make a new component, in the active component unless `parent` says another, and make it the
|
||||
/// active one unless `activate` is false. The design's first part is grounded; the others are
|
||||
/// not. Bodies are not moved here (`component.move_bodies`, `component.from_bodies`).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CreateParams {
|
||||
/// The new component's name. Default: a name made from the design's naming.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
/// The component to put it in, by id or name. Default: the active one.
|
||||
#[serde(default, deserialize_with = "parent", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub parent: Option<ComponentRef>,
|
||||
/// The exact placement of the parent to place it by, as occurrence ids from the top of the
|
||||
/// design (up to 63; none is the design itself). It must belong to the parent. Default: the
|
||||
/// active placement when the parent is the active component, else the parent's first.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ParentPath")]
|
||||
pub parent_path: Option<ParentPath>,
|
||||
/// Make it the active component. Default: `true`.
|
||||
#[serde(default)]
|
||||
pub activate: Option<bool>,
|
||||
/// Ground its placement. Default: `true` for the design's first part, `false` otherwise.
|
||||
#[serde(default, deserialize_with = "grounded_flag", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub grounded: Option<bool>,
|
||||
}
|
||||
|
||||
/// What `component.create` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct CreateResult {
|
||||
/// The new component, by id.
|
||||
pub component: u64,
|
||||
/// Its name.
|
||||
pub name: String,
|
||||
/// The component it is in, by id (0 is the design).
|
||||
pub parent: u64,
|
||||
/// Its placement, by id.
|
||||
pub occurrence: Option<u64>,
|
||||
/// Whether its placement is grounded.
|
||||
pub grounded: bool,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// `component.from_bodies`' `bodies`: a list of body names, each once, as `body_names` reads
|
||||
/// it. The handler also looks each name up in the design.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DefinitionBodies(pub Vec<String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for DefinitionBodies {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let names = Value::deserialize(d)?
|
||||
.as_array()
|
||||
.and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>())
|
||||
.ok_or_else(|| D::Error::custom(whole("bodies must be an array of body names")))?;
|
||||
if names.is_empty() || names.len() > 1000 || names.iter().collect::<BTreeSet<_>>().len() != names.len() {
|
||||
return Err(D::Error::custom(whole("bodies must list 1..1000 distinct existing definition bodies")));
|
||||
}
|
||||
Ok(DefinitionBodies(names))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DefinitionBodies {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DefinitionBodies".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "1 to 1000 different body names.",
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"minItems": 1,
|
||||
"maxItems": 1000,
|
||||
"uniqueItems": true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn bodies_required(schema: &mut Schema) {
|
||||
require(schema, "bodies");
|
||||
}
|
||||
|
||||
/// Make one new component per body, in the active component and named after the body, and move
|
||||
/// each body into its component, keeping it where it is in the world. All or nothing, one undo
|
||||
/// step; refused while the timeline is rolled back.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = bodies_required)]
|
||||
pub struct FromBodiesParams {
|
||||
// Optional in the type and required in the schema (`bodies_required`).
|
||||
/// The bodies, by name.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "DefinitionBodies")]
|
||||
pub bodies: Option<DefinitionBodies>,
|
||||
}
|
||||
|
||||
/// One component `component.from_bodies` made.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyComponent {
|
||||
/// The new component, by id.
|
||||
pub component: u64,
|
||||
/// The body it holds, by name.
|
||||
pub body: String,
|
||||
/// The Body Transfer feature that moved the body, by id.
|
||||
pub feature: u64,
|
||||
}
|
||||
|
||||
/// What `component.from_bodies` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct FromBodiesResult {
|
||||
/// The new components, in the order of `bodies`.
|
||||
pub components: Vec<BodyComponent>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// An occurrence by its id (a number) or its name, as `occurrence` reads it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OccurrenceRef(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for OccurrenceRef {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => Ok(OccurrenceRef(n.to_string())),
|
||||
Value::String(s) => Ok(OccurrenceRef(s)),
|
||||
_ => Err(D::Error::custom(whole("`occurrence` must be an id or name"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for OccurrenceRef {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"OccurrenceRef".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "An occurrence's id (a number) or its name.", "type": ["number", "string"]})
|
||||
}
|
||||
}
|
||||
|
||||
fn activate_schema(schema: &mut Schema) {
|
||||
require(schema, "component");
|
||||
schema.insert("dependentRequired".into(), json!({"path": ["occurrence"]}));
|
||||
}
|
||||
|
||||
/// Make a component the active one: new sketches and features go into it, authored in its
|
||||
/// frame. With `occurrence` (and `path`), the placement that shared geometry is authored
|
||||
/// through. A change of what is active, not an undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = activate_schema)]
|
||||
pub struct ActivateKeys {
|
||||
// Optional in the type and required in the schema (`activate_schema`).
|
||||
/// The component to make active, by id or name (0 or `"root"` for the design).
|
||||
#[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
/// The placement the component is authored in, by id or name, for a component placed more
|
||||
/// than once. Needed when `path` is given.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "OccurrenceRef")]
|
||||
pub occurrence: Option<OccurrenceRef>,
|
||||
/// The occurrence's exact placement, as occurrence ids from the top of the design (1 to 64),
|
||||
/// ending in `occurrence`, and a placement of the component. Default: the occurrence's
|
||||
/// first placement.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "OccurrencePath")]
|
||||
pub path: Option<OccurrencePath>,
|
||||
}
|
||||
|
||||
/// `component.activate`'s parameters: [`ActivateKeys`], with `path` asked to come with
|
||||
/// `occurrence`, as the handler asks.
|
||||
#[derive(Debug)]
|
||||
pub struct ActivateParams(pub ActivateKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ActivateParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let value = Value::deserialize(d)?;
|
||||
let keys: ActivateKeys = serde_path_to_error::deserialize(&value).map_err(|e| D::Error::custom(located(&e)))?;
|
||||
if keys.path.is_some() && keys.occurrence.is_none() {
|
||||
return Err(D::Error::custom(whole("`occurrence` must be an id or name")));
|
||||
}
|
||||
Ok(ActivateParams(keys))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ActivateParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ActivateParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ActivateKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `component.activate` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ActivateResult {
|
||||
/// The active component now, by id.
|
||||
pub active: u64,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// List the components as a tree: each with its bodies, features, sketches, construction planes,
|
||||
/// placements and children, the active component and the pending moves. The design is not
|
||||
/// changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ListKeys {
|
||||
/// Counts of bodies, features, sketches and construction planes instead of their names;
|
||||
/// placements leave out identity transforms; children as occurrence ids. Default: `false`.
|
||||
#[serde(default)]
|
||||
pub compact: Option<bool>,
|
||||
/// With `compact`: body names, not their count. Read only with `compact: true`. Default:
|
||||
/// `false`.
|
||||
#[serde(default)]
|
||||
pub bodies: Option<bool>,
|
||||
}
|
||||
|
||||
/// `component.list`'s parameters: [`ListKeys`], with `bodies` read only when `compact` is true,
|
||||
/// as the handler reads it.
|
||||
#[derive(Debug)]
|
||||
pub struct ListParams(pub ListKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ListParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut()
|
||||
&& keys.get("compact").and_then(Value::as_bool) != Some(true)
|
||||
{
|
||||
keys.remove("bodies");
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ListParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ListParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ListParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ListKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// A placement as `component.list` shows it, in full.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PlacementInfo {
|
||||
/// The occurrence, by id.
|
||||
pub id: u64,
|
||||
/// The component it places, by id.
|
||||
pub component: u64,
|
||||
/// The component it sits in, by id (0 is the design).
|
||||
pub parent: u64,
|
||||
pub name: String,
|
||||
/// Its placement in its parent, as a 4×4 matrix.
|
||||
pub transform: [[f64; 4]; 4],
|
||||
/// Whether it is grounded.
|
||||
pub grounded: bool,
|
||||
}
|
||||
|
||||
impl From<&Occurrence> for PlacementInfo {
|
||||
fn from(o: &Occurrence) -> Self {
|
||||
PlacementInfo { id: o.id, component: o.component, parent: o.parent, name: o.name.clone(), transform: o.transform, grounded: o.grounded }
|
||||
}
|
||||
}
|
||||
|
||||
/// A placement as `compact` `component.list` shows it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct CompactPlacement {
|
||||
/// The occurrence, by id.
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// The component it sits in, by id (0 is the design).
|
||||
pub parent: u64,
|
||||
/// Whether it is grounded.
|
||||
pub grounded: bool,
|
||||
/// Its placement in its parent, as a 4×4 matrix; left out when it is the identity.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub transform: Option<[[f64; 4]; 4]>,
|
||||
}
|
||||
|
||||
/// A placement in a component's `occurrences`: in full, or compact.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum PlacementEntry {
|
||||
Full(PlacementInfo),
|
||||
Compact(CompactPlacement),
|
||||
}
|
||||
|
||||
/// A placement in a component's `children`: in full, or with `compact` its id.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum ChildEntry {
|
||||
Full(PlacementInfo),
|
||||
Id(u64),
|
||||
}
|
||||
|
||||
/// Names, or with `compact` how many there are.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum NamesOrCount {
|
||||
Names(Vec<String>),
|
||||
Count(usize),
|
||||
}
|
||||
|
||||
/// One component of `component.list`; the design itself is the first, with id 0.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ComponentNode {
|
||||
/// The component, by id (0 is the design).
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// The component it is in; null for the design.
|
||||
pub parent: Option<u64>,
|
||||
/// Its bodies by name; with `compact` their count unless `bodies` is true.
|
||||
pub bodies: NamesOrCount,
|
||||
/// Its features other than sketches and construction planes, by name; with `compact` their count.
|
||||
pub features: NamesOrCount,
|
||||
/// Its sketches, by name; with `compact` their count.
|
||||
pub sketches: NamesOrCount,
|
||||
/// Its construction planes, by name; with `compact` their count.
|
||||
pub construction: NamesOrCount,
|
||||
/// Where it is placed.
|
||||
pub occurrences: Vec<PlacementEntry>,
|
||||
/// The placements it holds.
|
||||
pub children: Vec<ChildEntry>,
|
||||
}
|
||||
|
||||
/// What `component.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ListResult {
|
||||
/// The active component, by id.
|
||||
pub active: u64,
|
||||
/// The design and its components.
|
||||
pub components: Vec<ComponentNode>,
|
||||
/// The occurrences with a move not captured yet, by id.
|
||||
pub pending_moves: Vec<u64>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// `about`, a point in mm or `null`, with the handler's message for anything else.
|
||||
fn about<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Point3>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
v => params::vec3(&v).map(|p| Some(Point3(p))).ok_or_else(|| D::Error::custom(whole("`about` must be a point [x, y, z] in mm"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure a component where its first placement puts it (every placement for the design):
|
||||
/// material-aware mass and centre of mass in world coordinates, volume, density, and inertia
|
||||
/// for closed, consistently oriented bodies, with totals and principal moments. Pending moves
|
||||
/// are included. The design is not changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PropertiesParams {
|
||||
/// The component, by id or name. Default: the active component.
|
||||
#[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
/// Include the components and placements inside it. Default: `true`.
|
||||
#[serde(default, deserialize_with = "descendants_flag", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub descendants: Option<bool>,
|
||||
/// A point in mm, also given the total inertia about it (`total.inertia_about`).
|
||||
#[serde(default, deserialize_with = "about", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<Point3>")]
|
||||
pub about: Option<Point3>,
|
||||
}
|
||||
|
||||
/// A body's box, in world coordinates (mm).
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BoundingBox {
|
||||
#[schemars(with = "[f64; 3]")]
|
||||
pub min: Vec3,
|
||||
#[schemars(with = "[f64; 3]")]
|
||||
pub max: Vec3,
|
||||
}
|
||||
|
||||
/// One body's measurements at one placement. Volume, density, mass, centre of mass and inertia
|
||||
/// are null for a body that is not closed.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyProperties {
|
||||
pub name: String,
|
||||
/// The component it belongs to, by id.
|
||||
pub component: u64,
|
||||
/// The placement it is measured at, as occurrence ids from the top.
|
||||
pub path: Vec<u64>,
|
||||
/// Its material's name.
|
||||
pub material: String,
|
||||
/// Whether it is closed and consistently oriented.
|
||||
pub closed: bool,
|
||||
pub density_g_cm3: Option<f64>,
|
||||
pub mass_g: Option<f64>,
|
||||
pub volume_mm3: Option<f64>,
|
||||
pub area_mm2: f64,
|
||||
/// Its centre of mass, in world coordinates (mm).
|
||||
#[schemars(with = "Option<[f64; 3]>")]
|
||||
pub center_of_mass: Option<Vec3>,
|
||||
/// The inertia tensor about its centre of mass, in world axes (g·mm²).
|
||||
pub inertia_g_mm2: Option<[[f64; 3]; 3]>,
|
||||
pub bbox: BoundingBox,
|
||||
}
|
||||
|
||||
/// The inertia about the point `about` asked for.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct InertiaAbout {
|
||||
/// The point, in mm.
|
||||
#[schemars(with = "[f64; 3]")]
|
||||
pub point: Vec3,
|
||||
/// The total inertia tensor about it (g·mm²); null when it is not known.
|
||||
pub inertia_g_mm2: Option<[[f64; 3]; 3]>,
|
||||
}
|
||||
|
||||
/// The totals of a physical-properties measurement, over the closed bodies unless said.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct TotalProperties {
|
||||
/// How many open bodies are left out of the volume and mass totals.
|
||||
pub open_bodies_skipped: usize,
|
||||
pub volume_mm3: f64,
|
||||
/// The area of all bodies, closed or not.
|
||||
pub area_mm2: f64,
|
||||
pub mass_g: f64,
|
||||
/// The centre of mass (mm); null when the mass is zero.
|
||||
#[schemars(with = "Option<[f64; 3]>")]
|
||||
pub center_of_mass: Option<Vec3>,
|
||||
/// Mass times centre of mass (g·mm).
|
||||
#[schemars(with = "[f64; 3]")]
|
||||
pub first_moment_g_mm: Vec3,
|
||||
/// The inertia tensor about the centre of mass, in world axes (g·mm²); null when it is not known.
|
||||
pub inertia_g_mm2: Option<[[f64; 3]; 3]>,
|
||||
/// The principal moments, smallest first (g·mm²).
|
||||
pub principal_moments_g_mm2: Option<[f64; 3]>,
|
||||
/// The principal axes: unit vectors, right-handed.
|
||||
#[schemars(with = "Option<[[f64; 3]; 3]>")]
|
||||
pub principal_axes: Option<[Vec3; 3]>,
|
||||
/// The box around all bodies; null when there are none.
|
||||
pub bbox: Option<BoundingBox>,
|
||||
pub faces: usize,
|
||||
pub edges: usize,
|
||||
pub vertices: usize,
|
||||
/// With `about`: the inertia about that point.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub inertia_about: Option<InertiaAbout>,
|
||||
}
|
||||
|
||||
/// Physical properties of a placement and what it holds, in world coordinates.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PhysicalProperties {
|
||||
/// The placement measured, as occurrence ids from the top; empty for the design.
|
||||
pub path: Vec<u64>,
|
||||
/// Always `world`.
|
||||
pub coordinate_frame: String,
|
||||
/// Whether what is inside the placement is included.
|
||||
pub descendants: bool,
|
||||
pub placement_count: usize,
|
||||
pub body_count: usize,
|
||||
pub bodies: Vec<BodyProperties>,
|
||||
pub total: TotalProperties,
|
||||
}
|
||||
|
||||
/// What `component.properties` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PropertiesResult {
|
||||
/// The component, by id.
|
||||
pub component: u64,
|
||||
pub name: String,
|
||||
#[serde(flatten)]
|
||||
pub properties: PhysicalProperties,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The new name `component.rename` reads: text of 1 to 128 bytes once trimmed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ComponentName(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for ComponentName {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) if !s.trim().is_empty() && s.trim().len() <= 128 => Ok(ComponentName(s)),
|
||||
_ => Err(D::Error::custom(whole("`name` must be 1…128 characters"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ComponentName {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ComponentName".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Text with something in it; once surrounding blanks are cut, at most 128 bytes.",
|
||||
"type": "string",
|
||||
"pattern": not_blank_pattern()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn rename_schema(schema: &mut Schema) {
|
||||
require(schema, "component");
|
||||
require(schema, "name");
|
||||
}
|
||||
|
||||
/// Rename a component, or the design itself (id 0). Placements still named after it follow.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = rename_schema)]
|
||||
pub struct RenameParams {
|
||||
// Optional in the type and required in the schema (`rename_schema`).
|
||||
/// The component, by id or name (0 or `"root"` for the design).
|
||||
#[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
/// The new name.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentName")]
|
||||
pub name: Option<ComponentName>,
|
||||
}
|
||||
|
||||
/// What `component.rename` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct RenameResult {
|
||||
/// The component, by id.
|
||||
pub component: u64,
|
||||
/// Its name now, trimmed.
|
||||
pub name: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Delete a component with its subcomponents, placements and features. Refused for the design
|
||||
/// itself, and for a tree that supplies a body transfer recorded outside it.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = component_required)]
|
||||
pub struct DeleteParams {
|
||||
// Optional in the type and required in the schema (`component_required`).
|
||||
/// The component, by id or name.
|
||||
#[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
}
|
||||
|
||||
/// What `component.delete` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DeleteResult {
|
||||
/// The components removed, by id: it and everything inside it.
|
||||
pub deleted: Vec<u64>,
|
||||
/// The features that were inside them, by id.
|
||||
pub features: Vec<u64>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Remove the rigid joints that hold a component's contents together (an imported assembly's
|
||||
/// rigid group), so its parts move and take joints one by one. Refused for the design and when
|
||||
/// nothing holds the contents together.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = component_required)]
|
||||
pub struct UnlockParams {
|
||||
// Optional in the type and required in the schema (`component_required`).
|
||||
/// The component, by id or name.
|
||||
#[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
}
|
||||
|
||||
/// What `component.unlock` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct UnlockResult {
|
||||
/// The component, by id.
|
||||
pub component: u64,
|
||||
/// The joints removed, by id.
|
||||
pub joints: Vec<u64>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "component_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -52,7 +52,7 @@ impl JsonSchema for ComponentRef {
|
||||
|
||||
/// `key`, a component's id or name, with the handler's message for anything else, `null`
|
||||
/// included.
|
||||
pub(super) fn component_key<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result<Option<ComponentRef>, D::Error> {
|
||||
fn component_key<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result<Option<ComponentRef>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => Ok(Some(ComponentRef(n.to_string()))),
|
||||
Value::String(s) => Ok(Some(ComponentRef(s))),
|
||||
@@ -95,7 +95,7 @@ fn path_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
|
||||
/// Adds `key` to the schema's `required` list: for a key the type has optional so that the
|
||||
/// handler, not the check, refuses it when it's left out.
|
||||
pub(super) fn require(schema: &mut Schema, key: &str) {
|
||||
fn require(schema: &mut Schema, key: &str) {
|
||||
match schema.get_mut("required") {
|
||||
Some(Value::Array(required)) => {
|
||||
if !required.iter().any(|k| k == key) {
|
||||
|
||||
@@ -4,12 +4,11 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
ActivateParams, ActivateResult, CreateParams, CreateResult, DeleteParams, DeleteResult, EditInPlaceParams, FinishEditParams, FromBodiesParams,
|
||||
FromBodiesResult, ListParams, ListResult, MoveFeaturesParams, MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult,
|
||||
PropertiesParams, PropertiesResult, RenameParams, RenameResult, ReparentItemsParams, UnlockParams, UnlockResult,
|
||||
EditInPlaceParams, FinishEditParams, MoveFeaturesParams, MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult,
|
||||
ReparentItemsParams,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::tests::{assert_keys, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
#[test]
|
||||
@@ -37,340 +36,6 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<MoveFeaturesParams>(), &["component", "features"]);
|
||||
assert_keys(input_schema_for::<MoveSketchesToPartsParams>(), &["sketches"]);
|
||||
assert_keys(input_schema_for::<ReparentItemsParams>(), &["bodies", "component", "component_path", "features", "occurrences"]);
|
||||
assert_keys(input_schema_for::<CreateParams>(), &["activate", "grounded", "name", "parent", "parent_path"]);
|
||||
assert_keys(input_schema_for::<FromBodiesParams>(), &["bodies"]);
|
||||
assert_keys(input_schema_for::<ActivateParams>(), &["component", "occurrence", "path"]);
|
||||
assert_keys(input_schema_for::<ListParams>(), &["bodies", "compact"]);
|
||||
assert_keys(input_schema_for::<PropertiesParams>(), &["about", "component", "descendants"]);
|
||||
assert_keys(input_schema_for::<RenameParams>(), &["component", "name"]);
|
||||
assert_keys(input_schema_for::<DeleteParams>(), &["component"]);
|
||||
assert_keys(input_schema_for::<UnlockParams>(), &["component"]);
|
||||
}
|
||||
|
||||
/// The calls these commands already refuse (the handlers' own messages), refused alike in strict.
|
||||
/// An unknown key to `component.create` is left out: its handler lists the accepted parameters,
|
||||
/// where strict gives the check's `unknown key` with a suggestion (refused either way).
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("component.create", json!({"parent": null})),
|
||||
("component.create", json!({"parent": true})),
|
||||
("component.create", json!({"parent": [1]})),
|
||||
("component.create", json!({"parent": "Nope"})),
|
||||
("component.create", json!({"parent_path": "1"})),
|
||||
("component.create", json!({"parent_path": null})),
|
||||
("component.create", json!({"parent_path": [1, "a"]})),
|
||||
("component.create", json!({"parent_path": vec![1; 64]})),
|
||||
("component.create", json!({"grounded": "yes"})),
|
||||
("component.create", json!({"grounded": null})),
|
||||
("component.from_bodies", json!({})),
|
||||
("component.from_bodies", json!({"bodies": null})),
|
||||
("component.from_bodies", json!({"bodies": "Box"})),
|
||||
("component.from_bodies", json!({"bodies": [1]})),
|
||||
("component.from_bodies", json!({"bodies": []})),
|
||||
("component.from_bodies", json!({"bodies": ["A", "A"]})),
|
||||
("component.from_bodies", json!({"bodies": vec!["A"; 1001]})),
|
||||
("component.from_bodies", json!({"bodies": ["Nope"]})),
|
||||
("component.activate", json!({})),
|
||||
("component.activate", json!({"component": null})),
|
||||
("component.activate", json!({"component": [1]})),
|
||||
("component.activate", json!({"component": "Nope"})),
|
||||
("component.activate", json!({"component": 0, "path": [1]})),
|
||||
("component.activate", json!({"component": 0, "occurrence": null})),
|
||||
("component.activate", json!({"component": 0, "occurrence": true})),
|
||||
("component.properties", json!({"component": null})),
|
||||
("component.properties", json!({"component": true})),
|
||||
("component.properties", json!({"descendants": "yes"})),
|
||||
("component.properties", json!({"descendants": null})),
|
||||
("component.properties", json!({"about": [1, 2]})),
|
||||
("component.properties", json!({"about": "origin"})),
|
||||
("component.properties", json!({"about": [1, 2, 1e9]})),
|
||||
("component.rename", json!({})),
|
||||
("component.rename", json!({"component": 0})),
|
||||
("component.rename", json!({"name": "A"})),
|
||||
("component.rename", json!({"component": null, "name": "A"})),
|
||||
("component.rename", json!({"component": 0, "name": ""})),
|
||||
("component.rename", json!({"component": 0, "name": " \t "})),
|
||||
("component.rename", json!({"component": 0, "name": 5})),
|
||||
("component.rename", json!({"component": 0, "name": null})),
|
||||
("component.rename", json!({"component": 0, "name": "x".repeat(129)})),
|
||||
("component.delete", json!({})),
|
||||
("component.delete", json!({"component": false})),
|
||||
("component.delete", json!({"component": 0})),
|
||||
("component.unlock", json!({})),
|
||||
("component.unlock", json!({"component": [0]})),
|
||||
("component.unlock", json!({"component": 0})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A name of 128 bytes is taken once trimmed, and one of 129 is not, as the handler counts.
|
||||
#[test]
|
||||
fn a_name_is_counted_as_the_handler_counts_it() {
|
||||
let issues = |p: Value| crate::schema::issues("component.rename", &p).len();
|
||||
assert_eq!(issues(json!({"component": 0, "name": format!(" {} ", "x".repeat(128))})), 0);
|
||||
assert_eq!(issues(json!({"component": 0, "name": "x".repeat(129)})), 1);
|
||||
// 64 two-byte characters are 128 bytes.
|
||||
assert_eq!(issues(json!({"component": 0, "name": "é".repeat(64)})), 0);
|
||||
assert_eq!(issues(json!({"component": 0, "name": "é".repeat(65)})), 1);
|
||||
}
|
||||
|
||||
/// The contracts say what the handlers need: a key a handler refuses without is required in the
|
||||
/// schema, though the type leaves it to the handler's message.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<CreateParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"name": "Arm", "parent": "Frame", "parent_path": [1, 2], "activate": false, "grounded": true}), true),
|
||||
(json!({"parent": 3, "parent_path": []}), true),
|
||||
(json!({"parent": true}), false),
|
||||
(json!({"parent_path": vec![1; 64]}), false),
|
||||
(json!({"grounded": "yes"}), false),
|
||||
(json!({"bodies": ["A"]}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<FromBodiesParams>(),
|
||||
&[
|
||||
(json!({"bodies": ["A", "B"]}), true),
|
||||
(json!({}), false),
|
||||
(json!({"bodies": []}), false),
|
||||
(json!({"bodies": ["A", "A"]}), false),
|
||||
(json!({"bodies": "A"}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ActivateParams>(),
|
||||
&[
|
||||
(json!({"component": 0}), true),
|
||||
(json!({"component": "root"}), true),
|
||||
(json!({"component": "Arm", "occurrence": "Arm:2", "path": [1, 2]}), true),
|
||||
(json!({"component": "Arm", "occurrence": 2}), true),
|
||||
(json!({}), false),
|
||||
(json!({"component": true}), false),
|
||||
(json!({"component": 1, "occurrence": true}), false),
|
||||
(json!({"component": 1, "path": []}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ListParams>(),
|
||||
&[(json!({}), true), (json!({"compact": true, "bodies": true}), true), (json!({"compact": "yes"}), false)],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<PropertiesParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"component": "Arm", "descendants": false, "about": [1, 2, 3]}), true),
|
||||
(json!({"about": {"x": 1, "y": 2, "z": 3}}), true),
|
||||
(json!({"about": [1, 2]}), false),
|
||||
(json!({"descendants": 1}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<RenameParams>(),
|
||||
&[(json!({"component": "Arm", "name": "Bar"}), true), (json!({"component": "Arm"}), false), (json!({"name": "Bar"}), false)],
|
||||
);
|
||||
// `conforms` doesn't read patterns: pin the text that keeps blank names out.
|
||||
let rename = input_schema_for::<RenameParams>();
|
||||
assert_eq!(rename.as_value()["$defs"]["ComponentName"]["pattern"], crate::schema::types::not_blank_pattern());
|
||||
takes(input_schema_for::<DeleteParams>(), &[(json!({"component": 2}), true), (json!({}), false)]);
|
||||
takes(input_schema_for::<UnlockParams>(), &[(json!({"component": "rig"}), true), (json!({}), false)]);
|
||||
}
|
||||
|
||||
/// Keys the handlers read only in some cases are read only in those cases: `bodies` of
|
||||
/// `component.list` with `compact`, `path` of `component.activate` with `occurrence`. And the
|
||||
/// warnings say what is wrong with a key.
|
||||
#[test]
|
||||
fn the_check_reads_keys_as_the_handlers_do() {
|
||||
let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
let none = Vec::<String>::new();
|
||||
assert_eq!(issues("component.list", json!({"bodies": "x"})), none);
|
||||
assert_eq!(issues("component.list", json!({"compact": false, "bodies": 3})), none);
|
||||
assert_eq!(issues("component.list", json!({"compact": true, "bodies": true})), none);
|
||||
assert_eq!(issues("component.list", json!({"compact": true, "bodies": "x"})).len(), 1);
|
||||
assert_eq!(issues("component.list", json!({"compact": "x"})).len(), 1);
|
||||
assert_eq!(issues("component.list", json!({"compat": true})), ["unknown key `compat`; did you mean `compact`?"]);
|
||||
assert_eq!(issues("component.activate", json!({"component": 1, "occurrence": 2})), none);
|
||||
assert_eq!(issues("component.activate", json!({"component": 1, "occurrence": 2, "path": [1, 2]})), none);
|
||||
assert_eq!(issues("component.activate", json!({"component": 1, "path": [2]})), ["`occurrence` must be an id or name"]);
|
||||
assert_eq!(issues("component.activate", json!({"component": 1, "occurrence": 2, "path": []})), ["`path` must list 1..64 occurrence ids"]);
|
||||
assert_eq!(issues("component.activate", json!({"component": 1, "occurrence": null})), ["`occurrence` must be an id or name"]);
|
||||
assert_eq!(issues("component.create", json!({"parent": true})), ["`parent` must be a component id or name"]);
|
||||
assert_eq!(issues("component.create", json!({"parent_path": [1, null]})), ["parent_path must list up to 63 occurrence ids"]);
|
||||
assert_eq!(issues("component.create", json!({"grounded": 1})), ["grounded must be true or false"]);
|
||||
assert_eq!(issues("component.create", json!({"parent_path": vec![1; 63]})), none);
|
||||
assert_eq!(issues("component.create", json!({"parent_path": vec![1; 64]})), ["parent_path must list up to 63 occurrence ids"]);
|
||||
assert_eq!(issues("component.create", json!({"activate": "no"})).len(), 1);
|
||||
assert_eq!(issues("component.from_bodies", json!({"bodies": [1]})), ["bodies must be an array of body names"]);
|
||||
assert_eq!(issues("component.from_bodies", json!({"bodies": ["a", "a"]})), ["bodies must list 1..1000 distinct existing definition bodies"]);
|
||||
assert_eq!(issues("component.properties", json!({"about": [1]})), ["`about` must be a point [x, y, z] in mm"]);
|
||||
assert_eq!(issues("component.properties", json!({"about": null})), none);
|
||||
assert_eq!(issues("component.properties", json!({"descendants": null})), ["`descendants` must be a boolean"]);
|
||||
assert_eq!(issues("component.properties", json!({"component": null})), ["`component` must be a component id or name"]);
|
||||
assert_eq!(issues("component.rename", json!({"component": 0, "name": ""})), ["`name` must be 1…128 characters"]);
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// A glTF file whose node `rig` holds a `Part` (one cube): imported, it is a component held
|
||||
/// together by a rigid group that `component.unlock` releases.
|
||||
fn rig_file(name: &str) -> String {
|
||||
let side = 0.01f32;
|
||||
let points: Vec<[f32; 3]> = (0..8).map(|i| [(i & 1) as f32 * side, ((i >> 1) & 1) as f32 * side, ((i >> 2) & 1) as f32 * side]).collect();
|
||||
let tris: [u16; 36] = [0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 1, 4, 1, 5, 4, 2, 6, 3, 3, 6, 7, 0, 4, 2, 2, 4, 6, 1, 3, 5, 3, 7, 5];
|
||||
let mut bin: Vec<u8> = points.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
|
||||
bin.extend(tris.iter().flat_map(|v| v.to_le_bytes()));
|
||||
let doc = json!({
|
||||
"asset": {"version": "2.0"},
|
||||
"scene": 0,
|
||||
"scenes": [{"nodes": [0]}],
|
||||
"nodes": [{"name": "Base", "mesh": 0, "children": [1]}, {"name": "Arm", "mesh": 1, "translation": [0.0, 0.05, 0.0]}],
|
||||
"meshes": [{"name": "Block", "primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]},
|
||||
{"name": "Peg", "primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]}],
|
||||
"accessors": [
|
||||
{"bufferView": 0, "componentType": 5126, "count": 8, "type": "VEC3", "min": [0.0, 0.0, 0.0], "max": [side, side, side]},
|
||||
{"bufferView": 1, "componentType": 5123, "count": 36, "type": "SCALAR"},
|
||||
],
|
||||
"bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 96}, {"buffer": 0, "byteOffset": 96, "byteLength": 72}],
|
||||
"buffers": [{"byteLength": bin.len()}],
|
||||
});
|
||||
let path = std::env::temp_dir().join(format!("solidcraft-component-schema-{}-{name}.glb", std::process::id()));
|
||||
std::fs::write(&path, solidcraft_io::glb_container(doc.to_string().as_bytes(), &bin)).unwrap_or_else(|e| panic!("{e}"));
|
||||
path.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// Every command, in each form it takes, in Warn: the real reply matches its output schema and
|
||||
/// carries no `param_warnings` (Warn runs a call the contract refuses anyway, so the replies
|
||||
/// are also checked for warnings), and a key spelt wrongly on purpose is reported.
|
||||
#[test]
|
||||
fn replies_match_the_output_schemas_of_the_component_commands() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
|
||||
let arm = run("component.create", json!({"name": "Arm"}));
|
||||
assert_eq!(arm["name"], "Arm");
|
||||
assert_eq!(arm["grounded"], true, "the design's first part is grounded: {arm}");
|
||||
matches(output_schema_for::<CreateResult>(), "component.create", &arm);
|
||||
run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "ArmBox"}));
|
||||
let hand = run("component.create", json!({"name": "Hand", "parent": "Arm", "activate": false, "grounded": false}));
|
||||
assert!(hand["parent"] == arm["component"] && hand["grounded"] == false, "{hand}");
|
||||
matches(output_schema_for::<CreateResult>(), "component.create", &hand);
|
||||
let at = run("component.create", json!({"name": "Thumb", "parent": hand["parent"], "parent_path": [arm["occurrence"]]}));
|
||||
matches(output_schema_for::<CreateResult>(), "component.create", &at);
|
||||
let top = run("component.create", json!({"name": "Top", "parent": 0, "parent_path": []}));
|
||||
matches(output_schema_for::<CreateResult>(), "component.create", &top);
|
||||
|
||||
let active = run("component.activate", json!({"component": "root"}));
|
||||
assert_eq!(active["active"], 0);
|
||||
matches(output_schema_for::<ActivateResult>(), "component.activate", &active);
|
||||
let active = run("component.activate", json!({"component": arm["component"]}));
|
||||
matches(output_schema_for::<ActivateResult>(), "component.activate", &active);
|
||||
let active = run("component.activate", json!({"component": "Arm", "occurrence": arm["occurrence"], "path": [arm["occurrence"]]}));
|
||||
assert_eq!(active["active"], arm["component"], "{active}");
|
||||
matches(output_schema_for::<ActivateResult>(), "component.activate", &active);
|
||||
|
||||
run("solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "RootBox"}));
|
||||
run("solid.box", json!({"length": 6, "width": 6, "height": 6, "body_name": "RootBox2", "operation": "new"}));
|
||||
let made = run("component.from_bodies", json!({"bodies": ["RootBox", "RootBox2"]}));
|
||||
assert_eq!(made["components"].as_array().map(Vec::len), Some(2), "{made}");
|
||||
matches(output_schema_for::<FromBodiesResult>(), "component.from_bodies", &made);
|
||||
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"compact": true}),
|
||||
json!({"compact": true, "bodies": true}),
|
||||
json!({"compact": false, "bodies": "ignored"}),
|
||||
json!({"bodies": true}),
|
||||
] {
|
||||
let listed = run("component.list", p.clone());
|
||||
matches(output_schema_for::<ListResult>(), "component.list", &listed);
|
||||
assert!(listed["components"].as_array().is_some_and(|c| c.len() >= 5), "{p}: {listed}");
|
||||
}
|
||||
let moved = run("occurrence.move", json!({"occurrence": hand["occurrence"], "translate": [5, 0, 0], "capture": false, "move_grounded": true}));
|
||||
assert_eq!(moved["pending"], true, "{moved}");
|
||||
run("occurrence.move", json!({"occurrence": top["occurrence"], "translate": [0, 7, 0], "move_grounded": true}));
|
||||
let listed = run("component.list", json!({"compact": true}));
|
||||
assert!(listed["pending_moves"].as_array().is_some_and(|m| !m.is_empty()), "{listed}");
|
||||
// Compact placements carry `transform` only when it is not the identity.
|
||||
let placements: Vec<&Value> =
|
||||
listed["components"].as_array().into_iter().flatten().flat_map(|c| c["occurrences"].as_array().into_iter().flatten()).collect();
|
||||
assert!(placements.iter().any(|o| o.get("transform").is_some()) && placements.iter().any(|o| o.get("transform").is_none()), "{listed}");
|
||||
matches(output_schema_for::<ListResult>(), "component.list", &listed);
|
||||
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"component": "Arm"}),
|
||||
json!({"component": 0, "descendants": false}),
|
||||
json!({"component": "root", "about": [10, 0, 0]}),
|
||||
json!({"about": {"x": 1, "y": 2, "z": 3}, "descendants": true}),
|
||||
json!({"about": null}),
|
||||
json!({"component": "Top"}),
|
||||
] {
|
||||
let measured = run("component.properties", p.clone());
|
||||
matches(output_schema_for::<PropertiesResult>(), "component.properties", &measured);
|
||||
assert_eq!(measured["coordinate_frame"], "world", "{p}");
|
||||
assert_eq!(measured["total"].get("inertia_about").is_some(), p.get("about").is_some_and(|a| !a.is_null()), "{p}: {measured}");
|
||||
}
|
||||
let measured = run("component.properties", json!({"component": 0}));
|
||||
assert!(measured["body_count"].as_u64().is_some_and(|n| n >= 3) && measured["total"]["bbox"].is_object(), "{measured}");
|
||||
let empty = run("component.properties", json!({"component": "Top"}));
|
||||
assert!(empty["total"]["bbox"].is_null() && empty["total"]["center_of_mass"].is_null(), "{empty}");
|
||||
|
||||
let renamed = run("component.rename", json!({"component": "Hand", "name": " Palm "}));
|
||||
assert_eq!(renamed["name"], "Palm");
|
||||
matches(output_schema_for::<RenameResult>(), "component.rename", &renamed);
|
||||
let renamed = run("component.rename", json!({"component": 0, "name": "Whole"}));
|
||||
matches(output_schema_for::<RenameResult>(), "component.rename", &renamed);
|
||||
|
||||
let deleted = run("component.delete", json!({"component": "Arm"}));
|
||||
assert!(deleted["deleted"].as_array().is_some_and(|d| d.len() >= 3), "{deleted}");
|
||||
matches(output_schema_for::<DeleteResult>(), "component.delete", &deleted);
|
||||
|
||||
// Unlock: a glTF node tree is held together by a rigid group.
|
||||
let inserted = run("file.insert_mesh", json!({"path": rig_file("rig"), "up": "z"}));
|
||||
let rig = inserted["component"].clone();
|
||||
let unlocked = run("component.unlock", json!({"component": rig}));
|
||||
assert!(unlocked["joints"].as_array().is_some_and(|j| !j.is_empty()), "{unlocked}");
|
||||
matches(output_schema_for::<UnlockResult>(), "component.unlock", &unlocked);
|
||||
|
||||
// Misspelt keys still run in Warn, say so, and the reply still matches.
|
||||
let cases: [(&str, Value, &str, schemars::Schema); 3] = [
|
||||
("component.list", json!({"compat": true}), "compat", output_schema_for::<ListResult>()),
|
||||
("component.properties", json!({"descendents": false}), "descendents", output_schema_for::<PropertiesResult>()),
|
||||
("component.rename", json!({"component": 0, "nmae": "x", "name": "Again"}), "nmae", output_schema_for::<RenameResult>()),
|
||||
];
|
||||
for (id, p, key, schema) in cases {
|
||||
let warned = run(id, p);
|
||||
let warnings = warned["param_warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains(key)), "{id}: {warned}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{id}: {warned}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An unknown key is refused by `component.create` as before (its own message lists the
|
||||
/// accepted parameters), at every check level but strict, where the check names the key first.
|
||||
#[test]
|
||||
fn create_refuses_an_unknown_key_as_before() {
|
||||
for level in ParamCheck::ALL {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
let e = s.execute("component.create", &json!({"nme": "A"})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `nme`") ^ (level == ParamCheck::Strict), "{level:?}: {e}");
|
||||
assert!(e.contains("nme"), "{e}");
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let e = s.execute("component.create", &json!({"bodies": ["A"]})).unwrap_err().to_string();
|
||||
assert!(e.contains("use component.move_bodies or component.from_bodies"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,656 +0,0 @@
|
||||
//! Contracts and result types for the commands in `cmd/frame.rs`: `frame.member`,
|
||||
//! `frame.profile.list`, `frame.profile.properties` and `frame.profile.insert` (#12500).
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. Whether a sketch exists, a dimension evaluates
|
||||
//! or a profile can be built stays the handler's to check. A key the handler refuses when it is
|
||||
//! left out (`profile`, `sketch`) is optional in the type and required in the schema, so that the
|
||||
//! handler's message, not the check's "is required", is what a caller sees. A call with several
|
||||
//! problems may get a different one first in strict than with the check off (the check goes key
|
||||
//! by key, the handlers in their own order).
|
||||
//!
|
||||
//! `frame.member` reads some keys only in some cases. With `profile` (a built-in profile) it
|
||||
//! never reads `profiles` or `exact_regions`, which pick among a section sketch's profiles; with
|
||||
//! `profile_sketch` it never reads `profile`. Given both, or neither, it refuses the call before
|
||||
//! it reads anything about the section, so none of the three is read then either.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use solidcore_record::Vec2;
|
||||
use solidcraft_doc::Expr;
|
||||
use solidcraft_doc::frame::{self, Anchor, MAX_MEMBERS, Profile, ProfileSpec};
|
||||
|
||||
use super::check::{keyed, located, whole};
|
||||
use super::motion::require;
|
||||
use super::sketch_ends::SketchTarget;
|
||||
use super::types::{AngleExpr, Point2, ProfilesParam, SketchRef, StringList, not_blank_pattern, present};
|
||||
use crate::params;
|
||||
|
||||
/// The words `Anchor` is spelled with, as the handlers' message lists them.
|
||||
const ANCHORS: [&str; 11] =
|
||||
["origin", "center", "centroid", "top_left", "top", "top_right", "left", "right", "bottom_left", "bottom", "bottom_right"];
|
||||
|
||||
/// The longest name a member may be given, in bytes once trimmed, as the handler requires.
|
||||
const MAX_NAME: usize = 128;
|
||||
|
||||
/// `v` as the only key of an object, for the helpers that read `p.get(key)`.
|
||||
fn wrap(key: &str, v: Value) -> Value {
|
||||
json!({ key: v })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Shared types
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// A built-in profile as the commands take it: `{kind, …dimensions}`, each dimension a number or
|
||||
/// an expression, read by `ProfileSpec`'s own deserializer. Whether a dimension evaluates, and
|
||||
/// whether the profile can be built from the values (a wall thicker than the tube), is the
|
||||
/// handler's to check, as it has the design.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ProfileParam(pub ProfileSpec);
|
||||
|
||||
impl<'de> Deserialize<'de> for ProfileParam {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
// The handler's `` `profile`: {error} ``, with serde_json's own wording of the error.
|
||||
serde_json::from_value::<ProfileSpec>(Value::deserialize(d)?).map(ProfileParam).map_err(|e| D::Error::custom(keyed(e)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The schema of one dimension, a number or an expression.
|
||||
fn dimension_schema() -> Value {
|
||||
json!({
|
||||
"anyOf": [
|
||||
{"type": "number"},
|
||||
{"type": "string", "minLength": 1, "maxLength": 4096, "pattern": not_blank_pattern()}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/// One schema per built-in profile kind: its `kind`, its required dimensions and its optional
|
||||
/// ones, each as `dimension` says, and nothing else.
|
||||
fn profile_kinds_schema(dimension: &Value) -> Vec<Value> {
|
||||
frame::profile_kinds()
|
||||
.into_iter()
|
||||
.map(|k| {
|
||||
let mut properties = Map::new();
|
||||
properties.insert("kind".into(), json!({"enum": [k.kind]}));
|
||||
for name in k.required.iter().chain(k.optional) {
|
||||
properties.insert((*name).into(), dimension.clone());
|
||||
}
|
||||
let required: Vec<&str> = std::iter::once("kind").chain(k.required.iter().copied()).collect();
|
||||
json!({"type": "object", "properties": properties, "required": required, "additionalProperties": false})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl JsonSchema for ProfileParam {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ProfileParam".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A built-in profile: {\"kind\": bar | round_bar | rect_tube | round_tube | angle | channel | i_beam, …its dimensions}. Each dimension is a number in the design's units or a length expression over its parameters (\"tube_wall\", \"2 in\"); `frame.profile.list` gives each kind's dimensions and an example. A dimension that is left out and isn't required takes a default worked out from the profile's size.",
|
||||
"anyOf": profile_kinds_schema(&dimension_schema())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A built-in profile as a command reports it, every number in mm: serialized as the profile's
|
||||
/// own JSON (`{kind, …dimensions}`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ProfileOut(pub Profile);
|
||||
|
||||
impl JsonSchema for ProfileOut {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ProfileOut".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A built-in profile: {\"kind\", …its dimensions}, each in mm.",
|
||||
"anyOf": profile_kinds_schema(&json!({"type": "number"}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a profile is held to its placement point, as `Anchor` is spelled in JSON.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct AnchorParam(pub Anchor);
|
||||
|
||||
impl<'de> Deserialize<'de> for AnchorParam {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
serde_json::from_value::<Anchor>(Value::deserialize(d)?).map(AnchorParam).map_err(|_| {
|
||||
D::Error::custom(whole(
|
||||
"`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right",
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for AnchorParam {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"AnchorParam".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The profile point that is placed: its origin (the default; a built-in profile's centre), `center` (its bounding box's centre), `centroid`, or a corner or edge middle of its bounding box.",
|
||||
"type": "string",
|
||||
"enum": ANCHORS
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// frame.profile.list
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `frame.profile.list` takes no parameters.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ProfileListParams {}
|
||||
|
||||
/// One built-in profile kind.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProfileKindInfo {
|
||||
/// The kind's id, as `profile.kind` takes it.
|
||||
pub kind: String,
|
||||
/// The kind's name for people.
|
||||
pub label: String,
|
||||
/// The dimensions it needs.
|
||||
pub required: Vec<String>,
|
||||
/// The dimensions that default when left out.
|
||||
pub optional: Vec<String>,
|
||||
/// A complete example profile.
|
||||
pub example: ProfileOut,
|
||||
}
|
||||
|
||||
impl From<&frame::ProfileKind> for ProfileKindInfo {
|
||||
fn from(k: &frame::ProfileKind) -> Self {
|
||||
ProfileKindInfo {
|
||||
kind: k.kind.to_string(),
|
||||
label: k.label.to_string(),
|
||||
required: k.required.iter().map(|d| d.to_string()).collect(),
|
||||
optional: k.optional.iter().map(|d| d.to_string()).collect(),
|
||||
example: ProfileOut(k.example.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `frame.profile.list` returns: the built-in profiles, each SolidCraft's own parametric
|
||||
/// definition.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProfileListResult {
|
||||
/// Every built-in profile kind.
|
||||
pub kinds: Vec<ProfileKindInfo>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// frame.profile.properties and the section both profile commands report
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// A density in kg/m³: above 0 and at most 1e6, as `frame.profile.properties` requires.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Density(pub f64);
|
||||
|
||||
impl<'de> Deserialize<'de> for Density {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::num(&wrap("density", Value::deserialize(d)?), "density")
|
||||
.filter(|d| *d > 0.0 && *d <= 1e6)
|
||||
.map(Density)
|
||||
.ok_or_else(|| D::Error::custom(whole("`density` must be a positive number of kg/m³ (at most 1e6)")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for Density {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"Density".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A density in kg/m³: above 0 and at most 1e6.",
|
||||
"type": "number", "exclusiveMinimum": 0, "maximum": 1e6
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_required(schema: &mut Schema) {
|
||||
require(schema, "profile");
|
||||
}
|
||||
|
||||
/// Work out a built-in profile's section: its area, centroid and second moments, about axes
|
||||
/// through the centroid, parallel to the profile's x and y.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = profile_required)]
|
||||
pub struct ProfilePropertiesParams {
|
||||
// Optional in the type and required in the schema (`profile_required`).
|
||||
/// The profile, as `frame.profile.list` describes the kinds.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProfileParam")]
|
||||
pub profile: Option<ProfileParam>,
|
||||
/// The material's density, which adds `mass_per_m`. Default: none, and no `mass_per_m`.
|
||||
#[serde(default)]
|
||||
pub density: Option<Density>,
|
||||
}
|
||||
|
||||
/// A profile's section, as `frame.profile.properties` and `frame.profile.insert` report it.
|
||||
/// Lengths are in mm, areas in mm² and second moments in mm⁴.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProfileSection {
|
||||
/// The profile with every default filled in.
|
||||
pub profile: ProfileOut,
|
||||
/// The section's area, mm².
|
||||
pub area: f64,
|
||||
/// The centroid [x, y], mm, in the profile's own plane (x across, y up) from the centre of its
|
||||
/// bounding box.
|
||||
pub centroid: [f64; 2],
|
||||
/// ∫ y² dA about the centroid: bending about the x axis, mm⁴.
|
||||
pub ixx: f64,
|
||||
/// ∫ x² dA about the centroid: bending about the y axis, mm⁴.
|
||||
pub iyy: f64,
|
||||
/// ∫ x·y dA about the centroid, mm⁴.
|
||||
pub ixy: f64,
|
||||
/// The bounding box's width, mm.
|
||||
pub width: f64,
|
||||
/// The bounding box's height, mm.
|
||||
pub height: f64,
|
||||
/// With a `density`: the mass of a metre of the profile, kg/m.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mass_per_m: Option<f64>,
|
||||
}
|
||||
|
||||
/// What `frame.profile.properties` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProfilePropertiesResult {
|
||||
#[serde(flatten)]
|
||||
pub section: ProfileSection,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// frame.profile.insert
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// A point of the sketch in mm: `[x, y]` or `{x, y}`, with `frame.profile.insert`'s message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct InsertAt(pub Vec2);
|
||||
|
||||
impl<'de> Deserialize<'de> for InsertAt {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec2(&Value::deserialize(d)?).map(InsertAt).ok_or_else(|| D::Error::custom(whole("`at` must be [x, y] in sketch millimetres")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for InsertAt {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"InsertAt".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point2>()
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle in radians as `frame.profile.insert` reads it: a number, at most 1e6 in size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Radians(pub f64);
|
||||
|
||||
impl<'de> Deserialize<'de> for Radians {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::num(&wrap("angle", Value::deserialize(d)?), "angle")
|
||||
.filter(|a| a.abs() <= 1e6)
|
||||
.map(Radians)
|
||||
.ok_or_else(|| D::Error::custom(whole("`angle` must be a number of radians")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for Radians {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"Radians".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "An angle in radians, counter-clockwise: a number of at most 1e6 in size.", "type": "number", "minimum": -1e6, "maximum": 1e6})
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a built-in profile into a sketch as lines and arcs, placed by its anchor and turned about
|
||||
/// it. A tube's inside is drawn too, so the wall is one profile. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = profile_required)]
|
||||
pub struct ProfileInsertParams {
|
||||
// Optional in the type and required in the schema (`profile_required`).
|
||||
/// The profile, as `frame.profile.list` describes the kinds.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProfileParam")]
|
||||
pub profile: Option<ProfileParam>,
|
||||
/// Where the anchor goes, in sketch mm. Default: the origin.
|
||||
#[serde(default)]
|
||||
pub at: Option<InsertAt>,
|
||||
/// The profile point that is placed on `at`. Default: origin.
|
||||
#[serde(default)]
|
||||
pub anchor: Option<AnchorParam>,
|
||||
/// How far the profile turns about the anchor, in radians counter-clockwise (not degrees).
|
||||
/// Default: 0.
|
||||
#[serde(default)]
|
||||
pub angle: Option<Radians>,
|
||||
/// Lock the curves, so that solving the sketch keeps the shape. Default: true.
|
||||
#[serde(default)]
|
||||
pub fixed: Option<bool>,
|
||||
/// The sketch to draw in, by id or name. Default: the sketch being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// The ids of what a sketch edit added, stable and never reused.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CreatedIds {
|
||||
/// The points added.
|
||||
pub points: Vec<String>,
|
||||
/// The curves added.
|
||||
pub curves: Vec<String>,
|
||||
/// The constraints added, dimensions apart.
|
||||
pub constraints: Vec<String>,
|
||||
/// The dimensions added.
|
||||
pub dimensions: Vec<String>,
|
||||
/// The wires added. Left out when there are none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub wires: Vec<String>,
|
||||
}
|
||||
|
||||
/// The sketch's solve after an edit.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct SketchSolve {
|
||||
/// Whether the constraints solved, keeping the sketch's orientation.
|
||||
pub solved: bool,
|
||||
/// The degrees of freedom left.
|
||||
pub dof: usize,
|
||||
}
|
||||
|
||||
/// What `frame.profile.insert` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProfileInsertResult {
|
||||
/// What the insertion added to the sketch.
|
||||
pub created: CreatedIds,
|
||||
/// The inserted profile's section, as `frame.profile.properties` reports it.
|
||||
pub section: ProfileSection,
|
||||
/// The sketch's solve, or null when it was not solved again.
|
||||
pub sketch: Option<SketchSolve>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// frame.member
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `lines`: one to 1000 curve ids, none twice, as `frame.member` reads them (a single id isn't
|
||||
/// taken).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LineIds(pub Vec<String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for LineIds {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let fail = || D::Error::custom(whole(format!("`lines` must list 1…{MAX_MEMBERS} curve ids")));
|
||||
let Value::Array(a) = Value::deserialize(d)? else { return Err(fail()) };
|
||||
if a.is_empty() || a.len() > MAX_MEMBERS {
|
||||
return Err(fail());
|
||||
}
|
||||
let lines = a.into_iter().map(|v| if let Value::String(s) = v { Some(s) } else { None }).collect::<Option<Vec<_>>>().ok_or_else(fail)?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
match lines.iter().find(|l| !seen.insert(l.as_str())) {
|
||||
Some(twice) => Err(D::Error::custom(whole(format!("line `{twice}` is listed twice")))),
|
||||
None => Ok(LineIds(lines)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for LineIds {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"LineIds".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Curve ids of the frame sketch's lines, each once.",
|
||||
"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": MAX_MEMBERS, "uniqueItems": true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The name members are named after: text of 1 to 128 bytes once trimmed, as `frame.member` reads
|
||||
/// `body_name`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MemberName(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for MemberName {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) if !s.trim().is_empty() && s.trim().len() <= MAX_NAME => Ok(MemberName(s)),
|
||||
_ => Err(D::Error::custom(whole(format!("`body_name` must be 1…{MAX_NAME} characters")))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for MemberName {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"MemberName".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A name: text that isn't blank, at most 128 bytes once trimmed of the whitespace around it.",
|
||||
"type": "string", "pattern": not_blank_pattern()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `names`: up to 1000 line ids, each with a name of 1 to 128 bytes once trimmed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MemberNames(pub BTreeMap<String, String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for MemberNames {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Object(m) if m.len() <= MAX_MEMBERS => m
|
||||
.into_iter()
|
||||
.map(|(line, v)| match v.as_str().map(str::trim).filter(|n| !n.is_empty() && n.len() <= MAX_NAME) {
|
||||
Some(name) => Ok((line, name.to_string())),
|
||||
None => Err(D::Error::custom(whole(format!("`names`: the name of line `{line}` must be 1…{MAX_NAME} characters")))),
|
||||
})
|
||||
.collect::<Result<_, _>>()
|
||||
.map(MemberNames),
|
||||
_ => Err(D::Error::custom(whole(format!("`names` must map up to {MAX_MEMBERS} line ids to names")))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for MemberNames {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"MemberNames".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Names to keep, by line id. A name is text that isn't blank, at most 128 bytes once trimmed.",
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string", "pattern": not_blank_pattern()},
|
||||
"maxProperties": MAX_MEMBERS
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `angle` as `frame.member` reads it: a number of degrees or an expression, with its message. Whether
|
||||
/// the expression evaluates as an angle is the handler's to check.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MemberAngle(pub Expr);
|
||||
|
||||
impl<'de> Deserialize<'de> for MemberAngle {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::expr(&wrap("angle", Value::deserialize(d)?), "angle")
|
||||
.map(MemberAngle)
|
||||
.ok_or_else(|| D::Error::custom(whole("`angle` must be an angle expression")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for MemberAngle {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"MemberAngle".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<AngleExpr>()
|
||||
}
|
||||
}
|
||||
|
||||
/// `participants`, read as `features::add_feature` reads it: a name or a list of names, with the
|
||||
/// message of `params::string_list`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Participants(pub Vec<String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Participants {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match params::string_list("", &wrap("participants", Value::deserialize(d)?), "participants") {
|
||||
Ok(names) => Ok(Participants(names)),
|
||||
Err(crate::EngineError::BadParams { msg, .. }) => Err(D::Error::custom(whole(msg))),
|
||||
Err(e) => Err(D::Error::custom(whole(e))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for Participants {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"Participants".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<StringList>()
|
||||
}
|
||||
}
|
||||
|
||||
/// `sketch` is required and one of `profile` and `profile_sketch`, not both, as the schema says;
|
||||
/// the type leaves them to the handler's messages.
|
||||
fn member_required(schema: &mut Schema) {
|
||||
require(schema, "sketch");
|
||||
let only = |key: &str, other: &str| json!({"required": [key], "not": {"required": [other]}});
|
||||
schema.insert("anyOf".into(), json!([only("profile", "profile_sketch"), only("profile_sketch", "profile")]));
|
||||
}
|
||||
|
||||
/// Lay structural members along the lines of a frame sketch: one body per line, from its start
|
||||
/// to its end, its cross-section square to the line. The section is a built-in `profile` or the
|
||||
/// profiles of a `profile_sketch`, one of them. Each member keeps its name when other lines are
|
||||
/// added or deleted. Returns the feature and the bodies it made.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = member_required)]
|
||||
pub struct FrameMemberKeys {
|
||||
// Optional in the type and required in the schema (`member_required`).
|
||||
/// The frame sketch, 2D or 3D, by id or name.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SketchRef")]
|
||||
pub sketch: Option<SketchRef>,
|
||||
/// The lines to lay members along, by curve id, one member each. Default: every straight
|
||||
/// line drawn in the sketch that isn't construction, projected or otherwise linked, or of no
|
||||
/// length.
|
||||
#[serde(default)]
|
||||
pub lines: Option<LineIds>,
|
||||
/// The section as a built-in profile. Give it or `profile_sketch`, not both.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProfileParam")]
|
||||
pub profile: Option<ProfileParam>,
|
||||
/// The section as a sketch: its profiles, in the sketch's own x and y around its origin. It
|
||||
/// can't be the frame sketch. Give it or `profile`, not both.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SketchRef")]
|
||||
pub profile_sketch: Option<SketchRef>,
|
||||
/// With `profile_sketch`: which of its profiles are the section, as `solid.extrude` takes
|
||||
/// them. Default: its material, nested loops alternating, so two circles make a tube. Not
|
||||
/// used with `profile`.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProfilesParam")]
|
||||
pub profiles: Option<ProfilesParam>,
|
||||
/// With `profile_sketch`: each index or point pick in `profiles` is exactly the region it
|
||||
/// names, where it would otherwise take the whole drawn profile a face's projected outline
|
||||
/// cuts into regions. Default: false. Not used with `profile`.
|
||||
#[serde(default)]
|
||||
pub exact_regions: Option<bool>,
|
||||
/// The profile point that sits on each line. Default: origin.
|
||||
#[serde(default)]
|
||||
pub anchor: Option<AnchorParam>,
|
||||
/// How far the profile turns about the line, a number of degrees or an expression. Default:
|
||||
/// 0, which puts its y as near world up as the line allows (a vertical member's x along
|
||||
/// world X).
|
||||
#[serde(default)]
|
||||
pub angle: Option<MemberAngle>,
|
||||
/// The profile mirrored across its y axis, before it turns. Default: false.
|
||||
#[serde(default)]
|
||||
pub mirror: Option<bool>,
|
||||
/// The feature's name in the timeline.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
/// What the members are named after, then numbered: `Rail`, `Rail (2)`… Default: the
|
||||
/// profile's description (`Rect Tube 40x40x3`), or the profile sketch's name.
|
||||
#[serde(default)]
|
||||
pub body_name: Option<MemberName>,
|
||||
/// Names to keep, by line id, as Edit Feature keeps them. A line not listed gets a name from
|
||||
/// `body_name`.
|
||||
#[serde(default)]
|
||||
pub names: Option<MemberNames>,
|
||||
/// The bodies taking part, which every feature records; each an existing body or `*`. Members
|
||||
/// are new bodies, whatever this lists.
|
||||
#[serde(default)]
|
||||
pub participants: Option<Participants>,
|
||||
}
|
||||
|
||||
/// `frame.member`'s parameters: [`FrameMemberKeys`], reading the section's keys only as the
|
||||
/// handler does (see the module docs).
|
||||
#[derive(Debug)]
|
||||
pub struct FrameMemberParams(pub FrameMemberKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for FrameMemberParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut() {
|
||||
// A key counts as given when it is there, `null` included, as the handler tests it.
|
||||
match (keys.contains_key("profile"), keys.contains_key("profile_sketch")) {
|
||||
// A built-in profile: the sketch's profile picks are never read.
|
||||
(true, false) => {
|
||||
keys.remove("profiles");
|
||||
keys.remove("exact_regions");
|
||||
}
|
||||
(false, true) => {}
|
||||
// Both or neither: the handler refuses before it reads any of them.
|
||||
_ => {
|
||||
for key in ["profile", "profile_sketch", "profiles", "exact_regions"] {
|
||||
keys.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(FrameMemberParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for FrameMemberParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"FrameMemberParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
FrameMemberKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "frame_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,568 +0,0 @@
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::FeatureKind;
|
||||
use solidcraft_doc::frame::{self, MAX_MEMBERS};
|
||||
|
||||
use super::{
|
||||
FrameMemberParams, ProfileInsertParams, ProfileInsertResult, ProfileListParams, ProfileListResult, ProfilePropertiesParams,
|
||||
ProfilePropertiesResult,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::features::FeatureResult;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};
|
||||
use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
|
||||
|
||||
fn tube() -> Value {
|
||||
json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3})
|
||||
}
|
||||
|
||||
/// The id of the first sketch of `s`.
|
||||
fn first_sketch(s: &Session) -> u64 {
|
||||
s.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.id).unwrap_or_else(|| panic!("no sketch"))
|
||||
}
|
||||
|
||||
/// A session with the 600 × 400 rectangle `Frame` (its four line ids returned) and the sketch
|
||||
/// `Section`, two concentric circles: a tube's wall.
|
||||
fn frame_session(level: ParamCheck) -> (Session, Vec<String>) {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
run("sketch.create", json!({"plane": "XY", "name": "Frame"}));
|
||||
let rectangle = run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [600, 400]}));
|
||||
run("sketch.finish", json!({}));
|
||||
run("sketch.create", json!({"plane": "XY", "name": "Section"}));
|
||||
run("sketch.circle.center", json!({"center": [0, 0], "radius": 20}));
|
||||
run("sketch.circle.center", json!({"center": [0, 0], "radius": 17}));
|
||||
run("sketch.finish", json!({}));
|
||||
let lines =
|
||||
rectangle["created"]["curves"].as_array().map(|c| c.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()).unwrap_or_default();
|
||||
(s, lines)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(
|
||||
input_schema_for::<FrameMemberParams>(),
|
||||
&[
|
||||
"anchor",
|
||||
"angle",
|
||||
"body_name",
|
||||
"exact_regions",
|
||||
"lines",
|
||||
"mirror",
|
||||
"name",
|
||||
"names",
|
||||
"participants",
|
||||
"profile",
|
||||
"profile_sketch",
|
||||
"profiles",
|
||||
"sketch",
|
||||
],
|
||||
);
|
||||
assert_keys(input_schema_for::<ProfileListParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ProfilePropertiesParams>(), &["density", "profile"]);
|
||||
assert_keys(input_schema_for::<ProfileInsertParams>(), &["anchor", "angle", "at", "fixed", "profile", "sketch"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let sketch = {
|
||||
let mut s = Session::default();
|
||||
sketch_rectangle(&mut s);
|
||||
first_sketch(&s)
|
||||
};
|
||||
let member = |extra: Value| {
|
||||
let mut p = json!({"sketch": sketch, "profile": tube()});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
("frame.member", p)
|
||||
};
|
||||
let bar = json!({"kind": "round_bar", "diameter": 10});
|
||||
let insert = |extra: Value| {
|
||||
let mut p = json!({"profile": bar});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
("frame.profile.insert", p)
|
||||
};
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
// frame.member
|
||||
("frame.member", json!({})),
|
||||
("frame.member", json!({"sketch": null, "profile": tube()})),
|
||||
("frame.member", json!({"sketch": true, "profile": tube()})),
|
||||
("frame.member", json!({"sketch": [1], "profile": tube()})),
|
||||
("frame.member", json!({"sketch": sketch})),
|
||||
("frame.member", json!({"sketch": sketch, "profile": tube(), "profile_sketch": sketch})),
|
||||
("frame.member", json!({"sketch": sketch, "profile": tube(), "profile_sketch": null})),
|
||||
("frame.member", json!({"sketch": sketch, "profile_sketch": true})),
|
||||
("frame.member", json!({"sketch": sketch, "profile_sketch": null})),
|
||||
("frame.member", json!({"sketch": sketch, "profile_sketch": sketch})),
|
||||
("frame.member", json!({"sketch": sketch, "profile_sketch": "Nowhere"})),
|
||||
("frame.member", json!({"sketch": sketch, "profile_sketch": 99999, "profiles": 3})),
|
||||
("frame.member", json!({"sketch": "Nowhere", "profile": tube()})),
|
||||
member(json!({"profile": null})),
|
||||
member(json!({"profile": "tube"})),
|
||||
member(json!({"profile": {}})),
|
||||
member(json!({"profile": {"kind": "hexagon"}})),
|
||||
member(json!({"profile": {"kind": 5}})),
|
||||
member(json!({"profile": {"kind": "bar", "width": 10}})),
|
||||
member(json!({"profile": {"kind": "bar", "width": 10, "height": 5, "diameter": 3}})),
|
||||
member(json!({"profile": {"kind": "bar", "width": true, "height": 5}})),
|
||||
member(json!({"profile": {"kind": "bar", "width": " ", "height": 5}})),
|
||||
member(json!({"profile": {"kind": "rect_tube", "width": 10, "height": 10, "wall": 5}})),
|
||||
member(json!({"profile": {"kind": "bar", "width": "nonsense(", "height": 5}})),
|
||||
member(json!({"lines": []})),
|
||||
member(json!({"lines": "l1"})),
|
||||
member(json!({"lines": [1]})),
|
||||
member(json!({"lines": ["l1", "l1"]})),
|
||||
member(json!({"lines": (0..=MAX_MEMBERS).map(|i| format!("l{i}")).collect::<Vec<_>>()})),
|
||||
member(json!({"lines": ["nope"]})),
|
||||
member(json!({"body_name": ""})),
|
||||
member(json!({"body_name": " "})),
|
||||
member(json!({"body_name": 5})),
|
||||
member(json!({"body_name": "x".repeat(129)})),
|
||||
member(json!({"anchor": "middle"})),
|
||||
member(json!({"anchor": 5})),
|
||||
member(json!({"anchor": ["top"]})),
|
||||
member(json!({"angle": true})),
|
||||
member(json!({"angle": ""})),
|
||||
member(json!({"angle": "x".repeat(4097)})),
|
||||
member(json!({"angle": "a lot"})),
|
||||
member(json!({"mirror": 3})),
|
||||
member(json!({"mirror": "yes"})),
|
||||
member(json!({"names": ["Rail"]})),
|
||||
member(json!({"names": {"l1": " "}})),
|
||||
member(json!({"names": {"l1": 5}})),
|
||||
member(json!({"names": {"l1": "x".repeat(129)}})),
|
||||
member(json!({"participants": 5})),
|
||||
member(json!({"participants": [5]})),
|
||||
member(json!({"participants": ["Nobody"]})),
|
||||
// frame.profile.properties
|
||||
("frame.profile.properties", json!({})),
|
||||
("frame.profile.properties", json!({"profile": null})),
|
||||
("frame.profile.properties", json!({"profile": {"kind": "hexagon"}})),
|
||||
("frame.profile.properties", json!({"profile": {"kind": "round_bar"}})),
|
||||
("frame.profile.properties", json!({"profile": {"kind": "round_bar", "diameter": -1}})),
|
||||
("frame.profile.properties", json!({"profile": bar, "density": -1})),
|
||||
("frame.profile.properties", json!({"profile": bar, "density": 0})),
|
||||
("frame.profile.properties", json!({"profile": bar, "density": "steel"})),
|
||||
("frame.profile.properties", json!({"profile": bar, "density": 1e7})),
|
||||
("frame.profile.properties", json!({"profile": bar, "density": true})),
|
||||
// frame.profile.insert
|
||||
("frame.profile.insert", json!({})),
|
||||
("frame.profile.insert", json!({"profile": {"kind": "bar", "width": 5}})),
|
||||
insert(json!({"at": "here"})),
|
||||
insert(json!({"at": [1]})),
|
||||
insert(json!({"at": [1e300, 0]})),
|
||||
insert(json!({"at": {"x": 1}})),
|
||||
insert(json!({"anchor": "middle"})),
|
||||
insert(json!({"anchor": 3})),
|
||||
insert(json!({"angle": "a lot"})),
|
||||
insert(json!({"angle": 1e7})),
|
||||
insert(json!({"fixed": 3})),
|
||||
insert(json!({"fixed": "false"})),
|
||||
insert(json!({"sketch": true})),
|
||||
insert(json!({"sketch": -1})),
|
||||
insert(json!({"sketch": 1.5})),
|
||||
insert(json!({"sketch": "Nowhere"})),
|
||||
// No sketch is being edited, and none is named.
|
||||
insert(json!({})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Each key is read as its handler reads it: a call the handler takes has no issue, and a call
|
||||
/// it refuses over a key has one. (A call with a key the handler ignores is told apart below.)
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_the_handlers_do() {
|
||||
let (_, lines) = frame_session(ParamCheck::Off);
|
||||
let line = lines.first().cloned().unwrap_or_default();
|
||||
let member = |extra: Value| {
|
||||
let mut p = json!({"sketch": "Frame", "profile": tube()});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
};
|
||||
let section = |extra: Value| {
|
||||
let mut p = json!({"sketch": "Frame", "profile_sketch": "Section"});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
};
|
||||
// (call, whether the handler takes it)
|
||||
let cases = [
|
||||
(member(json!({})), true),
|
||||
(member(json!({"lines": [line]})), true),
|
||||
(member(json!({"lines": null})), true),
|
||||
(member(json!({"lines": []})), false),
|
||||
(member(json!({"lines": [line, line]})), false),
|
||||
(member(json!({"body_name": "Rail"})), true),
|
||||
(member(json!({"body_name": " Rail "})), true),
|
||||
(member(json!({"body_name": null})), true),
|
||||
(member(json!({"body_name": "x".repeat(128)})), true),
|
||||
(member(json!({"body_name": "x".repeat(129)})), false),
|
||||
(member(json!({"body_name": " "})), false),
|
||||
(member(json!({"anchor": "bottom_left"})), true),
|
||||
(member(json!({"anchor": null})), true),
|
||||
(member(json!({"anchor": "Top"})), false),
|
||||
(member(json!({"angle": "90 deg"})), true),
|
||||
(member(json!({"angle": 45})), true),
|
||||
(member(json!({"angle": " 30 deg "})), true),
|
||||
(member(json!({"angle": null})), true),
|
||||
(member(json!({"angle": ""})), false),
|
||||
(member(json!({"angle": 1e9})), false),
|
||||
(member(json!({"mirror": true})), true),
|
||||
(member(json!({"mirror": null})), true),
|
||||
(member(json!({"mirror": 1})), false),
|
||||
(member(json!({"names": {line.clone(): " Mine "}})), true),
|
||||
(member(json!({"names": {}})), true),
|
||||
(member(json!({"names": null})), true),
|
||||
(member(json!({"names": {line.clone(): ""}})), false),
|
||||
(member(json!({"names": [line]})), false),
|
||||
(member(json!({"name": "Frame members"})), true),
|
||||
(member(json!({"participants": "*"})), true),
|
||||
(member(json!({"participants": ["*"]})), true),
|
||||
(member(json!({"participants": null})), true),
|
||||
(member(json!({"participants": [3]})), false),
|
||||
(member(json!({"participants": {"a": 1}})), false),
|
||||
(member(json!({"profile": {"kind": "bar", "width": "40 mm", "height": 10, "corner_radius": 0}})), true),
|
||||
(member(json!({"profile": {"kind": "bar", "width": 40}})), false),
|
||||
(member(json!({"profile": {"kind": "i_beam", "height": 100, "width": 50, "web": 4.5, "flange": 7, "root_radius": null}})), false),
|
||||
(section(json!({})), true),
|
||||
(section(json!({"profiles": "all"})), true),
|
||||
(section(json!({"profiles": [{"point": [0, 0]}], "exact_regions": true})), true),
|
||||
(section(json!({"profiles": [0]})), true),
|
||||
(section(json!({"profiles": "none"})), false),
|
||||
(section(json!({"profiles": null})), false),
|
||||
(section(json!({"profiles": []})), false),
|
||||
// Keys the handler never reads in this form: no issue, and the call is as good as without.
|
||||
(member(json!({"profiles": "none", "exact_regions": "yes"})), true),
|
||||
(member(json!({"profiles": null})), true),
|
||||
];
|
||||
for (p, takes) in cases {
|
||||
let (mut s, _) = frame_session(ParamCheck::Off);
|
||||
let outcome = s.execute("frame.member", &p);
|
||||
assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");
|
||||
assert_eq!(issues("frame.member", &p).is_empty(), takes, "{p}: {:?}", issues("frame.member", &p));
|
||||
}
|
||||
|
||||
// One of `profile` and `profile_sketch`: with both or neither the handler refuses before it
|
||||
// reads the section's keys, and the check, which can't see the design, leaves it that.
|
||||
for p in [
|
||||
json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section"}),
|
||||
json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section", "profiles": "none", "exact_regions": 1}),
|
||||
json!({"sketch": "Frame", "profile": null, "profile_sketch": null}),
|
||||
json!({"sketch": "Frame"}),
|
||||
json!({"sketch": "Frame", "profiles": "none"}),
|
||||
] {
|
||||
let (mut s, _) = frame_session(ParamCheck::Off);
|
||||
let error = s.execute("frame.member", &p).unwrap_err().to_string();
|
||||
assert!(error.contains("`profile`") && error.contains("one of them"), "{p}: {error}");
|
||||
assert!(issues("frame.member", &p).is_empty(), "{p}: {:?}", issues("frame.member", &p));
|
||||
}
|
||||
|
||||
// The properties and insert commands.
|
||||
let (mut s, _) = frame_session(ParamCheck::Off);
|
||||
let bar = json!({"kind": "round_bar", "diameter": 10});
|
||||
for (p, takes) in [
|
||||
(json!({"profile": bar}), true),
|
||||
(json!({"profile": bar, "density": 7850}), true),
|
||||
(json!({"profile": bar, "density": null}), true),
|
||||
(json!({"profile": bar, "density": 1e6}), true),
|
||||
(json!({"profile": bar, "density": 1e6 + 1.0}), false),
|
||||
(json!({"profile": bar, "density": 0}), false),
|
||||
(json!({"profile": bar, "density": "7850"}), false),
|
||||
] {
|
||||
let outcome = s.execute("frame.profile.properties", &p);
|
||||
assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");
|
||||
assert_eq!(issues("frame.profile.properties", &p).is_empty(), takes, "{p}");
|
||||
}
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"));
|
||||
for (p, takes) in [
|
||||
(json!({"profile": bar}), true),
|
||||
(json!({"profile": bar, "at": [3, 4], "anchor": "centroid", "angle": 0.5, "fixed": false}), true),
|
||||
(json!({"profile": bar, "at": {"x": 3, "y": 4}}), true),
|
||||
(json!({"profile": bar, "at": null, "anchor": null, "angle": null, "fixed": null, "sketch": null}), true),
|
||||
(json!({"profile": bar, "angle": -1e6}), true),
|
||||
(json!({"profile": bar, "angle": 1e6 + 1.0}), false),
|
||||
(json!({"profile": bar, "at": [1, 2, 3]}), false),
|
||||
(json!({"profile": bar, "fixed": 0}), false),
|
||||
(json!({"profile": bar, "anchor": "CENTER"}), false),
|
||||
(json!({"profile": bar, "sketch": 1.5}), false),
|
||||
] {
|
||||
let outcome = s.execute("frame.profile.insert", &p);
|
||||
assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");
|
||||
assert_eq!(issues("frame.profile.insert", &p).is_empty(), takes, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With a built-in profile, a `profiles` or `exact_regions` that couldn't be read is no warning;
|
||||
/// with a profile sketch it is, and says what the handler says.
|
||||
#[test]
|
||||
fn a_section_sketchs_keys_count_only_with_a_section_sketch() {
|
||||
let messages = |p: Value| issues("frame.member", &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
assert_eq!(messages(json!({"sketch": 1, "profile": tube(), "profiles": 7, "exact_regions": []})), Vec::<String>::new());
|
||||
assert_eq!(messages(json!({"sketch": 1, "profile_sketch": 2, "profiles": "none"})), ["`profiles` must be \"all\" or a list"]);
|
||||
assert_eq!(messages(json!({"sketch": 1, "profile_sketch": 2, "exact_regions": "yes"})), ["`exact_regions` must be true or false"]);
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need: `sketch` and a profile are required, `profile` and
|
||||
/// `profile_sketch` are alternatives, and values have the shape the handlers read.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
let bar = json!({"kind": "round_bar", "diameter": 10});
|
||||
takes(
|
||||
input_schema_for::<FrameMemberParams>(),
|
||||
&[
|
||||
(json!({"sketch": "Frame", "profile": tube()}), true),
|
||||
(json!({"sketch": 3, "profile_sketch": "Section"}), true),
|
||||
(json!({"sketch": 3, "profile_sketch": 4, "profiles": [{"point": [0, 0]}], "exact_regions": true}), true),
|
||||
(
|
||||
json!({
|
||||
"sketch": "Frame", "lines": ["l1", "l2"], "profile": {"kind": "bar", "width": "w", "height": 5, "corner_radius": 1},
|
||||
"anchor": "top_left", "angle": "90 deg", "mirror": true, "name": "N", "body_name": "Rail",
|
||||
"names": {"l1": "A"}, "participants": ["*"]
|
||||
}),
|
||||
true,
|
||||
),
|
||||
(json!({"profile": tube()}), false),
|
||||
(json!({"sketch": "Frame"}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section"}), false),
|
||||
(json!({"sketch": "Frame", "profile": {"kind": "hexagon"}}), false),
|
||||
(json!({"sketch": "Frame", "profile": {"kind": "bar", "width": 5}}), false),
|
||||
(json!({"sketch": "Frame", "profile": {"kind": "bar", "width": 5, "height": 5, "wall": 1}}), false),
|
||||
(json!({"sketch": true, "profile": tube()}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "lines": []}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "lines": ["a", "a"]}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "anchor": "middle"}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "angle": true}), false),
|
||||
(json!({"sketch": "Frame", "profile": tube(), "body_names": ["a"]}), false),
|
||||
],
|
||||
);
|
||||
takes(input_schema_for::<ProfileListParams>(), &[(json!({}), true), (json!({"kind": "bar"}), false)]);
|
||||
takes(
|
||||
input_schema_for::<ProfilePropertiesParams>(),
|
||||
&[
|
||||
(json!({"profile": bar}), true),
|
||||
(json!({"profile": bar, "density": 7850}), true),
|
||||
(json!({"profile": bar, "density": null}), true),
|
||||
(json!({"profile": bar, "density": 0}), false),
|
||||
(json!({"profile": bar, "density": 1e6 + 1.0}), false),
|
||||
(json!({"density": 7850}), false),
|
||||
(json!({"profile": {"kind": "round_bar"}}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ProfileInsertParams>(),
|
||||
&[
|
||||
(json!({"profile": bar}), true),
|
||||
(json!({"profile": bar, "at": [1, 2], "anchor": "bottom", "angle": 2.5, "fixed": false, "sketch": "S"}), true),
|
||||
(json!({"profile": bar, "at": {"x": 1, "y": 2}, "sketch": 4}), true),
|
||||
(json!({}), false),
|
||||
(json!({"profile": bar, "at": [1, 2, 3]}), false),
|
||||
(json!({"profile": bar, "angle": 2e6}), false),
|
||||
(json!({"profile": bar, "fixed": "yes"}), false),
|
||||
(json!({"profile": bar, "sketch": 1.5}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The "not blank" patterns are the shared one, which `conforms` doesn't read: pin where they are.
|
||||
#[test]
|
||||
fn the_name_patterns_are_the_blank_pattern() {
|
||||
let blank = crate::schema::types::not_blank_pattern();
|
||||
let member = input_schema_for::<FrameMemberParams>();
|
||||
let member = member.as_value();
|
||||
assert_eq!(member["properties"]["body_name"]["anyOf"][0]["$ref"], json!("#/$defs/MemberName"));
|
||||
assert_eq!(member["$defs"]["MemberName"]["pattern"], json!(blank));
|
||||
assert_eq!(member["$defs"]["MemberNames"]["additionalProperties"]["pattern"], json!(blank));
|
||||
let properties = input_schema_for::<ProfilePropertiesParams>();
|
||||
let properties = properties.as_value();
|
||||
let kinds = properties["$defs"]["ProfileParam"]["anyOf"].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(kinds.len(), frame::profile_kinds().len());
|
||||
assert_eq!(kinds[0]["properties"]["width"]["anyOf"][1]["pattern"], json!(blank));
|
||||
}
|
||||
|
||||
/// The warning for what a key gets wrong, and the check that every built-in kind is described.
|
||||
#[test]
|
||||
fn the_check_names_what_is_wrong_with_a_key() {
|
||||
let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
assert_eq!(issues("frame.profile.properties", json!({"profile": {"kind": "hexagon"}})).len(), 1);
|
||||
assert_eq!(
|
||||
issues("frame.profile.properties", json!({"profile": {"kind": "bar", "width": 1, "height": 1, "wall": 1}})),
|
||||
["`profile`: a bar profile has no dimension `wall`"]
|
||||
);
|
||||
assert_eq!(issues("frame.profile.properties", json!({"profile": {"kind": "bar"}})), ["`profile`: a bar profile needs `width`"]);
|
||||
assert_eq!(
|
||||
issues("frame.profile.properties", json!({"profile": {"kind": "round_bar", "diameter": 1}, "density": -3})),
|
||||
["`density` must be a positive number of kg/m³ (at most 1e6)"]
|
||||
);
|
||||
assert_eq!(
|
||||
issues("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 1}, "at": 3})),
|
||||
["`at` must be [x, y] in sketch millimetres"]
|
||||
);
|
||||
assert_eq!(
|
||||
issues("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 1}, "fixed": "no"})),
|
||||
["`fixed` must be true or false"]
|
||||
);
|
||||
assert_eq!(issues("frame.member", json!({"sketch": 1, "profile": tube(), "mirror": "no"})), ["`mirror` must be true or false"]);
|
||||
assert_eq!(issues("frame.member", json!({"sketch": 1, "profile": tube(), "lines": ["a", "a"]})), ["line `a` is listed twice"]);
|
||||
assert_eq!(
|
||||
issues("frame.member", json!({"sketch": 1, "profile": tube(), "body_names": ["a"]})),
|
||||
["unknown key `body_names`; did you mean `body_name`?"]
|
||||
);
|
||||
// The schemas describe every built-in kind with its dimensions, and its example is one.
|
||||
let schema = input_schema_for::<ProfilePropertiesParams>();
|
||||
let schema = schema.as_value();
|
||||
for kind in frame::profile_kinds() {
|
||||
let example = serde_json::to_value(&kind.example).unwrap_or_default();
|
||||
let profile = json!({"profile": example});
|
||||
assert!(conforms(schema, schema, &profile), "{profile}");
|
||||
assert!(crate::schema::issues("frame.profile.properties", &profile).is_empty(), "{profile}");
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// The library's list and properties replies match the output schemas and are what the handlers
|
||||
/// built before the typed replies: the same JSON.
|
||||
#[test]
|
||||
fn profile_library_replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let listed = run("frame.profile.list", json!({}));
|
||||
matches(output_schema_for::<ProfileListResult>(), "frame.profile.list", &listed);
|
||||
assert_eq!(listed, json!({"kinds": frame::profile_kinds()}));
|
||||
let kinds = listed["kinds"].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(kinds.len(), 7);
|
||||
for kind in &kinds {
|
||||
let r = run("frame.profile.properties", json!({"profile": kind["example"]}));
|
||||
matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &r);
|
||||
let profile: frame::Profile = serde_json::from_value(kind["example"].clone()).unwrap_or_else(|e| panic!("{e}"));
|
||||
let region = profile.region().unwrap_or_else(|e| panic!("{e}"));
|
||||
let sec = frame::section(®ion);
|
||||
assert_eq!(
|
||||
r,
|
||||
json!({
|
||||
"profile": profile.filled(), "area": sec.area, "centroid": sec.centroid, "ixx": sec.ixx, "iyy": sec.iyy, "ixy": sec.ixy,
|
||||
"width": sec.width, "height": sec.height
|
||||
})
|
||||
);
|
||||
}
|
||||
let heavy = run("frame.profile.properties", json!({"profile": tube(), "density": 7850}));
|
||||
matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &heavy);
|
||||
let area = heavy["area"].as_f64().unwrap_or_default();
|
||||
assert_eq!(heavy["mass_per_m"], json!(area * 1e-6 * 7850.0), "{heavy}");
|
||||
assert_eq!(heavy["profile"]["outer_radius"], json!(6.0), "{heavy}");
|
||||
// Dimensions as expressions, in a design with parameters.
|
||||
run("parameters.add", json!({"name": "wall", "expression": "3 mm"}));
|
||||
let by_parameter =
|
||||
run("frame.profile.properties", json!({"profile": {"kind": "rect_tube", "width": "40 mm", "height": 40, "wall": "wall"}, "density": null}));
|
||||
matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &by_parameter);
|
||||
assert_eq!(by_parameter["area"], run("frame.profile.properties", json!({"profile": tube()}))["area"]);
|
||||
|
||||
// A misspelt key still runs in Warn and says so, with a reply that matches.
|
||||
for (id, p) in [("frame.profile.list", json!({"kinds": true})), ("frame.profile.properties", json!({"profile": tube(), "densty": 7850}))] {
|
||||
let warned = run(id, p);
|
||||
assert!(warned["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{warned}");
|
||||
let schema =
|
||||
if id == "frame.profile.list" { output_schema_for::<ProfileListResult>() } else { output_schema_for::<ProfilePropertiesResult>() };
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a profile in every form, in Warn: each reply matches its output schema, carries no
|
||||
/// warning and is what the handler built before.
|
||||
#[test]
|
||||
fn insert_replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let made = run("sketch.create", json!({"plane": "XY", "name": "Drawing"}));
|
||||
let id = made["sketch"].clone();
|
||||
let plain = run("frame.profile.insert", json!({"profile": tube()}));
|
||||
matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &plain);
|
||||
assert_eq!(plain["created"]["curves"].as_array().map(Vec::len), Some(16), "{plain}");
|
||||
assert!(plain["sketch"]["solved"].is_boolean() && plain["sketch"]["dof"].is_u64(), "{plain}");
|
||||
let mut keys: Vec<&String> = plain.as_object().map(|o| o.keys().collect()).unwrap_or_default();
|
||||
keys.sort();
|
||||
assert_eq!(keys, ["created", "section", "sketch"]);
|
||||
let mut created: Vec<&String> = plain["created"].as_object().map(|o| o.keys().collect()).unwrap_or_default();
|
||||
created.sort();
|
||||
assert_eq!(created, ["constraints", "curves", "dimensions", "points"]);
|
||||
let section = run("frame.profile.properties", json!({"profile": tube()}));
|
||||
// The section is what the library computes for the profile, not just what the other command says.
|
||||
let profile: frame::Profile = serde_json::from_value(tube()).unwrap_or_else(|e| panic!("{e}"));
|
||||
let sec = frame::section(&profile.region().unwrap_or_else(|e| panic!("{e}")));
|
||||
assert_eq!(plain["section"]["area"], json!(sec.area), "{plain}");
|
||||
assert_eq!(plain["section"]["centroid"], json!(sec.centroid), "{plain}");
|
||||
assert_eq!(plain["section"]["profile"], serde_json::to_value(profile.filled()).unwrap_or_default(), "{plain}");
|
||||
assert_eq!(plain["section"], section);
|
||||
let placed = run(
|
||||
"frame.profile.insert",
|
||||
json!({
|
||||
"profile": {"kind": "channel", "height": "60 mm", "width": 45, "web": 5, "flange": 6},
|
||||
"at": [100, 50], "anchor": "bottom_left", "angle": 0.5, "fixed": false, "sketch": "Drawing"
|
||||
}),
|
||||
);
|
||||
matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &placed);
|
||||
let by_id = run(
|
||||
"frame.profile.insert",
|
||||
json!({"profile": {"kind": "round_bar", "diameter": 20}, "sketch": id, "at": {"x": -50, "y": 5}, "anchor": null}),
|
||||
);
|
||||
matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &by_id);
|
||||
assert_eq!(by_id["created"]["curves"].as_array().map(Vec::len), Some(1), "{by_id}");
|
||||
// A misspelt key still runs in Warn, and says so, with a reply that matches.
|
||||
let warned = run("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 5}, "sketch": "Drawing", "ancor": "center"}));
|
||||
assert_eq!(warned["param_warnings"], json!(["unknown key `ancor`; did you mean `anchor`?"]), "{warned}");
|
||||
let schema = output_schema_for::<ProfileInsertResult>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");
|
||||
}
|
||||
|
||||
/// Members in every form, in Warn: each reply matches `FeatureResult` and carries no warning.
|
||||
#[test]
|
||||
fn member_replies_match_the_output_schema() {
|
||||
let (mut s, lines) = frame_session(ParamCheck::Warn);
|
||||
let mut run = |p: Value| s.execute("frame.member", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
let first = lines.first().cloned().unwrap_or_default();
|
||||
let second = lines.get(1).cloned().unwrap_or_default();
|
||||
let calls = [
|
||||
json!({"sketch": "Frame", "profile": tube()}),
|
||||
json!({"sketch": "Frame", "profile": {"kind": "angle", "width": 60, "height": 40, "thickness": "5 mm"}, "lines": [first], "anchor": "bottom_left"}),
|
||||
json!({"sketch": "Frame", "profile": tube(), "lines": [first, second], "angle": "90 deg", "mirror": true, "name": "Rails", "body_name": "Rail"}),
|
||||
json!({"sketch": "Frame", "profile": tube(), "lines": [first], "angle": 45, "names": {first.clone(): "Chosen"}, "participants": "*"}),
|
||||
json!({"sketch": "Frame", "profile": tube(), "lines": null}),
|
||||
json!({"sketch": "Frame", "profile_sketch": "Section"}),
|
||||
json!({"sketch": "Frame", "profile_sketch": "Section", "profiles": [{"point": [0, 0]}], "exact_regions": true, "lines": [first], "anchor": "center"}),
|
||||
json!({"sketch": "Frame", "profile_sketch": "Section", "profiles": "all", "mirror": false, "angle": null, "names": null}),
|
||||
];
|
||||
for p in calls {
|
||||
let reply = run(p.clone());
|
||||
matches(output_schema_for::<FeatureResult>(), "frame.member", &reply);
|
||||
assert!(reply["created_bodies"].as_array().is_some_and(|b| !b.is_empty()), "{p}: {reply}");
|
||||
}
|
||||
// By the id of the sketch.
|
||||
let by_id = s_first_sketch_call(&mut s, &first);
|
||||
matches(output_schema_for::<FeatureResult>(), "frame.member", &by_id);
|
||||
|
||||
// A misspelt key still runs in Warn, and says so, with a reply that matches.
|
||||
let warned =
|
||||
s.execute("frame.member", &json!({"sketch": "Frame", "profile": tube(), "lines": [first], "profil": 1})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(warned["param_warnings"], json!(["unknown key `profil`; did you mean `profile`?"]), "{warned}");
|
||||
let schema = output_schema_for::<FeatureResult>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");
|
||||
}
|
||||
|
||||
fn s_first_sketch_call(s: &mut Session, line: &str) -> Value {
|
||||
let id = first_sketch(s);
|
||||
s.execute("frame.member", &json!({"sketch": id, "profile": tube(), "lines": [line]})).unwrap_or_else(|e| panic!("{e}"))
|
||||
}
|
||||
@@ -50,44 +50,6 @@ pub struct BodyListParams {
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ModelThreadsParams {}
|
||||
|
||||
/// List the timeline features that built each body (#11945).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct BodyFeaturesParams {
|
||||
/// One body, by name (a placed copy's name means the body it shows); every body when left out.
|
||||
#[serde(default)]
|
||||
pub body: Option<String>,
|
||||
}
|
||||
|
||||
/// What `model.body_features` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ModelBodyFeatures {
|
||||
/// The bodies, in the model's order (the one asked for alone).
|
||||
pub bodies: Vec<BodyFeatures>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A body and the features that built it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyFeatures {
|
||||
/// The body's name.
|
||||
pub body: String,
|
||||
/// In timeline order: the feature that created it, every later one that changed its
|
||||
/// geometry, and those of the bodies consumed into it (a Combine's tools, a body joined in).
|
||||
pub features: Vec<BodyFeature>,
|
||||
}
|
||||
|
||||
/// A timeline feature.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyFeature {
|
||||
/// The feature's id.
|
||||
pub id: u64,
|
||||
/// Its name in the timeline.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// What `model.edges` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ModelEdges {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{BodyFeaturesParams, BodyListParams, DescribeParams, ModelBodyFeatures, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
|
||||
use super::{BodyListParams, DescribeParams, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
@@ -10,7 +10,6 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<DescribeParams>(), &["command"]);
|
||||
assert_keys(input_schema_for::<BodyListParams>(), &["body"]);
|
||||
assert_keys(input_schema_for::<ModelThreadsParams>(), &[]);
|
||||
assert_keys(input_schema_for::<BodyFeaturesParams>(), &["body"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -23,7 +22,6 @@ fn strict_keeps_todays_errors() {
|
||||
("model.edges", json!({"body": "Nope"})),
|
||||
("model.faces", json!({})),
|
||||
("model.faces", json!({"body": "Nope"})),
|
||||
("model.body_features", json!({"body": "Nope"})),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -89,47 +87,3 @@ fn describe_returns_both_schemas() {
|
||||
let e = s.execute("engine.describe", &json!({"command": "solid.extrud"})).err().map(|e| e.to_string());
|
||||
assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
|
||||
}
|
||||
|
||||
/// #11945: each body lists the features that built it, in timeline order: its own box, the fillet
|
||||
/// that changed it, and the cutting box a Combine consumed into it with that Combine. Another body
|
||||
/// keeps only its own. Rolled back before the Combine, neither it nor the tool's box are listed.
|
||||
#[test]
|
||||
fn body_features_list_what_built_each_body() {
|
||||
let schema = output_schema_for::<ModelBodyFeatures>();
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let id = |r: Value| r["feature"].as_u64().unwrap_or_else(|| panic!("{r}"));
|
||||
let a = id(run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "A"})));
|
||||
let b =
|
||||
id(run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [50, 0, 0], "operation": "new", "body_name": "B"})));
|
||||
let fillet = id(run(&mut s, "solid.fillet", json!({"body": "A", "edges": [[10, 0, 10]], "radius": 1})));
|
||||
let tool =
|
||||
id(run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 20, "corner": [5, 5, -5], "operation": "new", "body_name": "T"})));
|
||||
let combine = id(run(&mut s, "solid.combine", json!({"target": "A", "tools": ["T"], "operation": "cut"})));
|
||||
|
||||
let listed = |r: &Value, body: &str| -> Vec<u64> {
|
||||
let entry = r["bodies"].as_array().into_iter().flatten().find(|e| e["body"] == body).unwrap_or_else(|| panic!("no {body} in {r}"));
|
||||
entry["features"].as_array().into_iter().flatten().filter_map(|f| f["id"].as_u64()).collect()
|
||||
};
|
||||
let r = run(&mut s, "model.body_features", json!({}));
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
assert_eq!(listed(&r, "A"), vec![a, fillet, tool, combine], "{r}");
|
||||
assert_eq!(listed(&r, "B"), vec![b], "{r}");
|
||||
assert_eq!(r["bodies"].as_array().map(Vec::len), Some(2), "the consumed tool is gone: {r}");
|
||||
assert_eq!(r["bodies"][0]["features"][1]["name"], s.doc.feature(fillet).map(|f| f.name.clone()).unwrap_or_default().as_str());
|
||||
|
||||
// One body, and the Session data the browser reads agree.
|
||||
let one = run(&mut s, "model.body_features", json!({"body": "B"}));
|
||||
assert_eq!((one["bodies"].as_array().map(Vec::len), listed(&one, "B")), (Some(1), vec![b]), "{one}");
|
||||
assert_eq!(s.body_features().get("A"), Some(&vec![a, fillet, tool, combine]));
|
||||
|
||||
run(&mut s, "timeline.rollback", json!({"position": 3}));
|
||||
assert_eq!(s.body_features().get("A"), Some(&vec![a, fillet]));
|
||||
assert_eq!(s.body_features().get("B"), Some(&vec![b]));
|
||||
|
||||
// A misspelt key warns; an unknown body is refused.
|
||||
let warned = run(&mut s, "model.body_features", json!({"bdy": "A"}));
|
||||
assert!(warned.get("param_warnings").is_some(), "{warned}");
|
||||
assert!(s.execute("model.body_features", &json!({"body": "Nope"})).is_err());
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,707 +1,27 @@
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_doc::joints::JointKind;
|
||||
use serde_json::json;
|
||||
|
||||
use super::{
|
||||
AsBuiltJointParams, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams, DriveJointResult, EditJointParams,
|
||||
InspectJointParams, InspectJointResult, JointAddedResult, JointKindName, JointLimitsParams, ListJointsParams, ListJointsResult,
|
||||
SolveJointsParams, SolveResult,
|
||||
};
|
||||
use super::{EditJointParams, EditJointResult};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
use crate::schema::tests::{assert_keys, conforms};
|
||||
use crate::schema::{input_schema_for, output_schema_for};
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<EditJointParams>(), &["a", "angle", "b", "flip", "joint", "name", "offset", "quiet", "suppressed", "type"]);
|
||||
assert_keys(
|
||||
input_schema_for::<CreateJointParams>(),
|
||||
&["a", "angle", "b", "flip", "limits", "name", "offset", "quiet", "type", "value", "values"],
|
||||
);
|
||||
assert_keys(input_schema_for::<AsBuiltJointParams>(), &["a", "at", "b", "limits", "name", "quiet", "type", "value", "values"]);
|
||||
assert_keys(input_schema_for::<DriveJointParams>(), &["continuous", "index", "joint", "quiet", "value", "values"]);
|
||||
assert_keys(input_schema_for::<JointLimitsParams>(), &["index", "joint", "max", "min", "quiet"]);
|
||||
assert_keys(input_schema_for::<DeleteJointParams>(), &["joint", "link", "origin", "quiet"]);
|
||||
assert_keys(input_schema_for::<ListJointsParams>(), &["quiet"]);
|
||||
assert_keys(input_schema_for::<InspectJointParams>(), &["joint"]);
|
||||
assert_keys(input_schema_for::<SolveJointsParams>(), &["quiet"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commands_publish_their_schemas() {
|
||||
for id in ["joint.create", "joint.as_built", "joint.drive", "joint.limits", "joint.delete", "joint.list", "joint.inspect", "joint.solve"] {
|
||||
let spec = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(spec.contract.is_some() && spec.output.is_some(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The replies name a joint's type as the document does.
|
||||
#[test]
|
||||
fn every_joint_type_has_its_reply_name() {
|
||||
let names = output_schema_for::<JointKindName>();
|
||||
let names: Vec<&str> = names.as_value()["oneOf"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(names.as_value()["enum"].as_array().into_iter().flatten())
|
||||
.filter_map(|v| v.get("const").or(Some(v)).and_then(Value::as_str))
|
||||
.collect();
|
||||
for spelling in [
|
||||
"rigid",
|
||||
"revolute",
|
||||
"slider",
|
||||
"cylindrical",
|
||||
"pin_slot",
|
||||
"planar",
|
||||
"ball",
|
||||
"parallel",
|
||||
"perpendicular",
|
||||
"angle",
|
||||
"point_on_plane",
|
||||
"point_on_line",
|
||||
"line_on_plane",
|
||||
] {
|
||||
let kind = JointKind::parse(spelling).unwrap_or_else(|| panic!("{spelling}"));
|
||||
assert_eq!(serde_json::to_value(kind).ok(), Some(json!(spelling)));
|
||||
assert!(names.contains(&spelling), "{spelling} in {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let at = |o: u64, x: f64| json!({"occurrence": o, "point": [x, 0, 0]});
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("joint.create", json!({})),
|
||||
("joint.create", json!({"type": "nope"})),
|
||||
("joint.create", json!({"type": 5})),
|
||||
("joint.create", json!({"type": null})),
|
||||
("joint.create", json!({"type": "rigid"})),
|
||||
("joint.create", json!({"type": "rigid", "a": 5, "b": at(0, 1.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": null, "b": at(0, 1.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": {}, "b": at(0, 1.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": {"frame": 1}, "b": at(0, 1.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": {"face": [1, 2]}, "b": at(0, 1.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": at(0, 0.0)})),
|
||||
("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "offset": true})),
|
||||
("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "offset": null})),
|
||||
("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "angle": [1]})),
|
||||
("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "values": [true]})),
|
||||
("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "value": {}})),
|
||||
("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "values": [1e12]})),
|
||||
("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "limits": [[true, 1]]})),
|
||||
("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "limits": [[0, 1e12]]})),
|
||||
("joint.as_built", json!({})),
|
||||
("joint.as_built", json!({"type": "rigid"})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": true, "b": 0})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": 0, "b": null})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": [1], "b": 0})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": null})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": 3})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": {"frame": {}}})),
|
||||
("joint.as_built", json!({"type": "revolute", "a": 0, "b": 0, "limits": [[true, 1]]})),
|
||||
("joint.drive", json!({})),
|
||||
("joint.drive", json!({"joint": true})),
|
||||
("joint.drive", json!({"joint": null})),
|
||||
("joint.drive", json!({"joint": [1]})),
|
||||
("joint.limits", json!({})),
|
||||
("joint.limits", json!({"joint": {}})),
|
||||
("joint.delete", json!({})),
|
||||
("joint.delete", json!({"joint": true})),
|
||||
("joint.delete", json!({"joint": null})),
|
||||
("joint.delete", json!({"origin": "nothing"})),
|
||||
("joint.delete", json!({"link": 4})),
|
||||
("joint.delete", json!({"link": null})),
|
||||
("joint.inspect", json!({"joint": true})),
|
||||
("joint.inspect", json!({"joint": [1]})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A design with a grounded plate and a hinged leaf, a joint origin, and a third part joined as
|
||||
/// built, for the calls that need joints to fail on.
|
||||
fn hinged(level: ParamCheck) -> Session {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
for name in ["LeafA", "LeafB"] {
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
let made = run("component.create", json!({"name": name, "grounded": false}));
|
||||
run("solid.box", json!({"length": 40, "width": 30, "height": 3, "corner": [0, 0, 0]}));
|
||||
run("solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));
|
||||
if name == "LeafA" {
|
||||
run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));
|
||||
}
|
||||
}
|
||||
run(
|
||||
"joint.create",
|
||||
json!({"type": "revolute", "a": {"occurrence": "LeafA", "circle": [1, 37, 4]}, "b": {"occurrence": "LeafB", "circle": [1, 37, 4]},
|
||||
"flip": true, "name": "Hinge", "limits": [[-90, 90]]}),
|
||||
);
|
||||
run("joint.origin", json!({"occurrence": "LeafA", "face": [20, 15, 3], "name": "Top"}));
|
||||
s
|
||||
}
|
||||
|
||||
/// What the handlers refuse, with a joint in the design to refuse it for: strict says the same.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_with_joints() {
|
||||
let cases = [
|
||||
("joint.drive", json!({"joint": "Hinge"})),
|
||||
("joint.drive", json!({"joint": "Hinge", "value": true})),
|
||||
("joint.drive", json!({"joint": "Hinge", "values": [true]})),
|
||||
("joint.drive", json!({"joint": "Hinge", "values": [1e12]})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": null, "value": 5})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": "0", "value": 5})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": -1, "value": 5})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": 0, "values": [5]})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": 0, "values": null, "value": 5})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": 0, "value": null})),
|
||||
("joint.drive", json!({"joint": "Hinge", "index": 0, "value": "1 +"})),
|
||||
("joint.limits", json!({"joint": "Hinge", "min": 1})),
|
||||
("joint.limits", json!({"joint": "Hinge", "max": 1})),
|
||||
("joint.limits", json!({"joint": "Hinge", "min": null, "max": 1})),
|
||||
("joint.limits", json!({"joint": "Hinge", "min": 1, "max": true})),
|
||||
("joint.limits", json!({"joint": "Hinge", "min": true, "max": 1})),
|
||||
("joint.limits", json!({"joint": "Hinge", "min": 1e12, "max": 1})),
|
||||
("joint.limits", json!({"joint": "Hinge", "index": 3, "min": 1, "max": 2})),
|
||||
("joint.delete", json!({"joint": "Hinge", "origin": "Missing"})),
|
||||
("joint.delete", json!({"link": 7, "joint": "Hinge"})),
|
||||
("joint.create", json!({"type": "rigid", "a": "Top", "b": "Top"})),
|
||||
("joint.create", json!({"type": "rigid", "a": "Missing", "b": "Top"})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafA"})),
|
||||
("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "Missing"})),
|
||||
("joint.inspect", json!({"joint": "Missing"})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let off = hinged(ParamCheck::Off).execute(id, &p).err().map(|e| e.to_string());
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(hinged(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string()), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
fn issues(id: &str, p: Value) -> Vec<String> {
|
||||
crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()
|
||||
}
|
||||
|
||||
/// The types read each key as its handler does, and in the cases the handler reads it.
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_the_handlers_do() {
|
||||
let none = Vec::<String>::new;
|
||||
let sides = json!({"a": {"occurrence": 0, "point": [0, 0, 0]}, "b": "Origin"});
|
||||
let create = |extra: Value| {
|
||||
let mut p = json!({"type": "revolute"});
|
||||
p.as_object_mut().into_iter().for_each(|o| {
|
||||
o.extend(sides.as_object().cloned().unwrap_or_default());
|
||||
o.extend(extra.as_object().cloned().unwrap_or_default());
|
||||
});
|
||||
issues("joint.create", p)
|
||||
};
|
||||
// The forms of a side, and the key left out, which the handler refuses with its own message.
|
||||
assert_eq!(create(json!({})), none());
|
||||
for side in [
|
||||
json!("Name"),
|
||||
json!({"face": "F1"}),
|
||||
json!({"circle": "F1", "occurrence": "A"}),
|
||||
json!({"face": [0, 0, 0]}),
|
||||
json!({"edge": {"x": 0, "y": 0, "z": 0}, "z": [0, 0, 1]}),
|
||||
json!({"point": [1, 2, 3], "x": [1, 0, 0]}),
|
||||
json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1]}}),
|
||||
] {
|
||||
assert_eq!(create(json!({"a": side})), none(), "{side}");
|
||||
}
|
||||
assert_eq!(issues("joint.create", json!({"type": "rigid"})), none());
|
||||
let why = "a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name";
|
||||
for side in [json!(5), json!(null), json!([1, 2, 3]), json!({}), json!({"face": [1, 2]}), json!({"face": 7})] {
|
||||
assert_eq!(create(json!({"a": side})), [why], "{side}");
|
||||
}
|
||||
assert_eq!(create(json!({"b": {"frame": {"z": [0, 0, 1]}}})), ["`frame` needs origin and z"]);
|
||||
// The type: any spelling `JointKind::parse` takes.
|
||||
for t in ["Revolute", "pin-slot", "POINT ON PLANE", "rotate", "square"] {
|
||||
assert_eq!(issues("joint.create", json!({"type": t, "a": "A", "b": "B"})), none(), "{t}");
|
||||
}
|
||||
assert_eq!(issues("joint.create", json!({"type": "hinge", "a": "A", "b": "B"})).len(), 1);
|
||||
// `value` is read only when `values` is not a list; `values` and `limits` only as lists.
|
||||
assert_eq!(create(json!({"values": [1, "w / 2"], "value": true})), none());
|
||||
assert_eq!(create(json!({"value": true})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(create(json!({"value": "5 mm"})), none());
|
||||
assert_eq!(create(json!({"values": null, "value": 4})), none());
|
||||
assert_eq!(create(json!({"values": [true]})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(create(json!({"values": [1e12]})), ["a joint value must be a number between -1e9 and 1e9"]);
|
||||
assert_eq!(create(json!({"values": 5})), ["`values` must be a list of joint values"]);
|
||||
for limits in [json!([[0, 90]]), json!([null, ["-1 mm", "w"]]), json!([[1]]), json!([[]]), json!([[0, 1, true]]), json!(null), json!([])] {
|
||||
assert_eq!(create(json!({"limits": limits})), none(), "{limits}");
|
||||
}
|
||||
for limits in [json!([[true, 1]]), json!([[0, {}]]), json!([5]), json!({"a": 1}), json!("x")] {
|
||||
assert_eq!(create(json!({"limits": limits})).len(), 1, "{limits}");
|
||||
}
|
||||
// Numbers: `offset` and `angle` read `null` as a value, the flags and the name as absent.
|
||||
assert_eq!(create(json!({"offset": "w", "angle": 30, "flip": true, "name": "J", "quiet": false})), none());
|
||||
assert_eq!(create(json!({"offset": null})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(create(json!({"angle": {}})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(create(json!({"flip": null, "name": null, "quiet": null})), none());
|
||||
assert_eq!(create(json!({"flip": "yes"})), ["`flip` must be true or false"]);
|
||||
assert_eq!(create(json!({"name": 3})), ["`name` must be text"]);
|
||||
assert_eq!(create(json!({"quiet": 1})), ["`quiet` must be true or false"]);
|
||||
assert_eq!(create(json!({"nme": "J"})), ["unknown key `nme`; did you mean `name`?"]);
|
||||
|
||||
// joint.as_built: occurrences by id or name, `at` a joint origin, `values` only by being there.
|
||||
let built = |extra: Value| {
|
||||
let mut p = json!({"type": "rigid", "a": 0, "b": "Part"});
|
||||
p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
|
||||
issues("joint.as_built", p)
|
||||
};
|
||||
assert_eq!(built(json!({})), none());
|
||||
assert_eq!(built(json!({"at": {"face": "F"}, "name": "N", "limits": [[0, 1]], "quiet": true, "values": "anything", "value": {"x": 1}})), none());
|
||||
assert_eq!(built(json!({"a": true})), ["an occurrence must be an id or a name"]);
|
||||
assert_eq!(built(json!({"b": null})), ["an occurrence must be an id or a name"]);
|
||||
assert_eq!(built(json!({"at": null})), [why]);
|
||||
assert_eq!(built(json!({"at": []})), [why]);
|
||||
assert_eq!(issues("joint.as_built", json!({"type": "rigid"})), none());
|
||||
|
||||
// joint.drive: one coordinate with `index`, else `value` or a list of `values`.
|
||||
let drive = |p: Value| {
|
||||
let mut all = json!({"joint": "Hinge"});
|
||||
all.as_object_mut().into_iter().for_each(|o| o.extend(p.as_object().cloned().unwrap_or_default()));
|
||||
issues("joint.drive", all)
|
||||
};
|
||||
assert_eq!(drive(json!({"value": 45})), none());
|
||||
assert_eq!(drive(json!({"value": "pi rad", "quiet": true, "continuous": true})), none());
|
||||
assert_eq!(drive(json!({"values": [10, "w"]})), none());
|
||||
assert_eq!(drive(json!({"values": [10], "value": true})), none());
|
||||
assert_eq!(drive(json!({"values": null, "value": 5})), none());
|
||||
assert_eq!(drive(json!({})), none());
|
||||
assert_eq!(drive(json!({"index": 1, "value": 5})), none());
|
||||
assert_eq!(drive(json!({"index": 1, "value": 5, "values": [1]})), ["index goes with value, not values"]);
|
||||
assert_eq!(drive(json!({"index": 1, "values": null})), ["index goes with value, not values"]);
|
||||
assert_eq!(drive(json!({"index": 1})), none());
|
||||
assert_eq!(drive(json!({"index": "1", "value": 5})), ["index is outside this joint's coordinates"]);
|
||||
assert_eq!(drive(json!({"index": null, "value": 5})), ["index is outside this joint's coordinates"]);
|
||||
assert_eq!(drive(json!({"index": -1, "value": 5})), ["index is outside this joint's coordinates"]);
|
||||
assert_eq!(drive(json!({"index": 0, "value": true})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(drive(json!({"value": null})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(drive(json!({"values": [null]})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(drive(json!({"values": "x"})), ["`values` must be a list of joint values"]);
|
||||
assert_eq!(issues("joint.drive", json!({"value": 1})), none());
|
||||
assert_eq!(issues("joint.drive", json!({"joint": null, "value": 1})), ["`joint` must be an id or a name"]);
|
||||
assert_eq!(issues("joint.drive", json!({"joint": 3, "value": 1})), none());
|
||||
|
||||
// joint.limits: both or neither, the minimum read first; `index` a number.
|
||||
let limits = |p: Value| {
|
||||
let mut all = json!({"joint": 2});
|
||||
all.as_object_mut().into_iter().for_each(|o| o.extend(p.as_object().cloned().unwrap_or_default()));
|
||||
issues("joint.limits", all)
|
||||
};
|
||||
assert_eq!(limits(json!({})), none());
|
||||
assert_eq!(limits(json!({"min": -90, "max": "w / 2", "index": 0, "quiet": true})), none());
|
||||
assert_eq!(limits(json!({"index": -3.5})), none());
|
||||
assert_eq!(limits(json!({"min": 1})), ["give both `min` and `max`, or neither to clear"]);
|
||||
assert_eq!(limits(json!({"max": null})), ["give both `min` and `max`, or neither to clear"]);
|
||||
assert_eq!(limits(json!({"min": null, "max": 1})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(limits(json!({"min": 0, "max": true})), ["a joint value must be a number or an expression"]);
|
||||
assert_eq!(limits(json!({"index": "0"})), ["`index` must be a number"]);
|
||||
assert_eq!(limits(json!({"index": null})), none());
|
||||
|
||||
// joint.delete: a joint origin's name, else a motion link, else a joint; each mode reads only
|
||||
// its own keys.
|
||||
assert_eq!(issues("joint.delete", json!({"origin": "Top"})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"origin": "Top", "joint": true, "link": "x", "quiet": 5})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"link": 1})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"link": 1, "joint": [1], "quiet": "no"})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"link": 1e12, "joint": "Hinge"})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"joint": "Hinge", "quiet": true})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"origin": null, "link": null, "joint": 4})), none());
|
||||
assert_eq!(issues("joint.delete", json!({})), none());
|
||||
assert_eq!(issues("joint.delete", json!({"joint": true})), ["`joint` must be an id or a name"]);
|
||||
assert_eq!(issues("joint.delete", json!({"link": 1e12, "joint": true})), ["`joint` must be an id or a name"]);
|
||||
assert_eq!(issues("joint.delete", json!({"joint": 1, "quiet": 5})), ["`quiet` must be true or false"]);
|
||||
assert_eq!(issues("joint.delete", json!({"origin": 5, "joint": 1})), ["`origin` must be the name of a joint origin"]);
|
||||
assert_eq!(issues("joint.delete", json!({"link": "1", "joint": 1})), ["`link` must be a motion link's index, a number"]);
|
||||
|
||||
// joint.list, joint.solve and joint.inspect.
|
||||
for id in ["joint.list", "joint.solve"] {
|
||||
assert_eq!(issues(id, json!({"quiet": true})), none());
|
||||
assert_eq!(issues(id, json!({"quiet": null})), none());
|
||||
assert_eq!(issues(id, json!({"quiet": "x"})), ["`quiet` must be true or false"]);
|
||||
assert_eq!(issues(id, json!({"quet": true})), ["unknown key `quet`; did you mean `quiet`?"]);
|
||||
}
|
||||
assert_eq!(issues("joint.inspect", json!({})), none());
|
||||
assert_eq!(issues("joint.inspect", json!({"joint": null})), none());
|
||||
assert_eq!(issues("joint.inspect", json!({"joint": 4})), none());
|
||||
assert_eq!(issues("joint.inspect", json!({"joint": "Hinge"})), none());
|
||||
assert_eq!(issues("joint.inspect", json!({"joint": false})), ["`joint` must be an id or a name"]);
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need: the keys a handler refuses without are required, the
|
||||
/// modes are shown, and the values a handler reads are the ones the schemas take.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
let sides = json!({"a": {"face": [0, 0, 0]}, "b": "Origin"});
|
||||
let mut full = sides.clone();
|
||||
full["type"] = json!("revolute");
|
||||
let with = |extra: Value| {
|
||||
let mut p = full.clone();
|
||||
p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
|
||||
p
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<CreateJointParams>(),
|
||||
&[
|
||||
(full.clone(), true),
|
||||
(with(json!({"values": [1, "w"], "limits": [[0, 90], null], "flip": true, "offset": "w", "angle": 5, "name": "J", "quiet": true})), true),
|
||||
(with(json!({"value": 3})), true),
|
||||
(
|
||||
json!({"type": "revolute", "a": {"edge": {"x": 0, "y": 0, "z": 0}, "z": {"x": 0, "y": 0, "z": 1}}, "b": {"point": {"x": 1, "y": 2, "z": 3}}}),
|
||||
true,
|
||||
),
|
||||
(json!({"type": "revolute", "a": {"edge": {"x": 0, "y": 0}}, "b": "Origin"}), false),
|
||||
(json!({"a": {"face": [0, 0, 0]}, "b": "Origin"}), false),
|
||||
(json!({"type": "revolute", "b": "Origin"}), false),
|
||||
(json!({"type": "revolute", "a": 5, "b": "Origin"}), false),
|
||||
(with(json!({"values": 5})), false),
|
||||
// The schema can't spell the type's leniency; the type refuses "hinge" (see above).
|
||||
(with(json!({"type": 5})), false),
|
||||
(with(json!({"type": "Pin Slot"})), true),
|
||||
(with(json!({"type": "REVOLUTE"})), true),
|
||||
(with(json!({"offset": true})), false),
|
||||
(with(json!({"limits": [[true, 1]]})), false),
|
||||
(with(json!({"nme": "J"})), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<AsBuiltJointParams>(),
|
||||
&[
|
||||
(json!({"type": "rigid", "a": 0, "b": "Part"}), true),
|
||||
(json!({"type": "rigid", "a": "A", "b": 3, "at": {"circle": [0, 0, 0]}, "limits": [null], "values": [1]}), true),
|
||||
(json!({"type": "rigid", "a": 0}), false),
|
||||
(json!({"type": "rigid", "a": true, "b": 0}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<DriveJointParams>(),
|
||||
&[
|
||||
(json!({"joint": "Hinge", "value": 45}), true),
|
||||
(json!({"joint": 1, "values": [1, "w"], "quiet": true, "continuous": true}), true),
|
||||
(json!({"joint": 1, "index": 1, "value": "w"}), true),
|
||||
(json!({"value": 45}), false),
|
||||
(json!({"joint": "Hinge"}), false),
|
||||
(json!({"joint": "Hinge", "index": 0, "values": [1]}), false),
|
||||
(json!({"joint": "Hinge", "index": -1, "value": 1}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<JointLimitsParams>(),
|
||||
&[
|
||||
(json!({"joint": "Hinge"}), true),
|
||||
(json!({"joint": 1, "index": 1, "min": -1, "max": "w"}), true),
|
||||
(json!({"index": 1}), false),
|
||||
(json!({"joint": 1, "min": true, "max": 1}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<DeleteJointParams>(),
|
||||
&[
|
||||
(json!({"joint": "Hinge", "quiet": true}), true),
|
||||
(json!({"origin": "Top"}), true),
|
||||
(json!({"link": 2}), true),
|
||||
(json!({}), false),
|
||||
(json!({"quiet": true}), false),
|
||||
(json!({"joint": true}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<InspectJointParams>(),
|
||||
&[(json!({}), true), (json!({"joint": "J"}), true), (json!({"joint": 4}), true), (json!({"joint": true}), false)],
|
||||
);
|
||||
takes(input_schema_for::<ListJointsParams>(), &[(json!({}), true), (json!({"quiet": false}), true), (json!({"quiet": 1}), false)]);
|
||||
takes(input_schema_for::<SolveJointsParams>(), &[(json!({}), true), (json!({"quiet": false}), true), (json!({"quiet": 1}), false)]);
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// Hinge leaves, a slider, a screw, a joint origin and two loose parts joined to each other: each
|
||||
/// command, run in Warn in every form it takes, gives a reply that matches its output schema and
|
||||
/// carries no warning.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
for name in ["LeafA", "LeafB", "LeafC", "LeafD", "LeafE"] {
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
let made = run("component.create", json!({"name": name, "grounded": false}));
|
||||
run("solid.box", json!({"length": 40, "width": 30, "height": 3, "corner": [0, 0, 0]}));
|
||||
run("solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));
|
||||
if name == "LeafA" {
|
||||
run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));
|
||||
}
|
||||
}
|
||||
let hinge = |a: &str, b: &str, name: &str| json!({"type": "revolute", "a": {"occurrence": a, "circle": [1, 37, 4]}, "b": {"occurrence": b, "circle": [1, 37, 4]}, "flip": true, "name": name});
|
||||
|
||||
// joint.create, in the forms of a side, with a value held inside its limits, and as built.
|
||||
let made = run("joint.create", with_limits(hinge("LeafA", "LeafB", "Hinge"), json!([[-90, 90]])));
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.create", &made);
|
||||
assert!(made.get("warnings").is_none() && made["name"] == "Hinge" && made.get("dof").is_some(), "{made}");
|
||||
let quiet = run("joint.create", with_extra(hinge("LeafC", "LeafB", "Quiet"), json!({"quiet": true, "value": 30, "limits": [null]})));
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.create", &quiet);
|
||||
assert!(quiet.get("dof").is_none() && quiet.get("fixed").is_none(), "{quiet}");
|
||||
run("joint.delete", json!({"joint": "Quiet"}));
|
||||
let clamped = run("joint.create", with_extra(hinge("LeafD", "LeafE", "Clamped"), json!({"values": [100], "limits": [[-10, 10]]})));
|
||||
assert!(clamped["warnings"].as_array().is_some_and(|w| w.len() == 1), "{clamped}");
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.create", &clamped);
|
||||
run("joint.origin", json!({"occurrence": "LeafA", "face": [20, 15, 3], "name": "Top"}));
|
||||
let by_origin = run(
|
||||
"joint.create",
|
||||
json!({"type": "rigid", "a": "Top", "b": {"occurrence": "LeafC", "face": [20, 15, 0]}, "name": "Stack", "offset": "0 mm", "angle": 0}),
|
||||
);
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.create", &by_origin);
|
||||
let built = run("joint.as_built", json!({"type": "slider", "a": "LeafB", "b": "LeafC", "name": "Slide", "limits": [[0, 10]], "quiet": false}));
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.as_built", &built);
|
||||
let at = run("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafD", "at": {"point": [0, 0, 0]}, "values": [1]}));
|
||||
matches(output_schema_for::<JointAddedResult>(), "joint.as_built", &at);
|
||||
run("joint.delete", json!({"joint": at["joint"]}));
|
||||
|
||||
// A screw ties Slide's travel to Hinge's turn: a coupling for the list.
|
||||
run("joint.screw", json!({"a": "Hinge", "b": "Slide", "pitch": 2}));
|
||||
|
||||
let list = run("joint.list", json!({}));
|
||||
matches(output_schema_for::<ListJointsResult>(), "joint.list", &list);
|
||||
assert!(list["links"].as_array().is_some_and(|l| l.len() == 1) && list["links"][0]["coupling"]["type"] == "screw", "{list}");
|
||||
assert!(list["joints"].as_array().is_some_and(|j| j.len() == 4) && list["origins"][0]["name"] == "Top", "{list}");
|
||||
assert!(list["floating"].as_array().is_some_and(|f| f.len() == 1), "{list}");
|
||||
let quiet = run("joint.list", json!({"quiet": true}));
|
||||
matches(output_schema_for::<ListJointsResult>(), "joint.list", &quiet);
|
||||
assert!(quiet.get("dof").is_none(), "{quiet}");
|
||||
|
||||
for p in [json!({}), json!({"joint": "Slide"}), json!({"joint": null}), json!({"joint": made["joint"]})] {
|
||||
let inspected = run("joint.inspect", p);
|
||||
matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &inspected);
|
||||
}
|
||||
let inspected = run("joint.inspect", json!({"joint": "Hinge"}));
|
||||
assert!(inspected["joints"][0]["links"][0]["role"] == "driver" && inspected["joints"][0]["a"]["references"].as_array().is_some(), "{inspected}");
|
||||
|
||||
// joint.drive: a value, a list, one coordinate, past a limit, a drag frame, a suppressed joint
|
||||
// and one joined to nothing grounded.
|
||||
for p in [
|
||||
json!({"joint": "Hinge", "value": 45}),
|
||||
json!({"joint": "Hinge", "values": [30]}),
|
||||
json!({"joint": "Hinge", "index": 0, "value": "20 deg", "quiet": true}),
|
||||
json!({"joint": "Hinge", "value": 50, "continuous": true}),
|
||||
json!({"joint": "Slide", "value": 3}),
|
||||
] {
|
||||
let driven = run("joint.drive", p);
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &driven);
|
||||
}
|
||||
let held = run("joint.drive", json!({"joint": "Hinge", "value": 200}));
|
||||
assert!(held["held"][0]["why"].as_str().is_some_and(|w| w.contains("limits")), "{held}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &held);
|
||||
let linked = run("joint.drive", json!({"joint": "Slide", "value": 5}));
|
||||
assert!(linked["held"][0]["why"].as_str().is_some_and(|w| w.contains("motion link")), "{linked}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &linked);
|
||||
let loose = run("joint.drive", json!({"joint": "Clamped", "value": 5}));
|
||||
assert!(loose["unconnected"].is_string() && loose["reason"].is_string(), "{loose}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &loose);
|
||||
run("joint.edit", json!({"joint": "Stack", "type": "revolute"}));
|
||||
let turned = run("joint.drive", json!({"joint": "Stack", "value": 1}));
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &turned);
|
||||
run("joint.edit", json!({"joint": "Stack", "suppressed": true}));
|
||||
let hidden = run("joint.drive", json!({"joint": "Stack", "value": 2}));
|
||||
assert!(hidden["reason"].as_str().is_some_and(|r| r.contains("suppressed")), "{hidden}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &hidden);
|
||||
|
||||
// joint.limits and joint.solve.
|
||||
for p in [
|
||||
json!({"joint": "Hinge", "min": -45, "max": "45 deg"}),
|
||||
json!({"joint": "Hinge", "index": 0, "min": -10, "max": 10, "quiet": true}),
|
||||
json!({"joint": "Hinge"}),
|
||||
] {
|
||||
let limited = run("joint.limits", p);
|
||||
matches(output_schema_for::<SolveResult>(), "joint.limits", &limited);
|
||||
}
|
||||
for p in [json!({}), json!({"quiet": true})] {
|
||||
let solved = run("joint.solve", p);
|
||||
matches(output_schema_for::<SolveResult>(), "joint.solve", &solved);
|
||||
}
|
||||
|
||||
// joint.delete: a motion link, a joint origin, a joint.
|
||||
let link = run("joint.delete", json!({"link": 0}));
|
||||
assert_eq!(link["deleted_link"], 0, "{link}");
|
||||
matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &link);
|
||||
let origin = run("joint.delete", json!({"origin": "Top", "joint": true, "link": "x"}));
|
||||
assert_eq!((origin["deleted_origin"].clone(), origin["joints"].clone()), (json!("Top"), json!(4)), "{origin}");
|
||||
matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &origin);
|
||||
let deleted = run("joint.delete", json!({"joint": "Stack"}));
|
||||
assert!(deleted["deleted"].is_u64() && deleted.get("dof").is_some(), "{deleted}");
|
||||
matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &deleted);
|
||||
let quiet = run("joint.delete", json!({"joint": "Clamped", "quiet": true}));
|
||||
assert!(quiet.get("dof").is_none() && quiet["deleted"].is_u64(), "{quiet}");
|
||||
matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &quiet);
|
||||
}
|
||||
|
||||
fn with_limits(mut p: Value, limits: Value) -> Value {
|
||||
p["limits"] = limits;
|
||||
p
|
||||
}
|
||||
|
||||
fn with_extra(mut p: Value, extra: Value) -> Value {
|
||||
if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
|
||||
o.extend(e.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// A misspelt key still runs in Warn, says so, and the reply still matches its schema.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_in_warn() {
|
||||
let mut s = hinged(ParamCheck::Warn);
|
||||
let calls = [
|
||||
("joint.create", json!({"type": "rigid", "a": "Top", "b": {"occurrence": "LeafB", "face": [20, 15, 0]}, "nme": "J"}), "name"),
|
||||
("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafB", "nam": "As built"}), "name"),
|
||||
("joint.drive", json!({"joint": "Hinge", "valu": 10, "value": 10}), "value"),
|
||||
("joint.limits", json!({"joint": "Hinge", "mn": 1, "min": -10, "max": 10}), "min"),
|
||||
("joint.list", json!({"quet": true}), "quet"),
|
||||
("joint.inspect", json!({"joynt": "Hinge"}), "joint"),
|
||||
("joint.solve", json!({"quet": true}), "quet"),
|
||||
("joint.delete", json!({"origin": "Top", "oringin": 1}), "origin"),
|
||||
];
|
||||
for (id, p, near) in calls {
|
||||
let reply = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key") && w.contains(near)), "{id}: {reply}");
|
||||
let out = crate::cmd::find_command(id).and_then(|c| c.output).map(|f| f()).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(conforms(out.as_value(), out.as_value(), &reply), "{id}: {reply} doesn't match {}", out.as_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// A cam on a revolute joint: `joint.list` and `joint.inspect` give its follower's lift, a table
|
||||
/// that is not whole as `null`, and the replies match their schemas.
|
||||
#[test]
|
||||
fn a_cam_link_shows_its_lift() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let part = |run: &mut dyn FnMut(&str, Value) -> Value, name: &str, corner: [f64; 3]| {
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
let made = run("component.create", json!({"name": name, "grounded": false}));
|
||||
run("solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": corner}));
|
||||
made["occurrence"].clone()
|
||||
};
|
||||
let pin = |run: &mut dyn FnMut(&str, Value) -> Value, kind: &str, name: &str, a: &str, b: &str, p: Vec3, z: Vec3| {
|
||||
let at = |o: &str| json!({"occurrence": o, "point": [p.x, p.y, p.z], "z": [z.x, z.y, z.z]});
|
||||
run("joint.create", json!({"type": kind, "a": at(a), "b": at(b), "flip": true, "name": name}));
|
||||
};
|
||||
let occurrence = part(&mut run, "Base", [-90.0, -90.0, -20.0]);
|
||||
run("occurrence.ground", json!({"occurrence": occurrence, "grounded": true}));
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
run("component.create", json!({"name": "Cam"}));
|
||||
run("sketch.create", json!({"plane": "XY", "name": "CamSketch"}));
|
||||
run("sketch.circle.center", json!({"center": [10, 0], "radius": 30, "id": "c1"}));
|
||||
run("sketch.finish", json!({}));
|
||||
run("solid.extrude", json!({"distance": 5}));
|
||||
pin(&mut run, "revolute", "Cam", "Base", "Cam", Vec3::ZERO, Vec3::Z);
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
run("component.create", json!({"name": "Tappet"}));
|
||||
run("solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [40, -2, 0]}));
|
||||
pin(&mut run, "slider", "Tappet", "Base", "Tappet", Vec3::new(0.0, 0.0, 2.5), Vec3::X);
|
||||
run("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
let list = run("joint.list", json!({}));
|
||||
let schema = output_schema_for::<ListJointsResult>();
|
||||
assert!(list["links"][0]["lift"]["rise"].is_number() && list["links"][0].get("ratio").is_none(), "{list}");
|
||||
assert!(list["links"][0]["coupling"]["type"] == "cam" && conforms(schema.as_value(), schema.as_value(), &list), "{list}");
|
||||
let inspected = run("joint.inspect", json!({"joint": "Tappet"}));
|
||||
let schema = output_schema_for::<InspectJointResult>();
|
||||
assert!(inspected["joints"][0]["links"][0]["role"] == "driven" && conforms(schema.as_value(), schema.as_value(), &inspected), "{inspected}");
|
||||
// A table that is not whole moves nothing, and says `null`.
|
||||
if let Some(l) = s.doc_mut().assembly.links.first_mut() {
|
||||
l.lift.truncate(3);
|
||||
}
|
||||
let broken = s.execute("joint.list", &json!({})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let schema = output_schema_for::<ListJointsResult>();
|
||||
assert!(broken["links"][0]["lift"].is_null() && broken["links"][0].get("lift").is_some(), "{broken}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &broken), "{broken}");
|
||||
}
|
||||
|
||||
/// A slider stopped by contact: the bodies that touched and how far it got, in the reply.
|
||||
#[test]
|
||||
fn a_drive_stopped_by_contact_matches_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
for (name, x) in [("A", 0), ("B", 20)] {
|
||||
run("component.activate", json!({"component": 0}));
|
||||
let made = run("component.create", json!({"name": name}));
|
||||
run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]}));
|
||||
if name == "A" {
|
||||
run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));
|
||||
}
|
||||
}
|
||||
run("joint.create", json!({"type": "slider", "a": {"face": [10, 5, 5]}, "b": {"face": [20, 5, 5]}, "name": "Rail"}));
|
||||
run("contact.create", json!({"occurrences": ["A", "B"]}));
|
||||
let free = run("joint.drive", json!({"joint": "Rail", "value": 10}));
|
||||
assert!(free["stopped_by_contact"].is_null() && free["stopped_by_loop"].is_null(), "{free}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &free);
|
||||
let stopped = run("joint.drive", json!({"joint": "Rail", "value": -30}));
|
||||
assert!(stopped["stopped_by_contact"]["fraction"].is_number() && stopped["stopped_by_contact"]["a"].is_string(), "{stopped}");
|
||||
assert!(stopped["held"][0]["why"].as_str().is_some_and(|w| w.contains("contact")), "{stopped}");
|
||||
matches(output_schema_for::<DriveJointResult>(), "joint.drive", &stopped);
|
||||
}
|
||||
|
||||
/// An origin on an edge names the edge and its two faces; a round origin on an extruded circle
|
||||
/// names the sketch curve its wall was swept from.
|
||||
#[test]
|
||||
fn inspect_names_what_edges_and_swept_faces_refer_to() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let panel = run("component.create", json!({"name": "Panel"}));
|
||||
run("solid.box", json!({"length": 400, "width": 300, "height": 2, "corner": [0, 0, 0]}));
|
||||
run("occurrence.ground", json!({"occurrence": panel["occurrence"], "grounded": true}));
|
||||
run("component.activate", json!({"component": "root"}));
|
||||
run("component.create", json!({"name": "Pin"}));
|
||||
run("sketch.create", json!({"plane": "XY", "name": "PinSketch"}));
|
||||
run("sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c1"}));
|
||||
run("sketch.finish", json!({}));
|
||||
run("solid.extrude", json!({"distance": 20}));
|
||||
run(
|
||||
"joint.create",
|
||||
json!({"type": "revolute", "name": "Edge", "a": {"occurrence": "Panel", "edge": [200, 0, 2]}, "b": {"occurrence": "Pin", "circle": [105, 0, 20]}}),
|
||||
);
|
||||
let inspected = run("joint.inspect", json!({"joint": "Edge"}));
|
||||
matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &inspected);
|
||||
let side = |s: &str, role: &str| inspected["joints"][0][s]["references"].as_array().and_then(|r| r.iter().find(|r| r["role"] == role)).cloned();
|
||||
let edge = side("a", "edge").unwrap_or_default();
|
||||
assert!(edge["faces"].as_array().is_some_and(|f| f.len() == 2 && f[0]["feature"]["type"] == "BoxFeature"), "{inspected}");
|
||||
let wall = side("b", "face").unwrap_or_default();
|
||||
assert_eq!((wall["sketch"]["name"].clone(), wall["sketch"]["curve_type"].clone()), (json!("PinSketch"), json!("circle")), "{inspected}");
|
||||
// The extrude goes: the names are kept, and say what is gone.
|
||||
run("timeline.delete", json!({"feature": "Extrude1"}));
|
||||
let gone = run("joint.inspect", json!({"joint": "Edge"}));
|
||||
assert!(gone["joints"][0]["b"]["resolves"] == false && gone["joints"][0]["b"]["error"].is_string(), "{gone}");
|
||||
matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &gone);
|
||||
}
|
||||
|
||||
/// The contract looks at every key before the handler looks at the design, so a call with two
|
||||
/// problems may name another one in strict than the handler does (the documented difference), and
|
||||
/// a call the handler ignores a wrong-typed key in is refused (the stricter reading).
|
||||
#[test]
|
||||
fn strict_may_name_another_problem_first_and_refuses_ignored_wrong_types() {
|
||||
let strict = |id: &str, p: Value| hinged(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string());
|
||||
let off = |id: &str, p: Value| hinged(ParamCheck::Off).execute(id, &p).err().map(|e| e.to_string());
|
||||
for (id, p) in
|
||||
[("joint.drive", json!({"joint": "nope", "index": "x", "value": 1})), ("joint.limits", json!({"joint": "Hinge", "index": 9, "min": 0}))]
|
||||
{
|
||||
assert!(off(id, p.clone()).is_some() && strict(id, p.clone()).is_some() && off(id, p.clone()) != strict(id, p), "{id}");
|
||||
}
|
||||
for (id, p) in [
|
||||
("joint.limits", json!({"joint": "Hinge", "limits": [5]})),
|
||||
("joint.limits", json!({"joint": "Hinge", "index": "0", "min": 1, "max": 2})),
|
||||
("joint.solve", json!({"quiet": "yes"})),
|
||||
("joint.delete", json!({"joint": "Hinge", "link": "x"})),
|
||||
("joint.delete", json!({"joint": "Hinge", "origin": 5})),
|
||||
] {
|
||||
let works = |level| hinged(level).execute(id, &p).is_ok();
|
||||
assert!(works(ParamCheck::Off) && !works(ParamCheck::Strict), "{id} {p}");
|
||||
}
|
||||
let schema = output_schema_for::<EditJointResult>();
|
||||
let schema = schema.as_value();
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
|
||||
s.execute("component.create", &json!({"name": "B", "grounded": false})).unwrap_or_else(|e| panic!("{e}"));
|
||||
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]})).unwrap_or_else(|e| panic!("{e}"));
|
||||
s.execute("joint.create", &json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}))
|
||||
.unwrap_or_else(|e| panic!("{e}"));
|
||||
let full = s.execute("joint.edit", &json!({"joint": "Stack", "flip": true})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(conforms(schema, schema, &full), "{full} doesn't match {schema}");
|
||||
let quiet = s.execute("joint.edit", &json!({"joint": "Stack", "quiet": true})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(quiet.get("dof").is_none() && conforms(schema, schema, &quiet), "{quiet}");
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ pub mod edit;
|
||||
pub mod features;
|
||||
pub mod features_more;
|
||||
pub mod file;
|
||||
pub mod frame;
|
||||
pub mod inspect;
|
||||
pub mod interference;
|
||||
pub mod joints;
|
||||
@@ -111,11 +110,9 @@ pub mod sketch_ends;
|
||||
pub mod sketch_equation;
|
||||
pub mod sketch_inspect;
|
||||
pub mod sketch_modify;
|
||||
pub mod sketch_shapes;
|
||||
pub mod surface_analysis;
|
||||
pub mod surface_boundary;
|
||||
pub mod surface_match;
|
||||
pub mod timeline_clipboard;
|
||||
pub mod ui_prefs;
|
||||
pub mod view_navigation;
|
||||
|
||||
|
||||
@@ -7,9 +7,7 @@ use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use solidcraft_geom::Vec3Geom as _;
|
||||
|
||||
use super::check::{located, whole};
|
||||
use super::check::whole;
|
||||
|
||||
/// Find where each value of a joint can go before the parts it moves touch another body. The
|
||||
/// design is not changed.
|
||||
@@ -627,268 +625,6 @@ pub struct MotionStudyDeleted {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- Exploded views (#12501) ----
|
||||
//
|
||||
// The exploded view handlers read their parameters from the raw JSON, so each key here reads as
|
||||
// its handler reads it and fails with its message. Whether an occurrence or a view exists stays
|
||||
// the handler's to check.
|
||||
|
||||
/// Make an exploded view: occurrences moved apart, shown with `explode.show`. The design keeps
|
||||
/// its placements. One undo step. With `moves`, each occurrence moves as given; without, every
|
||||
/// top-level occurrence is pushed away from the assembly's centre by `scale` times its offset.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExplodeCreateKeys {
|
||||
/// The view's name. Default: "Exploded View" and the first number no view's name has.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
/// For the automatic view: how far each occurrence is pushed away from the assembly's
|
||||
/// centre, as a multiple of its offset from it (a number from -100 to 100). Default: 1.
|
||||
/// Not read, and so not checked, when `moves` is given.
|
||||
#[serde(default, deserialize_with = "explode_scale", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "explode_scale_schema")]
|
||||
pub scale: Option<f64>,
|
||||
/// The moves, instead of the automatic view (at most 10 000): each an `occurrence` (by id or
|
||||
/// name, or a component's name for its first occurrence) and its `translate`, in mm, as
|
||||
/// [x, y, z] or {x, y, z}, less than 1e7 in length. An occurrence named twice is moved by
|
||||
/// the last.
|
||||
#[serde(default, deserialize_with = "explode_moves", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "explode_moves_schema")]
|
||||
pub moves: Option<Vec<Value>>,
|
||||
}
|
||||
|
||||
/// `explode.create`'s parameters: [`ExplodeCreateKeys`], where `scale` is read only without
|
||||
/// `moves`, as the handler does.
|
||||
#[derive(Debug)]
|
||||
pub struct ExplodeCreateParams(pub ExplodeCreateKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ExplodeCreateParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
// `moves`, even `null`, is what the handler goes by: it never reads `scale` then.
|
||||
if let Some(keys) = value.as_object_mut()
|
||||
&& keys.contains_key("moves")
|
||||
{
|
||||
keys.remove("scale");
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ExplodeCreateParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ExplodeCreateParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ExplodeCreateParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ExplodeCreateKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// `scale`: a number of at most 100 in size, with the handler's message for anything else,
|
||||
/// `null` included.
|
||||
fn explode_scale<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
|
||||
Value::deserialize(d)?
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && x.abs() <= 100.0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| D::Error::custom(whole("`scale` must be a number up to 100")))
|
||||
}
|
||||
|
||||
fn explode_scale_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "For the automatic view: how far each occurrence is pushed away from the assembly's centre, as a multiple of its offset from it (a number from -100 to 100). Default: 1. Not read, and so not checked, when `moves` is given.",
|
||||
"type": "number",
|
||||
"minimum": -100,
|
||||
"maximum": 100
|
||||
})
|
||||
}
|
||||
|
||||
/// Why the handler refuses `item`, one of `moves`, before looking at the design.
|
||||
/// The handler also looks each occurrence up as it goes, so a call with an unknown occurrence in
|
||||
/// an earlier move and a malformed later one gets the handler's "no occurrence" message with the
|
||||
/// check off and this shape message in strict; both refuse the call.
|
||||
fn explode_move_problem(item: &Value) -> Option<&'static str> {
|
||||
if !matches!(item.get("occurrence"), Some(Value::Number(_) | Value::String(_))) {
|
||||
return Some("an occurrence must be an id or a name");
|
||||
}
|
||||
let translate = item.get("translate").and_then(crate::params::vec3).filter(|v| v.len() < 1e7);
|
||||
translate.is_none().then_some("each move needs `translate`: [x, y, z]")
|
||||
}
|
||||
|
||||
/// `moves`: a list of at most 10 000 moves, each checked as [`explode_move_problem`] says. Given,
|
||||
/// `null` included, it must be a list, as the handler reads it.
|
||||
fn explode_moves<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<Value>>, D::Error> {
|
||||
let Value::Array(moves) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom(whole("`moves` must be a list")));
|
||||
};
|
||||
if moves.len() > MAX_EXPLODE_ITEMS {
|
||||
return Err(D::Error::custom(whole("too many moves")));
|
||||
}
|
||||
if let Some(problem) = moves.iter().find_map(explode_move_problem) {
|
||||
return Err(D::Error::custom(whole(problem)));
|
||||
}
|
||||
Ok(Some(moves))
|
||||
}
|
||||
|
||||
/// The most moves a view takes, and the most views a design has, as `cmd/motion.rs`'s `MAX_ITEMS`.
|
||||
const MAX_EXPLODE_ITEMS: usize = 10_000;
|
||||
|
||||
fn explode_moves_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let c = json!({"type": "number", "exclusiveMinimum": -1e7, "exclusiveMaximum": 1e7});
|
||||
json_schema!({
|
||||
"description": "The moves, instead of the automatic view (at most 10 000): each an `occurrence` (by id or name, or a component's name for its first occurrence) and its `translate`, in mm, as [x, y, z] or {x, y, z}, less than 1e7 in length. An occurrence named twice is moved by the last.",
|
||||
"type": "array",
|
||||
"maxItems": MAX_EXPLODE_ITEMS,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["occurrence", "translate"],
|
||||
"properties": {
|
||||
"occurrence": {"type": ["number", "string"]},
|
||||
"translate": {
|
||||
"anyOf": [
|
||||
{"type": "array", "items": c, "minItems": 3, "maxItems": 3},
|
||||
{"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// An exploded view by its id (a number) or its name.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ViewRef(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for ViewRef {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
v @ (Value::Number(_) | Value::String(_)) => Ok(ViewRef(v)),
|
||||
_ => Err(D::Error::custom(whole("`view` must be an id or a name"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ViewRef {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ViewRef".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "An exploded view's id (a number) or its name.", "type": ["number", "string"]})
|
||||
}
|
||||
}
|
||||
|
||||
/// Show an exploded view in the model: the occurrences are drawn moved apart, and the design
|
||||
/// keeps its placements. Without a view (or `none`), show the assembled placement again.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExplodeShowParams {
|
||||
/// The view to show, by id (a number) or name. Default: none, which shows the assembled
|
||||
/// placement; `null` and the text `none` (in any case) mean the same.
|
||||
#[serde(default)]
|
||||
pub view: Option<ViewRef>,
|
||||
}
|
||||
|
||||
/// List the design's exploded views. Nothing is changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExplodeListParams {}
|
||||
|
||||
/// Delete an exploded view. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = view_required)]
|
||||
pub struct ExplodeDeleteParams {
|
||||
// Required in the schema (`view_required`), optional in the type: left out, the handler
|
||||
// refuses it with its own message, not the check's "is required". `null` is refused too.
|
||||
/// The view to delete, by id (a number) or name.
|
||||
#[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ViewRef")]
|
||||
pub view: Option<ViewRef>,
|
||||
}
|
||||
|
||||
/// `view`: an id or a name, with the handler's message for anything else, `null` included.
|
||||
fn some_view<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ViewRef>, D::Error> {
|
||||
ViewRef::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
fn view_required(schema: &mut Schema) {
|
||||
require(schema, "view");
|
||||
}
|
||||
|
||||
/// One move of an exploded view.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodeMoveInfo {
|
||||
/// The occurrence, by id.
|
||||
pub occurrence: u64,
|
||||
/// How far it moves, in mm (world).
|
||||
pub translate: [f64; 3],
|
||||
}
|
||||
|
||||
impl From<&(u64, solidcore_record::Vec3)> for ExplodeMoveInfo {
|
||||
fn from((occurrence, t): &(u64, solidcore_record::Vec3)) -> Self {
|
||||
ExplodeMoveInfo { occurrence: *occurrence, translate: [t.x, t.y, t.z] }
|
||||
}
|
||||
}
|
||||
|
||||
/// What `explode.create` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodeCreated {
|
||||
/// The new view's id.
|
||||
pub view: u64,
|
||||
pub name: String,
|
||||
pub moves: Vec<ExplodeMoveInfo>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `explode.show` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodeShown {
|
||||
/// The view shown, by id; `null` when the assembled placement is shown.
|
||||
pub view: Option<u64>,
|
||||
/// The view's name; not there when the assembled placement is shown.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `explode.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodeViews {
|
||||
pub views: Vec<ExplodedViewInfo>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// An exploded view, as the design saves it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodedViewInfo {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// [occurrence id, translation in mm] pairs.
|
||||
pub moves: Vec<(u64, [f64; 3])>,
|
||||
}
|
||||
|
||||
impl From<&solidcraft_doc::motion::ExplodedView> for ExplodedViewInfo {
|
||||
fn from(view: &solidcraft_doc::motion::ExplodedView) -> Self {
|
||||
let moves = view.moves.iter().map(|(o, t)| (*o, [t.x, t.y, t.z])).collect();
|
||||
ExplodedViewInfo { id: view.id, name: view.name.clone(), moves }
|
||||
}
|
||||
}
|
||||
|
||||
/// What `explode.delete` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExplodeDeleted {
|
||||
/// The deleted view's name.
|
||||
pub deleted: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "motion_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -2,8 +2,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
ContactCheck, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetCreated, ContactSetEdited, ContactSets,
|
||||
ContactSwitch, ExplodeCreateParams, ExplodeCreated, ExplodeDeleteParams, ExplodeDeleted, ExplodeListParams, ExplodeShowParams, ExplodeShown,
|
||||
ExplodeViews, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted,
|
||||
ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted,
|
||||
MotionStudyParams, MotionStudySaved,
|
||||
};
|
||||
use crate::Session;
|
||||
@@ -20,10 +19,6 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<MotionStudyParams>(), &["keys", "name", "steps", "study"]);
|
||||
assert_keys(input_schema_for::<MotionListParams>(), &[]);
|
||||
assert_keys(input_schema_for::<MotionStudyDeleteParams>(), &["study"]);
|
||||
assert_keys(input_schema_for::<ExplodeCreateParams>(), &["moves", "name", "scale"]);
|
||||
assert_keys(input_schema_for::<ExplodeShowParams>(), &["view"]);
|
||||
assert_keys(input_schema_for::<ExplodeListParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ExplodeDeleteParams>(), &["view"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -264,203 +259,3 @@ fn motion_studies_reply_with_their_schemas() {
|
||||
let error = s.execute("motion.study", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`step`"), "{error}");
|
||||
}
|
||||
|
||||
/// The exploded view commands in a design with three occurrences, in Off and in Strict: each call
|
||||
/// the handler refuses is refused with the same message. They need the door's occurrences, so
|
||||
/// the shared helper doesn't fit.
|
||||
#[test]
|
||||
fn strict_keeps_the_exploded_views_errors() {
|
||||
let many: Vec<Value> = (0..10_001).map(|_| move_of(json!("Door"), json!([1, 2, 3]))).collect();
|
||||
for (id, p) in [
|
||||
("explode.create", json!({"moves": null})),
|
||||
("explode.create", json!({"moves": "Door"})),
|
||||
("explode.create", json!({"moves": {"occurrence": "Door", "translate": [1, 2, 3]}})),
|
||||
("explode.create", json!({"moves": many})),
|
||||
("explode.create", json!({"moves": [{}]})),
|
||||
("explode.create", json!({"moves": [true]})),
|
||||
("explode.create", json!({"moves": [move_of(json!(null), json!([1, 2, 3]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!(true), json!([1, 2, 3]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!(["Door"]), json!([1, 2, 3]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Nope"), json!([1, 2, 3]))]})),
|
||||
("explode.create", json!({"moves": [{"occurrence": "Door"}]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!(null))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!([1, 2]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!({"x": 1, "y": 2}))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!(["a", 2, 3]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!([1e7, 0, 0]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!([8e6, 8e6, 0]))]})),
|
||||
("explode.create", json!({"moves": [move_of(json!("Door"), json!([1, 2, 3])), {"translate": [1, 2, 3]}]})),
|
||||
("explode.create", json!({"scale": "2"})),
|
||||
("explode.create", json!({"scale": null})),
|
||||
("explode.create", json!({"scale": true})),
|
||||
("explode.create", json!({"scale": 100.5})),
|
||||
("explode.create", json!({"scale": -101})),
|
||||
("explode.show", json!({"view": true})),
|
||||
("explode.show", json!({"view": [1]})),
|
||||
("explode.show", json!({"view": {"id": 1}})),
|
||||
("explode.show", json!({"view": "Nope"})),
|
||||
("explode.show", json!({"view": 7})),
|
||||
("explode.delete", json!({})),
|
||||
("explode.delete", json!({"view": null})),
|
||||
("explode.delete", json!({"view": false})),
|
||||
("explode.delete", json!({"view": ["Apart"]})),
|
||||
("explode.delete", json!({"view": "Nope"})),
|
||||
] {
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = door();
|
||||
s.param_check = level;
|
||||
s.execute(id, &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
fn move_of(occurrence: Value, translate: Value) -> Value {
|
||||
json!({"occurrence": occurrence, "translate": translate})
|
||||
}
|
||||
|
||||
/// The exploded view types read each key as the handlers do: `scale` only without `moves`, a move
|
||||
/// by an occurrence's id or name with a point in either form, `view` left out, `null` or `none`
|
||||
/// to show the assembled placement but refused by `explode.delete`, and keys a move carries
|
||||
/// besides its two ignored. Each case is also checked against the schema.
|
||||
#[test]
|
||||
fn the_exploded_view_types_read_the_keys_as_the_handlers_do() {
|
||||
let issues = |id: &str, p: &Value| crate::schema::issues(id, p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
let ok = |id: &str, p: Value, takes: bool| assert_eq!(issues(id, &p).is_empty(), takes, "{id} {p}: {:?}", issues(id, &p));
|
||||
let schema_takes = |schema: schemars::Schema, p: Value, takes: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert_eq!(conforms(schema, schema, &p), takes, "{p}");
|
||||
};
|
||||
// `scale` is read only when `moves` is not there; `moves` is read when it is there at all.
|
||||
let one = move_of(json!(3), json!({"x": 1, "y": 2, "z": 3}));
|
||||
for (p, takes) in [
|
||||
(json!({}), true),
|
||||
(json!({"name": "Apart", "scale": 2.5}), true),
|
||||
(json!({"scale": -100}), true),
|
||||
(json!({"scale": 101}), false),
|
||||
(json!({"scale": "2"}), false),
|
||||
(json!({"scale": null}), false),
|
||||
(json!({"moves": [], "scale": "ignored"}), true),
|
||||
(json!({"moves": [one.clone()], "scale": null}), true),
|
||||
(json!({"moves": [{"occurrence": "Door", "translate": [0, 0, 5], "note": "ignored"}]}), true),
|
||||
(json!({"moves": null, "scale": 2}), false),
|
||||
(json!({"moves": "Door"}), false),
|
||||
(json!({"moves": [{"occurrence": "Door"}]}), false),
|
||||
(json!({"moves": [{"occurrence": true, "translate": [0, 0, 5]}]}), false),
|
||||
(json!({"moves": [{"occurrence": "Door", "translate": [0, 0, 1e7]}]}), false),
|
||||
] {
|
||||
ok("explode.create", p, takes);
|
||||
}
|
||||
schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"moves": [one], "name": "N"}), true);
|
||||
schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"moves": [{"occurrence": "Door"}]}), false);
|
||||
schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"scale": 101}), false);
|
||||
// Showing: no view, `null` and `none` in any case show the assembled placement.
|
||||
for (p, takes) in [
|
||||
(json!({}), true),
|
||||
(json!({"view": null}), true),
|
||||
(json!({"view": "None"}), true),
|
||||
(json!({"view": "Apart"}), true),
|
||||
(json!({"view": 4}), true),
|
||||
(json!({"view": true}), false),
|
||||
(json!({"view": ["Apart"]}), false),
|
||||
] {
|
||||
ok("explode.show", p.clone(), takes);
|
||||
schema_takes(input_schema_for::<ExplodeShowParams>(), p, takes);
|
||||
}
|
||||
// Deleting needs a view, by id or name.
|
||||
for (p, takes) in [(json!({"view": "Apart"}), true), (json!({"view": 4}), true), (json!({}), false), (json!({"view": null}), false)] {
|
||||
schema_takes(input_schema_for::<ExplodeDeleteParams>(), p, takes);
|
||||
}
|
||||
ok("explode.delete", json!({"view": "Apart"}), true);
|
||||
assert_eq!(issues("explode.delete", &json!({"view": null})), ["`view` must be an id or a name"]);
|
||||
assert_eq!(issues("explode.delete", &json!({})), Vec::<String>::new(), "the handler gives its own message for a missing view");
|
||||
assert_eq!(issues("explode.show", &json!({"view": true})), ["`view` must be an id or a name"]);
|
||||
assert_eq!(issues("explode.create", &json!({"scale": "x"})), ["`scale` must be a number up to 100"]);
|
||||
assert_eq!(issues("explode.create", &json!({"moves": 1})), ["`moves` must be a list"]);
|
||||
assert_eq!(issues("explode.create", &json!({"moves": [{}]})), ["an occurrence must be an id or a name"]);
|
||||
assert_eq!(issues("explode.create", &json!({"moves": [{"occurrence": 1}]})), ["each move needs `translate`: [x, y, z]"]);
|
||||
assert_eq!(issues("explode.list", &json!({"x": 1})).len(), 1);
|
||||
}
|
||||
|
||||
/// Making, showing, listing and deleting exploded views reply as the output schemas say, in Warn
|
||||
/// without warnings, with the JSON the handlers have always returned. A misspelt key gets
|
||||
/// `param_warnings` in Warn, since the handlers ignore unknown keys, and strict refuses it.
|
||||
#[test]
|
||||
fn exploded_views_reply_with_their_schemas() {
|
||||
let mut s = door();
|
||||
s.param_check = ParamCheck::Warn;
|
||||
let run = |s: &mut Session, id: &str, p: Value, schema: schemars::Schema| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
r
|
||||
};
|
||||
let auto = run(&mut s, "explode.create", json!({}), output_schema_for::<ExplodeCreated>());
|
||||
assert_eq!(auto["name"], "Exploded View1", "{auto}");
|
||||
assert_eq!(auto["moves"].as_array().map(Vec::len), Some(3), "{auto}");
|
||||
assert!(auto["moves"][0]["occurrence"].is_u64() && auto["moves"][0]["translate"].as_array().is_some_and(|t| t.len() == 3), "{auto}");
|
||||
let scaled = run(&mut s, "explode.create", json!({"name": "Far", "scale": 2.5}), output_schema_for::<ExplodeCreated>());
|
||||
assert_eq!(scaled["name"], "Far", "{scaled}");
|
||||
run(&mut s, "explode.create", json!({"scale": -1}), output_schema_for::<ExplodeCreated>());
|
||||
// `scale` is not read with `moves`, so a bad one is no problem.
|
||||
let by_hand = run(
|
||||
&mut s,
|
||||
"explode.create",
|
||||
json!({"name": "Hand", "scale": "ignored", "moves": [move_of(json!("Door"), json!([0, 0, 50])), move_of(json!("Slide"), json!({"x": 1, "y": 2, "z": 3}))]}),
|
||||
output_schema_for::<ExplodeCreated>(),
|
||||
);
|
||||
let (door_id, slide_id) = (by_hand["moves"][0]["occurrence"].clone(), by_hand["moves"][1]["occurrence"].clone());
|
||||
let expected = json!({
|
||||
"view": by_hand["view"],
|
||||
"name": "Hand",
|
||||
"moves": [{"occurrence": door_id, "translate": [0.0, 0.0, 50.0]}, {"occurrence": slide_id, "translate": [1.0, 2.0, 3.0]}]
|
||||
});
|
||||
assert_eq!(by_hand, expected);
|
||||
run(&mut s, "explode.create", json!({"name": "Empty", "moves": []}), output_schema_for::<ExplodeCreated>());
|
||||
|
||||
let list = run(&mut s, "explode.list", json!({}), output_schema_for::<ExplodeViews>());
|
||||
assert_eq!(list["views"].as_array().map(Vec::len), Some(5), "{list}");
|
||||
// Exactly what the design's own views serialize to, as the handler returned them before.
|
||||
assert_eq!(list["views"], serde_json::to_value(&s.doc.assembly.exploded).unwrap_or_default());
|
||||
assert_eq!(list["views"][3], json!({"id": by_hand["view"], "name": "Hand", "moves": [[door_id, [0.0, 0.0, 50.0]], [slide_id, [1.0, 2.0, 3.0]]]}));
|
||||
|
||||
// Shown by name, by id and, to put the assembled placement back, by nothing, `null` or `none`.
|
||||
let r = run(&mut s, "explode.show", json!({"view": "Hand"}), output_schema_for::<ExplodeShown>());
|
||||
assert_eq!(r, json!({"view": by_hand["view"], "name": "Hand"}));
|
||||
let r = run(&mut s, "explode.show", json!({"view": scaled["view"]}), output_schema_for::<ExplodeShown>());
|
||||
assert_eq!(r, json!({"view": scaled["view"], "name": "Far"}));
|
||||
for p in [json!({}), json!({"view": null}), json!({"view": "None"})] {
|
||||
run(&mut s, "explode.show", json!({"view": "Hand"}), output_schema_for::<ExplodeShown>());
|
||||
let r = run(&mut s, "explode.show", p, output_schema_for::<ExplodeShown>());
|
||||
assert_eq!(r, json!({"view": null}));
|
||||
}
|
||||
|
||||
let r = run(&mut s, "explode.delete", json!({"view": "Hand"}), output_schema_for::<ExplodeDeleted>());
|
||||
assert_eq!(r, json!({"deleted": "Hand"}));
|
||||
let r = run(&mut s, "explode.delete", json!({"view": scaled["view"]}), output_schema_for::<ExplodeDeleted>());
|
||||
assert_eq!(r, json!({"deleted": "Far"}));
|
||||
|
||||
// A misspelt key runs in Warn and says so, with a reply that still matches; strict refuses it.
|
||||
run(&mut s, "explode.create", json!({"name": "Typo"}), output_schema_for::<ExplodeCreated>());
|
||||
for (id, p, schema) in [
|
||||
("explode.create", json!({"nme": "Typo"}), output_schema_for::<ExplodeCreated>()),
|
||||
("explode.show", json!({"veiw": "Exploded View"}), output_schema_for::<ExplodeShown>()),
|
||||
("explode.list", json!({"view": 1}), output_schema_for::<ExplodeViews>()),
|
||||
("explode.delete", json!({"view": "Typo", "name": 1}), output_schema_for::<ExplodeDeleted>()),
|
||||
] {
|
||||
s.param_check = ParamCheck::Warn;
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let schema = schema.as_value();
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()) && conforms(schema, schema, &r), "{id}: {r}");
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let error = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("unknown key"), "{id}: {error}");
|
||||
}
|
||||
let before = s.doc.assembly.exploded.len();
|
||||
s.param_check = ParamCheck::Strict;
|
||||
assert!(s.execute("explode.create", &json!({"nme": "Typo"})).is_err());
|
||||
assert_eq!(s.doc.assembly.exploded.len(), before, "strict ran nothing");
|
||||
}
|
||||
|
||||
@@ -1,590 +0,0 @@
|
||||
//! Contracts and result types for the drawing commands in `cmd/sketch.rs`: a line, a point, the
|
||||
//! circles and the arcs (#12953).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec2;
|
||||
|
||||
use super::check::whole;
|
||||
use super::sketch_ends::SketchTarget;
|
||||
use super::types::{LengthExpr, Point2, Point3, present};
|
||||
use crate::params;
|
||||
|
||||
/// What the coordinates of a point typed as text must be.
|
||||
const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters";
|
||||
/// The most points a line takes.
|
||||
const MAX_LINE_POINTS: usize = 10_000;
|
||||
|
||||
/// The forms of a point argument: [`SketchPoint`] and [`SnapPoint`] differ in the snaps.
|
||||
fn point_arg_schema(generator: &mut SchemaGenerator, snaps: bool) -> Schema {
|
||||
let point = generator.subschema_for::<Point2>();
|
||||
let coordinate = generator.subschema_for::<LengthExpr>();
|
||||
let mut forms = vec![
|
||||
json!(point),
|
||||
json!({
|
||||
"description": "[x, y] where a coordinate may be an expression over the design's parameters, such as [\"w / 2\", 5]: a point that follows the parameters.",
|
||||
"type": "array", "items": coordinate, "minItems": 2, "maxItems": 2
|
||||
}),
|
||||
json!({"description": "An existing point's id such as \"l1.end\" or \"p3\", or a snap such as \"mid:l1\".", "type": "string"}),
|
||||
json!({"description": "An existing point by id.", "type": "object", "properties": {"ref": {"type": "string"}}, "required": ["ref"]}),
|
||||
json!({"description": "A point by place.", "type": "object", "properties": {"at": point}, "required": ["at"]}),
|
||||
];
|
||||
let description = if snaps {
|
||||
let model = generator.subschema_for::<Point3>();
|
||||
forms.push(json!({"description": "A model vertex [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"vertex": model}, "required": ["vertex"]}));
|
||||
forms.push(json!({"description": "A point on a model edge [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"on_edge": model}, "required": ["on_edge"]}));
|
||||
"A sketch point: [x, y] in mm (a coordinate may be an expression), an existing point's id (\"l1.end\"), {ref} or {at}, a snap as text (\"mid:<line>\", \"on:<curve>:x,y\", \"x:<a>+<b>:x,y\", \"vertex:x,y,z\"), or a model {vertex} or {on_edge}."
|
||||
} else {
|
||||
"A sketch point: [x, y] in mm (a coordinate may be an expression over the design's parameters), an existing point's id such as \"l1.end\", or {ref} or {at}."
|
||||
};
|
||||
json_schema!({"description": description, "anyOf": forms})
|
||||
}
|
||||
|
||||
/// A point argument as `sketch::parg` reads it: a place `[x, y]` (a coordinate may be an
|
||||
/// expression), an existing point's id, `{ref}` or `{at}`. Kept as given, for the handler, which
|
||||
/// has the design to find a point and evaluate an expression.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SketchPoint(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for SketchPoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
crate::cmd::point_arg_form(&v, false).map(|()| SketchPoint(v)).map_err(|why| D::Error::custom(whole(why)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SketchPoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SketchPoint".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
point_arg_schema(generator, false)
|
||||
}
|
||||
}
|
||||
|
||||
/// A point argument of a command that snaps its points (`sketch_project::snap_points`): a
|
||||
/// [`SketchPoint`], or a model `{vertex}` or `{on_edge}`. Snaps given as text are text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SnapPoint(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for SnapPoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
crate::cmd::point_arg_form(&v, true).map(|()| SnapPoint(v)).map_err(|why| D::Error::custom(whole(why)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SnapPoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SnapPoint".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
point_arg_schema(generator, true)
|
||||
}
|
||||
}
|
||||
|
||||
/// A point as `params::req_vec2` reads it: `[x, y]` or `{x, y}` of numbers, with no expression, id
|
||||
/// or snap (the 2-point circle's `p0` and `p1`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PlainPoint(pub Vec2);
|
||||
|
||||
impl<'de> Deserialize<'de> for PlainPoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec2(&Value::deserialize(d)?).map(PlainPoint).ok_or_else(|| D::Error::custom("must be a point [x, y]"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PlainPoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PlainPoint".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point2>()
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of a line: a list of [`SnapPoint`]s, 2 to 10 000.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinePoints(pub Vec<Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for LinePoints {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let Value::Array(list) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom(whole("`points` must be a list")));
|
||||
};
|
||||
if list.len() < 2 || list.len() > MAX_LINE_POINTS {
|
||||
return Err(D::Error::custom(whole("a line needs 2 or more points")));
|
||||
}
|
||||
for v in &list {
|
||||
crate::cmd::point_arg_form(v, true).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
}
|
||||
Ok(LinePoints(list))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for LinePoints {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"LinePoints".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<SnapPoint>();
|
||||
json_schema!({
|
||||
"description": "The points the line runs through, in order: 2 to 10 000. Each is a SnapPoint.",
|
||||
"type": "array", "items": point, "minItems": 2, "maxItems": MAX_LINE_POINTS
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `v` is a snap that `sketch.point` takes as one, and if so whether it is well formed
|
||||
/// (what the design makes of it, such as a line that is not there, stays the handler's).
|
||||
fn snap_form(v: &Value) -> Option<bool> {
|
||||
let text = v.as_str();
|
||||
let snapped =
|
||||
text.is_some_and(|t| ["mid:", "on:", "vertex:"].iter().any(|k| t.starts_with(k))) || v.get("vertex").is_some() || v.get("on_edge").is_some();
|
||||
if !snapped {
|
||||
return None;
|
||||
}
|
||||
let numbers = |t: &str| -> Vec<f64> { t.split(',').filter_map(|x| x.trim().parse().ok()).collect() };
|
||||
let finite3 = |n: &[f64]| matches!(n, [x, y, z] if x.is_finite() && y.is_finite() && z.is_finite());
|
||||
let vertex =
|
||||
v.get("vertex").and_then(params::vec3).is_some() || text.and_then(|t| t.strip_prefix("vertex:")).is_some_and(|t| finite3(&numbers(t)));
|
||||
let edge = v.get("on_edge").and_then(params::vec3).is_some();
|
||||
let mid = text.is_some_and(|t| t.starts_with("mid:"));
|
||||
let on = text
|
||||
.and_then(|t| t.strip_prefix("on:"))
|
||||
.and_then(|t| t.rsplit_once(':'))
|
||||
.is_some_and(|(_, xy)| matches!(numbers(xy)[..], [x, y] if x.is_finite() && y.is_finite()));
|
||||
Some(vertex || edge || mid || on)
|
||||
}
|
||||
|
||||
/// `sketch.point`'s `point`: `[x, y]` (numbers, or text expressions over the design's parameters),
|
||||
/// `{x, y}`, or a snap that makes the point. An existing point's id is not taken.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PointOrSnap(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for PointOrSnap {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
match snap_form(&v) {
|
||||
Some(true) => return Ok(PointOrSnap(v)),
|
||||
Some(false) => {
|
||||
return Err(D::Error::custom(whole(format!(
|
||||
"`point` {v} is not a snap it takes: \"mid:<line>\", \"on:<curve>:x,y\", \"vertex:x,y,z\", {{vertex: [x,y,z]}} or {{on_edge: [x,y,z]}}"
|
||||
))));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some([x, y]) = v.as_array().map(Vec::as_slice)
|
||||
&& (x.is_string() || y.is_string())
|
||||
{
|
||||
// The coordinates `sketch::expr_point` reads: a finite number, or text that isn't blank.
|
||||
let coordinate = |c: &Value| match c {
|
||||
Value::Number(n) => n.as_f64().and_then(params::finite).is_some(),
|
||||
Value::String(e) => !e.trim().is_empty() && e.len() <= 4096,
|
||||
_ => false,
|
||||
};
|
||||
return if coordinate(x) && coordinate(y) { Ok(PointOrSnap(v)) } else { Err(D::Error::custom(whole(POINT_MUST))) };
|
||||
}
|
||||
if params::vec2(&v).is_some() { Ok(PointOrSnap(v)) } else { Err(D::Error::custom("must be a point [x, y]")) }
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PointOrSnap {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PointOrSnap".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point2>();
|
||||
let coordinate = generator.subschema_for::<LengthExpr>();
|
||||
let model = generator.subschema_for::<Point3>();
|
||||
json_schema!({
|
||||
"description": "A point to make: [x, y] in mm (a coordinate may be an expression over the design's parameters: the point then follows them), or a snap that makes it and holds it: \"mid:<line>\" (the line's midpoint), \"on:<curve>:x,y\" (on the curve, near x,y), \"vertex:x,y,z\" or {vertex: [x,y,z]} (a model vertex, projected) or {on_edge: [x,y,z]} (a point on a model edge, projected). An existing point's id is not taken.",
|
||||
"anyOf": [
|
||||
point,
|
||||
{"type": "array", "items": coordinate, "minItems": 2, "maxItems": 2},
|
||||
{"type": "string", "pattern": "^(mid:|on:|vertex:)"},
|
||||
{"type": "object", "properties": {"vertex": model}, "required": ["vertex"]},
|
||||
{"type": "object", "properties": {"on_edge": model}, "required": ["on_edge"]}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An id a drawing command gives its curve or point, as `named_id` reads it: text that can be
|
||||
/// written into a face name whole.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DrawId(pub String);
|
||||
|
||||
/// `id`, or an entry of `ids`, as `named_id` refuses it (the entry's position is not named).
|
||||
fn id_problem(id: &str) -> Option<String> {
|
||||
(!solidcraft_doc::persistent_name::text_fits_name(id))
|
||||
.then(|| format!("the id `{id}` cannot be written into a name whole; give an id without `|`, `,`, `~`, `#` or `]`"))
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawId {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let Value::String(id) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom("must be text"));
|
||||
};
|
||||
match id_problem(&id) {
|
||||
Some(why) => Err(D::Error::custom(whole(why))),
|
||||
None => Ok(DrawId(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DrawId {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DrawId".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "An id for the new geometry, such as \"base\". It may not hold `|`, `,`, `~`, `#` or `]`, which a face name made from it would read as its own.",
|
||||
"type": "string"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A line's `ids`, as `params::string_list` and `named_id` read them: a list of ids (one id is a
|
||||
/// list of one), at most 10 000.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DrawIds(pub Vec<String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawIds {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
let ids = match params::string_list("", &json!({"ids": v}), "ids") {
|
||||
Ok(ids) => ids,
|
||||
Err(crate::EngineError::BadParams { msg, .. }) => return Err(D::Error::custom(whole(msg))),
|
||||
Err(e) => return Err(D::Error::custom(whole(e))),
|
||||
};
|
||||
if let Some(why) = ids.iter().find_map(|id| id_problem(id)) {
|
||||
return Err(D::Error::custom(whole(why)));
|
||||
}
|
||||
Ok(DrawIds(ids))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DrawIds {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DrawIds".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Ids for the lines, in order: the first for the first segment and so on. One id is a list of one. Segments past the end of the list get an id of the sketch's own. An id may not hold `|`, `,`, `~`, `#` or `]`.",
|
||||
"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A circle's `radius` or `diameter`, as `radius_arg` and `circle_size` read it: a number, or text
|
||||
/// that is an expression over the design's parameters (a dimension driven by them). Whether it is
|
||||
/// positive, and whether an expression evaluates, is the handler's to check.
|
||||
fn size_form(v: &Value, key: &str) -> Result<(), String> {
|
||||
match v {
|
||||
Value::Number(n) if n.as_f64().and_then(params::finite).is_some() => Ok(()),
|
||||
Value::String(_) if params::expr(&json!({ "v": v }), "v").is_some() => Ok(()),
|
||||
Value::String(_) => Err(format!("`{key}` {}", params::expr_problem(Some(v)))),
|
||||
_ => Err(format!("`{key}` must be a number")),
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! circle_size {
|
||||
($name:ident, $key:literal, $doc:literal) => {
|
||||
#[doc = $doc]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct $name(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
size_form(&v, $key).map(|()| $name(v)).map_err(|why| D::Error::custom(whole(why)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for $name {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
stringify!($name).into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<LengthExpr>()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
circle_size!(CircleRadius, "radius", "A circle's `radius`: a number or an expression.");
|
||||
circle_size!(CircleDiameter, "diameter", "A circle's `diameter`: a number or an expression.");
|
||||
|
||||
/// An arc's `sweep`, as `params::num` reads it: a number below 1e9 in size. That it is between
|
||||
/// -360 and 360 and not 0 is the handler's to check.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sweep(pub f64);
|
||||
|
||||
impl<'de> Deserialize<'de> for Sweep {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?.as_f64().and_then(params::finite).map(Sweep).ok_or_else(|| D::Error::custom("must be a number of degrees"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for Sweep {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"Sweep".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The angle the arc turns through, in degrees: positive counter-clockwise from `start`, negative clockwise. Not 0, and less than 360 in size.",
|
||||
"type": "number", "exclusiveMinimum": -360, "exclusiveMaximum": 360
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a line through two or more points, or a closed polyline.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct LineParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// The points to run through, in order: one segment between each two. A point that is an
|
||||
/// existing point's id (or `{ref}`) shares that point, so the line starts or ends there.
|
||||
pub points: LinePoints,
|
||||
/// Close the line with a segment from the last point back to the first. Default: false.
|
||||
#[serde(default)]
|
||||
pub closed: Option<bool>,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Ids for the segments, in order. Default: ids of the sketch's own.
|
||||
#[serde(default)]
|
||||
pub ids: Option<DrawIds>,
|
||||
/// Add a horizontal or vertical constraint to a segment that is drawn exactly so, and a
|
||||
/// tangent to the arc or a perpendicular to the line that it starts from. Default: false.
|
||||
#[serde(default)]
|
||||
pub infer: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Add a point to the sketch, or a point made by a snap that holds it.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PointParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// Where the point goes, or the snap that makes it.
|
||||
pub point: PointOrSnap,
|
||||
/// An id for the point. Default: one of the sketch's own. Ignored when `point` is a snap.
|
||||
#[serde(default)]
|
||||
pub id: Option<DrawId>,
|
||||
/// Make the new point coincident with an existing point it lands exactly on (the origin
|
||||
/// too). Default: true. Ignored when `point` is a snap.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Draw a circle from its centre and its radius or diameter.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CircleCenterParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// The centre. A point's id or `{ref}` makes that point the centre, so the circle follows it.
|
||||
pub center: SnapPoint,
|
||||
/// The radius, in mm: a number, or an expression over the design's parameters, which makes
|
||||
/// the radius a dimension driven by them. Wins over `diameter`. Give one of the two.
|
||||
#[serde(default)]
|
||||
pub radius: Option<CircleRadius>,
|
||||
/// The diameter, in mm, as `radius` is given. Used when `radius` is not.
|
||||
#[serde(default)]
|
||||
pub diameter: Option<CircleDiameter>,
|
||||
/// A point the circle passes through, kept on it. With a placed centre and an existing
|
||||
/// point, that point and `radius` both fix the radius.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SnapPoint")]
|
||||
pub through: Option<SnapPoint>,
|
||||
/// An id for the circle. Default: one of the sketch's own.
|
||||
#[serde(default)]
|
||||
pub id: Option<DrawId>,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Draw a circle from the two ends of a diameter.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CircleTwoPointParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// One end of the diameter, as [x, y] or {x, y} in mm. An expression, a point's id or a
|
||||
/// snap is not taken.
|
||||
pub p0: PlainPoint,
|
||||
/// The other end of the diameter. Not the same point as `p0`.
|
||||
pub p1: PlainPoint,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Draw a circle through three points.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CircleThreePointParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// A point on the circle. One that is an existing point's id stays on the circle.
|
||||
pub p0: SnapPoint,
|
||||
/// A second point on the circle.
|
||||
pub p1: SnapPoint,
|
||||
/// A third point on the circle. The three may not be in a line.
|
||||
pub p2: SnapPoint,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Draw an arc from its two ends and a point on it.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ArcThreePointParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// One end of the arc.
|
||||
pub start: SnapPoint,
|
||||
/// The other end of the arc.
|
||||
pub end: SnapPoint,
|
||||
/// A point the arc passes through, between the ends. One that is an existing point's id
|
||||
/// stays on the arc. The three may not be in a line.
|
||||
pub through: SnapPoint,
|
||||
/// An id for the arc. Default: one of the sketch's own.
|
||||
#[serde(default)]
|
||||
pub id: Option<DrawId>,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// Draw an arc round a centre, from a start point to an end point or through a sweep.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ArcCenterPointParams {
|
||||
/// The sketch to draw in: its feature id or name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// The centre of the arc.
|
||||
pub center: SnapPoint,
|
||||
/// Where the arc starts. Its distance from `center` is the radius.
|
||||
pub start: SnapPoint,
|
||||
/// A point in the direction of the arc's end from `center`: the arc ends on the ray through
|
||||
/// it, at the radius. Give `end` or `sweep`; `sweep` wins.
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SnapPoint")]
|
||||
pub end: Option<SnapPoint>,
|
||||
/// With `end`: go clockwise from `start` to `end`. Default: false, counter-clockwise.
|
||||
#[serde(default)]
|
||||
pub clockwise: Option<bool>,
|
||||
/// The angle to turn through from `start`, in degrees, instead of `end`.
|
||||
#[serde(default)]
|
||||
pub sweep: Option<Sweep>,
|
||||
/// An id for the arc. Default: one of the sketch's own.
|
||||
#[serde(default)]
|
||||
pub id: Option<DrawId>,
|
||||
/// Draw construction geometry, which is not part of a profile. Default: false.
|
||||
#[serde(default)]
|
||||
pub construction: Option<bool>,
|
||||
/// Make a new point that lands exactly on an existing point (the origin too) coincident with
|
||||
/// it. Default: true.
|
||||
#[serde(default)]
|
||||
pub connect: Option<bool>,
|
||||
}
|
||||
|
||||
/// What a command added to its sketch: the ids that the sketch has now and did not before.
|
||||
#[derive(Debug, Default, Serialize, JsonSchema)]
|
||||
pub struct Created {
|
||||
/// Point ids.
|
||||
pub points: Vec<String>,
|
||||
/// Curve ids.
|
||||
pub curves: Vec<String>,
|
||||
/// Constraint ids, dimensions not among them.
|
||||
pub constraints: Vec<String>,
|
||||
/// Dimension ids.
|
||||
pub dimensions: Vec<String>,
|
||||
/// The ids of 3D curves, when the command made any.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub wires: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a drawing command returns for a line, a circle or an arc.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DrawResult {
|
||||
/// The ids of the curves drawn, in order.
|
||||
pub curves: Vec<String>,
|
||||
/// The ids of the constraints added besides the curves' own: a coincident for a point that
|
||||
/// landed on an existing one, a point on the curve for a point that was given by id, a radius
|
||||
/// for a size given as an expression, what `infer` added.
|
||||
pub constraints: Vec<String>,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`, and
|
||||
/// `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Created>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.point` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PointResult {
|
||||
/// The id of the point made.
|
||||
pub point: String,
|
||||
/// The ids of the constraints added: a coincident with the existing point it landed on.
|
||||
pub constraints: Vec<String>,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Created>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_shapes_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,217 +0,0 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, DrawResult, LineParams, PointParams,
|
||||
PointResult,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
|
||||
|
||||
/// A session in a new sketch that holds one line, `l1`, from [0, 0] to [10, 0].
|
||||
fn session(level: ParamCheck) -> Session {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["l1"]}));
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<LineParams>(), &["closed", "connect", "construction", "ids", "infer", "points", "sketch"]);
|
||||
assert_keys(input_schema_for::<PointParams>(), &["connect", "id", "point", "sketch"]);
|
||||
assert_keys(input_schema_for::<CircleCenterParams>(), &["center", "connect", "construction", "diameter", "id", "radius", "sketch", "through"]);
|
||||
assert_keys(input_schema_for::<CircleTwoPointParams>(), &["connect", "construction", "p0", "p1", "sketch"]);
|
||||
assert_keys(input_schema_for::<CircleThreePointParams>(), &["connect", "construction", "p0", "p1", "p2", "sketch"]);
|
||||
assert_keys(input_schema_for::<ArcThreePointParams>(), &["connect", "construction", "end", "id", "sketch", "start", "through"]);
|
||||
assert_keys(
|
||||
input_schema_for::<ArcCenterPointParams>(),
|
||||
&["center", "clockwise", "connect", "construction", "end", "id", "sketch", "start", "sweep"],
|
||||
);
|
||||
}
|
||||
|
||||
/// Calls the handler refuses fail in strict with the same message. (The shared helper finishes
|
||||
/// its sketch first; these need one being edited.)
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let cases = [
|
||||
("sketch.line", json!({"points": 5})),
|
||||
("sketch.line", json!({"points": [[0, 0]]})),
|
||||
("sketch.line", json!({"points": [[0, 0], "zz"]})),
|
||||
("sketch.line", json!({"points": [[0, 0], [1]]})),
|
||||
("sketch.line", json!({"points": [[0, 0], [true, "a"]]})),
|
||||
("sketch.line", json!({"points": [[0, 0], ["", 1]]})),
|
||||
("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": 5})),
|
||||
("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": [1]})),
|
||||
("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": ["a|b"]})),
|
||||
("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": "a,b"})),
|
||||
("sketch.line", json!({"points": [[0, 0], {"vertex": "x"}]})),
|
||||
("sketch.point", json!({"point": "l1.end"})),
|
||||
("sketch.point", json!({"point": [1]})),
|
||||
("sketch.point", json!({"point": ["", 2]})),
|
||||
("sketch.point", json!({"point": [1, true]})),
|
||||
("sketch.point", json!({"point": "mid:nope"})),
|
||||
("sketch.point", json!({"point": {"vertex": "x"}})),
|
||||
("sketch.point", json!({"point": "on:l1:x"})),
|
||||
("sketch.point", json!({"point": "vertex:1,2"})),
|
||||
("sketch.point", json!({"point": [1, 2], "id": "a|b"})),
|
||||
("sketch.circle.center", json!({"center": [0, 0]})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": true})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": " "})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": 1e12})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": 0})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "diameter": [1]})),
|
||||
("sketch.circle.center", json!({"center": 5, "radius": 1})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "through": null})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "id": "a]"})),
|
||||
("sketch.circle.two_point", json!({"p0": "l1.end", "p1": [1, 1]})),
|
||||
("sketch.circle.two_point", json!({"p0": [0, 0], "p1": ["1", 1]})),
|
||||
("sketch.circle.two_point", json!({"p0": [0, 0], "p1": [0, 0]})),
|
||||
("sketch.circle.three_point", json!({"p0": [0, 0], "p1": [1, 0], "p2": [2, 0]})),
|
||||
("sketch.circle.three_point", json!({"p0": [0, 0], "p1": 5, "p2": [2, 3]})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 0]})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": "zz"})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 5], "id": "a|b"})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 0})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 400})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "end": true})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "end": null})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0]})),
|
||||
];
|
||||
for (id, p) in &cases {
|
||||
let error = |level| session(level).execute(id, p).err().map(|e| e.to_string());
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every form each command takes is accepted by the contract: run in warn, the reply has no
|
||||
/// warnings and matches the output schema.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema_and_forms_are_accepted() {
|
||||
let draw = output_schema_for::<DrawResult>();
|
||||
let draw = draw.as_value();
|
||||
let point = output_schema_for::<PointResult>();
|
||||
let point = point.as_value();
|
||||
let calls = [
|
||||
("sketch.line", json!({"points": [[0, 5], [10, 5]]})),
|
||||
("sketch.line", json!({"points": ["l1.end", [20, 0]], "infer": true})),
|
||||
("sketch.line", json!({"points": [{"ref": "l1.start"}, {"at": [1, 2]}], "construction": true})),
|
||||
("sketch.line", json!({"points": [[30, 0], ["5 mm", 3], {"x": 40, "y": 9}], "closed": true, "ids": "solo", "connect": false})),
|
||||
("sketch.line", json!({"points": [[50, 0], [60, 0]], "ids": ["a", "b"], "sketch": null})),
|
||||
("sketch.circle.center", json!({"center": [50, 50], "radius": 2})),
|
||||
("sketch.circle.center", json!({"center": [50, 60], "diameter": 4, "id": "ring", "construction": true})),
|
||||
("sketch.circle.center", json!({"center": [50, 70], "radius": "3 mm", "connect": false})),
|
||||
("sketch.circle.center", json!({"center": ["1 mm", 80], "diameter": "6 mm", "through": "l1.end"})),
|
||||
("sketch.circle.two_point", json!({"p0": [70, 0], "p1": [80, 0]})),
|
||||
("sketch.circle.two_point", json!({"p0": {"x": 70, "y": 10}, "p1": {"x": 80, "y": 10}, "construction": false})),
|
||||
("sketch.circle.three_point", json!({"p0": [90, 0], "p1": [100, 10], "p2": [110, 0]})),
|
||||
("sketch.circle.three_point", json!({"p0": "l1.start", "p1": {"at": [0, -10]}, "p2": [-10, 0]})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 20], "end": [10, 20], "through": [5, 25], "id": "arc_one"})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 30], "end": [10, 30], "through": [5, 35], "construction": true})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 40], "start": [5, 40], "end": [0, 45]})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 50], "start": [5, 50], "end": [0, 55], "clockwise": true, "id": "arc_two"})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 60], "start": [5, 60], "sweep": 90})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 70], "start": [5, 70], "sweep": -45, "end": [0, 75]})),
|
||||
];
|
||||
let point_calls = [
|
||||
json!({"point": [30, 30]}),
|
||||
json!({"point": {"x": 31, "y": 31}, "id": "pt"}),
|
||||
json!({"point": ["10 mm", 40], "connect": false}),
|
||||
json!({"point": "mid:l1"}),
|
||||
json!({"point": "on:l1:5,0"}),
|
||||
];
|
||||
let mut s = session(ParamCheck::Warn);
|
||||
for (id, p) in &calls {
|
||||
let r = run(&mut s, id, p.clone());
|
||||
assert!(conforms(draw, draw, &r), "{id} {p}: {r} doesn't match {draw}");
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
assert!(r["created"]["curves"].is_array(), "{r}");
|
||||
}
|
||||
for p in &point_calls {
|
||||
let r = run(&mut s, "sketch.point", p.clone());
|
||||
assert!(conforms(point, point, &r), "{p}: {r} doesn't match {point}");
|
||||
assert!(r.get("param_warnings").is_none(), "{p}: {r}");
|
||||
}
|
||||
// A misspelt key still runs in warn and is named.
|
||||
let r = run(&mut s, "sketch.line", json!({"points": [[0, 90], [10, 90]], "constructon": true}));
|
||||
assert!(conforms(draw, draw, &r), "{r} doesn't match {draw}");
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
|
||||
let r = run(&mut s, "sketch.point", json!({"point": [3, 95], "constructon": true}));
|
||||
assert!(conforms(point, point, &r), "{r} doesn't match {point}");
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
|
||||
}
|
||||
|
||||
/// The same calls give the same JSON with the check off and in strict.
|
||||
#[test]
|
||||
fn the_check_does_not_change_the_reply() {
|
||||
let calls = [
|
||||
("sketch.line", json!({"points": [[0, 5], [10, 5], [10, 15]], "closed": true, "ids": ["a", "b", "c"]})),
|
||||
("sketch.point", json!({"point": [3, 3]})),
|
||||
("sketch.point", json!({"point": "mid:l1"})),
|
||||
("sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c1"})),
|
||||
("sketch.circle.two_point", json!({"p0": [70, 0], "p1": [80, 0]})),
|
||||
("sketch.circle.three_point", json!({"p0": [90, 0], "p1": [100, 10], "p2": [110, 0]})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 20], "end": [10, 20], "through": [5, 25]})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 40], "start": [5, 40], "sweep": 90})),
|
||||
];
|
||||
let (mut off, mut strict) = (session(ParamCheck::Off), session(ParamCheck::Strict));
|
||||
for (id, p) in &calls {
|
||||
let (a, b) = (run(&mut off, id, p.clone()), run(&mut strict, id, p.clone()));
|
||||
assert_eq!(a, b, "{id} {p}");
|
||||
assert!(a["created"]["points"].is_array() && a["sketch"]["dof"].is_number(), "{a}");
|
||||
}
|
||||
// Key order and spelling of a reply, as the handlers wrote it before the types.
|
||||
let r = run(&mut off, "sketch.point", json!({"point": [4, 4]}));
|
||||
assert_eq!(
|
||||
r.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()),
|
||||
Some(vec!["constraints".into(), "created".into(), "point".into(), "sketch".into()])
|
||||
);
|
||||
}
|
||||
|
||||
/// Values of the wrong type that a handler ignores or reads as left out are refused by the
|
||||
/// contract: that is what warn reports and strict refuses.
|
||||
#[test]
|
||||
fn wrong_typed_keys_are_reported() {
|
||||
let base = [
|
||||
("sketch.line", json!({"points": [[0, 0], [5, 5]]})),
|
||||
("sketch.point", json!({"point": [1, 1]})),
|
||||
("sketch.circle.center", json!({"center": [0, 0], "radius": 1})),
|
||||
("sketch.circle.two_point", json!({"p0": [0, 0], "p1": [5, 5]})),
|
||||
("sketch.circle.three_point", json!({"p0": [0, 0], "p1": [5, 5], "p2": [10, 0]})),
|
||||
("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 5]})),
|
||||
("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 90})),
|
||||
];
|
||||
for (id, p) in &base {
|
||||
assert!(issues(id, p).is_empty(), "{id} {p}");
|
||||
for key in ["connect", "construction", "closed", "infer", "clockwise"] {
|
||||
let mut bad = p.clone();
|
||||
bad[key] = json!("yes");
|
||||
if input_schema_has(id, key) {
|
||||
assert_eq!(issues(id, &bad).len(), 1, "{id} {key}: {:?}", issues(id, &bad));
|
||||
}
|
||||
}
|
||||
let mut bad = p.clone();
|
||||
bad["sketch"] = json!(true);
|
||||
assert_eq!(issues(id, &bad)[0].message, "`sketch` must be an id or a name");
|
||||
}
|
||||
let message = |id: &str, p: Value| issues(id, &p).first().map(|i| i.message.clone());
|
||||
assert_eq!(message("sketch.point", json!({"point": [1, 1], "id": 5})).as_deref(), Some("`id` must be text"));
|
||||
assert_eq!(
|
||||
message("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": "90"})).as_deref(),
|
||||
Some("`sweep` must be a number of degrees")
|
||||
);
|
||||
assert_eq!(message("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "through": {"vertex": [1, 2, 3]}})), None);
|
||||
assert_eq!(message("sketch.point", json!({"point": {"on_edge": [1, 2, 3]}})), None);
|
||||
assert_eq!(message("sketch.point", json!({"point": "vertex:1,2,3"})), None);
|
||||
assert_eq!(message("sketch.line", json!({"points": [{"vertex": [1, 2, 3]}, {"on_edge": [1, 2, 3]}]})), None);
|
||||
}
|
||||
|
||||
fn input_schema_has(id: &str, key: &str) -> bool {
|
||||
crate::cmd::find_command(id).and_then(|c| c.contract).is_some_and(|c| c.allowed_keys().contains(key))
|
||||
}
|
||||
@@ -1,426 +0,0 @@
|
||||
//! Contracts and result types for the commands in `cmd/clipboard.rs` and `cmd/script.rs`:
|
||||
//! `timeline.copy`, `timeline.paste`, `timeline.add` and `timeline.export_script` (#12502).
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message; where a reader is shared with the handler
|
||||
//! (`copy_keys`, `component_path_form`, `step_params`) the type calls it. Whether a feature, a
|
||||
//! component or a file exists stays the handler's to check. A key the handler refuses when it is
|
||||
//! left out (`features`, `feature`) is optional in the type and required in the schema, so that the
|
||||
//! handler's message, not the check's "is required", is what a caller sees. A call with several
|
||||
//! problems may get a different one first in strict than with the check off (the check goes key by
|
||||
//! key, the handlers in their own order).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
|
||||
use super::check::whole;
|
||||
use super::component_link::ComponentRef;
|
||||
use super::motion::require;
|
||||
use super::types::not_blank_pattern;
|
||||
use crate::EngineError;
|
||||
use crate::params;
|
||||
|
||||
/// The most features one `timeline.copy` lists, as the handler reads them.
|
||||
const MAX_COPY: usize = 1000;
|
||||
/// The most occurrence ids in a `component_path`, as the handler reads them.
|
||||
const MAX_PATH: usize = 64;
|
||||
|
||||
/// The message of a handler's refusal, to pass on as it is.
|
||||
fn handler_message(e: EngineError) -> String {
|
||||
match e {
|
||||
EngineError::BadParams { msg, .. } => whole(msg),
|
||||
other => whole(other),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- timeline.copy ----
|
||||
|
||||
/// The features `timeline.copy` lists: one name, or a list of names and ids, in any mix.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FeatureKeys(pub Vec<Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for FeatureKeys {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let wrapped = json!({ "features": Value::deserialize(d)? });
|
||||
crate::cmd::copy_keys(&wrapped).map(|keys| FeatureKeys(keys.to_vec())).map_err(|e| D::Error::custom(handler_message(e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for FeatureKeys {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"FeatureKeys".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let key = json!({"anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0}]});
|
||||
json_schema!({
|
||||
"description": "Features by name or id: one name, or a list of names and ids in any mix.",
|
||||
"anyOf": [
|
||||
{"type": "string"},
|
||||
{"type": "array", "items": key, "minItems": 1, "maxItems": MAX_COPY}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy features to the session's clipboard, and a snapshot of them for pasting into another
|
||||
/// design. The features stay where they are; the clipboard replaces what was copied before. Not an
|
||||
/// undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = features_required)]
|
||||
pub struct CopyParams {
|
||||
// Optional in the type and required in the schema (`features_required`).
|
||||
/// The features to copy, by name or id: one name, or 1 to 1000 names and ids. Pasted in
|
||||
/// timeline order whatever the order given.
|
||||
#[serde(default, deserialize_with = "features", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "FeatureKeys")]
|
||||
pub features: Option<FeatureKeys>,
|
||||
}
|
||||
|
||||
/// `features`, with the handler's message for anything else, `null` and an empty list included.
|
||||
fn features<'de, D: Deserializer<'de>>(d: D) -> Result<Option<FeatureKeys>, D::Error> {
|
||||
FeatureKeys::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
fn features_required(schema: &mut Schema) {
|
||||
require(schema, "features");
|
||||
}
|
||||
|
||||
/// What `timeline.copy` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct CopyResult {
|
||||
/// The names of the features copied, in timeline order.
|
||||
pub copied: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- timeline.paste ----
|
||||
|
||||
/// A `translate` as `timeline.paste` reads it: `[x, y, z]` or `{x, y, z}` of numbers in mm, each
|
||||
/// under 1e9 in size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PasteTranslation(pub Vec3);
|
||||
|
||||
impl<'de> Deserialize<'de> for PasteTranslation {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec3(&Value::deserialize(d)?).map(PasteTranslation).ok_or_else(|| D::Error::custom(whole("`translate` must be [x, y, z]")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PasteTranslation {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PasteTranslation".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let c = json!({"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9});
|
||||
json_schema!({
|
||||
"description": "A distance in mm, as [x, y, z] or {\"x\", \"y\", \"z\"}.",
|
||||
"anyOf": [
|
||||
{"type": "array", "items": c, "minItems": 3, "maxItems": 3},
|
||||
{"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A `component_path` as `timeline.paste` reads it: 0 to 64 occurrence ids.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PastePath(pub Vec<u64>);
|
||||
|
||||
impl<'de> Deserialize<'de> for PastePath {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
crate::cmd::component_path_form(&Value::deserialize(d)?)
|
||||
.map(PastePath)
|
||||
.ok_or_else(|| D::Error::custom(whole("`component_path` must list 0..64 occurrence ids")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PastePath {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PastePath".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The occurrence ids from the top of the design down to a placement.",
|
||||
"type": "array",
|
||||
"items": {"type": "integer", "minimum": 0},
|
||||
"maxItems": MAX_PATH
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn paste_component<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => Ok(Some(ComponentRef(n.to_string()))),
|
||||
Value::String(s) => Ok(Some(ComponentRef(s))),
|
||||
_ => Err(D::Error::custom(whole("`component` must be a component id or name"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn paste_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<PastePath>, D::Error> {
|
||||
PastePath::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
fn paste_translate<'de, D: Deserializer<'de>>(d: D) -> Result<Option<PasteTranslation>, D::Error> {
|
||||
PasteTranslation::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// `from_design` is true or false; `null` is refused, as the handler does.
|
||||
fn from_design<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Bool(b) => Ok(Some(b)),
|
||||
_ => Err(D::Error::custom(whole("`from_design` must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste the copied features as independent copies at the timeline marker: sketches get their own
|
||||
/// dimension parameters, features their own names, and references inside the copied set point at
|
||||
/// the copies. Body transfers are left out. One undo step. With `from_design`, only sketch
|
||||
/// features are pasted, from the snapshot another design's copy left. Every key reads the same
|
||||
/// either way.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PasteParams {
|
||||
/// Move the copies' geometry by this much, in mm. Default: not moved.
|
||||
#[serde(default, deserialize_with = "paste_translate", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "PasteTranslation")]
|
||||
pub translate: Option<PasteTranslation>,
|
||||
/// The component the copies go into, by id or name. Default: the active one.
|
||||
#[serde(default, deserialize_with = "paste_component", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ComponentRef")]
|
||||
pub component: Option<ComponentRef>,
|
||||
/// The placement of that component the copies are authored in, as occurrence ids. Default: the
|
||||
/// active placement for the active component, else the component's only placement.
|
||||
#[serde(default, deserialize_with = "paste_path", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "PastePath")]
|
||||
pub component_path: Option<PastePath>,
|
||||
/// True pastes the sketch features of the clipboard snapshot of another design, with their
|
||||
/// parameters. Default: false, the features copied in this design.
|
||||
#[serde(default, deserialize_with = "from_design", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub from_design: Option<bool>,
|
||||
}
|
||||
|
||||
/// A feature a paste made.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Pasted {
|
||||
/// The new feature, by id.
|
||||
pub id: u64,
|
||||
/// Its name.
|
||||
pub name: String,
|
||||
/// The name of the feature it is a copy of.
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
/// A pasted feature that did not rebuild.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PasteError {
|
||||
/// The pasted feature, by id.
|
||||
pub feature: u64,
|
||||
/// Why it did not rebuild.
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
/// What `timeline.paste` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PasteResult {
|
||||
/// The features made, in timeline order.
|
||||
pub pasted: Vec<Pasted>,
|
||||
/// The pasted features that did not rebuild.
|
||||
pub errors: Vec<PasteError>,
|
||||
/// What the paste left out or kept (body transfers, external face attachments).
|
||||
pub notices: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- timeline.add ----
|
||||
|
||||
/// The `feature` of `timeline.add`: an object, as a design file or `timeline.inspect` holds a
|
||||
/// feature.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecordedFeature(pub Map<String, Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for RecordedFeature {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Object(o) => Ok(RecordedFeature(o)),
|
||||
_ => Err(D::Error::custom(whole("`feature` must be a feature object, as a design file or timeline.inspect has it"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for RecordedFeature {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"RecordedFeature".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A feature as the design file and timeline.inspect hold it: {type, name?, id?, …}. \
|
||||
The name is kept even when another feature has it; the id is kept, and refused when another \
|
||||
feature has it. Whether the rest is a feature is the command's to check.",
|
||||
"type": "object"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The model parameters of `timeline.add`: read by the handler's own reader.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StepParams(pub Vec<solidcraft_doc::Param>);
|
||||
|
||||
impl<'de> Deserialize<'de> for StepParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let value = Value::deserialize(d)?;
|
||||
crate::cmd::step_params("timeline.add", Some(&value)).map(StepParams).map_err(|e| D::Error::custom(handler_message(e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for StepParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"StepParams".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let text = json!({"type": ["string", "null"]});
|
||||
json_schema!({
|
||||
"description": "Model parameters the feature's sketch dimensions use.",
|
||||
"type": "array",
|
||||
"maxItems": solidcraft_sketch::MAX_CONSTRAINTS,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string", "description": "The parameter's name."},
|
||||
"expression": {
|
||||
"description": "Its value: a number or an expression that is not blank.",
|
||||
"anyOf": [{"type": "string", "pattern": not_blank_pattern()}, {"type": "number"}]
|
||||
},
|
||||
"unit": text.clone(),
|
||||
"comment": text
|
||||
},
|
||||
"required": ["name", "expression"]
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn recorded<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RecordedFeature>, D::Error> {
|
||||
RecordedFeature::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
fn feature_required(schema: &mut Schema) {
|
||||
require(schema, "feature");
|
||||
}
|
||||
|
||||
/// Append one recorded feature to the timeline, as the design file holds it, so every feature
|
||||
/// kind replays exactly: the same ids, names, parameter names and stored edge and face names (the
|
||||
/// steps `timeline.export_script` writes). It goes at the timeline marker. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = feature_required)]
|
||||
pub struct AddParams {
|
||||
// Optional in the type and required in the schema (`feature_required`).
|
||||
/// The feature, as a design file or `timeline.inspect` has it.
|
||||
#[serde(default, deserialize_with = "recorded", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "RecordedFeature")]
|
||||
pub feature: Option<RecordedFeature>,
|
||||
/// The model parameters its sketch dimensions use, each {name, expression, unit?, comment?}.
|
||||
/// Default: none.
|
||||
#[serde(default)]
|
||||
#[schemars(with = "StepParams")]
|
||||
pub params: Option<StepParams>,
|
||||
}
|
||||
|
||||
/// What `timeline.add` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct AddResult {
|
||||
/// The new feature, by id.
|
||||
pub feature: u64,
|
||||
/// Its name.
|
||||
pub name: String,
|
||||
/// Why it did not build, or null.
|
||||
pub error: Option<String>,
|
||||
/// A warning from building it, or null.
|
||||
pub warning: Option<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- timeline.export_script ----
|
||||
|
||||
fn script_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::String(s) => Ok(Some(s)),
|
||||
_ => Err(D::Error::custom(whole("`path` must be a file path"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the design's history as a command script that rebuilds it (`solidcraft-cli eval` and
|
||||
/// `run` replay it): one step per setting and feature, and a list of what the script leaves out.
|
||||
/// A design with components or joints is refused for now. The design is not changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExportScriptParams {
|
||||
/// A file to write the script to, as JSON. Default: none, the script is only returned.
|
||||
#[serde(default, deserialize_with = "script_path", skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// One step of a command script.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ScriptStep {
|
||||
/// The command the step runs.
|
||||
pub command: String,
|
||||
/// Its parameters.
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
/// Where a script came from and how to replay it. Fields stay in alphabetical order: a script file
|
||||
/// is written from this type, and its keys have always been sorted.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ScriptAbout {
|
||||
/// The design's name.
|
||||
pub design: String,
|
||||
/// The design file format the `timeline.add` steps hold features in.
|
||||
pub format: String,
|
||||
/// How to replay the script.
|
||||
pub replay: String,
|
||||
/// The version of SolidCraft that wrote it.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// A command script. Fields stay in alphabetical order (see [`ScriptAbout`]).
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Script {
|
||||
pub about: ScriptAbout,
|
||||
/// The steps that rebuild the design on an empty one.
|
||||
#[schemars(with = "Vec<ScriptStep>")]
|
||||
pub commands: Vec<Value>,
|
||||
}
|
||||
|
||||
/// What `timeline.export_script` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExportScriptResult {
|
||||
/// What the script leaves out (appearances, folders, views, configurations, print-face
|
||||
/// assignments…).
|
||||
pub omitted: Vec<String>,
|
||||
/// The file written, or null.
|
||||
pub path: Option<String>,
|
||||
/// The script.
|
||||
pub script: Script,
|
||||
/// How many steps it has.
|
||||
pub steps: usize,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "timeline_clipboard_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,410 +0,0 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{AddParams, AddResult, CopyParams, CopyResult, ExportScriptParams, ExportScriptResult, PasteParams, PasteResult};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
fn warn_session() -> Session {
|
||||
Session { param_check: ParamCheck::Warn, ..Session::default() }
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A dimensioned sketch named S, extruded into Body, for the commands to work on.
|
||||
fn plate(s: &mut Session) {
|
||||
run(s, "parameters.change", json!({"name": "base", "expression": "5 mm"}));
|
||||
run(s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}));
|
||||
run(s, "sketch.constraint.coincident", json!({"a": "p1", "b": "origin"}));
|
||||
run(s, "sketch.dimension", json!({"entities": ["l1"], "value": "base * 4"}));
|
||||
run(s, "sketch.finish", json!({}));
|
||||
run(s, "solid.extrude", json!({"sketch": "S", "distance": 5, "name": "E"}));
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
fn issues(id: &str, p: Value) -> Vec<String> {
|
||||
crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<CopyParams>(), &["features"]);
|
||||
assert_keys(input_schema_for::<PasteParams>(), &["component", "component_path", "from_design", "translate"]);
|
||||
assert_keys(input_schema_for::<AddParams>(), &["feature", "params"]);
|
||||
assert_keys(input_schema_for::<ExportScriptParams>(), &["path"]);
|
||||
}
|
||||
|
||||
/// Strict gives the handlers' own messages for what they already refuse (a missing `features` or
|
||||
/// `feature` included: the handlers' words, not "is required").
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let key = |k: Value| json!({"feature": {"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]}, "params": k});
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("timeline.copy", json!({})),
|
||||
("timeline.copy", json!({"features": null})),
|
||||
("timeline.copy", json!({"features": []})),
|
||||
("timeline.copy", json!({"features": 3})),
|
||||
("timeline.copy", json!({"features": true})),
|
||||
("timeline.copy", json!({"features": [true]})),
|
||||
("timeline.copy", json!({"features": ["S", -1]})),
|
||||
("timeline.copy", json!({"features": ["S", 1.5]})),
|
||||
("timeline.copy", json!({"features": vec!["S"; 1001]})),
|
||||
("timeline.copy", json!({"features": vec!["S"; 10_001]})),
|
||||
("timeline.copy", json!({"features": ["Nope"]})),
|
||||
("timeline.paste", json!({"from_design": null})),
|
||||
("timeline.paste", json!({"from_design": 1})),
|
||||
("timeline.paste", json!({"from_design": "true"})),
|
||||
("timeline.add", json!({})),
|
||||
("timeline.add", json!({"feature": null})),
|
||||
("timeline.add", json!({"feature": [1, 2, 3]})),
|
||||
("timeline.add", json!({"feature": "box"})),
|
||||
("timeline.add", key(json!("q"))),
|
||||
("timeline.add", key(json!({"name": "q"}))),
|
||||
("timeline.add", key(json!(vec![json!({"name": "q", "expression": "1"}); 40_001]))),
|
||||
("timeline.add", key(json!([1]))),
|
||||
("timeline.add", key(json!([{"expression": "1"}]))),
|
||||
("timeline.add", key(json!([{"name": 4, "expression": "1"}]))),
|
||||
("timeline.add", key(json!([{"name": "q"}]))),
|
||||
("timeline.add", key(json!([{"name": "q", "expression": " "}]))),
|
||||
("timeline.add", key(json!([{"name": "q", "expression": true}]))),
|
||||
("timeline.add", key(json!([{"name": "q", "expression": "1", "unit": 3}]))),
|
||||
("timeline.add", key(json!([{"name": "q", "expression": "1", "comment": []}]))),
|
||||
("timeline.export_script", json!({"path": 7})),
|
||||
("timeline.export_script", json!({"path": true})),
|
||||
("timeline.export_script", json!({"path": ["a"]})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A paste with something to paste (in this design, or from another one): strict gives the
|
||||
/// handler's message for each key it refuses. Without anything copied the handler says so before
|
||||
/// it reads the other keys.
|
||||
#[test]
|
||||
fn paste_strict_keeps_todays_errors() {
|
||||
let mut source = Session::default();
|
||||
plate(&mut source);
|
||||
run(&mut source, "timeline.copy", json!({"features": ["S"]}));
|
||||
let cases = [
|
||||
json!({"translate": [1, 2]}),
|
||||
json!({"translate": null}),
|
||||
json!({"translate": "1,2,3"}),
|
||||
json!({"translate": [1e9, 0, 0]}),
|
||||
json!({"component": true}),
|
||||
json!({"component": null}),
|
||||
json!({"component_path": "0"}),
|
||||
json!({"component_path": null}),
|
||||
json!({"component_path": [-1]}),
|
||||
json!({"component_path": vec![0; 65]}),
|
||||
];
|
||||
for design in [false, true] {
|
||||
for case in &cases {
|
||||
let mut p = case.clone();
|
||||
p["from_design"] = json!(design);
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
plate(&mut s);
|
||||
s.foreign_copy = source.foreign_copy.clone();
|
||||
run(&mut s, "timeline.copy", json!({"features": ["S"]}));
|
||||
s.foreign_copy = source.foreign_copy.clone();
|
||||
s.execute("timeline.paste", &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some_and(|e| !e.contains("nothing copied")), "{p} should fail on the key");
|
||||
assert_eq!(error(ParamCheck::Strict), error(ParamCheck::Off), "{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The types read each key as the handlers do: what the handler's reader takes the type takes,
|
||||
/// and a refusal has the handler's message.
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_the_handlers_do() {
|
||||
let ok = |id: &str, p: Value| assert_eq!(issues(id, p.clone()), Vec::<String>::new(), "{p}");
|
||||
let refused = |id: &str, p: Value, message: &str| assert_eq!(issues(id, p.clone()), [message], "{p}");
|
||||
|
||||
// timeline.copy: a name, or names and ids in any mix; null is not absent.
|
||||
ok("timeline.copy", json!({"features": "S"}));
|
||||
ok("timeline.copy", json!({"features": ["S", 3, "E"]}));
|
||||
ok("timeline.copy", json!({"features": vec!["S"; 1000]}));
|
||||
refused("timeline.copy", json!({"features": []}), "`features` must list 1…1000 features");
|
||||
refused("timeline.copy", json!({"features": null}), "`features` must list 1…1000 features");
|
||||
refused("timeline.copy", json!({"features": vec!["S"; 1001]}), "`features` must list 1…1000 features");
|
||||
refused("timeline.copy", json!({"features": 3}), "`features` must be a list of names or ids; it is 3");
|
||||
refused("timeline.copy", json!({"features": ["S", true]}), "`features` must list names or ids; the entry 2 is true");
|
||||
|
||||
// timeline.paste: the same keys with or without from_design.
|
||||
for design in [json!({}), json!({"from_design": false}), json!({"from_design": true})] {
|
||||
let with = |k: &str, v: Value| {
|
||||
let mut p = design.clone();
|
||||
p[k] = v;
|
||||
p
|
||||
};
|
||||
ok("timeline.paste", design.clone());
|
||||
ok("timeline.paste", with("translate", json!([1, 2.5, -3])));
|
||||
ok("timeline.paste", with("translate", json!({"x": 1, "y": 2, "z": 3})));
|
||||
ok("timeline.paste", with("component", json!("Plate")));
|
||||
ok("timeline.paste", with("component", json!(4)));
|
||||
ok("timeline.paste", with("component_path", json!([])));
|
||||
ok("timeline.paste", with("component_path", json!([1, 2])));
|
||||
refused("timeline.paste", with("translate", json!([1, 2])), "`translate` must be [x, y, z]");
|
||||
refused("timeline.paste", with("translate", json!(null)), "`translate` must be [x, y, z]");
|
||||
refused("timeline.paste", with("component", json!(null)), "`component` must be a component id or name");
|
||||
refused("timeline.paste", with("component", json!([1])), "`component` must be a component id or name");
|
||||
refused("timeline.paste", with("component_path", json!(null)), "`component_path` must list 0..64 occurrence ids");
|
||||
refused("timeline.paste", with("component_path", json!([1.5])), "`component_path` must list 0..64 occurrence ids");
|
||||
refused("timeline.paste", with("component_path", json!(vec![0; 65])), "`component_path` must list 0..64 occurrence ids");
|
||||
}
|
||||
ok("timeline.paste", json!({"component_path": vec![0; 64]}));
|
||||
refused("timeline.paste", json!({"from_design": null}), "`from_design` must be true or false");
|
||||
refused("timeline.paste", json!({"from_design": 0}), "`from_design` must be true or false");
|
||||
|
||||
// timeline.add: the feature is an object; params are read by the handler's own reader.
|
||||
let feature = json!({"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]});
|
||||
ok("timeline.add", json!({"feature": feature}));
|
||||
ok("timeline.add", json!({"feature": feature, "params": null}));
|
||||
ok("timeline.add", json!({"feature": feature, "params": []}));
|
||||
ok("timeline.add", json!({"feature": feature, "params": [{"name": "q", "expression": 5}]}));
|
||||
ok("timeline.add", json!({"feature": feature, "params": [{"name": "q", "expression": "5", "unit": null, "comment": null, "extra": 1}]}));
|
||||
ok("timeline.add", json!({"feature": feature, "params": [{"name": " q ", "expression": " 5 ", "unit": "mm", "comment": "c"}]}));
|
||||
let message = "`feature` must be a feature object, as a design file or timeline.inspect has it";
|
||||
refused("timeline.add", json!({"feature": 1}), message);
|
||||
refused("timeline.add", json!({"feature": null}), message);
|
||||
refused("timeline.add", json!({"feature": feature, "params": {}}), "`params` must be a list of parameters");
|
||||
refused("timeline.add", json!({"feature": feature, "params": [{}]}), "each parameter needs a `name`");
|
||||
refused("timeline.add", json!({"feature": feature, "params": [{"name": "q"}]}), "parameter `q` needs an `expression`");
|
||||
refused(
|
||||
"timeline.add",
|
||||
json!({"feature": feature, "params": [{"name": "q", "expression": "1", "unit": 1}]}),
|
||||
"parameter `q`: `unit` must be text",
|
||||
);
|
||||
refused(
|
||||
"timeline.add",
|
||||
json!({"feature": feature, "params": [{"name": "q", "expression": "1", "comment": 1}]}),
|
||||
"parameter `q`: `comment` must be text",
|
||||
);
|
||||
// The feature's own keys are the design file's to check, not the contract's.
|
||||
ok("timeline.add", json!({"feature": {"type": "warp_drive", "anything": [1, 2]}}));
|
||||
|
||||
// timeline.export_script: text, or null for no file.
|
||||
ok("timeline.export_script", json!({}));
|
||||
ok("timeline.export_script", json!({"path": null}));
|
||||
ok("timeline.export_script", json!({"path": "script.json"}));
|
||||
refused("timeline.export_script", json!({"path": 1}), "`path` must be a file path");
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need: the keys a handler refuses without are required, and
|
||||
/// each value is the form its reader takes.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<CopyParams>(),
|
||||
&[
|
||||
(json!({"features": "S"}), true),
|
||||
(json!({"features": ["S", 2]}), true),
|
||||
(json!({}), false),
|
||||
(json!({"features": []}), false),
|
||||
(json!({"features": 2}), false),
|
||||
(json!({"features": [true]}), false),
|
||||
(json!({"features": [-1]}), false),
|
||||
(json!({"features": vec!["S"; 1001]}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<PasteParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"translate": [1, 2, 3], "component": "P", "component_path": [1], "from_design": true}), true),
|
||||
(json!({"translate": {"x": 1, "y": 2, "z": 3}, "component": 2}), true),
|
||||
(json!({"translate": [1, 2]}), false),
|
||||
(json!({"translate": [1e9, 0, 0]}), false),
|
||||
(json!({"component": true}), false),
|
||||
(json!({"component_path": [-1]}), false),
|
||||
(json!({"component_path": vec![0; 65]}), false),
|
||||
(json!({"from_design": null}), false),
|
||||
(json!({"from_design": "yes"}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<AddParams>(),
|
||||
&[
|
||||
(json!({"feature": {"type": "box"}}), true),
|
||||
(json!({"feature": {"type": "box"}, "params": [{"name": "q", "expression": 5, "unit": "mm", "comment": null}]}), true),
|
||||
(json!({"feature": {"type": "box"}, "params": [{"name": "q", "expression": "5"}]}), true),
|
||||
(json!({}), false),
|
||||
(json!({"feature": []}), false),
|
||||
(json!({"feature": {"type": "box"}, "params": [{"name": "q"}]}), false),
|
||||
(json!({"feature": {"type": "box"}, "params": {"name": "q"}}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ExportScriptParams>(),
|
||||
&[(json!({}), true), (json!({"path": "a.json"}), true), (json!({"path": 3}), false), (json!({"file": "a.json"}), false)],
|
||||
);
|
||||
}
|
||||
|
||||
/// Copy (a name, an id, both), paste (as it is, moved, into a component, from another design),
|
||||
/// in Warn: each real reply matches its output schema and carries no warning.
|
||||
#[test]
|
||||
fn copy_and_paste_replies_match_the_output_schema() {
|
||||
let mut s = warn_session();
|
||||
plate(&mut s);
|
||||
let sketch_id = s.doc.find_feature("S").map(|f| f.id).unwrap_or_default();
|
||||
|
||||
for features in [json!("S"), json!(["S"]), json!([sketch_id]), json!(["S", "E"]), json!(["E", sketch_id])] {
|
||||
let copied = run(&mut s, "timeline.copy", json!({"features": features}));
|
||||
assert!(copied["copied"].as_array().is_some_and(|c| !c.is_empty()), "{copied}");
|
||||
matches(output_schema_for::<CopyResult>(), "timeline.copy", &copied);
|
||||
}
|
||||
assert_eq!(run(&mut s, "timeline.copy", json!({"features": ["E", "S"]}))["copied"], json!(["S", "E"]), "timeline order");
|
||||
|
||||
let pasted = run(&mut s, "timeline.paste", json!({}));
|
||||
assert_eq!(pasted["pasted"].as_array().map(Vec::len), Some(2), "{pasted}");
|
||||
assert_eq!(pasted["pasted"][0]["from"], "S", "{pasted}");
|
||||
assert_eq!(pasted["pasted"][0]["name"], "S (2)", "{pasted}");
|
||||
assert!(pasted["pasted"][0]["id"].is_u64(), "{pasted}");
|
||||
assert_eq!(pasted["errors"], json!([]), "{pasted}");
|
||||
assert_eq!(pasted["notices"], json!([]), "{pasted}");
|
||||
matches(output_schema_for::<PasteResult>(), "timeline.paste", &pasted);
|
||||
|
||||
for p in [json!({"translate": [30, 0, 0]}), json!({"translate": {"x": 0, "y": 30, "z": 0}, "from_design": false})] {
|
||||
let moved = run(&mut s, "timeline.paste", p);
|
||||
matches(output_schema_for::<PasteResult>(), "timeline.paste", &moved);
|
||||
}
|
||||
|
||||
// Into a component, by name and by id, with its placement.
|
||||
let made = run(&mut s, "component.create", json!({"name": "Plate", "grounded": false}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let (component, occurrence) = (made["component"].clone(), made["occurrence"].clone());
|
||||
let into = run(&mut s, "timeline.paste", json!({"component": "Plate", "component_path": [occurrence.clone()]}));
|
||||
matches(output_schema_for::<PasteResult>(), "timeline.paste", &into);
|
||||
let by_id = run(&mut s, "timeline.paste", json!({"component": component, "translate": [0, 0, 20]}));
|
||||
matches(output_schema_for::<PasteResult>(), "timeline.paste", &by_id);
|
||||
|
||||
// From another design: its copy is in the snapshot, pasted with the same keys.
|
||||
let mut source = warn_session();
|
||||
plate(&mut source);
|
||||
run(&mut source, "timeline.copy", json!({"features": ["S"]}));
|
||||
let mut target = warn_session();
|
||||
target.foreign_copy = source.foreign_copy.clone();
|
||||
let foreign = run(&mut target, "timeline.paste", json!({"from_design": true, "translate": [5, 0, 0], "component_path": []}));
|
||||
assert_eq!(foreign["pasted"][0]["from"], "S", "{foreign}");
|
||||
assert_eq!(foreign["errors"], json!([]), "{foreign}");
|
||||
assert_eq!(foreign["notices"], json!([]), "{foreign}");
|
||||
matches(output_schema_for::<PasteResult>(), "timeline.paste", &foreign);
|
||||
|
||||
// A copy of a feature that is not a sketch, by id.
|
||||
let mut notices = warn_session();
|
||||
run(&mut notices, "solid.box", json!({"length": 5, "width": 5, "height": 5}));
|
||||
let nothing = run(&mut notices, "timeline.copy", json!({"features": [1]}));
|
||||
matches(output_schema_for::<CopyResult>(), "timeline.copy", ¬hing);
|
||||
}
|
||||
|
||||
/// Add every step of a design's script in Warn, with its parameters: each `timeline.add` reply
|
||||
/// matches the output schema without warnings, a feature that does not build says why, and the
|
||||
/// script is returned and written as before.
|
||||
#[test]
|
||||
fn add_and_export_replies_match_the_output_schema() {
|
||||
let mut s = warn_session();
|
||||
plate(&mut s);
|
||||
let exported = run(&mut s, "timeline.export_script", json!({}));
|
||||
matches(output_schema_for::<ExportScriptResult>(), "timeline.export_script", &exported);
|
||||
assert_eq!(exported["path"], Value::Null, "{exported}");
|
||||
assert_eq!(exported["omitted"], json!([]), "{exported}");
|
||||
assert_eq!(exported["steps"].as_u64(), exported["script"]["commands"].as_array().map(|c| c.len() as u64), "{exported}");
|
||||
let mut about: Vec<_> = exported["script"]["about"].as_object().into_iter().flat_map(|o| o.keys().cloned()).collect();
|
||||
about.sort();
|
||||
assert_eq!(about, ["design", "format", "replay", "version"], "{exported}");
|
||||
assert!(exported["script"]["commands"].as_array().is_some_and(|c| c.iter().all(|c| c["command"].is_string() && c.get("params").is_some())));
|
||||
|
||||
let mut t = warn_session();
|
||||
let mut added = 0;
|
||||
for step in exported["script"]["commands"].as_array().into_iter().flatten() {
|
||||
let reply = run(&mut t, step["command"].as_str().unwrap_or_default(), step["params"].clone());
|
||||
if step["command"] == "timeline.add" {
|
||||
added += 1;
|
||||
assert!(reply["error"].is_null() && reply["warning"].is_null(), "{reply}");
|
||||
matches(output_schema_for::<AddResult>(), "timeline.add", &reply);
|
||||
}
|
||||
}
|
||||
assert!(added >= 2, "a sketch and an extrude");
|
||||
assert!(
|
||||
exported["script"]["commands"].as_array().is_some_and(|c| c.iter().any(|c| c["params"]["params"].is_array())),
|
||||
"a step brings parameters"
|
||||
);
|
||||
|
||||
// Parameters as a number, with text and null in the other keys; a feature that doesn't build.
|
||||
let mut u = warn_session();
|
||||
let reply = run(
|
||||
&mut u,
|
||||
"timeline.add",
|
||||
json!({"feature": {"type": "box", "length": "q", "width": "5", "height": "5", "corner": [0, 0, 0]}, "params": [{"name": "q", "expression": 8, "unit": null, "comment": "a size"}]}),
|
||||
);
|
||||
assert_eq!(reply["name"], "Box1", "{reply}");
|
||||
matches(output_schema_for::<AddResult>(), "timeline.add", &reply);
|
||||
let broken = run(&mut u, "timeline.add", json!({"feature": {"type": "box", "length": "0", "width": "5", "height": "5", "corner": [0, 0, 0]}}));
|
||||
assert!(broken["error"].is_string() || broken["warning"].is_string(), "{broken}");
|
||||
matches(output_schema_for::<AddResult>(), "timeline.add", &broken);
|
||||
|
||||
// With a path the script is written, and the reply names the file.
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-timeline-schema-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));
|
||||
let file = dir.join("script.json");
|
||||
let written = run(&mut s, "timeline.export_script", json!({"path": file}));
|
||||
let text = std::fs::read_to_string(&file).unwrap_or_default();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(serde_json::from_str::<Value>(&text).ok(), Some(written["script"].clone()));
|
||||
// The file's text is the pretty-printed script with its keys sorted, as it has always been.
|
||||
let sorted = serde_json::to_string_pretty(&written["script"]).unwrap_or_default();
|
||||
assert_eq!(text, sorted);
|
||||
assert_eq!(written["path"], json!(file), "{written}");
|
||||
matches(output_schema_for::<ExportScriptResult>(), "timeline.export_script", &written);
|
||||
}
|
||||
|
||||
/// A misspelt key still runs in Warn, and says so, with a reply that matches its schema.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_in_warn() {
|
||||
let mut s = warn_session();
|
||||
plate(&mut s);
|
||||
let sketch = json!({"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]});
|
||||
let cases = [
|
||||
("timeline.copy", json!({"features": ["S"], "featurs": 1}), output_schema_for::<CopyResult>()),
|
||||
("timeline.paste", json!({"translat": [1, 0, 0]}), output_schema_for::<PasteResult>()),
|
||||
("timeline.add", json!({"feature": sketch, "param": []}), output_schema_for::<AddResult>()),
|
||||
("timeline.export_script", json!({"paht": "x.json"}), output_schema_for::<ExportScriptResult>()),
|
||||
];
|
||||
for (id, p, schema) in cases {
|
||||
if id == "timeline.paste" {
|
||||
run(&mut s, "timeline.copy", json!({"features": ["S"]}));
|
||||
}
|
||||
let reply = run(&mut s, id, p);
|
||||
let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {reply}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{id}: {reply}");
|
||||
}
|
||||
// In strict the call is refused before it runs.
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let refused = s.execute("timeline.export_script", &json!({"paht": "x.json"}));
|
||||
assert!(refused.is_err_and(|e| e.to_string().contains("unknown key `paht`")));
|
||||
}
|
||||
|
||||
/// The expression of a parameter that isn't blank once trimmed: the pattern is the one the
|
||||
/// shared check builds from `trim`'s whitespace.
|
||||
#[test]
|
||||
fn a_blank_expression_is_refused_by_the_pattern() {
|
||||
let schema = input_schema_for::<AddParams>();
|
||||
let pattern = schema.as_value()["$defs"]["StepParams"]["items"]["properties"]["expression"]["anyOf"][0]["pattern"].clone();
|
||||
assert_eq!(pattern, json!(crate::schema::types::not_blank_pattern()));
|
||||
}
|
||||
@@ -2,17 +2,29 @@
|
||||
# (coverage_tests.rs). This list only shrinks: when you give a command its contract and output
|
||||
# type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id
|
||||
# per line.
|
||||
component.activate
|
||||
component.capture_position
|
||||
component.create
|
||||
component.delete
|
||||
component.from_bodies
|
||||
component.list
|
||||
component.move_bodies
|
||||
component.move_sketches
|
||||
component.paste_new
|
||||
component.properties
|
||||
component.rename
|
||||
component.revert_position
|
||||
component.unlock
|
||||
doc.open
|
||||
doc.recover
|
||||
doc.recovery_discard
|
||||
doc.recovery_list
|
||||
document.inspect
|
||||
engine.commands
|
||||
explode.create
|
||||
explode.delete
|
||||
explode.list
|
||||
explode.show
|
||||
expr.evaluate
|
||||
face.delete
|
||||
file.export
|
||||
@@ -23,15 +35,27 @@ file.save
|
||||
file.save_as
|
||||
file.save_mesh
|
||||
file.slicers
|
||||
frame.member
|
||||
frame.profile.insert
|
||||
frame.profile.list
|
||||
frame.profile.properties
|
||||
inspect.measure
|
||||
joint.as_built
|
||||
joint.cam
|
||||
joint.create
|
||||
joint.delete
|
||||
joint.drive
|
||||
joint.gear
|
||||
joint.inspect
|
||||
joint.limits
|
||||
joint.list
|
||||
joint.motion_link
|
||||
joint.origin
|
||||
joint.rack_pinion
|
||||
joint.reach
|
||||
joint.rigid_group
|
||||
joint.screw
|
||||
joint.solve
|
||||
joint.sweep
|
||||
material.assign
|
||||
material.list
|
||||
@@ -71,7 +95,9 @@ sheet.export_bend_table
|
||||
sheet.export_dxf
|
||||
sheet.flat_pattern
|
||||
sheet.path_flange
|
||||
sketch.arc.center_point
|
||||
sketch.arc.tangent
|
||||
sketch.arc.three_point
|
||||
sketch.auto_constrain
|
||||
sketch.auto_constrain_from_datum
|
||||
sketch.auto_project
|
||||
@@ -79,7 +105,10 @@ sketch.blend_curve
|
||||
sketch.break_link
|
||||
sketch.centerline
|
||||
sketch.chain
|
||||
sketch.circle.center
|
||||
sketch.circle.three_point
|
||||
sketch.circle.three_tangent
|
||||
sketch.circle.two_point
|
||||
sketch.circle.two_tangent
|
||||
sketch.conic
|
||||
sketch.constrainer
|
||||
@@ -107,11 +136,13 @@ sketch.inspect
|
||||
sketch.intersect
|
||||
sketch.intersection_curve
|
||||
sketch.isoparametric_curve
|
||||
sketch.line
|
||||
sketch.line.midpoint
|
||||
sketch.line3d
|
||||
sketch.move3d
|
||||
sketch.move_point
|
||||
sketch.options
|
||||
sketch.point
|
||||
sketch.point3d
|
||||
sketch.polygon.circumscribed
|
||||
sketch.polygon.edge
|
||||
@@ -122,6 +153,7 @@ sketch.rectangle.center
|
||||
sketch.rectangle.rounded
|
||||
sketch.rectangle.three_point
|
||||
sketch.rectangle.two_point
|
||||
sketch.redefine
|
||||
sketch.slot.arc_center
|
||||
sketch.slot.arc_three_point
|
||||
sketch.slot.center_point
|
||||
@@ -173,11 +205,20 @@ surface.thicken
|
||||
surface.trim
|
||||
surface.unstitch
|
||||
surface.untrim
|
||||
timeline.add
|
||||
timeline.copy
|
||||
timeline.export_script
|
||||
timeline.group
|
||||
timeline.move_many
|
||||
timeline.move_to_group
|
||||
timeline.paste
|
||||
timeline.redefine
|
||||
timeline.rename_group
|
||||
timeline.reorder
|
||||
timeline.reorder_many
|
||||
timeline.ungroup
|
||||
view.apply
|
||||
view.delete
|
||||
view.list
|
||||
view.rename
|
||||
view.save
|
||||
|
||||
+9
-62
@@ -397,23 +397,8 @@ fn polyline(verts: &[(Vec2, f64)], closed: bool, out: &mut Vec<Geom2>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for writing an R12-style ASCII DXF.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DxfWriteOptions {
|
||||
/// DXF $INSUNITS: 1 in, 2 ft, 4 mm (default), 5 cm, 6 m.
|
||||
pub insunits: i32,
|
||||
/// Default layer name (default "0").
|
||||
pub layer: String,
|
||||
}
|
||||
|
||||
impl Default for DxfWriteOptions {
|
||||
fn default() -> Self {
|
||||
DxfWriteOptions { insunits: 4, layer: "0".to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Write 2D geometry with per-entity layer names as an R12-style ASCII DXF.
|
||||
pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
|
||||
/// Write 2D geometry (millimetres) as an R12-style ASCII DXF.
|
||||
pub fn write_dxf(geom: &[Geom2]) -> String {
|
||||
let mut s = String::new();
|
||||
let mut w = |c: i32, v: &str| {
|
||||
s.push_str(&format!("{c}\n{v}\n"));
|
||||
@@ -421,24 +406,22 @@ pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
|
||||
w(0, "SECTION");
|
||||
w(2, "HEADER");
|
||||
w(9, "$INSUNITS");
|
||||
let insunits_str = insunits.to_string();
|
||||
w(70, &insunits_str);
|
||||
w(70, "4");
|
||||
w(0, "ENDSEC");
|
||||
w(0, "SECTION");
|
||||
w(2, "ENTITIES");
|
||||
let f = |x: f64| format!("{x:.9}");
|
||||
for (layer, g) in entities {
|
||||
let lyr = if layer.trim().is_empty() { "0" } else { layer.trim() };
|
||||
for g in geom {
|
||||
match g {
|
||||
Geom2::Point(p) => {
|
||||
w(0, "POINT");
|
||||
w(8, lyr);
|
||||
w(8, "0");
|
||||
w(10, &f(p.x));
|
||||
w(20, &f(p.y));
|
||||
}
|
||||
Geom2::Line(a, b) => {
|
||||
w(0, "LINE");
|
||||
w(8, lyr);
|
||||
w(8, "0");
|
||||
w(10, &f(a.x));
|
||||
w(20, &f(a.y));
|
||||
w(11, &f(b.x));
|
||||
@@ -446,14 +429,14 @@ pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
|
||||
}
|
||||
Geom2::Circle(c, r) => {
|
||||
w(0, "CIRCLE");
|
||||
w(8, lyr);
|
||||
w(8, "0");
|
||||
w(10, &f(c.x));
|
||||
w(20, &f(c.y));
|
||||
w(40, &f(*r));
|
||||
}
|
||||
Geom2::Arc { c, a, b } => {
|
||||
w(0, "ARC");
|
||||
w(8, lyr);
|
||||
w(8, "0");
|
||||
w(10, &f(c.x));
|
||||
w(20, &f(c.y));
|
||||
w(40, &f(c.dist(*a)));
|
||||
@@ -462,7 +445,7 @@ pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
|
||||
}
|
||||
Geom2::Text { text, at, height, angle } => {
|
||||
w(0, "TEXT");
|
||||
w(8, lyr);
|
||||
w(8, "0");
|
||||
w(10, &f(at.x));
|
||||
w(20, &f(at.y));
|
||||
w(40, &f(*height));
|
||||
@@ -478,18 +461,6 @@ pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Write 2D geometry as an R12-style ASCII DXF with options.
|
||||
pub fn write_dxf_opts(geom: &[Geom2], opts: &DxfWriteOptions) -> String {
|
||||
let layer = if opts.layer.trim().is_empty() { "0" } else { opts.layer.as_str() };
|
||||
let entities: Vec<(&str, Geom2)> = geom.iter().cloned().map(|g| (layer, g)).collect();
|
||||
write_dxf_entities(&entities, opts.insunits)
|
||||
}
|
||||
|
||||
/// Write 2D geometry (millimetres) as an R12-style ASCII DXF.
|
||||
pub fn write_dxf(geom: &[Geom2]) -> String {
|
||||
write_dxf_opts(geom, &DxfWriteOptions::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -672,28 +643,4 @@ mod tests {
|
||||
let g = read_dxf(&array).unwrap_or_default();
|
||||
assert!(g.is_empty(), "an empty block has no geometry to place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_dxf_opts_and_entities_round_trip() {
|
||||
let geom = vec![Geom2::Line(Vec2::ZERO, Vec2::new(25.4, 0.0)), Geom2::Circle(Vec2::new(12.7, 12.7), 6.35)];
|
||||
|
||||
// Default write_dxf: byte-identical check with write_dxf_opts default
|
||||
let d0 = write_dxf(&geom);
|
||||
let d1 = write_dxf_opts(&geom, &DxfWriteOptions::default());
|
||||
assert_eq!(d0, d1);
|
||||
assert!(d0.contains("\n8\n0\n"));
|
||||
assert!(d0.contains("\n70\n4\n"));
|
||||
|
||||
// Custom layer and inch units (insunits = 1)
|
||||
let opts = DxfWriteOptions { insunits: 1, layer: "CUT".to_string() };
|
||||
let d_inch = write_dxf_opts(&geom, &opts);
|
||||
assert!(d_inch.contains("\n8\nCUT\n"));
|
||||
assert!(d_inch.contains("\n70\n1\n"));
|
||||
|
||||
// Per-entity layers with write_dxf_entities
|
||||
let ents = vec![("OUTLINE", Geom2::Line(Vec2::ZERO, Vec2::new(10.0, 0.0))), ("CUT", Geom2::Circle(Vec2::new(5.0, 5.0), 2.0))];
|
||||
let d_roles = write_dxf_entities(&ents, 4);
|
||||
assert!(d_roles.contains("\n8\nOUTLINE\n"));
|
||||
assert!(d_roles.contains("\n8\nCUT\n"));
|
||||
}
|
||||
}
|
||||
|
||||
+3
-157
@@ -68,12 +68,6 @@ pub enum DxfShape {
|
||||
Polyline {
|
||||
points: Vec<Vec2>,
|
||||
},
|
||||
/// A lightweight polyline (AutoCAD `LWPOLYLINE`) with bulges for arc segments.
|
||||
/// Each entry in `verts` is `(position, bulge)`, where bulge is `tan(sweep / 4)`.
|
||||
LwPolyline {
|
||||
verts: Vec<(Vec2, f64)>,
|
||||
closed: bool,
|
||||
},
|
||||
Circle {
|
||||
c: Vec2,
|
||||
r: f64,
|
||||
@@ -159,54 +153,6 @@ pub fn loop_shapes(lp: &Loop2) -> Vec<DxfShape> {
|
||||
lp.segs.iter().map(seg_shape).collect()
|
||||
}
|
||||
|
||||
/// The closed loop as one AutoCAD `LWPOLYLINE` entity, with circular arc segments represented
|
||||
/// by their DXF bulge (tan of a quarter of the included angle). Free-form curves are sampled as lines.
|
||||
pub fn loop_lwpolyline_scaled(lp: &Loop2, scale: f64) -> DxfShape {
|
||||
let mut verts: Vec<(Vec2, f64)> = Vec::new();
|
||||
for s in &lp.segs {
|
||||
match *s {
|
||||
Seg2::Line { a, .. } => {
|
||||
verts.push((a * scale, 0.0));
|
||||
}
|
||||
Seg2::Arc { center, radius, start, sweep } => {
|
||||
if (sweep.abs() - TAU).abs() < 1e-9 {
|
||||
// Full circle: split into two 180° semicircles.
|
||||
let b = if sweep >= 0.0 { 1.0 } else { -1.0 };
|
||||
let p0 = (center + Vec2::from_angle(start) * radius) * scale;
|
||||
let p1 = (center + Vec2::from_angle(start + std::f64::consts::PI) * radius) * scale;
|
||||
verts.push((p0, b));
|
||||
verts.push((p1, b));
|
||||
} else if sweep.abs() > std::f64::consts::PI + 1e-9 {
|
||||
// Arc larger than 180°: split into two pieces.
|
||||
let half = sweep * 0.5;
|
||||
let b = (half / 4.0).tan();
|
||||
let p0 = (center + Vec2::from_angle(start) * radius) * scale;
|
||||
let p1 = (center + Vec2::from_angle(start + half) * radius) * scale;
|
||||
verts.push((p0, b));
|
||||
verts.push((p1, b));
|
||||
} else {
|
||||
let b = (sweep / 4.0).tan();
|
||||
let p0 = (center + Vec2::from_angle(start) * radius) * scale;
|
||||
verts.push((p0, b));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let poly = s.polyline(0.01);
|
||||
let count = poly.len().saturating_sub(1);
|
||||
for p in poly.iter().take(count) {
|
||||
verts.push((*p * scale, 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
DxfShape::LwPolyline { verts, closed: true }
|
||||
}
|
||||
|
||||
/// [`loop_lwpolyline_scaled`] at scale 1.0 (millimetres).
|
||||
pub fn loop_lwpolyline(lp: &Loop2) -> DxfShape {
|
||||
loop_lwpolyline_scaled(lp, 1.0)
|
||||
}
|
||||
|
||||
/// A parameter reduced to [0, 2π); one within 1e-12 of a full turn is 0.
|
||||
fn wrap(t: f64) -> f64 {
|
||||
let r = t.rem_euclid(TAU);
|
||||
@@ -275,30 +221,6 @@ impl DxfShape {
|
||||
match self {
|
||||
DxfShape::Line(a, b) => out.extend([*a, *b]),
|
||||
DxfShape::Polyline { points } => out.extend(points.iter().copied()),
|
||||
DxfShape::LwPolyline { verts, closed } => {
|
||||
for (i, (p0, b)) in verts.iter().enumerate() {
|
||||
out.push(*p0);
|
||||
if b.abs() > 1e-12 {
|
||||
let next_idx = if i + 1 < verts.len() {
|
||||
Some(i + 1)
|
||||
} else if *closed {
|
||||
Some(0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(next) = next_idx
|
||||
&& let Some((p1, _)) = verts.get(next)
|
||||
{
|
||||
let chord = *p1 - *p0;
|
||||
let mid = (*p0 + *p1) * 0.5;
|
||||
let arc_mid = mid + chord.perp() * (*b * 0.5);
|
||||
if arc_mid.x.is_finite() && arc_mid.y.is_finite() {
|
||||
out.push(arc_mid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
DxfShape::Circle { c, r } => out.extend([*c - Vec2::new(*r, *r), *c + Vec2::new(*r, *r)]),
|
||||
DxfShape::Arc { c, r, a0, a1 } => {
|
||||
let sweep = (a1 - a0).rem_euclid(360.0);
|
||||
@@ -427,11 +349,6 @@ fn text_value(s: &str) -> Result<String> {
|
||||
/// (layer `0` is always there). A TEXT character beyond U+FFFF returns an error naming the
|
||||
/// character, its position, the entity and its layer; no drawing is returned on failure.
|
||||
pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result<String> {
|
||||
write_dxf_drawing_units(layers, entities, 4)
|
||||
}
|
||||
|
||||
/// [`write_dxf_drawing`], with explicit DXF `$INSUNITS` (1 in, 2 ft, 4 mm, 5 cm, 6 m).
|
||||
pub fn write_dxf_drawing_units(layers: &[DxfLayer], entities: &[DxfEntity], insunits: i32) -> Result<String> {
|
||||
let mut pts = Vec::new();
|
||||
for e in entities {
|
||||
e.shape.sample(&mut pts);
|
||||
@@ -590,7 +507,7 @@ pub fn write_dxf_drawing_units(layers: &[DxfLayer], entities: &[DxfEntity], insu
|
||||
for (index, e) in entities.iter().enumerate() {
|
||||
let kind = match &e.shape {
|
||||
DxfShape::Line(..) => "LINE",
|
||||
DxfShape::Polyline { .. } | DxfShape::LwPolyline { .. } => "LWPOLYLINE",
|
||||
DxfShape::Polyline { .. } => "LWPOLYLINE",
|
||||
DxfShape::Circle { .. } => "CIRCLE",
|
||||
DxfShape::Arc { .. } => "ARC",
|
||||
DxfShape::Ellipse { .. } => "ELLIPSE",
|
||||
@@ -614,19 +531,6 @@ pub fn write_dxf_drawing_units(layers: &[DxfLayer], entities: &[DxfEntity], insu
|
||||
o.num(20, p.y);
|
||||
}
|
||||
}
|
||||
DxfShape::LwPolyline { verts, closed } => {
|
||||
o.code(100, "AcDbPolyline");
|
||||
o.code(90, verts.len());
|
||||
// Autodesk DXF reference: bit 1 closed, bit 128 (PLINEGEN) continues dash pattern.
|
||||
o.code(70, 128 + if *closed { 1 } else { 0 });
|
||||
for (p, b) in verts {
|
||||
o.num(10, p.x);
|
||||
o.num(20, p.y);
|
||||
if b.abs() > 1e-12 {
|
||||
o.num(42, *b);
|
||||
}
|
||||
}
|
||||
}
|
||||
DxfShape::Line(a, b) => {
|
||||
o.code(100, "AcDbLine");
|
||||
o.point(10, *a);
|
||||
@@ -728,9 +632,9 @@ pub fn write_dxf_drawing_units(layers: &[DxfLayer], entities: &[DxfEntity], insu
|
||||
head.code(9, "$HANDSEED");
|
||||
head.code(5, format!("{:X}", o.next));
|
||||
head.code(9, "$INSUNITS");
|
||||
head.code(70, insunits);
|
||||
head.code(70, 4);
|
||||
head.code(9, "$MEASUREMENT");
|
||||
head.code(70, if insunits == 1 || insunits == 2 { 0 } else { 1 });
|
||||
head.code(70, 1);
|
||||
head.code(9, "$EXTMIN");
|
||||
head.point(10, lo);
|
||||
head.code(9, "$EXTMAX");
|
||||
@@ -1224,62 +1128,4 @@ mod tests {
|
||||
assert_eq!(&after("$EXTMIN")[..2], &[(10, "27.0".to_string()), (20, "6.0".to_string())]);
|
||||
assert_eq!(&after("$EXTMAX")[..2], &[(10, "30.0".to_string()), (20, "18.0".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lwpolyline_with_bulge_and_units_round_trip() {
|
||||
// Closed loop with a line and a 90° arc segment (bulge tan(pi / 8)).
|
||||
let sweep = FRAC_PI_2;
|
||||
let bulge = (sweep / 4.0).tan();
|
||||
let loop2 = Loop2 {
|
||||
segs: vec![
|
||||
Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(0.0, 0.0) },
|
||||
Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(0.0, 10.0) },
|
||||
Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: FRAC_PI_2, sweep: -FRAC_PI_2 },
|
||||
],
|
||||
};
|
||||
let shape = loop_lwpolyline(&loop2);
|
||||
let DxfShape::LwPolyline { ref verts, closed } = shape else { panic!("expected LwPolyline") };
|
||||
assert!(closed);
|
||||
assert_eq!(verts.len(), 3);
|
||||
// Third segment is clockwise (-90°), bulge is negative
|
||||
assert!((verts[2].1 - (-bulge)).abs() < 1e-12, "bulge was {}", verts[2].1);
|
||||
|
||||
// Write with inch units (insunits = 1)
|
||||
let dxf = write_dxf_drawing_units(
|
||||
&[DxfLayer::new("CUT", 4)],
|
||||
&[DxfEntity { layer: "CUT".into(), shape: loop_lwpolyline_scaled(&loop2, 1.0 / 25.4) }],
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(dxf.contains("LWPOLYLINE"));
|
||||
assert!(dxf.contains("\n 8\nCUT\n") || dxf.contains("\n8\nCUT\n"));
|
||||
assert!(dxf.contains("\n 70\n1\n") || dxf.contains("\n70\n1\n")); // $INSUNITS 1
|
||||
|
||||
// Read back via read_dxf: should scale from inches back to mm
|
||||
let geom = read_dxf(&dxf).unwrap();
|
||||
assert_eq!(geom.len(), 3);
|
||||
// Arcs and lines should be recovered in millimetres
|
||||
let Some((c, a, b)) = geom.iter().find_map(|g| match *g {
|
||||
Geom2::Arc { c, a, b } => Some((c, a, b)),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("arc not recovered");
|
||||
};
|
||||
assert!(c.dist(Vec2::ZERO) < 1e-6);
|
||||
assert!((c.dist(a) - 10.0).abs() < 1e-6);
|
||||
assert!((c.dist(b) - 10.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lwpolyline_open_sampling_does_not_wrap_around() {
|
||||
// Unclosed polyline with 2 vertices: (0, 0) and (10, 0), with a bulge on the last vertex.
|
||||
// For an unclosed polyline, the last vertex cannot form an arc segment to vertex 0.
|
||||
let shape = DxfShape::LwPolyline { verts: vec![(Vec2::new(0.0, 0.0), 0.0), (Vec2::new(10.0, 0.0), 1.0)], closed: false };
|
||||
let mut pts = Vec::new();
|
||||
shape.sample(&mut pts);
|
||||
// Only the two vertices should be sampled, not an arc chord back to (0, 0)
|
||||
assert_eq!(pts.len(), 2);
|
||||
assert_eq!(pts[0], Vec2::new(0.0, 0.0));
|
||||
assert_eq!(pts[1], Vec2::new(10.0, 0.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,11 +39,8 @@ mod threemf;
|
||||
pub mod urdf;
|
||||
pub mod vfs;
|
||||
|
||||
pub use dxf::{DxfWriteOptions, read_dxf, write_dxf, write_dxf_entities, write_dxf_opts};
|
||||
pub use dxf_out::{
|
||||
DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_lwpolyline, loop_lwpolyline_scaled, loop_shapes, seg_shape, write_dxf_drawing,
|
||||
write_dxf_drawing_units,
|
||||
};
|
||||
pub use dxf::{read_dxf, write_dxf};
|
||||
pub use dxf_out::{DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_shapes, seg_shape, write_dxf_drawing};
|
||||
pub use legacy_dir::{APP_ID, LEGACY_APP_ID, PREVIOUS_APP_IDS, adopt_legacy_dir, legacy_flatpak_paths};
|
||||
pub use safe_write::{backup_path, write_atomic};
|
||||
pub use sketch2d::{Geom2, MAX_DRAWING_BYTES};
|
||||
|
||||
@@ -3150,25 +3150,10 @@ fn entry_row(
|
||||
let patterns_open = pattern_key.is_some_and(|key| is_open(app, key, start_open));
|
||||
let rect = row_rect(ui);
|
||||
let revealed = folder == "bodies" && body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b));
|
||||
// Features under bodies (#11945): the body row folds open on the features that built it.
|
||||
let built_key = (folder == "bodies"
|
||||
&& app.preferences.browser_body_features
|
||||
&& !crate::render_workspace::active(app)
|
||||
&& matches!(e.sel, Some(Sel::Body { .. })))
|
||||
.then(|| format!("{}/features", e.row_key));
|
||||
let built_open = built_key.as_deref().is_some_and(|key| is_open(app, key, false));
|
||||
if !ui.is_rect_visible(rect) && !patterns_open && !revealed && !built_open {
|
||||
if !ui.is_rect_visible(rect) && !patterns_open && !revealed {
|
||||
ui.allocate_space(rect.size());
|
||||
return;
|
||||
}
|
||||
let built: Vec<u64> = match &built_key {
|
||||
Some(_) => {
|
||||
prepare_model(app);
|
||||
app.tree.model.as_mut().map(|model| model.body_features(&app.session, &e.key)).unwrap_or_default()
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
let built_key = built_key.filter(|_| !built.is_empty());
|
||||
let (selected, mark) = lit_row(acts.lit.entry(app, e));
|
||||
let visible = e.is_visible(app);
|
||||
let locked = match &e.sel {
|
||||
@@ -3188,7 +3173,7 @@ fn entry_row(
|
||||
ui.scope_id().with(("item", &e.row_key)),
|
||||
&Row {
|
||||
depth,
|
||||
fold: pattern_key.map(|_| patterns_open).or(built_key.as_ref().map(|_| built_open)),
|
||||
fold: pattern_key.map(|_| patterns_open),
|
||||
eye: Some(visible),
|
||||
icon: e.icon,
|
||||
kind_tip: e.tip,
|
||||
@@ -3220,10 +3205,6 @@ fn entry_row(
|
||||
&& let Some(key) = pattern_key
|
||||
{
|
||||
toggle(app, key, start_open);
|
||||
} else if r.fold
|
||||
&& let Some(key) = &built_key
|
||||
{
|
||||
toggle(app, key, false);
|
||||
}
|
||||
if folder == "bodies"
|
||||
&& body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b))
|
||||
@@ -3295,9 +3276,6 @@ fn entry_row(
|
||||
if patterns_open && let Some(Sel::Feature { id }) = &e.sel {
|
||||
crate::sketch_pattern_tree::rows(app, ui, *id, depth + 1, "browser", path.map(|path| (comp, path)), !visible || parent_hidden);
|
||||
}
|
||||
if built_open && built_key.is_some() {
|
||||
features::body_rows(app, ui, acts, comp, path.unwrap_or_default(), &e.row_key, &built, depth + 1);
|
||||
}
|
||||
let Some(resp) = &r.resp else { return };
|
||||
// Drag: the selected items of this folder when this one is selected, else just this one.
|
||||
if resp.drag_started()
|
||||
|
||||
@@ -137,7 +137,7 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path:
|
||||
.filter_map(|(i, f)| (f.component == component && (compact || !matches!(f.kind, FeatureKind::Sketch { .. }))).then_some(i))
|
||||
.collect(),
|
||||
};
|
||||
let here = Here { component, path, scope: &scope, body_row: None };
|
||||
let here = Here { component, path, scope: &scope };
|
||||
// The feature that made what is under the cursor or picked in the viewport, as the history
|
||||
// lights it, and in the history layout what a selected history row lights.
|
||||
let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)];
|
||||
@@ -206,32 +206,6 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path:
|
||||
drag_rows(app, ui, &plan, drag_id, dragged, &drops, resp.rect.center().y);
|
||||
}
|
||||
|
||||
/// The features that built a body, one level in under its row (#11945): the feature rows the
|
||||
/// Features folder draws, without dragging, each lit as there when the view lights it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn body_rows(
|
||||
app: &mut SolveApp,
|
||||
ui: &mut egui::Ui,
|
||||
acts: &mut Actions,
|
||||
component: u64,
|
||||
path: &[u64],
|
||||
body_row: &str,
|
||||
features: &[u64],
|
||||
depth: usize,
|
||||
) {
|
||||
let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(path) };
|
||||
let here = Here { component, path, scope: &scope, body_row: Some(body_row) };
|
||||
let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)];
|
||||
// A feature that built several bodies is listed under each: its rows need ids of their own.
|
||||
ui.push_id(("body_features", body_row), |ui| {
|
||||
for id in features {
|
||||
let Some(index) = app.session.doc.features.iter().position(|f| f.id == *id) else { continue };
|
||||
let mark = if from_view.contains(&Some(*id)) { Mark::Here } else { Mark::None };
|
||||
let _ = feature_row(app, ui, acts, &here, index, depth, None, mark, None);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A place in the browser's History where dragged rows can land: its height, the timeline
|
||||
/// position they move to and the folder they join (`None`: the timeline root).
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -246,9 +220,6 @@ struct Here<'a> {
|
||||
component: u64,
|
||||
path: &'a [u64],
|
||||
scope: &'a str,
|
||||
/// The body row a feature row is listed under (#11945): its row-order key is then its own,
|
||||
/// `<body row>/s:<id>`, so a feature listed under two bodies is a range end at each row.
|
||||
body_row: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// The component's history rows, `indices` its features' timeline positions: with Sketches:
|
||||
@@ -306,8 +277,7 @@ fn feature_row(
|
||||
// stays the face or edge.
|
||||
let by_geometry = !app.session.selection.contains(&Sel::Feature { id }) && crate::timeline::picked_feature(app) == Some(id);
|
||||
let selected = app.session.selection.contains(&Sel::Feature { id }) || by_geometry;
|
||||
let order_key = here.body_row.map_or_else(|| format!("f:{id}"), |row| format!("{row}/s:{id}"));
|
||||
app.tree.remember(&order_key);
|
||||
app.tree.remember(&format!("f:{id}"));
|
||||
let action = sketch.map(|_| ("sketch", "Edit Profile Sketch"));
|
||||
// A sketch row has the eye its Sketches folder row has. A feature's eye shows and hides the
|
||||
// bodies it made (#5099); a component listed on its own stands for all of its placements.
|
||||
@@ -373,7 +343,7 @@ fn feature_row(
|
||||
// active before comes back when the editor ends (#12720).
|
||||
app.edit_feature_in(id, Some((component, path)));
|
||||
} else if r.clicked {
|
||||
click_select(app, ui, order_key, Some(Sel::Feature { id }));
|
||||
click_select(app, ui, format!("f:{id}"), Some(Sel::Feature { id }));
|
||||
}
|
||||
if let Some(at) = r.secondary {
|
||||
acts.menu = Some((at, if is_sketch { Target::Sketch { id } } else { Target::Feature { id } }));
|
||||
@@ -1372,81 +1342,4 @@ mod tests {
|
||||
assert_eq!(h.app.session.doc.marker, Some(2), "the marker drag still rolls back");
|
||||
assert_eq!(order(&h), [ids[2], ids[0], ids[1]], "rolling back moves no feature");
|
||||
}
|
||||
|
||||
/// #11945: with Features under bodies on, a body row folds open on the features that built it,
|
||||
/// in timeline order and only those; a click on one selects it. Off, the default, body rows
|
||||
/// have no fold arrow and list nothing.
|
||||
#[test]
|
||||
fn body_rows_fold_open_on_the_features_that_built_them() {
|
||||
let mut h = Harness::new();
|
||||
h.app.run("solid.box", json!({"length":20,"width":20,"height":10,"name":"Base","body_name":"Plate"})).unwrap();
|
||||
h.app
|
||||
.run("solid.box", json!({"length":5,"width":5,"height":5,"corner":[50,0,0],"operation":"new","name":"Block","body_name":"Other"}))
|
||||
.unwrap();
|
||||
let round =
|
||||
h.app.run("solid.fillet", json!({"body":"Plate","edges":[[10,0,10]],"radius":1,"name":"Round"})).unwrap()["feature"].as_u64().unwrap();
|
||||
h.frames(3);
|
||||
assert_eq!(fold_of("Plate"), None, "off by default: no fold arrow on a body");
|
||||
assert_eq!(count("Round"), 0);
|
||||
|
||||
assert_eq!(h.call("ui.prefs", json!({"browser_body_features": true}))["ok"], true);
|
||||
h.frames(2);
|
||||
assert_eq!(fold_of("Plate"), Some(false), "the body starts folded");
|
||||
assert_eq!(count("Round"), 0);
|
||||
h.step(&json!({"click": {"handle": "fold:Plate"}})).unwrap();
|
||||
h.frames(2);
|
||||
let rows = drawn_rows();
|
||||
let top = |label: &str| rows.iter().find(|(l, ..)| l == label).map(|row| row.1.top()).unwrap();
|
||||
assert_eq!((count("Base"), count("Round"), count("Block")), (1, 1, 0), "only what built Plate");
|
||||
assert!(top("Plate") < top("Base") && top("Base") < top("Round") && top("Round") < top("Other"), "under Plate, in timeline order");
|
||||
|
||||
let at = rows.iter().find(|(l, ..)| l == "Round").map(|row| row.1.center()).unwrap();
|
||||
h.step(&json!({"click": [at.x, at.y]})).unwrap();
|
||||
assert_eq!(h.app.session.selection, [Sel::Feature { id: round }]);
|
||||
|
||||
h.call("ui.prefs", json!({"browser_body_features": false}));
|
||||
h.frames(2);
|
||||
assert_eq!((fold_of("Plate"), count("Round")), (None, 0), "off again: as before");
|
||||
}
|
||||
|
||||
/// #11945: a feature that changed two bodies is listed under each; Shift-clicking its second
|
||||
/// row takes the range from the anchor to that row, not to its first row under the other body.
|
||||
#[test]
|
||||
fn a_feature_under_two_bodies_is_a_range_end_at_each_row() {
|
||||
let mut h = Harness::new();
|
||||
h.app.run("solid.box", json!({"length":20,"width":20,"height":10,"name":"Base","body_name":"Plate"})).unwrap();
|
||||
let block = h
|
||||
.app
|
||||
.run("solid.box", json!({"length":5,"width":5,"height":10,"corner":[50,0,0],"operation":"new","name":"Block","body_name":"Other"}))
|
||||
.unwrap()["feature"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
// A groove along the top of both bodies, splitting neither.
|
||||
let groove = h
|
||||
.app
|
||||
.run(
|
||||
"solid.box",
|
||||
json!({"length":70,"width":2,"height":10,"corner":[-5,1,5],"operation":"cut","targets":["Plate","Other"],"name":"Groove"}),
|
||||
)
|
||||
.unwrap()["feature"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
assert_eq!(h.call("ui.prefs", json!({"browser_body_features": true}))["ok"], true);
|
||||
h.frames(2);
|
||||
for body in ["Plate", "Other"] {
|
||||
h.step(&json!({"click": {"handle": format!("fold:{body}")}})).unwrap();
|
||||
h.frames(2);
|
||||
}
|
||||
assert_eq!(count("Groove"), 2, "listed under both bodies");
|
||||
let rows = drawn_rows();
|
||||
let at = |label: &str, last: bool| {
|
||||
let mut hits = rows.iter().filter(|(l, ..)| l == label);
|
||||
let hit = if last { hits.next_back() } else { hits.next() };
|
||||
hit.map(|row| row.1.center()).unwrap()
|
||||
};
|
||||
let (block_at, groove_at) = (at("Block", false), at("Groove", true));
|
||||
h.step(&json!({"click": [block_at.x, block_at.y]})).unwrap();
|
||||
h.step(&json!({"click": [groove_at.x, groove_at.y], "shift": true})).unwrap();
|
||||
assert_eq!(h.app.session.selection, [Sel::Feature { id: block }, Sel::Feature { id: groove }], "only the rows under Other");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,6 @@ pub(super) struct Model {
|
||||
placements: HashMap<Vec<u64>, Option<Arc<OccurrencePlacement>>>,
|
||||
/// Each placed body's placement path, by the body's world name (built on first use).
|
||||
body_paths: Option<HashMap<String, Vec<u64>>>,
|
||||
/// The features that built each body, by its model name (worked out on first use, #11945).
|
||||
body_features: Option<BTreeMap<String, Vec<u64>>>,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
@@ -69,16 +67,9 @@ impl Model {
|
||||
children,
|
||||
placements: HashMap::new(),
|
||||
body_paths: None,
|
||||
body_features: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The features that built the body with this model name, in timeline order
|
||||
/// ([`Session::body_features`]), worked out once per model.
|
||||
pub fn body_features(&mut self, session: &Session, body: &str) -> Vec<u64> {
|
||||
self.body_features.get_or_insert_with(|| session.body_features()).get(body).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn matches(&self, session: &Session) -> bool {
|
||||
Arc::ptr_eq(&self.doc, &session.doc) && Arc::ptr_eq(&self.state, &session.model.state()) && self.pending_moves == session.pending_moves
|
||||
}
|
||||
|
||||
@@ -1378,9 +1378,6 @@ preference_settings! {
|
||||
/// A Play History button in the History controls, between Previous and Next (#3688). Off
|
||||
/// gives the four controls History had before; right-clicking the controls toggles it too.
|
||||
history_play_button: bool = true, PAGE_LAYOUT;
|
||||
/// A History folder whose features are all of one kind (Holes, say) shows their icon instead of
|
||||
/// the folder icon, in both Histories. Off by default: every folder shows the folder icon.
|
||||
history_folder_kind_icon: bool = false, PAGE_LAYOUT;
|
||||
/// On, two or more joints show as one button with their count in the History, and a click
|
||||
/// shows each one (#8884). Off, the default, shows each joint as the History always has.
|
||||
history_group_joints: bool = false, PAGE_LAYOUT;
|
||||
@@ -1426,9 +1423,6 @@ preference_settings! {
|
||||
/// Every component placement in the browser starts open, as before #9274, instead of closed
|
||||
/// until the user opens it. Off by default.
|
||||
browser_components_open: bool = false, PAGE_LAYOUT;
|
||||
/// Each body row in the Browser folds open on the timeline features that built it, in
|
||||
/// timeline order (#11945). Off by default: body rows have no fold arrow, as before.
|
||||
browser_body_features: bool = false, PAGE_LAYOUT;
|
||||
/// Folders in the Browser start closed, and placements too whatever "Components start open"
|
||||
/// says, and they open only on request (#8768): with their arrow, Expand All or Find in
|
||||
/// Browser, which opens just the rows down to its body and closes again the ones the last find
|
||||
@@ -6391,7 +6385,6 @@ mod tests {
|
||||
("timeline_under_browser", json!(true), PAGE_LAYOUT),
|
||||
("history_sketches", json!("under_feature"), PAGE_LAYOUT),
|
||||
("history_play_button", json!(false), PAGE_LAYOUT),
|
||||
("history_folder_kind_icon", json!(true), PAGE_LAYOUT),
|
||||
("history_group_joints", json!(true), PAGE_LAYOUT),
|
||||
("history_bar_groups", json!(true), PAGE_LAYOUT),
|
||||
("browser_float", json!(true), PAGE_LAYOUT),
|
||||
|
||||
@@ -458,25 +458,6 @@ pub(super) fn layout(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
&mut app.preferences.browser_eye_left,
|
||||
"browser_eye_left",
|
||||
);
|
||||
layout_check(
|
||||
ui,
|
||||
app.tr("prefs.browser_body_features"),
|
||||
app.tr("prefs.browser_body_features_note"),
|
||||
&mut app.preferences.browser_body_features,
|
||||
"browser_body_features",
|
||||
);
|
||||
});
|
||||
// A folder's icon from its features (#12514), in a row of its own: one more box in the
|
||||
// row above widens it past the page at narrow windows.
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = egui::vec2(t.space_16, t.space_6);
|
||||
layout_check(
|
||||
ui,
|
||||
app.tr("prefs.history_folder_kind_icon"),
|
||||
app.tr("prefs.history_folder_kind_icon_note"),
|
||||
&mut app.preferences.history_folder_kind_icon,
|
||||
"history_folder_kind_icon",
|
||||
);
|
||||
});
|
||||
});
|
||||
ui_kit::settings_section(ui, "dialogs", app.tr("prefs.dialogs"), |ui| {
|
||||
|
||||
@@ -212,36 +212,6 @@ pub(crate) fn icon_of(k: &FeatureKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon a History folder takes from its features when Preferences says so: theirs, when every
|
||||
/// feature in it (and in the folders inside it) has the same icon and it holds no joints.
|
||||
pub(crate) fn folder_kind_icon(app: &SolveApp, id: u64) -> Option<&'static str> {
|
||||
if !app.preferences.history_folder_kind_icon {
|
||||
return None;
|
||||
}
|
||||
let doc = &app.session.doc;
|
||||
let mut pending = vec![id];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut icon = None;
|
||||
while let Some(id) = pending.pop() {
|
||||
if !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let group = doc.timeline_groups.iter().find(|group| group.id == id)?;
|
||||
if !group.joints.is_empty() {
|
||||
return None;
|
||||
}
|
||||
for feature in &group.features {
|
||||
let this = icon_of(&doc.feature(*feature)?.kind);
|
||||
if icon.is_some_and(|icon| icon != this) {
|
||||
return None;
|
||||
}
|
||||
icon = Some(this);
|
||||
}
|
||||
pending.extend(doc.timeline_groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id));
|
||||
}
|
||||
icon
|
||||
}
|
||||
|
||||
fn construction_plane_icon(plane: &PlaneRef) -> &'static str {
|
||||
match plane {
|
||||
PlaneRef::AtAngle { .. } => "plane_angle",
|
||||
@@ -1292,38 +1262,6 @@ mod tests {
|
||||
|
||||
use crate::scenario::Harness;
|
||||
|
||||
#[test]
|
||||
fn a_folder_of_one_kind_of_feature_takes_its_icon_when_preferences_say_so() {
|
||||
let mut h = Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20, "name": "Block"})).unwrap();
|
||||
for x in [8, 16, 24, 32] {
|
||||
h.app.run("solid.hole", json!({"position": [x, 10, 20], "diameter": 4, "name": format!("H{x}")})).unwrap();
|
||||
}
|
||||
let group = |h: &mut Harness, p: serde_json::Value| h.app.run("timeline.group", p).unwrap()["group"].as_u64().unwrap();
|
||||
let inner = group(&mut h, json!({"name": "Inner", "features": ["H8", "H16"]}));
|
||||
// Holes, and a folder of holes inside: all one kind.
|
||||
let holes = group(&mut h, json!({"name": "Holes", "features": ["H24"], "groups": [inner]}));
|
||||
let mixed = group(&mut h, json!({"name": "Mixed", "features": ["Block"]}));
|
||||
let hole = super::icon_of(&h.app.session.doc.find_feature("H8").unwrap().kind);
|
||||
// Off (the default): every folder keeps the folder icon.
|
||||
assert!(!h.app.preferences.history_folder_kind_icon);
|
||||
assert_eq!(super::folder_kind_icon(&h.app, holes), None);
|
||||
crate::prefs::set(&mut h.app, &json!({"history_folder_kind_icon": true})).unwrap();
|
||||
assert_eq!(super::folder_kind_icon(&h.app, holes), Some(hole));
|
||||
assert_eq!(super::folder_kind_icon(&h.app, inner), Some(hole));
|
||||
assert_eq!(super::folder_kind_icon(&h.app, mixed), Some(super::icon_of(&h.app.session.doc.find_feature("Block").unwrap().kind)));
|
||||
// A box among the holes: back to the folder icon.
|
||||
h.app.run("timeline.group", json!({"name": "Both", "groups": [holes, mixed]})).unwrap();
|
||||
let both = h.app.session.doc.timeline_groups.iter().find(|g| g.name == "Both").unwrap().id;
|
||||
assert_eq!(super::folder_kind_icon(&h.app, both), None);
|
||||
// Both Histories draw it without trouble.
|
||||
for left in [false, true] {
|
||||
h.app.preferences.timeline_left = left;
|
||||
h.frames(3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joint_folder_hides_fifty_joint_tiles_in_both_history_layouts() {
|
||||
use crate::scenario::handle_at;
|
||||
|
||||
@@ -250,9 +250,8 @@ pub(crate) fn folder_chip(
|
||||
let state = history.inside(folder.start, folder.end, folder.open);
|
||||
let picked = app.tree.picked_timeline_groups.contains(&folder.id)
|
||||
|| (!folder.open && history.folders.joints.get(&folder.id).is_some_and(|j| j.iter().any(|j| app.tree.picked_joints.contains(j))));
|
||||
let icon = crate::timeline::folder_kind_icon(app, folder.id).unwrap_or("feature_group");
|
||||
let chip = HistoryGroupChip {
|
||||
icon,
|
||||
icon: "feature_group",
|
||||
name: &name,
|
||||
count,
|
||||
open: folder.open,
|
||||
|
||||
@@ -1128,8 +1128,7 @@ fn vertical_group_row(
|
||||
painter.multiply_opacity(0.42);
|
||||
}
|
||||
let icon = Rect::from_center_size(pos2(rect.left() + 27.5 + offset, rect.center().y), vec2(17.0, 17.0));
|
||||
let kind = crate::timeline::folder_kind_icon(app, group.id).unwrap_or("feature_group");
|
||||
icons::paint_icon(&painter, icon, kind, f32::from(t.icon.a()) / 255.0);
|
||||
icons::paint_icon(&painter, icon, "feature_group", f32::from(t.icon.a()) / 255.0);
|
||||
if suppressed {
|
||||
painter.line_segment([icon.left_bottom(), icon.right_top()], Stroke::new(1.5, t.text_dim));
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ Source today: Interface page (`prefs/interface.rs`, `prefs/navbar.rs`).
|
||||
| Sketches in History | Segmented: In order / Under feature | `Prefs.history_sketches` (`HistorySketches`) | In order | none | none | |
|
||||
| Bodies folders | Segmented: Always / Several / Never | `Prefs.browser_bodies_folders` (`BodiesFolders`) | Several | none | none | |
|
||||
| Play History button | Checkbox | `Prefs.history_play_button` | `true` | none | none | |
|
||||
| Folder icon from its features | Checkbox | `Prefs.history_folder_kind_icon` | `false` | "A folder whose features are all of one kind shows their icon." | none | |
|
||||
| Origin and bodies on top | Checkbox | `Prefs.timeline_origin_bodies` | `false` | "Vertical history only." | none | |
|
||||
| Eye beside the fold arrow | Checkbox | `Prefs.browser_eye_left` | `false` | none | none | |
|
||||
|
||||
|
||||
@@ -589,7 +589,6 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm
|
||||
|
||||
| Command | Id | Toolbar |
|
||||
|---|---|---|
|
||||
| List Body Features | `model.body_features` | – |
|
||||
| List Edges | `model.edges` | – |
|
||||
| List Faces | `model.faces` | – |
|
||||
| List Threads | `model.threads` | – |
|
||||
|
||||
@@ -75,19 +75,6 @@ staple() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# validate <path>: stapler validate looks the ticket up at Apple and can lose the connection
|
||||
# ("The network connection was lost", error 68), so try it a few times as staple does.
|
||||
validate() {
|
||||
local i
|
||||
for i in 1 2 3 4 5 6; do
|
||||
if xcrun stapler validate "$1"; then return 0; fi
|
||||
echo "stapler validate failed (attempt $i), retrying" >&2
|
||||
sleep "${STAPLE_RETRY_SLEEP:-20}"
|
||||
done
|
||||
echo "could not validate the staple of $1" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
ARCH=universal
|
||||
SKIP_BUILD=0
|
||||
BUILD_ONLY=
|
||||
@@ -202,7 +189,7 @@ if [ "$NOTARIZE" = 1 ]; then
|
||||
ditto -c -k --keepParent "$APP" "$WORK/SolidCraft-app.zip"
|
||||
notarize "$WORK/SolidCraft-app.zip"
|
||||
staple "$APP"
|
||||
validate "$APP"
|
||||
xcrun stapler validate "$APP"
|
||||
fi
|
||||
|
||||
# ---- DMG ---------------------------------------------------------------------------------------
|
||||
@@ -255,7 +242,7 @@ if [ "$NOTARIZE" = 1 ]; then
|
||||
echo "==> notarizing $DMG"
|
||||
notarize "$DMG"
|
||||
staple "$DMG"
|
||||
validate "$DMG"
|
||||
xcrun stapler validate "$DMG"
|
||||
# Gatekeeper's verdict on the DMG and on the app as a user gets it.
|
||||
spctl -a -t open --context context:primary-signature -vv "$DMG"
|
||||
MNT="$(mktemp -d)"
|
||||
|
||||
@@ -107,7 +107,6 @@ material.inspect materials and their properties
|
||||
material.list materials and their properties
|
||||
material.properties.directional materials and their properties
|
||||
material.properties.validate materials and their properties
|
||||
model.body_features a listing of the model's timeline per body; crates/engine/src/schema/inspect_tests.rs
|
||||
model.edges a listing of the model's topology
|
||||
model.faces a listing of the model's topology
|
||||
model.threads a listing of the model's topology
|
||||
|
||||
Reference in New Issue
Block a user