Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-render shields after fonts load #991

Merged
merged 18 commits into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const buildWith = async (
"src/americana.js",
"src/bare_americana.js",
"src/shieldtest.js",
"src/js/load_fonts.js",
],
format: "esm",
bundle: true,
Expand Down
12 changes: 8 additions & 4 deletions scripts/generate_samples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type * as maplibre from "maplibre-gl";

// Declare a global augmentation for the Window interface
declare global {
interface Window {
interface WindowWithMap extends Window {
map?: maplibre.Map;
}
}
Expand Down Expand Up @@ -43,10 +43,14 @@ const screenshots: SampleSpecification[] =
fs.mkdirSync(sampleFolder, { recursive: true });

const browser = await chromium.launch({
headless: true,
executablePath: process.env.CHROME_BIN,
args: ["--headless=new"],
});
const context = await browser.newContext({
bypassCSP: true,
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36",
});
const context = await browser.newContext();

const page = await context.newPage();

Expand All @@ -64,7 +68,7 @@ async function createImage(screenshot: SampleSpecification) {

// Wait for map to load, then wait two more seconds for images, etc. to load.
try {
await page.waitForFunction(() => window.map?.loaded(), {
await page.waitForFunction(() => (window as WindowWithMap).map?.loaded(), {
timeout: 3000,
});
} catch (e) {
Expand Down
3 changes: 2 additions & 1 deletion shieldlib/src/shield.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export function storeNoShield(
export function missingIconLoader(
renderContext: ShieldRenderingContext,
routeDef: RouteDefinition,
spriteID: string
spriteID: string,
update?: boolean
ZeLonewolf marked this conversation as resolved.
Show resolved Hide resolved
): void;

export function romanizeRef(ref: string): string;
9 changes: 5 additions & 4 deletions shieldlib/src/shield.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,17 +166,17 @@ function drawShieldText(r, ctx, shieldDef, routeDef) {
return ctx;
}

export function missingIconLoader(r, routeDef, spriteID) {
export function missingIconLoader(r, routeDef, spriteID, update) {
let ctx = generateShieldCtx(r, routeDef);
if (ctx == null) {
// Want to return null here, but that gives a corrupted display. See #243
console.warn("Didn't produce a shield for", JSON.stringify(routeDef));
ctx = r.gfxFactory.createGraphics({ width: 1, height: 1 });
}
storeSprite(r, spriteID, ctx);
storeSprite(r, spriteID, ctx, update);
}

function storeSprite(r, id, ctx) {
function storeSprite(r, id, ctx, update) {
const imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
r.spriteRepo.putSprite(
id,
Expand All @@ -185,7 +185,8 @@ function storeSprite(r, id, ctx) {
height: ctx.canvas.height,
data: imgData.data,
},
r.px(1)
r.px(1),
update
);
}

Expand Down
52 changes: 45 additions & 7 deletions shieldlib/src/shield_renderer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Map, MapStyleImageMissingEvent, StyleImage } from "maplibre-gl";
import {
Map as MapLibre,
jleedev marked this conversation as resolved.
Show resolved Hide resolved
MapStyleImageMissingEvent,
StyleImage,
} from "maplibre-gl";
import {
Bounds,
DebugOptions,
Expand Down Expand Up @@ -52,15 +56,26 @@ export type ShapeDrawFunction = (
) => number;

class MaplibreGLSpriteRepository implements SpriteRepository {
map: Map;
constructor(map: Map) {
map: MapLibre;
constructor(map: MapLibre) {
this.map = map;
}
getSprite(spriteID: string): StyleImage {
return this.map.style.getImage(spriteID);
}
putSprite(spriteID: string, image: ImageData, pixelRatio: number): void {
this.map.addImage(spriteID, image, { pixelRatio: pixelRatio });
putSprite(
spriteID: string,
image: ImageData,
pixelRatio: number,
update: boolean
): void {
if (update) {
console.log(`update ${spriteID}`);
1ec5 marked this conversation as resolved.
Show resolved Hide resolved
this.map.updateImage(spriteID, image);
} else {
console.log(`add ${spriteID}`);
this.map.addImage(spriteID, image, { pixelRatio: pixelRatio });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last parameter to addImage() accepts some other options, of which sdf may be the most relevant to a client of this library. Should we plumb through an entire options object?

}
}
}

Expand All @@ -69,6 +84,10 @@ export class AbstractShieldRenderer {
private _shieldPredicate: StringPredicate = () => true;
private _networkPredicate: StringPredicate = () => true;
private _routeParser: RouteParser;
private _fontsLoaded: boolean = false;
/** Cache images that are loaded before fonts so they can be re-rendered later */
private _preFontImageCache: Map<string, RouteDefinition> = new Map();

/** @hidden */
private _renderContext: ShieldRenderingContext;
private _shieldDefCallbacks = [];
Expand Down Expand Up @@ -123,9 +142,25 @@ export class AbstractShieldRenderer {
}

/** Set which MaplibreGL map to handle shields for */
public renderOnMaplibreGL(map: Map): AbstractShieldRenderer {
public renderOnMaplibreGL(map: MapLibre): AbstractShieldRenderer {
this.renderOnRepository(new MaplibreGLSpriteRepository(map));
map.on("styleimagemissing", this.getStyleImageMissingHandler());
document.fonts.ready.then(() => {
this._fontsLoaded = true;
if (this._preFontImageCache.size == 0) {
return;
}
console.log("Re-processing shields with loaded fonts");

// Loop through each previously-loaded shield and re-render it
for (let [id, routeDef] of this._preFontImageCache.entries()) {
missingIconLoader(this._renderContext, routeDef, id, true);
console.log(`Updated ${id} post font-load`); // Example action
}

this._preFontImageCache.clear();
ZeLonewolf marked this conversation as resolved.
Show resolved Hide resolved
map.redraw();
});
return this;
}

Expand Down Expand Up @@ -166,7 +201,10 @@ export class AbstractShieldRenderer {
return;
}
if (routeDef) {
missingIconLoader(this._renderContext, routeDef, e.id);
if (!this._fontsLoaded && routeDef.ref) {
this._preFontImageCache.set(e.id, routeDef);
}
missingIconLoader(this._renderContext, routeDef, e.id, false);
}
} catch (err) {
console.error(`Exception while loading image ‘${e?.id}’:\n`, err);
Expand Down
7 changes: 6 additions & 1 deletion shieldlib/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ export interface SpriteProducer {
getSprite(spriteID: string): StyleImage;
}
export interface SpriteConsumer {
putSprite(spriteID: string, image: ImageData, pixelRatio: number): void;
putSprite(
spriteID: string,
image: ImageData,
pixelRatio: number,
update: boolean
): void;
}
export type SpriteRepository = SpriteProducer & SpriteConsumer;
export interface ShieldDefinitions {
Expand Down
7 changes: 6 additions & 1 deletion shieldlib/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,12 @@ export interface SpriteProducer {

/** Store a sprite graphic based on an ID */
export interface SpriteConsumer {
putSprite(spriteID: string, image: ImageData, pixelRatio: number): void;
putSprite(
spriteID: string,
image: ImageData,
pixelRatio: number,
update: boolean
): void;
}

/** Respository that can store and retrieve sprite graphics */
Expand Down
8 changes: 1 addition & 7 deletions src/bare_map.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<title>OpenStreetMap Americana</title>
<link rel="preconnect" href="https://osm-americana.github.io" />
<link href="fonts.css" rel="stylesheet" />
<script type="module" src="js/load_fonts.js"></script>
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
Expand All @@ -27,13 +28,6 @@
</head>

<body>
<p style="
font-family: 'Noto Sans Condensed';
font-weight: 500;
visibility: hidden;
">
Invisible text so the font will load early
</p>
<div id="map"></div>
</body>
</html>
2 changes: 2 additions & 0 deletions src/fonts.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
format("woff");
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Noto Sans Armenian Condensed";
Expand All @@ -15,4 +16,5 @@
format("woff");
font-weight: 500;
font-style: normal;
font-display: swap;
}
10 changes: 1 addition & 9 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<title>OpenStreetMap Americana</title>
<link rel="preconnect" href="https://osm-americana.github.io" />
<link href="fonts.css" rel="stylesheet" />
<script type="module" src="js/load_fonts.js"></script>
ZeLonewolf marked this conversation as resolved.
Show resolved Hide resolved
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta
name="viewport"
Expand Down Expand Up @@ -98,15 +99,6 @@
</head>

<body>
<p
style="
font-family: 'Noto Sans Condensed';
font-weight: 500;
visibility: hidden;
"
>
Invisible text so the font will load early
</p>
<div id="map"></div>
<div id="attribution-logo"></div>
<a href="https://github.com/ZeLonewolf/openstreetmap-americana/"
Expand Down
26 changes: 26 additions & 0 deletions src/js/load_fonts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
function loadFontByCreatingInvisibleDiv(fontFamily, dummyText) {
// Create a div element
const div = document.createElement("div");

// Set the font-family
div.style.fontFamily = fontFamily;

// Set the dummy text
div.textContent = dummyText;

// Make the div invisible
div.style.position = "absolute";
div.style.opacity = "0";
div.style.pointerEvents = "none";
div.style.zIndex = "-1";
div.style.left = "-1000px";
div.style.top = "-1000px";

// Append the div to the body
document.body.appendChild(div);
ZeLonewolf marked this conversation as resolved.
Show resolved Hide resolved

return div;
}

loadFontByCreatingInvisibleDiv("Noto Sans Condensed", "dummy");
loadFontByCreatingInvisibleDiv("Noto Sans Armenian Condensed", "Քանզի անդամ");
10 changes: 1 addition & 9 deletions src/shieldtest.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<title>Shield Test</title>
<link rel="preconnect" href="https://osm-americana.github.io" />
<link href="fonts.css" rel="stylesheet" />
<script type="module" src="js/load_fonts.js"></script>
<style>
body {
background: #faf6f2;
Expand Down Expand Up @@ -33,15 +34,6 @@
</head>

<body>
<p
style="
font-family: 'Noto Sans Condensed';
font-weight: 500;
visibility: hidden;
"
>
Invisible text so the font will load early
</p>
<table id="shield-table">
<thead>
<tr>
Expand Down