Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Improve the Cargo documentation #87

Merged
merged 10 commits into from
May 12, 2022
2 changes: 2 additions & 0 deletions maplibre-winit/src/input/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ impl InputController {
false
}

/// Process the given winit `[winit::event::WindowEvent]`.
/// Returns true if the event has been processed and false otherwise.
pub fn window_input(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::CursorMoved { position, .. } => {
Expand Down
4 changes: 0 additions & 4 deletions maplibre-winit/src/input/pan_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,6 @@ impl PanHandler {
return false;
}

if !self.is_panning {
// starting to pan
}

if *state == ElementState::Pressed {
// currently panning or starting to pan
self.is_panning = true;
Expand Down
7 changes: 6 additions & 1 deletion maplibre/build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
//! # Build
//!
//! This script is built and executed just before building the package.
//! It will validate the WGSL (WebGPU Shading Language) shaders and embed static files.

use std::path::{Path, PathBuf};
use std::{env, fs};

Expand All @@ -8,7 +13,7 @@ const MUNICH_X: u32 = 17425;
const MUNICH_Y: u32 = 11365;
const MUNICH_Z: u8 = 15;

/// Tiles which can be used by StaticTileFetcher
/// Tiles which can be used by StaticTileFetcher.
fn clean_static_tiles() -> PathBuf {
let out_dir = env::var("OUT_DIR").unwrap();

Expand Down
4 changes: 4 additions & 0 deletions maplibre/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
//! Collection of utilities used to perform certain calculations more conveniently.

/// Re-export of the io module.
pub mod io {
pub use crate::io::*;
}

/// Re-export of the tessellation module.
pub mod tessellation {
pub use crate::tessellation::*;
}
10 changes: 9 additions & 1 deletion maplibre/src/coords.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! File which exposes all kinds of coordinates used throughout maplibre-rs
//! Provides utilities related to coordinates.

use std::fmt;
use std::fmt::Formatter;
Expand Down Expand Up @@ -31,6 +31,11 @@ const fn create_zoom_bounds<const DIM: usize>() -> [u32; DIM] {
result
}

/// Represents the position of a node within a quad tree. The first u8 defines the `ZoomLevel` of the node.
/// The remaining bytes define which part (north west, south west, south east, north east) of each
/// subdivision of the quadtree is concerned.
///
/// TODO: We can optimize the quadkey and store the keys on 2 bits instead of 8
#[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Copy)]
pub struct Quadkey([u8; MAX_ZOOM]);

Expand All @@ -55,6 +60,8 @@ impl fmt::Debug for Quadkey {
}
}

/// `Zoom` is an exponential scale that defines the zoom of the camera on the map.
/// We can derive the `ZoomLevel` from `Zoom` by using the `[crate::coords::ZOOM_BOUNDS]`.
#[derive(Copy, Clone, Debug)]
pub struct Zoom(f64);

Expand Down Expand Up @@ -439,6 +446,7 @@ impl From<Point3<f64>> for WorldCoords {
}
}

/// Defines a bounding box on a tiled map with a [`ZoomLevel`] and a padding.
#[derive(Debug)]
pub struct ViewRegion {
min_tile: WorldTileCoords,
Expand Down
1 change: 1 addition & 0 deletions maplibre/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ impl RenderError {
}
}

/// Enumeration of errors which can happen during the operation of the library.
#[derive(Debug)]
pub enum Error {
Schedule,
Expand Down
28 changes: 20 additions & 8 deletions maplibre/src/io/geometry_index.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Geometry index.

use std::collections::{BTreeMap, HashMap};

use cgmath::num_traits::Signed;
Expand All @@ -12,6 +14,7 @@ use rstar::{Envelope, PointDistance, RTree, RTreeObject, AABB};
use crate::coords::{InnerCoords, Quadkey, WorldCoords, WorldTileCoords, Zoom, EXTENT, TILE_SIZE};
use crate::util::math::bounds_from_points;

/// A quad tree storing the currently loaded tiles.
pub struct GeometryIndex {
index: BTreeMap<Quadkey, TileIndex>,
}
Expand Down Expand Up @@ -55,6 +58,11 @@ impl GeometryIndex {
}
}

/// Index of tiles which can be of two types: spatial or linear.
/// Spatial tiles are stored in a multi-dimentional tree which represents their position in the tile.
/// Linear tiles are simply stored in a vector.
///
/// A spatial tile index can theoretically improve query performance on tiles. Practically it could be slower though. The `Spatial` index is experimental and currently unused.
pub enum TileIndex {
Spatial { tree: RTree<IndexedGeometry<f64>> },
Linear { list: Vec<IndexedGeometry<f64>> },
Expand Down Expand Up @@ -85,6 +93,8 @@ impl TileIndex {
}
}

/// An indexed geometry contains an exact vector geometry, computed bounds which
/// can be helpful when interacting with the geometry and a hashmap of properties.
#[derive(Debug, Clone)]
pub struct IndexedGeometry<T>
where
Expand All @@ -95,6 +105,7 @@ where
pub properties: HashMap<String, String>,
}

/// Contains either a polygon or line vector.
#[derive(Debug, Clone)]
pub enum ExactGeometry<T>
where
Expand Down Expand Up @@ -158,6 +169,7 @@ where
}
}

