The map draws its own icons on an overlay (#967)

An overlay drawn with a style of its own names icons, which needed the sprite sheet that style was made for.  The map now ships icons for overlays, the Maki and Temaki sets (both CC0), and always draws those, in both viewers.

The sprite sheet is the translation: its index lists every icon under its own name, under each other name it answers to (modules/map/icons/aliases.json), and in both spellings of each.  A name with no icon is drawn as a plain dot.  The icons are signed distance fields, so a style's icon color and halo apply.

A pattern is not an icon: what it filled (a fill, a line or an extrusion) is drawn in a translucent color, where removing a pattern used to leave MapLibre's opaque black.

A sprite sheet beside a map file is no longer used, served or reported.  wrolpi/scripts/build_map_icons.py builds the sheet from the SVGs; the sheet is committed.
This commit is contained in:
lrnselfreliance 2026-11-13 17:59:03 -07:00 • committed by Roland
parent 177d0dba4b
commit b2b8e2075c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
794 changed files with 4193 additions and 252 deletions

View file

@ -32,7 +32,7 @@ import {
setOverlayEnabled,
setOverlayLayerEnabled,
} from "./mapOverlays";
import {loadOverlayStyles, overlaySpriteId, overlaySpriteUrl} from "./mapOverlayStyle";
import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle";
// Layer groups matching the standalone viewer.
const LAYER_GROUPS = {
@ -213,16 +213,19 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
addOverlaysToStyle(styleSources, allLayers, overlays, overlayState);
// An overlay drawn with its own style may bring its own icons: a second sprite beside the
// basemap's, whose images are named `<sprite id>:<image>`.
// An overlay drawn with a style of its own names icons: the map's overlay icons, a second
// sprite beside the basemap's. It is only asked for when there is such an overlay.
const basemapSprite = `${window.location.origin}/map-assets/sprites/${sprite}`;
const overlaySprites = overlays.filter(f => isStyledOverlay(f) && f.has_sprite)
.map(f => ({id: overlaySpriteId(f), url: overlaySpriteUrl(f)}));
const overlayIcons = {
id: OVERLAY_ICONS_SPRITE_ID,
url: `${window.location.origin}/map-assets/sprites/${OVERLAY_ICONS_SPRITE_ID}`,
};
const styled = overlays.some(isStyledOverlay);
return {
version: 8,
glyphs: "/map-assets/fonts/{fontstack}/{range}.pbf",
sprite: overlaySprites.length ? [{id: "default", url: basemapSprite}, ...overlaySprites] : basemapSprite,
sprite: styled ? [{id: "default", url: basemapSprite}, overlayIcons] : basemapSprite,
sources: styleSources,
layers: allLayers,
};
@ -793,6 +796,8 @@ export default function MapViewer() {
});
});
map.on("click", () => setContextMenu(null));
// A name the overlay icons do not have is drawn as a plain dot.
map.on("styleimagemissing", (e) => addMissingOverlayIcon(map, e.id));
map.on("movestart", () => setContextMenu(null));
// Click a POI to see the details the pmtiles file already has (kind, detail, elevation).

View file

