Give the aerodromes a colour of their own, and say what each aircraft is
Four things about the animated pictures, and the window kept in step with them. The aerodromes were amber, and so is an aeroplane at twelve thousand feet. Sixteen units of CIELAB apart is not two colours, it is one: an aircraft low over a field was drawn in the field's own colour and neither could be picked out from the other. They are magenta now, fifty-six units from the nearest altitude colour, which is what the ramp leaves free once red, amber, green, cyan and violet have gone on height -- and what an aeronautical chart marks an aerodrome in anyway. The test states that as the distance rather than as the colour, so that changing the ramp cannot quietly walk an aircraft back into the airports. The height beside an aircraft was the flight level, which is shorter and is what an aviator reads, but "376" is only a height to somebody who already knows it is one. It is feet with the unit on it now, rounded to the twenty-five feet Mode S reports altitude in: a real reading is a multiple of that and comes through untouched, while a moment interpolated between two reports stops claiming to know the height to the foot. The flag of the country of registration now comes off the address block where no register answered. Taking it from the register's answer alone left the flag off exactly the aircraft that had nothing else beside them either. Mexico was missing from the address table while we were in there, which a receiver in the American southwest notices; two registers independently give XA- registrations for that block. And what sort of aircraft it is, which is two facts and not one. What it is comes off the air: every identification message carries three bits under its type code saying whether it is light, large, heavy, a rotorcraft, a glider, a drone or a van on the apron, and that is the only word about what an aircraft *is* that needs no register. They were being decoded and thrown away. They are inside the identification frame the log already writes down in full, so every log this program has ever written has them, including the ones written before anything here knew to look. Whether it is military comes off no air at all -- a tanker calls itself heavy exactly as an airliner does -- and is read from the address block instead. On one evening here AE07D3 broadcast "heavy" and sat in the United States military block; the register, asked separately, came back with a C-17A Globemaster III, tail 90-0534, United States Air Force. Labels in an animation now behave as the boxes in the window do. One keeps its place for as long as that place still works and is moved only when something takes it, which on a real log is about half as many moves as deciding afresh every frame; the moves that are left are eased over half a second of playback; and what the next label is laid out against is where a moving one is going rather than where it has reached. A still has no frame before it and places its labels exactly as it always did. The fading was only half done. A label's name faded, because it is drawn in the aircraft's own colour, but its rows and its flag were fixed colours and stayed at full brightness -- so the brightest thing on that part of the picture was the one aeroplane nothing had been heard from. An indexed picture cannot blend, so the row grey and all twelve flag colours now have dimmed copies at each of the four fade steps, and the whole box goes together. A crowded frame, which drops back to the short label, drops the class and the flag with it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
This commit is contained in:
parent
8eb3bdbb86
commit
f9b21f7e35
13 changed files with 1616 additions and 67 deletions
121
README.md
121
README.md
|
|
@ -1013,6 +1013,35 @@ would otherwise make one box wider than the map under it. A route breaks at
|
|||
the arrow first, so the two ends of the flight stay whole and sit under one
|
||||
another where they read as a pair.
|
||||
|
||||
**A box that has to move swings there rather than jumping.** Two things make
|
||||
one move: an aircraft flies into the space its neighbour's box was using, or
|
||||
a new one arrives and claims it. Recomputing the layout every frame and
|
||||
drawing the answer means boxes teleport, and the eye reads a thing that
|
||||
teleports as a different thing — on a busy screen several do it at once.
|
||||
|
||||
So a box keeps the spot it has for as long as that spot still works, and is
|
||||
only moved when something genuinely takes it. On a real evening's log that is
|
||||
about a third as many moves as placing each box afresh every frame. The moves
|
||||
that are left are eased over about half a second, and the picture redraws at
|
||||
thirty frames a second for as long as anything is actually moving, dropping
|
||||
back to its usual five the moment everything has settled.
|
||||
|
||||
The spot a box is *heading for* is what the next box is laid out against, not
|
||||
the place it has got to so far — laying out against a box in mid-swing would
|
||||
move its neighbours too, and move them back when it arrived, and the screen
|
||||
would never settle. A box on the move is drawn last, over the ones standing
|
||||
still, so it stays readable while it crosses them. The box is remembered as an
|
||||
offset from its aircraft, so one crossing the window carries its box along
|
||||
without that counting as a move at all.
|
||||
|
||||
Thirty frames a second is affordable because **the ground is dimmed once and
|
||||
kept**. Cutting the view out of the fetched map, dimming it and looking every
|
||||
level up in the palette is about 70 ms over two megapixels, and none of it
|
||||
changes between one frame and the next unless the view, the window, the
|
||||
brightness or the map itself has. Doing it every frame put a ceiling of a
|
||||
dozen frames a second on the window at 1920×1080 and spent a whole core
|
||||
holding it there; keeping it takes the same window from 87 ms a frame to 14.
|
||||
|
||||
`d` cycles the detail — full box, just height and speed, or symbols alone —
|
||||
for when the sky is busy. `t` toggles trails, `g` the map underneath, `[`/`]`
|
||||
its brightness, `+`/`-` the range, `q` closes it.
|
||||
|
|
@ -1022,7 +1051,7 @@ losing their box as they go — a box at a tenth of its colour is something in
|
|||
the way of the aircraft still flying. One that has gone quiet stops being
|
||||
counted as overhead, since saying it is would be saying more than was heard.
|
||||
|
||||
The map holds still. It is fetched a third larger than the window in every
|
||||
The map holds still. It is fetched an eighth larger than the window in every
|
||||
direction, and the middle of the view settles once and then stays put rather
|
||||
than being recomputed as aircraft come and go — otherwise the view shifts by a
|
||||
fraction of a mile every few seconds, throws away the tiles fetched for the
|
||||
|
|
@ -1225,18 +1254,34 @@ Time runs at `--speed` seconds of flying per second of animation, or give
|
|||
high cold, with the key along the bottom; the trail behind each aircraft is the
|
||||
path it actually flew, in the colours of the heights it flew them at.
|
||||
|
||||
Beside each aircraft goes what is known about it — flight level and speed,
|
||||
type and registration, and the two ends of the route, each with **a small flag
|
||||
of the country the airport is in**:
|
||||
Beside each aircraft goes what is known about it — height and speed, what sort
|
||||
of aircraft it is, type and registration, and the two ends of the route, each
|
||||
with **a small flag of the country the airport is in**:
|
||||
|
||||
```
|
||||
PRIME04
|
||||
36,000 ft 493MPH
|
||||
[US] MILITARY HEAVY
|
||||
C17 90-0534
|
||||
```
|
||||
```
|
||||
BAW49
|
||||
330 552MPH
|
||||
33,000 ft 552MPH
|
||||
[GB] HEAVY
|
||||
B744 G-VROS
|
||||
[GB] EGLL
|
||||
[US] KSEA
|
||||
```
|
||||
|
||||
The height is in feet with the unit on it. It used to be the flight level —
|
||||
`330`, hundreds of feet, the way it is said on the radio — which is shorter
|
||||
and is what an aviator reads, but three digits beside an aircraft are only a
|
||||
height to somebody who already knows they are one. It is rounded to the
|
||||
nearest 25 ft, the step Mode S reports altitude in: a real reading is a
|
||||
multiple of that and comes through untouched, while a moment between two
|
||||
reports — which is most of the moments in an animation, since they are
|
||||
interpolated — stops claiming to know the aircraft's height to the foot.
|
||||
|
||||
The flags are twelve pixels by eight, drawn from a table in `flags.py` rather
|
||||
than fetched: at that size a flag is not a rendering of the real thing but the
|
||||
arrangement that makes one recognisable — the bands and where they run, the
|
||||
|
|
@ -1251,6 +1296,34 @@ The aircraft's own **country of registration** gets a flag too, beside the
|
|||
type and registration — from the register where one answered, and otherwise
|
||||
from the 24-bit address, which says by treaty who issued it.
|
||||
|
||||
### What sort of aircraft it is
|
||||
|
||||
`MILITARY HEAVY` above is two facts, joined only because both are known.
|
||||
|
||||
**What it is** comes off the air. Every identification message carries three
|
||||
bits under its type code saying what sort of thing is transmitting — light,
|
||||
small, large, high vortex, heavy, high performance, rotorcraft, and under a
|
||||
different type code glider, airship, parachutist, ultralight, drone,
|
||||
spacecraft, or a vehicle on the ground. It is the only word about what an
|
||||
aircraft *is* that needs no register at all. Which list the three bits index
|
||||
depends on the type code, so the same value means "heavy" in one message and
|
||||
"parachutist" in another. Zero means the aircraft declined to say, which is
|
||||
common and is answered with nothing rather than a guess.
|
||||
|
||||
**Whether it is military** comes off no air at all: no aircraft broadcasts it,
|
||||
and a tanker calls itself `heavy` exactly as an airliner does. It is read from
|
||||
the 24-bit address instead — states set aside blocks of their national range
|
||||
for their armed forces, and those blocks are published. Two honest limits: a
|
||||
state can fly a military aircraft on a civil address whenever it likes, so
|
||||
this finds nobody who does not want to be found; and the table here holds the
|
||||
allocations a receiver in the ordinary world actually hears rather than every
|
||||
one that exists.
|
||||
|
||||
Worth seeing the two agree. On one evening here, address `AE07D3` was in the
|
||||
United States military block and broadcast the category `heavy`; the register,
|
||||
asked separately and knowing nothing of either, came back with a C-17A
|
||||
Globemaster III, tail 90-0534, operated by the United States Air Force.
|
||||
|
||||
**Every aerodrome under the picture is marked**, not only the ones being flown
|
||||
between: a receiver hears aircraft over its own county, and the county's
|
||||
airports are what say where on the map you are looking. They come from the
|
||||
|
|
@ -1258,6 +1331,44 @@ same OpenStreetMap data the tiles are drawn from, asked as a question rather
|
|||
than a picture, once per area and kept for a month — a runway does not move.
|
||||
`--no-airports` turns it off.
|
||||
|
||||
They are drawn **magenta**, which nothing else on the picture is. The old
|
||||
amber sat 16 units of CIELAB from the altitude ramp's 12,000-foot yellow,
|
||||
which is to say it was the same colour: an aeroplane low over a field was
|
||||
drawn in the field's own colour and neither could be picked out from the
|
||||
other. The ramp already spends red, amber, green, cyan and violet on height;
|
||||
magenta is what it leaves free, it is 56 units away, and it is what an
|
||||
aeronautical chart marks an aerodrome in anyway. There is a test that states
|
||||
this as the property — how far the airport colour is from the nearest
|
||||
altitude colour — rather than as the colour, so that changing the ramp cannot
|
||||
quietly walk an aircraft back into the airports.
|
||||
|
||||
### Labels that stay where they are
|
||||
|
||||
The same two rules as the window, so the two look like the same program.
|
||||
|
||||
**A label keeps its place** for as long as that place still works, and is
|
||||
moved only when something genuinely takes it. Deciding afresh every frame
|
||||
means a label hops from one side of its aircraft to the other and back
|
||||
because the aeroplane two along moved a pixel — on a real evening's log that
|
||||
is about twice as many moves as keeping it. The place is remembered as an
|
||||
offset from the aircraft, so one crossing the picture carries its label along
|
||||
and only a real clash asks for a new spot.
|
||||
|
||||
**The moves that are left are eased** over about half a second of playback,
|
||||
not jumped. What the next label is laid out against is where a moving one is
|
||||
going, not where it has got to, since laying out against a label in mid-swing
|
||||
would move its neighbours too and move them back when it arrived. A still
|
||||
picture has no frame before it, so it places its labels exactly as it always
|
||||
did.
|
||||
|
||||
**The whole box fades with the aircraft.** The name always did, because it is
|
||||
drawn in the aircraft's own colour; the rows and the flag were fixed colours
|
||||
and stayed at full brightness on a label that was on its way out, which left
|
||||
the brightest thing on that part of the picture being the one aeroplane
|
||||
nothing had been heard from. An indexed picture cannot blend, so the row grey
|
||||
and all twelve flag colours have their own dimmed copies at each of the four
|
||||
fade steps.
|
||||
|
||||
The GIF is written here from first principles — a palette, an LZW stream, frame
|
||||
differencing with a transparent index — in the same spirit as the PNGs
|
||||
elsewhere, so nothing but numpy is needed to draw one. Where ffmpeg happens to
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ and transcribing speech.
|
|||
# 2026-08-21_02 is the second build made on the 21st. The revision is padded
|
||||
# to two digits so versions sort as text.
|
||||
VERSION_DATE = "2026-09-04"
|
||||
VERSION_REVISION = 9
|
||||
VERSION_REVISION = 10
|
||||
|
||||
__version__ = f"{VERSION_DATE}_{VERSION_REVISION:02d}"
|
||||
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@ import numpy as np
|
|||
__all__ = ["decode_adsb", "Frame", "Aircraft", "AircraftRegistry", "crc24",
|
||||
"ADSB_HZ", "SAMPLE_RATE", "PREAMBLE_US", "encode_identification",
|
||||
"encode_position", "encode_velocity", "modulate", "SimulatedSky",
|
||||
"VirtualAircraft", "default_sky"]
|
||||
"VirtualAircraft", "default_sky", "category_name",
|
||||
"EMITTER_CATEGORIES"]
|
||||
|
||||
ADSB_HZ = 1_090_000_000.0
|
||||
|
||||
|
|
@ -68,6 +69,35 @@ TYPE_NAMES = {
|
|||
}
|
||||
|
||||
|
||||
# The three bits under an identification message's type code say what sort
|
||||
# of thing is transmitting. Which list they index depends on the type code
|
||||
# -- the same three bits mean "heavy" under type 4 and "glider" under type 3
|
||||
# -- which is why this is a table of tables and not a table.
|
||||
#
|
||||
# This is the only word about what an aircraft *is* that comes off the air.
|
||||
# Everything else -- the model, the operator, the registration -- is a
|
||||
# lookup in somebody's database against the address. There is no category
|
||||
# for "military": that has to be read off the address block instead.
|
||||
EMITTER_CATEGORIES = {
|
||||
4: {1: "light", 2: "small", 3: "large", 4: "high vortex",
|
||||
5: "heavy", 6: "high performance", 7: "rotorcraft"},
|
||||
3: {1: "glider", 2: "airship", 3: "parachutist", 4: "ultralight",
|
||||
6: "drone", 7: "spacecraft"},
|
||||
2: {1: "emergency vehicle", 2: "service vehicle", 3: "obstacle",
|
||||
4: "obstacle", 5: "obstacle"},
|
||||
1: {}, # reserved, and nothing transmits it
|
||||
}
|
||||
|
||||
|
||||
def category_name(type_code: int, category: int) -> str:
|
||||
"""What an identification message says the transmitter is, or "".
|
||||
|
||||
Zero means the aircraft declined to say, which is common and is not an
|
||||
error: it is answered with nothing rather than with a guess.
|
||||
"""
|
||||
return EMITTER_CATEGORIES.get(type_code, {}).get(category, "")
|
||||
|
||||
|
||||
def crc24(data: bytes) -> int:
|
||||
"""The Mode S parity, polynomial 0xFFF409.
|
||||
|
||||
|
|
@ -99,6 +129,7 @@ class Frame:
|
|||
df: int = 0 # downlink format
|
||||
icao: str = "" # the aircraft's permanent 24-bit address
|
||||
type_code: int = 0
|
||||
category: int = 0 # the emitter category, with the type code
|
||||
at_sample: int = 0
|
||||
callsign: str = ""
|
||||
altitude_ft: int = 0
|
||||
|
|
@ -277,6 +308,10 @@ def _read(bits: str, data: bytes) -> Frame:
|
|||
frame.type_code = int(me[:5], 2)
|
||||
if 1 <= frame.type_code <= 4:
|
||||
frame.callsign = _callsign(me)
|
||||
# The three bits under the type code say what sort of thing this is
|
||||
# -- heavy, rotorcraft, glider, ground vehicle. It comes off the
|
||||
# air with the callsign and costs nothing to keep.
|
||||
frame.category = int(me[5:8], 2)
|
||||
elif 9 <= frame.type_code <= 18 or 20 <= frame.type_code <= 22:
|
||||
frame.altitude_ft = _altitude(me)
|
||||
frame.cpr_odd = me[21] == "1"
|
||||
|
|
@ -392,6 +427,7 @@ class Aircraft:
|
|||
track_deg: float = 0.0
|
||||
vertical_rate_fpm: int = 0
|
||||
messages: int = 0
|
||||
category: str = "" # what it said it was: heavy, rotorcraft...
|
||||
first_seen: float = 0.0
|
||||
last_seen: float = 0.0
|
||||
_even: Frame | None = field(default=None, repr=False)
|
||||
|
|
@ -440,6 +476,8 @@ class AircraftRegistry:
|
|||
frame.received_at = when
|
||||
if frame.callsign:
|
||||
seen.callsign = frame.callsign
|
||||
if frame.category and not seen.category:
|
||||
seen.category = category_name(frame.type_code, frame.category)
|
||||
if frame.altitude_ft:
|
||||
seen.altitude_ft = frame.altitude_ft
|
||||
if frame.ground_speed_kt:
|
||||
|
|
|
|||
|
|
@ -322,6 +322,14 @@ class Track:
|
|||
first_seen: float = 0.0
|
||||
last_seen: float = 0.0
|
||||
altitudes: list[tuple[float, int]] = field(default_factory=list)
|
||||
category: str = "" # what it said it was: heavy, rotorcraft...
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
"""What sort of aircraft this is, as far as can be told."""
|
||||
from .flights import aircraft_class
|
||||
|
||||
return aircraft_class(self.icao, self.category)
|
||||
|
||||
@property
|
||||
def located(self) -> bool:
|
||||
|
|
@ -561,6 +569,13 @@ def read_logs(paths) -> list[Track]:
|
|||
track.last_seen = max(track.last_seen, when)
|
||||
if line.get("callsign"):
|
||||
track.callsign = str(line["callsign"])
|
||||
# Read back out of the frame rather than stored beside it. The
|
||||
# three bits are in the identification message that is already
|
||||
# written down in full, so every log ever written by this
|
||||
# program has them, including the ones written before anything
|
||||
# here knew to look.
|
||||
if not track.category:
|
||||
track.category = _category_of(line)
|
||||
if line.get("alt_ft"):
|
||||
track.altitudes.append((when, int(line["alt_ft"])))
|
||||
# What it last said about itself, from whichever frame said it.
|
||||
|
|
@ -597,6 +612,22 @@ def read_logs(paths) -> list[Track]:
|
|||
return sorted(tracks.values(), key=lambda t: (t.first_seen, t.icao))
|
||||
|
||||
|
||||
def _category_of(line: dict) -> str:
|
||||
"""The emitter category out of a logged identification frame."""
|
||||
try:
|
||||
type_code = int(line.get("tc") or 0)
|
||||
if not 1 <= type_code <= 4:
|
||||
return ""
|
||||
raw = str(line.get("hex") or "")
|
||||
if len(raw) < 10:
|
||||
return ""
|
||||
from .adsb import category_name
|
||||
|
||||
return category_name(type_code, int(raw[8:10], 16) & 0x07)
|
||||
except (TypeError, ValueError):
|
||||
return ""
|
||||
|
||||
|
||||
def _lines(path: Path):
|
||||
try:
|
||||
with path.open(encoding="utf8") as handle:
|
||||
|
|
@ -691,6 +722,11 @@ def report(tracks: list[Track], book=None, title: str = "",
|
|||
out.append(f" {line}")
|
||||
if entry.country and not entry.owner_country:
|
||||
out.append(f" registered in: {entry.country}")
|
||||
# What sort of aircraft it is, which is the one thing here that the
|
||||
# aeroplane said about itself rather than a register saying it.
|
||||
if track.kind:
|
||||
out.append(f" class: {track.kind}")
|
||||
if entry is not None:
|
||||
if entry.route:
|
||||
out.append(f" route: {entry.route}{_doubtful(entry, track)}")
|
||||
out.append(f" heard: {_clock(track.first_seen)} to "
|
||||
|
|
|
|||
|
|
@ -61,6 +61,12 @@ OLD = TRAIL + 32 # and dimmer still, for the path flown earlier
|
|||
GROUND = OLD + 32 # 32 shades of the map underneath
|
||||
FLAG = GROUND + 32 # the dozen colours the little flags are made of
|
||||
FAINT = FLAG + 12 # the same 32 again, fainter still, for fading
|
||||
# A fading aircraft's box has to fade with it. An indexed picture cannot
|
||||
# blend, so everything the box is made of needs its own dimmed copies: the
|
||||
# grey the rows are written in, and the flag colours, at the same three
|
||||
# steps the aircraft itself fades through.
|
||||
LABEL_INK = FAINT + 32 # the row grey, at the four strengths
|
||||
FLAG_FADED = LABEL_INK + 4 # three dimmer sets of the twelve flag colours
|
||||
RAMP_STEPS = 32
|
||||
GROUND_SHADES = 32
|
||||
TRANSPARENT = 255 # never drawn with: it means "as the frame before"
|
||||
|
|
@ -79,12 +85,20 @@ CROWDED = 14
|
|||
# opening.
|
||||
MAX_FRAMES = 3000
|
||||
|
||||
# The airport colour is chosen to be as far from every altitude colour as a
|
||||
# colour can be. The old amber sat 16 units of CIELAB from the ramp's
|
||||
# 12,000-foot yellow, which is to say it was the same colour: an aeroplane
|
||||
# low over a field was drawn in the field's own colour, and neither could be
|
||||
# picked out from the other. Magenta is 56 units away, further than any
|
||||
# other hue the ramp leaves free -- the ramp already spends red, amber,
|
||||
# green, cyan and violet on height -- and it is what an aeronautical chart
|
||||
# marks an aerodrome in anyway.
|
||||
_FIXED = ((14, 16, 22), # background: night, not black
|
||||
(38, 44, 58), # grid
|
||||
(196, 204, 218), # ink
|
||||
(120, 130, 148), # dim ink
|
||||
(24, 28, 38), # panel
|
||||
(230, 170, 90), # airports
|
||||
(255, 64, 200), # airports: magenta, and nothing else is
|
||||
(70, 84, 110), # route lines
|
||||
(255, 255, 255)) # white
|
||||
|
||||
|
|
@ -147,17 +161,42 @@ def _flag_colours() -> list[tuple[int, int, int]]:
|
|||
return [COLOURS[letter] for letter in COLOUR_ORDER]
|
||||
|
||||
|
||||
def flag_index(letter: str) -> int:
|
||||
"""Where one of the flag colours lives in the palette."""
|
||||
def flag_index(letter: str, level: int = 0) -> int:
|
||||
"""Where one of the flag colours lives in the palette.
|
||||
|
||||
``level`` is how far the aircraft has faded, 0 for full strength.
|
||||
"""
|
||||
from .flags import COLOUR_ORDER
|
||||
|
||||
return FLAG + COLOUR_ORDER.index(letter)
|
||||
place = COLOUR_ORDER.index(letter)
|
||||
if level <= 0:
|
||||
return FLAG + place
|
||||
return FLAG_FADED + (min(level, 3) - 1) * len(COLOUR_ORDER) + place
|
||||
|
||||
|
||||
def fade_level(strength: float) -> int:
|
||||
"""How far a thing at this strength has faded: 0 full, 3 nearly gone."""
|
||||
for level, (above, _base) in enumerate(FADE_STEPS):
|
||||
if strength > above:
|
||||
return level
|
||||
return len(FADE_STEPS) - 1
|
||||
|
||||
|
||||
# What each fade step multiplies a colour by. The first is the aircraft at
|
||||
# full strength and is not dimmed at all.
|
||||
FADE_FACTORS = (1.0, 0.55, 0.30, 0.14)
|
||||
|
||||
|
||||
def _palette() -> np.ndarray:
|
||||
ramp = _ramp()
|
||||
flags = _flag_colours()
|
||||
table = (list(_FIXED) + ramp + _dimmed(ramp, 0.55) + _dimmed(ramp, 0.30)
|
||||
+ _ground_shades() + _flag_colours() + _dimmed(ramp, 0.14))
|
||||
+ _ground_shades() + flags + _dimmed(ramp, 0.14)
|
||||
# The row grey and then the flags, dimmed the same way the
|
||||
# aircraft above them is, so that a whole label fades together.
|
||||
+ [_dimmed([_FIXED[DIM]], factor)[0] for factor in FADE_FACTORS])
|
||||
for factor in FADE_FACTORS[1:]:
|
||||
table += _dimmed(flags, factor)
|
||||
table += [(0, 0, 0)] * (256 - len(table))
|
||||
return np.array(table[:256], dtype=np.uint8)
|
||||
|
||||
|
|
@ -504,12 +543,105 @@ def _key(img: np.ndarray, view: Projection) -> None:
|
|||
# One frame
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# How long a label takes to swing across when it has to move, in seconds of
|
||||
# the animation as it plays. The same half-second the window uses, so the
|
||||
# two look like the same program.
|
||||
LABEL_GLIDE = 0.45
|
||||
|
||||
|
||||
class LabelPlaces:
|
||||
"""Where each aircraft's label is, and where it is going.
|
||||
|
||||
A frame on its own has no reason to put a label anywhere in particular,
|
||||
and the placer is happy to answer differently on the next one -- so a
|
||||
label hops from one side of its aircraft to the other and back as the
|
||||
aeroplane two along moves a pixel. Watching that is worse than reading
|
||||
a label in an awkward place.
|
||||
|
||||
So the same rule the window uses: a label keeps the spot it has for as
|
||||
long as that spot still works, and the moves that are left are eased
|
||||
rather than jumped. Kept as an offset from the aircraft, so one
|
||||
crossing the picture carries its label with it and only a real clash
|
||||
asks for a new place.
|
||||
"""
|
||||
|
||||
def __init__(self, glide: float = LABEL_GLIDE):
|
||||
self.glide = glide
|
||||
self.want: dict[str, tuple[int, int]] = {}
|
||||
self.at: dict[str, tuple[float, float]] = {}
|
||||
self._seen: set[str] = set()
|
||||
|
||||
def begin(self) -> None:
|
||||
self._seen = set()
|
||||
|
||||
def end(self) -> None:
|
||||
"""Forget the labels that were not drawn this time.
|
||||
|
||||
An aircraft that has gone must not glide in from where it stood
|
||||
half an hour ago when it comes back.
|
||||
"""
|
||||
for gone in set(self.at) - self._seen:
|
||||
self.at.pop(gone, None)
|
||||
self.want.pop(gone, None)
|
||||
|
||||
def kept(self, icao: str, x: int, y: int, fits):
|
||||
"""The spot this label already holds, if it still works.
|
||||
|
||||
``fits`` is asked whether a place is free and returns it, or None.
|
||||
A label is only sent looking for somewhere new when the place it has
|
||||
has actually been taken.
|
||||
"""
|
||||
self._seen.add(icao)
|
||||
held = self.want.get(icao)
|
||||
if held is None:
|
||||
return None
|
||||
return fits(x + held[0], y + held[1])
|
||||
|
||||
def settle(self, icao: str, x: int, y: int, spot) -> tuple[int, int]:
|
||||
"""Remember where this label belongs, and say where to draw it."""
|
||||
self._seen.add(icao)
|
||||
self.want[icao] = (spot[0] - x, spot[1] - y)
|
||||
return spot
|
||||
|
||||
def drawn(self, icao: str, x: int, y: int, spot,
|
||||
step: float) -> tuple[int, int]:
|
||||
"""Where the label actually goes this frame, on its way to `spot`."""
|
||||
target = (float(spot[0] - x), float(spot[1] - y))
|
||||
here = self.at.get(icao)
|
||||
if here is None: # first sight: no swing to make
|
||||
self.at[icao] = target
|
||||
return spot
|
||||
here = _glide(here, target, step, self.glide)
|
||||
self.at[icao] = here
|
||||
return int(round(x + here[0])), int(round(y + here[1]))
|
||||
|
||||
|
||||
def _glide(current, target, elapsed: float, seconds: float):
|
||||
"""One step of a label on its way to where it now belongs.
|
||||
|
||||
Eased by the distance left rather than by a count of frames, so the
|
||||
swing takes the same time whatever the frame rate is set to.
|
||||
"""
|
||||
cx, cy = current
|
||||
tx, ty = target
|
||||
if seconds <= 0.0:
|
||||
return (float(tx), float(ty))
|
||||
if elapsed <= 0.0:
|
||||
return (float(cx), float(cy))
|
||||
part = 1.0 - math.exp(-3.0 * elapsed / seconds)
|
||||
nx, ny = cx + (tx - cx) * part, cy + (ty - cy) * part
|
||||
if abs(tx - nx) < 0.4 and abs(ty - ny) < 0.4:
|
||||
return (float(tx), float(ty))
|
||||
return (nx, ny)
|
||||
|
||||
|
||||
def render_frame(base: np.ndarray, view: Projection, tracks: list[Track],
|
||||
when: float, *, trail_seconds: float = 0.0,
|
||||
stale: float = 300.0, labels: bool = True,
|
||||
clock: str = "", unit: str = DEFAULT_SPEED_UNIT,
|
||||
project: bool = True, known=None,
|
||||
fade: float = 0.0) -> np.ndarray:
|
||||
fade: float = 0.0, places: "LabelPlaces | None" = None,
|
||||
step: float = 0.0) -> np.ndarray:
|
||||
"""The map at one moment: where everything was, and where it had been.
|
||||
|
||||
``project`` is what makes an animation an animation: between reports an
|
||||
|
|
@ -526,6 +658,8 @@ def render_frame(base: np.ndarray, view: Projection, tracks: list[Track],
|
|||
crowded = sum(1 for track in tracks
|
||||
if track.at(when, stale=stale) is not None) > CROWDED
|
||||
taken: list[tuple[int, int, int, int]] = []
|
||||
if places is not None:
|
||||
places.begin()
|
||||
for track in tracks:
|
||||
if project:
|
||||
seen = showing(track, when, stale, fade)
|
||||
|
|
@ -554,7 +688,11 @@ def render_frame(base: np.ndarray, view: Projection, tracks: list[Track],
|
|||
if labels and strength > LABEL_WHILE:
|
||||
_label(img, x, y, track, now, colour, taken, unit,
|
||||
entry=(known.get(track.icao)
|
||||
if known and not crowded else None))
|
||||
if known and not crowded else None),
|
||||
places=places, step=step, strength=strength,
|
||||
brief=crowded)
|
||||
if places is not None:
|
||||
places.end()
|
||||
if clock:
|
||||
_clock_strip(img, view, clock, flying)
|
||||
return img
|
||||
|
|
@ -615,20 +753,28 @@ def _marker(img: np.ndarray, x: int, y: int, heading: float,
|
|||
|
||||
|
||||
def label_lines(track: Track, now, unit: str = DEFAULT_SPEED_UNIT,
|
||||
entry=None) -> list[tuple[str, str]]:
|
||||
entry=None, brief: bool = False) -> list[tuple[str, str]]:
|
||||
"""What goes beside one aircraft, a line at a time.
|
||||
|
||||
Each row is the text and the country whose flag belongs next to it -- a
|
||||
two-letter code the drawing turns into twelve pixels of one, or empty for
|
||||
a row that is only words.
|
||||
|
||||
The height is the flight level, hundreds of feet, the way it is said on
|
||||
the radio: five digits beside every aircraft is a picture made of
|
||||
numbers. The airports are their codes for the same reason, since a full
|
||||
name runs to forty characters beside an aircraft twelve pixels across.
|
||||
The height is in feet with its unit on it. It used to be the flight
|
||||
level, hundreds of feet the way it is said on the radio, which is shorter
|
||||
and is what an aviator reads -- but "376" beside an aircraft is only a
|
||||
height to somebody who already knows it is one. The airports stay as
|
||||
their codes, since a full name runs to forty characters beside an
|
||||
aircraft twelve pixels across.
|
||||
"""
|
||||
rows: list[tuple[str, str]] = []
|
||||
height = f"{now.altitude_ft // 100:03d}" if now.altitude_ft else ""
|
||||
# To the nearest twenty-five feet, which is the step Mode S reports
|
||||
# altitude in: a real reading is a multiple of it and comes through
|
||||
# untouched, while a moment between two reports -- which is interpolated,
|
||||
# and is most of the moments in an animation -- stops claiming to know
|
||||
# the aircraft's height to the foot.
|
||||
height = (f"{round(now.altitude_ft / 25) * 25:,} ft"
|
||||
if now.altitude_ft else "")
|
||||
# The unit goes on the number, every time: a bare "480" beside an
|
||||
# aircraft is three different speeds depending on who is reading it.
|
||||
speed = (f"{in_speed(now.ground_speed_kt, unit):.0f}"
|
||||
|
|
@ -636,17 +782,39 @@ def label_lines(track: Track, now, unit: str = DEFAULT_SPEED_UNIT,
|
|||
line = " ".join(x for x in (height, speed) if x)
|
||||
if line:
|
||||
rows.append((line, ""))
|
||||
if entry is None:
|
||||
if brief:
|
||||
# A crowded picture: the height and the speed and nothing else. A
|
||||
# flag and a class beside each of three hundred aircraft is not more
|
||||
# information, it is a page of small pictures with a map behind it.
|
||||
return rows
|
||||
from .flags import iso_for
|
||||
from .flights import aircraft_class, describe_address
|
||||
|
||||
# The country of registration, off the address block, so it is there for
|
||||
# an aircraft no register has ever heard of. Taking it from the
|
||||
# register's answer instead left the flag off exactly the aircraft that
|
||||
# had nothing else beside them either.
|
||||
home = iso_for(getattr(entry, "owner_country", "")
|
||||
or getattr(entry, "country", ""))
|
||||
or getattr(entry, "country", "")
|
||||
or describe_address(track.icao))
|
||||
# What sort of aircraft it is: what it broadcast about itself, and
|
||||
# whether its address is a military one.
|
||||
kind_of = aircraft_class(track.icao, getattr(track, "category", ""))
|
||||
if kind_of:
|
||||
rows.append((kind_of, home))
|
||||
if entry is None:
|
||||
# Nothing but the flag left to say, and it is worth a row of its
|
||||
# own: it says where the aeroplane is from, which is more than the
|
||||
# rest of an unknown aircraft's box says put together.
|
||||
if home and not kind_of:
|
||||
rows.append(("", home))
|
||||
return rows
|
||||
kind = entry.type_code or entry.model
|
||||
if kind and entry.registration:
|
||||
rows.append((f"{kind} {entry.registration}", home))
|
||||
elif kind or entry.registration:
|
||||
rows.append((kind or entry.registration, home))
|
||||
identity = " ".join(x for x in (kind, entry.registration) if x)
|
||||
if identity:
|
||||
rows.append((identity, "" if kind_of else home))
|
||||
elif home and not kind_of:
|
||||
rows.append(("", home))
|
||||
# Only when the aircraft could actually be flying it. A callsign is a
|
||||
# flight number and an airline runs the same number over several legs in
|
||||
# a day, so a register's one route for it is quite often somebody else's
|
||||
|
|
@ -674,7 +842,9 @@ def _short_place(code: str, name: str) -> str:
|
|||
|
||||
def _label(img: np.ndarray, x: int, y: int, track: Track, now,
|
||||
colour: int, taken: list | None = None,
|
||||
unit: str = DEFAULT_SPEED_UNIT, entry=None) -> None:
|
||||
unit: str = DEFAULT_SPEED_UNIT, entry=None,
|
||||
places: "LabelPlaces | None" = None, step: float = 0.0,
|
||||
strength: float = 1.0, brief: bool = False) -> None:
|
||||
"""Who it is, and everything else known about it, beside the aircraft.
|
||||
|
||||
Two aircraft that pass close together would otherwise have their labels
|
||||
|
|
@ -682,11 +852,16 @@ def _label(img: np.ndarray, x: int, y: int, track: Track, now,
|
|||
at that part of the picture. So the four places a label can go are tried
|
||||
in turn and the first clear one is used; when they are all taken the
|
||||
label goes to the right anyway, because a label somewhere beats none.
|
||||
|
||||
``places`` carries what was decided on the frame before, so that a label
|
||||
keeps its spot instead of being re-decided from nothing every frame, and
|
||||
swings to a new one rather than jumping. Without it -- a still picture,
|
||||
where there is no frame before -- the placing is exactly as it was.
|
||||
"""
|
||||
from .flags import FLAG_W
|
||||
|
||||
height, width = img.shape
|
||||
rows = label_lines(track, now, unit, entry)
|
||||
rows = label_lines(track, now, unit, entry, brief=brief)
|
||||
indent = FLAG_W + 3 if any(country for _, country in rows) else 0
|
||||
span = max([text_width(track.name)]
|
||||
+ [indent + text_width(text) for text, _ in rows])
|
||||
|
|
@ -705,8 +880,12 @@ def _label(img: np.ndarray, x: int, y: int, track: Track, now,
|
|||
(x - 8 - span, y - GLYPH_H - 1), # left
|
||||
(x - span // 2, y + 9), # under it
|
||||
(x - span // 2, y - tall - 6)) # over it
|
||||
found = next((spot for spot in map(lambda p: clear(*p), beside) if spot),
|
||||
None)
|
||||
# The place it had, first of all, and only if something has taken it is
|
||||
# anywhere else considered.
|
||||
found = None if places is None else places.kept(track.icao, x, y, clear)
|
||||
if found is None:
|
||||
found = next((spot for spot in map(lambda p: clear(*p), beside)
|
||||
if spot), None)
|
||||
if found is None:
|
||||
# The four places beside it are taken, which happens as soon as a few
|
||||
# aircraft are close together. Working outwards buys a readable
|
||||
|
|
@ -723,18 +902,33 @@ def _label(img: np.ndarray, x: int, y: int, track: Track, now,
|
|||
left, top = found if found else beside[0]
|
||||
left = max(2, min(int(left), width - 2 - span))
|
||||
top = max(1, min(int(top), height - 1 - tall))
|
||||
# What is spoken for is where the label is settling, not where it has
|
||||
# got to: laying the next one out against a label in mid-swing would
|
||||
# move that one as well, and move it back when the first arrived.
|
||||
if taken is not None:
|
||||
taken.append((left, top, left + span, top + tall))
|
||||
if places is not None:
|
||||
places.settle(track.icao, x, y, (left, top))
|
||||
left, top = places.drawn(track.icao, x, y, (left, top), step)
|
||||
left = max(2, min(left, width - 2 - span))
|
||||
top = max(1, min(top, height - 1 - tall))
|
||||
# The box fades with the aircraft: the name already did, because it is
|
||||
# drawn in the aircraft's own colour, but the rows and the flag were
|
||||
# fixed colours and stayed at full brightness on a label that was on its
|
||||
# way out -- which left the brightest thing on that part of the picture
|
||||
# being the one aeroplane nothing had been heard from.
|
||||
level = fade_level(strength)
|
||||
draw_text(img, left, top, track.name, colour)
|
||||
at = top + GLYPH_H + 2
|
||||
for text, country in rows:
|
||||
if country:
|
||||
draw_flag(img, left, at - 1, country)
|
||||
draw_text(img, left + indent, at, text, DIM)
|
||||
draw_flag(img, left, at - 1, country, level)
|
||||
draw_text(img, left + indent, at, text, LABEL_INK + level)
|
||||
at += GLYPH_H + 2
|
||||
|
||||
|
||||
def draw_flag(img: np.ndarray, x: int, y: int, country: str) -> None:
|
||||
def draw_flag(img: np.ndarray, x: int, y: int, country: str,
|
||||
level: int = 0) -> None:
|
||||
"""Twelve pixels by eight of a flag, or the country's letters instead.
|
||||
|
||||
A country with no flag here is named rather than approximated: two
|
||||
|
|
@ -745,7 +939,8 @@ def draw_flag(img: np.ndarray, x: int, y: int, country: str) -> None:
|
|||
|
||||
rows = flag_for(country)
|
||||
if rows is None:
|
||||
draw_text(img, x, y + 1, country[:2].upper(), GRID)
|
||||
draw_text(img, x, y + 1, country[:2].upper(),
|
||||
GRID if level <= 0 else LABEL_INK + min(level, 3))
|
||||
return
|
||||
height, width = img.shape
|
||||
for row, line in enumerate(rows):
|
||||
|
|
@ -755,7 +950,7 @@ def draw_flag(img: np.ndarray, x: int, y: int, country: str) -> None:
|
|||
for column, letter in enumerate(line[:FLAG_W]):
|
||||
xx = x + column
|
||||
if 0 <= xx < width:
|
||||
img[yy, xx] = flag_index(letter)
|
||||
img[yy, xx] = flag_index(letter, level)
|
||||
|
||||
|
||||
def _overlaps(a, b) -> bool:
|
||||
|
|
@ -1149,6 +1344,14 @@ def animate(tracks: list[Track], out_path, *, fps: float = 12.0,
|
|||
base = _pad_to(base, canvas_w, canvas_h)
|
||||
|
||||
def frames():
|
||||
# One of these for the whole run: it is what remembers where each
|
||||
# label was on the frame before, so a label can keep its place and
|
||||
# swing to a new one instead of being re-decided from nothing. The
|
||||
# step is a frame of the animation as it plays, not of the flying,
|
||||
# so the swing takes half a second to watch however fast the evening
|
||||
# is being run through.
|
||||
places = LabelPlaces()
|
||||
step = 1.0 / fps if fps else 0.0
|
||||
for i in range(frame_count):
|
||||
when = start + i * speed / fps
|
||||
clock = datetime.fromtimestamp(when).strftime("%H:%M:%S")
|
||||
|
|
@ -1156,7 +1359,7 @@ def animate(tracks: list[Track], out_path, *, fps: float = 12.0,
|
|||
trail_seconds=trail_seconds,
|
||||
stale=stale, labels=labels,
|
||||
clock=clock, unit=unit, known=known,
|
||||
fade=fade),
|
||||
fade=fade, places=places, step=step),
|
||||
canvas_w, canvas_h)
|
||||
|
||||
path = Path(out_path)
|
||||
|
|
|
|||
|
|
@ -32,7 +32,8 @@ from pathlib import Path
|
|||
|
||||
__all__ = ["Flight", "FlightBook", "describe_address", "airline_of",
|
||||
"route_fits", "ROUTE_SLACK_NM",
|
||||
"AIRCRAFT_URL", "ROUTE_URL", "CACHE_VERSION"]
|
||||
"AIRCRAFT_URL", "ROUTE_URL", "CACHE_VERSION",
|
||||
"MILITARY_BLOCKS", "is_military", "aircraft_class"]
|
||||
|
||||
AIRCRAFT_URL = "https://api.adsbdb.com/v0/aircraft/{icao}"
|
||||
ROUTE_URL = "https://api.adsbdb.com/v0/callsign/{call}"
|
||||
|
|
@ -193,6 +194,12 @@ ADDRESS_BLOCKS: tuple[tuple[int, int, str], ...] = (
|
|||
(0x902000, 0x9023FF, "Fiji"),
|
||||
(0x905000, 0x9053FF, "Tonga"),
|
||||
(0x907000, 0x9073FF, "Vanuatu"),
|
||||
# Mexico was missing, and a receiver anywhere in the American southwest
|
||||
# hears Mexican aircraft all evening. Two registers independently give
|
||||
# XA- registrations for addresses in this block -- XA-SPO and XA-VRW
|
||||
# were the ones that turned up here -- which is what an aircraft
|
||||
# registered in Mexico wears.
|
||||
(0x0D0000, 0x0D7FFF, "Mexico"),
|
||||
(0xA00000, 0xAFFFFF, "United States"),
|
||||
(0xC00000, 0xC3FFFF, "Canada"),
|
||||
(0xC80000, 0xC87FFF, "New Zealand"),
|
||||
|
|
@ -407,6 +414,40 @@ class Flight:
|
|||
# How far off a route an aircraft may be before it is decided that it cannot
|
||||
# be flying it. Generous: an aircraft holds, diverts around weather and gets
|
||||
# vectored, and none of that is a wrong route.
|
||||
def is_military(icao: str) -> bool:
|
||||
"""Whether this address sits in a block set aside for armed forces.
|
||||
|
||||
The blocks are the ones named above, so this and the country an address
|
||||
is described with can never disagree.
|
||||
|
||||
Two honest limits. A state can fly a military aircraft on a civil
|
||||
address whenever it likes, so this finds nobody who does not want to be
|
||||
found; and it says nothing about the twenty or so smaller allocations
|
||||
the table above leaves out on purpose. It is a reading of the address,
|
||||
and is worth exactly what that is.
|
||||
"""
|
||||
try:
|
||||
value = int(str(icao), 16)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return any(low <= value <= high for low, high, _name in MILITARY_BLOCKS)
|
||||
|
||||
|
||||
def aircraft_class(icao: str, category: str = "") -> str:
|
||||
"""What sort of aircraft this is, in as few words as say it.
|
||||
|
||||
Two different facts, joined only when both are known: what the aeroplane
|
||||
says it is -- heavy, rotorcraft, glider -- which comes off the air in
|
||||
every identification message, and whether its address is a military one,
|
||||
which does not come off the air at all. A tanker broadcasts "heavy"
|
||||
exactly as an airliner does, and its address is the only thing that says
|
||||
whose it is; "military heavy" is both of those facts and not a third one
|
||||
made up out of them.
|
||||
"""
|
||||
return " ".join(x for x in ("military" if is_military(icao) else "",
|
||||
category) if x)
|
||||
|
||||
|
||||
ROUTE_SLACK_NM = 150.0
|
||||
ROUTE_SLACK_PART = 0.5
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,8 @@ from .ui import compass
|
|||
# so that importing it costs nothing on a machine with no Qt on it, and so
|
||||
# they cannot be listed here.
|
||||
__all__ = ["available", "binding", "show", "fetch_ground", "Sky", "Blip",
|
||||
"blip_for", "place_box", "wrap_value", "WRAP_CHARS", "MISSING_QT"]
|
||||
"blip_for", "place_box", "glide", "wrap_value", "WRAP_CHARS",
|
||||
"MISSING_QT"]
|
||||
|
||||
BINDINGS = ("PyQt6", "PyQt5", "PySide6", "PySide2")
|
||||
|
||||
|
|
@ -82,6 +83,16 @@ FLAG_PIXELS = 12
|
|||
# Below this an aircraft keeps its symbol and loses its box.
|
||||
LABEL_WHILE = 0.40
|
||||
|
||||
# How long a box takes to swing across when it has to move, and how often to
|
||||
# repaint while one is on its way. The ordinary redraw is five times a
|
||||
# second, which is plenty for aeroplanes -- they move a pixel or two between
|
||||
# frames -- but a box crossing the window in five steps is a slideshow, so
|
||||
# the picture is redrawn faster for as long as anything is actually moving
|
||||
# and drops back to the slow rate the moment everything has settled.
|
||||
BOX_GLIDE = 0.45
|
||||
BOX_GLIDE_MS = 33
|
||||
BOX_SETTLED_PX = 0.4
|
||||
|
||||
|
||||
def _alpha(strength: float) -> int:
|
||||
"""How opaque something at this strength is drawn."""
|
||||
|
|
@ -149,6 +160,7 @@ class Blip:
|
|||
track_deg: float = 0.0
|
||||
vertical_rate_fpm: int = 0
|
||||
messages: int = 0
|
||||
category: str = "" # what it said it was: heavy, rotorcraft...
|
||||
first_seen: float = 0.0
|
||||
last_seen: float = 0.0
|
||||
# Everything below comes from a register rather than off the air.
|
||||
|
|
@ -186,6 +198,14 @@ class Blip:
|
|||
that never fill in.
|
||||
"""
|
||||
out: list[tuple[str, str, str]] = []
|
||||
# What sort of aircraft it is: the emitter category, which came off
|
||||
# the air with the callsign, and whether the address is a military
|
||||
# one, which comes off no air at all.
|
||||
from .flights import aircraft_class
|
||||
|
||||
sort_of = aircraft_class(self.icao, self.category)
|
||||
if sort_of:
|
||||
out.append(("class", sort_of, ""))
|
||||
kind = " ".join(x for x in (self.manufacturer, self.model) if x)
|
||||
if self.type_code and self.registration:
|
||||
out.append((self.type_code, self.registration, ""))
|
||||
|
|
@ -282,7 +302,8 @@ def blip_for(craft, entry=None) -> Blip:
|
|||
track_deg=craft.track_deg,
|
||||
vertical_rate_fpm=craft.vertical_rate_fpm,
|
||||
messages=craft.messages, first_seen=craft.first_seen,
|
||||
last_seen=craft.last_seen)
|
||||
last_seen=craft.last_seen,
|
||||
category=getattr(craft, "category", ""))
|
||||
if entry is not None:
|
||||
blip.registration = entry.registration
|
||||
blip.type_code = entry.type_code
|
||||
|
|
@ -342,6 +363,7 @@ class Sky:
|
|||
self._ground = None
|
||||
self._ground_for = None
|
||||
self._ground_box = None
|
||||
self._ground_serial = 0
|
||||
self._wanted = None
|
||||
self._settled = None
|
||||
|
||||
|
|
@ -368,9 +390,18 @@ class Sky:
|
|||
with self._lock:
|
||||
self._ground, self._ground_for = levels, key
|
||||
self._ground_box = box
|
||||
# Counted rather than compared: the drawing side keeps the
|
||||
# dimmed pixels it made last time, and needs to know whether
|
||||
# what it made them from is still the same map.
|
||||
self._ground_serial += 1
|
||||
if self._wanted is not None and self._wanted[0] == key:
|
||||
self._wanted = None
|
||||
|
||||
def ground_serial(self) -> int:
|
||||
"""Which map is in hand. Changes whenever a new one is fetched."""
|
||||
with self._lock:
|
||||
return self._ground_serial
|
||||
|
||||
def want_ground(self, key, box, size) -> None:
|
||||
"""Say which map is needed. Painting must never wait on a network."""
|
||||
with self._lock:
|
||||
|
|
@ -476,6 +507,37 @@ def _clear(bx: int, by: int, width: int, height: int, taken: list) -> bool:
|
|||
and by < t[1] + t[3] and t[1] < by + height for t in taken)
|
||||
|
||||
|
||||
def glide(current: tuple[float, float], target: tuple[float, float],
|
||||
elapsed: float, seconds: float = BOX_GLIDE) -> tuple[float, float]:
|
||||
"""One step of a box on its way to where it now belongs.
|
||||
|
||||
Boxes are placed afresh every frame, so a box whose spot has been taken
|
||||
by something else jumps to its new one between one frame and the next.
|
||||
The jump is the problem: the eye reads a thing that teleports as a
|
||||
different thing, and on a busy screen several of them teleport at once.
|
||||
Easing it means the same box is still the same box, and the movement
|
||||
itself says that something moved rather than appeared.
|
||||
|
||||
Eased by the distance left rather than by a count of frames, so it is
|
||||
the same swing whatever the redraw rate is doing, and so a window that
|
||||
was buried under another for ten seconds does not spend the next half
|
||||
second replaying moves nobody watched: a long enough gap arrives.
|
||||
"""
|
||||
cx, cy = current
|
||||
tx, ty = target
|
||||
if seconds <= 0.0:
|
||||
return (float(tx), float(ty))
|
||||
if elapsed <= 0.0:
|
||||
return (float(cx), float(cy))
|
||||
# Three time constants, so `seconds` is most of the way there rather
|
||||
# than a fraction of the way there.
|
||||
part = 1.0 - math.exp(-3.0 * elapsed / seconds)
|
||||
nx, ny = cx + (tx - cx) * part, cy + (ty - cy) * part
|
||||
if abs(tx - nx) < BOX_SETTLED_PX and abs(ty - ny) < BOX_SETTLED_PX:
|
||||
return (float(tx), float(ty)) # arrived; stop asking for frames
|
||||
return (nx, ny)
|
||||
|
||||
|
||||
def place_box(x: int, y: int, width: int, height: int, taken: list,
|
||||
bounds: tuple[int, int, int, int]) -> tuple[int, int]:
|
||||
"""Where to put an aircraft's box so that it covers nothing that matters.
|
||||
|
|
@ -557,6 +619,20 @@ def _build():
|
|||
self.trails = True
|
||||
self.show_ground = True
|
||||
self._ground_pixels = None # kept alive for the QImage
|
||||
self._ground_ready = None # what those pixels were made from
|
||||
# Where each aircraft's box is, and where it is going: kept as
|
||||
# an offset from the symbol rather than a place on the screen,
|
||||
# so that a box follows its aeroplane across the window without
|
||||
# that counting as a move to be animated.
|
||||
self._box_at: dict[str, tuple[float, float]] = {}
|
||||
self._box_want: dict[str, tuple[int, int]] = {}
|
||||
self._box_seen: set[str] = set()
|
||||
self._box_moving = False
|
||||
self._glide_at = 0.0
|
||||
self._glide_step = 0.0
|
||||
self._glide_timer = QTimer(self)
|
||||
self._glide_timer.setSingleShot(True)
|
||||
self._glide_timer.timeout.connect(self.update)
|
||||
self.setMinimumSize(480, 360)
|
||||
small = QFont()
|
||||
small.setStyleHint(MONOSPACE)
|
||||
|
|
@ -635,6 +711,12 @@ def _build():
|
|||
# aircraft -- which is the one thing on the picture that has to
|
||||
# stay visible.
|
||||
now = time.time()
|
||||
# One step for every box on the picture, so that they all swing
|
||||
# at the same rate whatever the frame took.
|
||||
self._glide_step = (now - self._glide_at) if self._glide_at else 0.0
|
||||
self._glide_at = now
|
||||
self._box_seen = set()
|
||||
self._box_moving = False
|
||||
placed = [(blip, view.xy(blip.latitude, blip.longitude),
|
||||
self.sky.strength(blip, now)) for blip in flying]
|
||||
taken: list[tuple[int, int, int, int]] = []
|
||||
|
|
@ -643,8 +725,22 @@ def _build():
|
|||
craft_colour(blip.altitude_ft,
|
||||
_alpha(strength)), strength)
|
||||
taken.append((x - 11, y - 11, 22, 22))
|
||||
for blip, (x, y), strength in placed:
|
||||
self._draw_aircraft(painter, view, blip, x, y, taken, strength)
|
||||
labels = [self._lay_out(blip, x, y, taken, strength)
|
||||
for blip, (x, y), strength in placed]
|
||||
# A box on its way somewhere is drawn last, over the ones that
|
||||
# are standing still. It crosses its neighbours for a moment,
|
||||
# and the one that is moving is the one the eye is following,
|
||||
# so it is the one that has to stay readable while it does.
|
||||
for laid in sorted((x for x in labels if x is not None),
|
||||
key=lambda laid: laid[0]):
|
||||
self._paint_label(painter, laid)
|
||||
# An aircraft with no box this time -- gone, faded past reading,
|
||||
# or the detail turned down -- is forgotten, so one that comes
|
||||
# back is placed afresh instead of gliding in from wherever it
|
||||
# was standing minutes ago.
|
||||
for gone in set(self._box_at) - self._box_seen:
|
||||
self._box_at.pop(gone, None)
|
||||
self._box_want.pop(gone, None)
|
||||
self._draw_scale(painter, view)
|
||||
# Counted as overhead only while it is still being heard: one
|
||||
# that has gone quiet is on the picture, fading, and saying it
|
||||
|
|
@ -652,6 +748,10 @@ def _build():
|
|||
self._draw_header(painter,
|
||||
sum(1 for _b, _xy, s in placed if s >= 1.0))
|
||||
painter.end()
|
||||
# Only while something is actually moving: the rest of the time
|
||||
# the ordinary five-a-second redraw is what runs.
|
||||
if self._box_moving and not self._glide_timer.isActive():
|
||||
self._glide_timer.start(BOX_GLIDE_MS)
|
||||
|
||||
def _draw_waiting(self, painter) -> None:
|
||||
painter.setFont(self.text_font)
|
||||
|
|
@ -680,13 +780,25 @@ def _build():
|
|||
(int(view.width * scale),
|
||||
int(view.height * scale)))
|
||||
return
|
||||
from .flightmap import dim_ground
|
||||
# Cutting the view out of the fetched map, dimming it and
|
||||
# looking every level up in the palette is about seventy
|
||||
# milliseconds over two megapixels, and none of it changes
|
||||
# between one frame and the next unless the view, the window,
|
||||
# the brightness or the map itself has. Doing it every frame
|
||||
# put a ceiling of a dozen frames a second on the window and
|
||||
# spent a whole core holding it there.
|
||||
key = (self.sky.ground_serial(), self.sky.brightness,
|
||||
view.south, view.west, view.north, view.east,
|
||||
view.width, view.height)
|
||||
if key != getattr(self, "_ground_ready", None):
|
||||
from .flightmap import dim_ground
|
||||
|
||||
shades = dim_ground(self._crop(levels, box, view),
|
||||
self.sky.brightness)
|
||||
pixels = np.ascontiguousarray(
|
||||
PALETTE[GROUND + shades].astype(np.uint8))
|
||||
self._ground_pixels = pixels # QImage does not copy it
|
||||
shades = dim_ground(self._crop(levels, box, view),
|
||||
self.sky.brightness)
|
||||
self._ground_pixels = np.ascontiguousarray(
|
||||
PALETTE[GROUND + shades].astype(np.uint8))
|
||||
self._ground_ready = key
|
||||
pixels = self._ground_pixels # QImage does not copy it
|
||||
height, width = pixels.shape[0], pixels.shape[1]
|
||||
image = QImage(pixels.data, width, height, 3 * width, RGB888)
|
||||
painter.drawImage(0, 0, image)
|
||||
|
|
@ -753,29 +865,81 @@ def _build():
|
|||
for lat, lon, _ in points])
|
||||
painter.drawPolyline(path)
|
||||
|
||||
def _draw_aircraft(self, painter, view, blip: Blip, x, y,
|
||||
taken, strength: float = 1.0) -> None:
|
||||
def _lay_out(self, blip: Blip, x, y, taken, strength: float = 1.0):
|
||||
"""Where this aircraft's box goes, and what is in it.
|
||||
|
||||
Kept apart from the painting so that every box's place is
|
||||
decided before any of them is drawn, which is what lets the
|
||||
ones in motion go down last.
|
||||
"""
|
||||
# A box at a tenth of its colour is not information, it is
|
||||
# something in the way of the aircraft still flying.
|
||||
if self.detail <= 0 or strength < LABEL_WHILE:
|
||||
return
|
||||
colour = craft_colour(blip.altitude_ft, _alpha(strength))
|
||||
return None
|
||||
lines = self._wrapped(self._box_lines(blip))
|
||||
box = self._box_size(lines)
|
||||
bx, by = place_box(x, y, box[0], box[1], taken,
|
||||
(2, self._header_height() + 2,
|
||||
self.width() - 2, self.height() - 26))
|
||||
bx, by = self._box_spot(blip.icao, x, y, box, taken)
|
||||
# The settled place is what is spoken for, not the place the box
|
||||
# happens to have reached: laying out against a box in mid-swing
|
||||
# would move every box near it as well, and they would move
|
||||
# again when it arrived. A glide crosses its neighbours for a
|
||||
# moment; a whole screen rearranging itself twice does not
|
||||
# settle at all.
|
||||
taken.append((bx, by, box[0], box[1]))
|
||||
dx, dy = self._box_drawn(blip.icao, x, y, (bx, by))
|
||||
return ((dx, dy) != (bx, by), blip, x, y, dx, dy, box, lines,
|
||||
strength)
|
||||
|
||||
def _paint_label(self, painter, laid) -> None:
|
||||
_moving, blip, x, y, dx, dy, box, lines, strength = laid
|
||||
colour = craft_colour(blip.altitude_ft, _alpha(strength))
|
||||
# To the near edge of the box rather than its middle: a leader
|
||||
# drawn to the centre crosses the box and strikes out a line of
|
||||
# what it was drawn to point at.
|
||||
painter.setPen(QPen(colour.lighter(120), 1.0))
|
||||
painter.drawLine(x, y,
|
||||
int(max(bx, min(x, bx + box[0]))),
|
||||
int(max(by, min(y, by + box[1]))))
|
||||
int(max(dx, min(x, dx + box[0]))),
|
||||
int(max(dy, min(y, dy + box[1]))))
|
||||
title = f"{blip.callsign} {blip.icao}" if blip.callsign \
|
||||
else blip.icao
|
||||
self._draw_box(painter, bx, by, box, lines, colour, title)
|
||||
self._draw_box(painter, dx, dy, box, lines, colour, title)
|
||||
|
||||
def _box_spot(self, icao: str, x: int, y: int, box, taken):
|
||||
"""Where this aircraft's box belongs, once everything settles.
|
||||
|
||||
The spot it already had is kept for as long as it still works,
|
||||
which is what stops a box hopping about because the aeroplane
|
||||
two along moved a pixel. It is remembered as an offset, so an
|
||||
aircraft crossing the window carries its box with it and only a
|
||||
genuine clash asks for a new place.
|
||||
"""
|
||||
bounds = (2, self._header_height() + 2,
|
||||
self.width() - 2, self.height() - 26)
|
||||
left, top, right, bottom = bounds
|
||||
want = self._box_want.get(icao)
|
||||
if want is not None:
|
||||
bx = max(left, min(int(x + want[0]), right - box[0]))
|
||||
by = max(top, min(int(y + want[1]), bottom - box[1]))
|
||||
if _clear(bx, by, box[0], box[1], taken):
|
||||
self._box_want[icao] = (bx - x, by - y)
|
||||
return bx, by
|
||||
bx, by = place_box(x, y, box[0], box[1], taken, bounds)
|
||||
self._box_want[icao] = (bx - x, by - y)
|
||||
return bx, by
|
||||
|
||||
def _box_drawn(self, icao: str, x: int, y: int, want):
|
||||
"""Where to draw the box this frame, on its way to `want`."""
|
||||
self._box_seen.add(icao)
|
||||
target = (want[0] - x, want[1] - y)
|
||||
here = self._box_at.get(icao)
|
||||
if here is None: # first sight: no swing to make
|
||||
self._box_at[icao] = (float(target[0]), float(target[1]))
|
||||
return want
|
||||
here = glide(here, target, self._glide_step)
|
||||
self._box_at[icao] = here
|
||||
if here != (float(target[0]), float(target[1])):
|
||||
self._box_moving = True
|
||||
return int(round(x + here[0])), int(round(y + here[1]))
|
||||
|
||||
def _draw_symbol(self, painter, x, y, heading, colour,
|
||||
strength: float = 1.0) -> None:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
.\" Generated by packaging/make-man.py -- do not edit by hand.
|
||||
.TH BANDSAUNTER 1 "2026-09-04" "bandsaunter 2026-09-04_09" "User Commands"
|
||||
.TH BANDSAUNTER 1 "2026-09-04" "bandsaunter 2026-09-04_10" "User Commands"
|
||||
.SH NAME
|
||||
bandsaunter \- scan, record and identify radio signals with an RTL-SDR
|
||||
.SH SYNOPSIS
|
||||
|
|
@ -1329,6 +1329,21 @@ stretch one \[em] a route between two airports under their full names runs to
|
|||
sixty characters, and breaks at the arrow so that the two ends of the flight
|
||||
stay whole.
|
||||
.PP
|
||||
A box keeps its place for as long as that place still works and is moved only
|
||||
when an aircraft or another box genuinely takes it, which is about a third as
|
||||
many moves as laying every box out afresh each frame. The moves that are left
|
||||
are eased over about half a second rather than jumped, since a box that
|
||||
teleports reads as a different box, and the window redraws at thirty frames a
|
||||
second for as long as anything is moving and drops back to five when it
|
||||
stops. That is affordable because the ground is dimmed once and kept: cutting
|
||||
the view out of the fetched map and looking every level up in the palette is
|
||||
most of a tenth of a second over two megapixels, and nothing about it changes
|
||||
between frames unless the view, the window, the brightness or the map itself
|
||||
has. What the next box is laid out against is the place a moving box is
|
||||
going to, not the place it has reached, as otherwise its neighbours would
|
||||
move as well and move back when it arrived; and a box in motion is drawn over
|
||||
the ones standing still, so that it stays readable while it crosses them.
|
||||
.PP
|
||||
.B d
|
||||
cycles how much each box says, for a busy sky;
|
||||
.B t
|
||||
|
|
@ -1566,7 +1581,46 @@ between \[em] a receiver hears aircraft over its own county, and the county's
|
|||
airports say where on the map you are looking. They come from the same map
|
||||
data the tiles are drawn from, asked once per area and kept for a month.
|
||||
.B \-\-no\-airports
|
||||
turns that off.
|
||||
turns that off. They are drawn magenta, which nothing else on the picture is:
|
||||
the old amber sat sixteen units of CIELAB from the altitude ramp's yellow,
|
||||
which is to say it was the same colour, and an aeroplane low over a field was
|
||||
drawn in the field's own colour. The ramp already spends red, amber, green,
|
||||
cyan and violet on height; magenta is what it leaves free, and is what an
|
||||
aeronautical chart marks an aerodrome in anyway.
|
||||
.SS What is beside each aircraft
|
||||
Its height in feet with the unit on it, rounded to the twenty-five feet Mode S
|
||||
reports altitude in, so that a moment interpolated between two reports stops
|
||||
claiming to know the height to the foot; its speed; what sort of aircraft it
|
||||
is; its type and registration; and the two ends of the route, each with the
|
||||
flag of the country its airport is in. The country of registration gets a flag
|
||||
too, from the register where one answered and otherwise from the address
|
||||
block, so it is there for an aircraft no register has heard of.
|
||||
.PP
|
||||
What sort of aircraft it is comes from two places. Every identification
|
||||
message carries three bits under its type code saying what is transmitting
|
||||
\[em] light, small, large, high vortex, heavy, high performance, rotorcraft,
|
||||
and under another type code glider, airship, parachutist, ultralight, drone,
|
||||
spacecraft, or a vehicle on the ground \[em] and that is the only word about
|
||||
what an aircraft is that needs no register. Which list the three bits index
|
||||
depends on the type code, and zero means the aircraft declined to say, which
|
||||
is answered with nothing rather than a guess.
|
||||
.PP
|
||||
Whether it is military comes off no air at all, as no aircraft broadcasts it
|
||||
and a tanker calls itself heavy exactly as an airliner does. It is read from
|
||||
the address instead, since states set aside blocks of their national range for
|
||||
their armed forces. A state can fly a military aircraft on a civil address
|
||||
whenever it likes, so this finds nobody who does not want to be found, and the
|
||||
table holds the allocations a receiver in the ordinary world hears rather than
|
||||
every one that exists.
|
||||
.PP
|
||||
A label keeps its place for as long as that place still works and is moved
|
||||
only when something takes it, which is about half as many moves as deciding
|
||||
afresh every frame; the moves that are left are eased over about half a second
|
||||
of playback rather than jumped, and what the next label is laid out against is
|
||||
where a moving one is going rather than where it has reached. A still picture
|
||||
has no frame before it and places its labels exactly as it always did. The
|
||||
whole box fades with its aircraft: an indexed picture cannot blend, so the row
|
||||
grey and all twelve flag colours have dimmed copies at each fade step.
|
||||
.SH METERS AND SENSORS
|
||||
Two things on the ISM bands are worth naming rather than reporting as
|
||||
hexadecimal.
|
||||
|
|
|
|||
|
|
@ -722,6 +722,21 @@ stretch one \[em] a route between two airports under their full names runs to
|
|||
sixty characters, and breaks at the arrow so that the two ends of the flight
|
||||
stay whole.
|
||||
.PP
|
||||
A box keeps its place for as long as that place still works and is moved only
|
||||
when an aircraft or another box genuinely takes it, which is about a third as
|
||||
many moves as laying every box out afresh each frame. The moves that are left
|
||||
are eased over about half a second rather than jumped, since a box that
|
||||
teleports reads as a different box, and the window redraws at thirty frames a
|
||||
second for as long as anything is moving and drops back to five when it
|
||||
stops. That is affordable because the ground is dimmed once and kept: cutting
|
||||
the view out of the fetched map and looking every level up in the palette is
|
||||
most of a tenth of a second over two megapixels, and nothing about it changes
|
||||
between frames unless the view, the window, the brightness or the map itself
|
||||
has. What the next box is laid out against is the place a moving box is
|
||||
going to, not the place it has reached, as otherwise its neighbours would
|
||||
move as well and move back when it arrived; and a box in motion is drawn over
|
||||
the ones standing still, so that it stays readable while it crosses them.
|
||||
.PP
|
||||
.B d
|
||||
cycles how much each box says, for a busy sky;
|
||||
.B t
|
||||
|
|
@ -959,7 +974,46 @@ between \[em] a receiver hears aircraft over its own county, and the county's
|
|||
airports say where on the map you are looking. They come from the same map
|
||||
data the tiles are drawn from, asked once per area and kept for a month.
|
||||
.B \-\-no\-airports
|
||||
turns that off.
|
||||
turns that off. They are drawn magenta, which nothing else on the picture is:
|
||||
the old amber sat sixteen units of CIELAB from the altitude ramp's yellow,
|
||||
which is to say it was the same colour, and an aeroplane low over a field was
|
||||
drawn in the field's own colour. The ramp already spends red, amber, green,
|
||||
cyan and violet on height; magenta is what it leaves free, and is what an
|
||||
aeronautical chart marks an aerodrome in anyway.
|
||||
.SS What is beside each aircraft
|
||||
Its height in feet with the unit on it, rounded to the twenty-five feet Mode S
|
||||
reports altitude in, so that a moment interpolated between two reports stops
|
||||
claiming to know the height to the foot; its speed; what sort of aircraft it
|
||||
is; its type and registration; and the two ends of the route, each with the
|
||||
flag of the country its airport is in. The country of registration gets a flag
|
||||
too, from the register where one answered and otherwise from the address
|
||||
block, so it is there for an aircraft no register has heard of.
|
||||
.PP
|
||||
What sort of aircraft it is comes from two places. Every identification
|
||||
message carries three bits under its type code saying what is transmitting
|
||||
\[em] light, small, large, high vortex, heavy, high performance, rotorcraft,
|
||||
and under another type code glider, airship, parachutist, ultralight, drone,
|
||||
spacecraft, or a vehicle on the ground \[em] and that is the only word about
|
||||
what an aircraft is that needs no register. Which list the three bits index
|
||||
depends on the type code, and zero means the aircraft declined to say, which
|
||||
is answered with nothing rather than a guess.
|
||||
.PP
|
||||
Whether it is military comes off no air at all, as no aircraft broadcasts it
|
||||
and a tanker calls itself heavy exactly as an airliner does. It is read from
|
||||
the address instead, since states set aside blocks of their national range for
|
||||
their armed forces. A state can fly a military aircraft on a civil address
|
||||
whenever it likes, so this finds nobody who does not want to be found, and the
|
||||
table holds the allocations a receiver in the ordinary world hears rather than
|
||||
every one that exists.
|
||||
.PP
|
||||
A label keeps its place for as long as that place still works and is moved
|
||||
only when something takes it, which is about half as many moves as deciding
|
||||
afresh every frame; the moves that are left are eased over about half a second
|
||||
of playback rather than jumped, and what the next label is laid out against is
|
||||
where a moving one is going rather than where it has reached. A still picture
|
||||
has no frame before it and places its labels exactly as it always did. The
|
||||
whole box fades with its aircraft: an indexed picture cannot blend, so the row
|
||||
grey and all twelve flag colours have dimmed copies at each fade step.
|
||||
.SH METERS AND SENSORS
|
||||
Two things on the ISM bands are worth naming rather than reporting as
|
||||
hexadecimal.
|
||||
|
|
|
|||
|
|
@ -278,3 +278,45 @@ def test_the_unit_reaches_the_display_from_the_options():
|
|||
finally:
|
||||
if live is not None:
|
||||
live.stop()
|
||||
|
||||
|
||||
def test_the_emitter_category_is_kept_as_the_frames_arrive():
|
||||
"""It comes off the air in the identification message, alongside the
|
||||
callsign, and is the only word about what an aircraft *is* that does
|
||||
not need a register."""
|
||||
import binascii
|
||||
|
||||
from bandsaunter.adsb import _read, category_name
|
||||
|
||||
# A real identification frame: type code 4, category 3.
|
||||
raw = binascii.unhexlify("8DA80A97234CB5F5CF4C604EB016")
|
||||
frame = _read("".join(f"{b:08b}" for b in raw), raw)
|
||||
assert (frame.type_code, frame.category) == (4, 3)
|
||||
assert category_name(4, 3) == "large"
|
||||
|
||||
reg = AircraftRegistry()
|
||||
craft = reg.add(frame, when=1.0)
|
||||
assert craft.category == "large"
|
||||
|
||||
|
||||
def test_an_aircraft_that_declines_to_say_is_not_given_a_category():
|
||||
from bandsaunter.adsb import Frame, category_name
|
||||
|
||||
assert category_name(4, 0) == "" # zero means "not saying"
|
||||
assert category_name(9, 3) == "" # not an identification message
|
||||
reg = AircraftRegistry()
|
||||
craft = reg.add(Frame(icao="ABCDEF", type_code=4, category=0), when=1.0)
|
||||
assert craft.category == ""
|
||||
|
||||
|
||||
def test_the_same_three_bits_mean_different_things_under_different_codes():
|
||||
"""Which list they index depends on the type code, which is why it is a
|
||||
table of tables: category 1 is a light aeroplane under type 4 and a
|
||||
glider under type 3."""
|
||||
from bandsaunter.adsb import category_name
|
||||
|
||||
assert category_name(4, 1) == "light"
|
||||
assert category_name(3, 1) == "glider"
|
||||
assert category_name(2, 1) == "emergency vehicle"
|
||||
assert category_name(4, 7) == "rotorcraft"
|
||||
assert category_name(3, 7) == "spacecraft"
|
||||
|
|
|
|||
|
|
@ -763,7 +763,9 @@ def test_the_label_says_height_speed_type_and_both_ends_of_the_route():
|
|||
track = straight()
|
||||
rows = fm.label_lines(track, track.fixes[0], "knots", _Entry())
|
||||
text = [line for line, _flag in rows]
|
||||
assert text[0].startswith("350") # flight level
|
||||
# The height in feet with its unit on it: "350" is only a height to
|
||||
# somebody who already knows it is one.
|
||||
assert text[0].startswith("35,000 ft")
|
||||
assert "480KT" in text[0]
|
||||
assert "B739 N904DN" in text
|
||||
assert "KATL" in text and "EGLL" in text
|
||||
|
|
@ -778,9 +780,24 @@ def test_each_end_of_the_route_carries_its_own_country():
|
|||
|
||||
|
||||
def test_with_no_register_the_label_is_what_the_aircraft_itself_said():
|
||||
"""The height and the speed, which came off the air, and the flag of the
|
||||
country that issued the address, which needs no register either."""
|
||||
track = straight()
|
||||
rows = fm.label_lines(track, track.fixes[0], "knots", None)
|
||||
assert len(rows) == 1 and rows[0][1] == ""
|
||||
assert rows[0][0].startswith("35,000 ft") and rows[0][1] == ""
|
||||
assert [flag for _text, flag in rows if flag] == ["IE"]
|
||||
assert not any("N904DN" in text for text, _flag in rows)
|
||||
|
||||
|
||||
def test_the_flag_is_there_for_an_aircraft_no_register_has_heard_of():
|
||||
"""Taking the country from the register's answer left the flag off
|
||||
exactly the aircraft that had nothing else beside them either. The
|
||||
address block says it without asking anybody."""
|
||||
for icao, expected in (("4CA1FA", "IE"), ("A12345", "US"),
|
||||
("0D0468", "MX"), ("406B12", "GB")):
|
||||
track = straight(icao=icao)
|
||||
rows = fm.label_lines(track, track.fixes[0], "knots", None)
|
||||
assert [flag for _text, flag in rows if flag] == [expected], icao
|
||||
|
||||
|
||||
def test_an_airport_with_no_code_is_named_short_rather_than_in_full():
|
||||
|
|
@ -861,11 +878,28 @@ def test_the_route_reaches_the_drawn_picture(tmp_path):
|
|||
known = {t.icao: _Entry() for t in tracks}
|
||||
frame = fm.render_frame(base, view, tracks, tracks[0].first_seen + 60,
|
||||
known=known)
|
||||
assert (frame >= fm.FLAG).any(), "no flag was drawn"
|
||||
assert _has_flag(frame), "no flag was drawn"
|
||||
assert _has_text(frame, "KATL")
|
||||
assert _has_text(frame, "B739")
|
||||
|
||||
|
||||
def _has_flag(frame) -> bool:
|
||||
"""Whether any flag was drawn: its own colours, at any fade step.
|
||||
|
||||
Checked by the exact palette ranges rather than "any index above the
|
||||
flags", because everything a fading label is drawn in lives above them
|
||||
too.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
from bandsaunter.flags import COLOUR_ORDER
|
||||
|
||||
wide = len(COLOUR_ORDER)
|
||||
return bool(((frame >= fm.FLAG) & (frame < fm.FLAG + wide)).any()
|
||||
or ((frame >= fm.FLAG_FADED)
|
||||
& (frame < fm.FLAG_FADED + 3 * wide)).any())
|
||||
|
||||
|
||||
def test_a_crowded_frame_goes_back_to_the_short_label():
|
||||
"""Five lines beside each of three hundred aircraft is not more
|
||||
information, it is a page of overlapping text with a map behind it."""
|
||||
|
|
@ -877,7 +911,7 @@ def test_a_crowded_frame_goes_back_to_the_short_label():
|
|||
known = {t.icao: _Entry() for t in many}
|
||||
frame = fm.render_frame(base, view, many, many[0].first_seen + 60,
|
||||
known=known)
|
||||
assert not (frame >= fm.FLAG).any(), "still drawing flags when crowded"
|
||||
assert not _has_flag(frame), "still drawing flags when crowded"
|
||||
assert not _has_text(frame, "B739")
|
||||
|
||||
|
||||
|
|
@ -949,12 +983,18 @@ def test_the_address_block_stands_in_when_a_register_says_nothing():
|
|||
|
||||
|
||||
def test_a_country_nobody_named_gets_no_flag():
|
||||
track = straight()
|
||||
"""An address outside every block anybody has published, and a register
|
||||
that did not say either: no flag rather than a guessed one."""
|
||||
from bandsaunter.flights import describe_address
|
||||
|
||||
assert describe_address("0F0000") == "", "pick an unallocated address"
|
||||
track = straight(icao="0F0000")
|
||||
entry = _Entry()
|
||||
entry.owner_country = ""
|
||||
entry.country = ""
|
||||
rows = dict(fm.label_lines(track, track.fixes[0], "knots", entry))
|
||||
assert rows["B739 N904DN"] == ""
|
||||
rows = fm.label_lines(track, track.fixes[0], "knots", entry)
|
||||
assert not any(flag for _text, flag in rows if _text == "B739 N904DN")
|
||||
assert dict(rows)["B739 N904DN"] == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
|
@ -1209,3 +1249,314 @@ def test_a_route_it_could_be_flying_is_drawn():
|
|||
said = [text for text, _flag in
|
||||
fm.label_lines(track, track.fixes[0], "knots", entry)]
|
||||
assert "KLAX" in said and "KDFW" in said
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# What sort of aircraft it is
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_label_says_what_sort_of_aircraft_it_is():
|
||||
"""It comes off the air: the three bits under an identification
|
||||
message's type code, which every aircraft sends with its callsign."""
|
||||
track = straight()
|
||||
track.category = "heavy"
|
||||
said = [text for text, _flag in fm.label_lines(track, track.fixes[0],
|
||||
"knots", None)]
|
||||
assert "heavy" in said
|
||||
|
||||
|
||||
def test_a_military_address_says_so_beside_the_aircraft():
|
||||
"""No aircraft broadcasts that it is military -- a tanker calls itself
|
||||
"heavy" exactly as an airliner does -- so it is read off the address."""
|
||||
track = straight(icao="AE07D3") # a United States military block
|
||||
track.category = "heavy"
|
||||
said = [text for text, _flag in fm.label_lines(track, track.fixes[0],
|
||||
"knots", None)]
|
||||
assert "military heavy" in said
|
||||
plain = straight(icao="A12345") # the civil part of the same range
|
||||
plain.category = "heavy"
|
||||
assert "heavy" in [t for t, _f in fm.label_lines(plain, plain.fixes[0],
|
||||
"knots", None)]
|
||||
assert "military heavy" not in [t for t, _f in
|
||||
fm.label_lines(plain, plain.fixes[0],
|
||||
"knots", None)]
|
||||
|
||||
|
||||
def test_an_aircraft_that_says_nothing_about_itself_is_not_given_a_class():
|
||||
track = straight()
|
||||
assert not any(t in ("heavy", "large", "light") for t, _f in
|
||||
fm.label_lines(track, track.fixes[0], "knots", None))
|
||||
|
||||
|
||||
def test_the_class_carries_the_flag_so_the_type_line_need_not():
|
||||
"""One flag per aircraft, on the first row that says what it is."""
|
||||
track = straight()
|
||||
track.category = "large"
|
||||
rows = fm.label_lines(track, track.fixes[0], "knots", _Entry())
|
||||
flags = [(text, flag) for text, flag in rows if flag]
|
||||
assert ("large", "IE") in flags
|
||||
assert dict(rows)["B739 N904DN"] == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A label that has to move swings there
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_label_glide_moves_towards_the_target_and_arrives():
|
||||
here = (0.0, 0.0)
|
||||
for _ in range(40):
|
||||
here = fm._glide(here, (120.0, -80.0), 0.05, fm.LABEL_GLIDE)
|
||||
assert 0.0 <= here[0] <= 120.0 and -80.0 <= here[1] <= 0.0
|
||||
assert here == (120.0, -80.0)
|
||||
|
||||
|
||||
def test_the_label_glide_is_the_same_swing_at_any_frame_rate():
|
||||
fast = slow = (0.0, 0.0)
|
||||
for _ in range(8):
|
||||
fast = fm._glide(fast, (200.0, 0.0), 0.025, fm.LABEL_GLIDE)
|
||||
for _ in range(2):
|
||||
slow = fm._glide(slow, (200.0, 0.0), 0.1, fm.LABEL_GLIDE)
|
||||
assert abs(fast[0] - slow[0]) < 1.0
|
||||
|
||||
|
||||
def test_a_label_keeps_the_place_it_has():
|
||||
"""The reason labels stay still: one is only moved when its own place
|
||||
has actually been taken, never because the placer would now prefer a
|
||||
different one."""
|
||||
places = fm.LabelPlaces()
|
||||
places.settle("ABC123", 100, 100, (160, 90))
|
||||
kept = places.kept("ABC123", 104, 100, lambda bx, by: (int(bx), int(by)))
|
||||
assert kept == (164, 90), "it did not travel with its aircraft"
|
||||
|
||||
|
||||
def test_a_label_whose_place_is_taken_is_sent_looking():
|
||||
places = fm.LabelPlaces()
|
||||
places.settle("ABC123", 100, 100, (160, 90))
|
||||
assert places.kept("ABC123", 100, 100, lambda bx, by: None) is None
|
||||
|
||||
|
||||
def test_a_label_that_has_to_move_swings_rather_than_jumps():
|
||||
places = fm.LabelPlaces()
|
||||
places.settle("ABC123", 0, 0, (100, 100))
|
||||
assert places.drawn("ABC123", 0, 0, (100, 100), 0.08) == (100, 100)
|
||||
part = places.drawn("ABC123", 0, 0, (300, 240), 0.08)
|
||||
assert part != (300, 240), "it jumped the whole way in one frame"
|
||||
assert 100 < part[0] < 300
|
||||
for _ in range(40):
|
||||
part = places.drawn("ABC123", 0, 0, (300, 240), 0.08)
|
||||
assert part == (300, 240)
|
||||
|
||||
|
||||
def test_a_label_is_forgotten_when_its_aircraft_goes():
|
||||
"""Otherwise one that comes back glides in from wherever it stood half
|
||||
an hour ago, across the whole picture."""
|
||||
places = fm.LabelPlaces()
|
||||
places.begin()
|
||||
places.settle("ABC123", 0, 0, (100, 100))
|
||||
places.drawn("ABC123", 0, 0, (100, 100), 0.08)
|
||||
places.end()
|
||||
assert "ABC123" in places.at
|
||||
places.begin()
|
||||
places.end()
|
||||
assert places.at == {} and places.want == {}
|
||||
|
||||
|
||||
def test_a_label_swings_across_a_real_frame_rather_than_jumping():
|
||||
"""The same easing the window does, wired through a drawn frame: the
|
||||
label is somewhere between where it was and where it now belongs, and
|
||||
what is spoken for is where it is going."""
|
||||
track = straight()
|
||||
# A canvas with room around the aircraft, so that a displaced label is
|
||||
# displaced rather than pushed off the edge and refused.
|
||||
view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0))
|
||||
base = fm.background(view, unit="knots")
|
||||
places = fm.LabelPlaces()
|
||||
when = track.fixes[0].at
|
||||
fm.render_frame(base, view, [track], when, labels=True, unit="knots",
|
||||
places=places, step=1.0 / 12.0)
|
||||
settled = places.want[track.icao]
|
||||
assert places.at[track.icao] == (float(settled[0]), float(settled[1]))
|
||||
# Push its place a long way, as a crowd of aircraft arriving would.
|
||||
places.want[track.icao] = (settled[0] - 120, settled[1] + 90)
|
||||
after = fm.render_frame(base, view, [track], when, labels=True,
|
||||
unit="knots", places=places, step=1.0 / 12.0)
|
||||
target = places.want[track.icao]
|
||||
now_at = places.at[track.icao]
|
||||
assert target != settled, "the test did not displace it"
|
||||
assert now_at != (float(settled[0]), float(settled[1])), "it did not move"
|
||||
assert now_at != (float(target[0]), float(target[1])), \
|
||||
"it jumped the whole way in one frame"
|
||||
part = (now_at[0] - settled[0]) / (target[0] - settled[0])
|
||||
assert 0.05 < part < 0.60, f"one frame carried it {part:.0%} of the way"
|
||||
# And it gets there, given the frames.
|
||||
for _ in range(30):
|
||||
fm.render_frame(base, view, [track], when, labels=True, unit="knots",
|
||||
places=places, step=1.0 / 12.0)
|
||||
assert places.at[track.icao] == (float(places.want[track.icao][0]),
|
||||
float(places.want[track.icao][1]))
|
||||
assert after.shape == base.shape
|
||||
|
||||
|
||||
def test_a_still_picture_places_its_labels_exactly_as_it_always_did():
|
||||
"""There is no frame before a still, so there is nothing to keep and
|
||||
nothing to swing: the placing has to be untouched."""
|
||||
track = straight()
|
||||
view = fm.fit([track], width=800)
|
||||
base = fm.background(view, unit="knots")
|
||||
when = track.fixes[0].at
|
||||
plain = fm.render_frame(base, view, [track], when, labels=True,
|
||||
unit="knots", project=False)
|
||||
again = fm.render_frame(base, view, [track], when, labels=True,
|
||||
unit="knots", project=False)
|
||||
assert np.array_equal(plain, again)
|
||||
|
||||
|
||||
def test_the_height_does_not_claim_to_know_a_foot_it_was_not_told():
|
||||
"""Most moments in an animation are between two reports and the height
|
||||
at them is interpolated. Mode S reports altitude in twenty-five foot
|
||||
steps, so a real reading survives untouched and an invented one stops
|
||||
pretending to be exact."""
|
||||
track = straight(altitude=37_675)
|
||||
fix = track.fixes[0]
|
||||
assert fm.label_lines(track, fix, "knots", None)[0][0] \
|
||||
.startswith("37,675 ft")
|
||||
from dataclasses import replace
|
||||
|
||||
between = replace(fix, altitude_ft=37_699)
|
||||
assert fm.label_lines(track, between, "knots", None)[0][0] \
|
||||
.startswith("37,700 ft")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The box fades with the aircraft
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_fade_level_follows_the_strength():
|
||||
assert fm.fade_level(1.0) == 0
|
||||
assert fm.fade_level(0.5) == 1
|
||||
assert fm.fade_level(0.3) == 2
|
||||
assert fm.fade_level(0.05) == 3
|
||||
|
||||
|
||||
def test_each_fade_step_of_the_row_grey_is_darker_than_the_last():
|
||||
greys = [fm.PALETTE[fm.LABEL_INK + i].astype(int).sum() for i in range(4)]
|
||||
assert greys == sorted(greys, reverse=True)
|
||||
assert greys[0] > greys[-1] * 3, "the last step is barely dimmer"
|
||||
|
||||
|
||||
def test_each_fade_step_of_a_flag_colour_is_darker_than_the_last():
|
||||
for letter in ("r", "w", "b"):
|
||||
shades = [fm.PALETTE[fm.flag_index(letter, level)].astype(int).sum()
|
||||
for level in range(4)]
|
||||
assert shades == sorted(shades, reverse=True), letter
|
||||
|
||||
|
||||
def test_a_fading_label_is_drawn_fainter_than_a_full_one():
|
||||
"""The name already faded, because it is drawn in the aircraft's own
|
||||
colour. The rows and the flag were fixed colours, so the brightest
|
||||
thing left on that part of the picture was the one aeroplane nothing
|
||||
had been heard from."""
|
||||
track = straight()
|
||||
view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0))
|
||||
base = fm.background(view, unit="knots")
|
||||
entry = _Entry()
|
||||
|
||||
def rows_of(strength):
|
||||
img = base.copy()
|
||||
fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots",
|
||||
entry=entry, strength=strength)
|
||||
drawn = img != base
|
||||
return fm.PALETTE[img[drawn]].astype(int).sum()
|
||||
|
||||
full = rows_of(1.0)
|
||||
half = rows_of(0.5)
|
||||
nearly_gone = rows_of(0.05)
|
||||
assert half < full, "a fading label was as bright as a full one"
|
||||
assert nearly_gone < half
|
||||
|
||||
|
||||
def _label_pixels(strength, entry=None):
|
||||
"""One label drawn at a strength, as the palette indices it used."""
|
||||
track = straight()
|
||||
track.category = "large"
|
||||
view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0))
|
||||
base = fm.background(view, unit="knots")
|
||||
img = base.copy()
|
||||
fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots",
|
||||
entry=entry if entry is not None else _Entry(),
|
||||
strength=strength)
|
||||
return set(np.unique(img[img != base]).tolist())
|
||||
|
||||
|
||||
def test_the_rows_are_drawn_in_the_grey_for_the_strength_they_are_at():
|
||||
"""Not merely dimmer on average -- the label has a name in it that
|
||||
fades on its own -- but each row written in the grey that belongs to
|
||||
how far the aircraft has faded."""
|
||||
full = _label_pixels(1.0)
|
||||
assert fm.LABEL_INK + 0 in full
|
||||
for strength, level in ((0.5, 1), (0.3, 2), (0.05, 3)):
|
||||
used = _label_pixels(strength)
|
||||
assert fm.LABEL_INK + level in used, strength
|
||||
assert not any(fm.LABEL_INK + other in used
|
||||
for other in range(4) if other != level), strength
|
||||
|
||||
|
||||
def test_the_flag_on_a_label_is_drawn_at_the_labels_own_fade_step():
|
||||
from bandsaunter.flags import COLOUR_ORDER
|
||||
|
||||
wide = len(COLOUR_ORDER)
|
||||
full = _label_pixels(1.0)
|
||||
assert any(fm.FLAG <= i < fm.FLAG + wide for i in full), "no flag drawn"
|
||||
for strength, level in ((0.5, 1), (0.3, 2), (0.05, 3)):
|
||||
used = _label_pixels(strength)
|
||||
assert not any(fm.FLAG <= i < fm.FLAG + wide for i in used), \
|
||||
f"a full-strength flag on a label faded to {strength}"
|
||||
want = fm.FLAG_FADED + (level - 1) * wide
|
||||
assert any(want <= i < want + wide for i in used), strength
|
||||
|
||||
|
||||
def test_a_flag_on_a_fading_label_fades_with_it():
|
||||
from bandsaunter.flags import FLAG_H, FLAG_W
|
||||
|
||||
bright = np.full((40, 60), fm.BG, dtype=np.uint8)
|
||||
faint = np.full((40, 60), fm.BG, dtype=np.uint8)
|
||||
fm.draw_flag(bright, 5, 5, "US", 0)
|
||||
fm.draw_flag(faint, 5, 5, "US", 3)
|
||||
patch = (slice(5, 5 + FLAG_H), slice(5, 5 + FLAG_W))
|
||||
assert fm.PALETTE[faint[patch]].astype(int).sum() < \
|
||||
fm.PALETTE[bright[patch]].astype(int).sum()
|
||||
|
||||
|
||||
def test_a_named_country_with_no_flag_fades_too():
|
||||
faint = np.full((40, 60), fm.BG, dtype=np.uint8)
|
||||
bright = np.full((40, 60), fm.BG, dtype=np.uint8)
|
||||
fm.draw_flag(bright, 5, 5, "ZZ", 0)
|
||||
fm.draw_flag(faint, 5, 5, "ZZ", 3)
|
||||
assert fm.PALETTE[faint].astype(int).sum() < \
|
||||
fm.PALETTE[bright].astype(int).sum()
|
||||
|
||||
|
||||
def test_an_airport_cannot_be_mistaken_for_an_aircraft():
|
||||
"""The old amber sat sixteen units of CIELAB from the ramp's yellow,
|
||||
which is to say it was the same colour: an aeroplane low over a field
|
||||
was drawn in the field's own colour and neither could be picked out.
|
||||
|
||||
Stated as the property rather than as the colour, so that changing the
|
||||
altitude ramp cannot quietly walk an aircraft back into the airports.
|
||||
"""
|
||||
def lab(rgb):
|
||||
c = np.asarray(rgb, float) / 255.0
|
||||
c = np.where(c > 0.04045, ((c + 0.055) / 1.055) ** 2.4, c / 12.92)
|
||||
m = np.array([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722],
|
||||
[0.0193, 0.1192, 0.9505]])
|
||||
xyz = (c @ m.T) / np.array([0.9505, 1.0, 1.089])
|
||||
f = np.where(xyz > 0.008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116)
|
||||
return np.array([116 * f[1] - 16, 500 * (f[0] - f[1]),
|
||||
200 * (f[1] - f[2])])
|
||||
|
||||
airport = lab(fm.PALETTE[fm.AIRPORT])
|
||||
apart = min(float(np.linalg.norm(airport - lab(fm.PALETTE[fm.RAMP + i])))
|
||||
for i in range(fm.RAMP_STEPS))
|
||||
assert apart > 40, (f"the airport colour is {apart:.0f} units from the "
|
||||
f"nearest altitude colour; under about 25 they read "
|
||||
f"as the same colour")
|
||||
|
|
|
|||
|
|
@ -786,3 +786,104 @@ def test_an_airport_nobody_can_place_costs_only_its_own_leg(register,
|
|||
# The middle stop cannot be placed, so neither leg touching it can be
|
||||
# tested; nothing is claimed.
|
||||
assert book.leg_for(entry, 40.8, -78.0) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# What sort of aircraft it is
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_military_address_is_read_off_the_block():
|
||||
from bandsaunter.flights import aircraft_class, is_military
|
||||
|
||||
assert is_military("AE07D3") # a United States military block
|
||||
assert not is_military("AC4C44") # the civil part of the same range
|
||||
assert not is_military("") and not is_military("nonsense")
|
||||
assert aircraft_class("AE07D3", "heavy") == "military heavy"
|
||||
assert aircraft_class("AC4C44", "large") == "large"
|
||||
assert aircraft_class("AE07D3") == "military"
|
||||
assert aircraft_class("AC4C44") == ""
|
||||
|
||||
|
||||
def test_military_and_the_country_it_is_described_with_never_disagree():
|
||||
"""Both read the same table, so an address cannot be military and be
|
||||
described as an ordinary country at the same time."""
|
||||
from bandsaunter.flights import (MILITARY_BLOCKS, describe_address,
|
||||
is_military)
|
||||
|
||||
for low, high, name in MILITARY_BLOCKS:
|
||||
for address in (low, (low + high) // 2, high):
|
||||
assert is_military(f"{address:06X}")
|
||||
assert describe_address(f"{address:06X}") == name
|
||||
assert name.endswith(" military")
|
||||
|
||||
|
||||
def test_the_report_says_what_sort_of_aircraft_it_is(tmp_path):
|
||||
"""Off the air, not out of a register: the aeroplane says "heavy" and
|
||||
the address says whose it is."""
|
||||
from bandsaunter.flightlog import report
|
||||
|
||||
log = _log(tmp_path)
|
||||
for i in range(3):
|
||||
log.append(_Frame(icao="AE07D3", callsign="PRIME04"),
|
||||
_Craft(32.7086, -110.4061 + i * 0.01, "PRIME04"),
|
||||
when=1_000_000.0 + i)
|
||||
log.close()
|
||||
tracks = read_logs(log.path)
|
||||
tracks[0].category = "heavy"
|
||||
text = "\n".join(report(tracks, None))
|
||||
assert "class: military heavy" in text
|
||||
|
||||
|
||||
def test_the_report_leaves_the_class_out_when_nothing_said_one(tmp_path):
|
||||
from bandsaunter.flightlog import report
|
||||
|
||||
log = _log(tmp_path)
|
||||
for i in range(3):
|
||||
log.append(_Frame(icao="AC4C44", callsign="SWA2444"),
|
||||
_Craft(32.7086, -110.4061 + i * 0.01, "SWA2444"),
|
||||
when=1_000_000.0 + i)
|
||||
log.close()
|
||||
assert "class:" not in "\n".join(report(read_logs(log.path), None))
|
||||
|
||||
|
||||
def test_the_category_is_read_back_out_of_a_logged_frame(tmp_path):
|
||||
"""The three bits are inside the identification message, which is
|
||||
written down in full, so every log this program has ever written has
|
||||
them -- including the ones written before anything here knew to look."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from bandsaunter.flightlog import read_logs as read
|
||||
|
||||
path = Path(tmp_path) / "old.jsonl"
|
||||
with path.open("w") as out:
|
||||
out.write(json.dumps({"log": "bandsaunter-adsb", "version": 1}) + "\n")
|
||||
# A real identification frame: type code 4, category 3, "large".
|
||||
out.write(json.dumps(
|
||||
{"t": 1.0, "icao": "A80A97", "df": 17, "tc": 4,
|
||||
"hex": "8DA80A97234CB5F5CF4C604EB016",
|
||||
"callsign": "SKW5341"}) + "\n")
|
||||
out.write(json.dumps(
|
||||
{"t": 2.0, "icao": "A80A97", "df": 17, "tc": 11,
|
||||
"hex": "8DA338A6591521A2C718D47E24C0",
|
||||
"lat": 32.2, "lon": -111.0, "alt_ft": 3050}) + "\n")
|
||||
track = read([path])[0]
|
||||
assert track.category == "large"
|
||||
assert track.kind == "large"
|
||||
|
||||
|
||||
def test_a_log_with_nothing_to_read_the_category_from_says_nothing(tmp_path):
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from bandsaunter.flightlog import read_logs as read
|
||||
|
||||
path = Path(tmp_path) / "thin.jsonl"
|
||||
with path.open("w") as out:
|
||||
for line in ({"t": 1.0, "icao": "A80A97", "tc": 4}, # no hex
|
||||
{"t": 2.0, "icao": "A80A97", "tc": 11,
|
||||
"hex": "8DA338A6591521A2C718D47E24C0", # not an ident
|
||||
"lat": 32.2, "lon": -111.0},
|
||||
{"t": 3.0, "icao": "A80A97", "tc": 4, "hex": "8D"}):
|
||||
out.write(json.dumps(line) + "\n")
|
||||
assert read([path])[0].category == ""
|
||||
|
|
|
|||
|
|
@ -1002,3 +1002,357 @@ def test_a_route_it_could_be_flying_stays_in_the_box():
|
|||
assert blip.route_fits is True
|
||||
labels = [label for label, _v, _f in blip.lines("knots")]
|
||||
assert "from" in labels and "to" in labels
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A box that has to move swings there rather than jumping
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_glide_moves_towards_the_target_without_passing_it():
|
||||
from bandsaunter.livemap import glide
|
||||
|
||||
here = (0.0, 0.0)
|
||||
last = here
|
||||
for _ in range(40):
|
||||
here = glide(here, (100.0, -60.0), 0.05)
|
||||
assert 0.0 <= here[0] <= 100.0 and -60.0 <= here[1] <= 0.0
|
||||
assert here[0] >= last[0] and here[1] <= last[1]
|
||||
last = here
|
||||
assert here == (100.0, -60.0), "never actually arrived"
|
||||
|
||||
|
||||
def test_the_glide_arrives_and_stops_asking_for_frames():
|
||||
"""It has to land exactly on the target, not approach it forever: the
|
||||
window repaints faster while anything is moving, and a box that is
|
||||
always a thousandth of a pixel out never lets it stop."""
|
||||
from bandsaunter.livemap import BOX_GLIDE, glide
|
||||
|
||||
here = glide((0.0, 0.0), (50.0, 50.0), BOX_GLIDE * 4)
|
||||
assert here == (50.0, 50.0)
|
||||
assert glide(here, (50.0, 50.0), 0.1) == (50.0, 50.0)
|
||||
|
||||
|
||||
def test_the_glide_is_the_same_swing_at_any_frame_rate():
|
||||
"""Eased by the distance left rather than counted in frames, so a busy
|
||||
machine drawing half as often makes the same movement, not a slower
|
||||
one."""
|
||||
from bandsaunter.livemap import glide
|
||||
|
||||
fast = (0.0, 0.0)
|
||||
for _ in range(8):
|
||||
fast = glide(fast, (200.0, 0.0), 0.025)
|
||||
slow = (0.0, 0.0)
|
||||
for _ in range(2):
|
||||
slow = glide(slow, (200.0, 0.0), 0.1)
|
||||
assert abs(fast[0] - slow[0]) < 1.0
|
||||
|
||||
|
||||
def test_a_frame_that_took_no_time_moves_nothing():
|
||||
from bandsaunter.livemap import glide
|
||||
|
||||
assert glide((3.0, 4.0), (99.0, 99.0), 0.0) == (3.0, 4.0)
|
||||
|
||||
|
||||
def test_a_window_left_buried_does_not_replay_the_moves():
|
||||
"""Ten seconds behind another window is not ten seconds of animation
|
||||
owed; it is a box that should already be where it belongs."""
|
||||
from bandsaunter.livemap import glide
|
||||
|
||||
assert glide((0.0, 0.0), (300.0, 300.0), 10.0) == (300.0, 300.0)
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_box_that_need_not_move_does_not_move(app):
|
||||
"""The whole point of remembering the spot: one aircraft shifting a
|
||||
pixel must not send its neighbour's box across the window."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.60, lon=-111.30),
|
||||
a_blip(icao="A00002", callsign="AAL2", lat=32.20, lon=-110.60))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
first = dict(view._box_want)
|
||||
assert first, "no box was placed at all"
|
||||
for _ in range(4):
|
||||
_rendered(view)
|
||||
assert dict(view._box_want) == first
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_spot_that_still_works_is_kept(app):
|
||||
"""Hysteresis, and the reason boxes stay still: a box is only moved
|
||||
when its own place is actually taken, never because the placer would
|
||||
now prefer a different one."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
view = SkyView(a_sky(a_blip()))
|
||||
view.resize(900, 650)
|
||||
view._box_want["A00001"] = (50, 20)
|
||||
assert view._box_spot("A00001", 400, 300, (120, 60), []) == (450, 320)
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_spot_that_has_been_taken_is_given_up(app):
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
view = SkyView(a_sky(a_blip()))
|
||||
view.resize(900, 650)
|
||||
view._box_want["A00001"] = (50, 20)
|
||||
spot = view._box_spot("A00001", 400, 300, (120, 60),
|
||||
[(450, 320, 120, 60)])
|
||||
assert spot != (450, 320)
|
||||
assert view._box_want["A00001"] == (spot[0] - 400, spot[1] - 300)
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_settled_place_is_what_is_spoken_for(app):
|
||||
"""Laying the next box out against one still in mid-swing would move
|
||||
that one too, and again when the first arrived; the screen would never
|
||||
settle. So the target is what goes into the taken list."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.55, lon=-111.20))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
was = view._box_at["A00001"]
|
||||
view._box_want["A00001"] = (was[0] + 200, was[1] + 100)
|
||||
view._glide_at = time.time() - 0.05
|
||||
_rendered(view)
|
||||
# Mid-swing, and the spot it is heading for is the one it holds.
|
||||
assert view._box_at["A00001"] != view._box_want["A00001"]
|
||||
assert view._box_spot("A00001", 0, 0, (10, 10), []) == \
|
||||
tuple(view._box_want["A00001"])
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_placer_is_shown_the_settled_spot_not_the_gliding_one(app, monkeypatch):
|
||||
"""The one that decides whether the screen settles. If a box in mid-
|
||||
swing is what the next box is laid out against, that next box moves
|
||||
too -- and moves back when the first one arrives."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
early, late = now() - 900, now() - 800
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.55, lon=-111.20,
|
||||
first_seen=early),
|
||||
a_blip(icao="B00002", callsign="AAL2", lat=32.25, lon=-110.70,
|
||||
first_seen=late))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
was = view._box_at["A00001"]
|
||||
settled = view._box_want["A00001"]
|
||||
view._box_want["A00001"] = (was[0] + 220, was[1] + 130)
|
||||
# The second one is made to ask for a place, so we can see what it is
|
||||
# shown when it does.
|
||||
view._box_want.pop("B00002")
|
||||
seen = []
|
||||
real = livemap.place_box
|
||||
monkeypatch.setattr(livemap, "place_box",
|
||||
lambda *a: (seen.append(list(a[4])), real(*a))[1])
|
||||
view._glide_at = time.time() - 0.05
|
||||
_rendered(view)
|
||||
assert seen, "the second box never asked for a place"
|
||||
offered = [(r[0], r[1]) for r in seen[-1]]
|
||||
# The offsets are from the symbol, so they only mean anything once the
|
||||
# symbol is where the picture put it.
|
||||
ax, ay = view.projection().xy(32.55, -111.20)
|
||||
target = view._box_want["A00001"]
|
||||
drawn = view._box_at["A00001"]
|
||||
assert drawn != settled and drawn != (float(target[0]), float(target[1])), \
|
||||
"the first box was not in mid-swing, so this proves nothing"
|
||||
going = (ax + target[0], ay + target[1])
|
||||
got_to = (int(round(ax + drawn[0])), int(round(ay + drawn[1])))
|
||||
assert going != got_to, "the two places are the same; nothing is proved"
|
||||
assert going in offered, "the settled spot was not spoken for"
|
||||
assert got_to not in offered, "laid out against a box in mid-swing"
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_box_pushed_off_its_spot_swings_rather_than_jumps(app):
|
||||
"""Drawn between where it was and where it now belongs, for several
|
||||
frames, instead of being in the new place on the very next one."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.55, lon=-111.20))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
was = view._box_at["A00001"]
|
||||
# Push its settled spot well away, as a crowd of new aircraft would.
|
||||
view._box_want["A00001"] = (was[0] + 240, was[1] + 120)
|
||||
view._glide_at = time.time() - 0.05 # a frame's worth of clock
|
||||
_rendered(view)
|
||||
# Read the target back rather than assuming it: a spot near the edge is
|
||||
# clamped into the window, so the swing may be shorter than it was asked
|
||||
# to be.
|
||||
target = view._box_want["A00001"]
|
||||
moved = view._box_at["A00001"]
|
||||
assert target != was, "the test did not actually displace it"
|
||||
assert moved != was, "it did not move at all"
|
||||
assert moved != target, "it jumped the whole way in one frame"
|
||||
part = (moved[0] - was[0]) / (target[0] - was[0])
|
||||
assert 0.05 < part < 0.60, f"one frame carried it {part:.0%} of the way"
|
||||
assert view._box_moving is True
|
||||
# And it does get there, given the frames.
|
||||
for _ in range(30):
|
||||
view._glide_at = time.time() - 0.05
|
||||
_rendered(view)
|
||||
assert view._box_at["A00001"] == (float(target[0]), float(target[1]))
|
||||
assert view._box_moving is False, "still asking for frames after arriving"
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_box_follows_its_aeroplane_without_that_counting_as_a_move(app):
|
||||
"""The offset is what is remembered, so an aircraft crossing the window
|
||||
carries its box along instead of dragging it there a frame late."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.50, lon=-111.10))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
settled = view._box_at["A00001"]
|
||||
sky.update([a_blip(icao="A00001", callsign="AAL1",
|
||||
lat=32.70, lon=-110.70)], 1, 1)
|
||||
_rendered(view)
|
||||
assert view._box_at["A00001"] == settled # same offset, new place
|
||||
assert view._box_moving is False
|
||||
|
||||
|
||||
@qt
|
||||
def test_an_aircraft_that_goes_is_forgotten(app):
|
||||
"""Otherwise one that comes back an hour later glides in from wherever
|
||||
it was standing then, across the whole window."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1"))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
assert "A00001" in view._box_at
|
||||
view.detail = 0 # symbols only: no boxes
|
||||
_rendered(view)
|
||||
assert view._box_at == {} and view._box_want == {}
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_box_in_motion_is_drawn_over_the_ones_standing_still(app):
|
||||
"""It crosses its neighbours for a moment on the way, and the one that
|
||||
is moving is the one being followed, so it is the one that has to stay
|
||||
readable while it does."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(icao="A00001", callsign="AAL1", lat=32.55, lon=-111.20,
|
||||
first_seen=now() - 900),
|
||||
a_blip(icao="B00002", callsign="AAL2", lat=32.25, lon=-110.70,
|
||||
first_seen=now() - 800))
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
_rendered(view)
|
||||
order = []
|
||||
real = SkyView._paint_label
|
||||
def watch(self, painter, laid):
|
||||
order.append((laid[0], laid[1].icao))
|
||||
return real(self, painter, laid)
|
||||
SkyView._paint_label = watch
|
||||
try:
|
||||
was = view._box_at["A00001"]
|
||||
# Away from the other one, so that only this box is on the move.
|
||||
view._box_want["A00001"] = (was[0] - 160, was[1] + 150)
|
||||
view._glide_at = time.time() - 0.05
|
||||
_rendered(view)
|
||||
finally:
|
||||
SkyView._paint_label = real
|
||||
assert [icao for moving, icao in order if moving] == ["A00001"], \
|
||||
f"expected only the displaced box to be moving, got {order}"
|
||||
# Everything standing still goes down before anything that is moving.
|
||||
assert order == sorted(order, key=lambda seen: seen[0])
|
||||
assert order[-1][1] == "A00001"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The ground is dimmed once, not every frame
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _with_ground(width=900, height=650, brightness=0.70):
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip(), brightness=brightness)
|
||||
view = SkyView(sky)
|
||||
view.resize(width, height)
|
||||
projection = view.projection()
|
||||
levels = np.random.default_rng(7).integers(
|
||||
0, 32, (int(height * 1.3), int(width * 1.3)), dtype=np.uint8)
|
||||
sky.set_ground(levels, view.ground_key(projection),
|
||||
view.ground_box(projection))
|
||||
return sky, view
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_dimmed_map_is_kept_between_frames(app):
|
||||
"""Cutting the view out, dimming it and looking every level up in the
|
||||
palette is most of a tenth of a second over two megapixels. Doing it
|
||||
again for a frame in which nothing about it changed put a ceiling of a
|
||||
dozen frames a second on the window."""
|
||||
sky, view = _with_ground()
|
||||
_rendered(view)
|
||||
made = view._ground_pixels
|
||||
assert made is not None
|
||||
_rendered(view)
|
||||
assert view._ground_pixels is made, "the map was dimmed all over again"
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_new_map_is_dimmed_afresh(app):
|
||||
"""Same window, same brightness, same view: only the map itself is
|
||||
different, which is what the count on it is for."""
|
||||
sky, view = _with_ground()
|
||||
_rendered(view)
|
||||
made = view._ground_pixels
|
||||
projection = view.projection()
|
||||
sky.set_ground(np.full_like(sky._ground, 31),
|
||||
view.ground_key(projection), view.ground_box(projection))
|
||||
_rendered(view)
|
||||
assert view._ground_pixels is not made
|
||||
|
||||
|
||||
@qt
|
||||
def test_turning_the_brightness_up_redraws_the_map(app):
|
||||
sky, view = _with_ground()
|
||||
_rendered(view)
|
||||
made = view._ground_pixels.copy()
|
||||
sky.brightness = 0.30
|
||||
_rendered(view)
|
||||
assert not np.array_equal(view._ground_pixels, made)
|
||||
|
||||
|
||||
@qt
|
||||
def test_resizing_the_window_redraws_the_map(app):
|
||||
sky, view = _with_ground()
|
||||
_rendered(view)
|
||||
_rendered(view, width=700, height=500)
|
||||
assert view._ground_pixels.shape[:2] == (500, 700)
|
||||
|
||||
|
||||
def test_the_window_box_says_what_sort_of_aircraft_it_is():
|
||||
"""The same two facts the animation shows, so the two look like the
|
||||
same program: what it broadcast, and whether its address is military."""
|
||||
military = a_blip(icao="AE07D3", callsign="PRIME04")
|
||||
military.category = "heavy"
|
||||
rows = military.lines("knots")
|
||||
assert ("class", "military heavy", "") in rows
|
||||
plain = a_blip(icao="AC4C44", callsign="SWA2444")
|
||||
plain.category = "large"
|
||||
assert ("class", "large", "") in plain.lines("knots")
|
||||
quiet = a_blip(icao="AC4C44", callsign="SWA2444")
|
||||
assert not any(label == "class" for label, _v, _f in quiet.lines("knots"))
|
||||
|
||||
|
||||
def test_the_category_reaches_the_window_from_the_air():
|
||||
from bandsaunter.adsb import Aircraft
|
||||
|
||||
craft = Aircraft(icao="AE07D3", callsign="PRIME04", latitude=32.5,
|
||||
longitude=-111.0, category="heavy")
|
||||
assert blip_for(craft).category == "heavy"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue