feat(vessels): draw vessels as shaded sprites seen from the camera's angle

Vessels on the map were flat, top-down hulls turned along their course,
drawn at one size at every range.

Each hull shape (the ten vessel kinds, a dredger and a pilot boat) is
now rendered in Blender into a view sheet like the aircraft's
(public/sprites/vessel-views.webp: 208 views a shape, 7.5 degrees apart
from straight above down to the horizon, 4096 x 2496, grey, 2.2 MB),
cut at the waterline. On a renderer with `viewSheets` the Vessels layer
draws a vessel as the view of its hull from where the eye is, with the
flat hull as the fallback while the sheet loads or if it cannot load.
A vessel keeps its kind's colour; aids to navigation keep their upright
buoy; a renderer without view sheets draws the flat hulls as before.

Every AIS ship type code 0-99 maps to a shape in the sheet
(`vesselShape`, vesselTypes.js), pinned by a test. Type text such as
"Search & Rescue" and "Anti Pollution" is now recognised, which also
gives those vessels their right kind colour.

Size: a vessel's icon now follows its range from the eye on the same
range aircraft icons use (1.5 times its former size up close, its
former size at about 1,000 km, a third from 8,000 km out), so it stays
under an aircraft's icon at every range, and the vessel set recedes
toward the horizon as the aircraft sets do.

Tools: the bake script handles both sheets
(scripts/bake-view-sheet.py; `npm run build:aircraft-views`,
`npm run build:vessel-views`), and refuses a partial bake over a shipped
sheet. scripts/qa-view-sheet.mjs writes contact sheets of a bake;
scripts/qa-aircraft-views.mjs takes `--layer vessels`. The aircraft
sheet is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Mazeyar Moeini FeizabadiandClaude Fable 5.2 committed 2026-11-23 04:10:58 +01:00
1 parent b4ff9b1e07
commit 01187cbe7a
19 files changed
+1115 -272

No files matched your search

