summaryrefslogtreecommitdiff
path: root/src/mbgl/map/map_context.cpp
blob: bd288a5cdacba4421d469451d83cd09016f18c69 (plain)
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#include <mbgl/map/map_context.hpp>
#include <mbgl/map/map_data.hpp>
#include <mbgl/map/view.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/map/annotation.hpp>

#include <mbgl/platform/log.hpp>

#include <mbgl/renderer/painter.hpp>

#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>

#include <mbgl/style/style.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/style/style_layer.hpp>

#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/worker.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/util/exception.hpp>

#include <algorithm>

namespace mbgl {

MapContext::MapContext(uv_loop_t* loop, View& view_, FileSource& fileSource, MapData& data_)
    : view(view_),
      data(data_),
      env(fileSource),
      envScope(env, ThreadType::Map, "Map"),
      updated(static_cast<UpdateType>(Update::Nothing)),
      asyncUpdate(std::make_unique<uv::async>(loop, [this] { update(); })),
      texturePool(std::make_unique<TexturePool>()) {
    assert(Environment::currentlyOn(ThreadType::Map));

    asyncUpdate->unref();

    view.activate();
}

MapContext::~MapContext() {
    // Make sure we call cleanup() before deleting this object.
    assert(!style);
}

void MapContext::cleanup() {
    view.notify();

    // Explicit resets currently necessary because these abandon resources that need to be
    // cleaned up by env.performCleanup();
    style.reset();
    painter.reset();
    texturePool.reset();

    env.performCleanup();

    view.deactivate();
}

void MapContext::pause() {
    MBGL_CHECK_ERROR(glFinish());

    view.deactivate();

    std::unique_lock<std::mutex> lockPause(data.mutexPause);
    data.condPaused.notify_all();
    data.condResume.wait(lockPause);

    view.activate();
}

void MapContext::resize(uint16_t width, uint16_t height, float ratio) {
    view.resize(width, height, ratio);
    triggerUpdate();
}

void MapContext::triggerUpdate(const Update u) {
    updated |= static_cast<UpdateType>(u);
    asyncUpdate->send();
}

void MapContext::setStyleURL(const std::string& url) {
    styleURL = url;
    styleJSON.clear();

    const size_t pos = styleURL.rfind('/');
    std::string base = "";
    if (pos != std::string::npos) {
        base = styleURL.substr(0, pos + 1);
    }

    env.request({ Resource::Kind::Style, styleURL }, [this, base](const Response &res) {
        if (res.status == Response::Successful) {
            loadStyleJSON(res.data, base);
        } else {
            Log::Error(Event::Setup, "loading style failed: %s", res.message.c_str());
        }
    });
}

void MapContext::setStyleJSON(const std::string& json, const std::string& base) {
    styleURL.clear();
    styleJSON = json;

    loadStyleJSON(json, base);
}

void MapContext::loadStyleJSON(const std::string& json, const std::string& base) {
    assert(Environment::currentlyOn(ThreadType::Map));

    style.reset();
    style = std::make_unique<Style>(json, base, asyncUpdate->get()->loop, env);
    style->cascade(data.getClasses());
    style->setDefaultTransitionDuration(data.getDefaultTransitionDuration());
    style->setObserver(this);

    triggerUpdate(Update::Zoom);

    auto staleTiles = data.annotationManager.resetStaleTiles();
    if (staleTiles.size()) {
        updateAnnotationTiles(staleTiles);
    }
}

void MapContext::updateTiles() {
    assert(Environment::currentlyOn(ThreadType::Map));

    style->update(data, transformState, *texturePool);
}

void MapContext::updateAnnotationTiles(const std::unordered_set<TileID, TileID::Hash>& ids) {
    assert(Environment::currentlyOn(ThreadType::Map));

    data.annotationManager.markStaleTiles(ids);

    if (!style) return;

    // grab existing, single shape annotations source
    const auto& shapeID = AnnotationManager::ShapeLayerID;

    const auto source_it = std::find_if(style->sources.begin(), style->sources.end(),
        [&shapeID](util::ptr<Source> source) {
        return (source->info.source_id == shapeID);
    });
    assert(source_it != style->sources.end());
    source_it->get()->enabled = true;

    // create (if necessary) layers and buckets for each shape
    for (const auto &shapeAnnotationID : data.annotationManager.getOrderedShapeAnnotations()) {
        const std::string shapeLayerID = shapeID + "." + std::to_string(shapeAnnotationID);

        const auto layer_it = std::find_if(style->layers.begin(), style->layers.end(),
            [&shapeLayerID](util::ptr<StyleLayer> layer) {
            return (layer->id == shapeLayerID);
        });

        if (layer_it == style->layers.end()) {
            // query shape styling
            auto& shapeStyle = data.annotationManager.getAnnotationStyleProperties(shapeAnnotationID);

            // apply shape paint properties
            ClassProperties paintProperties;

            if (shapeStyle.is<LineProperties>()) {
                // opacity
                PropertyValue lineOpacity = ConstantFunction<float>(shapeStyle.get<LineProperties>().opacity);
                paintProperties.set(PropertyKey::LineOpacity, lineOpacity);

                // line width
                PropertyValue lineWidth = ConstantFunction<float>(shapeStyle.get<LineProperties>().width);
                paintProperties.set(PropertyKey::LineWidth, lineWidth);

                // stroke color
                PropertyValue strokeColor = ConstantFunction<Color>(shapeStyle.get<LineProperties>().color);
                paintProperties.set(PropertyKey::LineColor, strokeColor);
            } else if (shapeStyle.is<FillProperties>()) {
                // opacity
                PropertyValue fillOpacity = ConstantFunction<float>(shapeStyle.get<FillProperties>().opacity);
                paintProperties.set(PropertyKey::FillOpacity, fillOpacity);

                // fill color
                PropertyValue fillColor = ConstantFunction<Color>(shapeStyle.get<FillProperties>().fill_color);
                paintProperties.set(PropertyKey::FillColor, fillColor);

                // stroke color
                PropertyValue strokeColor = ConstantFunction<Color>(shapeStyle.get<FillProperties>().stroke_color);
                paintProperties.set(PropertyKey::FillOutlineColor, strokeColor);
            }

            std::map<ClassID, ClassProperties> shapePaints;
            shapePaints.emplace(ClassID::Default, std::move(paintProperties));

            // create shape layer
            util::ptr<StyleLayer> shapeLayer = std::make_shared<StyleLayer>(shapeLayerID, std::move(shapePaints));
            shapeLayer->type = (shapeStyle.is<LineProperties>() ? StyleLayerType::Line : StyleLayerType::Fill);

            // add to end of other shape layers just before (last) point layer
            style->layers.emplace((style->layers.end() - 2), shapeLayer);

            // create shape bucket & connect to source
            util::ptr<StyleBucket> shapeBucket = std::make_shared<StyleBucket>(shapeLayer->type);
            shapeBucket->name = shapeLayer->id;
            shapeBucket->source_layer = shapeLayer->id;
            shapeBucket->source = *source_it;

            // apply line layout properties to bucket
            if (shapeStyle.is<LineProperties>()) {
                shapeBucket->layout.set(PropertyKey::LineJoin, ConstantFunction<JoinType>(JoinType::Round));
            }

            // connect layer to bucket
            shapeLayer->bucket = shapeBucket;
        }
    }

    // invalidate annotations layer tiles
    for (const auto &source : style->sources) {
        if (source->info.type == SourceType::Annotations) {
            source->invalidateTiles(ids);
        }
    }

    cascadeClasses();

    triggerUpdate(Update::Classes);

    data.annotationManager.resetStaleTiles();
}

void MapContext::cascadeClasses() {
    style->cascade(data.getClasses());
}

void MapContext::recalculateStyle(TimePoint now) {
    style->recalculate(transformState.getNormalizedZoom(), now);
}

void MapContext::update() {
    assert(Environment::currentlyOn(ThreadType::Map));

    const auto now = Clock::now();
    data.setAnimationTime(now);

    updated |= data.transform.updateTransitions(now);
    transformState = data.transform.currentState();

    if (style) {
        if (updated & static_cast<UpdateType>(Update::DefaultTransitionDuration)) {
            style->setDefaultTransitionDuration(data.getDefaultTransitionDuration());
        }

        if (updated & static_cast<UpdateType>(Update::Classes)) {
            cascadeClasses();
        }

        if (updated & static_cast<UpdateType>(Update::Classes) ||
            updated & static_cast<UpdateType>(Update::Zoom)) {
            recalculateStyle(now);
        }

        updateTiles();

        if (style->isLoaded()) {
            if (!data.getFullyLoaded()) {
                data.setFullyLoaded(true);
            }
        } else {
            if (data.getFullyLoaded()) {
                data.setFullyLoaded(false);
            }
        }

        view.invalidate([this] { render(); });
    }

    updated = static_cast<UpdateType>(Update::Nothing);
}

void MapContext::renderStill(StillImageCallback fn) {
    if (data.mode != MapMode::Still) {
        throw util::Exception("Map is not in still image render mode");
    }

    if (callback) {
        throw util::Exception("Map is currently rendering an image");
    }

    if (style->getLastError()) {
        fn(style->getLastError(), nullptr);
        return;
    }

    callback = fn;
    triggerUpdate(Update::RenderStill);
}

void MapContext::render() {
    assert(Environment::currentlyOn(ThreadType::Map));

    // Cleanup OpenGL objects that we abandoned since the last render call.
    env.performCleanup();

    if (data.mode == MapMode::Still && (!callback || !data.getFullyLoaded())) {
        // We are either not waiting for a map to be rendered, or we don't have all resources yet.
        return;
    }

    assert(style);

    if (!painter) {
        painter = std::make_unique<Painter>();
        painter->setup();
    }

    painter->setDebug(data.getDebug());
    painter->render(*style, transformState, data.getAnimationTime());

    if (data.mode == MapMode::Still) {
        callback(nullptr, view.readStillImage());
        callback = nullptr;
    }

    // Schedule another rerender when we definitely need a next frame.
    if (data.transform.needsTransition() || style->hasTransitions()) {
        triggerUpdate();
    }
}

double MapContext::getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol) {
    assert(Environment::currentlyOn(ThreadType::Map));
    const SpritePosition pos = style->sprite->getSpritePosition(symbol);
    return -pos.height / pos.pixelRatio / 2;
}

void MapContext::setSourceTileCacheSize(size_t size) {
    assert(Environment::currentlyOn(ThreadType::Map));
    if (size != sourceCacheSize) {
        sourceCacheSize = size;
        if (!style) return;
        for (const auto &source : style->sources) {
            source->setCacheSize(sourceCacheSize);
        }
        view.invalidate([this] { render(); });
    }
}

void MapContext::onLowMemory() {
    assert(Environment::currentlyOn(ThreadType::Map));
    if (!style) return;
    for (const auto &source : style->sources) {
        source->onLowMemory();
    }
    view.invalidate([this] { render(); });
}

void MapContext::onTileDataChanged() {
    assert(Environment::currentlyOn(ThreadType::Map));
    triggerUpdate();
}

void MapContext::onResourceLoadingFailed(std::exception_ptr error) {
    assert(Environment::currentlyOn(ThreadType::Map));

    if (data.mode == MapMode::Still && callback) {
        callback(error, nullptr);
        callback = nullptr;
    }
}

}