Skip to content

Commit

Permalink
Render new terrain
Browse files Browse the repository at this point in the history
  • Loading branch information
wilsonzlin committed May 3, 2024
1 parent cb26289 commit c00e35f
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 39 deletions.
76 changes: 47 additions & 29 deletions app/util/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import Dict from "@xtjs/lib/Dict";
import UnreachableError from "@xtjs/lib/UnreachableError";
import assertExists from "@xtjs/lib/assertExists";
import assertState from "@xtjs/lib/assertState";
import derivedComparator from "@xtjs/lib/derivedComparator";
import propertyComparator from "@xtjs/lib/propertyComparator";
import reversedComparator from "@xtjs/lib/reversedComparator";
import slices from "@xtjs/lib/slices";
import RBush, { BBox } from "rbush";
import {
MapStateInit,
Expand Down Expand Up @@ -303,26 +305,41 @@ export const createCanvasPointMap = ({
let heatmaps: ImageBitmap[] = [];
let resultPoints: { x: number; y: number }[] = [];

let terrainLand: ImageBitmap | undefined;
let terrainWater: ImageBitmap | undefined;
Promise.all(
["land", "water"].map(async (feature) => {
const res = await fetch(
`https://${edge}.edge-hndr.wilsonl.in/map/${MAP_DATASET}/terrain/${feature}`,
);
if (!res.ok) {
throw new Error(`Failed to fetch terrain with error ${res.status}`);
}
const raw = await res.arrayBuffer();
const img = await createImageBitmap(new Blob([raw]));
if (feature === "land") {
terrainLand = img;
} else {
terrainWater = img;
let terrain = Array<{ level: number; points: { x: number; y: number }[] }>();
(async () => {
const res = await fetch(
`https://${edge}.edge-hndr.wilsonl.in/map/${MAP_DATASET}/terrain`,
);
if (!res.ok) {
throw new Error(`Failed to fetch terrain with error ${res.status}`);
}
const raw = await res.arrayBuffer();
const dv = new DataView(raw);
let i = 0;
const paths = [];
while (i < raw.byteLength) {
const level = dv.getUint32(i, true);
i += 4;
const pathCount = dv.getUint32(i, true);
i += 4;
for (let j = 0; j < pathCount; j++) {
const pathLen = dv.getUint32(i, true);
i += 4;
const pointsRaw = new Float32Array(
raw.slice(i, (i += pathLen * 4 * 2)),
);
paths.push({
level,
points: slices(pointsRaw, 2).map(([x, y]) => ({ x, y })),
});
}
render();
}),
);
}
assertState(i === raw.byteLength);
// Render level 1, then 2 on top, then 3, etc. However, render 0 last, because those are holes.
terrain = paths.sort(derivedComparator((e) => e.level || Infinity));
// @ts-expect-error This is not used before initialization.
render();
})();

// Zoom (integer) level => point IDs.
const labelledPoints = new Dict<number, Set<number>>();
Expand Down Expand Up @@ -389,18 +406,19 @@ export const createCanvasPointMap = ({
const scale = map.viewportScale(vp);
const ctx = assertExists(canvas.getContext("2d"));
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fcfcfc";
ctx.fillStyle = "#6cd2e7";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const image of [terrainWater, terrainLand]) {
if (image) {
renderImage({
canvas,
context: ctx,
image,
map,
viewport: vp,
});
for (const { level, points } of terrain) {
ctx.fillStyle = ["#6cd2e7", "#bbecd8", "#a7e6cc", "#90e0be"][level];
ctx.beginPath();
const toCanvasPos = ({ x, y }: { x: number; y: number }) =>
[scale.ptToPx(x - vp.x0Pt), scale.ptToPx(y - vp.y0Pt)] as const;
ctx.moveTo(...toCanvasPos(points[0]));
for (const p of points.slice(1)) {
ctx.lineTo(...toCanvasPos(p));
}
ctx.closePath();
ctx.fill();
}
for (const heatmap of heatmaps) {
renderImage({
Expand Down
1 change: 0 additions & 1 deletion common/terrain.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from scipy.ndimage import gaussian_filter
from typing import Dict
from typing import List
from typing import Tuple
import cv2
import numpy as np
import numpy.typing as npt
Expand Down
11 changes: 4 additions & 7 deletions edge/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ struct Map {
meta: MapMeta,
// One for each LOD level.
tiles: Vec<AHashMap<String, ByteBuf>>,
terrain: AHashMap<String, ByteBuf>,
terrain: ByteBuf,
}

#[derive(Clone, Deserialize, Serialize)]
Expand Down Expand Up @@ -113,16 +113,13 @@ async fn get_map_tile(

async fn get_map_terrain(
State(ctx): State<Arc<Ctx>>,
Path((variant, typ)): Path<(String, String)>,
Path(variant): Path<String>,
) -> Result<Vec<u8>, axum::http::StatusCode> {
let data = ctx.data.read();
let Some(map) = data.maps.get(&variant) else {
return Err(axum::http::StatusCode::NOT_FOUND);
};
let Some(img) = map.terrain.get(&typ) else {
return Err(axum::http::StatusCode::NOT_FOUND);
};
Ok(img.to_vec())
Ok(map.terrain.to_vec())
}

async fn get_post(
Expand Down Expand Up @@ -243,7 +240,7 @@ async fn main() {
.route("/healthz", get(|| async { "OK" }))
.route("/map/:map/meta", get(get_map_meta))
.route("/map/:map/point/:id", get(get_map_point))
.route("/map/:map/terrain/:typ", get(get_map_terrain))
.route("/map/:map/terrain", get(get_map_terrain))
.route("/map/:map/tile/:lod/:tile_id", get(get_map_tile))
.route("/post-title-lengths", post(get_post_title_lengths))
.route("/post-titles", post(get_post_titles))
Expand Down
12 changes: 12 additions & 0 deletions wrench/edge/logs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env bash

set -Eeuo pipefail

pushd "$(dirname "$0")/../.." >/dev/null

region="$1"

# We assume that the edge server exists as a Docker context named `hndr-edge-$region`.
DOCKER_CONTEXT=hndr-edge-$region \
EDGE_DOMAIN=$region.edge-hndr.wilsonl.in \
docker compose logs -f
5 changes: 3 additions & 2 deletions wrench/edge/up
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pushd "$(dirname "$0")/../.." >/dev/null
region="$1"

# We assume that the edge server exists as a Docker context named `hndr-edge-$region`.
DOCKER_CONTEXT=hndr-edge-$region \
EDGE_DOMAIN=$region.edge-hndr.wilsonl.in \
export DOCKER_CONTEXT=hndr-edge-$region
export EDGE_DOMAIN=$region.edge-hndr.wilsonl.in
docker compose pull edge edge-caddy
docker compose up -d edge edge-caddy

0 comments on commit c00e35f

Please sign in to comment.