Compare commits
4
Commits
604beca236
...
0a1fc266b7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a1fc266b7 | ||
|
|
916b016da1 | ||
|
|
69aa284e36 | ||
|
|
58ca871662 |
No files matched your search
@@ -448,13 +448,14 @@ module Maptool
|
|||||||
end
|
end
|
||||||
|
|
||||||
# A route through the posted points ({"locations": [[lon, lat], ...]})
|
# A route through the posted points ({"locations": [[lon, lat], ...]})
|
||||||
# for the stored vehicle. Open to anyone, like viewing the map; only
|
# for the vehicle profile "vehicle" (an id, default the first). Open to anyone, like viewing the map; only
|
||||||
# saving it to the library needs a login.
|
# saving it to the library needs a login.
|
||||||
post "/api/route" do
|
post "/api/route" do
|
||||||
locations = JSON.parse(request.body.read)["locations"]
|
body = JSON.parse(request.body.read)
|
||||||
|
locations = body["locations"]
|
||||||
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
|
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
|
||||||
|
|
||||||
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR))
|
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
|
||||||
rescue JSON::ParserError
|
rescue JSON::ParserError
|
||||||
halt 400, json(error: "invalid JSON")
|
halt 400, json(error: "invalid JSON")
|
||||||
rescue Routing::RouteError => e
|
rescue Routing::RouteError => e
|
||||||
@@ -463,11 +464,11 @@ module Maptool
|
|||||||
halt 503, json(error: e.message)
|
halt 503, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Where the stored vehicle gets in each of `minutes` from `center`
|
# Where the vehicle profile gets in each of `minutes` from `center`
|
||||||
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
|
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
|
||||||
post "/api/isochrone" do
|
post "/api/isochrone" do
|
||||||
body = JSON.parse(request.body.read)
|
body = JSON.parse(request.body.read)
|
||||||
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR))
|
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
|
||||||
rescue JSON::ParserError
|
rescue JSON::ParserError
|
||||||
halt 400, json(error: "invalid JSON")
|
halt 400, json(error: "invalid JSON")
|
||||||
rescue Routing::RouteError => e
|
rescue Routing::RouteError => e
|
||||||
@@ -476,14 +477,16 @@ module Maptool
|
|||||||
halt 503, json(error: e.message)
|
halt 503, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/api/vehicle" do
|
get "/api/vehicles" do
|
||||||
json Routing.vehicle(DATA_DIR)
|
json Routing.vehicles(DATA_DIR)
|
||||||
end
|
end
|
||||||
|
|
||||||
put "/api/vehicle" do
|
put "/api/vehicles" do
|
||||||
require_login!
|
require_login!
|
||||||
json Routing.save_vehicle(DATA_DIR, params)
|
json Routing.save_vehicles(DATA_DIR, JSON.parse(request.body.read))
|
||||||
rescue ArgumentError, KeyError => e
|
rescue JSON::ParserError
|
||||||
|
halt 400, json(error: "invalid JSON")
|
||||||
|
rescue ArgumentError => e
|
||||||
halt 400, json(error: e.message)
|
halt 400, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
|||||||
* "Offline routing" row in the Offline data panel, next to the offline
|
* "Offline routing" row in the Offline data panel, next to the offline
|
||||||
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
||||||
three. A routing request made while the offline map is still
|
three. A routing request made while the offline map is still
|
||||||
downloading extracts waits for it (`Routing.offline_build_finished`).
|
downloading extracts waits for the downloads only, then runs alongside Planetiler (`Routing.extracts_ready`).
|
||||||
The row says whether the service answers.
|
The row says whether the service answers.
|
||||||
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
||||||
Valhalla `/route` and returns the route as a GeoJSON line with
|
Valhalla `/route` and returns the route as a GeoJSON line with
|
||||||
@@ -139,9 +139,21 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
|||||||
up to 3.5 t it's `auto` with the vehicle's height and width, because a
|
up to 3.5 t it's `auto` with the vehicle's height and width, because a
|
||||||
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
|
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
|
||||||
3.5 t it's `truck` with every dimension.
|
3.5 t it's `truck` with every dimension.
|
||||||
* Vehicle profile: height, width, length, weight in `data/vehicle.json`
|
* Vehicle profiles in `data/vehicles.json` (`GET`/`PUT /api/vehicles`,
|
||||||
(`GET`/`PUT /api/vehicle`), one for now, edited in the route panel.
|
saving needs a login): a name plus optional height, width, length,
|
||||||
The default is a camper: 3.0 m, 2.3 m, 7 m, 3.5 t.
|
weight (missing: no limit). Defaults: Car (no limits) and Camper
|
||||||
|
(3.0 m, 2.3 m, 7 m, 3.5 t; an older single `vehicle.json` becomes the
|
||||||
|
camper). The route panel picks one per browser (localStorage) and sends
|
||||||
|
its id with `/api/route` and `/api/isochrone`; Edit shows the fields.
|
||||||
|
* Avoid tolls / motorways (`"avoid": {"tolls": true, "highways": true}`)
|
||||||
|
sets Valhalla's `use_tolls` / `use_highways` to 0 for the whole route.
|
||||||
|
Per country isn't possible in one Valhalla request.
|
||||||
|
* Vignettes and tolls: `/api/route` adds `countries`, the km, motorway km
|
||||||
|
and toll km per country, from `/trace_attributes` (edge_walk on each
|
||||||
|
leg's shape). The panel lists vignette countries (fixed list in
|
||||||
|
route.js) with motorway km, other countries with toll km. In vignette
|
||||||
|
countries every motorway km counts, since OSM doesn't tag those as toll
|
||||||
|
reliably.
|
||||||
* Route panel (`public/js/route.js`): while it's open, a map click adds a
|
* Route panel (`public/js/route.js`): while it's open, a map click adds a
|
||||||
point; markers drag; Reverse, Clear. The route is drawn with distance,
|
point; markers drag; Reverse, Clear. The route is drawn with distance,
|
||||||
time and directions. "Save to library" stores it as a `route` item in
|
time and directions. "Save to library" stores it as a `route` item in
|
||||||
|
|||||||
@@ -164,6 +164,7 @@ module Maptool
|
|||||||
# for those.
|
# for those.
|
||||||
def self.reset!
|
def self.reset!
|
||||||
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
|
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
|
||||||
|
@fetching_extracts = false
|
||||||
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
|
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -241,14 +242,29 @@ module Maptool
|
|||||||
raise BuildError, "select at least one region first" if codes.empty?
|
raise BuildError, "select at least one region first" if codes.empty?
|
||||||
|
|
||||||
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
|
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
|
||||||
|
@fetching_extracts = true
|
||||||
Thread.new do
|
Thread.new do
|
||||||
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
||||||
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
||||||
end
|
end
|
||||||
|
extracts_ready(data_dir) # no-op unless the build failed before its extracts were in
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# True while an offline build may still be replacing the extracts that
|
||||||
|
# a routing build reads; Planetiler afterwards doesn't touch them.
|
||||||
|
def self.fetching_extracts?
|
||||||
|
@fetching_extracts
|
||||||
|
end
|
||||||
|
|
||||||
# A routing build requested meanwhile waited for these extracts.
|
# A routing build requested meanwhile waited for these extracts.
|
||||||
Routing.offline_build_finished(data_dir) if defined?(Routing)
|
def self.extracts_ready(data_dir)
|
||||||
end
|
return unless @fetching_extracts
|
||||||
|
|
||||||
|
@fetching_extracts = false
|
||||||
|
Routing.extracts_ready(data_dir) if defined?(Routing)
|
||||||
end
|
end
|
||||||
|
private_class_method :extracts_ready
|
||||||
|
|
||||||
# fetch_manifest: same injectable-seam reasoning as download_extract
|
# fetch_manifest: same injectable-seam reasoning as download_extract
|
||||||
# above, for the one Mapterhorn manifest lookup this needs.
|
# above, for the one Mapterhorn manifest lookup this needs.
|
||||||
@@ -334,6 +350,7 @@ module Maptool
|
|||||||
report_step.call(progress_step("fetching #{code}", codes, i))
|
report_step.call(progress_step("fetching #{code}", codes, i))
|
||||||
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
|
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
|
||||||
end
|
end
|
||||||
|
extracts_ready(data_dir)
|
||||||
|
|
||||||
osm_path =
|
osm_path =
|
||||||
if sources.size == 1
|
if sources.size == 1
|
||||||
|
|||||||
+89
-23
@@ -33,13 +33,13 @@ module Maptool
|
|||||||
|
|
||||||
# Routing covers the offline map's selected countries. While an offline
|
# Routing covers the offline map's selected countries. While an offline
|
||||||
# build is running (it may be downloading those very extracts), the
|
# build is running (it may be downloading those very extracts), the
|
||||||
# request waits for it — PmtilesBuilder calls offline_build_finished.
|
# request waits for its downloads — PmtilesBuilder calls extracts_ready.
|
||||||
def self.request_build(data_dir)
|
def self.request_build(data_dir)
|
||||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||||
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
||||||
|
|
||||||
MUTEX.synchronize do
|
MUTEX.synchronize do
|
||||||
if PmtilesBuilder.offline_status[:state] == "running"
|
if PmtilesBuilder.fetching_extracts?
|
||||||
@pending = true
|
@pending = true
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
@@ -67,17 +67,18 @@ module Maptool
|
|||||||
# one merged file. Its image has no osmium; this container does.
|
# one merged file. Its image has no osmium; this container does.
|
||||||
def self.merge_and_request(data_dir, codes)
|
def self.merge_and_request(data_dir, codes)
|
||||||
merged = File.join(dir(data_dir), "merged.osm.pbf")
|
merged = File.join(dir(data_dir), "merged.osm.pbf")
|
||||||
|
part = File.join(dir(data_dir), "merged.part.osm.pbf") # osmium picks the format by extension
|
||||||
inputs = codes.map { |code| extract_path(data_dir, code) }
|
inputs = codes.map { |code| extract_path(data_dir, code) }
|
||||||
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", "#{merged}.part")
|
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", part)
|
||||||
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
|
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
|
||||||
|
|
||||||
File.rename("#{merged}.part", merged)
|
File.rename(part, merged)
|
||||||
MUTEX.synchronize do
|
MUTEX.synchronize do
|
||||||
write_request(data_dir, codes, "routing/merged.osm.pbf")
|
write_request(data_dir, codes, "routing/merged.osm.pbf")
|
||||||
@merging = nil
|
@merging = nil
|
||||||
end
|
end
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
FileUtils.rm_f("#{merged}.part")
|
FileUtils.rm_f(part)
|
||||||
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
|
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
|
||||||
end
|
end
|
||||||
private_class_method :merge_and_request
|
private_class_method :merge_and_request
|
||||||
@@ -88,7 +89,7 @@ module Maptool
|
|||||||
end
|
end
|
||||||
private_class_method :write_request
|
private_class_method :write_request
|
||||||
|
|
||||||
def self.offline_build_finished(data_dir)
|
def self.extracts_ready(data_dir)
|
||||||
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
||||||
request_build(data_dir) if pending
|
request_build(data_dir) if pending
|
||||||
rescue PmtilesBuilder::BuildError
|
rescue PmtilesBuilder::BuildError
|
||||||
@@ -99,7 +100,7 @@ module Maptool
|
|||||||
# started_at, message.
|
# started_at, message.
|
||||||
def self.build_status(data_dir)
|
def self.build_status(data_dir)
|
||||||
pending, merging = MUTEX.synchronize { [@pending, @merging] }
|
pending, merging = MUTEX.synchronize { [@pending, @merging] }
|
||||||
return { state: "running", step: "waiting for the offline map build" } if pending
|
return { state: "running", step: "waiting for the offline map downloads" } if pending
|
||||||
return merging if merging
|
return merging if merging
|
||||||
status = read_json(File.join(dir(data_dir), "status.json"))
|
status = read_json(File.join(dir(data_dir), "status.json"))
|
||||||
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
|
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
|
||||||
@@ -162,33 +163,68 @@ module Maptool
|
|||||||
class Unavailable < StandardError; end
|
class Unavailable < StandardError; end
|
||||||
|
|
||||||
# A camper by default; one profile for now (docs/routing-design.adoc).
|
# A camper by default; one profile for now (docs/routing-design.adoc).
|
||||||
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
|
# Vehicle profiles: a name plus optional limits (nil: no limit, a plain
|
||||||
|
# car). Stored for everyone, picked per browser (route.js).
|
||||||
|
DEFAULT_VEHICLES = [
|
||||||
|
{ id: "car", name: "Car" },
|
||||||
|
{ id: "camper", name: "Camper", height: 3.0, width: 2.3, length: 7.0, weight: 3.5 },
|
||||||
|
].freeze
|
||||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
|
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
|
||||||
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
||||||
# better than "truck": a camper isn't kept off roads closed to lorries.
|
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||||
CAR_MAX_WEIGHT = 3.5
|
CAR_MAX_WEIGHT = 3.5
|
||||||
|
|
||||||
def self.vehicle(data_dir)
|
def self.vehicles(data_dir)
|
||||||
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
|
read_json(File.join(data_dir, "vehicles.json")) || begin
|
||||||
|
# The single vehicle stored before profiles became the camper.
|
||||||
|
old = read_json(File.join(data_dir, "vehicle.json"))
|
||||||
|
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(*VEHICLE_LIMITS.keys))] : DEFAULT_VEHICLES
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.save_vehicle(data_dir, values)
|
# The profile with this id, or the first one.
|
||||||
vehicle = VEHICLE_LIMITS.to_h do |key, range|
|
def self.vehicle(data_dir, id = nil)
|
||||||
value = Float(values.fetch(key.to_s), exception: false)
|
list = vehicles(data_dir)
|
||||||
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
|
list.find { |v| v[:id] == id } || list.first
|
||||||
|
end
|
||||||
|
|
||||||
|
# Replaces the whole list: [{ "id", "name", "height", ... }, ...].
|
||||||
|
def self.save_vehicles(data_dir, list)
|
||||||
|
raise ArgumentError, "at least one vehicle is needed" unless list.is_a?(Array) && list.any? && list.size <= 20
|
||||||
|
|
||||||
|
vehicles = list.map do |values|
|
||||||
|
raise ArgumentError, "invalid vehicle" unless values.is_a?(Hash)
|
||||||
|
|
||||||
|
name = values["name"].to_s.strip
|
||||||
|
id = values["id"].to_s
|
||||||
|
raise ArgumentError, "every vehicle needs a name" if name.empty? || name.size > 40
|
||||||
|
raise ArgumentError, "invalid vehicle id" unless id.match?(/\A[\w-]{1,40}\z/)
|
||||||
|
|
||||||
|
limits = VEHICLE_LIMITS.to_h do |key, range|
|
||||||
|
raw = values[key.to_s]
|
||||||
|
next [key, nil] if raw.nil? || raw.to_s.strip.empty?
|
||||||
|
|
||||||
|
value = Float(raw, exception: false)
|
||||||
|
raise ArgumentError, "#{name}: #{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
|
||||||
|
|
||||||
[key, value]
|
[key, value]
|
||||||
end
|
end
|
||||||
write_json(File.join(data_dir, "vehicle.json"), vehicle)
|
{ id: id, name: name, **limits.compact }
|
||||||
vehicle
|
end
|
||||||
|
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
|
||||||
|
|
||||||
|
write_json(File.join(data_dir, "vehicles.json"), vehicles)
|
||||||
|
vehicles
|
||||||
end
|
end
|
||||||
|
|
||||||
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
||||||
# (km), time (s) and the turn-by-turn instructions.
|
# (km), time (s), the turn-by-turn instructions and, per country, the
|
||||||
def self.route(valhalla_url, locations, vehicle)
|
# km on motorways and toll roads (for vignettes and tolls).
|
||||||
|
# avoid: {"tolls" => true, "highways" => true}, for the whole route.
|
||||||
|
def self.route(valhalla_url, locations, vehicle, avoid = {})
|
||||||
raise RouteError, "at least two points are needed" if locations.size < 2
|
raise RouteError, "at least two points are needed" if locations.size < 2
|
||||||
|
|
||||||
costing, options = costing(vehicle)
|
costing, options = costing(vehicle, avoid)
|
||||||
data = valhalla(valhalla_url, "/route",
|
data = valhalla(valhalla_url, "/route",
|
||||||
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
||||||
costing: costing, costing_options: { costing => options }, units: "kilometers")
|
costing: costing, costing_options: { costing => options }, units: "kilometers")
|
||||||
@@ -197,21 +233,46 @@ module Maptool
|
|||||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||||
time_s: data["trip"]["summary"]["time"],
|
time_s: data["trip"]["summary"]["time"],
|
||||||
|
countries: countries(valhalla_url, legs, costing, options),
|
||||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
||||||
rescue ArgumentError, TypeError
|
rescue ArgumentError, TypeError
|
||||||
raise RouteError, "invalid coordinates"
|
raise RouteError, "invalid coordinates"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
|
||||||
|
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
|
||||||
|
def self.countries(valhalla_url, legs, costing, options)
|
||||||
|
totals = {}
|
||||||
|
legs.each do |leg|
|
||||||
|
data = valhalla(valhalla_url, "/trace_attributes",
|
||||||
|
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
|
||||||
|
costing_options: { costing => options },
|
||||||
|
filters: { attributes: %w[edge.length edge.road_class edge.toll node.admin_index admin.country_code], action: "include" })
|
||||||
|
codes = data["admins"].map { |admin| admin["country_code"] }
|
||||||
|
data["edges"].each do |edge|
|
||||||
|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
|
||||||
|
row = totals[code] ||= { code: code, km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
|
||||||
|
row[:km] += edge["length"]
|
||||||
|
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
|
||||||
|
row[:toll_km] += edge["length"] if edge["toll"]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }
|
||||||
|
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
private_class_method :countries
|
||||||
|
|
||||||
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
||||||
|
|
||||||
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
||||||
# GeoJSON FeatureCollection of polygons, largest first.
|
# GeoJSON FeatureCollection of polygons, largest first.
|
||||||
def self.isochrone(valhalla_url, center, minutes, vehicle)
|
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
|
||||||
lon, lat = center
|
lon, lat = center
|
||||||
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
|
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
|
||||||
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
|
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
|
||||||
|
|
||||||
costing, options = costing(vehicle)
|
costing, options = costing(vehicle, avoid)
|
||||||
valhalla(valhalla_url, "/isochrone",
|
valhalla(valhalla_url, "/isochrone",
|
||||||
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
|
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
|
||||||
contours: minutes.map { |m| { time: m } }, polygons: true)
|
contours: minutes.map { |m| { time: m } }, polygons: true)
|
||||||
@@ -220,8 +281,13 @@ module Maptool
|
|||||||
end
|
end
|
||||||
|
|
||||||
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
||||||
def self.costing(vehicle)
|
def self.costing(vehicle, avoid = {})
|
||||||
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
|
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
|
||||||
|
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
|
||||||
|
avoid = {} unless avoid.is_a?(Hash)
|
||||||
|
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
|
||||||
|
options = options.merge(use_highways: 0.0) if avoid["highways"]
|
||||||
|
[costing, options]
|
||||||
end
|
end
|
||||||
private_class_method :costing
|
private_class_method :costing
|
||||||
|
|
||||||
|
|||||||
Generated
+4
-4
@@ -9,7 +9,7 @@
|
|||||||
"flag-icons": "7.6.0",
|
"flag-icons": "7.6.0",
|
||||||
"maplibre-contour": "0.1.1",
|
"maplibre-contour": "0.1.1",
|
||||||
"maplibre-gl": "6.18.0",
|
"maplibre-gl": "6.18.0",
|
||||||
"maplibre-gl-lanes": "1.4.1",
|
"maplibre-gl-lanes": "1.6.0",
|
||||||
"pmtiles": "4.5.0",
|
"pmtiles": "4.5.0",
|
||||||
"suncalc": "2.1.4"
|
"suncalc": "2.1.4"
|
||||||
}
|
}
|
||||||
@@ -210,9 +210,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/maplibre-gl-lanes": {
|
"node_modules/maplibre-gl-lanes": {
|
||||||
"version": "1.4.1",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.6.0.tgz",
|
||||||
"integrity": "sha512-xlq/bUfbRG/7dXd+P5jZkXOW0FA2RwadNNv8KR8LLzNuiZUWuqQxXmPlk3PXNoCWNMFQ3aaro6BSgFQpNomlhg==",
|
"integrity": "sha512-cnHkrQW9LYD9j0HtVoptOMq2LG/HjEC3pWqLpwhElIzViF3ho+BP8E+YH3wS0Af/J34Wum2mlrRFFWAvw88H1g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
"flag-icons": "7.6.0",
|
"flag-icons": "7.6.0",
|
||||||
"maplibre-contour": "0.1.1",
|
"maplibre-contour": "0.1.1",
|
||||||
"maplibre-gl": "6.18.0",
|
"maplibre-gl": "6.18.0",
|
||||||
"maplibre-gl-lanes": "1.4.1",
|
"maplibre-gl-lanes": "1.6.0",
|
||||||
"pmtiles": "4.5.0",
|
"pmtiles": "4.5.0",
|
||||||
"suncalc": "2.1.4"
|
"suncalc": "2.1.4"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2336,10 +2336,47 @@ html, body {
|
|||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.route-panel__vehicle[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.route-panel__vehicle input {
|
.route-panel__vehicle input {
|
||||||
width: 4.5em;
|
width: 4.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.route-panel__avoid {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.route-panel__countries {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 1.2em;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.route-panel__vehicle-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.route-panel__vehicle-name,
|
||||||
|
.route-panel__vehicle-hint {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.route-panel__vehicle-name input {
|
||||||
|
width: 12em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.route-panel__vehicle-hint {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.85em;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
.route-marker {
|
.route-marker {
|
||||||
width: 22px;
|
width: 22px;
|
||||||
height: 22px;
|
height: 22px;
|
||||||
|
|||||||
+105
-17
@@ -10,7 +10,12 @@ const ISOCHRONE_URL = "/api/isochrone";
|
|||||||
const REACH_SOURCE = "route-reach";
|
const REACH_SOURCE = "route-reach";
|
||||||
const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
|
const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
|
||||||
const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
|
const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
|
||||||
const VEHICLE_URL = "/api/vehicle";
|
const VEHICLES_URL = "/api/vehicles";
|
||||||
|
const VEHICLE_KEY = "maptool.routeVehicle";
|
||||||
|
const AVOID_KEY = "maptool.routeAvoid";
|
||||||
|
// Motorways paid by a time-based vignette rather than per section. Not
|
||||||
|
// reliably tagged as toll in OSM, so every motorway km there counts.
|
||||||
|
const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
|
||||||
const NOTES_URL = "/api/library/notes";
|
const NOTES_URL = "/api/library/notes";
|
||||||
const SOURCE = "route";
|
const SOURCE = "route";
|
||||||
const COLOR = "#1d6fdc";
|
const COLOR = "#1d6fdc";
|
||||||
@@ -62,6 +67,8 @@ export class RoutePanelControl {
|
|||||||
this._list = this._panel.querySelector(".route-panel__points");
|
this._list = this._panel.querySelector(".route-panel__points");
|
||||||
this._summary = this._panel.querySelector(".route-panel__summary");
|
this._summary = this._panel.querySelector(".route-panel__summary");
|
||||||
this._directions = this._panel.querySelector(".route-panel__directions");
|
this._directions = this._panel.querySelector(".route-panel__directions");
|
||||||
|
this._countries = this._panel.querySelector(".route-panel__countries");
|
||||||
|
this._setupAvoid();
|
||||||
this._saveButton = this._panel.querySelector('[data-action="save"]');
|
this._saveButton = this._panel.querySelector('[data-action="save"]');
|
||||||
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
|
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
|
||||||
this._points.reverse();
|
this._points.reverse();
|
||||||
@@ -141,6 +148,8 @@ export class RoutePanelControl {
|
|||||||
// A saved route's points back in the panel; Save then updates that item.
|
// A saved route's points back in the panel; Save then updates that item.
|
||||||
_edit(key, feature) {
|
_edit(key, feature) {
|
||||||
this._clear();
|
this._clear();
|
||||||
|
// Back to the vehicle it was planned for, if that profile still exists.
|
||||||
|
if (this._vehicles?.some((v) => v.id === feature.properties.vehicle?.id)) this._selectVehicle(feature.properties.vehicle.id);
|
||||||
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
|
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
|
||||||
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
||||||
this._setOpen(true);
|
this._setOpen(true);
|
||||||
@@ -219,7 +228,7 @@ export class RoutePanelControl {
|
|||||||
const response = await fetch(ROUTE_URL, {
|
const response = await fetch(ROUTE_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }),
|
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
|
||||||
});
|
});
|
||||||
data = await response.json().catch(() => ({}));
|
data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) error = data.error || `routing failed (${response.status})`;
|
if (!response.ok) error = data.error || `routing failed (${response.status})`;
|
||||||
@@ -237,6 +246,7 @@ export class RoutePanelControl {
|
|||||||
this._saveButton.hidden = !route || !isLoggedIn();
|
this._saveButton.hidden = !route || !isLoggedIn();
|
||||||
this._directions.hidden = !route;
|
this._directions.hidden = !route;
|
||||||
this._profileButton.hidden = true;
|
this._profileButton.hidden = true;
|
||||||
|
this._showCountries(route?.properties.countries);
|
||||||
if (!route) {
|
if (!route) {
|
||||||
this._summary.textContent = message;
|
this._summary.textContent = message;
|
||||||
return;
|
return;
|
||||||
@@ -287,7 +297,7 @@ export class RoutePanelControl {
|
|||||||
const response = await fetch(ISOCHRONE_URL, {
|
const response = await fetch(ISOCHRONE_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ center, minutes }),
|
body: JSON.stringify({ center, minutes, vehicle: this._vehicleId, avoid: this._avoid }),
|
||||||
});
|
});
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
|
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
|
||||||
@@ -392,31 +402,109 @@ export class RoutePanelControl {
|
|||||||
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
|
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Where the route needs a vignette or pays tolls, country by country.
|
||||||
|
_showCountries(countries) {
|
||||||
|
const rows = (countries || []).flatMap(({ code, motorway_km: motorway, toll_km: toll }) => {
|
||||||
|
if (VIGNETTE_COUNTRIES.has(code) && motorway > 0) {
|
||||||
|
return [`${code}: vignette, ${motorway.toFixed(0)} km motorway${toll > 0 ? ` (${toll.toFixed(0)} km tolled)` : ""}`];
|
||||||
|
}
|
||||||
|
return toll > 0 ? [`${code}: toll, ${toll.toFixed(0)} km`] : [];
|
||||||
|
});
|
||||||
|
this._countries.replaceChildren(...rows.map((text) => Object.assign(document.createElement("li"), { textContent: text })));
|
||||||
|
this._countries.hidden = rows.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avoid tolls / motorways for the whole route; this browser's choice.
|
||||||
|
_setupAvoid() {
|
||||||
|
try {
|
||||||
|
this._avoid = JSON.parse(localStorage.getItem(AVOID_KEY)) || {};
|
||||||
|
} catch {
|
||||||
|
this._avoid = {};
|
||||||
|
}
|
||||||
|
this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => {
|
||||||
|
input.checked = Boolean(this._avoid[input.name]);
|
||||||
|
input.addEventListener("change", () => {
|
||||||
|
this._avoid[input.name] = input.checked;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(AVOID_KEY, JSON.stringify(this._avoid));
|
||||||
|
} catch {}
|
||||||
|
this._fetchRoute();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// --- vehicle --------------------------------------------------------------
|
// --- vehicle --------------------------------------------------------------
|
||||||
|
|
||||||
// Readable by anyone, saved only when logged in; a change re-routes.
|
// Profiles (Car, Camper, ...) are shared and edited only when logged in;
|
||||||
|
// which one is in use is this browser's own choice. A change re-routes.
|
||||||
async _setupVehicle() {
|
async _setupVehicle() {
|
||||||
const inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")];
|
const select = this._panel.querySelector(".route-panel__vehicle-select");
|
||||||
|
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
|
||||||
|
const fieldset = this._panel.querySelector(".route-panel__vehicle");
|
||||||
|
const inputs = [...fieldset.querySelectorAll("input")];
|
||||||
try {
|
try {
|
||||||
this._vehicle = await (await fetch(VEHICLE_URL)).json();
|
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||||
} catch {
|
} catch {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
inputs.forEach((input) => {
|
const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0];
|
||||||
input.value = this._vehicle[input.name];
|
const fill = () => {
|
||||||
input.disabled = !isLoggedIn();
|
select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id)));
|
||||||
input.addEventListener("change", async () => {
|
this._vehicle = current();
|
||||||
const body = new URLSearchParams(inputs.map((i) => [i.name, i.value]));
|
this._vehicleId = select.value = this._vehicle.id;
|
||||||
const response = await fetch(VEHICLE_URL, { method: "PUT", body });
|
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
|
||||||
|
};
|
||||||
|
this._selectVehicle = (id) => {
|
||||||
|
this._vehicleId = id;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(VEHICLE_KEY, id);
|
||||||
|
} catch {}
|
||||||
|
fill();
|
||||||
|
};
|
||||||
|
const save = async () => {
|
||||||
|
const response = await fetch(VEHICLES_URL, { method: "PUT", body: JSON.stringify(this._vehicles) });
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (response.ok) {
|
||||||
window.alert(data.error || "Could not save the vehicle.");
|
this._vehicles = data;
|
||||||
input.value = this._vehicle[input.name];
|
} else {
|
||||||
return;
|
window.alert(data.error || "Could not save the vehicles.");
|
||||||
|
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||||
}
|
}
|
||||||
this._vehicle = data;
|
fill();
|
||||||
|
this._fetchRoute();
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
this._vehicleId = localStorage.getItem(VEHICLE_KEY);
|
||||||
|
} catch {}
|
||||||
|
fill();
|
||||||
|
select.addEventListener("change", () => {
|
||||||
|
this._selectVehicle(select.value);
|
||||||
this._fetchRoute();
|
this._fetchRoute();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
editButton.hidden = !isLoggedIn();
|
||||||
|
editButton.addEventListener("click", () => (fieldset.hidden = !fieldset.hidden));
|
||||||
|
inputs.forEach((input) =>
|
||||||
|
input.addEventListener("change", () => {
|
||||||
|
const value = input.value.trim();
|
||||||
|
if (input.name === "name") current().name = value;
|
||||||
|
else if (value === "") delete current()[input.name];
|
||||||
|
else current()[input.name] = value;
|
||||||
|
save();
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
fieldset.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => {
|
||||||
|
const id = `v${Date.now().toString(36)}`;
|
||||||
|
this._vehicles.push({ ...current(), id, name: "New vehicle" });
|
||||||
|
this._selectVehicle(id);
|
||||||
|
save();
|
||||||
|
});
|
||||||
|
fieldset.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => {
|
||||||
|
if (this._vehicles.length < 2 || !window.confirm(`Delete the vehicle "${current().name}"?`)) return;
|
||||||
|
this._vehicles = this._vehicles.filter((v) => v !== current());
|
||||||
|
this._selectVehicle(this._vehicles[0].id);
|
||||||
|
save();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+188
-92
@@ -3,6 +3,7 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
|
|||||||
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
||||||
|
|
||||||
// src/core/graph.ts
|
// src/core/graph.ts
|
||||||
|
var ONEWAY_VALUES = /* @__PURE__ */ new Set(["yes", "true", "1", "-1", !0, 1, -1]);
|
||||||
function lngLatToMercator(lng, lat) {
|
function lngLatToMercator(lng, lat) {
|
||||||
let x = (lng + 180) / 360, s = Math.sin(lat * Math.PI / 180), y = 0.5 - 0.25 * Math.log((1 + s) / (1 - s)) / Math.PI;
|
let x = (lng + 180) / 360, s = Math.sin(lat * Math.PI / 180), y = 0.5 - 0.25 * Math.log((1 + s) / (1 - s)) / Math.PI;
|
||||||
return [x, y];
|
return [x, y];
|
||||||
@@ -12,7 +13,7 @@ function mercatorToLngLat(x, y) {
|
|||||||
return [lng, lat];
|
return [lng, lat];
|
||||||
}
|
}
|
||||||
function buildLineGraph(features, opts = {}) {
|
function buildLineGraph(features, opts = {}) {
|
||||||
let routeProp = opts.routeProperty ?? "route", colorProp = opts.colorProperty ?? "color", nameProp = opts.nameProperty ?? "name", snap = opts.snapDegrees ?? 1e-7, uniform = opts.uniformProperties ?? [], routes = /* @__PURE__ */ new Map(), vertexPos = /* @__PURE__ */ new Map(), elem = /* @__PURE__ */ new Map(), adjacency = /* @__PURE__ */ new Map(), keyOf = (lng, lat) => {
|
let routeProp = opts.routeProperty ?? "route", colorProp = opts.colorProperty ?? "color", nameProp = opts.nameProperty ?? "name", snap = opts.snapDegrees ?? 1e-7, onewayProp = opts.onewayProperty, uniform = onewayProp && !(opts.uniformProperties ?? []).includes(onewayProp) ? [...opts.uniformProperties ?? [], onewayProp] : opts.uniformProperties ?? [], routes = /* @__PURE__ */ new Map(), vertexPos = /* @__PURE__ */ new Map(), elem = /* @__PURE__ */ new Map(), adjacency = /* @__PURE__ */ new Map(), keyOf = (lng, lat) => {
|
||||||
let kx = Math.round(lng / snap), ky = Math.round(lat / snap);
|
let kx = Math.round(lng / snap), ky = Math.round(lat / snap);
|
||||||
return `${kx},${ky}`;
|
return `${kx},${ky}`;
|
||||||
};
|
};
|
||||||
@@ -101,7 +102,13 @@ function buildLineGraph(features, opts = {}) {
|
|||||||
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
|
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
|
||||||
}
|
}
|
||||||
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
|
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
|
||||||
first.props && (edge.properties = first.props), edges.push(edge), nodes[a].ports.push({ edge: id, end: "a" }), nodes[b].ports.push({ edge: id, end: "b" });
|
if (first.props)
|
||||||
|
if (onewayProp && ONEWAY_VALUES.has(first.props[onewayProp]) && (edge.oneway = !0), onewayProp && !opts.uniformProperties?.includes(onewayProp)) {
|
||||||
|
let { [onewayProp]: _, ...rest } = first.props;
|
||||||
|
Object.keys(rest).length && (edge.properties = rest);
|
||||||
|
} else
|
||||||
|
edge.properties = first.props;
|
||||||
|
edges.push(edge), nodes[a].ports.push({ edge: id, end: "a" }), nodes[b].ports.push({ edge: id, end: "b" });
|
||||||
};
|
};
|
||||||
for (let vk of adjacency.keys())
|
for (let vk of adjacency.keys())
|
||||||
if (isJunction(vk))
|
if (isJunction(vk))
|
||||||
@@ -124,7 +131,12 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
}
|
}
|
||||||
let l = Math.hypot(dx, dy) || 1;
|
let l = Math.hypot(dx, dy) || 1;
|
||||||
return [dx / l, dy / l];
|
return [dx / l, dy / l];
|
||||||
};
|
}, flowAt = (rid, edge, end) => {
|
||||||
|
let e = edges[edge];
|
||||||
|
if (!e.oneway) return 0;
|
||||||
|
let d = e.direction.get(rid) ?? 0;
|
||||||
|
return d ? end === "b" == d > 0 ? 1 : -1 : 0;
|
||||||
|
}, clash = (a, b) => a !== 0 && a === b;
|
||||||
for (let rid of routes.keys()) {
|
for (let rid of routes.keys()) {
|
||||||
let routeEdges = edges.filter((e) => e.routes.includes(rid));
|
let routeEdges = edges.filter((e) => e.routes.includes(rid));
|
||||||
if (!routeEdges.length) {
|
if (!routeEdges.length) {
|
||||||
@@ -158,9 +170,9 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
steps.push({ edge: nextEdge.id, forward }), unused.delete(nextEdge.id);
|
steps.push({ edge: nextEdge.id, forward }), unused.delete(nextEdge.id);
|
||||||
let far = forward ? nextEdge.b : nextEdge.a, farEnd = forward ? "b" : "a", d = outDir(nextEdge.id, farEnd);
|
let far = forward ? nextEdge.b : nextEdge.a, farEnd = forward ? "b" : "a", d = outDir(nextEdge.id, farEnd);
|
||||||
arriving = [-d[0], -d[1]], node = far;
|
arriving = [-d[0], -d[1]], node = far;
|
||||||
let best = null, bestDot = -1 / 0;
|
let best = null, bestDot = -1 / 0, arrFlow = flowAt(rid, nextEdge.id, farEnd), arrEdge = nextEdge.id, hasAgreeing = arrFlow !== 0 && nodes[node].ports.some((p) => p.edge !== arrEdge && edges[p.edge].routes.includes(rid) && flowAt(rid, p.edge, p.end) === -arrFlow);
|
||||||
for (let p of nodes[node].ports) {
|
for (let p of nodes[node].ports) {
|
||||||
if (!unused.has(p.edge)) continue;
|
if (!unused.has(p.edge) || hasAgreeing && clash(arrFlow, flowAt(rid, p.edge, p.end))) continue;
|
||||||
let o = outDir(p.edge, p.end), dot = o[0] * arriving[0] + o[1] * arriving[1];
|
let o = outDir(p.edge, p.end), dot = o[0] * arriving[0] + o[1] * arriving[1];
|
||||||
(dot > bestDot + 1e-9 || Math.abs(dot - bestDot) <= 1e-9 && best && p.edge < best.id) && (bestDot = dot, best = edges[p.edge]);
|
(dot > bestDot + 1e-9 || Math.abs(dot - bestDot) <= 1e-9 && best && p.edge < best.id) && (bestDot = dot, best = edges[p.edge]);
|
||||||
}
|
}
|
||||||
@@ -181,7 +193,7 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
if (n.ports.forEach((p, i) => {
|
if (n.ports.forEach((p, i) => {
|
||||||
if (i === ce.port || !edges[p.edge].routes.includes(rid)) return;
|
if (i === ce.port || !edges[p.edge].routes.includes(rid)) return;
|
||||||
let o = outDir(p.edge, p.end), dot = o[0] * arriveDir[0] + o[1] * arriveDir[1];
|
let o = outDir(p.edge, p.end), dot = o[0] * arriveDir[0] + o[1] * arriveDir[1];
|
||||||
dot > bestDot && (bestDot = dot, best = i);
|
clash(flowAt(rid, own.edge, own.end), flowAt(rid, p.edge, p.end)) && (dot -= 4), dot > bestDot && (bestDot = dot, best = i);
|
||||||
}), best < 0) continue;
|
}), best < 0) continue;
|
||||||
let key = `${ce.node}:${Math.min(ce.port, best)}:${Math.max(ce.port, best)}`;
|
let key = `${ce.node}:${Math.min(ce.port, best)}:${Math.max(ce.port, best)}`;
|
||||||
seen.has(key) || (seen.add(key), n.transitions.push({ route: rid, from: ce.port, to: best }), ce.end === "start" ? ce.chain.mergeStart = n.ports[best].edge : ce.chain.mergeEnd = n.ports[best].edge);
|
seen.has(key) || (seen.add(key), n.transitions.push({ route: rid, from: ce.port, to: best }), ce.end === "start" ? ce.chain.mergeStart = n.ports[best].edge : ce.chain.mergeEnd = n.ports[best].edge);
|
||||||
@@ -1373,7 +1385,7 @@ function getWorker(kind) {
|
|||||||
if (failed[kind] || typeof Worker > "u") return null;
|
if (failed[kind] || typeof Worker > "u") return null;
|
||||||
let worker;
|
let worker;
|
||||||
try {
|
try {
|
||||||
blobUrl || (blobUrl = URL.createObjectURL(new Blob(['"use strict";(()=>{var Rn=Object.defineProperty;var Tn=(e,n,t)=>n in e?Rn(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var G=(e,n,t)=>Tn(e,typeof n!="symbol"?n+"":n,t);function Se(e){let n=e.edges.map(o=>({...o,direction:new Map(o.direction??[]),order:o.order.slice()})),t=e.routes?new Map(e.routes.map(o=>[o.id,o])):new Map(e.routeIds.map(o=>[o,{id:o,color:"#000"}]));return{nodes:e.nodes,edges:n,routes:t,chains:new Map(e.chains)}}function Ie(e){let n=e.length,t=new Uint32Array(n+1),o=0;for(let l=0;l<n;l++)o+=e[l].coords.length,t[l+1]=o;let r={coords:new Float64Array(o),anchors:new Float64Array(o),offsets:t,routeIds:[],route:new Uint32Array(n),looks:[],look:new Uint32Array(n),kind:new Uint8Array(n),travel:new Int8Array(n),startDistance:new Float64Array(n),edge:new Int32Array(n),node:new Int32Array(n),betweenU:new Int32Array(n),betweenV:new Int32Array(n)},s=new Map,u=new Map;for(let l=0;l<n;l++){let a=e[l],i=t[l];for(let m=0;m<a.coords.length;m++)r.coords[i+m]=a.coords[m],r.anchors[i+m]=a.anchors[m];let c=s.get(a.route);c===void 0&&(c=r.routeIds.push(a.route)-1,s.set(a.route,c));let d=u.get(a.look);d===void 0&&(d=r.looks.push(a.look)-1,u.set(a.look,d)),r.route[l]=c,r.look[l]=d,r.kind[l]=a.kind==="lane"?0:1,r.travel[l]=a.travel,r.startDistance[l]=a.startDistance,r.edge[l]=a.edge,r.node[l]=a.node??-1,r.betweenU[l]=a.between?a.between[0]:-1,r.betweenV[l]=a.between?a.between[1]:-1}return r}function Ve(e){return[e.coords.buffer,e.anchors.buffer,e.offsets.buffer,e.route.buffer,e.look.buffer,e.kind.buffer,e.travel.buffer,e.startDistance.buffer,e.edge.buffer,e.node.buffer,e.betweenU.buffer,e.betweenV.buffer]}function K(e){let n=0;for(let t=2;t<e.length;t+=2)n+=Math.hypot(e[t]-e[t-2],e[t+1]-e[t-1]);return n}function W(e){let n=new Array(e.length);for(let t=0,o=e.length-2;t<e.length;t+=2,o-=2)n[t]=e[o],n[t+1]=e[o+1];return n}function ne(e){for(let n=2;n<e.length;n+=2){let t=e[n]-e[0],o=e[n+1]-e[1],r=Math.hypot(t,o);if(r>0)return[t/r,o/r]}return[0,0]}function te(e){let n=e.length;for(let t=n-4;t>=0;t-=2){let o=e[n-2]-e[t],r=e[n-1]-e[t+1],s=Math.hypot(o,r);if(s>0)return[o/s,r/s]}return[0,0]}function Xe(e,n){let t=Ze(e,n),o=t[0]-e[0],r=t[1]-e[1],s=Math.hypot(o,r);return s>0?[o/s,r/s]:ne(e)}function Ce(e,n){let t=e.length,o=Ze(W(e),n),r=e[t-2]-o[0],s=e[t-1]-o[1],u=Math.hypot(r,s);return u>0?[r/u,s/u]:te(e)}function Ze(e,n){let t=0;for(let o=2;o<e.length;o+=2){let r=Math.hypot(e[o]-e[o-2],e[o+1]-e[o-1]);if(t+r>=n){let s=r>0?(n-t)/r:0;return[e[o-2]+(e[o]-e[o-2])*s,e[o-1]+(e[o+1]-e[o-1])*s]}t+=r}return[e[e.length-2],e[e.length-1]]}function ue(e,n,t,o=.2){let r=e.length/2,s=new Float64Array(Math.max(0,r-1)),u=0;for(let m=0;m<r-1;m++)s[m]=Math.hypot(e[m*2+2]-e[m*2],e[m*2+3]-e[m*2+1]),u+=s[m];if(u<=0)return e.slice();let l=u*(1-o);if(n+t>l){let m=l/(n+t);n*=m,t*=m}let a=ze(e,s,n),i=ze(e,s,u-t),c=[a.x,a.y],d=0;for(let m=0;m<r-1;m++)d+=s[m],d>n&&d<u-t&&c.push(e[m*2+2],e[m*2+3]);return c.push(i.x,i.y),c}function ze(e,n,t){if(t<=0)return{x:e[0],y:e[1]};let o=0;for(let r=0;r<n.length;r++){let s=n[r];if(o+s>=t){let u=s>0?(t-o)/s:0;return{x:e[r*2]+(e[r*2+2]-e[r*2])*u,y:e[r*2+1]+(e[r*2+3]-e[r*2+1])*u}}o+=s}return{x:e[e.length-2],y:e[e.length-1]}}function pe(e,n){let t=e.length/2;if(t<=2||n<=0)return e.slice();let o=new Uint8Array(t);o[0]=1,o[t-1]=1;let r=n*n,s=[0,t-1];for(;s.length;){let l=s.pop(),a=s.pop(),i=0,c=-1,d=e[a*2],m=e[a*2+1],b=e[l*2],f=e[l*2+1];for(let h=a+1;h<l;h++){let p=He(e[h*2],e[h*2+1],d,m,b,f);p>i&&(i=p,c=h)}i>r&&c>0&&(o[c]=1,s.push(a,c,c,l))}let u=[];for(let l=0;l<t;l++)o[l]&&u.push(e[l*2],e[l*2+1]);return u}function Je(e){let n=e.length/2,t=new Float64Array(n);if(n===0||(t[0]=1/0,t[n-1]=1/0,n<=2))return t;let o=[0,n-1],r=[1/0];for(;o.length;){let s=o.pop(),u=o.pop(),l=r.pop(),a=0,i=-1,c=e[u*2],d=e[u*2+1],m=e[s*2],b=e[s*2+1];for(let f=u+1;f<s;f++){let h=He(e[f*2],e[f*2+1],c,d,m,b);h>a&&(a=h,i=f)}if(a>0&&i>0){let f=a<l?a:l;t[i]=f,o.push(u,i,i,s),r.push(f,f)}}return t}function Ye(e,n,t){let o=e.length/2;if(o<=2||t<=0)return e.slice();let r=t*t,s=[];for(let u=0;u<o;u++)n[u]>r&&s.push(e[u*2],e[u*2+1]);return s}function He(e,n,t,o,r,s){let u=r-t,l=s-o,a=u*u+l*l;if(a>0){let i=Math.max(0,Math.min(1,((e-t)*u+(n-o)*l)/a));u=t+u*i,l=o+l*i}else u=t,l=o;return(e-u)*(e-u)+(n-l)*(n-l)}function Ke(e,n=1e-9){let t=[];for(let o=0;o<e.length;o+=2){let r=t.length;r>=2&&Math.abs(t[r-2]-e[o])<n&&Math.abs(t[r-1]-e[o+1])<n||t.push(e[o],e[o+1])}return t}var qe=12,Nn=8;function Qe(e,n,t=Math.PI/9){return H(e,n,t).points}function H(e,n,t=Math.PI/9){let o=Ke(e),r=o.length/2;if(r<2||n===0)return{points:o.slice(),anchors:o.slice()};let s=new Float64Array((r-1)*4);for(let i=0;i<r-1;i++){let c=o[i*2],d=o[i*2+1],m=o[i*2+2],b=o[i*2+3],f=m-c,h=b-d,p=Math.hypot(f,h),g=h/p,A=-f/p;s[i*4]=c+g*n,s[i*4+1]=d+A*n,s[i*4+2]=m+g*n,s[i*4+3]=b+A*n}let u=[s[0],s[1]],l=[o[0],o[1]];for(let i=1;i<r-1;i++){let c=(i-1)*4,d=i*4,m=s[c],b=s[c+1],f=s[c+2],h=s[c+3],p=s[d],g=s[d+1],A=s[d+2],M=s[d+3],yLine truncated
|
blobUrl || (blobUrl = URL.createObjectURL(new Blob(['"use strict";(()=>{var _n=Object.defineProperty;var Vn=(e,n,t)=>n in e?_n(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var D=(e,n,t)=>Vn(e,typeof n!="symbol"?n+"":n,t);function Ie(e){let n=e.edges.map(o=>({...o,direction:new Map(o.direction??[]),order:o.order.slice()})),t=e.routes?new Map(e.routes.map(o=>[o.id,o])):new Map(e.routeIds.map(o=>[o,{id:o,color:"#000"}]));return{nodes:e.nodes,edges:n,routes:t,chains:new Map(e.chains)}}function Ce(e){let n=e.length,t=new Uint32Array(n+1),o=0;for(let l=0;l<n;l++)o+=e[l].coords.length,t[l+1]=o;let i={coords:new Float64Array(o),anchors:new Float64Array(o),offsets:t,routeIds:[],route:new Uint32Array(n),looks:[],look:new Uint32Array(n),kind:new Uint8Array(n),travel:new Int8Array(n),startDistance:new Float64Array(n),edge:new Int32Array(n),node:new Int32Array(n),betweenU:new Int32Array(n),betweenV:new Int32Array(n)},r=new Map,u=new Map;for(let l=0;l<n;l++){let s=e[l],a=t[l];for(let g=0;g<s.coords.length;g++)i.coords[a+g]=s.coords[g],i.anchors[a+g]=s.anchors[g];let c=r.get(s.route);c===void 0&&(c=i.routeIds.push(s.route)-1,r.set(s.route,c));let d=u.get(s.look);d===void 0&&(d=i.looks.push(s.look)-1,u.set(s.look,d)),i.route[l]=c,i.look[l]=d,i.kind[l]=s.kind==="lane"?0:1,i.travel[l]=s.travel,i.startDistance[l]=s.startDistance,i.edge[l]=s.edge,i.node[l]=s.node??-1,i.betweenU[l]=s.between?s.between[0]:-1,i.betweenV[l]=s.between?s.between[1]:-1}return i}function De(e){return[e.coords.buffer,e.anchors.buffer,e.offsets.buffer,e.route.buffer,e.look.buffer,e.kind.buffer,e.travel.buffer,e.startDistance.buffer,e.edge.buffer,e.node.buffer,e.betweenU.buffer,e.betweenV.buffer]}function H(e){let n=0;for(let t=2;t<e.length;t+=2)n+=Math.hypot(e[t]-e[t-2],e[t+1]-e[t-1]);return n}function W(e){let n=new Array(e.length);for(let t=0,o=e.length-2;t<e.length;t+=2,o-=2)n[t]=e[o],n[t+1]=e[o+1];return n}function ne(e){for(let n=2;n<e.length;n+=2){let t=e[n]-e[0],o=e[n+1]-e[1],i=Math.hypot(t,o);if(i>0)return[t/i,o/i]}return[0,0]}function te(e){let n=e.length;for(let t=n-4;t>=0;t-=2){let o=e[n-2]-e[t],i=e[n-1]-e[t+1],r=Math.hypot(o,i);if(r>0)return[o/r,i/r]}return[0,0]}function Oe(e,n){let t=Xe(e,n),o=t[0]-e[0],i=t[1]-e[1],r=Math.hypot(o,i);return r>0?[o/r,i/r]:ne(e)}function me(e,n){let t=e.length,o=Xe(W(e),n),i=e[t-2]-o[0],r=e[t-1]-o[1],u=Math.hypot(i,r);return u>0?[i/u,r/u]:te(e)}function Xe(e,n){let t=0;for(let o=2;o<e.length;o+=2){let i=Math.hypot(e[o]-e[o-2],e[o+1]-e[o-1]);if(t+i>=n){let r=i>0?(n-t)/i:0;return[e[o-2]+(e[o]-e[o-2])*r,e[o-1]+(e[o+1]-e[o-1])*r]}t+=i}return[e[e.length-2],e[e.length-1]]}function ue(e,n,t,o=.2){let i=e.length/2,r=new Float64Array(Math.max(0,i-1)),u=0;for(let g=0;g<i-1;g++)r[g]=Math.hypot(e[g*2+2]-e[g*2],e[g*2+3]-e[g*2+1]),u+=r[g];if(u<=0)return e.slice();let l=u*(1-o);if(n+t>l){let g=l/(n+t);n*=g,t*=g}let s=ze(e,r,n),a=ze(e,r,u-t),c=[s.x,s.y],d=0;for(let g=0;g<i-1;g++)d+=r[g],d>n&&d<u-t&&c.push(e[g*2+2],e[g*2+3]);return c.push(a.x,a.y),c}function ze(e,n,t){if(t<=0)return{x:e[0],y:e[1]};let o=0;for(let i=0;i<n.length;i++){let r=n[i];if(o+r>=t){let u=r>0?(t-o)/r:0;return{x:e[i*2]+(e[i*2+2]-e[i*2])*u,y:e[i*2+1]+(e[i*2+3]-e[i*2+1])*u}}o+=r}return{x:e[e.length-2],y:e[e.length-1]}}function pe(e,n){let t=e.length/2;if(t<=2||n<=0)return e.slice();let o=new Uint8Array(t);o[0]=1,o[t-1]=1;let i=n*n,r=[0,t-1];for(;r.length;){let l=r.pop(),s=r.pop(),a=0,c=-1,d=e[s*2],g=e[s*2+1],p=e[l*2],h=e[l*2+1];for(let f=s+1;f<l;f++){let b=Ye(e[f*2],e[f*2+1],d,g,p,h);b>a&&(a=b,c=f)}a>i&&c>0&&(o[c]=1,r.push(s,c,c,l))}let u=[];for(let l=0;l<t;l++)o[l]&&u.push(e[l*2],e[l*2+1]);return u}function Ze(e){let n=e.length/2,t=new Float64Array(n);if(n===0||(t[0]=1/0,t[n-1]=1/0,n<=2))return t;let o=[0,n-1],i=[1/0];for(;o.length;){let r=o.pop(),u=o.pop(),l=i.pop(),s=0,a=-1,c=e[u*2],d=e[u*2+1],g=e[r*2],p=e[r*2+1];for(let h=u+1;h<r;h++){let f=Ye(e[h*2],e[h*2+1],c,d,g,p);f>s&&(s=f,a=h)}if(s>0&&a>0){let h=s<l?s:l;t[a]=h,o.push(u,a,a,r),i.push(h,h)}}return t}function Je(e,n,t){let o=e.length/2;if(o<=2||t<=0)return e.slice();let i=t*t,r=[];for(let u=0;u<o;u++)n[u]>i&&r.push(e[u*2],e[u*2+1]);return r}function Ye(e,n,t,o,i,r){let u=i-t,l=r-o,s=u*u+l*l;if(s>0){let a=Math.max(0,Math.min(1,((e-t)*u+(n-o)*l)/s));u=t+u*a,l=o+l*a}else u=t,l=o;return(e-u)*(e-u)+(n-l)*(n-l)}function He(e,n=1e-9){let t=[];for(let o=0;o<e.length;o+=2){let i=t.length;i>=2&&Math.abs(t[i-2]-e[o])<n&&Math.abs(t[i-1]-e[o+1])<n||t.push(e[o],e[o+1])}return t}var Ke=12,Bn=8;function qe(e,n,t=Math.PI/9){return K(e,n,t).points}function K(e,n,t=Math.PI/9){let o=He(e),i=o.length/2;if(i<2||n===0)return{points:o.slice(),anchors:o.slice()};let r=new Float64Array((i-1)*4);for(let a=0;a<i-1;a++){let c=o[a*2],d=o[a*2+1],g=o[a*2+2],p=o[a*2+3],h=g-c,f=p-d,b=Math.hypot(h,f),m=f/b,k=-h/b;r[a*4]=c+m*n,r[a*4+1]=d+k*n,r[a*4+2]=g+m*n,r[a*4+3]=p+k*n}let u=[r[0],r[1]],l=[o[0],o[1]];for(let a=1;a<i-1;a++){let c=(a-1)*4,d=a*4,g=r[c],p=r[c+1],h=r[c+2],f=r[c+3],b=r[d],m=r[d+1],k=r[d+2],y=r[d+3],MLine truncated
|
||||||
} catch {
|
} catch {
|
||||||
return failed[kind] = !0, null;
|
return failed[kind] = !0, null;
|
||||||
}
|
}
|
||||||
@@ -1701,7 +1713,7 @@ function solve(g) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// src/core/layout.ts
|
// src/core/layout.ts
|
||||||
var SIMPLIFY_TOLERANCE_PX2 = 0.25, GENERALIZE_PER_OFFSET = 0.25, MIN_FRONT_MARGIN_LANES = 0.6, MAX_FRONT_FRACTION = 0.42, CLIQUE_MIN_REF_LANES = 1.5, MAX_SLIDE_SLOPE = 0.4, SOLO_EASE_LANES = 12, SOLO_EASE_STEPS = 6, MERGE_BELOW_BUNDLE_WIDTHS = 1, MAX_MERGE_PASSES = 4, BEND_DEVIATION_PX = 1.5, CORNER_BEND_DEG = 60, CORNER_RADIUS_LANES = 1.5, CORNER_MIN_TURN_DEG = 60, CORNER_MAX_REACH = 1.5, FOLLOW_ABOVE_LANES = 1, SNAP_HOOK_LANES = 3, LayoutCache = class {
|
var SIMPLIFY_TOLERANCE_PX2 = 0.25, GENERALIZE_PER_OFFSET = 0.25, MIN_FRONT_MARGIN_LANES = 0.6, MIN_PIECE_PX = 1e-3, MAX_FRONT_FRACTION = 0.42, CLIQUE_MIN_REF_LANES = 1.5, MAX_SLIDE_SLOPE = 0.4, SOLO_EASE_LANES = 12, SOLO_EASE_STEPS = 6, MERGE_BELOW_BUNDLE_WIDTHS = 1, MAX_MERGE_PASSES = 4, BEND_DEVIATION_PX = 1.5, CORNER_BEND_DEG = 60, CORNER_RADIUS_LANES = 1.5, CORNER_MIN_TURN_DEG = 60, CORNER_MAX_REACH = 1.5, FOLLOW_ABOVE_LANES = 1, SNAP_HOOK_LANES = 3, LayoutCache = class {
|
||||||
constructor() {
|
constructor() {
|
||||||
__publicField(this, "state", null);
|
__publicField(this, "state", null);
|
||||||
}
|
}
|
||||||
@@ -1751,8 +1763,8 @@ function layoutAtZoom(g, zoom, styleAt, opts = {}) {
|
|||||||
let tails = planJunction(st, ji).tails;
|
let tails = planJunction(st, ji).tails;
|
||||||
for (let plan of tails) {
|
for (let plan of tails) {
|
||||||
let t = plan.tail;
|
let t = plan.tail;
|
||||||
if (!inView[plan.port.edge] && !t.edges.some((s) => inView[s.edge]) || (resolveTail(st, plan), plan.mode !== 1 || only && !only.has(t.route))) continue;
|
if (!(!inView[plan.port.edge] && !t.edges.some((s) => inView[s.edge])) && (resolveTail(st, plan), !(plan.mode !== 1 || only && !only.has(t.route))))
|
||||||
let path = plan.slide;
|
for (let path of plan.slide)
|
||||||
vertices += path.coords.length / 2, paths.push(path);
|
vertices += path.coords.length / 2, paths.push(path);
|
||||||
}
|
}
|
||||||
for (let plan of tails)
|
for (let plan of tails)
|
||||||
@@ -1779,11 +1791,10 @@ function layoutAtZoom(g, zoom, styleAt, opts = {}) {
|
|||||||
for (let grp of planJunction(st, ji).groups)
|
for (let grp of planJunction(st, ji).groups)
|
||||||
if (!(!inView[grp.edgeU] || !inView[grp.edgeV])) {
|
if (!(!inView[grp.edgeU] || !inView[grp.edgeV])) {
|
||||||
buildGroup(st, grp);
|
buildGroup(st, grp);
|
||||||
for (let m of grp.members) {
|
for (let m of grp.members)
|
||||||
if (m.plan?.mode === 1 || only && !only.has(m.route)) continue;
|
if (!(m.plan?.mode === 1 || only && !only.has(m.route)))
|
||||||
let path = st.connPaths.get(m.key);
|
for (let path of st.connPaths.get(m.key) ?? [])
|
||||||
path && (vertices += path.coords.length / 2, paths.push(path));
|
vertices += path.coords.length / 2, paths.push(path);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (let p of paths)
|
for (let p of paths)
|
||||||
@@ -1905,9 +1916,9 @@ function touchesView(j, inView) {
|
|||||||
function planJunction(st, ji) {
|
function planJunction(st, ji) {
|
||||||
let known = st.groups[ji];
|
let known = st.groups[ji];
|
||||||
if (known) return { groups: known, tails: st.tails[ji] };
|
if (known) return { groups: known, tails: st.tails[ji] };
|
||||||
let g = st.graph, j = st.junctions[ji], byKey = /* @__PURE__ */ new Map(), groups = [];
|
let j = st.junctions[ji], byKey = /* @__PURE__ */ new Map(), groups = [];
|
||||||
for (let t of j.transitions) {
|
for (let t of j.transitions) {
|
||||||
let pu = j.ports[t.u], pv = j.ports[t.v], lateral = offsetTravel(st, pu.edge, t.route, pu.end === "b"), lateralOut = offsetTravel(st, pv.edge, t.route, pv.end === "a"), tu = travelSign(g.edges[pu.edge].direction.get(t.route)) * (pu.end === "b" ? 1 : -1), tv = travelSign(g.edges[pv.edge].direction.get(t.route)) * (pv.end === "a" ? 1 : -1), key = `${pu.edge}:${pv.edge}:${(lateral - lateralOut).toFixed(3)}`, grp = byKey.get(key);
|
let pu = j.ports[t.u], pv = j.ports[t.v], lateral = offsetTravel(st, pu.edge, t.route, pu.end === "b"), lateralOut = offsetTravel(st, pv.edge, t.route, pv.end === "a"), key = `${pu.edge}:${pv.edge}:${(lateral - lateralOut).toFixed(3)}`, grp = byKey.get(key);
|
||||||
grp || (grp = { edgeU: pu.edge, edgeV: pv.edge, members: [] }, byKey.set(key, grp), groups.push(grp)), grp.members.push({
|
grp || (grp = { edgeU: pu.edge, edgeV: pv.edge, members: [] }, byKey.set(key, grp), groups.push(grp)), grp.members.push({
|
||||||
route: t.route,
|
route: t.route,
|
||||||
key: connKey(st, t.route, pu.edge, pu.end, pv.edge, pv.end),
|
key: connKey(st, t.route, pu.edge, pu.end, pv.edge, pv.end),
|
||||||
@@ -1915,7 +1926,6 @@ function planJunction(st, ji) {
|
|||||||
pv,
|
pv,
|
||||||
lateral,
|
lateral,
|
||||||
lateralOut,
|
lateralOut,
|
||||||
travel: tu || tv,
|
|
||||||
via: t.via
|
via: t.via
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1929,7 +1939,7 @@ function planJunction(st, ji) {
|
|||||||
for (let list of crossings.values()) if (list.length > 1) for (let m of list) m.forked = !0;
|
for (let list of crossings.values()) if (list.length > 1) for (let m of list) m.forked = !0;
|
||||||
let tails = [];
|
let tails = [];
|
||||||
for (let t of j.tails) {
|
for (let t of j.tails) {
|
||||||
let p = j.ports[t.port], far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], step = t.edges[t.side === "end" ? 0 : t.edges.length - 1], travel = travelSign(g.edges[p.edge].direction.get(t.route)) * (t.side === "end" ? p.end === "b" ? 1 : -1 : p.end === "a" ? 1 : -1), plan = {
|
let p = j.ports[t.port], far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], step = t.edges[t.side === "end" ? 0 : t.edges.length - 1], plan = {
|
||||||
tail: t,
|
tail: t,
|
||||||
port: p,
|
port: p,
|
||||||
mode: 0,
|
mode: 0,
|
||||||
@@ -1946,7 +1956,6 @@ function planJunction(st, ji) {
|
|||||||
pv: p,
|
pv: p,
|
||||||
lateral: 0,
|
lateral: 0,
|
||||||
lateralOut: 0,
|
lateralOut: 0,
|
||||||
travel,
|
|
||||||
via: [],
|
via: [],
|
||||||
plan,
|
plan,
|
||||||
key: t.side === "end" ? connKey(st, t.route, u, p.end, v, step.forward ? "a" : "b") : connKey(st, t.route, u, step.forward ? "b" : "a", v, p.end)
|
key: t.side === "end" ? connKey(st, t.route, u, p.end, v, step.forward ? "a" : "b") : connKey(st, t.route, u, step.forward ? "b" : "a", v, p.end)
|
||||||
@@ -2066,43 +2075,21 @@ function guideOf(st, parts, edges) {
|
|||||||
function resolveTail(st, plan) {
|
function resolveTail(st, plan) {
|
||||||
if (plan.mode) return;
|
if (plan.mode) return;
|
||||||
plan.mode = 2;
|
plan.mode = 2;
|
||||||
let g = st.graph, t = plan.tail, p = plan.port, portLane = laneOf(st, p.edge, t.route), parts = t.edges.map((s) => orientedPx(st, s.edge, s.forward)), far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], farOffset = offsetTravel(st, far.edge, t.route, far.forward), portOffset = offsetTravel(st, p.edge, t.route, t.side === "end" ? p.end === "b" : p.end === "a"), portPx = preparedPx(st, p.edge), portPart = t.side === "end" ? lastPortion(p.end === "b" ? portPx : reversed(portPx), p.end === "b" ? st.frontB[p.edge] : st.frontA[p.edge]) : firstPortion(p.end === "a" ? portPx : reversed(portPx), p.end === "a" ? st.frontA[p.edge] : st.frontB[p.edge]), edges = [p.edge, ...t.edges.map((s) => s.edge)], guide = t.side === "end" ? guideOf(st, [portPart, ...parts], edges) : guideOf(st, [...parts, portPart], edges), slide = t.side === "end" ? offsetPolylineSlidingAnchored(guide, portOffset, farOffset) : offsetPolylineSlidingAnchored(guide, farOffset, portOffset);
|
let t = plan.tail, p = plan.port, portLane = laneOf(st, p.edge, t.route), parts = t.edges.map((s) => orientedPx(st, s.edge, s.forward)), far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], farOffset = offsetTravel(st, far.edge, t.route, far.forward), portOffset = offsetTravel(st, p.edge, t.route, t.side === "end" ? p.end === "b" : p.end === "a"), portPx = preparedPx(st, p.edge), portPart = t.side === "end" ? lastPortion(p.end === "b" ? portPx : reversed(portPx), p.end === "b" ? st.frontB[p.edge] : st.frontA[p.edge]) : firstPortion(p.end === "a" ? portPx : reversed(portPx), p.end === "a" ? st.frontA[p.edge] : st.frontB[p.edge]), edges = [p.edge, ...t.edges.map((s) => s.edge)], guide = t.side === "end" ? guideOf(st, [portPart, ...parts], edges) : guideOf(st, [...parts, portPart], edges), slide = t.side === "end" ? offsetPolylineSlidingAnchored(guide, portOffset, farOffset) : offsetPolylineSlidingAnchored(guide, farOffset, portOffset);
|
||||||
if (slide.points.length < 4) return;
|
if (slide.points.length < 4) return;
|
||||||
let lanePts = t.side === "end" ? p.end === "b" ? portLane.points : reversed(portLane.points) : p.end === "a" ? portLane.points : reversed(portLane.points);
|
let lanePts = t.side === "end" ? p.end === "b" ? portLane.points : reversed(portLane.points) : p.end === "a" ? portLane.points : reversed(portLane.points);
|
||||||
t.side === "end" ? (slide.points[0] = lanePts[lanePts.length - 2], slide.points[1] = lanePts[lanePts.length - 1]) : (slide.points[slide.points.length - 2] = lanePts[0], slide.points[slide.points.length - 1] = lanePts[1]);
|
t.side === "end" ? (slide.points[0] = lanePts[lanePts.length - 2], slide.points[1] = lanePts[lanePts.length - 1]) : (slide.points[slide.points.length - 2] = lanePts[0], slide.points[slide.points.length - 1] = lanePts[1]);
|
||||||
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
|
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
|
||||||
if (coords.length < 4) return;
|
if (coords.length < 4) return;
|
||||||
let travel = travelSign(g.edges[p.edge].direction.get(t.route)) * (t.side === "end" ? p.end === "b" ? 1 : -1 : p.end === "a" ? 1 : -1), between = t.side === "end" ? [p.edge, far.edge] : [far.edge, p.edge];
|
let between = t.side === "end" ? [p.edge, far.edge] : [far.edge, p.edge], steps = t.side === "end" ? [{ edge: p.edge, forward: p.end === "b" }, ...t.edges] : [...t.edges, { edge: p.edge, forward: p.end === "a" }];
|
||||||
plan.slide = {
|
plan.slide = splitAtNodes(st, t.route, coords, anchors, steps, p.node, between, !0), st.connPaths.set(plan.key, plan.slide), plan.mode = 1;
|
||||||
route: t.route,
|
|
||||||
look: lookOf(st, g.edges[p.edge], t.route),
|
|
||||||
coords,
|
|
||||||
anchors,
|
|
||||||
kind: "connector",
|
|
||||||
travel,
|
|
||||||
startDistance: 0,
|
|
||||||
edge: between[0],
|
|
||||||
node: p.node,
|
|
||||||
between
|
|
||||||
}, st.connPaths.set(plan.key, plan.slide), plan.mode = 1;
|
|
||||||
}
|
}
|
||||||
function islandPaths(st, isl) {
|
function islandPaths(st, isl) {
|
||||||
if (isl.paths) return isl.paths;
|
if (isl.paths) return isl.paths;
|
||||||
let g = st.graph, first = isl.steps[0], last = isl.steps[isl.steps.length - 1], guide = guideOf(st, isl.steps.map((s) => orientedPx(st, s.edge, s.forward)), isl.steps.map((s) => s.edge)), d0 = offsetTravel(st, first.edge, isl.route, first.forward), d1 = offsetTravel(st, last.edge, isl.route, last.forward), slide = offsetPolylineSlidingAnchored(guide, d0, d1);
|
let g = st.graph, first = isl.steps[0], last = isl.steps[isl.steps.length - 1], guide = guideOf(st, isl.steps.map((s) => orientedPx(st, s.edge, s.forward)), isl.steps.map((s) => s.edge)), d0 = offsetTravel(st, first.edge, isl.route, first.forward), d1 = offsetTravel(st, last.edge, isl.route, last.forward), slide = offsetPolylineSlidingAnchored(guide, d0, d1);
|
||||||
if (slide.points.length >= 4) {
|
if (slide.points.length >= 4) {
|
||||||
let e = g.edges[first.edge], travel = travelSign(e.direction.get(isl.route)) * (first.forward ? 1 : -1);
|
let e = g.edges[first.edge];
|
||||||
return isl.paths = [{
|
return isl.paths = splitAtNodes(st, isl.route, slide.points, slide.anchors, isl.steps, first.forward ? e.a : e.b, [first.edge, last.edge], !0);
|
||||||
route: isl.route,
|
|
||||||
look: lookOf(st, e, isl.route),
|
|
||||||
coords: slide.points,
|
|
||||||
anchors: slide.anchors,
|
|
||||||
kind: "connector",
|
|
||||||
travel,
|
|
||||||
startDistance: 0,
|
|
||||||
edge: first.edge,
|
|
||||||
node: first.forward ? e.a : e.b,
|
|
||||||
between: [first.edge, last.edge]
|
|
||||||
}];
|
|
||||||
}
|
}
|
||||||
let lanes = [];
|
let lanes = [];
|
||||||
for (let s of isl.steps) {
|
for (let s of isl.steps) {
|
||||||
@@ -2116,7 +2103,11 @@ function assignDashPhase(st, route) {
|
|||||||
for (let chain of g.chains.get(route) ?? [])
|
for (let chain of g.chains.get(route) ?? [])
|
||||||
for (let s of chain.steps) forwardOn.set(s.edge, s.forward);
|
for (let s of chain.steps) forwardOn.set(s.edge, s.forward);
|
||||||
let travelEnd = (edge) => forwardOn.get(edge) === !1 ? "a" : "b", pieces = [], index = /* @__PURE__ */ new Map(), along = [], add = (p, withTravel) => {
|
let travelEnd = (edge) => forwardOn.get(edge) === !1 ? "a" : "b", pieces = [], index = /* @__PURE__ */ new Map(), along = [], add = (p, withTravel) => {
|
||||||
p && !index.has(p) && (index.set(p, pieces.length), pieces.push(p), along.push(withTravel));
|
let list = p ? Array.isArray(p) ? p : [p] : [];
|
||||||
|
if (list.length && !index.has(list[0])) {
|
||||||
|
for (let q of list) index.set(q, pieces.length);
|
||||||
|
pieces.push(list), along.push(withTravel);
|
||||||
|
}
|
||||||
}, addLane = (edge) => add(lanePathOf(st, edge, route), forwardOn.get(edge) !== !1);
|
}, addLane = (edge) => add(lanePathOf(st, edge, route), forwardOn.get(edge) !== !1);
|
||||||
for (let e of g.edges) !st.short[e.id] && e.routes.includes(route) && addLane(e.id);
|
for (let e of g.edges) !st.short[e.id] && e.routes.includes(route) && addLane(e.id);
|
||||||
for (let ji = 0; ji < st.junctions.length; ji++) {
|
for (let ji = 0; ji < st.junctions.length; ji++) {
|
||||||
@@ -2128,18 +2119,25 @@ function assignDashPhase(st, route) {
|
|||||||
for (let grp of groups)
|
for (let grp of groups)
|
||||||
if (grp.members.some((m) => m.route === route)) {
|
if (grp.members.some((m) => m.route === route)) {
|
||||||
buildGroup(st, grp);
|
buildGroup(st, grp);
|
||||||
for (let m of grp.members)
|
for (let m of grp.members) {
|
||||||
m.route !== route || m.plan?.mode === 1 || add(st.connPaths.get(m.key), !!m.plan || m.pu.end === travelEnd(m.pu.edge));
|
if (m.route !== route || m.plan?.mode === 1) continue;
|
||||||
|
let withTravel = !!m.plan || m.pu.end === travelEnd(m.pu.edge);
|
||||||
|
add(st.connPaths.get(m.key), withTravel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let isl of st.junctions[ji].islands) {
|
||||||
|
if (isl.route !== route) continue;
|
||||||
|
let ps = islandPaths(st, isl);
|
||||||
|
if (ps[0]?.kind === "connector") add(ps, !0);
|
||||||
|
else for (let p of ps) add(p, !0);
|
||||||
}
|
}
|
||||||
for (let isl of st.junctions[ji].islands)
|
|
||||||
if (isl.route === route) for (let p of islandPaths(st, isl)) add(p, !0);
|
|
||||||
}
|
}
|
||||||
if (!pieces.length) return;
|
if (!pieces.length) return;
|
||||||
let n = pieces.length, atPoint = /* @__PURE__ */ new Map(), endsAt = new Array(2 * n);
|
let n = pieces.length, atPoint = /* @__PURE__ */ new Map(), endsAt = new Array(2 * n);
|
||||||
for (let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
let c = pieces[i].coords;
|
let first = pieces[i][0].coords, last = pieces[i][pieces[i].length - 1].coords;
|
||||||
for (let end = 0; end < 2; end++) {
|
for (let end = 0; end < 2; end++) {
|
||||||
let x = end ? c[c.length - 2] : c[0], y = end ? c[c.length - 1] : c[1], row = atPoint.get(x);
|
let x = end ? last[last.length - 2] : first[0], y = end ? last[last.length - 1] : first[1], row = atPoint.get(x);
|
||||||
row || atPoint.set(x, row = /* @__PURE__ */ new Map());
|
row || atPoint.set(x, row = /* @__PURE__ */ new Map());
|
||||||
let list = row.get(y);
|
let list = row.get(y);
|
||||||
list || row.set(y, list = []), list.push(i * 2 + end), endsAt[i * 2 + end] = list;
|
list || row.set(y, list = []), list.push(i * 2 + end), endsAt[i * 2 + end] = list;
|
||||||
@@ -2147,7 +2145,11 @@ function assignDashPhase(st, route) {
|
|||||||
}
|
}
|
||||||
let length = new Float64Array(n).fill(-1), at = new Float64Array(2 * n), reached = new Uint8Array(n), reach = (i, end, d) => {
|
let length = new Float64Array(n).fill(-1), at = new Float64Array(2 * n), reached = new Uint8Array(n), reach = (i, end, d) => {
|
||||||
let l = length[i];
|
let l = length[i];
|
||||||
l < 0 && (length[i] = l = polylineLength(pieces[i].coords));
|
if (l < 0) {
|
||||||
|
l = 0;
|
||||||
|
for (let p of pieces[i]) l += polylineLength(p.coords);
|
||||||
|
length[i] = l;
|
||||||
|
}
|
||||||
let d0 = along[i] ? end ? d - l : d : end ? d + l : d;
|
let d0 = along[i] ? end ? d - l : d : end ? d + l : d;
|
||||||
at[i * 2] = d0, at[i * 2 + 1] = along[i] ? end ? d : d + l : end ? d : d - l, reached[i] = 1;
|
at[i * 2] = d0, at[i * 2 + 1] = along[i] ? end ? d : d + l : end ? d : d - l, reached[i] = 1;
|
||||||
}, root = 0;
|
}, root = 0;
|
||||||
@@ -2180,7 +2182,11 @@ function assignDashPhase(st, route) {
|
|||||||
for (let i of queue) least = Math.min(least, at[i * 2], at[i * 2 + 1]);
|
for (let i of queue) least = Math.min(least, at[i * 2], at[i * 2 + 1]);
|
||||||
for (let i of queue) {
|
for (let i of queue) {
|
||||||
let d0 = at[i * 2] - least;
|
let d0 = at[i * 2] - least;
|
||||||
pieces[i].startDistance = along[i] ? d0 : -d0;
|
for (let p of pieces[i]) {
|
||||||
|
p.startDistance = along[i] ? d0 : -d0;
|
||||||
|
let l = pieces[i].length > 1 ? polylineLength(p.coords) : 0;
|
||||||
|
d0 = along[i] ? d0 + l : d0 - l;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2213,18 +2219,7 @@ function buildGroup(st, grp) {
|
|||||||
let m = c.member, conn = c.coords, node = g.nodes[m.pu.node], anchors = new Array(conn.length);
|
let m = c.member, conn = c.coords, node = g.nodes[m.pu.node], anchors = new Array(conn.length);
|
||||||
for (let i = 0; i < conn.length; i += 2)
|
for (let i = 0; i < conn.length; i += 2)
|
||||||
anchors[i] = node.x * st.scale, anchors[i + 1] = node.y * st.scale;
|
anchors[i] = node.x * st.scale, anchors[i + 1] = node.y * st.scale;
|
||||||
st.connPaths.set(m.key, {
|
st.connPaths.set(m.key, splitAtNodes(st, m.route, conn, anchors, memberSteps(m), m.pu.node, [grp.edgeU, grp.edgeV], !1));
|
||||||
route: m.route,
|
|
||||||
look: lookOf(st, g.edges[grp.edgeU], m.route),
|
|
||||||
coords: conn,
|
|
||||||
anchors,
|
|
||||||
kind: "connector",
|
|
||||||
travel: m.travel,
|
|
||||||
startDistance: 0,
|
|
||||||
edge: grp.edgeU,
|
|
||||||
node: m.pu.node,
|
|
||||||
between: [grp.edgeU, grp.edgeV]
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function cutDirection(st, edge, end, leaving = !1) {
|
function cutDirection(st, edge, end, leaving = !1) {
|
||||||
@@ -2264,7 +2259,7 @@ function buildTailConnector(st, m, clique) {
|
|||||||
made.coords.length < 4 || clique.push({ member: m, lateral: 0, own: made.coords, coords: made.coords, corner: made.corner });
|
made.coords.length < 4 || clique.push({ member: m, lateral: 0, own: made.coords, coords: made.coords, corner: made.corner });
|
||||||
}
|
}
|
||||||
function buildViaConnector(st, m, from, to) {
|
function buildViaConnector(st, m, from, to) {
|
||||||
let g = st.graph, centerline = [], length = 0, append = (pts) => {
|
let centerline = [], length = 0, append = (pts) => {
|
||||||
for (let i = 0; i < pts.length; i += 2) {
|
for (let i = 0; i < pts.length; i += 2) {
|
||||||
let n = centerline.length;
|
let n = centerline.length;
|
||||||
n && Math.abs(centerline[n - 2] - pts[i]) < 1e-6 && Math.abs(centerline[n - 1] - pts[i + 1]) < 1e-6 || (n && (length += Math.hypot(pts[i] - centerline[n - 2], pts[i + 1] - centerline[n - 1])), centerline.push(pts[i], pts[i + 1]));
|
n && Math.abs(centerline[n - 2] - pts[i]) < 1e-6 && Math.abs(centerline[n - 1] - pts[i + 1]) < 1e-6 || (n && (length += Math.hypot(pts[i] - centerline[n - 2], pts[i + 1] - centerline[n - 1])), centerline.push(pts[i], pts[i + 1]));
|
||||||
@@ -2302,18 +2297,100 @@ function buildViaConnector(st, m, from, to) {
|
|||||||
if (slide.points.length < 4) return !1;
|
if (slide.points.length < 4) return !1;
|
||||||
slide.points[0] = from[from.length - 2], slide.points[1] = from[from.length - 1], slide.points[slide.points.length - 2] = to[0], slide.points[slide.points.length - 1] = to[1];
|
slide.points[0] = from[from.length - 2], slide.points[1] = from[from.length - 1], slide.points[slide.points.length - 2] = to[0], slide.points[slide.points.length - 1] = to[1];
|
||||||
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
|
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
|
||||||
return coords.length < 4 ? !1 : (st.connPaths.set(m.key, {
|
return coords.length < 4 ? !1 : (st.connPaths.set(m.key, splitAtNodes(st, m.route, coords, anchors, memberSteps(m), m.pu.node, [m.pu.edge, m.pv.edge], !0)), !0);
|
||||||
route: m.route,
|
}
|
||||||
look: lookOf(st, g.edges[m.pu.edge], m.route),
|
function memberSteps(m) {
|
||||||
coords,
|
let t = m.plan?.tail;
|
||||||
anchors,
|
if (t) {
|
||||||
|
let p = m.pu, step = t.edges[t.side === "end" ? 0 : t.edges.length - 1];
|
||||||
|
return t.side === "end" ? [{ edge: p.edge, forward: p.end === "b" }, step] : [step, { edge: p.edge, forward: p.end === "a" }];
|
||||||
|
}
|
||||||
|
return [{ edge: m.pu.edge, forward: m.pu.end === "b" }, ...m.via, { edge: m.pv.edge, forward: m.pv.end === "a" }];
|
||||||
|
}
|
||||||
|
function splitAtNodes(st, route, coords, anchors, steps, node, between, slide) {
|
||||||
|
let g = st.graph, cut = [], c = coords, a = anchors;
|
||||||
|
for (let k = 0; k + 1 < steps.length; k++) {
|
||||||
|
let [i, t] = nodeCut(st, c, a, steps[k], steps[k + 1], slide), head, headA;
|
||||||
|
if (t <= 0 || t >= 1) {
|
||||||
|
let at = t <= 0 ? i : i + 2;
|
||||||
|
head = c.slice(0, at + 2), headA = a.slice(0, at + 2), c = c.slice(at), a = a.slice(at);
|
||||||
|
} else {
|
||||||
|
let x = c[i] + (c[i + 2] - c[i]) * t, y = c[i + 1] + (c[i + 3] - c[i + 1]) * t, ax = a[i] + (a[i + 2] - a[i]) * t, ay = a[i + 1] + (a[i + 3] - a[i + 1]) * t;
|
||||||
|
head = c.slice(0, i + 2).concat(x, y), headA = a.slice(0, i + 2).concat(ax, ay), c = [x, y, ...c.slice(i + 2)], a = [ax, ay, ...a.slice(i + 2)];
|
||||||
|
}
|
||||||
|
cut.push({ c: head, a: headA, step: steps[k], length: polylineLength(head) });
|
||||||
|
}
|
||||||
|
cut.push({ c, a, step: steps[steps.length - 1], length: polylineLength(c) });
|
||||||
|
let kept = [], pending2 = [];
|
||||||
|
for (let p of cut) {
|
||||||
|
if (p.length < MIN_PIECE_PX) {
|
||||||
|
pending2.push(p);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (let q of pending2.reverse())
|
||||||
|
p.c = q.c.concat(p.c.slice(2)), p.a = q.a.concat(p.a.slice(2));
|
||||||
|
pending2 = [], kept.push(p);
|
||||||
|
}
|
||||||
|
if (kept.length) {
|
||||||
|
let last = kept[kept.length - 1];
|
||||||
|
for (let q of pending2)
|
||||||
|
last.c = last.c.concat(q.c.slice(2)), last.a = last.a.concat(q.a.slice(2));
|
||||||
|
} else {
|
||||||
|
let longest = cut.reduce((x, y) => y.length > x.length ? y : x);
|
||||||
|
kept.push({ ...longest, c: coords, a: anchors });
|
||||||
|
}
|
||||||
|
return kept.map(({ c: c2, a: a2, step }) => {
|
||||||
|
let e = g.edges[step.edge];
|
||||||
|
return {
|
||||||
|
route,
|
||||||
|
look: lookOf(st, e, route),
|
||||||
|
coords: c2,
|
||||||
|
anchors: a2,
|
||||||
kind: "connector",
|
kind: "connector",
|
||||||
travel: m.travel,
|
travel: travelSign(e.direction.get(route)) * (step.forward ? 1 : -1),
|
||||||
startDistance: 0,
|
startDistance: 0,
|
||||||
edge: m.pu.edge,
|
edge: step.edge,
|
||||||
node: m.pu.node,
|
node,
|
||||||
between: [m.pu.edge, m.pv.edge]
|
between
|
||||||
}), !0);
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function signedOffset(line, x, y) {
|
||||||
|
let best = 1 / 0, off = 0;
|
||||||
|
for (let i = 0; i + 3 < line.length; i += 2) {
|
||||||
|
let x1 = line[i], y1 = line[i + 1], dx = line[i + 2] - x1, dy = line[i + 3] - y1, l2 = dx * dx + dy * dy;
|
||||||
|
if (!l2) continue;
|
||||||
|
let t = Math.max(0, Math.min(1, ((x - x1) * dx + (y - y1) * dy) / l2)), d = Math.hypot(x - x1 - t * dx, y - y1 - t * dy);
|
||||||
|
d < best && (best = d, off = (dx * (y - y1) - dy * (x - x1)) / Math.sqrt(l2));
|
||||||
|
}
|
||||||
|
return off;
|
||||||
|
}
|
||||||
|
function nodeCut(st, c, a, from, to, slide) {
|
||||||
|
let e = st.graph.edges[from.edge], n = st.graph.nodes[from.forward ? e.b : e.a], nx = n.x * st.scale, ny = n.y * st.scale, din = endDirectionOver(orientedPx(st, from.edge, from.forward), st.spacing), dout = startDirectionOver(orientedPx(st, to.edge, to.forward), st.spacing), ux = din[0] + dout[0], uy = din[1] + dout[1], ul = Math.hypot(ux, uy), p = slide ? a : c, crossing = (shift) => {
|
||||||
|
let best2 = 1 / 0, bi2 = 0, bt2 = 0;
|
||||||
|
for (let i = 0; i + 3 < p.length; i += 2) {
|
||||||
|
let f0 = (p[i] - nx) * ux + (p[i + 1] - ny) * uy - shift, f1 = (p[i + 2] - nx) * ux + (p[i + 3] - ny) * uy - shift;
|
||||||
|
if (f0 < 0 == f1 < 0) continue;
|
||||||
|
let t = f0 / (f0 - f1), d = Math.hypot(c[i] + (c[i + 2] - c[i]) * t - nx, c[i + 1] + (c[i + 3] - c[i + 1]) * t - ny);
|
||||||
|
d < best2 && ([best2, bi2, bt2] = [d, i, t]);
|
||||||
|
}
|
||||||
|
return best2 < 1 / 0 ? [bi2, bt2] : null;
|
||||||
|
};
|
||||||
|
if (ul > 1e-6) {
|
||||||
|
let shift = 0;
|
||||||
|
if (!slide) {
|
||||||
|
let m = c.length, lu = signedOffset(orientedPx(st, from.edge, from.forward), c[0], c[1]), lv = signedOffset(orientedPx(st, to.edge, to.forward), c[m - 2], c[m - 1]), sin = din[0] * dout[1] - din[1] * dout[0], cos = din[0] * dout[0] + din[1] * dout[1], d = lu - lv;
|
||||||
|
Math.abs(sin) > 1e-9 && (shift = Math.max(-Math.abs(d) * ul, Math.min(Math.abs(d) * ul, d * (1 + cos) / sin)));
|
||||||
|
}
|
||||||
|
let hit = crossing(shift) ?? (shift ? crossing(0) : null);
|
||||||
|
if (hit) return hit;
|
||||||
|
}
|
||||||
|
let best = 1 / 0, bi = 0, bt = 0;
|
||||||
|
for (let i = 0; i + 3 < c.length; i += 2) {
|
||||||
|
let dx = c[i + 2] - c[i], dy = c[i + 3] - c[i + 1], len = dx * dx + dy * dy, t = len ? Math.max(0, Math.min(1, ((nx - c[i]) * dx + (ny - c[i + 1]) * dy) / len)) : 0, d = Math.hypot(c[i] + dx * t - nx, c[i + 1] + dy * t - ny);
|
||||||
|
d < best && ([best, bi, bt] = [d, i, t]);
|
||||||
|
}
|
||||||
|
return [bi, bt];
|
||||||
}
|
}
|
||||||
function buildJunctions(g, short, edgeLen, dirA, dirB, halfWidth) {
|
function buildJunctions(g, short, edgeLen, dirA, dirB, halfWidth) {
|
||||||
let N = g.nodes.length, parent = new Int32Array(N);
|
let N = g.nodes.length, parent = new Int32Array(N);
|
||||||
@@ -2659,14 +2736,14 @@ var TessellateCache = class {
|
|||||||
return key !== this.key && (this.chunks = /* @__PURE__ */ new WeakMap(), this.key = key), this.out || (this.out = new MeshBuilder(Math.max(64, estimate * 3), Math.max(192, estimate * 9))), this.out.reset(), this.out;
|
return key !== this.key && (this.chunks = /* @__PURE__ */ new WeakMap(), this.key = key), this.out || (this.out = new MeshBuilder(Math.max(64, estimate * 3), Math.max(192, estimate * 9))), this.out.reset(), this.out;
|
||||||
}
|
}
|
||||||
/** @internal */
|
/** @internal */
|
||||||
emit(b, p, color, opts) {
|
emit(b, p, color, opts, before = null, after = null) {
|
||||||
let hit = this.chunks.get(p);
|
let hit = this.chunks.get(p), seams = seamKey(before, after);
|
||||||
if (hit && hit.startDistance === p.startDistance && hit.color === p.look.color) {
|
if (hit && hit.startDistance === p.startDistance && hit.color === p.look.color && hit.seams === seams) {
|
||||||
appendChunk(b, hit);
|
appendChunk(b, hit);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let nv = b.nv, ni = b.ni;
|
let nv = b.nv, ni = b.ni;
|
||||||
if (tessellatePath(b, p.coords, p.anchors, color, p.startDistance, opts), hit === void 0) {
|
if (tessellatePath(b, p.coords, p.anchors, color, p.startDistance, opts, before, after), hit === void 0) {
|
||||||
this.chunks.set(p, null);
|
this.chunks.set(p, null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -2678,7 +2755,8 @@ var TessellateCache = class {
|
|||||||
indices,
|
indices,
|
||||||
vertexCount: b.nv - nv,
|
vertexCount: b.nv - nv,
|
||||||
startDistance: p.startDistance,
|
startDistance: p.startDistance,
|
||||||
color: p.look.color
|
color: p.look.color,
|
||||||
|
seams
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -2706,9 +2784,9 @@ function tessellate(paths, opts) {
|
|||||||
let start = b.ni, c = colorCache.get(look.color);
|
let start = b.ni, c = colorCache.get(look.color);
|
||||||
c || colorCache.set(look.color, c = parseColor(look.color));
|
c || colorCache.set(look.color, c = parseColor(look.color));
|
||||||
let pieces = [];
|
let pieces = [];
|
||||||
for (let p of list) {
|
for (let k = 0; k < list.length; k++) {
|
||||||
let from = b.ni;
|
let p = list[k], from = b.ni, before = k > 0 ? seamDirection(list[k - 1], p, !0) : null, after = k + 1 < list.length ? seamDirection(p, list[k + 1], !1) : null;
|
||||||
cache2 ? cache2.emit(b, p, c, opts) : tessellatePath(b, p.coords, p.anchors, c, p.startDistance, opts), addPiece(pieces, from, b.ni - from, p.edge);
|
cache2 ? cache2.emit(b, p, c, opts, before, after) : tessellatePath(b, p.coords, p.anchors, c, p.startDistance, opts, before, after), addPiece(pieces, from, b.ni - from, p.edge);
|
||||||
}
|
}
|
||||||
if (b.ni > start) {
|
if (b.ni > start) {
|
||||||
groups.push([start, b.ni - start]), groupRoutes.push(rid), groupLooks.push(look), groupPieces.push(pieces);
|
groups.push([start, b.ni - start]), groupRoutes.push(rid), groupLooks.push(look), groupPieces.push(pieces);
|
||||||
@@ -2751,7 +2829,25 @@ function dotsOnPath(b, px, anchorsPx, color, startDistance, period, opts) {
|
|||||||
b.tri(v0, v1, v2), b.tri(v0, v2, v3);
|
b.tri(v0, v1, v2), b.tri(v0, v2, v3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function tessellatePath(b, px, anchorsPx, color, startDistance, opts) {
|
function seamKey(before, after) {
|
||||||
|
return `${before ? before.join() : ""}|${after ? after.join() : ""}`;
|
||||||
|
}
|
||||||
|
function seamDirection(p, q, last) {
|
||||||
|
if (p.kind !== "connector" || q.kind !== "connector" || p.between !== q.between || p.route !== q.route) return null;
|
||||||
|
let a = p.coords, c = q.coords, n = a.length;
|
||||||
|
if (n < 4 || c.length < 4 || a[n - 2] !== c[0] || a[n - 1] !== c[1]) return null;
|
||||||
|
if (last) {
|
||||||
|
let i = n - 4;
|
||||||
|
for (; i > 0 && Math.abs(a[i] - a[n - 2]) < 1e-6 && Math.abs(a[i + 1] - a[n - 1]) < 1e-6; ) i -= 2;
|
||||||
|
let dx2 = a[n - 2] - a[i], dy2 = a[n - 1] - a[i + 1], l2 = Math.hypot(dx2, dy2);
|
||||||
|
return l2 < 1e-6 ? null : [dx2 / l2, dy2 / l2];
|
||||||
|
}
|
||||||
|
let j = 2;
|
||||||
|
for (; j + 2 < c.length && Math.abs(c[j] - c[0]) < 1e-6 && Math.abs(c[j + 1] - c[1]) < 1e-6; ) j += 2;
|
||||||
|
let dx = c[j] - c[0], dy = c[j + 1] - c[1], l = Math.hypot(dx, dy);
|
||||||
|
return l < 1e-6 ? null : [dx / l, dy / l];
|
||||||
|
}
|
||||||
|
function tessellatePath(b, px, anchorsPx, color, startDistance, opts, before = null, after = null) {
|
||||||
let pts = [], anc = [];
|
let pts = [], anc = [];
|
||||||
for (let i = 0; i < px.length; i += 2) {
|
for (let i = 0; i < px.length; i += 2) {
|
||||||
let n2 = pts.length;
|
let n2 = pts.length;
|
||||||
@@ -2780,7 +2876,7 @@ function tessellatePath(b, px, anchorsPx, color, startDistance, opts) {
|
|||||||
sdx[i] = dx / l, sdy[i] = dy / l;
|
sdx[i] = dx / l, sdy[i] = dy / l;
|
||||||
}
|
}
|
||||||
for (let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
let hasPrev = i > 0, hasNext = i < n - 1, dPrevX = hasPrev ? sdx[i - 1] : 0, dPrevY = hasPrev ? sdy[i - 1] : 0, dNextX = hasNext ? sdx[i] : 0, dNextY = hasNext ? sdy[i] : 0, nPrevX = dPrevY, nPrevY = -dPrevX, nNextX = dNextY, nNextY = -dNextX;
|
let hasPrev = i > 0 || !!before, hasNext = i < n - 1 || !!after, dPrevX = i > 0 ? sdx[i - 1] : before ? before[0] : 0, dPrevY = i > 0 ? sdy[i - 1] : before ? before[1] : 0, dNextX = i < n - 1 ? sdx[i] : after ? after[0] : 0, dNextY = i < n - 1 ? sdy[i] : after ? after[1] : 0, nPrevX = dPrevY, nPrevY = -dPrevX, nNextX = dNextY, nNextY = -dNextX;
|
||||||
if (!hasPrev) {
|
if (!hasPrev) {
|
||||||
fan(i, nNextX, nNextY, -nNextX, -nNextY, !0), pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
fan(i, nNextX, nNextY, -nNextX, -nNextY, !0), pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
||||||
continue;
|
continue;
|
||||||
@@ -2789,9 +2885,9 @@ function tessellatePath(b, px, anchorsPx, color, startDistance, opts) {
|
|||||||
pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1);
|
pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let jx = nPrevX + nNextX, jy = nPrevY + nNextY, jl = Math.hypot(jx, jy);
|
let seamEnd = i === n - 1, seamStart = i === 0, jx = nPrevX + nNextX, jy = nPrevY + nNextY, jl = Math.hypot(jx, jy);
|
||||||
if (jl < 1e-9) {
|
if (jl < 1e-9) {
|
||||||
pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1), pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
seamStart || (pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1)), seamEnd || pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
jx /= jl, jy /= jl;
|
jx /= jl, jy /= jl;
|
||||||
@@ -2800,7 +2896,7 @@ function tessellatePath(b, px, anchorsPx, color, startDistance, opts) {
|
|||||||
pair(i, jx * miterLen, jy * miterLen, jx, jy, !0);
|
pair(i, jx * miterLen, jy * miterLen, jx, jy, !0);
|
||||||
else {
|
else {
|
||||||
let outsideLeft = dPrevX * dNextY - dPrevY * dNextX > 0;
|
let outsideLeft = dPrevX * dNextY - dPrevY * dNextX > 0;
|
||||||
pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), outsideLeft ? fan(i, nPrevX, nPrevY, nNextX, nNextY, !1) : fan(i, -nPrevX, -nPrevY, -nNextX, -nNextY, !0), pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
seamStart || (pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), outsideLeft ? fan(i, nPrevX, nPrevY, nNextX, nNextY, !1) : fan(i, -nPrevX, -nPrevY, -nNextX, -nNextY, !0)), seamEnd || pair(i, nNextX, nNextY, nNextX, nNextY, !1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-7
@@ -237,14 +237,14 @@ class AppTest < Minitest::Test
|
|||||||
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
|
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_the_vehicle_is_readable_by_anyone_but_saved_only_when_logged_in
|
def test_vehicles_are_readable_by_anyone_but_saved_only_when_logged_in
|
||||||
assert_equal 3.0, json_body(request.get("/api/vehicle"))["height"]
|
assert_equal "Car", json_body(request.get("/api/vehicles")).first["name"]
|
||||||
vehicle = { height: 3.3, width: 2.3, length: 7, weight: 3.5 }
|
vehicles = JSON.generate([{ id: "car", name: "Car" }, { id: "van", name: "Van", height: 3.3 }])
|
||||||
assert_equal 401, request.put("/api/vehicle", params: vehicle).status
|
assert_equal 401, request.put("/api/vehicles", input: vehicles).status
|
||||||
assert_equal 3.3, json_body(request.put("/api/vehicle", params: vehicle, **logged_in_env))["height"]
|
assert_equal 3.3, json_body(request.put("/api/vehicles", input: vehicles, **logged_in_env)).last["height"]
|
||||||
assert_equal 400, request.put("/api/vehicle", params: vehicle.merge(weight: 0), **logged_in_env).status
|
assert_equal 400, request.put("/api/vehicles", input: "[]", **logged_in_env).status
|
||||||
ensure
|
ensure
|
||||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json"))
|
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicles.json"))
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_changes_and_exports_need_login
|
def test_changes_and_exports_need_login
|
||||||
|
|||||||
+50
-18
@@ -25,16 +25,18 @@ class RoutingTest < Minitest::Test
|
|||||||
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_a_request_during_an_offline_build_waits_for_it
|
def test_a_request_while_the_offline_build_downloads_waits_for_the_extracts_only
|
||||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
Maptool::PmtilesBuilder.instance_variable_set(:@fetching_extracts, true)
|
||||||
Maptool::Routing.request_build(@data)
|
Maptool::Routing.request_build(@data)
|
||||||
assert_equal "waiting for the offline map build", Maptool::Routing.build_status(@data)[:step]
|
assert_equal "waiting for the offline map downloads", Maptool::Routing.build_status(@data)[:step]
|
||||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||||
|
|
||||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "done")
|
# Planetiler still running doesn't matter, the extracts are in.
|
||||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||||
Maptool::Routing.offline_build_finished(@data)
|
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||||
|
Maptool::PmtilesBuilder.send(:extracts_ready, @data)
|
||||||
assert File.exist?(File.join(@routing, "build-request.json"))
|
assert File.exist?(File.join(@routing, "build-request.json"))
|
||||||
|
refute Maptool::PmtilesBuilder.fetching_extracts?
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_update_check_compares_regions_and_extract_age
|
def test_update_check_compares_regions_and_extract_age
|
||||||
@@ -92,11 +94,22 @@ class RoutingTest < Minitest::Test
|
|||||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_the_vehicle_is_validated_and_stored
|
def test_vehicle_profiles_are_validated_and_stored
|
||||||
assert_equal Maptool::Routing::DEFAULT_VEHICLE, Maptool::Routing.vehicle(@data)
|
assert_equal %w[car camper], Maptool::Routing.vehicles(@data).map { |v| v[:id] }
|
||||||
Maptool::Routing.save_vehicle(@data, "height" => "3.4", "width" => "2.4", "length" => "8", "weight" => "4.2")
|
assert_equal "Car", Maptool::Routing.vehicle(@data, "nope")[:name]
|
||||||
assert_equal 4.2, Maptool::Routing.vehicle(@data)[:weight]
|
|
||||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicle(@data, "height" => "30", "width" => "2", "length" => "8", "weight" => "3") }
|
Maptool::Routing.save_vehicles(@data, [{ "id" => "car", "name" => "Car", "height" => "" },
|
||||||
|
{ "id" => "van", "name" => "Van", "height" => "3.4", "weight" => "4.2" }])
|
||||||
|
assert_equal({ id: "van", name: "Van", height: 3.4, weight: 4.2 }, Maptool::Routing.vehicle(@data, "van"))
|
||||||
|
assert_equal({ id: "car", name: "Car" }, Maptool::Routing.vehicle(@data, "car"))
|
||||||
|
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "height" => "30" }]) }
|
||||||
|
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "" }]) }
|
||||||
|
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_the_old_single_vehicle_becomes_the_camper
|
||||||
|
File.write(File.join(@data, "vehicle.json"), JSON.generate(height: 3.3, width: 2.3, length: 7, weight: 3.5))
|
||||||
|
assert_equal 3.3, Maptool::Routing.vehicle(@data, "camper")[:height]
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_decode_polyline_reads_valhallas_precision_6
|
def test_decode_polyline_reads_valhallas_precision_6
|
||||||
@@ -108,24 +121,40 @@ class RoutingTest < Minitest::Test
|
|||||||
shape = "wdg|xA{ubdQc@w@"
|
shape = "wdg|xA{ubdQc@w@"
|
||||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
||||||
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
|
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
|
||||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
# The per-country lookup failing (400) leaves the route as it is.
|
||||||
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLE)
|
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url|
|
||||||
|
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1])
|
||||||
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
|
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
|
||||||
end
|
end
|
||||||
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
|
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
|
||||||
|
|
||||||
request = serve_once("HTTP/1.1 400 Bad Request\r\nContent-Length: 20\r\n\r\n{\"error\":\"no route\"}") do |url|
|
request = serve_once("HTTP/1.1 400 Bad Request\r\nContent-Length: 20\r\n\r\n{\"error\":\"no route\"}") do |url|
|
||||||
error = assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::DEFAULT_VEHICLE.merge(weight: 7.5)) }
|
error = assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::DEFAULT_VEHICLES[1].merge(weight: 7.5)) }
|
||||||
assert_equal "no route", error.message
|
assert_equal "no route", error.message
|
||||||
end
|
end
|
||||||
assert_includes request, %("costing":"truck")
|
assert_includes request, %("costing":"truck")
|
||||||
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
|
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_a_route_sums_motorway_and_toll_km_per_country_and_can_avoid_tolls
|
||||||
|
route = JSON.generate(trip: { summary: { length: 3, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
|
||||||
|
attributes = JSON.generate(admins: [{ country_code: "AT" }, { country_code: "SK" }],
|
||||||
|
edges: [{ length: 1.0, road_class: "motorway", toll: false, end_node: { admin_index: 0 } },
|
||||||
|
{ length: 0.5, road_class: "primary", toll: false, end_node: { admin_index: 0 } },
|
||||||
|
{ length: 1.5, road_class: "motorway", toll: true, end_node: { admin_index: 1 } }])
|
||||||
|
ok = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
|
||||||
|
request = serve_once(ok.(route), ok.(attributes)) do |url|
|
||||||
|
countries = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties][:countries]
|
||||||
|
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], countries
|
||||||
|
end
|
||||||
|
assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}})
|
||||||
|
assert_includes request, "/trace_attributes"
|
||||||
|
end
|
||||||
|
|
||||||
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
|
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
|
||||||
reply = JSON.generate(type: "FeatureCollection", features: [])
|
reply = JSON.generate(type: "FeatureCollection", features: [])
|
||||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||||
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLE)["type"]
|
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLES[1])["type"]
|
||||||
end
|
end
|
||||||
assert_includes request, %("contours":[{"time":30},{"time":60}])
|
assert_includes request, %("contours":[{"time":30},{"time":60}])
|
||||||
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
|
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
|
||||||
@@ -146,17 +175,20 @@ class RoutingTest < Minitest::Test
|
|||||||
ENV.delete("OSMIUM_BIN")
|
ENV.delete("OSMIUM_BIN")
|
||||||
end
|
end
|
||||||
|
|
||||||
# Answers one HTTP request with `response`; returns what was received.
|
# Answers one HTTP request per response, in order; returns what was received.
|
||||||
def serve_once(response)
|
def serve_once(*responses)
|
||||||
server = TCPServer.new("127.0.0.1", 0)
|
server = TCPServer.new("127.0.0.1", 0)
|
||||||
received = +""
|
received = +""
|
||||||
thread = Thread.new do
|
thread = Thread.new do
|
||||||
|
responses.each do |response|
|
||||||
client = server.accept
|
client = server.accept
|
||||||
received << client.readpartial(65_536)
|
request = client.readpartial(65_536)
|
||||||
received << client.readpartial(65_536) unless received.include?("{")
|
request << client.readpartial(65_536) unless request.include?("{")
|
||||||
|
received << request
|
||||||
client.write(response)
|
client.write(response)
|
||||||
client.close
|
client.close
|
||||||
end
|
end
|
||||||
|
end
|
||||||
yield "http://127.0.0.1:#{server.addr[1]}"
|
yield "http://127.0.0.1:#{server.addr[1]}"
|
||||||
thread.join
|
thread.join
|
||||||
received
|
received
|
||||||
|
|||||||
+19
-6
@@ -121,6 +121,7 @@
|
|||||||
<button type="button" data-action="save" hidden>Save to library</button>
|
<button type="button" data-action="save" hidden>Save to library</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="route-panel__summary"></p>
|
<p class="route-panel__summary"></p>
|
||||||
|
<ul class="route-panel__countries" hidden></ul>
|
||||||
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
|
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
|
||||||
<details class="route-panel__directions" hidden>
|
<details class="route-panel__directions" hidden>
|
||||||
<summary>Directions</summary>
|
<summary>Directions</summary>
|
||||||
@@ -138,12 +139,24 @@
|
|||||||
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="route-panel__reach-status" hidden></p>
|
<p class="route-panel__reach-status" hidden></p>
|
||||||
<fieldset class="route-panel__vehicle">
|
<div class="route-panel__vehicle-row">
|
||||||
<legend>Vehicle</legend>
|
<label>Vehicle <select class="route-panel__vehicle-select"></select></label>
|
||||||
<label>Height <input type="number" name="height" step="0.1" min="1" max="6"> m</label>
|
<button type="button" data-action="vehicle-edit" hidden>Edit</button>
|
||||||
<label>Width <input type="number" name="width" step="0.1" min="1" max="4"> m</label>
|
</div>
|
||||||
<label>Length <input type="number" name="length" step="0.5" min="2" max="25"> m</label>
|
<div class="route-panel__avoid">
|
||||||
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60"> t</label>
|
Avoid
|
||||||
|
<label><input type="checkbox" name="tolls"> tolls</label>
|
||||||
|
<label><input type="checkbox" name="highways"> motorways</label>
|
||||||
|
</div>
|
||||||
|
<fieldset class="route-panel__vehicle" hidden>
|
||||||
|
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
|
||||||
|
<label>Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
|
||||||
|
<label>Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
|
||||||
|
<label>Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
|
||||||
|
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
|
||||||
|
<p class="route-panel__vehicle-hint">Empty: no limit. Over 3.5 t routes as a truck.</p>
|
||||||
|
<button type="button" data-action="vehicle-add">+ New vehicle</button>
|
||||||
|
<button type="button" data-action="vehicle-delete">Delete</button>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in new issue
Block a user