/// A processor able to create geometries using `[geozero::geo_types::GeoWriter]`.
pub struct IndexProcessor {
geo_writer: GeoWriter,
geometries: Vec<IndexedGeometry<f64>>,
Expand Down Expand Up @@ -236,36 +248,36 @@ impl PropertyProcessor for IndexProcessor {
}

impl FeatureProcessor for IndexProcessor {
/// Begin of dataset processing
/// Begin of dataset processing.
fn dataset_begin(&mut self, _name: Option<&str>) -> Result<(), GeozeroError> {
Ok(())
}
/// End of dataset processing
/// End of dataset processing.
fn dataset_end(&mut self) -> Result<(), GeozeroError> {
Ok(())
}
/// Begin of feature processing
/// Begin of feature processing.
fn feature_begin(&mut self, _idx: u64) -> Result<(), GeozeroError> {
Ok(())
}
/// End of feature processing
/// End of feature processing.
fn feature_end(&mut self, _idx: u64) -> Result<(), GeozeroError> {
Ok(())
}
/// Begin of feature property processing
/// Begin of feature property processing.
fn properties_begin(&mut self) -> Result<(), GeozeroError> {
self.properties = Some(HashMap::new());
Ok(())
}
/// End of feature property processing
/// End of feature property processing.
fn properties_end(&mut self) -> Result<(), GeozeroError> {
Ok(())
}
/// Begin of feature geometry processing
/// Begin of feature geometry processing.
fn geometry_begin(&mut self) -> Result<(), GeozeroError> {
Ok(())
}
/// End of feature geometry processing
/// End of feature geometry processing.
fn geometry_end(&mut self) -> Result<(), GeozeroError> {
let geometry = self.geo_writer.geometry().cloned().unwrap();

Expand Down
9 changes: 8 additions & 1 deletion maplibre/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub mod shared_thread_state;
pub mod tile_cache;
pub mod tile_request_state;

/// Contains a `Tile` if the fetch was successful otherwise `Unavailable`.
pub enum TileFetchResult {
Unavailable {
coords: WorldTileCoords,
Expand All @@ -41,16 +42,20 @@ impl fmt::Debug for TileFetchResult {
}
}

/// [crate::io::TileTessellateMessage] or [crate::io::LayerTessellateMessage] tessellation message.
pub enum TessellateMessage {
Tile(TileTessellateMessage),
Layer(LayerTessellateMessage),
}

/// The result of the tessellation of a tile.
pub struct TileTessellateMessage {
pub request_id: TileRequestID,
pub coords: WorldTileCoords,
}

/// `TessellatedLayer` contains the result of the tessellation for a specific layer, otherwise
/// `UnavailableLayer` if the layer doesn't exist.
pub enum LayerTessellateMessage {
UnavailableLayer {
coords: WorldTileCoords,
Expand All @@ -59,7 +64,7 @@ pub enum LayerTessellateMessage {
TessellatedLayer {
coords: WorldTileCoords,
buffer: OverAlignedVertexBuffer<ShaderVertex, IndexDataType>,
/// Holds for each feature the count of indices
/// Holds for each feature the count of indices.
feature_indices: Vec<u32>,
layer_data: tile::Layer,
},
Expand Down Expand Up @@ -87,6 +92,7 @@ impl LayerTessellateMessage {
}
}

/// A request for a tile at the given coordinates and in the given layers.
#[derive(Clone)]
pub struct TileRequest {
pub coords: WorldTileCoords,
Expand All @@ -99,4 +105,5 @@ impl fmt::Debug for TileRequest {
}
}

/// The ID format for a tile request.
pub type TileRequestID = u32;
4 changes: 4 additions & 0 deletions maplibre/src/io/scheduler.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
//! Scheduling.

use std::future::Future;

use crate::error::Error;

use crate::io::shared_thread_state::SharedThreadState;

/// Async/await scheduler.
pub struct Scheduler<SM>
where
SM: ScheduleMethod,
Expand All @@ -24,6 +27,7 @@ where
}
}

/// Can schedule a task from a future factory and a shared state.
pub trait ScheduleMethod: 'static {
#[cfg(not(feature = "no-thread-safe-futures"))]
fn schedule<T>(
Expand Down
3 changes: 3 additions & 0 deletions maplibre/src/io/shared_thread_state.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Shared thread state.
Drabble marked this conversation as resolved.
Show resolved Hide resolved

use crate::coords::{WorldCoords, WorldTileCoords, Zoom};
use crate::error::Error;
use crate::io::geometry_index::{GeometryIndex, IndexProcessor, IndexedGeometry, TileIndex};
Expand All @@ -14,6 +16,7 @@ use geozero::GeozeroDatasource;
use prost::Message;
use std::sync::{mpsc, Arc, Mutex};

/// Stores and provides access to the thread safe data shared between the schedulers.
#[derive(Clone)]
pub struct SharedThreadState {
pub tile_request_state: Arc<Mutex<TileRequestState>>,
Expand Down
19 changes: 13 additions & 6 deletions maplibre/src/io/source_client.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
//! HTTP client.

use crate::coords::WorldTileCoords;
use crate::error::Error;
use crate::style::source::TileAddressingScheme;
use async_trait::async_trait;

/// A closure that returns a HTTP client.
pub type HTTPClientFactory<HC> = dyn Fn() -> HC;

// On the web platform futures are not thread-safe (i.e. not Send). This means we need to tell
// async_trait that these bounds should not be placed on the async trait:
// https://github.com/dtolnay/async-trait/blob/b70720c4c1cc0d810b7446efda44f81310ee7bf2/README.md#non-threadsafe-futures
//
// Users of this library can decide whether futures from the HTTPClient are thread-safe or not via
// the future "no-thread-safe-futures". Tokio futures are thread-safe.
/// On the web platform futures are not thread-safe (i.e. not Send). This means we need to tell
/// async_trait that these bounds should not be placed on the async trait:
/// [https://github.com/dtolnay/async-trait/blob/b70720c4c1cc0d810b7446efda44f81310ee7bf2/README.md#non-threadsafe-futures](https://github.com/dtolnay/async-trait/blob/b70720c4c1cc0d810b7446efda44f81310ee7bf2/README.md#non-threadsafe-futures)
///
/// Users of this library can decide whether futures from the HTTPClient are thread-safe or not via
/// the future "no-thread-safe-futures". Tokio futures are thread-safe.
#[cfg_attr(feature = "no-thread-safe-futures", async_trait(?Send))]
#[cfg_attr(not(feature = "no-thread-safe-futures"), async_trait)]
pub trait HTTPClient: Clone + Sync + Send + 'static {
async fn fetch(&self, url: &str) -> Result<Vec<u8>, Error>;
}

/// Gives access to the HTTP client which can be of multiple types,
/// see [crates::io::source_client::SourceClient]
#[derive(Clone)]
pub struct HttpSourceClient<HC>
where
Expand All @@ -25,6 +30,8 @@ where
inner_client: HC,
}

/// Defines the different types of HTTP clients such as basic HTTP and Mbtiles.
/// More types might be coming such as S3 and other cloud http clients.
#[derive(Clone)]
pub enum SourceClient<HC>
where
Expand Down
7 changes: 7 additions & 0 deletions maplibre/src/io/static_tile_fetcher.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Static tile fetcher

use std::concat;
use std::env;

Expand All @@ -13,6 +15,7 @@ static TILES: Dir = include_dir!("$OUT_DIR/extracted-tiles");
#[cfg(not(static_tiles))]
static TILES: Dir = Dir::new("/path", &[]);

/// Load PBF files which were statically embedded in the `build.rs`
#[derive(Default)]
pub struct StaticTileFetcher;

Expand All @@ -25,10 +28,14 @@ impl StaticTileFetcher {
Self {}
}

/// Fetch the tile static file asynchrounously and returns a vector of bytes or a network error if the file
/// could not be fetched.
pub async fn fetch_tile(&self, coords: &TileCoords) -> Result<Vec<u8>, Error> {
self.sync_fetch_tile(coords)
}

/// Fetch the tile static file and returns a vector of bytes or a network error if the file
/// could not be fetched.
pub fn sync_fetch_tile(&self, coords: &TileCoords) -> Result<Vec<u8>, Error> {
if TILES.entries().is_empty() {
log::error!(
Expand Down
Loading