# request_stage.rs - source
Source of the Rust file `maplibre/src/stages/request_stage.rs`.
Keywords: rust, rustlang, rust-lang

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165

    //! Requests tiles which are currently in view

    use crate::context::MapContext;
    use crate::coords::{ViewRegion, WorldTileCoords};
    use crate::error::Error;
    use crate::io::source_client::{HttpSourceClient, SourceClient};
    use crate::io::tile_repository::TileRepository;
    use crate::io::TileRequest;
    use crate::schedule::Stage;
    use crate::stages::SharedThreadState;
    use crate::{HttpClient, ScheduleMethod, Scheduler, Style};
    use std::collections::HashSet;

    pub struct RequestStage<SM, HC>
    where
        SM: ScheduleMethod,
        HC: HttpClient,
    {
        shared_thread_state: SharedThreadState,
        scheduler: Scheduler<SM>,
        http_source_client: HttpSourceClient<HC>,
        try_failed: bool,
    }

    impl<SM, HC> RequestStage<SM, HC>
    where
        SM: ScheduleMethod,
        HC: HttpClient,
    {
        pub fn new(
            shared_thread_state: SharedThreadState,
            http_source_client: HttpSourceClient<HC>,
            scheduler: Scheduler<SM>,
        ) -> Self {
            Self {
                shared_thread_state,
                scheduler,
                http_source_client,
                try_failed: false,
            }
        }
    }

    impl<SM, HC> Stage for RequestStage<SM, HC>
    where
        SM: ScheduleMethod,
        HC: HttpClient,
    {
        fn run(
            &mut self,
            MapContext {
                view_state,
                style,
                tile_repository,
                ..
            }: &mut MapContext,
        ) {
            let visible_level = view_state.visible_level();

            let view_proj = view_state.view_projection();

            let view_region = view_state
                .camera
                .view_region_bounding_box(&view_proj.invert())
                .map(|bounding_box| ViewRegion::new(bounding_box, 0, *view_state.zoom, visible_level));

            if view_state.camera.did_change(0.05) || view_state.zoom.did_change(0.05) || self.try_failed
            {
                if let Some(view_region) = &view_region {
                    // FIXME: We also need to request tiles from layers above if we are over the maximum zoom level
                    self.try_failed = self.request_tiles_in_view(tile_repository, style, view_region);
                }
            }

            view_state.camera.update_reference();
            view_state.zoom.update_reference();
        }
    }

    impl<SM, HC> RequestStage<SM, HC>
    where
        SM: ScheduleMethod,
        HC: HttpClient,
    {
        /// Request tiles which are currently in view.
        #[tracing::instrument(skip_all)]
        fn request_tiles_in_view(
            &self,
            tile_repository: &TileRepository,
            style: &Style,
            view_region: &ViewRegion,
        ) -> bool {
            let mut try_failed = false;
            let source_layers: HashSet<String> = style
                .layers
                .iter()
                .filter_map(|layer| layer.source_layer.clone())
                .collect();

            for coords in view_region.iter() {
                if coords.build_quad_key().is_some() {
                    // TODO: Make tesselation depend on style?
                    try_failed = self
                        .try_request_tile(tile_repository, &coords, &source_layers)
                        .unwrap();
                }
            }
            try_failed
        }

        fn try_request_tile(
            &self,
            tile_repository: &TileRepository,
            coords: &WorldTileCoords,
            layers: &HashSet<String>,
        ) -> Result<bool, Error> {
            if !tile_repository.is_layers_missing(coords, layers) {
                return Ok(false);
            }

            if let Ok(mut tile_request_state) = self.shared_thread_state.tile_request_state.try_lock() {
                if let Some(request_id) = tile_request_state.start_tile_request(TileRequest {
                    coords: *coords,
                    layers: layers.clone(),
                }) {
                    tracing::info!("new tile request: {}", &coords);

                    // The following snippet can be added instead of the next code block to demonstrate
                    // an understanable approach of fetching
                    /*#[cfg(target_arch = "wasm32")]
                    if let Some(tile_coords) = coords.into_tile(TileAddressingScheme::TMS) {
                        crate::platform::legacy_webworker_fetcher::request_tile(
                            request_id,
                            tile_coords,
                        );
                    }*/

                    let client = SourceClient::Http(self.http_source_client.clone());
                    let coords = *coords;

                    let state = self.shared_thread_state.clone();
                    self.scheduler
                        .schedule_method()
                        .schedule(Box::new(move || {
                            Box::pin(async move {
                                match client.fetch(&coords).await {
                                    Ok(data) => state
                                        .process_tile(request_id, data.into_boxed_slice())
                                        .unwrap(),
                                    Err(e) => {
                                        log::error!("{:?}", &e);
                                        state.tile_unavailable(&coords, request_id).unwrap()
                                    }
                                }
                            })
                        }))
                        .unwrap();
                }

                Ok(false)
            } else {
                Ok(true)
            }
        }
    }