1use crate::edit_spec::{BlockFace, BlockRef, EditOp, Ref};
5use crate::{Block, FaceId, FaceMods, NodePath, NodeStep, Project, SurfaceEdit, SurfaceOp};
6use lensbench_core::System;
7use serde_json::{Map, Value};
8
9#[derive(Clone, Copy)]
11pub struct Edited<'a> {
12 pub system: &'a System,
13 pub faces: &'a [Option<FaceId>],
14 pub before: &'a System,
17}
18
19fn node_mut<'p>(blocks: &'p mut [Block], path: &NodePath) -> Option<&'p mut Block> {
21 let (first, rest) = path.0.split_first()?;
22 let b = match *first {
23 NodeStep::Block(i) => blocks.get_mut(i)?,
24 NodeStep::Arm(..) => return None,
25 };
26 let mut cur = b;
27 for st in rest {
28 cur = match (cur, *st) {
29 (Block::Group { blocks, .. }, NodeStep::Block(i)) => blocks.get_mut(i)?,
30 (Block::Splitter { spec, .. }, NodeStep::Arm(a, i)) => match a {
31 0 => spec.t.get_mut(i)?,
32 1 => spec.r.get_mut(i)?,
33 2 => spec.d.get_mut(i)?,
34 _ => return None,
35 },
36 _ => return None,
37 };
38 }
39 Some(cur)
40}
41
42fn node<'p>(blocks: &'p [Block], path: &NodePath) -> Option<&'p Block> {
43 let (first, rest) = path.0.split_first()?;
44 let mut cur = match *first {
45 NodeStep::Block(i) => blocks.get(i)?,
46 NodeStep::Arm(..) => return None,
47 };
48 for st in rest {
49 cur = match (cur, *st) {
50 (Block::Group { blocks, .. }, NodeStep::Block(i)) => blocks.get(i)?,
51 (Block::Splitter { spec, .. }, NodeStep::Arm(a, i)) => match a {
52 0 => spec.t.get(i)?,
53 1 => spec.r.get(i)?,
54 2 => spec.d.get(i)?,
55 _ => return None,
56 },
57 _ => return None,
58 };
59 }
60 Some(cur)
61}
62
63fn face_of(x: Edited, r: &Ref) -> Result<(FaceId, usize), String> {
68 let j = match r {
69 Ref::Index(j) => *j,
70 Ref::Name(n) => x.system.find_surface(n).map_err(|e| e.to_string())?,
71 };
72 let f = x
73 .faces
74 .get(j)
75 .cloned()
76 .flatten()
77 .ok_or_else(|| format!("surface {j} is not a surface of a block"))?;
78 if f.cb {
79 return Err(format!(
80 "surface {j} is a coordinate break of a block (use the block decenter and tilt)"
81 ));
82 }
83 if f.back {
84 let m = x
86 .faces
87 .iter()
88 .flatten()
89 .filter(|g| g.node == f.node && !g.cb && g.back && g.pass == f.pass)
90 .count();
91 let i = m.checked_sub(f.index + 1).ok_or_else(|| {
92 format!("surface {j} on the return pass has no surface on the forward pass")
93 })?;
94 return Ok((f, i));
95 }
96 let i = f.index;
97 Ok((f, i))
98}
99
100fn gap_field(k: &str) -> bool {
102 matches!(k, "t" | "material" | "dn" | "disp")
103}
104
105fn block_id_of<'p>(p: &'p Project, f: &FaceId, r: &Ref) -> Result<&'p str, String> {
107 let id = node(&p.blocks, &f.node).map(crate::block_id).unwrap_or("");
108 if id.is_empty() {
109 return Err(format!(
110 "surface {} is in a block without an id (give the block an id to refer to it)",
111 match r {
112 Ref::Index(j) => j.to_string(),
113 Ref::Name(n) => n.clone(),
114 }
115 ));
116 }
117 Ok(id)
118}
119
120fn round_trip(x: Edited, f: &FaceId) -> bool {
122 x.faces.iter().flatten().any(|g| g.node == f.node && g.back)
123}
124
125fn other_ref(p: &Project, x: Edited, r: &Ref) -> Result<BlockRef, String> {
127 let (f, i) = face_of(x, r)?;
128 let id = block_id_of(p, &f, r)?;
129 Ok(BlockRef::Block(BlockFace {
130 block: id.to_string(),
131 surface: i,
132 coordbrk: false,
133 back: f.back,
134 pass: f.pass,
135 }))
136}
137
138fn faces<'p>(p: &'p mut Project, n: &NodePath) -> Result<&'p mut FaceMods, String> {
140 node_mut(&mut p.blocks, n)
141 .ok_or("the block is not in the project")?
142 .faces_mut()
143 .ok_or_else(|| "this kind of block can't hold surface edits".into())
144}
145
146enum Mod {
149 Edit(SurfaceEdit),
150 Op(SurfaceOp, bool),
151}
152
153fn sys_index(x: Edited, r: &Ref) -> Option<usize> {
155 match r {
156 Ref::Index(j) => Some(*j),
157 Ref::Name(n) => x.system.find_surface(n).ok(),
158 }
159}
160
161fn put_edit(edits: &mut Vec<SurfaceEdit>, e: SurfaceEdit) {
163 for q in edits
164 .iter_mut()
165 .filter(|q| q.surface == e.surface && q.coordbrk == e.coordbrk)
166 {
167 q.fields.retain(|k, _| !e.fields.contains_key(k));
168 }
169 edits.retain(|q| !q.fields.is_empty());
170 edits.push(e);
171}
172
173fn put_op(ops: &mut Vec<SurfaceOp>, o: SurfaceOp, shown: bool) {
176 use crate::surface_ops as so;
177 match o {
178 SurfaceOp::AddSolve(o) => so::put_solve(ops, o, shown),
179 SurfaceOp::AddPickup(o) => so::put_pickup(ops, o, shown),
180 SurfaceOp::RemoveSolve {
181 surface: at @ (BlockRef::Sys(Ref::Index(_)) | BlockRef::Block(_)),
182 what,
183 } => so::drop_solve_at(ops, at, what),
184 SurfaceOp::RemovePickup {
185 dst: at @ (BlockRef::Sys(Ref::Index(_)) | BlockRef::Block(_)),
186 what,
187 } => so::drop_pickup_at(ops, at, what),
188 o => ops.push(o),
189 }
190}
191
192fn to_mod(p: &Project, x: Edited, op: &EditOp) -> Result<Vec<(NodePath, Mod)>, String> {
194 use EditOp as E;
195 let one = |f: &FaceId,
199 i: usize,
200 fields: Map<String, Value>|
201 -> Result<(NodePath, Mod), String> {
202 let last = !x
203 .faces
204 .iter()
205 .flatten()
206 .any(|g| g.node == f.node && !g.cb && !g.back && g.pass == 0 && g.index > i);
207 if last && fields.contains_key("t") {
208 return Err(
209 "the thickness after the last surface of a block includes the following air (change the air block)"
210 .into(),
211 );
212 }
213 if last && round_trip(x, f) && fields.keys().any(|k| gap_field(k)) {
214 return Err(
215 "the medium after the last surface of a round-trip block is the following air (change the air block)"
216 .into(),
217 );
218 }
219 Ok((
220 f.node.clone(),
221 Mod::Edit(SurfaceEdit {
222 surface: i,
223 coordbrk: false,
224 fields,
225 }),
226 ))
227 };
228 let edit = |r: &Ref, fields: Map<String, Value>| -> Result<Vec<(NodePath, Mod)>, String> {
229 let (f, i) = face_of(x, r)?;
230 if !f.back {
232 return Ok(vec![one(&f, i, fields)?]);
233 }
234 let (gap, own): (Map<String, Value>, Map<String, Value>) =
237 fields.into_iter().partition(|(k, _)| gap_field(k));
238 let mut out = Vec::new();
239 if !own.is_empty() {
240 out.push(one(&f, i, own)?);
241 }
242 if !gap.is_empty() {
243 let Some(prev) = i.checked_sub(1) else {
244 return Err(
245 "the medium and the spacing after this surface on the return pass are those before the block (change the block or air in front)"
246 .into(),
247 );
248 };
249 let mut g = Map::new();
250 for (k, v) in gap {
251 let v = if k == "t" {
252 let t = v
253 .as_f64()
254 .ok_or("the thickness on the return pass must be a number")?;
255 Value::from(-t)
256 } else {
257 v
258 };
259 g.insert(k, v);
260 }
261 out.push(one(&f, prev, g)?);
262 }
263 Ok(out)
264 };
265 let at = |r: &Ref, any: bool| -> Result<(NodePath, BlockRef), String> {
268 let (f, i) = face_of(x, r)?;
269 if f.back || f.pass > 0 {
270 if !any {
271 let j = match r {
272 Ref::Index(j) => j.to_string(),
273 Ref::Name(n) => n.clone(),
274 };
275 return Err(format!(
276 "surface {j} is on a later pass of a block (choose the surface on its first forward pass)"
277 ));
278 }
279 let id = block_id_of(p, &f, r)?.to_string();
280 let b = BlockFace {
281 block: id,
282 surface: i,
283 coordbrk: false,
284 back: f.back,
285 pass: f.pass,
286 };
287 return Ok((f.node, BlockRef::Block(b)));
288 }
289 Ok((f.node, BlockRef::Sys(Ref::Index(i))))
290 };
291 let own = |r: &Ref| at(r, false);
292 let any = |r: &Ref| at(r, true);
293 Ok(vec![match op {
294 E::SetSurface { surface, fields } => return edit(surface, fields.clone()),
295 E::SetSurfaceData { surface, data } => return edit(surface, data.clone()),
296 E::SetMaterial { surface, material } => {
297 let mut m = Map::new();
298 m.insert("material".into(), Value::String(material.clone()));
299 return edit(surface, m);
300 }
301 E::SetStop(o) => {
302 let (n, r) = own(&o.surface)?;
303 (
304 n,
305 Mod::Op(
306 SurfaceOp::SetStop(crate::edit_spec::StopOp { surface: r }),
307 false,
308 ),
309 )
310 }
311 E::AddSolve(o) => {
312 let (n, r) = any(&o.surface)?;
313 let other = o.other.as_ref().map(|q| other_ref(p, x, q)).transpose()?;
314 let j = sys_index(x, &o.surface);
315 let shown = x
316 .before
317 .solves
318 .iter()
319 .any(|q| Some(q.surf) == j && q.kind.is_curv() == o.is_curv());
320 (
321 n,
322 Mod::Op(
323 SurfaceOp::AddSolve(crate::edit_spec::SolveOp {
324 surface: r,
325 kind: o.kind.clone(),
326 value: o.value,
327 other,
328 param: o.param,
329 macro_ref: o.macro_ref.clone(),
330 }),
331 shown,
332 ),
333 )
334 }
335 E::AddPickup(o) => {
336 let (n, r) = any(&o.dst)?;
337 let src = other_ref(p, x, &o.src)?;
338 let j = sys_index(x, &o.dst);
339 let w = lensbench_core::pickup::pick_kind_parse(&o.what).ok();
340 let shown = x
341 .before
342 .pickups
343 .iter()
344 .any(|q| Some(q.dst) == j && Some(q.what) == w);
345 (
346 n,
347 Mod::Op(
348 SurfaceOp::AddPickup(crate::edit_spec::PickupOp {
349 dst: r,
350 src,
351 what: o.what.clone(),
352 scale: o.scale,
353 offset: o.offset,
354 from: o.from.clone(),
355 }),
356 shown,
357 ),
358 )
359 }
360 E::RemoveSolve { surface, what } => {
361 let (n, r) = any(surface)?;
362 (
363 n,
364 Mod::Op(
365 SurfaceOp::RemoveSolve {
366 surface: r,
367 what: *what,
368 },
369 false,
370 ),
371 )
372 }
373 E::RemovePickup { dst, what } => {
374 let (n, r) = any(dst)?;
375 (
376 n,
377 Mod::Op(
378 SurfaceOp::RemovePickup {
379 dst: r,
380 what: what.clone(),
381 },
382 false,
383 ),
384 )
385 }
386 E::SetParam { param, .. } => {
387 return Err(format!(
388 "parameter {param} can't be written back to blocks (only surface parameters)"
389 ))
390 }
391 _ => return Err("only surface edits can be written back to blocks".into()),
392 }])
393}
394
395pub fn face_mods(p: &Project) -> Vec<(&str, &FaceMods)> {
398 fn walk<'p>(bs: &'p [Block], out: &mut Vec<(&'p str, &'p FaceMods)>) {
399 for b in bs {
400 let id = crate::block_id(b);
401 if let (false, Some(f)) = (id.is_empty(), b.faces()) {
402 out.push((id, f));
403 }
404 match b {
405 Block::Group { blocks, .. } => walk(blocks, out),
406 Block::Splitter { spec, .. } => {
407 for arm in [&spec.t, &spec.r, &spec.d] {
408 walk(arm, out);
409 }
410 }
411 _ => {}
412 }
413 }
414 }
415 let mut out = Vec::new();
416 walk(&p.blocks, &mut out);
417 out
418}
419
420fn param_op(run: &mut Option<System>, x: Edited, op: &EditOp) -> Result<Option<EditOp>, String> {
425 let cur = run.get_or_insert_with(|| x.before.clone());
426 let EditOp::SetParam { param, value } = op else {
427 let mut next = cur.clone();
429 if crate::edit_ops::apply(&mut next, std::slice::from_ref(op)).is_ok() {
430 *cur = next;
431 }
432 return Ok(Some(op.clone()));
433 };
434 let no =
435 || format!("parameter {param} can't be written back to blocks (only surface parameters)");
436 let (s, k) = param.trim().rsplit_once('.').ok_or_else(no)?;
437 let s = s.strip_prefix("surf:").unwrap_or(s);
438 let j: usize = s.trim().parse().map_err(|_| no())?;
439 use lensbench_core::param::{Kind, Param};
440 let kind = Kind::parse(k).map_err(|e| e.to_string())?;
441 let key = match kind {
442 Kind::Curv => Some("c"),
443 Kind::Radius => Some("r"),
444 Kind::Conic => Some("k"),
445 Kind::Thick => Some("t"),
446 _ => None,
447 };
448 if cur.get_param(Param::new(j, kind)).ok() == Some(value.0) {
450 return Ok(None);
451 }
452 let mut fields = Map::new();
453 let next = cur
454 .with_params(&[(Param::new(j, kind), value.0)])
455 .map_err(|e| e.to_string())?;
456 if let Some(key) = key {
457 fields.insert(key.into(), Value::from(value.0));
458 *cur = next;
459 return Ok(Some(EditOp::SetSurface {
460 surface: Ref::Index(j),
461 fields,
462 }));
463 }
464 let a = crate::edit_ops::surface_data(cur, j).map_err(|e| e.to_string())?;
465 let b = crate::edit_ops::surface_data(&next, j).map_err(|e| e.to_string())?;
466 for (k, v) in b["data"].as_object().into_iter().flatten() {
467 if !matches!(k.as_str(), "semi" | "semi_auto") && a["data"].get(k) != Some(v) {
468 fields.insert(k.clone(), v.clone());
469 }
470 }
471 *cur = next;
472 if fields.is_empty() {
473 return Err(no());
474 }
475 Ok(Some(EditOp::SetSurfaceData {
476 surface: Ref::Index(j),
477 data: fields,
478 }))
479}
480
481pub fn write_back(
488 p: &mut Project,
489 x: Edited,
490 ops: &[EditOp],
491 check: &dyn Fn(&Project) -> Result<(), String>,
492) -> Vec<String> {
493 let mut notes = Vec::new();
494 let mut run = None;
495 for (k, op) in ops.iter().enumerate() {
496 if matches!(
497 op,
498 EditOp::InsertSurface { .. } | EditOp::DeleteSurface { .. }
499 ) {
500 notes.push(format!(
501 "edit {}: {} and the later edits are not written back (surfaces of blocks can't be inserted or deleted here)",
502 k + 1,
503 op.name()
504 ));
505 break;
506 }
507 let op2 = match param_op(&mut run, x, op) {
508 Ok(Some(o)) => o,
509 Ok(None) => continue,
510 Err(e) => {
511 notes.push(format!(
512 "edit {}: {} is not written back ({e})",
513 k + 1,
514 op.name()
515 ));
516 continue;
517 }
518 };
519 let r = to_mod(p, x, &op2).and_then(|mods| {
520 let mut rt = (false, false);
522 let mut saved: Vec<(NodePath, FaceMods)> = Vec::new();
523 for (n, m) in mods {
524 if matches!(m, Mod::Edit(_)) {
525 let g = x.faces.iter().flatten().filter(|g| g.node == n);
526 rt.0 |= g.clone().any(|g| g.back);
527 rt.1 |= g.clone().any(|g| !g.back && g.pass > 0);
528 }
529 let f = faces(p, &n)?;
530 if !saved.iter().any(|(s, _)| *s == n) {
531 saved.push((n.clone(), f.clone()));
532 }
533 match m {
534 Mod::Edit(e) => put_edit(&mut f.surface_edits, e),
535 Mod::Op(o, shown) => put_op(&mut f.surface_ops, o, shown),
536 }
537 }
538 if let Err(e) = check(p) {
539 for (n, before) in saved.into_iter().rev() {
540 *faces(p, &n)? = before;
541 }
542 return Err(format!("the project would not expand: {e}"));
543 }
544 Ok(rt)
545 });
546 match r {
547 Ok((true, _)) => notes.push(format!(
548 "edit {}: {} also changes the return path of the round-trip block",
549 k + 1,
550 op.name()
551 )),
552 Ok((false, true)) => notes.push(format!(
553 "edit {}: {} also changes the other passes through the block",
554 k + 1,
555 op.name()
556 )),
557 Ok((false, false)) => {}
558 Err(e) => notes.push(format!(
559 "edit {}: {} is not written back ({e})",
560 k + 1,
561 op.name()
562 )),
563 }
564 }
565 notes
566}