1use super::*;
4use crate::action::Action;
5use crate::shape::Shape;
6
7impl System {
8 pub fn ptrace(&self, y1: f64, u0: f64, w: usize, upto: Option<usize>) -> (Vec<f64>, Vec<f64>) {
10 self.ptrace_from(1, y1, u0, w, upto)
11 }
12
13 pub fn ptrace_from(
17 &self,
18 from: usize,
19 y1: f64,
20 u0: f64,
21 w: usize,
22 upto: Option<usize>,
23 ) -> (Vec<f64>, Vec<f64>) {
24 let sf = &self.surfaces;
25 let from = from.max(1);
26 let upto = upto.unwrap_or(sf.len() - 1);
27 let mut y = vec![f64::NAN; sf.len()];
28 let mut u = vec![f64::NAN; sf.len()];
29 let (mut uu, mut yy) = (u0, y1);
30 let (mut n, mut sgn) = if from == 1 {
31 y[0] = yy - uu * if sf[0].t.is_finite() { sf[0].t } else { 0.0 };
32 u[0] = uu;
33 (self.n(0)[w], 1.0)
34 } else {
35 let mirrors = sf[1..from]
36 .iter()
37 .filter(|d| !d.ignore && d.is_mirror())
38 .count();
39 let sgn = if mirrors % 2 == 1 { -1.0 } else { 1.0 };
40 (self.index_before(from, w), sgn)
41 };
42 let mut gmed: Option<(&crate::grin::Grin, f64)> = None;
43 for j in from..=upto {
44 let d = &sf[j];
45 if d.ignore {
46 y[j] = yy;
49 u[j] = uu;
50 continue;
51 }
52 y[j] = yy;
53 let action = d.action();
54 match action {
55 _ if d.is_coord_break() => {}
56 Action::Paraxial { f, .. } => uu -= yy / f,
57 Action::User(u) => {
58 if let Some(u) = u {
59 uu -= yy * u.instance().paraxial_power();
60 }
61 }
62 Action::Jones(_) => n = self.n(j)[w],
63 Action::Refract
64 | Action::Reflect { .. }
65 | Action::Binary2(_)
66 | Action::Fresnel(_)
67 | Action::Birefringent(_) => {
68 let bend = match action {
71 Action::Fresnel(b) => b.paraxial_curv(),
72 _ => None,
73 };
74 let c = sgn * bend.unwrap_or_else(|| d.shape().paraxial_curv());
75 let dphi = match action {
77 Action::Binary2(Some(b)) => {
78 let a = b.coef.first().copied().unwrap_or(0.0);
79 self.wave(w).mm() / (2.0 * std::f64::consts::PI) * b.order * 2.0 * a
80 / (b.norm * b.norm)
81 * yy
82 }
83 _ => match d.user_shape().filter(|u| u.has_phase()) {
85 Some(u) => {
86 let h = crate::usershape::paraxial_step(d.semi);
87 self.wave(w).mm() / (2.0 * std::f64::consts::PI)
88 * u.paraxial_dphi(h)
89 * yy
90 }
91 None => 0.0,
92 },
93 };
94 if d.is_mirror() {
95 uu += 2.0 * c * yy - sgn * dphi / n;
96 sgn = -sgn;
97 } else {
98 let n2 = d
100 .grin()
101 .and_then(|g| g.vertex_index(self.wavelengths[w]))
102 .unwrap_or(self.n(j)[w]);
103 uu = (n * uu - yy * c * (n2 - n) + sgn * dphi) / n2;
104 n = n2;
105 }
106 }
107 }
108 u[j] = uu;
109 gmed = match d.grin().filter(|_| !d.is_mirror()) {
111 Some(g) => Some((g, 0.0)),
112 None if d.is_coord_break() => gmed,
113 None => None,
114 };
115 if j < upto {
116 match gmed {
117 Some((g, z0)) => {
119 match g.paraxial(self.wavelengths[w], yy, uu, z0, d.t, sgn) {
120 Some((y2, u2, n2)) => {
121 yy = y2;
122 uu = u2;
123 n = n2;
124 }
125 None => {
126 yy = f64::NAN;
127 uu = f64::NAN;
128 }
129 }
130 gmed = Some((g, z0 + d.t));
131 }
132 None => yy += sgn * d.t * uu,
133 }
134 }
135 }
136 (y, u)
137 }
138
139 pub(super) fn stop_lin(&self) -> (f64, f64) {
140 let s = self.stop();
141 let a = self.ptrace(1.0, 0.0, self.primary, Some(s)).0[s];
142 let b = self.ptrace(0.0, 1.0, self.primary, Some(s)).0[s];
143 (a, b)
144 }
145
146 pub fn paraxial(&self) -> &Paraxial {
148 self.cache.par.get_or_init(|| self.compute_paraxial())
149 }
150
151 pub(super) fn compute_paraxial(&self) -> Paraxial {
152 let sf = &self.surfaces;
153 let s = self.stop();
154 let t0 = sf[0].t;
155 let pw = self.primary;
156 let (a, b) = self.stop_lin();
157 let enpp = if self.telecentric || a.abs() < 1e-300 {
158 ENPP_MAX
159 } else {
160 let e = b / a;
161 if e.abs() >= ENPP_MAX {
162 ENPP_MAX
163 } else {
164 e
165 }
166 };
167 let img = self.image();
168 let (_, uk) = self.ptrace(1.0, 0.0, pw, None);
169 let n_i = self.image_index(pw);
170 let efl = if uk[img - 1] != 0.0 {
173 -1.0 / (n_i * uk[img - 1])
174 } else {
175 f64::INFINITY
176 };
177 let (kind, val) = self.aperture;
178 let mut u_obj: Option<f64> = None;
179 let epd = match kind {
180 ApertureKind::Epd => val,
181 ApertureKind::FNum => efl.abs() / val,
182 ApertureKind::Float => {
183 let semi = sf[s].semi;
184 if self.infinite() {
185 2.0 * semi / a.abs()
186 } else {
187 let u = semi / (b + a * t0).abs();
188 u_obj = Some(u);
189 2.0 * u * (enpp + t0).abs()
190 }
191 }
192 ApertureKind::Na | ApertureKind::Cone => {
193 let n0 = self.n(0)[pw];
194 let th = if kind == ApertureKind::Na {
195 (val / n0).asin()
196 } else {
197 val.to_radians()
198 };
199 let u = th.tan();
200 u_obj = Some(u);
201 2.0 * u * (enpp + t0).abs()
202 }
203 ApertureKind::Pwfn => {
204 if self.infinite() {
205 let (_, um) = self.ptrace(1.0, 0.0, pw, None);
206 2.0 * 1.0 / (2.0 * val * um[img - 1].abs() * n_i)
207 } else {
208 let (_, um) = self.ptrace(t0, 1.0, pw, None);
209 let u = 1.0 / (2.0 * val * um[img - 1].abs() * n_i);
210 u_obj = Some(u);
211 2.0 * u * (enpp + t0).abs()
212 }
213 }
214 };
215 let (ym, um) = if self.infinite() {
216 self.ptrace(epd / 2.0, 0.0, pw, None)
217 } else {
218 let u = *u_obj.get_or_insert(epd / 2.0 / (enpp + t0));
219 self.ptrace(u * t0, u, pw, None)
220 };
221 let (yc, uc) = if self.infinite() {
222 self.ptrace(-enpp, 1.0, pw, None)
223 } else if enpp >= ENPP_MAX {
224 self.ptrace(1.0, 0.0, pw, None)
225 } else {
226 let u0 = -1.0 / (enpp + t0);
227 self.ptrace(1.0 + u0 * t0, u0, pw, None)
228 };
229 let (yci, uci) = (yc[img], uc[img - 1]);
230 let (ymi, umi) = (ym[img], um[img - 1]);
231 let ycp = if umi != 0.0 {
233 yci - uci * ymi / umi
234 } else {
235 yci
236 };
237 let mut expp = if uci != 0.0 {
238 -yci / uci
239 } else {
240 f64::INFINITY
241 };
242 let nmir = sf[1..img]
243 .iter()
244 .filter(|d| d.is_mirror() && !d.ignore)
245 .count();
246 if nmir % 2 == 1 {
247 expp = -expp;
248 }
249 let expd = if expp.is_finite() {
250 2.0 * (ymi + umi * expp).abs()
251 } else {
252 f64::INFINITY
253 };
254 Paraxial {
255 enpp,
256 epd,
257 efl,
258 expp,
259 expd,
260 stop: s,
261 stop_radius: ym[s].abs(),
262 u_obj,
263 chief_image_per_unit: yci,
264 chief_parimage_per_unit: ycp,
265 wfno: if umi != 0.0 {
266 1.0 / (2.0 * n_i * umi.abs())
267 } else {
268 f64::INFINITY
269 },
270 isfn: efl.abs() / epd,
271 pmag: if !self.infinite() && umi != 0.0 {
272 self.n(0)[pw] * um[0] / (n_i * umi)
273 } else {
274 0.0
275 },
276 marginal: (ym, um),
277 chief: (yc, uc),
278 }
279 }
280
281 pub fn symmetric(&self) -> bool {
283 self.symmetric_opts(true)
284 }
285
286 pub(crate) fn symmetric_opts(&self, freeform: bool) -> bool {
289 for d in &self.surfaces {
290 if d.ignore {
291 continue;
292 }
293 if d.is_coord_break() && d.cb().iter().any(|&v| v != 0.0) {
294 return false;
295 }
296 if d.before.is_some() || matches!(d.after, After::Tilt(_)) {
297 return false;
298 }
299 if freeform && d.shape().is_freeform() {
302 return false;
303 }
304 if d.grin().is_some_and(|g| !g.symmetric()) {
306 return false;
307 }
308 }
309 !self.units.iter().any(|u| u.moved())
310 }
311
312 pub fn exit_pupil(&self) -> f64 {
315 *self.cache.expp.get_or_init(|| {
316 let mut e = self.paraxial().expp;
317 if !self.symmetric() {
318 let Some(r0) = self.trace_novig(0.0, 0.0, &[0.0], &[0.0]) else {
320 return f64::NAN;
321 };
322 let (p0, k0) = (r0.rays[0].xyz, r0.rays[0].lmn);
323 let free = self.surfaces.iter().any(|d| {
325 !d.ignore
326 && (d.shape().is_freeform() || d.grin().is_some_and(|g| !g.symmetric()))
327 });
328 let cross_z = |p1: V3, k1: V3| -> f64 {
329 if free {
330 p0[2] + k0[2] * cross_yz_t(p0, k0, p1, k1)
334 } else {
335 closest_on_line(p0, k0, p1, k1)[2]
337 }
338 };
339 if self.cusp_pupil() {
340 let yc = &self.paraxial().chief.0;
344 let (s, img) = (self.stop(), self.image());
345 let chief = |deg: f64| {
346 self.trace_spec(
347 ObjSpec::Dir(normalize([
348 0.0,
349 crate::quantity::Angle::from_deg(deg).tan(),
350 1.0,
351 ])),
352 &[0.0],
353 &[0.0],
354 self.primary,
355 TraceOpts::new().vig([0.0; 5]).record(),
356 )
357 };
358 let mut r1 = chief(CUSP_FIELD_DEG);
359 let flipped = r1
360 .rec
361 .iter()
362 .any(|q| q.surf > s && q.surf < img && q.xyz[0][1] * yc[q.surf] < 0.0);
363 if flipped {
364 r1 = chief(CUSP_FIELD_DEG / 100.0);
365 }
366 e = cross_z(r1.rays[0].xyz, r1.rays[0].lmn);
367 } else {
368 let mut z = [0.0; 2];
369 for (i, h) in [2e-4, 1e-4].iter().enumerate() {
370 let r1 = if self.on_axis_only() {
371 match self.object_spec_abs(0.0, *h * ON_AXIS_PUPIL_FIELD) {
376 Ok(spec) => self.trace_spec(
377 spec,
378 &[0.0],
379 &[0.0],
380 self.primary,
381 TraceOpts::new().vig([0.0; 5]),
382 ),
383 Err(_) => {
384 z[i] = f64::NAN;
385 continue;
386 }
387 }
388 } else {
389 match self.trace_novig(0.0, *h, &[0.0], &[0.0]) {
390 Some(t) => t,
391 None => {
392 z[i] = f64::NAN;
393 continue;
394 }
395 }
396 };
397 z[i] = cross_z(r1.rays[0].xyz, r1.rays[0].lmn);
398 }
399 e = (4.0 * z[1] - z[0]) / 3.0;
400 }
401 }
402 e
403 })
404 }
405
406 pub(crate) fn cusp_pupil(&self) -> bool {
412 self.infinite()
413 && self.field_type == FieldType::Angle
414 && self.surfaces.iter().any(|d| {
415 !d.ignore
416 && matches!(d.shape(), Shape::OddAsphere { b, .. } if b.first().is_some_and(|&b1| b1 != 0.0))
417 })
418 }
419
420 pub(super) fn trace_novig(&self, hx: f64, hy: f64, px: &[f64], py: &[f64]) -> Option<Trace> {
423 let spec = self.object_spec(hx, hy).ok()?;
424 let mut t = self.trace_spec(
425 spec,
426 px,
427 py,
428 self.primary,
429 TraceOpts::new().vig([0.0; 5]).hxy((hx, hy)),
430 );
431 t.hx_hy = (hx, hy);
432 Some(t)
433 }
434
435 pub fn exit_pupil_diameter(&self) -> f64 {
437 *self.cache.expd.get_or_init(|| {
438 let e = self.exit_pupil();
439 if e.is_nan() {
440 return f64::NAN;
441 }
442 if (self.aiming == Aiming::Off && self.symmetric()) || !e.is_finite() {
443 self.paraxial().expd
444 } else {
445 let cusp = self.cusp_pupil();
447 let dl = if cusp { 1e-3 } else { 1e-4 };
448 let Some(r) = self.trace_novig(0.0, 0.0, &[0.0, 0.0, 0.0], &[0.0, dl, -dl]) else {
449 return f64::NAN;
450 };
451 let p: Vec<V3> = r.rays.iter().map(|x| x.xyz).collect();
452 let k: Vec<V3> = r.rays.iter().map(|x| x.lmn).collect();
453 let c = k[0];
454 let cc = add(p[0], scale(c, (e - p[0][2]) / c[2]));
455 let q: Vec<V3> = (0..3)
456 .map(|i| add(p[i], scale(k[i], dot(sub(cc, p[i]), c) / dot(k[i], c))))
457 .collect();
458 if cusp {
459 2.0 * norm(sub(q[1], q[0])) / dl
460 } else {
461 norm(sub(q[1], q[2])) / dl
462 }
463 }
464 })
465 }
466
467 pub fn lens_conjugate(&self, j: usize) -> f64 {
469 self.cache.conj.get_or_init(|| {
470 let (ym, um) = &self.paraxial().marginal;
471 (0..self.surfaces.len())
472 .map(|j| {
473 let prev = (0..j)
474 .rev()
475 .find(|&i| !self.surfaces[i].ignore)
476 .unwrap_or(0);
477 let u_in = um[prev];
478 if u_in.abs() > 1e-15 * ym[j].abs().max(1.0) {
479 -ym[j] / u_in
480 } else {
481 f64::INFINITY
482 }
483 })
484 .collect()
485 })[j]
486 }
487
488 }