@@ -1,46 +1,52 @@
"""Bake the aircraft view sheet: every aircraft class seen from a sphere of
directions, as one image of small shaded sprites.
"""Bake a view sheet: each subject of a sheet (an aircraft class, a vessel
kind) seen from a sphere of directions, as one image of small shaded sprites.
blender -b --factory-startup --python scripts/build-aircraft-view-sheet.py -- \
--out <dir> [--cell 64] [--supersample 4] [--only airliner,light]
[--preview <dir>]
blender -b --factory-startup --python scripts/bake-view-sheet.py -- \
--sheet aircraft|vessels --out <dir> [--cell 64] [--supersample 4]
[--only airliner,light] [--preview <dir>]
It writes `aircraft-views.png` and its manifest `aircraft-views.json` to
`--out`. The manifest names the shipped image, `aircraft-views.webp`, which
`npm run build:aircraft-views` (scripts/build-aircraft-views.mjs) makes from
the PNG (lossless) and writes to `public/sprites/` with the manifest.
It writes `<name>.png` and its manifest `<name>.json` to `--out`, `<name>`
being the sheet's name (`aircraft-views`, `vessel-views`). The manifest names
the shipped image, `<name>.webp`, which `npm run build:aircraft-views` or
`npm run build:vessel-views` (scripts/build-view-sheet.mjs) makes from the
PNG (lossless) and writes to `public/sprites/` with the manifest.
The layers draw a contact with the frame that shows it from where the eye is
(`src/data/viewSheet.js` holds the same layout and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's constants and the shipped
manifest against it). A frame is an orthographic view of the class's
fleet model (`public/models/fleet/`, nose toward -X, +Y starboard, +Z up),
centred on the model's origin, the model's bounding sphere filling
(`src/data/viewSheet.js` holds the same layouts and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's sheets and the shipped
manifests against it). A frame is an orthographic view of the subject's
fleet model (`public/models/fleet/`, nose or bow toward -X, +Y starboard, +Z
up), centred on the model's origin, the model's bounding sphere filling
`FILL` of the cell.
Directions. `d` is the unit vector from the aircraft to the eye in the
aircraft's own frame (forward, right, up), the aircraft lying flat on the
Directions. `d` is the unit vector from the subject to the eye in the
subject's own frame (forward, right, up), the subject lying flat on the
earth: up is the ground's normal, forward its course. Rings of frames lie
`RING_STEP_DEG` apart from straight above (ring 0, one frame) down to
`RINGS[-1]` below the horizon. A ring holds the eye's bearings from dead ahead
(first frame) round the starboard side to dead astern (last frame); the port
side is the starboard frame mirrored, which is why the light is symmetric
about the aircraft's centre plane.
the sheet's `ring_step_deg` apart from straight above (ring 0, one frame)
down to its last ring (30 degrees below the horizon for aircraft, the horizon
for vessels). A ring holds the eye's bearings from dead ahead (first frame)
round the starboard side to dead astern (last frame); the port side is the
starboard frame mirrored, which is why the light is symmetric about the
subject's centre plane.
Roll. A frame's image up is where the aircraft's forward goes under the
Roll. A frame's image up is where the subject's forward goes under the
smallest rotation that takes "up" to `d`: straight above, the nose points up
the image, and the roll then changes smoothly all the way round and below
(it has no meaning only from straight below, which no ring reaches).
The sprites are neutral (white paint, grey shading, dark glass and a dark
The sprites are neutral (light paint, grey shading, dark glass and a dark
edge) so a layer's tint multiplies them, as it does the flat glyphs; every
pixel's red, green and blue are equal (`"grey": true` in the manifest), as
the renderer keeps the sheet as grey and alpha, and the bake refuses a frame
that is not. A
helicopter's body and blades are painted light as well (its blades a solid
light grey), and its rotor frames share one scale: each rotor vertex counts
at the farthest point of the circle it sweeps about the rotor's axis. Thin
subjects are thickened before their edge (`BOLD_PX`), and every cell keeps
that is not. Each sheet has its paint ramp (`PAINTS`), and a subject may
have its own. A helicopter's body and blades are painted light as well (its
blades a solid light grey), and its rotor frames share one scale: each rotor
vertex counts at the farthest point of the circle it sweeps about the
rotor's axis. A vessel is cut at its waterline (its origin, z = 0) before it
is rendered, so no hull below the water is drawn and its bounding sphere is
of what floats; a subject's model may be widened across the beam (`beam`)
or squashed above a height (`squash_above`: a sailboat's mast). Thin
subjects are thickened before their edge (`bold_px`), and every cell keeps
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
refuses a frame that does not.
"""
@@ -51,49 +57,78 @@ import os
import struct
import sys
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheet's layout (mirrored in src/data/viewSheet.js) -----------------
# --- The sheets (their layouts mirrored in src/data/viewSheet.js) -----------
# A sheet: its name (the files it writes), its rings of frames (each ring's
# frame count, from dead ahead round starboard to dead astern), its paint,
# whether its models are cut at the waterline, and its subjects, in the order
# of their blocks of frames. A subject is (name, model, options); options:
# rotor_deg a helicopter's rotor frame: the rotors turned this far
# paint its own paint ramp (a key of PAINTS)
# bold_px cell pixels it is thickened by before its edge, so thin
# wings, blades and hulls still read 20 to 30 px wide
# beam its model scaled across the beam by this much
# squash_above [z, k]: its model above z metres scaled up by k
AIRCRAFT = {
"name": "aircraft-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22],
"columns": 64,
"paint": "aircraft",
"waterline": False,
"subjects": [
("airliner", "aircraft/a320.glb", {}),
("widebody", "aircraft/b789.glb", {}),
("quadjet", "aircraft/b744.glb", {}),
("turboprop", "aircraft/at72.glb", {}),
("light", "aircraft/c172.glb", {"bold_px": 0.35}),
("glider", "aircraft/glider.glb", {"bold_px": 1.0}),
("fastjet", "aircraft/t38.glb", {}),
("bizjet", "aircraft/glf4.glb", {}),
("uav", "aircraft/mq9.glb", {"bold_px": 1.0}),
# The helicopter has one block for each rotor frame (rotorFrames.js).
("helicopter0", "helicopters/generic_heli.glb", {"rotor_deg": 15, "paint": "helicopter", "bold_px": 0.4}),
("helicopter1", "helicopters/generic_heli.glb", {"rotor_deg": 45, "paint": "helicopter", "bold_px": 0.4}),
("helicopter2", "helicopters/generic_heli.glb", {"rotor_deg": 75, "paint": "helicopter", "bold_px": 0.4}),
],
}
# Vessels: down to the horizon only, as a ship is never seen from below. The
# subjects are the hull kinds of vesselKind (src/data/vesselTypes.js), then
# the dredger (AIS 33) and the pilot boat (pilot, rescue, tender and
# anti-pollution craft).
VESSELS = {
"name": "vessel-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25],
"columns": 64,
"paint": "ship",
"waterline": True,
"subjects": [
("cargo", "ships/container_ship.glb", {"beam": 1.4, "bold_px": 1.0}),
("tanker", "ships/tanker.glb", {"beam": 1.4, "bold_px": 1.0}),
("passenger", "ships/cruise_ship.glb", {"beam": 1.4, "bold_px": 0.5}),
("highspeed", "ships/fast_ferry.glb", {"beam": 1.2, "bold_px": 0.5}),
("fishing", "ships/trawler.glb", {"bold_px": 0.5}),
("tug", "ships/tug.glb", {"bold_px": 0.5}),
("sailing", "ships/sailboat.glb", {"beam": 1.3, "bold_px": 0.5, "squash_above": [1.2, 0.4]}),
("pleasure", "ships/motor_yacht.glb", {"beam": 1.25, "bold_px": 0.5}),
("military", "ships/patrol.glb", {"beam": 1.5, "bold_px": 1.0}),
("other", "ships/generic_vessel.glb", {"beam": 1.3, "bold_px": 0.5}),
("dredger", "ships/dredger.glb", {"beam": 1.3, "bold_px": 0.5}),
("pilot", "ships/pilot_boat.glb", {"beam": 1.2, "bold_px": 0.5}),
],
}
SHEETS = {"aircraft": AIRCRAFT, "vessels": VESSELS}
RING_STEP_DEG = 7.5
# Frames in each ring, from dead ahead round starboard to dead astern.
RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22]
FRAMES = sum(RINGS)
COLUMNS = 64
# How much of a cell the model's bounding sphere spans.
FILL = 0.92
# Each class's model, in the order of its block of frames in the sheet. A
# helicopter has one block for each rotor frame (rotorFrames.js).
ROTOR_ANGLES_DEG = [15, 45, 75]
SUBJECTS = [
("airliner", "aircraft/a320.glb", None),
("widebody", "aircraft/b789.glb", None),
("quadjet", "aircraft/b744.glb", None),
("turboprop", "aircraft/at72.glb", None),
("light", "aircraft/c172.glb", None),
("glider", "aircraft/glider.glb", None),
("fastjet", "aircraft/t38.glb", None),
("bizjet", "aircraft/glf4.glb", None),
("uav", "aircraft/mq9.glb", None),
("helicopter0", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[0]),
("helicopter1", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[1]),
("helicopter2", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[2]),
]
# Cell pixels each subject is thickened by before its dark edge, so thin
# wings and rotor blades still read when a contact is drawn 20 to 30 px
# wide. The big aircraft read as they are and are not thickened.
BOLD_PX = {
"light": 0.35,
"glider": 1.0,
"uav": 1.0,
"helicopter0": 0.4,
"helicopter1": 0.4,
"helicopter2": 0.4,
}
# Cells keep this many pixels at each edge clear: the renderer samples the
# sheet with mipmaps (to level 1), so a neighbour's pixels must not reach
# into a cell's footprint.
@@ -104,11 +139,11 @@ RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions():
def frame_directions(sheet):
"""Every frame's (ring, index, d) with d in the model's axes."""
out = []
for ring, count in enumerate(RINGS):
alpha = math.radians(ring * RING_STEP_DEG)
for ring, count in enumerate(sheet["rings"]):
alpha = math.radians(ring * sheet["ring_step_deg"])
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
@@ -131,6 +166,7 @@ def frame_up(d):
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"sheet": "aircraft",
"out": "public/sprites",
"cell": 64,
"supersample": 4,
@@ -148,6 +184,8 @@ def args_after_dashes():
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
if opts["sheet"] not in SHEETS:
raise SystemExit(f"--sheet is one of {', '.join(SHEETS)}")
return opts
@@ -210,17 +248,26 @@ def setup_scene(render_px, samples):
return scene, camera, fill
# Paint by the model's own colour value (its largest channel, linear): glass
# and tyres stay dark, a livery's accent becomes mid grey, and every body
# colour a light paint, so a tint reads on any model.
PAINT_RAMP = [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)]
HELICOPTER_PAINT_RAMP = [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)]
# Paint by the model's own colour value (its largest channel, linear), as
# (value, grey) stops. Aircraft: glass and tyres stay dark, a livery's accent
# becomes mid grey, and every body colour a light paint, so a tint reads on
# any model. Ships: windows and the darkest fittings stay dark, and hull
# paint, decks and cargo all become light greys a little apart.
PAINTS = {
"aircraft": [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)],
"helicopter": [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)],
"ship": [(0.0, 0.62), (0.25, 0.78), (0.85, 0.95)],
}
# Glass by its colour, for a paint that lifts even black hull paint: a dark
# colour (value at most `value`) whose blue is at least `blue` and
# `blue_over_red` times its red (the ship models' windows) is painted `grey`.
GLASS = {"ship": {"value": 0.08, "blue": 0.025, "blue_over_red": 2.5, "grey": 0.07}}
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp=PAINT_RAMP, solid=None):
def paint_material(paint_ramp, solid=None, glass=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
@@ -251,7 +298,37 @@ def paint_material(paint_ramp=PAINT_RAMP, solid=None):
element.position = position
element.color = (grey, grey, grey, 1.0)
links.new(value.outputs[0], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
if glass is None:
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def math_node(operation, a, b, c=None):
node = nodes.new("ShaderNodeMath")
node.operation = operation
for i, x in enumerate((a, b, c)):
if x is None:
continue
if isinstance(x, (int, float)):
node.inputs[i].default_value = x
else:
links.new(x, node.inputs[i])
return node.outputs[0]
dark = math_node("LESS_THAN", value.outputs[0], glass["value"] + 1e-4)
blue = math_node("GREATER_THAN", split.outputs[2], glass["blue"] - 1e-4)
red_scaled = math_node("MULTIPLY", split.outputs[0], glass["blue_over_red"])
over_red = math_node(
"GREATER_THAN", math_node("SUBTRACT", split.outputs[2], red_scaled), -1e-4
)
is_glass = math_node("MULTIPLY", math_node("MULTIPLY", dark, blue), over_red)
ramp_grey = nodes.new("ShaderNodeSeparateColor")
links.new(ramp.outputs["Color"], ramp_grey.inputs["Color"])
to_glass = math_node("SUBTRACT", glass["grey"], ramp_grey.outputs[0])
grey = math_node("MULTIPLY_ADD", is_glass, to_glass, ramp_grey.outputs[0])
combine = nodes.new("ShaderNodeCombineColor")
for i in range(3):
links.new(grey, combine.inputs[i])
links.new(combine.outputs["Color"], bsdf.inputs["Base Color"])
return material
@@ -316,15 +393,47 @@ def turn_rotors(mesh, parts, degrees, rotor_material):
return swept_radii
def load_model(path, material, rotor_deg, rotor_material):
def reshape(mesh, waterline, beam, squash_above):
"""Bring a mesh into the scene's axes, cut away what lies below the
waterline (z = 0) and scale it across the beam and above a height."""
world = mesh.matrix_world.copy()
mesh.parent = None
mesh.matrix_world = Matrix.Identity(4)
mesh.data.transform(world)
bm = bmesh.new()
bm.from_mesh(mesh.data)
if waterline:
bmesh.ops.bisect_plane(
bm,
geom=bm.verts[:] + bm.edges[:] + bm.faces[:],
dist=1e-4,
plane_co=(0.0, 0.0, 0.0),
plane_no=(0.0, 0.0, 1.0),
clear_inner=True,
)
for vertex in bm.verts:
vertex.co.y *= beam
if squash_above and vertex.co.z > squash_above[0]:
height, k = squash_above
vertex.co.z = height + (vertex.co.z - height) * k
bm.to_mesh(mesh.data)
bm.free()
def load_model(path, material, rotor_deg, rotor_material, waterline=False, options=None):
options = options or {}
before = set(bpy.data.objects)
bpy.ops.import_scene.gltf(filepath=path)
objects = [o for o in bpy.data.objects if o not in before]
meshes = [o for o in objects if o.type == "MESH"]
bpy.context.view_layer.update()
parts = model_parts(path) if rotor_deg is not None else []
beam = options.get("beam", 1.0)
squash_above = options.get("squash_above")
radius = 0.0
for mesh in meshes:
if waterline or beam != 1.0 or squash_above:
reshape(mesh, waterline, beam, squash_above)
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
@@ -490,55 +599,63 @@ def save_png(path, pixels):
def main():
opts = args_after_dashes()
config = SHEETS[opts["sheet"]]
name_of_sheet = config["name"]
columns = config["columns"]
subjects = config["subjects"]
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
models = os.path.join(root, "public", "models", "fleet")
cell = opts["cell"]
supersample = opts["supersample"]
only = set(opts["only"].split(",")) if opts["only"] else None
scene, camera, fill = setup_scene(cell * supersample, opts["samples"])
material = paint_material()
helicopter_material = paint_material(HELICOPTER_PAINT_RAMP)
rotor_material = paint_material(solid=0.82)
directions = frame_directions()
materials = {
key: paint_material(ramp, glass=GLASS.get(key)) for key, ramp in PAINTS.items()
}
rotor_material = paint_material(None, solid=0.82)
directions = frame_directions(config)
frames = len(directions)
tmp = os.path.join(bpy.app.tempdir, "view-frame.png")
rows = math.ceil(len(SUBJECTS) * FRAMES / COLUMNS)
sheet = np.zeros((rows * cell, COLUMNS * cell, 4), dtype=np.float32)
rows = math.ceil(len(subjects) * frames / columns)
sheet = np.zeros((rows * cell, columns * cell, 4), dtype=np.float32)
manifest = {
"image": "aircraft-views.webp",
"image": f"{name_of_sheet}.webp",
"cellPx": cell,
"columns": COLUMNS,
"columns": columns,
"rows": rows,
"ringStepDeg": RING_STEP_DEG,
"rings": RINGS,
"ringStepDeg": config["ring_step_deg"],
"rings": config["rings"],
"fill": FILL,
# Every pixel's red, green and blue are equal.
"grey": True,
"subjects": {},
}
for index, (name, model, rotor_deg) in enumerate(SUBJECTS):
first = index * FRAMES
for index, (name, model, options) in enumerate(subjects):
first = index * frames
manifest["subjects"][name] = {"first": first, "model": model}
if only and name not in only:
continue
objects, radius = load_model(
os.path.join(models, model),
material if rotor_deg is None else helicopter_material,
rotor_deg,
materials[options.get("paint", config["paint"])],
options.get("rotor_deg"),
rotor_material,
config["waterline"],
options,
)
manifest["subjects"][name]["radiusM"] = round(radius, 3)
for n, (ring, i, d) in enumerate(directions):
aim(camera, fill, d, radius)
scene.render.filepath = tmp
bpy.ops.render.render(write_still=True)
frame = finish(read_pixels(tmp), supersample, BOLD_PX.get(name, 0.0))
frame = finish(read_pixels(tmp), supersample, options.get("bold_px", 0.0))
check_clear_edge(frame, name, n)
frame = to_grey(frame, name, n)
at = first + n
y = (at // COLUMNS) * cell
x = (at % COLUMNS) * cell
y = (at // columns) * cell
x = (at % columns) * cell
sheet[y : y + cell, x : x + cell] = frame
if opts["preview"]:
os.makedirs(opts["preview"], exist_ok=True)
@@ -547,15 +664,15 @@ def main():
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {FRAMES} frames, radius {radius:.2f} m", flush=True)
print(f"baked {name}: {frames} frames, radius {radius:.2f} m", flush=True)
out = os.path.join(root, opts["out"]) if not os.path.isabs(opts["out"]) else opts["out"]
os.makedirs(out, exist_ok=True)
save_png(os.path.join(out, "aircraft-views.png"), sheet)
with open(os.path.join(out, "aircraft-views.json"), "w") as f:
save_png(os.path.join(out, f"{name_of_sheet}.png"), sheet)
with open(os.path.join(out, f"{name_of_sheet}.json"), "w") as f:
json.dump(manifest, f, indent=1)
f.write("\n")
print(f"wrote {out}/aircraft-views.png ({COLUMNS * cell}x{rows * cell})")
print(f"wrote {out}/{name_of_sheet}.png ({columns * cell}x{rows * cell})")
main()
@@ -1,13 +1,16 @@
#!/usr/bin/env node
/**
* build-aircraft-views.mjs: bake the aircraft view sheet and ship it.
* build-view-sheet.mjs: bake a view sheet (aircraft or vessels) and ship it.
*
* Runs `scripts/build-aircraft-view-sheet.py` in Blender (headless) into a
* scratch directory, then writes `public/sprites/aircraft-views.webp`
* (lossless WebP of the baked PNG) and `public/sprites/aircraft-views.json`
* (its manifest). See `public/sprites/README.md`.
* Runs `scripts/bake-view-sheet.py` in Blender (headless) into a scratch
* directory, then writes the sheet to `public/sprites/` as
* `<name>.webp` (lossless WebP of the baked PNG) and `<name>.json` (its
* manifest): `aircraft-views` or `vessel-views`. See
* `public/sprites/README.md`.
*
* Run: npm run build:aircraft-views [-- --only airliner,light] [--out public/sprites]
* Run: node scripts/build-view-sheet.mjs --sheet aircraft|vessels
* [--only airliner,light] [--out public/sprites]
* (npm run build:aircraft-views, npm run build:vessel-views)
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
@@ -25,6 +28,15 @@ const opt = (name, fallback) => {
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
const SHEET = opt('--sheet', null);
if (SHEET !== 'aircraft' && SHEET !== 'vessels')
throw new Error('--sheet is aircraft or vessels');
// A bake of some subjects leaves the others' cells empty: it is for looking
// at, never for the sheet the app loads.
if (ONLY && !argv.includes('--out'))
throw new Error(
'--only bakes part of a sheet: give it its own --out, not public/sprites',
);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
@@ -53,7 +65,7 @@ async function assertGrey(file) {
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'aircraft-views-'));
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'view-sheet-'));
try {
const bake = spawnSync(
blender(),
@@ -61,8 +73,10 @@ try {
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'build-aircraft-view-sheet.py'),
path.join(root, 'scripts', 'bake-view-sheet.py'),
'--',
'--sheet',
SHEET,
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
@@ -75,20 +89,19 @@ try {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const [json] = fs.readdirSync(scratch).filter((f) => f.endsWith('.json'));
const name = path.basename(json, '.json');
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, 'aircraft-views.json'), 'utf8'),
fs.readFileSync(path.join(scratch, json), 'utf8'),
);
const png = path.join(scratch, 'aircraft-views.png');
const png = path.join(scratch, `${name}.png`);
if (manifest.grey) await assertGrey(png);
fs.mkdirSync(OUT, { recursive: true });
const webp = path.join(OUT, manifest.image);
await sharp(png)
.webp({ lossless: true, effort: 6, exact: true })
.toFile(webp);
fs.copyFileSync(
path.join(scratch, 'aircraft-views.json'),
path.join(OUT, 'aircraft-views.json'),
);
fs.copyFileSync(path.join(scratch, json), path.join(OUT, json));
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
+6 -3
View File
@@ -2399,7 +2399,8 @@
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": ["cesium", "kdbush"]
},
@@ -5622,7 +5623,8 @@
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6480,7 +6482,8 @@
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
+85 -16
View File
@@ -10,7 +10,7 @@
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights] [--block-sheet] [--headful]
* [--layer military|flights|vessels] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
@@ -27,9 +27,13 @@ const opt = (name, fallback) => {
const APP_URL = opt('--url', 'http://localhost:4173');
const OUT = path.resolve(opt('--out', 'qa-shots/views'));
const HEADFUL = argv.includes('--headful');
// `military` (amber, every class by type code) or `flights` (white, the
// classes an ADS-B emitter category gives).
// `military` (amber, every class by type code), `flights` (white, the
// classes an ADS-B emitter category gives) or `vessels` (every hull kind by
// AIS ship type, at sea level).
const LAYER = opt('--layer', 'military');
const VESSELS = LAYER === 'vessels';
// The app's id of the layer.
const LAYER_ID = VESSELS ? 'ais-live-vessels' : LAYER;
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
@@ -56,11 +60,27 @@ const CATEGORIES = [
['glider', 9],
['helicopter', 8],
];
const ROWS = LAYER === 'flights' ? CATEGORIES : CLASSES;
// An AIS ship type for each hull kind (vesselTypes.js).
const HULLS = [
['cargo', 70],
['tanker', 80],
['passenger', 60],
['highspeed', 40],
['fishing', 30],
['tug', 52],
['sailing', 36],
['pleasure', 37],
['military', 35],
['other', 90],
['dredger', 33],
['pilot', 50],
];
const ROWS = VESSELS ? HULLS : LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
const CENTRE = { lon: -97.74, lat: 30.3 };
// Aircraft over Austin; vessels on open water in the North Sea.
const CENTRE = VESSELS ? { lon: 3.2, lat: 52.6 } : { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = 12000;
const ALT_FT = VESSELS ? 0 : 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
@@ -88,7 +108,11 @@ const SHOTS = [
{ name: '4-tilt55-east', heading: 90, pitch: -35, rangeKm: 50 },
{ name: '5-tilt55-southwest', heading: 225, pitch: -35, rangeKm: 50 },
{ name: '6-tilt75-north', heading: 0, pitch: -15, rangeKm: 52 },
{ name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
// From below, looking up at the grid; a vessel is never seen from there,
// so vessels get a shot from just above the water in its place.
VESSELS
? { name: '7-horizon-north', heading: 0, pitch: -5, rangeKm: 30 }
: { name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
];
// `--orbit`: the camera swung round the grid a little at a time, a frame
@@ -139,7 +163,7 @@ async function main() {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/aircraft-views\./.test(request.url())) request.abort();
if (/\/sprites\/[a-z]+-views\./.test(request.url())) request.abort();
else request.continue();
});
}
@@ -197,6 +221,39 @@ async function main() {
),
}),
);
if (url.includes('/api/vessels') && seed.layer === 'vessels') {
const now = Date.now();
return Promise.resolve(
json({
rows: seed.contacts.map((c, i) => ({
...at(c),
name: c.flight,
mmsi: String(235000000 + i),
imo: '0',
type: String(c.t),
destination: 'QA',
length: 120,
beam: 20,
speed: SPEED_MPS * 1.9438,
course: c.courseDeg,
heading: c.courseDeg,
last_position_UTC: new Date(now).toISOString(),
last_position_epoch: Math.floor(now / 1000),
})),
source: 'AISStream',
status: 'live',
error: null,
refreshing: false,
newestPositionAt: now,
lastMessageAt: now,
silentForMs: 0,
reconnectAttempt: 0,
nextAttemptAt: null,
staleAfterMs: 120000,
watchdog: 'armed',
}),
);
}
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
@@ -241,14 +298,26 @@ async function main() {
() => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager,
{ timeout: 60000, polling: 200 },
);
const seeded = await page.evaluate(async (name) => {
const { dataManager, viewer } = window.__godsEyeView;
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) await layer.update(viewer);
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
}, LAYER);
const seeded = await page.evaluate(
async (name, centre) => {
const { dataManager, viewer } = window.__godsEyeView;
// Over the grid first: a layer may ask only for what is in view.
const Cartesian3 = viewer.camera.position.constructor;
viewer.camera.setView({
destination: Cartesian3.fromDegrees(centre.lon, centre.lat, 60000),
});
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) {
await layer.update(viewer);
await new Promise((resolve) => setTimeout(resolve, 500));
}
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
},
LAYER_ID,
CENTRE,
);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
@@ -1,24 +1,29 @@
#!/usr/bin/env node
/**
* qa-aircraft-view-sheet.mjs: contact sheets of a baked aircraft view sheet,
* for reviewing a bake (`scripts/build-aircraft-view-sheet.py`) before it
* qa-view-sheet.mjs: contact sheets of a baked view sheet (aircraft or
* vessels), for reviewing a bake (`scripts/bake-view-sheet.py`) before it
* ships.
*
* For each subject it writes one image: its frames with the rings as rows
* (straight above at the top, 30° below the horizon at the bottom, each ring
* from dead ahead to dead astern), over a dark sea colour, a pale land colour
* and a mid satellite tone, each tinted as the layers tint it. Under them, a
* few frames (above, oblique, abeam, below) shrunk to the sizes a contact is
* drawn at, to judge whether thin wings still read.
* (straight above at the top, the last ring at the bottom, each ring from
* dead ahead to dead astern), in white, over three grounds the subject is
* seen over. Under them, a few frames (above, oblique, abeam, and below or
* low on the horizon) shrunk to the sizes a contact is drawn at, in each
* tint the layers draw it with, to judge whether thin wings and hulls still
* read. Aircraft: a dark sea, pale land and a mid satellite tone; the fleet,
* tracked and military tints. Vessels: a dark sea, pale shallow water and a
* satellite ocean tone; white and the colour of each kind the subject is
* drawn for (`VESSEL_KIND_STYLES`).
*
* Run: node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/aircraft-views] [--zoom 2] [--sizes 40,30,20]
* Run: node scripts/qa-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/<name>] [--zoom 2] [--sizes 40,30,20]
* [--only airliner,glider]
* `--sheet` defaults to the manifest's `image`, next to it.
*/
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
import { VESSEL_KIND_STYLES } from '../src/data/vesselTypes.js';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
@@ -28,26 +33,51 @@ const opt = (name, fallback) => {
const MANIFEST = path.resolve(
opt('--manifest', 'public/sprites/aircraft-views.json'),
);
const OUT = path.resolve(opt('--out', 'qa-shots/aircraft-views'));
const ZOOM = Number(opt('--zoom', '2'));
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
const ONLY = opt('--only', '').split(',').filter(Boolean);
/** Grounds a contact is seen over: a dark sea, pale land, a mid satellite tone. */
const GROUNDS = [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The layers' tints, multiplied into the neutral sprite. */
const TINTS = [
{ name: 'fleet', rgb: [1, 1, 1] },
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const GAP = 8;
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
const VESSELS = manifest.image.startsWith('vessel');
const OUT = path.resolve(
opt('--out', `qa-shots/${path.basename(manifest.image, '.webp')}`),
);
const WHITE = { name: 'white', rgb: [1, 1, 1] };
/** `#rrggbb` as 0..1 channels. */
const rgbOf = (css) =>
[1, 3, 5].map((i) => parseInt(css.slice(i, i + 2), 16) / 255);
/** Grounds a contact is seen over. */
const GROUNDS = VESSELS
? [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'shallows', css: '#8fc3c1' },
{ name: 'satellite', css: '#0f2e44' },
]
: [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The kinds a vessel shape that is not a kind of its own is coloured as: a
* vessel takes its kind's colour (`vesselKind`), whatever its shape. */
const SHAPE_KINDS = { dredger: ['other'], pilot: ['tug', 'military'] };
/** A subject's tints, multiplied into the neutral sprite as the layers do. */
const tintsOf = (name) =>
VESSELS
? [
WHITE,
...(SHAPE_KINDS[name] ?? [name]).map((kind) => ({
name: kind,
rgb: rgbOf(VESSEL_KIND_STYLES[kind].css),
})),
]
: [
WHITE,
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
@@ -58,13 +88,17 @@ const widest = Math.max(...rings);
/** The ring nearest `offDeg` from straight above. */
const ringAt = (offDeg) =>
Math.min(rings.length - 1, Math.round(offDeg / manifest.ringStepDeg));
const last = rings.length - 1;
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and from below, abeam. */
* ahead and to the right, abeam on the horizon, and the last ring from
* below abeam or, if the last ring is the horizon, from the bow quarter. */
const PICKS = [
[0, 0],
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
[rings.length - 1, Math.round((rings[rings.length - 1] - 1) / 2)],
last === ringAt(90)
? [last, Math.round((rings[last] - 1) / 4)]
: [last, Math.round((rings[last] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
@@ -100,6 +134,7 @@ async function cellImage(index, tint, size) {
}
async function subjectSheet(name, first) {
const TINTS = tintsOf(name);
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
@@ -122,11 +157,11 @@ async function subjectSheet(name, first) {
left: x0,
top: GAP,
});
// Rings as rows, fleet white.
// Rings as rows, white.
for (let ring = 0; ring < rings.length; ring++)
for (let i = 0; i < rings[ring]; i++)
layers.push({
input: await cellImage(first + firsts[ring] + i, TINTS[0], cell),
input: await cellImage(first + firsts[ring] + i, WHITE, cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});