mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
feat(aircraft): draw far-away aircraft as shaded sprites seen from the camera's angle
Aircraft on the map were flat, top-down SVG silhouettes turned along
their course: from an oblique camera they read as paper cut-outs lying
on the ground.
Each aircraft class (and each helicopter rotor frame) is now rendered in
Blender from a sphere of directions into one sheet of shaded sprites
(public/sprites/aircraft-views.webp: 302 views a class, 7.5 degrees
apart from straight above to 30 degrees below the horizon, 4096 x 3648,
grey, 3.1 MB). The renderer lays a contact flat on the ground along its
course, works out where the eye is in that frame and draws the nearest
view, mirrored for the port side. The view is a card standing at the
contact, square to the direction it was rendered from, so between views
the sprite is tilted (foreshortened and turned) as the aircraft would
be; views are not blended. Sprites are neutral, so the fleet, tracked
and military tints still apply.
Renderer: a new `viewSheets` capability, `DrawPort.views(id, sheet)` and
an image `{views, first, fallback}` for icon items (src/data/viewSheet.js
holds the layout and maths, in JS and GLSL). A view row draws from the
sheet's own texture, kept as luminance and alpha; until the sheet has
loaded, and if it cannot load, it draws its flat `fallback` along its
course as before. View sheets are offered on WebGL 2 only, and on
WebGL 1 the icon shader is as it was.
Layers: Flights, Military Flights (fleet and tracked contact) and Local
ADS-B draw views; the TR-3B, airport vehicles, ground stations and
Cockpit's far pips stay flat, as does any renderer without the
capability.
Tools: `npm run build:aircraft-views` bakes the sheet from the repo's
own fleet models (about 7 minutes); scripts/qa-aircraft-view-sheet.mjs
writes contact sheets of a bake and scripts/qa-aircraft-views.mjs
photographs a grid of every class in the app from above, tilted, from
below and round an orbit.
With 5,000 contacts on an M3 Max the frame takes 5.9-6.1 ms against
5.9 ms with the flat glyphs.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
d9d79ebc4d
commit
efdac0ba70
40 files changed
+3535
-109
No files matched your search
@@ -0,0 +1,561 @@
|
||||
"""Bake the aircraft view sheet: every aircraft class 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>]
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
`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
|
||||
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.
|
||||
|
||||
Roll. A frame's image up is where the aircraft'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
|
||||
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
|
||||
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
|
||||
refuses a frame that does not.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
from mathutils import Matrix, Vector
|
||||
|
||||
# --- The sheet's layout (mirrored in src/data/viewSheet.js) -----------------
|
||||
|
||||
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.
|
||||
CLEAR_EDGE_PX = 2
|
||||
|
||||
FORWARD = Vector((-1.0, 0.0, 0.0))
|
||||
RIGHT = Vector((0.0, 1.0, 0.0))
|
||||
UP = Vector((0.0, 0.0, 1.0))
|
||||
|
||||
|
||||
def frame_directions():
|
||||
"""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 i in range(count):
|
||||
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
|
||||
d = (
|
||||
FORWARD * (math.sin(alpha) * math.cos(phi))
|
||||
+ RIGHT * (math.sin(alpha) * math.sin(phi))
|
||||
+ UP * math.cos(alpha)
|
||||
)
|
||||
out.append((ring, i, d.normalized()))
|
||||
return out
|
||||
|
||||
|
||||
def frame_up(d):
|
||||
"""A frame's image up: forward, turned as `UP` turns onto `d`."""
|
||||
return (UP.rotation_difference(d) @ FORWARD).normalized()
|
||||
|
||||
|
||||
# --- Scene -------------------------------------------------------------------
|
||||
|
||||
|
||||
def args_after_dashes():
|
||||
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
|
||||
opts = {
|
||||
"out": "public/sprites",
|
||||
"cell": 64,
|
||||
"supersample": 4,
|
||||
"only": None,
|
||||
"preview": None,
|
||||
"samples": 48,
|
||||
}
|
||||
i = 0
|
||||
while i < len(argv):
|
||||
key = argv[i].lstrip("-")
|
||||
if key not in opts:
|
||||
raise SystemExit(f"unknown option {argv[i]}")
|
||||
opts[key] = argv[i + 1]
|
||||
i += 2
|
||||
opts["cell"] = int(opts["cell"])
|
||||
opts["supersample"] = int(opts["supersample"])
|
||||
opts["samples"] = int(opts["samples"])
|
||||
return opts
|
||||
|
||||
|
||||
def setup_scene(render_px, samples):
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
scene = bpy.context.scene
|
||||
scene.render.engine = "CYCLES"
|
||||
scene.cycles.device = "CPU"
|
||||
scene.cycles.samples = samples
|
||||
scene.cycles.use_denoising = False
|
||||
scene.cycles.max_bounces = 3
|
||||
scene.cycles.pixel_filter_type = "BOX"
|
||||
scene.cycles.filter_width = 1.0
|
||||
scene.render.film_transparent = True
|
||||
scene.render.resolution_x = render_px
|
||||
scene.render.resolution_y = render_px
|
||||
scene.render.resolution_percentage = 100
|
||||
scene.render.image_settings.file_format = "PNG"
|
||||
scene.render.image_settings.color_mode = "RGBA"
|
||||
scene.render.image_settings.color_depth = "8"
|
||||
scene.view_settings.view_transform = "Standard"
|
||||
scene.view_settings.look = "None"
|
||||
scene.display_settings.display_device = "sRGB"
|
||||
|
||||
# Sky: even light from every side, so the underside is lit and the
|
||||
# wings shade the fuselage softly where they meet.
|
||||
world = bpy.data.worlds.new("sky")
|
||||
world.use_nodes = True
|
||||
background = world.node_tree.nodes["Background"]
|
||||
background.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
|
||||
background.inputs["Strength"].default_value = SKY_STRENGTH
|
||||
scene.world = world
|
||||
|
||||
# Sun: from above, leaning toward the nose, in the aircraft's centre
|
||||
# plane (so a mirrored frame is lit as its twin).
|
||||
sun_data = bpy.data.lights.new("sun", "SUN")
|
||||
sun_data.energy = SUN_STRENGTH
|
||||
sun_data.angle = math.radians(18)
|
||||
sun = bpy.data.objects.new("sun", sun_data)
|
||||
scene.collection.objects.link(sun)
|
||||
lean = math.radians(28)
|
||||
to_sun = (UP * math.cos(lean) + FORWARD * math.sin(lean)).normalized()
|
||||
sun.rotation_euler = to_sun.to_track_quat("Z", "Y").to_euler()
|
||||
|
||||
# Fill: a weak light from the eye, so what faces the viewer is lighter
|
||||
# than what turns away and a round body reads as round from any side.
|
||||
fill_data = bpy.data.lights.new("fill", "SUN")
|
||||
fill_data.energy = FILL_STRENGTH
|
||||
fill_data.angle = math.radians(30)
|
||||
fill = bpy.data.objects.new("fill", fill_data)
|
||||
scene.collection.objects.link(fill)
|
||||
|
||||
camera_data = bpy.data.cameras.new("camera")
|
||||
camera_data.type = "ORTHO"
|
||||
camera_data.clip_start = 0.1
|
||||
camera_data.clip_end = 10000
|
||||
camera = bpy.data.objects.new("camera", camera_data)
|
||||
scene.collection.objects.link(camera)
|
||||
scene.camera = camera
|
||||
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)]
|
||||
SUN_STRENGTH = 1.4
|
||||
SKY_STRENGTH = 0.38
|
||||
FILL_STRENGTH = 0.9
|
||||
|
||||
|
||||
def paint_material(paint_ramp=PAINT_RAMP, solid=None):
|
||||
"""Neutral paint that keeps the model's light and dark parts apart."""
|
||||
material = bpy.data.materials.new("paint")
|
||||
material.use_nodes = True
|
||||
nodes = material.node_tree.nodes
|
||||
links = material.node_tree.links
|
||||
bsdf = nodes["Principled BSDF"]
|
||||
bsdf.inputs["Roughness"].default_value = 0.6
|
||||
if solid is not None:
|
||||
bsdf.inputs["Base Color"].default_value = (solid, solid, solid, 1.0)
|
||||
return material
|
||||
colour = nodes.new("ShaderNodeVertexColor")
|
||||
colour.layer_name = "Color"
|
||||
split = nodes.new("ShaderNodeSeparateColor")
|
||||
links.new(colour.outputs["Color"], split.inputs["Color"])
|
||||
red_green = nodes.new("ShaderNodeMath")
|
||||
red_green.operation = "MAXIMUM"
|
||||
links.new(split.outputs[0], red_green.inputs[0])
|
||||
links.new(split.outputs[1], red_green.inputs[1])
|
||||
value = nodes.new("ShaderNodeMath")
|
||||
value.operation = "MAXIMUM"
|
||||
links.new(red_green.outputs[0], value.inputs[0])
|
||||
links.new(split.outputs[2], value.inputs[1])
|
||||
ramp = nodes.new("ShaderNodeValToRGB")
|
||||
elements = ramp.color_ramp.elements
|
||||
while len(elements) < len(paint_ramp):
|
||||
elements.new(0.5)
|
||||
for element, (position, grey) in zip(elements, paint_ramp):
|
||||
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"])
|
||||
return material
|
||||
|
||||
|
||||
def model_parts(path):
|
||||
"""The part table in a fleet model's root node (`render/modelParts.js`)."""
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
length = struct.unpack("<I", data[12:16])[0]
|
||||
document = json.loads(data[20 : 20 + length])
|
||||
for node in document.get("nodes", []):
|
||||
parts = (node.get("extras") or {}).get("parts")
|
||||
if parts:
|
||||
return parts
|
||||
return []
|
||||
|
||||
|
||||
def gltf_to_blender(v):
|
||||
"""A glTF (Y up) vector in Blender's axes (Z up)."""
|
||||
return Vector((v[0], -v[2], v[1]))
|
||||
|
||||
|
||||
def turn_rotors(mesh, parts, degrees, rotor_material):
|
||||
"""Pose the rotors and bound each vertex over its entire rotation."""
|
||||
part_of = mesh.data.attributes.get("_PART")
|
||||
if part_of is None:
|
||||
return {}
|
||||
mesh.data.materials.append(rotor_material)
|
||||
swept_radii = {}
|
||||
to_world = mesh.matrix_world
|
||||
to_local = to_world.inverted()
|
||||
for index, part in enumerate(parts):
|
||||
if part.get("kind") != "spin" or not part["name"].startswith("rotor"):
|
||||
continue
|
||||
pivot = gltf_to_blender(part["pivot"])
|
||||
axis = gltf_to_blender(part["axis"]).normalized()
|
||||
turn = Matrix.Rotation(math.radians(degrees), 4, axis)
|
||||
move = to_local @ Matrix.Translation(pivot) @ turn @ Matrix.Translation(-pivot) @ to_world
|
||||
if part_of.domain == "POINT":
|
||||
members = [i for i, item in enumerate(part_of.data) if item.value == index]
|
||||
else:
|
||||
members = sorted(
|
||||
{
|
||||
mesh.data.loops[i].vertex_index
|
||||
for i, item in enumerate(part_of.data)
|
||||
if item.value == index
|
||||
}
|
||||
)
|
||||
for i in members:
|
||||
vertex = mesh.data.vertices[i]
|
||||
relative = to_world @ vertex.co - pivot
|
||||
axial = relative.dot(axis)
|
||||
center = pivot + axial * axis
|
||||
# The sweep lies in a plane perpendicular to the axis. Its
|
||||
# farthest point adds the circle radius to the projected center.
|
||||
radial = (relative - axial * axis).length
|
||||
offset = (center - center.dot(axis) * axis).length
|
||||
swept_radii[i] = math.hypot(center.dot(axis), offset + radial)
|
||||
vertex.co = move @ vertex.co
|
||||
for polygon in mesh.data.polygons:
|
||||
if all(i in swept_radii for i in polygon.vertices):
|
||||
polygon.material_index = 1
|
||||
return swept_radii
|
||||
|
||||
|
||||
def load_model(path, material, rotor_deg, rotor_material):
|
||||
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 []
|
||||
radius = 0.0
|
||||
for mesh in meshes:
|
||||
mesh.data.materials.clear()
|
||||
mesh.data.materials.append(material)
|
||||
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
|
||||
for vertex in mesh.data.vertices:
|
||||
distance = swept_radii.get(vertex.index)
|
||||
if distance is None:
|
||||
distance = (mesh.matrix_world @ vertex.co).length
|
||||
radius = max(radius, distance)
|
||||
return objects, radius
|
||||
|
||||
|
||||
def aim(camera, fill, d, radius):
|
||||
fill.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
|
||||
up = frame_up(d)
|
||||
right = up.cross(d).normalized()
|
||||
rotation = Matrix((right, up, d)).transposed()
|
||||
camera.matrix_world = Matrix.Translation(d * (radius * 4 + 10)) @ rotation.to_4x4()
|
||||
camera.data.ortho_scale = 2 * radius / FILL
|
||||
|
||||
|
||||
# --- Pixels ------------------------------------------------------------------
|
||||
|
||||
|
||||
def read_pixels(path):
|
||||
image = bpy.data.images.load(path)
|
||||
width, height = image.size
|
||||
pixels = np.array(image.pixels[:], dtype=np.float32).reshape(height, width, 4)
|
||||
bpy.data.images.remove(image)
|
||||
return pixels[::-1] # top row first
|
||||
|
||||
|
||||
def dilate(alpha, radius):
|
||||
out = alpha.copy()
|
||||
for dy in range(-radius, radius + 1):
|
||||
for dx in range(-radius, radius + 1):
|
||||
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
|
||||
continue
|
||||
shifted = np.zeros_like(alpha)
|
||||
ys = slice(max(dy, 0), alpha.shape[0] + min(dy, 0))
|
||||
xs = slice(max(dx, 0), alpha.shape[1] + min(dx, 0))
|
||||
yd = slice(max(-dy, 0), alpha.shape[0] + min(-dy, 0))
|
||||
xd = slice(max(-dx, 0), alpha.shape[1] + min(-dx, 0))
|
||||
shifted[ys, xs] = alpha[yd, xd]
|
||||
np.maximum(out, shifted, out=out)
|
||||
return out
|
||||
|
||||
|
||||
def disk_sum(values, radius):
|
||||
"""Each pixel's sum of `values` over a disk of `radius` around it."""
|
||||
out = values.copy()
|
||||
for dy in range(-radius, radius + 1):
|
||||
for dx in range(-radius, radius + 1):
|
||||
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
|
||||
continue
|
||||
ys = slice(max(dy, 0), values.shape[0] + min(dy, 0))
|
||||
xs = slice(max(dx, 0), values.shape[1] + min(dx, 0))
|
||||
yd = slice(max(-dy, 0), values.shape[0] + min(-dy, 0))
|
||||
xd = slice(max(-dx, 0), values.shape[1] + min(-dx, 0))
|
||||
out[ys, xs] += values[yd, xd]
|
||||
return out
|
||||
|
||||
|
||||
# Neutral, as the whole sheet is: the renderer keeps it as grey + alpha.
|
||||
EDGE_RGB = np.array([0.045, 0.045, 0.045], dtype=np.float32)
|
||||
EDGE_ALPHA = 0.62
|
||||
|
||||
|
||||
def inside_mask(size, supersample):
|
||||
"""1 within the disk that keeps CLEAR_EDGE_PX of the cell clear, fading
|
||||
to 0 over half a cell pixel inside its rim. Only what the bake adds round
|
||||
the model (its thickening and dark edge) is faded by it: the model's own
|
||||
bounding sphere ends at FILL, inside it."""
|
||||
cell = size / supersample
|
||||
centre = size / 2
|
||||
y, x = np.mgrid[0:size, 0:size] + 0.5
|
||||
r = np.hypot(x - centre, y - centre) / supersample
|
||||
outer = cell / 2 - CLEAR_EDGE_PX
|
||||
return np.clip((outer - r) / 0.5, 0, 1).astype(np.float32)
|
||||
|
||||
|
||||
def finish(pixels, supersample, bold_px=0.0):
|
||||
"""Thicken the sprite by `bold_px` cell pixels, put a dark edge round it,
|
||||
then bring it down to the cell by area."""
|
||||
rgb = pixels[..., :3]
|
||||
alpha = pixels[..., 3]
|
||||
premultiplied = rgb * alpha[..., None]
|
||||
mask = inside_mask(pixels.shape[0], supersample)
|
||||
radius = round(supersample * bold_px)
|
||||
if radius > 0:
|
||||
# Under the model, its own colour spread outward: each new pixel the
|
||||
# mean colour of the model round it.
|
||||
grown = dilate(alpha, radius) * mask
|
||||
weight = disk_sum(alpha, radius)
|
||||
spread = disk_sum(premultiplied, radius) / np.maximum(weight, 1e-6)[..., None]
|
||||
under = grown * (1 - alpha)
|
||||
premultiplied = premultiplied + spread * under[..., None]
|
||||
alpha = alpha + under
|
||||
# About 0.9 cell pixels of edge.
|
||||
halo = dilate(alpha, max(1, round(supersample * 0.9))) * EDGE_ALPHA * mask
|
||||
out_alpha = alpha + halo * (1 - alpha)
|
||||
premultiplied = premultiplied + EDGE_RGB * (halo * (1 - alpha))[..., None]
|
||||
size = pixels.shape[0] // supersample
|
||||
|
||||
def area(a):
|
||||
return a.reshape(size, supersample, size, supersample, -1).mean(axis=(1, 3))
|
||||
|
||||
small_alpha = area(out_alpha[..., None])[..., 0]
|
||||
small = area(premultiplied)
|
||||
colour = np.where(
|
||||
small_alpha[..., None] > 1e-4, small / np.maximum(small_alpha[..., None], 1e-4), 0
|
||||
)
|
||||
return np.dstack([np.clip(colour, 0, 1), np.clip(small_alpha, 0, 1)])
|
||||
|
||||
|
||||
# How far a frame's red, green and blue may differ (in 0..1) before the bake
|
||||
# refuses it as not grey: rendering noise, never a colour.
|
||||
GREY_TOLERANCE = 1.5 / 255
|
||||
|
||||
|
||||
def to_grey(frame, name, n):
|
||||
"""The frame with equal red, green and blue (their mean), refusing one
|
||||
whose channels differ by more than rendering noise: the sheet ships as
|
||||
grey (`"grey": true`), its red channel read as the grey."""
|
||||
rgb = frame[..., :3]
|
||||
lit = frame[..., 3] > 0
|
||||
spread = (rgb.max(axis=2) - rgb.min(axis=2))[lit]
|
||||
if spread.size and spread.max() > GREY_TOLERANCE:
|
||||
raise SystemExit(
|
||||
f"{name} frame {n}: not grey (its channels differ by "
|
||||
f"{spread.max() * 255:.1f}/255); the sheet ships as grey"
|
||||
)
|
||||
grey = rgb.mean(axis=2, keepdims=True)
|
||||
return np.dstack([np.repeat(grey, 3, axis=2), frame[..., 3:]])
|
||||
|
||||
|
||||
def check_clear_edge(frame, name, n):
|
||||
"""Refuse a frame with anything but transparent pixels near its edge."""
|
||||
e = CLEAR_EDGE_PX
|
||||
alpha = frame[..., 3]
|
||||
band = np.concatenate(
|
||||
[alpha[:e].ravel(), alpha[-e:].ravel(), alpha[:, :e].ravel(), alpha[:, -e:].ravel()]
|
||||
)
|
||||
if band.max() >= 0.5 / 255:
|
||||
raise SystemExit(
|
||||
f"{name} frame {n}: pixels within {e} px of the cell edge "
|
||||
f"(alpha {band.max():.3f}); the fill leaves them no room"
|
||||
)
|
||||
|
||||
|
||||
def save_png(path, pixels):
|
||||
height, width = pixels.shape[:2]
|
||||
image = bpy.data.images.new("out", width, height, alpha=True)
|
||||
image.alpha_mode = "STRAIGHT"
|
||||
image.pixels.foreach_set(pixels[::-1].astype(np.float32).ravel())
|
||||
image.filepath_raw = path
|
||||
image.file_format = "PNG"
|
||||
image.save()
|
||||
bpy.data.images.remove(image)
|
||||
|
||||
|
||||
# --- Bake --------------------------------------------------------------------
|
||||
|
||||
|
||||
def main():
|
||||
opts = args_after_dashes()
|
||||
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()
|
||||
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)
|
||||
manifest = {
|
||||
"image": "aircraft-views.webp",
|
||||
"cellPx": cell,
|
||||
"columns": COLUMNS,
|
||||
"rows": rows,
|
||||
"ringStepDeg": RING_STEP_DEG,
|
||||
"rings": 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
|
||||
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,
|
||||
rotor_material,
|
||||
)
|
||||
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))
|
||||
check_clear_edge(frame, name, n)
|
||||
frame = to_grey(frame, name, n)
|
||||
at = first + n
|
||||
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)
|
||||
save_png(
|
||||
os.path.join(opts["preview"], f"{name}-r{ring}-{i:02d}.png"), frame
|
||||
)
|
||||
for obj in objects:
|
||||
bpy.data.objects.remove(obj, do_unlink=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:
|
||||
json.dump(manifest, f, indent=1)
|
||||
f.write("\n")
|
||||
print(f"wrote {out}/aircraft-views.png ({COLUMNS * cell}x{rows * cell})")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* build-aircraft-views.mjs: bake the aircraft view sheet 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`.
|
||||
*
|
||||
* Run: npm run build:aircraft-views [-- --only airliner,light] [--out public/sprites]
|
||||
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
|
||||
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (name, fallback) => {
|
||||
const i = argv.indexOf(name);
|
||||
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
|
||||
};
|
||||
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
|
||||
const ONLY = opt('--only', null);
|
||||
|
||||
function blender() {
|
||||
if (process.env.BLENDER) return process.env.BLENDER;
|
||||
const which = spawnSync('which', ['blender'], { encoding: 'utf8' });
|
||||
if (which.status === 0 && which.stdout.trim()) return which.stdout.trim();
|
||||
const mac = '/Applications/Blender.app/Contents/MacOS/Blender';
|
||||
if (fs.existsSync(mac)) return mac;
|
||||
throw new Error('no Blender: set BLENDER to its executable');
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a sheet the manifest calls grey whose red, green and blue differ
|
||||
* anywhere: the renderer reads its red channel as the grey.
|
||||
*/
|
||||
async function assertGrey(file) {
|
||||
const { data, info } = await sharp(file)
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
for (let i = 0; i < data.length; i += info.channels)
|
||||
if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
|
||||
const pixel = i / info.channels;
|
||||
throw new Error(
|
||||
`the sheet is not grey at (${pixel % info.width}, ${Math.floor(pixel / info.width)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'aircraft-views-'));
|
||||
try {
|
||||
const bake = spawnSync(
|
||||
blender(),
|
||||
[
|
||||
'-b',
|
||||
'--factory-startup',
|
||||
'--python',
|
||||
path.join(root, 'scripts', 'build-aircraft-view-sheet.py'),
|
||||
'--',
|
||||
'--out',
|
||||
scratch,
|
||||
...(ONLY ? ['--only', ONLY] : []),
|
||||
],
|
||||
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' },
|
||||
);
|
||||
for (const line of bake.stdout.split('\n'))
|
||||
if (/^(baked|wrote)\b/.test(line)) console.log(line);
|
||||
if (bake.status !== 0) {
|
||||
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
|
||||
throw new Error(`the bake failed (exit ${bake.status})`);
|
||||
}
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(scratch, 'aircraft-views.json'), 'utf8'),
|
||||
);
|
||||
const png = path.join(scratch, 'aircraft-views.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'),
|
||||
);
|
||||
const kb = Math.round(fs.statSync(webp).size / 1024);
|
||||
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
|
||||
} finally {
|
||||
fs.rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
@@ -68,7 +68,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -1303,7 +1304,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/satellites/issMounts.js",
|
||||
"src/layers/satellites/tiangongMounts.js"
|
||||
"src/layers/satellites/tiangongMounts.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -1715,7 +1717,8 @@
|
||||
"src/data/liveStreams.js",
|
||||
"src/data/youtubeApi.js",
|
||||
"src/data/youtubeLivePlayer.js",
|
||||
"src/ui/liveControls.js"
|
||||
"src/ui/liveControls.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -1919,7 +1922,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/scenes/storyTags.js",
|
||||
"src/scenes/storyThumb.js"
|
||||
"src/scenes/storyThumb.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
|
||||
},
|
||||
@@ -2086,7 +2090,9 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/flights/placed.js",
|
||||
"src/data/courseFromFixes.js"
|
||||
"src/data/courseFromFixes.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2232,7 +2238,9 @@
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/flights/placed.js",
|
||||
"src/data/courseFromFixes.js",
|
||||
"src/data/approxDistance.js"
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2390,7 +2398,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/vessels/photos.js",
|
||||
"src/data/openVesselPhoto.js"
|
||||
"src/data/openVesselPhoto.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2521,7 +2530,8 @@
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/sky/assets.js",
|
||||
"src/render/cesium/cardPreviews.js"
|
||||
"src/render/cesium/cardPreviews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -2619,7 +2629,8 @@
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/time/frameWait.js"
|
||||
"src/time/frameWait.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -2771,7 +2782,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2894,7 +2906,8 @@
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js"
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "satellite.js", "kdbush"]
|
||||
},
|
||||
@@ -2998,7 +3011,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3110,7 +3124,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -3192,7 +3207,8 @@
|
||||
"src/data/installationFeedback.js",
|
||||
"src/ui/layerNames.js",
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/ui/statusText.js"
|
||||
"src/ui/statusText.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3318,7 +3334,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -3512,7 +3529,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -3642,7 +3660,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -3735,7 +3754,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -3847,7 +3867,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3922,7 +3943,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -4063,7 +4085,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -5597,7 +5620,9 @@
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js"
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"hls.js",
|
||||
@@ -6453,7 +6478,9 @@
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/layers/satellites/tiangongModel.js"
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"hls.js",
|
||||
@@ -6602,7 +6629,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -6716,7 +6744,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -7551,7 +7580,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -7681,7 +7711,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -7993,7 +8024,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -8442,7 +8474,8 @@
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/recession.js",
|
||||
"src/render/modelParts.js"
|
||||
"src/render/modelParts.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/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
|
||||
* 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.
|
||||
*
|
||||
* 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]
|
||||
* [--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';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (name, fallback) => {
|
||||
const i = argv.indexOf(name);
|
||||
return i >= 0 && argv[i + 1] ? argv[i + 1] : 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 sheetPath = path.resolve(
|
||||
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
|
||||
);
|
||||
const { cellPx: cell, columns, rings } = manifest;
|
||||
const firsts = [];
|
||||
rings.reduce((at, count) => (firsts.push(at), at + count), 0);
|
||||
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));
|
||||
/** Frames shown shrunk, as ring and index: straight above, oblique from
|
||||
* ahead and to the right, abeam on the horizon, and from below, abeam. */
|
||||
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)],
|
||||
];
|
||||
|
||||
const sheet = sharp(sheetPath, { limitInputPixels: false });
|
||||
const { data: pixels, info } = await sheet
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
/** One cell as raw RGBA, tinted. */
|
||||
function cellPixels(index, tint) {
|
||||
const out = Buffer.alloc(cell * cell * 4);
|
||||
const left = (index % columns) * cell;
|
||||
const top = Math.floor(index / columns) * cell;
|
||||
for (let y = 0; y < cell; y++)
|
||||
for (let x = 0; x < cell; x++) {
|
||||
const from = ((top + y) * info.width + left + x) * 4;
|
||||
const to = (y * cell + x) * 4;
|
||||
for (let c = 0; c < 3; c++)
|
||||
out[to + c] = Math.round(pixels[from + c] * tint.rgb[c]);
|
||||
out[to + 3] = pixels[from + 3];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function cellImage(index, tint, size) {
|
||||
let image = sharp(cellPixels(index, tint), {
|
||||
raw: { width: cell, height: cell, channels: 4 },
|
||||
});
|
||||
if (size !== cell) image = image.resize(size, size, { kernel: 'lanczos3' });
|
||||
else if (ZOOM !== 1)
|
||||
image = image.resize(cell * ZOOM, cell * ZOOM, { kernel: 'nearest' });
|
||||
return image.png().toBuffer();
|
||||
}
|
||||
|
||||
async function subjectSheet(name, first) {
|
||||
const tile = cell * ZOOM;
|
||||
const panelW = widest * tile;
|
||||
const panelH = rings.length * tile;
|
||||
const stripH = Math.max(...SIZES) + GAP;
|
||||
const blockH = panelH + GAP + TINTS.length * stripH;
|
||||
const width = GROUNDS.length * (panelW + GAP) + GAP;
|
||||
const height = blockH + 2 * GAP;
|
||||
const layers = [];
|
||||
for (const [g, ground] of GROUNDS.entries()) {
|
||||
const x0 = GAP + g * (panelW + GAP);
|
||||
layers.push({
|
||||
input: {
|
||||
create: {
|
||||
width: panelW,
|
||||
height: blockH,
|
||||
channels: 4,
|
||||
background: ground.css,
|
||||
},
|
||||
},
|
||||
left: x0,
|
||||
top: GAP,
|
||||
});
|
||||
// Rings as rows, fleet 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),
|
||||
left: x0 + i * tile,
|
||||
top: GAP + ring * tile,
|
||||
});
|
||||
// The picked frames shrunk to drawn sizes, one row a tint.
|
||||
for (const [t, tint] of TINTS.entries()) {
|
||||
let x = x0 + GAP;
|
||||
const y = GAP + panelH + GAP + t * stripH;
|
||||
for (const [ring, index] of PICKS)
|
||||
for (const size of SIZES) {
|
||||
layers.push({
|
||||
input: await cellImage(first + firsts[ring] + index, tint, size),
|
||||
left: x,
|
||||
top: y + (stripH - GAP - size),
|
||||
});
|
||||
x += size + 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
const file = path.join(OUT, `${name}.png`);
|
||||
await sharp({
|
||||
create: { width, height, channels: 4, background: '#111111' },
|
||||
})
|
||||
.composite(layers)
|
||||
.png()
|
||||
.toFile(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
for (const [name, entry] of Object.entries(manifest.subjects)) {
|
||||
if (ONLY.length && !ONLY.includes(name)) continue;
|
||||
const first = typeof entry === 'number' ? entry : entry.first;
|
||||
console.log('wrote', await subjectSheet(name, first));
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* qa-aircraft-views.mjs: screenshots of the aircraft view sheet in the app.
|
||||
*
|
||||
* Seeds a grid of synthetic military contacts (every icon class down the
|
||||
* rows, eight courses across) through a fetch shim, then photographs it from
|
||||
* straight above, tilted from several sides and from below, so a person can
|
||||
* check that each sprite shows its aircraft from where the camera is: the
|
||||
* nose along the course, the far wing foreshortened, the underside from
|
||||
* below.
|
||||
*
|
||||
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
|
||||
* [--layer military|flights] [--block-sheet] [--headful]
|
||||
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
|
||||
* Needs the dev server (`npm run dev`).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import puppeteer from 'puppeteer';
|
||||
import { stubPlanespotters } from './qa-photo-stub.mjs';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (name, fallback) => {
|
||||
const i = argv.indexOf(name);
|
||||
return i >= 0 && argv[i + 1] ? argv[i + 1] : 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).
|
||||
const LAYER = opt('--layer', 'military');
|
||||
// Fail the sheet's request: the contacts should draw their flat glyphs.
|
||||
const BLOCK_SHEET = argv.includes('--block-sheet');
|
||||
const GPU = argv.includes('--gpu');
|
||||
|
||||
// A type code for each icon class (aircraftClass.js).
|
||||
const CLASSES = [
|
||||
['airliner', 'A320'],
|
||||
['widebody', 'C17'],
|
||||
['quadjet', 'B744'],
|
||||
['turboprop', 'C130'],
|
||||
['light', 'C172'],
|
||||
['glider', 'DISC'],
|
||||
['fastjet', 'F16'],
|
||||
['bizjet', 'GLF4'],
|
||||
['uav', 'Q9'],
|
||||
['helicopter', 'H60'],
|
||||
];
|
||||
// The classes a flight's emitter category gives (OpenSky has no type code).
|
||||
const CATEGORIES = [
|
||||
['airliner', 4],
|
||||
['widebody', 6],
|
||||
['light', 2],
|
||||
['fastjet', 7],
|
||||
['glider', 9],
|
||||
['helicopter', 8],
|
||||
];
|
||||
const ROWS = LAYER === 'flights' ? CATEGORIES : CLASSES;
|
||||
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
|
||||
const CENTRE = { lon: -97.74, lat: 30.3 };
|
||||
const STEP_DEG = 0.03;
|
||||
const ALT_FT = 12000;
|
||||
|
||||
const contacts = [];
|
||||
ROWS.forEach(([klass, type], row) =>
|
||||
COURSES.forEach((courseDeg, column) =>
|
||||
contacts.push({
|
||||
hex: `ee${row.toString(16)}${column.toString(16)}00`.slice(0, 6),
|
||||
flight: `${klass.slice(0, 4).toUpperCase()}${courseDeg}`,
|
||||
t: type,
|
||||
klass,
|
||||
courseDeg,
|
||||
lon: CENTRE.lon + (column - (COURSES.length - 1) / 2) * STEP_DEG,
|
||||
lat: CENTRE.lat - (row - (ROWS.length - 1) / 2) * STEP_DEG,
|
||||
altFt: ALT_FT,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Each shot: where the camera looks from. `heading` is the way it looks
|
||||
// (degrees clockwise from north), `pitch` down from level, `rangeKm` from
|
||||
// the grid's centre at the contacts' height.
|
||||
const SHOTS = [
|
||||
{ name: '1-above', heading: 0, pitch: -90, rangeKm: 44 },
|
||||
{ name: '2-tilt30-north', heading: 0, pitch: -60, rangeKm: 46 },
|
||||
{ name: '3-tilt55-north', heading: 0, pitch: -35, rangeKm: 50 },
|
||||
{ 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 },
|
||||
];
|
||||
|
||||
// `--orbit`: the camera swung round the grid a little at a time, a frame
|
||||
// each step, to watch the sprites turn from one view to the next.
|
||||
const ORBIT_STEP_DEG = Number(opt('--orbit-step', 2));
|
||||
const ORBIT_SHOTS = Array.from(
|
||||
{ length: Math.floor(90 / ORBIT_STEP_DEG) + 1 },
|
||||
(_, i) => ({
|
||||
name: `orbit-${String(i).padStart(3, '0')}`,
|
||||
heading: i * ORBIT_STEP_DEG,
|
||||
pitch: Number(opt('--orbit-pitch', -35)),
|
||||
rangeKm: 50,
|
||||
settleMs: i === 0 ? 6000 : 900,
|
||||
}),
|
||||
);
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function main() {
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
const browser = await puppeteer.launch({
|
||||
headless: HEADFUL ? false : 'new',
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
...(GPU ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
|
||||
'--disable-web-security',
|
||||
'--disable-background-timer-throttling',
|
||||
'--disable-renderer-backgrounding',
|
||||
'--window-size=1500,1000',
|
||||
],
|
||||
});
|
||||
const errors = [];
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await stubPlanespotters(page);
|
||||
await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 2 });
|
||||
page.on('console', (msg) => {
|
||||
if (
|
||||
msg.type() === 'error' &&
|
||||
!/Failed to load resource/i.test(msg.text())
|
||||
)
|
||||
errors.push(msg.text());
|
||||
});
|
||||
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
|
||||
|
||||
if (BLOCK_SHEET) {
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
if (request.isInterceptResolutionHandled()) return;
|
||||
if (/\/sprites\/aircraft-views\./.test(request.url())) request.abort();
|
||||
else request.continue();
|
||||
});
|
||||
}
|
||||
await page.evaluateOnNewDocument(
|
||||
(seed) => {
|
||||
const realFetch = window.fetch.bind(window);
|
||||
// Each contact flies its course, slowly: a feed whose fixes stand
|
||||
// still while claiming a track makes the layers work a heading out
|
||||
// of no movement, and the contacts turn north over a run.
|
||||
const SPEED_MPS = 6;
|
||||
const started = Date.now();
|
||||
const at = (c) => {
|
||||
const flown = (SPEED_MPS * (Date.now() - started)) / 1000;
|
||||
const course = (c.courseDeg * Math.PI) / 180;
|
||||
return {
|
||||
lat: c.lat + (flown * Math.cos(course)) / 111320,
|
||||
lon:
|
||||
c.lon +
|
||||
(flown * Math.sin(course)) /
|
||||
(111320 * Math.cos((c.lat * Math.PI) / 180)),
|
||||
};
|
||||
};
|
||||
const json = (body) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
window.fetch = (input, init) => {
|
||||
const url =
|
||||
typeof input === 'string' ? input : (input && input.url) || '';
|
||||
if (url.includes('/api/openai/hud-summary'))
|
||||
return Promise.resolve(json({ summary: 'view QA' }));
|
||||
if (url.includes('/api/military/track'))
|
||||
return Promise.resolve(
|
||||
json({ timestamp: Math.floor(Date.now() / 1000), trace: [] }),
|
||||
);
|
||||
if (url.includes('/api/military'))
|
||||
return Promise.resolve(
|
||||
json({
|
||||
msg: 'No error',
|
||||
now: Date.now(),
|
||||
ac: (seed.layer === 'military' ? seed.contacts : []).map(
|
||||
(c) => ({
|
||||
hex: c.hex,
|
||||
flight: c.flight,
|
||||
...at(c),
|
||||
alt_baro: c.altFt,
|
||||
track: c.courseDeg,
|
||||
gs: SPEED_MPS * 1.9438,
|
||||
t: c.t,
|
||||
r: `QA-${c.hex.slice(-3)}`,
|
||||
ownOp: 'QA',
|
||||
seen_pos: 0,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (url.includes('/api/flights/track'))
|
||||
return Promise.resolve(json({ path: [] }));
|
||||
if (url.includes('/api/flights') && seed.layer === 'flights') {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
return Promise.resolve(
|
||||
json({
|
||||
time: now,
|
||||
states: seed.contacts.map((c) => [
|
||||
c.hex,
|
||||
c.flight,
|
||||
'QA',
|
||||
now,
|
||||
now,
|
||||
at(c).lon,
|
||||
at(c).lat,
|
||||
c.altFt * 0.3048,
|
||||
false,
|
||||
SPEED_MPS,
|
||||
c.courseDeg,
|
||||
0,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
0,
|
||||
c.t,
|
||||
]),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (url.includes('/api/adsbdb/'))
|
||||
return Promise.resolve(json({ found: false }));
|
||||
return realFetch(input, init);
|
||||
};
|
||||
},
|
||||
{ layer: LAYER, contacts },
|
||||
);
|
||||
|
||||
console.log(`Loading ${APP_URL} ...`);
|
||||
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||
await page.waitForFunction(
|
||||
() => 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);
|
||||
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
|
||||
if (seeded !== contacts.length)
|
||||
throw new Error(
|
||||
`the ${LAYER} layer took ${seeded} of ${contacts.length} contacts`,
|
||||
);
|
||||
// Past the layer's render delay, so every contact is drawn.
|
||||
await sleep(20000);
|
||||
|
||||
for (const shot of argv.includes('--orbit') ? ORBIT_SHOTS : SHOTS) {
|
||||
await page.evaluate(
|
||||
({ shot, centre, altM }) => {
|
||||
const { viewer } = window.__godsEyeView;
|
||||
const Cartesian3 = viewer.camera.position.constructor;
|
||||
const heading = (shot.heading * Math.PI) / 180;
|
||||
const pitch = (shot.pitch * Math.PI) / 180;
|
||||
const range = shot.rangeKm * 1000;
|
||||
// The eye sits `range` back along the way it looks.
|
||||
const east = -range * Math.sin(heading) * Math.cos(pitch);
|
||||
const north = -range * Math.cos(heading) * Math.cos(pitch);
|
||||
const up = -range * Math.sin(pitch);
|
||||
const lat = centre.lat + north / 111320;
|
||||
const lon =
|
||||
centre.lon +
|
||||
east / (111320 * Math.cos((centre.lat * Math.PI) / 180));
|
||||
viewer.camera.setView({
|
||||
destination: Cartesian3.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
Math.max(50, altM + up),
|
||||
),
|
||||
orientation: { heading, pitch, roll: 0 },
|
||||
});
|
||||
viewer.scene.requestRender();
|
||||
},
|
||||
{ shot, centre: CENTRE, altM: ALT_FT * 0.3048 },
|
||||
);
|
||||
await sleep(shot.settleMs ?? 6000);
|
||||
// The globe's own canvas, read right after a render: no HUD, dialogs
|
||||
// or label overlays in the way.
|
||||
const png = await page.evaluate(() => {
|
||||
const { viewer } = window.__godsEyeView;
|
||||
viewer.scene.render();
|
||||
return viewer.scene.canvas.toDataURL('image/png');
|
||||
});
|
||||
const file = path.join(OUT, `${shot.name}.png`);
|
||||
fs.writeFileSync(file, Buffer.from(png.split(',')[1], 'base64'));
|
||||
console.log(` wrote ${file}`);
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (errors.length) {
|
||||
console.log(`\nConsole errors (${errors.length}):`);
|
||||
for (const error of errors.slice(0, 20)) console.log(` ${error}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user