fuzzyworld

shadow-zone / files / src / shadowZone.ts

shadowZone.ts

2.3 KB · history · blame

1import type { EarthModel } from './earth';
2import { traceRay } from './rayTracer';
3import { R_EARTH } from './earth';
4
5export interface ShadowZoneResult {
6 start: number; // degrees
7 end: number; // degrees
8}
9
10export function findShadowZone(
11 model: EarthModel,
12 wave: 'P' | 'S',
13): ShadowZoneResult[] {
14 const N = 360;
15 const vSurf = model.vAt(R_EARTH - 0.1, wave);
16 if (vSurf === 0) return [];
17
18 const distances: number[] = [];
19
20 for (let i = 0; i < N; i++) {
21 const angleDeg = 1 + (i / (N - 1)) * 88;
22 const angleRad = (angleDeg * Math.PI) / 180;
23 const p = (R_EARTH * Math.sin(angleRad)) / vSurf;
24 const ray = traceRay(model, p, wave, angleDeg);
25 if (ray.epicentralDistance !== null && !ray.blocked) {
26 // Normalize to [0°, 180°]: a ray arriving at >180° has wrapped past the
27 // antipode; the receiver sits at 360°−dist on the near arc.
28 let d = ray.epicentralDistance % 360;
29 if (d > 180) d = 360 - d;
30 distances.push(d);
31 }
32 }
33
34 if (distances.length === 0) return [];
35
36 distances.sort((a, b) => a - b);
37
38 // S-waves are blocked by the liquid outer core and never arrive beyond ~105°.
39 // Without an endpoint, the gap-finder never sees the 105°→180° shadow zone.
40 if (wave === 'S') distances.push(180);
41
42 // Collect ALL gaps ≥ 3°.
43 const MIN_GAP = 3;
44 const zones: ShadowZoneResult[] = [];
45
46 for (let i = 1; i < distances.length; i++) {
47 const gap = distances[i] - distances[i - 1];
48 if (gap >= MIN_GAP) {
49 zones.push({ start: distances[i - 1], end: distances[i] });
50 }
51 }
52
53 // Merge zones whose inter-zone gap is ≤ MERGE_THRESH so that physically
54 // contiguous shadow regions (e.g. the many small gaps a water core creates)
55 // appear as one arc instead of many overlapping ones.
56 return mergeZones(zones, 5);
57}
58
59function mergeZones(zones: ShadowZoneResult[], threshDeg: number): ShadowZoneResult[] {
60 if (zones.length <= 1) return zones;
61 const sorted = [...zones].sort((a, b) => a.start - b.start);
62 const merged: ShadowZoneResult[] = [];
63 let cur = { ...sorted[0] };
64 for (let i = 1; i < sorted.length; i++) {
65 const next = sorted[i];
66 if (next.start - cur.end <= threshDeg) {
67 cur.end = Math.max(cur.end, next.end);
68 } else {
69 merged.push(cur);
70 cur = { ...next };
71 }
72 }
73 merged.push(cur);
74 return merged;
75}