brep_render/engine_state/
simulation_ops.rs1use super::EngineState;
15use brep_simulation::model::{Simulation, BLOCK_KEY};
16use serde_json::{Map, Value};
17
18#[derive(Debug, Clone, PartialEq, serde::Serialize)]
20#[serde(rename_all = "camelCase")]
21pub struct MotorMate {
22 pub id: String,
24 pub kind: String,
26 pub value: f64,
29 pub enabled: bool,
30}
31
32impl MotorMate {
33 pub fn rate_unit(&self) -> &'static str {
35 if self.kind == "angle" { "°/s" } else { "mm/s" }
36 }
37}
38
39impl EngineState {
40 pub fn simulation(&self) -> Result<Option<Simulation>, String> {
42 match self.history.document_block(BLOCK_KEY) {
43 None | Some(Value::Null) => Ok(None),
44 Some(block) => Simulation::from_value(block).map(Some),
45 }
46 }
47
48 pub fn simulation_available(&self) -> bool {
50 self.history_has_assembly()
51 }
52
53 pub fn simulation_edit<T>(
57 &mut self,
58 coalesce: Option<&str>,
59 edit: impl FnOnce(&mut Simulation) -> Result<T, String>,
60 ) -> Result<T, String> {
61 if !self.simulation_available() {
62 return Err("open an assembly: a study drives its mates".into());
63 }
64 let mut block = self.simulation()?.unwrap_or_default();
65 let out = edit(&mut block)?;
66 block.validate()?;
67 self.history.set_document_block(BLOCK_KEY, Some(block.to_value()), coalesce);
68 Ok(out)
69 }
70
71 pub fn simulation_motor_mates(&self) -> Vec<MotorMate> {
73 let constraints = self.history.document_block("assembly").and_then(|a| a.get("constraints")).and_then(Value::as_array);
74 constraints
75 .into_iter()
76 .flatten()
77 .filter_map(|entry| {
78 let kind = entry.get("type")?.as_str()?;
79 let key = match kind {
80 "distance" => "distance",
81 "angle" => "angle",
82 _ => return None,
83 };
84 let params = entry.get("inputParams")?;
85 Some(MotorMate {
86 id: params.get("id")?.as_str()?.to_string(),
87 kind: kind.to_string(),
88 value: params.get(key).and_then(Value::as_f64).unwrap_or(0.0),
89 enabled: entry.get("enabled").and_then(Value::as_bool).unwrap_or(true),
90 })
91 })
92 .collect()
93 }
94
95 pub fn simulation_add_study(&mut self, name: &str) -> Result<String, String> {
97 self.simulation_edit(None, |block| Ok(block.add_study(name)))
98 }
99
100 pub fn simulation_set_active(&mut self, study: &str) -> Result<(), String> {
102 self.simulation_edit(None, |block| {
103 block.study(study).ok_or_else(|| format!("no study '{study}'"))?;
104 block.active = Some(study.to_string());
105 Ok(())
106 })
107 }
108
109 pub fn simulation_add_motor(&mut self, study: Option<&str>, constraint: Option<&str>) -> Result<(String, String), String> {
114 let mates = self.simulation_motor_mates();
115 let mate = match constraint {
116 Some(id) => mates.iter().find(|m| m.id == id).ok_or_else(|| format!("'{id}' is not a distance or angle mate of this assembly"))?,
117 None => mates.first().ok_or("add a distance or angle mate first: a motor drives one")?,
118 };
119 let speed = if mate.kind == "angle" { 90.0 } else { 10.0 };
120 let constraint = mate.id.clone();
121 self.simulation_edit(None, |block| {
122 let study_id = match study {
123 Some(id) => id.to_string(),
124 None => match block.active_study() {
125 Some(active) => active.id.clone(),
126 None => block.add_study(""),
127 },
128 };
129 let id = block.next_id("MOT");
130 let target = block.study_mut(&study_id).ok_or_else(|| format!("no study '{study_id}'"))?;
131 let to = target.duration;
132 target.motors.push(brep_simulation::Motor { id: id.clone(), constraint, from: 0.0, to, drive: brep_simulation::Drive::Speed { speed } });
133 Ok((study_id, id))
134 })
135 }
136
137 pub fn simulation_constraint_ids(&self) -> Vec<String> {
141 self.history
142 .document_block("assembly")
143 .and_then(|a| a.get("constraints"))
144 .and_then(Value::as_array)
145 .map(|rows| rows.iter().filter_map(|row| row.get("inputParams")?.get("id")?.as_str().map(str::to_string)).collect())
146 .unwrap_or_default()
147 }
148
149 pub fn simulation_add_clip(&mut self, study: Option<&str>, kind: &str, target: Option<&str>) -> Result<(String, String), String> {
157 use brep_simulation::ClipBody;
158 let body = match kind {
159 "suppress" => {
160 let ids = self.simulation_constraint_ids();
161 let constraint = match target {
162 Some(id) if ids.iter().any(|c| c == id) => id.to_string(),
163 Some(id) => return Err(format!("'{id}' is not a constraint of this assembly")),
164 None => ids.first().cloned().ok_or("add a mate first: a suppress clip switches one off")?,
165 };
166 ClipBody::Suppress { constraint }
167 }
168 "camera" => {
169 let views: Vec<String> = self.pmi_state().views.iter().filter(|v| v.camera.is_some()).map(|v| v.id.clone()).collect();
170 let views = match target {
171 Some(id) if views.iter().any(|v| v == id) => vec![id.to_string()],
172 Some(id) => return Err(format!("'{id}' is not a PMI view with a camera")),
173 None if views.is_empty() => return Err("capture a PMI view first: a camera clip moves between views".into()),
174 None => views,
175 };
176 ClipBody::Camera { views }
177 }
178 "visibility" => {
179 let occurrences = match target {
180 Some(id) => vec![id.to_string()],
181 None => {
182 let selected = self.selected_occurrences();
183 if selected.is_empty() {
184 vec![self.component_ids().first().cloned().ok_or("add a component first: a visibility clip hides one")?]
185 } else {
186 selected
187 }
188 }
189 };
190 ClipBody::Visibility { occurrences }
191 }
192 "explode" => {
193 let views = self.exploded_views();
194 let view = match target {
195 Some(id) if views.iter().any(|v| v.id == id) => id.to_string(),
196 Some(id) => return Err(format!("'{id}' is not an exploded view")),
197 None => views.first().map(|v| v.id.clone()).ok_or("make an exploded view first (Assembly: Auto explode): an explode clip plays its steps")?,
198 };
199 ClipBody::Explode { view, collapse: false }
200 }
201 "transparency" => {
202 let occurrences = match target {
203 Some(id) => vec![id.to_string()],
204 None => {
205 let selected = self.selected_occurrences();
206 if selected.is_empty() {
207 vec![self.component_ids().first().cloned().ok_or("add a component first: a transparency clip fades one")?]
208 } else {
209 selected
210 }
211 }
212 };
213 ClipBody::Transparency { occurrences, opacity: [1.0, 0.3] }
214 }
215 "section" => {
216 let views: Vec<String> = self.pmi_state().views.iter().filter(|v| v.display.section.is_some()).map(|v| v.id.clone()).collect();
217 let view = match target {
218 Some(id) if views.iter().any(|v| v == id) => id.to_string(),
219 Some(id) => return Err(format!("'{id}' is not a PMI view with a section")),
220 None => views.first().cloned().ok_or("give a PMI view a section first: a section clip plays it")?,
221 };
222 ClipBody::Section { view, sweep: None }
223 }
224 other => return Err(format!("no clip kind '{other}': suppress, camera, visibility, transparency, section or explode")),
225 };
226 self.simulation_edit(None, |block| {
227 let study_id = match study {
228 Some(id) => id.to_string(),
229 None => match block.active_study() {
230 Some(active) => active.id.clone(),
231 None => block.add_study(""),
232 },
233 };
234 let id = block.next_id("CLIP");
235 let target = block.study_mut(&study_id).ok_or_else(|| format!("no study '{study_id}'"))?;
236 let to = target.duration;
237 target.clips.push(brep_simulation::Clip { id: id.clone(), from: 0.0, to, body });
238 Ok((study_id, id))
239 })
240 }
241
242 pub fn simulation_remove(&mut self, study: &str, item: Option<&str>) -> Result<(), String> {
244 self.simulation_edit(None, |block| {
245 match item {
246 None => {
247 let before = block.studies.len();
248 block.studies.retain(|s| s.id != study);
249 if block.studies.len() == before {
250 return Err(format!("no study '{study}'"));
251 }
252 if block.active.as_deref() == Some(study) {
253 block.active = block.studies.first().map(|s| s.id.clone());
254 }
255 }
256 Some(id) => {
257 let target = block.study_mut(study).ok_or_else(|| format!("no study '{study}'"))?;
258 let before = target.motors.len() + target.clips.len();
259 target.motors.retain(|m| m.id != id);
260 target.clips.retain(|c| c.id != id);
261 if target.motors.len() + target.clips.len() == before {
262 return Err(format!("study '{study}' has no motor or clip '{id}'"));
263 }
264 }
265 }
266 Ok(())
267 })
268 }
269
270 pub fn simulation_state_json(&self) -> Value {
273 let block = match self.simulation() {
274 Ok(block) => block.map(|b| b.to_value()).unwrap_or(Value::Null),
275 Err(error) => serde_json::json!({ "error": error }),
276 };
277 serde_json::json!({
278 "available": self.simulation_available(),
279 "block": block,
280 "mates": self.simulation_motor_mates(),
281 })
282 }
283
284 pub fn simulation_patch(&mut self, study: &str, item: Option<&str>, patch: &Value, coalesce: Option<&str>) -> Result<(), String> {
288 let patch = patch.as_object().ok_or("a patch is an object of fields")?.clone();
289 self.simulation_edit(coalesce, |block| {
290 let target = block.study_mut(study).ok_or_else(|| format!("no study '{study}'"))?;
291 match item {
292 None => {
293 if patch.contains_key("id") || patch.contains_key("motors") || patch.contains_key("clips") {
294 return Err("a study patch edits its own fields; motors and clips are edited one by one".into());
295 }
296 *target = merged(&*target, &patch)?;
297 }
298 Some(id) => {
299 if patch.contains_key("id") {
300 return Err("an id cannot be patched".into());
301 }
302 if let Some(motor) = target.motors.iter_mut().find(|m| m.id == id) {
303 *motor = merged(&*motor, &patch)?;
304 } else if let Some(clip) = target.clips.iter_mut().find(|c| c.id == id) {
305 *clip = merged(&*clip, &patch)?;
306 } else {
307 return Err(format!("study '{study}' has no motor or clip '{id}'"));
308 }
309 }
310 }
311 Ok(())
312 })
313 }
314}
315
316fn merged<T: serde::Serialize + serde::de::DeserializeOwned>(value: &T, patch: &Map<String, Value>) -> Result<T, String> {
318 let mut object = serde_json::to_value(value).map_err(|e| e.to_string())?;
319 let fields = object.as_object_mut().ok_or("not an object")?;
320 for (key, field) in patch {
321 if field.is_null() {
322 fields.remove(key);
323 } else {
324 fields.insert(key.clone(), field.clone());
325 }
326 }
327 serde_json::from_value(object).map_err(|e| format!("that edit does not make a valid study: {e}"))
328}