mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 00:32:21 +00:00
Show a flight's photo, route, model and cockpit view in its Context card
The card's hero tile now previews what was picked. A flight shows its photo when Contacts has one, its route on a small globe from origin to destination with the plane on it, its 3D model turning with callouts of what can be worked out about the flight (phase, flight level, Mach, squawk, signal age), and the view ahead from its cockpit with speed and altitude tapes. The model and the cockpit view take turns, the route hands over to the cockpit view after twenty seconds, and a switch picks one and holds it. Under reduced motion nothing swaps by itself. A satellite shows the ground beneath it and graphs its altitude and speed. Each preview draws in a small scene of its own and frees its graphics context as it closes, so flicking through cards never pushes out the globe's. Co-authored-by: Sameh Khamis <[email protected]>
This commit is contained in:
1 parent
8c1fd235c0
commit
c6bdd38b61
10 files changed
+2196
-14
No files matched your search
@@ -0,0 +1,30 @@
|
||||
// The card previews (the turning model, the route globe) each draw in a
|
||||
// small Cesium scene of their own, so each holds a WebGL context. A browser
|
||||
// keeps only a handful of those open, and when there are too many it drops
|
||||
// the oldest, which is the main globe's. A destroyed widget's context is
|
||||
// otherwise freed only when garbage is collected, so flicking through cards
|
||||
// can push the globe's context out. Losing a preview's context on purpose as
|
||||
// it closes frees it at once.
|
||||
|
||||
/**
|
||||
* Destroy a preview's Cesium widget and free its WebGL context.
|
||||
* @param {object|null} widget a Cesium CesiumWidget
|
||||
*/
|
||||
export function destroyPreviewWidget(widget) {
|
||||
if (!widget || widget.isDestroyed?.()) return;
|
||||
let gl = null;
|
||||
try {
|
||||
gl =
|
||||
widget.scene?.context?._gl ??
|
||||
widget.canvas?.getContext?.('webgl2') ??
|
||||
null;
|
||||
} catch {
|
||||
gl = null;
|
||||
}
|
||||
widget.destroy();
|
||||
try {
|
||||
gl?.getExtension?.('WEBGL_lose_context')?.loseContext();
|
||||
} catch {
|
||||
// Nothing more can be done; the context goes when it is collected.
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -248,7 +248,7 @@ watch(
|
||||
</div>
|
||||
</section>
|
||||
<div v-if="contextOpen" v-show="activeTab === 'view'" id="context-tab-view" role="tabpanel" aria-labelledby="context-tab-btn-view" :class="{ 'context-searching': contextSearchOpen && contextSearchText.trim() }">
|
||||
<EntityCard :with-contacts="contactsMatchCard">
|
||||
<EntityCard :with-contacts="contactsMatchCard" :aircraft-photo="contactsMatchCard ? awareness?.photo : null">
|
||||
<AwarenessPanel v-if="contactsMatchCard" compact />
|
||||
</EntityCard>
|
||||
<ViewContext v-if="!entityCard" />
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
<script setup>
|
||||
import { destroyPreviewWidget } from '../../previewWidget.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { CLASS_MODEL_REAL, CLASS_MODEL_URL } from '../../../data/aircraftClass.js';
|
||||
import PreviewHud from './PreviewHud.vue';
|
||||
import { t } from '../../../i18n/index.js';
|
||||
|
||||
// The selected aircraft's own model, turning slowly at the top of its card:
|
||||
// the same per-class mesh the globe draws (a Cessna for light aircraft, a
|
||||
// 787 for widebodies, the shared airliner otherwise). It renders in a small
|
||||
// Cesium scene of its own with no globe, sky or imagery, and is torn down
|
||||
// with the card. A satellite's card uses it too, with a NASA model in place
|
||||
// of the aircraft class's (`modelUrl`).
|
||||
//
|
||||
// Its look changes as it turns: a whole rotation as it is, then a short
|
||||
// wireframe scan (under a third of a turn, about six seconds), then round
|
||||
// again. The change each way is a reveal: a bright ring grows from the
|
||||
// craft's centre out to its edges, turning it to white wire inside it on the
|
||||
// way in and back to the model on the way out. In wire the body goes near-black with its own
|
||||
// colours faintly showing (solar panels stay blue).
|
||||
// One custom shader does it all, driven by a uniform, because a shader set on
|
||||
// a model after it is ready does nothing in this Cesium.
|
||||
//
|
||||
// While it turns, one callout at a time sits in the frame's top-left corner,
|
||||
// HUD-style, telling something worked out about the flight (phase, flight
|
||||
// level, Mach, what its squawk means, signal age). Each runs three states:
|
||||
// enter 0-2.3 s the label and value slide in;
|
||||
// hold 2.3-5.2 s a thin timer under the value fills;
|
||||
// exit 5.2-6.2 s the text fades; a short gap, then the next one.
|
||||
const props = defineProps({
|
||||
/** Aircraft class from the record (light, airliner, widebody...). */
|
||||
aircraftClass: { type: String, default: '' },
|
||||
/** A model to show instead of the class's own (a satellite's, say). */
|
||||
modelUrl: { type: String, default: '' },
|
||||
/** Degrees to turn that model about its east axis to lie level. */
|
||||
modelTilt: { type: Number, default: 0 },
|
||||
/** How far the camera stands, in bounding radii. */
|
||||
viewRange: { type: Number, default: 1.9 },
|
||||
/** The aircraft's heading, so the turntable starts facing its way. */
|
||||
heading: { type: Number, default: 0 },
|
||||
/** `[{label, value}]` figures to call out, in order. */
|
||||
callouts: { type: Array, default: () => [] },
|
||||
/** Whether the tile is the one showing; a hidden one stops drawing. */
|
||||
active: { type: Boolean, default: true },
|
||||
});
|
||||
const emit = defineEmits(['failed', 'cycle']);
|
||||
|
||||
const host = ref(null);
|
||||
const failed = ref(false);
|
||||
watch(failed, (now) => now && emit('failed'));
|
||||
// A hidden tile keeps drawing until its model has loaded, then rests on its
|
||||
// last frame; shown again, it draws once straight away so there is no gap.
|
||||
let ready = false;
|
||||
function syncLoop() {
|
||||
if (!widget || widget.isDestroyed()) return;
|
||||
const run = props.active || !ready;
|
||||
if (run && !widget.useDefaultRenderLoop) {
|
||||
widget.resize();
|
||||
widget.render();
|
||||
}
|
||||
widget.useDefaultRenderLoop = run;
|
||||
}
|
||||
watch(() => props.active, syncLoop);
|
||||
let widget = null;
|
||||
let model = null;
|
||||
let removeTick = null;
|
||||
|
||||
/** How long each look lasts, and each reveal between them, in turns. */
|
||||
const PLAIN_TURNS = 1;
|
||||
const SCAN_TURNS = 0.3;
|
||||
const REVEAL_TURNS = 0.07;
|
||||
/** How long (ms) the plain model holds after the reveal before a cycle ends. */
|
||||
const HOLD_MS = 700;
|
||||
const phase = ref('plain');
|
||||
|
||||
// Model space, normalised so the craft reaches about 1.7 from its centre.
|
||||
// u_reveal runs 0 to 2: from 0 to 1 the edge grows from the centre and
|
||||
// leaves wire inside it; at 1 it is all wire; from 1 to 2 it grows again and
|
||||
// leaves the model inside it. Outside that range the model draws as it is.
|
||||
const LOOK_SHADER = `
|
||||
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
if (u_reveal <= 0.0 || u_reveal >= 2.0) return;
|
||||
vec3 p = fsInput.attributes.positionMC / u_half;
|
||||
bool entering = u_reveal < 1.0;
|
||||
float r = length(p);
|
||||
float front = mix(0.0, 1.8, entering ? u_reveal : u_reveal - 1.0);
|
||||
float edge = 1.0 - smoothstep(0.0, 0.05, abs(r - front));
|
||||
vec3 white = vec3(0.9, 0.96, 1.0);
|
||||
bool wire = entering ? r < front : r > front;
|
||||
if (!wire) {
|
||||
material.emissive += white * edge * 1.4;
|
||||
return;
|
||||
}
|
||||
// A fine grid: many small cells, hairline lines.
|
||||
vec3 q = p * 18.0;
|
||||
vec3 g = abs(fract(q - 0.5) - 0.5) / max(fwidth(q), vec3(1e-4));
|
||||
float line = (1.0 - clamp(min(min(g.x, g.y), g.z) * 2.4, 0.0, 1.0)) * 0.7;
|
||||
vec3 base = material.diffuse;
|
||||
// Opaque: a near-black body with white lines on it and its own colour
|
||||
// faintly through, which reads as a wireframe against the dark card (a
|
||||
// translucent model does not blend onto this scene's transparent canvas).
|
||||
material.diffuse = base * 0.12 + vec3(0.015, 0.02, 0.03);
|
||||
material.specular = vec3(0.0);
|
||||
material.emissive = white * line + base * 0.35 + white * edge * 1.4;
|
||||
}`;
|
||||
let lookShader = null;
|
||||
|
||||
const classModelUrl = (cls) => CLASS_MODEL_REAL[cls]?.url || CLASS_MODEL_URL[cls] || '/models/airplane.glb';
|
||||
|
||||
// One callout's whole life: enter 2.3 s + hold 2.9 s + exit 1.0 s + 0.3 s gap.
|
||||
const CYCLE_MS = 6500;
|
||||
const CALLOUT_TIMING = { enter: 2300, leave: 1000 };
|
||||
const page = ref(0);
|
||||
let cycle = null;
|
||||
const shown = computed(() => {
|
||||
const list = props.callouts;
|
||||
if (!list.length) return null;
|
||||
const index = page.value % list.length;
|
||||
return { ...list[index], index, total: list.length };
|
||||
});
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
|
||||
async function show(cls) {
|
||||
if (!widget) return;
|
||||
ready = false;
|
||||
syncLoop();
|
||||
const scene = widget.scene;
|
||||
if (model) {
|
||||
scene.primitives.remove(model);
|
||||
model = null;
|
||||
}
|
||||
const origin = Cesium.Cartesian3.fromDegrees(0, 0, 0);
|
||||
lookShader = new Cesium.CustomShader({
|
||||
uniforms: {
|
||||
u_reveal: { type: Cesium.UniformType.FLOAT, value: 0 },
|
||||
u_half: { type: Cesium.UniformType.FLOAT, value: 20 },
|
||||
},
|
||||
fragmentShaderText: LOOK_SHADER,
|
||||
});
|
||||
try {
|
||||
model = await Cesium.Model.fromGltfAsync({
|
||||
url: props.modelUrl || classModelUrl(cls),
|
||||
customShader: lookShader,
|
||||
modelMatrix: Cesium.Matrix4.multiplyByMatrix3(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(origin),
|
||||
Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(props.modelTilt)),
|
||||
new Cesium.Matrix4(),
|
||||
),
|
||||
// A light rim so the mesh reads against the dark card.
|
||||
silhouetteColor: Cesium.Color.WHITE.withAlpha(0.3),
|
||||
silhouetteSize: 1,
|
||||
});
|
||||
} catch {
|
||||
failed.value = true;
|
||||
return;
|
||||
}
|
||||
if (!widget) return;
|
||||
scene.primitives.add(model);
|
||||
model.readyEvent.addEventListener(() => {
|
||||
if (!widget) return;
|
||||
const sphere = model.boundingSphere;
|
||||
// The craft reaches about 0.6 of its bounding radius from the centre.
|
||||
lookShader.setUniform('u_half', sphere.radius * 0.6);
|
||||
const start = Cesium.Math.toRadians(props.heading + 140);
|
||||
let heading = start;
|
||||
const began = performance.now();
|
||||
let cycleMs = 0;
|
||||
let lastFrame = began;
|
||||
let holdMs = null;
|
||||
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
|
||||
const range = sphere.radius * props.viewRange;
|
||||
const frame = () => {
|
||||
heading += 0.005;
|
||||
const turns = (heading - start) / (2 * Math.PI);
|
||||
// Where in the scan it is, and from that how far each reveal has gone.
|
||||
const into = (turns % (PLAIN_TURNS + SCAN_TURNS)) - PLAIN_TURNS;
|
||||
const ease = (x) => x * x * (3 - 2 * x);
|
||||
let reveal = 0;
|
||||
if (!still && into >= 0) {
|
||||
if (into < REVEAL_TURNS) reveal = ease(into / REVEAL_TURNS);
|
||||
else if (into > SCAN_TURNS - REVEAL_TURNS) reveal = 1 + ease((into - (SCAN_TURNS - REVEAL_TURNS)) / REVEAL_TURNS);
|
||||
else reveal = 1;
|
||||
}
|
||||
const next = reveal > 0 && reveal < 2 ? 'scan' : 'plain';
|
||||
// One look and its scan make a cycle; say when one ends, and how long
|
||||
// it took, so a card can give something else the same time.
|
||||
// Only time spent drawing counts: a hidden preview stops drawing.
|
||||
const now = performance.now();
|
||||
const drawn = now - lastFrame < 250 ? now - lastFrame : 0;
|
||||
cycleMs += drawn;
|
||||
lastFrame = now;
|
||||
// The cycle ends once the reveal back to the model has finished and the
|
||||
// plain model has held a moment, never mid-reveal.
|
||||
if (phase.value === 'scan' && next === 'plain') holdMs = 0;
|
||||
if (holdMs !== null && next === 'plain') {
|
||||
holdMs += drawn;
|
||||
if (holdMs >= HOLD_MS) {
|
||||
emit('cycle', cycleMs);
|
||||
cycleMs = 0;
|
||||
holdMs = null;
|
||||
}
|
||||
}
|
||||
if (next !== phase.value) phase.value = next;
|
||||
lookShader.setUniform('u_reveal', reveal);
|
||||
widget.camera.lookAt(sphere.center, new Cesium.HeadingPitchRange(heading, Cesium.Math.toRadians(-18), range));
|
||||
};
|
||||
frame();
|
||||
removeTick?.();
|
||||
removeTick = scene.preRender.addEventListener(frame);
|
||||
widget.render();
|
||||
ready = true;
|
||||
syncLoop();
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
try {
|
||||
widget = new Cesium.CesiumWidget(host.value, {
|
||||
globe: false,
|
||||
skyBox: false,
|
||||
skyAtmosphere: false,
|
||||
baseLayer: false,
|
||||
scene3DOnly: true,
|
||||
shadows: false,
|
||||
showRenderLoopErrors: false,
|
||||
contextOptions: { webgl: { alpha: true, antialias: true } },
|
||||
// The globe's own credits already show; this scene has none to add.
|
||||
creditContainer: document.createElement('div'),
|
||||
});
|
||||
const scene = widget.scene;
|
||||
scene.backgroundColor = Cesium.Color.TRANSPARENT;
|
||||
scene.light = new Cesium.DirectionalLight({
|
||||
direction: Cesium.Cartesian3.normalize(new Cesium.Cartesian3(-0.4, -0.6, -0.7), new Cesium.Cartesian3()),
|
||||
intensity: 2.4,
|
||||
});
|
||||
scene.screenSpaceCameraController.enableInputs = false;
|
||||
void show(props.aircraftClass);
|
||||
// Under reduced motion the first set of callouts stays.
|
||||
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
|
||||
if (!still) cycle = setInterval(() => page.value++, CYCLE_MS);
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [props.aircraftClass, props.modelUrl],
|
||||
() => void show(props.aircraftClass),
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearInterval(cycle);
|
||||
removeTick?.();
|
||||
removeTick = null;
|
||||
destroyPreviewWidget(widget);
|
||||
widget = null;
|
||||
model = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="!failed" class="aircraft-hero">
|
||||
<div ref="host" class="aircraft-hero__scene" aria-hidden="true"></div>
|
||||
<PreviewHud variant="model" />
|
||||
<Transition name="aircraft-hero-legend">
|
||||
<p v-if="phase === 'scan'" class="aircraft-hero__scan" aria-hidden="true">{{ t('Scanning') }}</p>
|
||||
</Transition>
|
||||
<Transition name="aircraft-hero-callout" mode="out-in" :duration="CALLOUT_TIMING">
|
||||
<div v-if="shown" :key="page" class="aircraft-hero__callout" role="status">
|
||||
<span class="aircraft-hero__label">{{ shown.label }}<em>{{ pad(shown.index + 1) }} / {{ pad(shown.total) }}</em></span>
|
||||
<strong class="aircraft-hero__value">{{ shown.value }}</strong>
|
||||
<i class="aircraft-hero__timer" aria-hidden="true"></i>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,7 +2,8 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { formatNumber, t } from '../../../i18n/index.js';
|
||||
|
||||
// A height as a filled graph (an aircraft's altitude, the camera's height):
|
||||
// A figure as a filled graph (an aircraft's altitude, the camera's height, a
|
||||
// satellite's altitude and speed):
|
||||
// each reading since it opened, left to right. The scale fits the readings (never less than about
|
||||
// 2,000 ft tall), so a climb or descent shows as a slope, and the fill
|
||||
// fades from the line down to the baseline.
|
||||
@@ -13,7 +14,11 @@ const props = defineProps({
|
||||
tick: { type: Number, default: 0 },
|
||||
/** The caption; 'Altitude' when not given. */
|
||||
label: { type: String, default: '' },
|
||||
/** 'feet' for aircraft; 'metric' reads in metres and kilometres. */
|
||||
/**
|
||||
* 'feet' for aircraft; 'metric' reads in metres and kilometres on a log
|
||||
* scale (the camera); 'km' is a height in kilometres and 'km/s' a speed
|
||||
* (given in m/s), both on a straight scale (a satellite).
|
||||
*/
|
||||
unit: { type: String, default: 'feet' },
|
||||
/** Only the caption, the current figure and the line: no scale or change. */
|
||||
compact: { type: Boolean, default: false },
|
||||
@@ -43,7 +48,14 @@ const metric = (m) =>
|
||||
: m >= 1000
|
||||
? t('{n} km', { n: formatNumber(m / 1000, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) })
|
||||
: t('{n} m', { n: number(Math.round(m)) });
|
||||
const shown = (m) => (props.unit === 'metric' ? metric(m) : t('{n} ft', { n: number(feet(m)) }));
|
||||
const SHOW = {
|
||||
metric,
|
||||
km: (m) => t('{n} km', { n: number(Math.round(m / 100) / 10) }),
|
||||
'km/s': (m) => t('{n} km/s', { n: formatNumber(m / 1000, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }),
|
||||
};
|
||||
const shown = (m) => (SHOW[props.unit] || ((value) => t('{n} ft', { n: number(feet(value)) })))(m);
|
||||
/** The least each scale spans, so a steady figure still reads as a line. */
|
||||
const LEAST = { feet: MIN_RANGE_M, km: 2000, 'km/s': 20 };
|
||||
|
||||
const graph = computed(() => {
|
||||
const list = readings.value;
|
||||
@@ -60,7 +72,7 @@ const graph = computed(() => {
|
||||
const low = Math.min(...heights);
|
||||
// The least the scale spans: about 2,000 ft for aircraft, half a decade
|
||||
// for the camera.
|
||||
const least = log ? 0.5 : MIN_RANGE_M;
|
||||
const least = log ? 0.5 : LEAST[props.unit] || MIN_RANGE_M;
|
||||
const pad = Math.max((least - (high - low)) / 2, (high - low) * 0.15);
|
||||
const bottom = Math.max(0, low - pad);
|
||||
const top = Math.max(high + pad, bottom + least);
|
||||
@@ -71,8 +83,9 @@ const graph = computed(() => {
|
||||
const points = list.length > 1 ? list.map((item) => [x(item.at), y(item.m)]) : [[0, y(first.m)], [WIDTH, y(first.m)]];
|
||||
const line = points.map(([px, py], index) => `${index ? 'L' : 'M'}${px.toFixed(2)} ${py.toFixed(2)}`).join(' ');
|
||||
const moved = last.m - first.m;
|
||||
const change = props.unit === 'metric' ? (Math.abs(moved) >= Math.max(1, last.m * 0.005) ? moved : 0) : feet(last.m) - feet(first.m);
|
||||
const changeText = props.unit === 'metric' ? metric(Math.abs(moved)) : t('{n} ft', { n: number(Math.abs(change)) });
|
||||
const feetScale = !SHOW[props.unit];
|
||||
const change = feetScale ? feet(last.m) - feet(first.m) : Math.abs(moved) >= Math.max(1, last.m * 0.0005) ? moved : 0;
|
||||
const changeText = feetScale ? t('{n} ft', { n: number(Math.abs(change)) }) : shown(Math.abs(moved));
|
||||
const minutes = Math.floor((last.at - first.at) / 60_000);
|
||||
return {
|
||||
line,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<script setup>
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { formatNumber, t } from '../../../i18n/index.js';
|
||||
import { factFigure, factLabel, factValue, sayWords, useEntityCardStore } from '../../stores/entityCard.js';
|
||||
import AircraftModelHero from './AircraftModelHero.vue';
|
||||
import SatelliteGroundView from './SatelliteGroundView.vue';
|
||||
import FlightCockpitView from './FlightCockpitView.vue';
|
||||
import AltitudeGraph from './AltitudeGraph.vue';
|
||||
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
|
||||
import RouteGlobe from './RouteGlobe.vue';
|
||||
import CctvPreview from './CctvPreview.vue';
|
||||
import { useCctvStore } from '../../stores/cctv.js';
|
||||
import SpotConditions from './SpotConditions.vue';
|
||||
@@ -17,6 +21,8 @@ import { countryName, nearestCity } from '../../../data/wikidataCities.js';
|
||||
const props = defineProps({
|
||||
/** Contacts follows this same aircraft, and its list sits inside the card. */
|
||||
withContacts: Boolean,
|
||||
/** The aircraft's photo from Contacts (`{src, link, credit}`), when it has one. */
|
||||
aircraftPhoto: { type: Object, default: null },
|
||||
});
|
||||
const store = useEntityCardStore();
|
||||
const { card, lost, tick } = storeToRefs(store);
|
||||
@@ -89,20 +95,31 @@ const ageText = computed(() => {
|
||||
// depth; a fire's power), in that order. The rest stay in the grid. An
|
||||
// aircraft's altitude is left out: its graph already leads with the figure.
|
||||
const altitudeGraphed = computed(() => card.value?.kind === 'aircraft' && Number.isFinite(card.value?.altitudeM));
|
||||
// A satellite graphs its altitude and its speed, and leaves both out of the
|
||||
// tiles and the grid.
|
||||
const orbitGraphed = computed(() => card.value?.kind === 'satellite' && Number.isFinite(card.value?.altitudeM));
|
||||
const graphedFields = computed(() => (orbitGraphed.value ? ['altitudeM', 'speedMps'] : altitudeGraphed.value ? ['altitudeM'] : []));
|
||||
const tiles = computed(() => {
|
||||
const facts = card.value?.facts || [];
|
||||
return (card.value?.headline || [])
|
||||
.filter((field) => !(altitudeGraphed.value && field === 'altitudeM'))
|
||||
.filter((field) => !graphedFields.value.includes(field))
|
||||
.map((field) => facts.find((fact) => fact.field === field))
|
||||
.filter(Boolean)
|
||||
.slice(0, 3);
|
||||
});
|
||||
const restFacts = computed(() => {
|
||||
const shown = new Set(tiles.value.map((fact) => fact.field));
|
||||
if (altitudeGraphed.value) shown.add('altitudeM');
|
||||
for (const field of graphedFields.value) shown.add(field);
|
||||
return (card.value?.facts || []).filter((fact) => !shown.has(fact.field));
|
||||
});
|
||||
|
||||
// What the turning model's callout says: what can be worked out about the
|
||||
// flight (its phase, flight level, Mach, what its squawk means, how fresh its
|
||||
// signal is), which the facts below don't already show.
|
||||
const callouts = computed(() =>
|
||||
(card.value?.insights || []).map((item) => ({ label: t(item.label), value: sayWords(item.words, item.value) })),
|
||||
);
|
||||
|
||||
|
||||
// The line under the name: who runs it and what it is. The layer is already
|
||||
// named on the line above the title.
|
||||
@@ -186,10 +203,96 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// The hero tile at the top of every card. A camera shows its latest frame.
|
||||
// The hero tile at the top of every card. A flight shows its photo (from
|
||||
// Contacts), its route on a small globe, its 3D model and the view from its
|
||||
// cockpit; a satellite, the ground beneath it; a camera, its latest frame.
|
||||
// Anything else gets a quiet placeholder with its icon and its headline
|
||||
// figures until it has imagery of its own.
|
||||
const heroKind = computed(() => (card.value?.layerId === 'cctv' ? 'camera' : 'none'));
|
||||
// figures until it has imagery of its own. Previews stay mounted so switching
|
||||
// shows the next one at once.
|
||||
const routeKnown = computed(() => Boolean(card.value?.route?.fromAt && card.value?.route?.toAt));
|
||||
const modelFailed = ref(false);
|
||||
const cockpitFailed = ref(false);
|
||||
const hasPosition = computed(() => Number.isFinite(card.value?.lat) && Number.isFinite(card.value?.lon));
|
||||
const cockpitKnown = computed(() => card.value?.kind === 'aircraft' && hasPosition.value && !cockpitFailed.value);
|
||||
const modelKnown = computed(() => Boolean(card.value?.aircraftClass) && !modelFailed.value);
|
||||
const preview = ref(null);
|
||||
const failedPhoto = ref('');
|
||||
const photoAvailable = computed(() => Boolean(props.aircraftPhoto?.src && props.aircraftPhoto.src !== failedPhoto.value));
|
||||
watch(() => props.withContacts, () => (preview.value = null));
|
||||
// The model and the cockpit view take turns: after each of the model's
|
||||
// cycles, the view ahead from the cockpit shows for as long as that cycle
|
||||
// took. It is made only once it is first needed. A manual selection holds the
|
||||
// preview until another view or another item is selected.
|
||||
const modelTurn = ref('model');
|
||||
const cockpitMade = ref(false);
|
||||
const activeFlightPreview = computed(() => {
|
||||
const chosen = preview.value;
|
||||
if (photoAvailable.value && (chosen === null || chosen === 'photo')) return 'photo';
|
||||
if (cockpitKnown.value && (chosen === 'cockpit' || modelTurn.value === 'other')) return 'cockpit';
|
||||
if (routeKnown.value && (chosen !== 'model' || !modelKnown.value)) return 'route';
|
||||
if (modelKnown.value) return 'model';
|
||||
return photoAvailable.value ? 'photo' : null;
|
||||
});
|
||||
let turnTimer = 0;
|
||||
function onCockpitFailed() {
|
||||
cockpitFailed.value = true;
|
||||
if (preview.value === 'cockpit') preview.value = null;
|
||||
clearTimeout(turnTimer);
|
||||
modelTurn.value = 'model';
|
||||
}
|
||||
function showOtherView(ms) {
|
||||
if (preview.value !== null || !hasPosition.value) return;
|
||||
if (!cockpitKnown.value || activeFlightPreview.value === 'photo') return;
|
||||
clearTimeout(turnTimer);
|
||||
modelTurn.value = 'other';
|
||||
cockpitMade.value = true;
|
||||
turnTimer = setTimeout(() => (modelTurn.value = 'model'), Math.min(Math.max(ms, 4000), 30000));
|
||||
}
|
||||
|
||||
const heroKind = computed(() => {
|
||||
if (photoAvailable.value || routeKnown.value || modelKnown.value) return 'flight';
|
||||
if (card.value?.layerId === 'satellites' && hasPosition.value) return 'satellite';
|
||||
if (card.value?.layerId === 'cctv') return 'camera';
|
||||
return 'none';
|
||||
});
|
||||
// The route globe has no cycle of its own: it shows for ROUTE_TURN_MS,
|
||||
// then the cockpit view shows for as long, and round again.
|
||||
const ROUTE_TURN_MS = 20_000;
|
||||
let routeTimer = 0;
|
||||
watch(
|
||||
[heroKind, activeFlightPreview, preview, cockpitKnown, () => card.value?.key],
|
||||
() => {
|
||||
clearTimeout(routeTimer);
|
||||
// Under reduced motion the views do not swap by themselves (the model
|
||||
// shows no scan there either, so it never hands over).
|
||||
if (globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) return;
|
||||
if (preview.value === null && cockpitKnown.value && heroKind.value === 'flight' && activeFlightPreview.value === 'route')
|
||||
routeTimer = setTimeout(() => showOtherView(ROUTE_TURN_MS), ROUTE_TURN_MS);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
// Picking a preview shows it at once, ending the cockpit view's turn.
|
||||
function choosePreview(which) {
|
||||
clearTimeout(turnTimer);
|
||||
modelTurn.value = 'model';
|
||||
preview.value = which;
|
||||
if (which === 'cockpit') cockpitMade.value = true;
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(turnTimer);
|
||||
clearTimeout(routeTimer);
|
||||
});
|
||||
watch(
|
||||
() => card.value?.key,
|
||||
() => {
|
||||
preview.value = null;
|
||||
modelFailed.value = false;
|
||||
cockpitFailed.value = false;
|
||||
clearTimeout(turnTimer);
|
||||
modelTurn.value = 'model';
|
||||
cockpitMade.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
// Things that move are read again only after they have gone a fair way, so
|
||||
// following a jet does not ask for the weather every few seconds.
|
||||
@@ -226,7 +329,31 @@ watch(
|
||||
<Transition name="entity-card">
|
||||
<section v-if="card" id="entity-card" class="entity-card" :aria-label="t('Selected on the map')" :data-layer="card.layerId">
|
||||
<div class="entity-hero" :data-hero="heroKind">
|
||||
<CctvPreview v-if="heroKind === 'camera'" :camera-id="card.identity?.id || ''" />
|
||||
<template v-if="heroKind === 'flight'">
|
||||
<a
|
||||
v-if="photoAvailable"
|
||||
:key="aircraftPhoto.src"
|
||||
class="entity-hero__layer entity-hero__photo"
|
||||
:class="{ 'is-shown': activeFlightPreview === 'photo' }"
|
||||
:href="aircraftPhoto.link"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
>
|
||||
<img :src="aircraftPhoto.src" :alt="t('Photo of {name}', { name: shownTitle })" @error="failedPhoto = $event.currentTarget.getAttribute('src')" />
|
||||
<small v-if="aircraftPhoto.credit">{{ aircraftPhoto.credit }}</small>
|
||||
</a>
|
||||
<RouteGlobe v-if="routeKnown" :key="`route-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'route' }" :active="activeFlightPreview === 'route'" :from="card.route.fromAt" :to="card.route.toAt" :at="{ lat: card.lat, lon: card.lon }" :heading="card.heading" />
|
||||
<AircraftModelHero v-if="card.aircraftClass && !modelFailed" :key="card.key" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'model' }" :active="activeFlightPreview === 'model'" :aircraft-class="card.aircraftClass" :heading="card.heading || 0" :callouts="callouts" @failed="modelFailed = true" @cycle="showOtherView" />
|
||||
<FlightCockpitView v-if="cockpitMade && cockpitKnown" :key="`cockpit-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'cockpit' }" :active="activeFlightPreview === 'cockpit'" :lat="card.lat" :lon="card.lon" :altitude-m="card.altitudeM" :heading="card.heading" :speed-mps="card.speedMps" @failed="onCockpitFailed" />
|
||||
<div v-if="cockpitKnown || (routeKnown && modelKnown) || (photoAvailable && (routeKnown || modelKnown))" class="entity-card__preview-switch" role="group" :aria-label="t('Preview')">
|
||||
<button v-if="photoAvailable" type="button" :class="{ active: activeFlightPreview === 'photo' }" :aria-pressed="String(activeFlightPreview === 'photo')" :aria-label="t('Photos')" :title="t('Photos')" @click="choosePreview('photo')"><span class="material-symbols-outlined" aria-hidden="true">photo_camera</span></button>
|
||||
<button v-if="routeKnown" type="button" :class="{ active: activeFlightPreview === 'route' }" :aria-pressed="String(activeFlightPreview === 'route')" :aria-label="t('Route')" :title="t('Route')" @click="choosePreview('route')"><span class="material-symbols-outlined" aria-hidden="true">timeline</span></button>
|
||||
<button v-if="modelKnown" type="button" :class="{ active: activeFlightPreview === 'model' }" :aria-pressed="String(activeFlightPreview === 'model')" :title="t('3D model')" @click="choosePreview('model')">{{ t('3D') }}</button>
|
||||
<button v-if="cockpitKnown" type="button" :class="{ active: activeFlightPreview === 'cockpit' }" :aria-pressed="String(activeFlightPreview === 'cockpit')" :aria-label="t('Cockpit view')" :title="t('Cockpit view')" @click="choosePreview('cockpit')"><span class="material-symbols-outlined" aria-hidden="true">visibility</span></button>
|
||||
</div>
|
||||
</template>
|
||||
<SatelliteGroundView v-else-if="heroKind === 'satellite'" :key="`ground-${card.key}`" class="entity-hero__layer is-shown" active :lat="card.lat" :lon="card.lon" />
|
||||
<CctvPreview v-else-if="heroKind === 'camera'" :camera-id="card.identity?.id || ''" />
|
||||
<!-- No imagery for it yet: its icon, with its headline figures beside it. -->
|
||||
<div v-else class="entity-hero__placeholder" :class="{ 'entity-hero__placeholder--bare': props.withContacts || !tiles.length }">
|
||||
<span class="material-symbols-outlined entity-hero__glyph" aria-hidden="true">{{ card.icon }}</span>
|
||||
@@ -278,6 +405,10 @@ watch(
|
||||
<span>{{ routePlaces.to }}</span>
|
||||
</p>
|
||||
<AltitudeGraph v-if="altitudeGraphed" v-show="!props.withContacts" :key="`altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" />
|
||||
<template v-if="orbitGraphed">
|
||||
<AltitudeGraph :key="`orbit-altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" unit="km" />
|
||||
<AltitudeGraph v-if="Number.isFinite(card.speedMps)" :key="`orbit-speed:${card.key}`" :altitude-m="lost ? null : card.speedMps" :tick="tick" unit="km/s" :label="t('Speed')" />
|
||||
</template>
|
||||
<p
|
||||
v-if="card.route && !card.route.verified"
|
||||
class="entity-card__route-note"
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<script setup>
|
||||
import * as Cesium from 'cesium';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { t } from '../../../i18n/index.js';
|
||||
import { ESRI_IMAGERY_CREDIT, createEsriImagery } from '../../../maps/imagery.js';
|
||||
import { destroyPreviewWidget } from '../../previewWidget.js';
|
||||
import PreviewHud from './PreviewHud.vue';
|
||||
|
||||
// What the crew sees: the view ahead from the aircraft's own position,
|
||||
// height and heading, a little nose down, over Esri World Imagery (the
|
||||
// app's keyless basemap) on a plain ellipsoid with the sky's haze. It takes
|
||||
// turns with the turning model, as a satellite's ground view does. It draws
|
||||
// only when asked (a still, moved along with the craft while it shows) and
|
||||
// holds still while hidden. Its credit line sits in the corner. Speed and
|
||||
// altitude ride on tapes either side, as on a head-up display: the ticks
|
||||
// roll as the figures change, with the figure boxed in the middle.
|
||||
const props = defineProps({
|
||||
lat: { type: Number, default: null },
|
||||
lon: { type: Number, default: null },
|
||||
/** Height above the ellipsoid, metres. */
|
||||
altitudeM: { type: Number, default: null },
|
||||
/** Degrees from north. */
|
||||
heading: { type: Number, default: null },
|
||||
/** Ground speed, metres a second. */
|
||||
speedMps: { type: Number, default: null },
|
||||
/** Whether the view is the one showing. */
|
||||
active: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['failed']);
|
||||
|
||||
const host = ref(null);
|
||||
let widget = null;
|
||||
|
||||
/** A ground floor for the eye, so a landed or taxiing craft is not underground. */
|
||||
const MIN_EYE_M = 60;
|
||||
|
||||
function place() {
|
||||
if (!widget || !Number.isFinite(props.lat) || !Number.isFinite(props.lon)) return;
|
||||
const height = Math.max(MIN_EYE_M, Number.isFinite(props.altitudeM) ? props.altitudeM : 0);
|
||||
widget.camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(props.lon, props.lat, height),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(Number.isFinite(props.heading) ? props.heading : 0),
|
||||
pitch: Cesium.Math.toRadians(-9),
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
widget.scene.requestRender();
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
widget = new Cesium.CesiumWidget(host.value, {
|
||||
baseLayer: false,
|
||||
skyBox: false,
|
||||
scene3DOnly: true,
|
||||
shadows: false,
|
||||
requestRenderMode: true,
|
||||
maximumRenderTimeChange: Infinity,
|
||||
showRenderLoopErrors: false,
|
||||
contextOptions: { webgl: { alpha: false, antialias: true } },
|
||||
creditContainer: document.createElement('div'),
|
||||
});
|
||||
const scene = widget.scene;
|
||||
scene.screenSpaceCameraController.enableInputs = false;
|
||||
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
|
||||
scene.globe.showGroundAtmosphere = true;
|
||||
scene.fog.enabled = true;
|
||||
scene.camera.frustum.fov = Cesium.Math.toRadians(70);
|
||||
// Tiles arriving ask for a frame, so the still fills in as they load.
|
||||
scene.globe.tileLoadProgressEvent.addEventListener(() => scene.requestRender());
|
||||
place();
|
||||
const imagery = await createEsriImagery();
|
||||
if (!widget) return;
|
||||
scene.imageryLayers.addImageryProvider(imagery);
|
||||
scene.requestRender();
|
||||
} catch {
|
||||
emit('failed');
|
||||
}
|
||||
});
|
||||
|
||||
// While it shows, the view keeps up with the craft as the card refreshes.
|
||||
watch(
|
||||
() => [props.active, props.lat, props.lon, props.altitudeM, props.heading],
|
||||
() => props.active && place(),
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
destroyPreviewWidget(widget);
|
||||
widget = null;
|
||||
});
|
||||
|
||||
const feet = computed(() =>
|
||||
Number.isFinite(props.altitudeM) ? `${(Math.round((props.altitudeM * 3.28084) / 100) * 100).toLocaleString('en-US')} ft` : '',
|
||||
);
|
||||
// The tapes: one tick every 10 kt and every 100 ft, 8 px apart; the ticks
|
||||
// roll by the remainder, so a change in the figure moves them.
|
||||
const TICK_PX = 8;
|
||||
const knots = computed(() => (Number.isFinite(props.speedMps) ? Math.round(props.speedMps * 1.94384) : null));
|
||||
const altFeet = computed(() => (Number.isFinite(props.altitudeM) ? Math.round(props.altitudeM * 3.28084) : null));
|
||||
const roll = (value, per) => (value === null ? 0 : ((value % per) / per) * TICK_PX);
|
||||
const speedRoll = computed(() => `${roll(knots.value, 10)}px`);
|
||||
const altRoll = computed(() => `${roll(altFeet.value, 100)}px`);
|
||||
const course = computed(() => (Number.isFinite(props.heading) ? `${String(Math.round(props.heading) % 360).padStart(3, '0')}°` : ''));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flight-cockpit" aria-hidden="true">
|
||||
<div ref="host" class="flight-cockpit__scene"></div>
|
||||
<PreviewHud variant="cockpit" :running="active" />
|
||||
<span class="flight-cockpit__horizon"><i></i></span>
|
||||
<span v-if="knots !== null" class="flight-cockpit__tape flight-cockpit__tape--speed">
|
||||
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: speedRoll }"></i>
|
||||
<b>{{ knots }}</b><em>{{ t('KT') }}</em>
|
||||
</span>
|
||||
<span v-if="altFeet !== null" class="flight-cockpit__tape flight-cockpit__tape--alt">
|
||||
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: altRoll }"></i>
|
||||
<b>{{ altFeet.toLocaleString('en-US') }}</b><em>{{ t('FT') }}</em>
|
||||
</span>
|
||||
<span class="flight-cockpit__label">{{ t('Cockpit view') }}<strong>{{ [feet, course].filter(Boolean).join(' · ') }}</strong></span>
|
||||
<span class="flight-cockpit__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
|
||||
// Small moving HUD marks laid over a card's preview, for look only: corner
|
||||
// brackets, a ruler down the right edge with a marker riding it, a tick
|
||||
// scale crawling along the bottom, a signal meter and a blinking dot at the
|
||||
// top right, and a slow dashed ring round the centre with its four ticks.
|
||||
// The ground view instead lays a square grid over the image, with cells lit
|
||||
// one by one at random, each fading as the next lights, and a scan line
|
||||
// sweeping down. Nothing here takes the pointer or says
|
||||
// anything; it all stops under reduced motion.
|
||||
const props = defineProps({
|
||||
/** 'model' over the turning craft, 'ground' over the view beneath. */
|
||||
variant: { type: String, default: 'model' },
|
||||
/** Whether the preview is showing; the grid scan steps only while it is. */
|
||||
running: { type: Boolean, default: true },
|
||||
});
|
||||
|
||||
const CELL = 22;
|
||||
const STEP_MS = 260;
|
||||
const TRAIL = 4;
|
||||
|
||||
const root = ref(null);
|
||||
const grid = ref({ cols: 0, rows: 0, left: 0, top: 0 });
|
||||
const cells = ref([]);
|
||||
let timer = 0;
|
||||
let lit = [];
|
||||
let serial = 0;
|
||||
|
||||
function measure() {
|
||||
const box = root.value?.getBoundingClientRect();
|
||||
if (!box?.width) return false;
|
||||
const cols = Math.floor(box.width / CELL);
|
||||
const rows = Math.floor(box.height / CELL);
|
||||
// The grid is centred in the view.
|
||||
grid.value = { cols, rows, left: (box.width - cols * CELL) / 2, top: (box.height - rows * CELL) / 2 };
|
||||
return cols > 0 && rows > 0;
|
||||
}
|
||||
|
||||
// Each step lights a random cell (never the one just lit) and dims the
|
||||
// ones before it, so a few faint cells fade out behind the newest.
|
||||
function step() {
|
||||
if (!grid.value.cols && !measure()) return;
|
||||
const { cols, rows, left, top } = grid.value;
|
||||
let col;
|
||||
let row;
|
||||
do {
|
||||
col = Math.floor(Math.random() * cols);
|
||||
row = Math.floor(Math.random() * rows);
|
||||
} while (cols * rows > 1 && lit[0]?.col === col && lit[0]?.row === row);
|
||||
lit = [{ key: ++serial, col, row }, ...lit].slice(0, TRAIL);
|
||||
cells.value = lit.map((cell, back) => ({
|
||||
key: cell.key,
|
||||
x: left + cell.col * CELL,
|
||||
y: top + cell.row * CELL,
|
||||
fade: 1 - back / TRAIL,
|
||||
}));
|
||||
}
|
||||
|
||||
function sync() {
|
||||
clearInterval(timer);
|
||||
timer = 0;
|
||||
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
|
||||
if (props.variant === 'ground' && props.running && !still) {
|
||||
measure();
|
||||
timer = setInterval(step, STEP_MS);
|
||||
}
|
||||
}
|
||||
onMounted(sync);
|
||||
watch(() => props.running, sync);
|
||||
onBeforeUnmount(() => clearInterval(timer));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="preview-hud" :class="`preview-hud--${variant}`" aria-hidden="true">
|
||||
<template v-if="variant === 'ground'">
|
||||
<span class="preview-hud__grid" :style="{ left: `${grid.left}px`, top: `${grid.top}px`, width: `${grid.cols * CELL}px`, height: `${grid.rows * CELL}px` }"></span>
|
||||
<i v-for="cell in cells" :key="cell.key" class="preview-hud__cell" :style="{ transform: `translate(${cell.x}px, ${cell.y}px)`, opacity: cell.fade }"></i>
|
||||
</template>
|
||||
<i class="preview-hud__corner preview-hud__corner--tl"></i>
|
||||
<i class="preview-hud__corner preview-hud__corner--tr"></i>
|
||||
<i class="preview-hud__corner preview-hud__corner--bl"></i>
|
||||
<i class="preview-hud__corner preview-hud__corner--br"></i>
|
||||
<span class="preview-hud__ruler"><i></i></span>
|
||||
<span class="preview-hud__scale"></span>
|
||||
<span class="preview-hud__meter"><i></i><i></i><i></i><i></i><b></b></span>
|
||||
<svg class="preview-hud__ring" viewBox="-100 -100 200 200">
|
||||
<circle r="92" class="preview-hud__dash" />
|
||||
<path d="M0 -100 V-90 M0 90 V100 M-100 0 H-90 M90 0 H100" class="preview-hud__ticks" />
|
||||
</svg>
|
||||
<span v-if="variant === 'ground'" class="preview-hud__sweep"></span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,326 @@
|
||||
<script setup>
|
||||
import { destroyPreviewWidget } from '../../previewWidget.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
|
||||
// A flight's route on a small globe of its own at the top of its card: the
|
||||
// great circle from origin to destination, solid where it has flown and
|
||||
// dashed ahead, the two airports marked with their codes, and a plane icon
|
||||
// where the craft is now, pointing the way it is flying. On opening, the flown part draws out from the
|
||||
// origin to the craft. The globe uses Cesium's bundled Natural Earth image,
|
||||
// so it fetches no map tiles. It holds still, north up and framed on the
|
||||
// route; the plane points at the destination. The card names the airports'
|
||||
// cities under its progress bar.
|
||||
const props = defineProps({
|
||||
/** `{code, lat, lon}` of the origin airport. */
|
||||
from: { type: Object, required: true },
|
||||
/** `{code, lat, lon}` of the destination airport. */
|
||||
to: { type: Object, required: true },
|
||||
/** The craft's position now. */
|
||||
at: { type: Object, default: null },
|
||||
/** Its heading in degrees; without one the icon points along the route. */
|
||||
heading: { type: Number, default: null },
|
||||
/** Whether the tile is the one showing; a hidden one stops drawing. */
|
||||
active: { type: Boolean, default: true },
|
||||
});
|
||||
|
||||
const host = ref(null);
|
||||
const failed = ref(false);
|
||||
let widget = null;
|
||||
let removeTick = null;
|
||||
let entities = null;
|
||||
let plane = null;
|
||||
let flownLine = null;
|
||||
let aheadLine = null;
|
||||
/** True while the plane flies in from the origin; position updates wait. */
|
||||
let flyingIn = false;
|
||||
|
||||
const CYAN = Cesium.Color.fromCssColorString('#36dcff');
|
||||
|
||||
// The plane: the Material "flight" silhouette, nose up (north), white with a
|
||||
// cyan glow, drawn once as an image.
|
||||
const PLANE_ICON = `data:image/svg+xml;utf8,${encodeURIComponent(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 32 32" width="64" height="64">' +
|
||||
'<defs><filter id="g" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="1.4"/></filter></defs>' +
|
||||
'<path filter="url(#g)" fill="#36dcff" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
|
||||
'<path fill="#ffffff" stroke="#0b1820" stroke-width="0.6" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
|
||||
'</svg>',
|
||||
)}`;
|
||||
|
||||
/** The initial bearing (degrees from north) of the great circle a → b. */
|
||||
function bearing(a, b) {
|
||||
const rad = Math.PI / 180;
|
||||
const y = Math.sin((b.lon - a.lon) * rad) * Math.cos(b.lat * rad);
|
||||
const x =
|
||||
Math.cos(a.lat * rad) * Math.sin(b.lat * rad) -
|
||||
Math.sin(a.lat * rad) * Math.cos(b.lat * rad) * Math.cos((b.lon - a.lon) * rad);
|
||||
return (Math.atan2(y, x) / rad + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Billboard placement for the plane, nose along `deg` from north: the icon's
|
||||
* up is tied to the local north direction on the globe and turned from there,
|
||||
* so it points the right way in this tilted view too.
|
||||
*/
|
||||
function planePose(at, deg) {
|
||||
const position = Cesium.Cartesian3.fromDegrees(at.lon, at.lat, 30_000);
|
||||
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
|
||||
const north = Cesium.Matrix4.getColumn(frame, 1, new Cesium.Cartesian4());
|
||||
return {
|
||||
position,
|
||||
rotation: -Cesium.Math.toRadians(deg),
|
||||
alignedAxis: new Cesium.Cartesian3(north.x, north.y, north.z),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The point on the route (the great circle from origin to destination)
|
||||
* nearest the craft. The craft is drawn there and the route split there, so
|
||||
* the path stays one smooth arc: a craft a little off the direct line
|
||||
* (vectors, airways, a detour) would otherwise bend it into a sharp corner.
|
||||
*/
|
||||
function onRoute(at) {
|
||||
if (!at || !Number.isFinite(at.lat)) return null;
|
||||
const route = new Cesium.EllipsoidGeodesic(
|
||||
Cesium.Cartographic.fromDegrees(props.from.lon, props.from.lat),
|
||||
Cesium.Cartographic.fromDegrees(props.to.lon, props.to.lat),
|
||||
);
|
||||
const here = Cesium.Cartesian3.fromDegrees(at.lon, at.lat);
|
||||
let best = null;
|
||||
let bestDistance = Infinity;
|
||||
const STEPS = 200;
|
||||
for (let i = 0; i <= STEPS; i++) {
|
||||
const c = route.interpolateUsingFraction(i / STEPS);
|
||||
const d = Cesium.Cartesian3.distanceSquared(here, Cesium.Cartesian3.fromRadians(c.longitude, c.latitude));
|
||||
if (d < bestDistance) {
|
||||
bestDistance = d;
|
||||
best = { lat: Cesium.Math.toDegrees(c.latitude), lon: Cesium.Math.toDegrees(c.longitude) };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// The nose points at the destination: along the great circle from here.
|
||||
const planeHeading = (at) => bearing(at, props.to);
|
||||
|
||||
// The compass: the view is north up, so N sits at the top; a cyan needle
|
||||
// shows the course to the destination, with its bearing in degrees.
|
||||
const course = computed(() => {
|
||||
const at = props.at && Number.isFinite(props.at.lat) ? props.at : props.from;
|
||||
return Math.round(bearing(at, props.to));
|
||||
});
|
||||
const courseLabel = computed(() => {
|
||||
const points = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
||||
return `${String(course.value).padStart(3, '0')}° ${points[Math.round(course.value / 45) % 8]}`;
|
||||
});
|
||||
const AMBER = Cesium.Color.fromCssColorString('#ffb86b');
|
||||
|
||||
/** Points along the great circle from a to b, `t` from 0 to 1. */
|
||||
function arc(a, b, steps = 64, upTo = 1) {
|
||||
const start = Cesium.Cartographic.fromDegrees(a.lon, a.lat);
|
||||
const end = Cesium.Cartographic.fromDegrees(b.lon, b.lat);
|
||||
const geodesic = new Cesium.EllipsoidGeodesic(start, end);
|
||||
const out = [];
|
||||
const n = Math.max(2, Math.round(steps * upTo));
|
||||
for (let i = 0; i <= n; i++) {
|
||||
const c = geodesic.interpolateUsingFraction((i / n) * upTo);
|
||||
out.push(Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 30_000));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!widget) return;
|
||||
const { from, to } = props;
|
||||
const at = onRoute(props.at);
|
||||
entities?.removeAll();
|
||||
entities = widget.entities;
|
||||
const pin = (place, color) =>
|
||||
entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(place.lon, place.lat),
|
||||
point: { pixelSize: 7, color, outlineColor: Cesium.Color.BLACK.withAlpha(0.6), outlineWidth: 1 },
|
||||
label: {
|
||||
text: place.code || '',
|
||||
font: '600 11px ui-monospace, monospace',
|
||||
fillColor: Cesium.Color.WHITE,
|
||||
outlineColor: Cesium.Color.BLACK,
|
||||
outlineWidth: 3,
|
||||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||||
pixelOffset: new Cesium.Cartesian2(0, -14),
|
||||
},
|
||||
});
|
||||
pin(from, CYAN.withAlpha(0.9));
|
||||
pin(to, AMBER);
|
||||
|
||||
// Ahead of the craft, dashed; behind it, solid, drawing out on open.
|
||||
aheadLine = entities.add({
|
||||
polyline: {
|
||||
positions: arc(at || from, to),
|
||||
width: 1.5,
|
||||
material: new Cesium.PolylineDashMaterialProperty({ color: AMBER.withAlpha(0.8), dashLength: 10 }),
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
},
|
||||
});
|
||||
if (at) {
|
||||
let progress = 0;
|
||||
const flown = (flownLine = entities.add({
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => arc(from, at, 48, Math.max(0.02, progress)), false),
|
||||
width: 2.5,
|
||||
material: new Cesium.PolylineGlowMaterialProperty({ color: CYAN, glowPower: 0.25 }),
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
},
|
||||
}));
|
||||
// The fly-in waits until the globe has drawn (its imagery loads a moment
|
||||
// after the card opens), at most 1.5 s, so it is seen from the start.
|
||||
let began = null;
|
||||
const opened = performance.now();
|
||||
// The plane starts at the origin and flies out along the flown line as it
|
||||
// draws, arriving where the craft is now; it points at the destination
|
||||
// all the way.
|
||||
const start = planePose(from, planeHeading(from));
|
||||
plane = entities.add({
|
||||
position: start.position,
|
||||
billboard: {
|
||||
image: PLANE_ICON,
|
||||
width: 26,
|
||||
height: 26,
|
||||
rotation: start.rotation,
|
||||
alignedAxis: start.alignedAxis,
|
||||
},
|
||||
});
|
||||
const leg = new Cesium.EllipsoidGeodesic(
|
||||
Cesium.Cartographic.fromDegrees(from.lon, from.lat),
|
||||
Cesium.Cartographic.fromDegrees(at.lon, at.lat),
|
||||
);
|
||||
const ease = (x) => 1 - (1 - x) ** 3;
|
||||
flyingIn = true;
|
||||
const grow = () => {
|
||||
if (began === null) {
|
||||
if (!widget.scene.globe.tilesLoaded && performance.now() - opened < 1500) return;
|
||||
began = performance.now();
|
||||
}
|
||||
const raw = Math.min(1, (performance.now() - began) / 1600);
|
||||
progress = ease(raw);
|
||||
const c = leg.interpolateUsingFraction(progress);
|
||||
const where = { lat: Cesium.Math.toDegrees(c.latitude), lon: Cesium.Math.toDegrees(c.longitude) };
|
||||
const pose = planePose(where, planeHeading(where));
|
||||
plane.position = pose.position;
|
||||
plane.billboard.rotation = pose.rotation;
|
||||
plane.billboard.alignedAxis = pose.alignedAxis;
|
||||
if (raw >= 1) {
|
||||
flyingIn = false;
|
||||
flown.polyline.positions = arc(from, at, 48);
|
||||
widget?.scene.preRender.removeEventListener(grow);
|
||||
}
|
||||
};
|
||||
widget.scene.preRender.addEventListener(grow);
|
||||
}
|
||||
|
||||
// Frame the whole route, north up, looking down at a slight tilt; the view
|
||||
// holds still so the plane and labels keep their bearings.
|
||||
const points = [from, to, ...(at ? [at] : [])].map((p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat));
|
||||
const sphere = Cesium.BoundingSphere.fromPoints(points);
|
||||
const range = Math.max(1_800_000, sphere.radius * 3.2);
|
||||
removeTick?.();
|
||||
removeTick = null;
|
||||
const center = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(sphere.center) || sphere.center;
|
||||
widget.camera.lookAt(center, new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-62), range));
|
||||
widget.scene.requestRender();
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
widget = new Cesium.CesiumWidget(host.value, {
|
||||
baseLayer: false,
|
||||
skyBox: false,
|
||||
skyAtmosphere: false,
|
||||
scene3DOnly: true,
|
||||
shadows: false,
|
||||
showRenderLoopErrors: false,
|
||||
contextOptions: { webgl: { alpha: true, antialias: true } },
|
||||
creditContainer: document.createElement('div'),
|
||||
});
|
||||
const scene = widget.scene;
|
||||
scene.backgroundColor = Cesium.Color.TRANSPARENT;
|
||||
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
|
||||
scene.globe.showGroundAtmosphere = false;
|
||||
scene.globe.enableLighting = false;
|
||||
scene.screenSpaceCameraController.enableInputs = false;
|
||||
const imagery = await Cesium.TileMapServiceImageryProvider.fromUrl(
|
||||
Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII'),
|
||||
);
|
||||
if (!widget) return;
|
||||
const layer = scene.imageryLayers.addImageryProvider(imagery);
|
||||
// Dimmed and cooled, so the route reads over it.
|
||||
layer.brightness = 0.55;
|
||||
layer.saturation = 0.35;
|
||||
layer.contrast = 1.1;
|
||||
draw();
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
// A new route redraws; the craft moving along it only moves its marker and
|
||||
// the two lines, without replaying the opening draw.
|
||||
// Watched as strings: a fresh array each card refresh would count as a change
|
||||
// every two seconds and restart the drawing and the turn.
|
||||
watch(
|
||||
() => `${props.from?.code}|${props.to?.code}`,
|
||||
() => draw(),
|
||||
);
|
||||
watch(
|
||||
() => `${props.at?.lat?.toFixed?.(4)}|${props.at?.lon?.toFixed?.(4)}|${Math.round(props.heading ?? -1)}`,
|
||||
() => {
|
||||
const at = onRoute(props.at);
|
||||
if (!widget || !at || !plane || flyingIn) return;
|
||||
const pose = planePose(at, planeHeading(at));
|
||||
plane.position = pose.position;
|
||||
plane.billboard.rotation = pose.rotation;
|
||||
plane.billboard.alignedAxis = pose.alignedAxis;
|
||||
if (flownLine) flownLine.polyline.positions = arc(props.from, at, 48);
|
||||
if (aheadLine) aheadLine.polyline.positions = arc(at, props.to);
|
||||
},
|
||||
);
|
||||
|
||||
// Hidden, the globe rests on its last frame; shown again, it draws once
|
||||
// straight away so there is no gap.
|
||||
watch(
|
||||
() => props.active,
|
||||
(active) => {
|
||||
if (!widget || widget.isDestroyed()) return;
|
||||
if (active && !widget.useDefaultRenderLoop) {
|
||||
widget.resize();
|
||||
widget.render();
|
||||
}
|
||||
widget.useDefaultRenderLoop = active;
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
removeTick?.();
|
||||
removeTick = null;
|
||||
destroyPreviewWidget(widget);
|
||||
widget = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="!failed" class="route-globe">
|
||||
<div ref="host" class="route-globe__scene" aria-hidden="true"></div>
|
||||
<div class="route-globe__compass" :title="`Course to ${to.code}: ${courseLabel}`">
|
||||
<svg viewBox="-24 -24 48 48" aria-hidden="true">
|
||||
<circle r="19" class="route-globe__compass-ring" />
|
||||
<g class="route-globe__compass-ticks">
|
||||
<line v-for="deg in [0, 45, 90, 135, 180, 225, 270, 315]" :key="deg" :transform="`rotate(${deg})`" y1="-19" :y2="deg % 90 ? -16.5 : -15" />
|
||||
</g>
|
||||
<text y="-9.5" class="route-globe__compass-n">N</text>
|
||||
<g :transform="`rotate(${course})`" class="route-globe__compass-needle">
|
||||
<path d="M0 -14 L3 2 L0 0 L-3 2 Z" />
|
||||
</g>
|
||||
<circle r="1.6" class="route-globe__compass-hub" />
|
||||
</svg>
|
||||
<span>{{ courseLabel }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { t } from '../../../i18n/index.js';
|
||||
import { nearestCity } from '../../../data/wikidataCities.js';
|
||||
import { ESRI_IMAGERY_CREDIT, ESRI_IMAGERY_URL } from '../../../maps/imagery.js';
|
||||
import PreviewHud from './PreviewHud.vue';
|
||||
|
||||
// What lies under a satellite: a dark, grey top-down image of the ground at
|
||||
// the point beneath it, with rings on that spot. It is a still taken each
|
||||
// time the view comes round, and its tiles load only while it shows (the craft moves several kilometres a second, so
|
||||
// a live view would only blur), and it drifts in slowly while it shows.
|
||||
// Near a town it looks close in, at street-block scale; over open water or
|
||||
// empty land, where a close view would be a blank, it stands well back so
|
||||
// coasts and terrain show. The image is Esri World Imagery, the app's
|
||||
// keyless basemap, from its classic tile endpoint; its credit line sits in
|
||||
// the corner.
|
||||
const props = defineProps({
|
||||
lat: { type: Number, default: null },
|
||||
lon: { type: Number, default: null },
|
||||
/** Whether the view is the one showing; each showing takes a new still. */
|
||||
active: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const TILE_URL = `${ESRI_IMAGERY_URL}/tile`;
|
||||
const CLOSE_ZOOM = 13;
|
||||
const WIDE_ZOOM = 4;
|
||||
const TILE = 256;
|
||||
|
||||
/** The spot the still was taken at, how close it looks and what is near. */
|
||||
const spot = ref(null);
|
||||
let taking = 0;
|
||||
async function take() {
|
||||
if (!Number.isFinite(props.lat) || !Number.isFinite(props.lon)) return;
|
||||
const lat = props.lat;
|
||||
const lon = props.lon;
|
||||
const turn = ++taking;
|
||||
spot.value = null;
|
||||
let city = null;
|
||||
try {
|
||||
city = await nearestCity(lat, lon, { radiusKm: 40, nearKm: 15 });
|
||||
} catch {
|
||||
city = null;
|
||||
}
|
||||
if (turn !== taking) return;
|
||||
spot.value = { lat, lon, zoom: city ? CLOSE_ZOOM : WIDE_ZOOM, near: city?.name || '' };
|
||||
}
|
||||
watch(
|
||||
() => props.active,
|
||||
(now) => now && take(),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// Web Mercator tile position of the spot, in tiles.
|
||||
const at = computed(() => {
|
||||
if (!spot.value) return null;
|
||||
const n = 2 ** spot.value.zoom;
|
||||
const lat = Math.max(-85, Math.min(85, spot.value.lat));
|
||||
const x = ((spot.value.lon + 180) / 360) * n;
|
||||
const rad = (lat * Math.PI) / 180;
|
||||
const y = ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n;
|
||||
return { x, y, n, zoom: spot.value.zoom };
|
||||
});
|
||||
|
||||
// A 3 by 3 block of tiles round the spot, placed so the spot is at the centre.
|
||||
const tiles = computed(() => {
|
||||
const here = at.value;
|
||||
if (!here) return [];
|
||||
const cx = Math.floor(here.x);
|
||||
const cy = Math.floor(here.y);
|
||||
const list = [];
|
||||
for (let dy = -1; dy <= 1; dy++)
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
const y = cy + dy;
|
||||
if (y < 0 || y >= here.n) continue;
|
||||
const x = (((cx + dx) % here.n) + here.n) % here.n;
|
||||
list.push({
|
||||
key: `${x}/${y}`,
|
||||
src: `${TILE_URL}/${here.zoom}/${y}/${x}`,
|
||||
left: (cx + dx - here.x) * TILE,
|
||||
top: (cy + dy - here.y) * TILE,
|
||||
});
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
const where = computed(() => {
|
||||
if (!spot.value) return '';
|
||||
const { lat, lon } = spot.value;
|
||||
return `${Math.abs(lat).toFixed(2)}°${lat >= 0 ? 'N' : 'S'} ${Math.abs(lon).toFixed(2)}°${lon >= 0 ? 'E' : 'W'}`;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="satellite-ground" aria-hidden="true">
|
||||
<div :key="where" class="satellite-ground__map" :class="{ 'is-drifting': active }">
|
||||
<img v-for="tile in active ? tiles : []" :key="tile.key" class="satellite-ground__tile" :src="tile.src" alt="" draggable="false" :style="{ transform: `translate(${tile.left}px, ${tile.top}px)` }" />
|
||||
</div>
|
||||
<svg class="satellite-ground__rings" viewBox="-100 -100 200 200">
|
||||
<circle r="88" class="satellite-ground__ring satellite-ground__ring--outer" />
|
||||
<circle r="56" class="satellite-ground__ring satellite-ground__ring--middle" />
|
||||
<circle r="34" class="satellite-ground__ring satellite-ground__ring--inner" />
|
||||
</svg>
|
||||
<PreviewHud variant="ground" :running="active" />
|
||||
<span class="satellite-ground__label">{{ spot?.near ? t('Over {place}', { place: spot.near }) : t('Below') }}<strong>{{ where }}</strong></span>
|
||||
<span class="satellite-ground__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
|
||||
</div>
|
||||
</template>
|
||||
Reference in new issue
Block a user