@ -292,7 +292,7 @@ describe('the basemap layer groups', () => {
});
describe('an overlay with a style beside it', () => {
const STYLED = {...FEATURES, style_path: 'map/extras/style.json', has_sprite: true};
const STYLED = {...FEATURES, style_path: 'map/extras/style.json'};
const STYLE = {
version: 8,
sources: {features: {type: 'vector', url: 'https://example.com/features.json'}},
@ -319,22 +319,19 @@ describe('an overlay with a style beside it', () => {
});
};
test('is drawn with that style and its own sprite', async () => {
test("is drawn with that style and the map's own icons", async () => {
serveStyle(STYLE);
const map = await renderViewer([PLANET, STYLED]);
expect(global.fetch).toHaveBeenCalledWith('/media/map/extras/style.json');
const overlayLayers = map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles');
expect(overlayLayers.map(l => l.id)).toEqual([STYLED_LINES, STYLED_TOWERS]);
expect(map.getLayer(STYLED_TOWERS).layout['icon-image']).toBe('overlay:extras/features.pmtiles:tower');
expect(map.getLayer(STYLED_TOWERS).layout['icon-image']).toBe('overlay-icons:tower');
expect(map.getLayer(STYLED_TOWERS).layout['text-font']).toEqual(['Noto Sans Medium']);
// The basemap keeps its sprite; the overlay's is beside it.
// The basemap keeps its sprite; the overlay icons are beside it.
expect(map.style.sprite).toEqual([
{id: 'default', url: `${window.location.origin}/map-assets/sprites/light`},
{
id: 'overlay:extras/features.pmtiles',
url: `${window.location.origin}/api/map/files/sprite/extras/features.pmtiles`,
},
{id: 'overlay-icons', url: `${window.location.origin}/map-assets/sprites/overlay-icons`},
]);
// Nothing of the style's own sources reaches the map.
expect(JSON.stringify(map.style)).not.toContain('example.com');
@ -372,7 +369,7 @@ describe('an overlay with a style beside it', () => {
const map = await renderViewer([PLANET, STYLED]);
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
.toEqual([WATER, POWER_LINES, TOWERS]);
// No overlay sprite is asked for.
// The overlay icons are only asked for when a style names them.
expect(map.style.sprite).toBe(`${window.location.origin}/map-assets/sprites/light`);
});
});

View file

@ -3,7 +3,9 @@ import {
bundledFont,
loadOverlayStyle,
loadOverlayStyles,
overlaySpriteUrl,
addMissingOverlayIcon,
missingOverlayIcon,
OVERLAY_ICONS_SPRITE_ID,
} from './mapOverlayStyle';
import {buildOverlayLayers, overlayToggleLayers, setOverlayEnabled, setOverlayLayerEnabled} from './mapOverlays';
@ -12,11 +14,13 @@ import {buildOverlayLayers, overlayToggleLayers, setOverlayEnabled, setOverlayLa
const layer = (id) => ({id, geometry: null, minzoom: 0, maxzoom: 13, description: null});
const FILE = {
name: 'features.pmtiles', map_path: 'extras/features.pmtiles', path: 'map/extras/features.pmtiles',
kind: 'overlay', tile_type: 'mvt', visible: true, has_sprite: true,
kind: 'overlay', tile_type: 'mvt', visible: true,
style_path: 'map/extras/style.json',
vector_layers: [layer('repeaters'), layer('roads'), layer('parks')],
};
const SOURCE = 'overlay:extras/features.pmtiles';
// The map's own icons: every image a style names is one of these.
const ICONS = 'overlay-icons';
// As a style arrives: its own source names and URLs, and layers of sources which are not this file.
const STYLE = {
@ -211,9 +215,10 @@ describe('icons', () => {
return adapted(style, file);
};
test("an image is one of the overlay's own sprite", () => {
expect(byId(adapted(), 'repeaters').layout['icon-image']).toBe(`${SOURCE}:ham_radio`);
expect(byId(withIcon('{class}_11'), 'repeaters').layout['icon-image']).toBe(`${SOURCE}:{class}_11`);
test("an image is one of the map's overlay icons, never of the style's own sprite", () => {
expect(OVERLAY_ICONS_SPRITE_ID).toBe(ICONS);
expect(byId(adapted(), 'repeaters').layout['icon-image']).toBe(`${ICONS}:ham_radio`);
expect(byId(withIcon('{class}_11'), 'repeaters').layout['icon-image']).toBe(`${ICONS}:{class}_11`);
});
test('an image chosen by an expression: what it evaluates to is renamed, not its strings', () => {
@ -223,14 +228,14 @@ describe('icons', () => {
const value = byId(result, 'repeaters').layout['icon-image'];
// The expression is intact inside the wrapping: the label "hospital" still matches the class.
expect(JSON.stringify(value)).toContain(JSON.stringify(icon));
expect(JSON.stringify(value)).toContain(`"${SOURCE}:"`);
expect(JSON.stringify(value)).toContain(`"${ICONS}:"`);
});
describe('an image named by a property function', () => {
// The wrapping every image gets; `expression` is what gives the name.
const wrapped = expression => ['image', ['let', 'wrolpi_image', ['to-string', expression],
['case', ['==', ['var', 'wrolpi_image'], ''], '',
['concat', `${SOURCE}:`, ['var', 'wrolpi_image']]]]];
['concat', `${ICONS}:`, ['var', 'wrolpi_image']]]]];
const iconOf = (fn) => {
const result = withIcon(fn);
// The layer is kept: its text is drawn whatever becomes of its image.
@ -257,13 +262,13 @@ describe('icons', () => {
expect(iconOf({property: 'height', stops: [[0, 'low'], [100, 'tall']]}))
.toEqual(wrapped(['step', ['to-number', ['get', 'height'], 0], 'low', 100, 'tall']));
// A single stop is one name.
expect(iconOf({property: 'height', type: 'interval', stops: [[10, 'only']]})).toBe(`${SOURCE}:only`);
expect(iconOf({stops: [[10, 'only']]})).toBe(`${SOURCE}:only`);
expect(iconOf({property: 'height', type: 'interval', stops: [[10, 'only']]})).toBe(`${ICONS}:only`);
expect(iconOf({stops: [[10, 'only']]})).toBe(`${ICONS}:only`);
});
test('a name for each range of the zoom: each name is renamed, the zoom stays outermost', () => {
expect(iconOf({stops: [[0, 'dot'], [12, 'tower'], [15, '{class}_big']]}))
.toEqual(['step', ['zoom'], `${SOURCE}:dot`, 12, `${SOURCE}:tower`, 15, `${SOURCE}:{class}_big`]);
.toEqual(['step', ['zoom'], `${ICONS}:dot`, 12, `${ICONS}:tower`, 15, `${ICONS}:{class}_big`]);
});
test('a function which cannot be rewritten: the layer is drawn without the image', () => {
@ -286,51 +291,138 @@ describe('icons', () => {
expect(byId(result, 'repeaters').layout['text-field']).toEqual(['get', 'callsign']);
}
});
test('a pattern named by a function', () => {
const style = {
...STYLE,
layers: [{
id: 'parks', type: 'fill', source: 'features', 'source-layer': 'parks',
paint: {'fill-pattern': {type: 'identity', property: 'pattern'}},
}],
};
const result = adapted(style);
expect(result.skipped).toBe(0);
expect(byId(result, 'parks').paint['fill-pattern']).toEqual(wrapped(['coalesce', ['get', 'pattern'], '']));
});
});
test('an image chosen by the zoom in an expression: the zoom stays outermost', () => {
const result = withIcon(['step', ['zoom'], 'dot', 12, ['match', ['get', 'class'], 'tower', 'tower', 'pin']]);
expect(result.skipped).toBe(0);
const value = byId(result, 'repeaters').layout['icon-image'];
expect(value.slice(0, 4)).toEqual(['step', ['zoom'], `${SOURCE}:dot`, 12]);
expect(value.slice(0, 4)).toEqual(['step', ['zoom'], `${ICONS}:dot`, 12]);
expect(JSON.stringify(value[4])).toContain(JSON.stringify(['match', ['get', 'class'], 'tower', 'tower', 'pin']));
});
test('a pattern is an image too', () => {
test("an icon is drawn at its own size, not at a scale of the style's artwork", () => {
const style = {
...STYLE,
layers: [{
id: 'parks', type: 'fill', source: 'features', 'source-layer': 'parks',
paint: {'fill-pattern': 'forest', 'fill-opacity': 0.5},
...STYLE.layers[6],
layout: {'icon-image': 'ham_radio', 'icon-size': 0.59, 'icon-anchor': 'bottom'},
}],
};
expect(byId(adapted(style), 'parks').paint).toEqual({'fill-pattern': `${SOURCE}:forest`, 'fill-opacity': 0.5});
});
test('without a sprite sheet there are no images, and the text is still drawn', () => {
const result = adapted(STYLE, {...FILE, has_sprite: false});
expect(byId(result, 'repeaters').layout).toEqual({
'text-field': ['get', 'callsign'], 'text-font': ['Noto Sans Medium'],
expect(byId(adapted(style), 'repeaters').layout).toEqual({
'icon-image': `${ICONS}:ham_radio`, 'icon-anchor': 'bottom',
});
expect(result.skipped).toBe(0);
});
test("the sprite is asked of this WROLPi, by the file's path", () => {
expect(overlaySpriteUrl({map_path: 'extras/my features.pmtiles'}))
.toBe(`${window.location.origin}/api/map/files/sprite/extras/my%20features.pmtiles`);
test('an icon is dark with a light edge unless its style says otherwise', () => {
expect(byId(adapted(), 'repeaters').paint).toEqual({
'icon-color': '#222222', 'icon-halo-color': '#ffffff', 'icon-halo-width': 1,
});
const style = {
...STYLE,
layers: [{...STYLE.layers[6], paint: {'icon-color': '#c00', 'text-color': '#00c'}}],
};
expect(byId(adapted(style), 'repeaters').paint).toEqual({
'icon-color': '#c00', 'icon-halo-color': '#ffffff', 'icon-halo-width': 1, 'text-color': '#00c',
});
// A layer without an icon is not given an icon's paint.
expect(byId(adapted(), 'roads').paint).toEqual({'line-color': '#c60'});
});
});
describe('patterns', () => {
// A pattern is an image of the style's own sprite, which the map does not use.
const pattern = (paint, type = 'fill') => {
const style = {
...STYLE,
layers: [{id: 'parks', type, source: 'features', 'source-layer': 'parks', paint}],
};
const result = adapted(style);
expect(result.skipped).toBe(0);
return byId(result, 'parks').paint;
};
test('a patterned fill is a translucent color, never the opaque black MapLibre would fill it with', () => {
expect(pattern({'fill-pattern': 'marsh'})).toEqual({'fill-color': '#808080', 'fill-opacity': 0.25});
// By an expression, or a function, too.
expect(pattern({'fill-pattern': ['match', ['get', 'class'], 'wet', 'marsh', 'sand']}))
.toEqual({'fill-color': '#808080', 'fill-opacity': 0.25});
expect(pattern({'fill-pattern': {type: 'identity', property: 'pattern'}}))
.toEqual({'fill-color': '#808080', 'fill-opacity': 0.25});
});
test("the fill keeps the style's own color and opacity", () => {
expect(pattern({'fill-pattern': 'marsh', 'fill-color': '#9cf'}))
.toEqual({'fill-color': '#9cf', 'fill-opacity': 0.25});
expect(pattern({'fill-pattern': 'marsh', 'fill-color': '#9cf', 'fill-opacity': 0.6}))
.toEqual({'fill-color': '#9cf', 'fill-opacity': 0.6});
});
test('a fill without a pattern is as its style has it', () => {
expect(pattern({'fill-color': '#9c9'})).toEqual({'fill-color': '#9c9'});
});
test('a patterned extrusion is a translucent color too, and keeps its shape', () => {
expect(pattern({'fill-extrusion-pattern': 'brick'}, 'fill-extrusion'))
.toEqual({'fill-extrusion-color': '#808080', 'fill-extrusion-opacity': 0.25});
expect(pattern({'fill-extrusion-pattern': 'brick', 'fill-extrusion-height': ['get', 'height']}, 'fill-extrusion'))
.toEqual({
'fill-extrusion-color': '#808080', 'fill-extrusion-opacity': 0.25,
'fill-extrusion-height': ['get', 'height'],
});
// The style's own color and opacity are kept.
expect(pattern({
'fill-extrusion-pattern': 'brick', 'fill-extrusion-color': '#a52', 'fill-extrusion-opacity': 0.8,
}, 'fill-extrusion')).toEqual({'fill-extrusion-color': '#a52', 'fill-extrusion-opacity': 0.8});
// An extrusion without a pattern is as its style has it.
expect(pattern({'fill-extrusion-height': 10}, 'fill-extrusion')).toEqual({'fill-extrusion-height': 10});
});
test('a patterned line is a plain line', () => {
expect(pattern({'line-pattern': 'ruling', 'line-width': 2}, 'line'))
.toEqual({'line-color': '#808080', 'line-width': 2});
expect(pattern({'line-pattern': 'ruling', 'line-color': '#c00'}, 'line')).toEqual({'line-color': '#c00'});
});
});
describe('a name the overlay icons do not have', () => {
class FakeMap {
images = {};
hasImage(id) {
return id in this.images;
}
addImage(id, image, options) {
this.images[id] = {image, options};
}
}
test('is drawn as a dot: a signed distance field, as the icons are', () => {
const {width, height, data} = missingOverlayIcon();
expect(data).toHaveLength(width * height * 4);
const alpha = (x, y) => data[(y * width + x) * 4 + 3];
const middle = Math.floor(width / 2);
// Full in the middle, three quarters at the edge of the dot, less beyond it.
expect(alpha(middle, middle)).toBe(255);
expect(alpha(0, 0)).toBeLessThan(alpha(middle + 6, middle));
expect(alpha(middle + 4, middle)).toBeGreaterThan(191);
expect(alpha(middle + 6, middle)).toBeLessThan(191);
});
test('is supplied when the map asks for it', () => {
const map = new FakeMap();
expect(addMissingOverlayIcon(map, `${ICONS}:wreck`)).toBe(true);
expect(map.images[`${ICONS}:wreck`].options).toEqual({sdf: true});
// Once.
expect(addMissingOverlayIcon(map, `${ICONS}:wreck`)).toBe(false);
});
test("an image of the basemap's is not the overlay icons' to supply", () => {
const map = new FakeMap();
expect(addMissingOverlayIcon(map, 'townspot')).toBe(false);
expect(addMissingOverlayIcon(map, 'default:townspot')).toBe(false);
expect(map.images).toEqual({});
});
});
@ -391,7 +483,7 @@ describe('a styled overlay on the map', () => {
[`${SOURCE}:parks:parks`, 'fill'], [`${SOURCE}:roads:roads`, 'line'],
[`${SOURCE}:repeaters:repeaters`, 'symbol'],
]);
expect(layers[2].layout['icon-image']).toBe(`${SOURCE}:ham_radio`);
expect(layers[2].layout['icon-image']).toBe(`${ICONS}:ham_radio`);
});
test('starts hidden, and its layers are shown and hidden by the layer of the file they draw', () => {

View file

@ -8,7 +8,7 @@
// this file keeps. A viewer which can check a layer before giving it to MapLibre passes
// `validateLayer(layer, sourceId, spriteId)`, which returns the layer's errors.
import {encodePath, overlaySourceId} from "./overlays.js";
import {overlaySourceId} from "./overlays.js";
// The fonts the map has glyphs for (modules/map/static/fonts). The map has one glyph URL, so a
// style's own fonts cannot be loaded; each is replaced by the nearest of these.
@ -16,11 +16,20 @@ const FONT_REGULAR = "Noto Sans Regular";
const FONT_MEDIUM = "Noto Sans Medium";
const FONT_ITALIC = "Noto Sans Italic";
// Properties whose value names an image of the sprite.
const IMAGE_PROPERTIES = {
layout: ["icon-image"],
paint: ["fill-pattern", "line-pattern", "fill-extrusion-pattern"],
};
// The map's own icons for overlays (see wrolpi/scripts/build_map_icons.py): a sprite beside the
// basemap's. MapLibre knows its images as `<sprite id>:<image name>`. Its index lists each icon
// under every name a style may call it, so pointing an image at this sprite is the whole
// translation; the artwork a style was made for is never used.
export const OVERLAY_ICONS_SPRITE_ID = "overlay-icons";
// How an icon is drawn when its style does not say: dark, with a light edge, to be seen on any
// basemap. (The icons are signed distance fields, which take a color and a halo.)
const ICON_PAINT_DEFAULTS = {"icon-color": "#222222", "icon-halo-color": "#ffffff", "icon-halo-width": 1};
// A pattern is an image the map does not have; what it filled is drawn in a translucent color.
const PATTERN_PROPERTIES = ["fill-pattern", "line-pattern", "fill-extrusion-pattern"];
const PATTERN_COLOR = "#808080";
const PATTERN_OPACITY = 0.25;
// Expression operators a `text-font` value can start with; anything else is a plain list of fonts.
const FONT_EXPRESSIONS = new Set(["literal", "match", "case", "step", "coalesce", "let", "var", "get"]);
@ -62,14 +71,26 @@ function adaptTextFieldFonts(value) {
return value;
}
// The id of an overlay's sprite; MapLibre knows its images as `<sprite id>:<image name>`.
export function overlaySpriteId(file) {
return overlaySourceId(file);
// The image MapLibre is given for a name the overlay icons do not have: a plain dot, so that a
// feature is marked on the map whatever its style calls its icon. A signed distance field, as
// the icons are.
export function missingOverlayIcon() {
const size = 25, radius = 5;
const data = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const outside = Math.hypot(x + 0.5 - size / 2, y + 0.5 - size / 2) - radius;
data[(y * size + x) * 4 + 3] = Math.max(0, Math.min(255, Math.round(255 - 255 * (outside / 8 + 0.25))));
}
}
return {width: size, height: size, data};
}
// The sprite sheet of an overlay, as MapLibre asks for it (it appends `@2x` and the extension).
export function overlaySpriteUrl(file) {
return `${window.location.origin}/api/map/files/sprite/${encodePath(file.map_path)}`;
// For a map's `styleimagemissing` event: supply the dot for a name the overlay icons do not have.
export function addMissingOverlayIcon(map, id) {
if (!String(id).startsWith(`${OVERLAY_ICONS_SPRITE_ID}:`) || map.hasImage(id)) return false;
map.addImage(id, missingOverlayIcon(), {sdf: true});
return true;
}
const isZoom = value => Array.isArray(value) && value.length === 1 && value[0] === "zoom";
@ -158,7 +179,7 @@ export function adaptOverlayStyle(style, file, {validateLayer} = {}) {
const fileLayerIds = new Set((file.vector_layers || []).map(l => l.id));
const styleSource = chooseSource(style, fileLayerIds);
const source = overlaySourceId(file);
const spriteId = overlaySpriteId(file);
const spriteId = OVERLAY_ICONS_SPRITE_ID;
// A style drawn for one scale (a printed map, say) is unreadable zoomed out; it can say the zoom
// it is meant to be seen from.
const minZoom = Number(style.metadata?.["wrolpi:minzoom"]);
@ -187,20 +208,36 @@ export function adaptOverlayStyle(style, file, {validateLayer} = {}) {
layer.layout["text-font"] = [FONT_REGULAR];
}
}
for (const [group, properties] of Object.entries(IMAGE_PROPERTIES)) {
for (const property of properties) {
if (layer[group]?.[property] === undefined) continue;
// Without a sprite sheet there are no images to draw. An image this cannot point at
// the overlay's sprite would be looked for in the basemap's; the layer is drawn
// without it (its text still is).
const image = file.has_sprite ? adaptImage(layer[group][property], spriteId) : undefined;
if (image === undefined) {
delete layer[group][property];
} else {
layer[group][property] = image;
}
if (layer.layout?.["icon-image"] !== undefined) {
// An image this cannot point at the overlay icons would be looked for among the
// basemap's; the layer is drawn without it (its text still is).
const image = adaptImage(layer.layout["icon-image"], spriteId);
if (image === undefined) {
delete layer.layout["icon-image"];
} else {
layer.layout["icon-image"] = image;
// A size is a scale of the artwork the style was made for; ours has its own size.
delete layer.layout["icon-size"];
layer.paint = {...ICON_PAINT_DEFAULTS, ...layer.paint};
}
}
const patterns = PATTERN_PROPERTIES.filter(property => layer.paint?.[property] !== undefined);
for (const property of patterns) {
delete layer.paint[property];
}
if (patterns.includes("fill-pattern")) {
// Without its pattern MapLibre would fill the area in opaque black.
layer.paint = {"fill-color": PATTERN_COLOR, "fill-opacity": PATTERN_OPACITY, ...layer.paint};
}
if (patterns.includes("line-pattern")) {
layer.paint = {"line-color": PATTERN_COLOR, ...layer.paint};
}
if (patterns.includes("fill-extrusion-pattern")) {
// As a fill: an extrusion without its pattern would be opaque black too.
layer.paint = {
"fill-extrusion-color": PATTERN_COLOR, "fill-extrusion-opacity": PATTERN_OPACITY, ...layer.paint,
};
}
// One bad layer must not stop the map: MapLibre refuses a whole style over it.
let errors = [];