summaryrefslogtreecommitdiff
path: root/src/mbgl/style/style.cpp
blob: 8dfe7eac067d56ad6d1f6446b85de5e035ff216e (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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#include <mbgl/style/style.hpp>
#include <mbgl/style/observer.hpp>
#include <mbgl/style/source_impl.hpp>
#include <mbgl/style/layers/symbol_layer.hpp>
#include <mbgl/style/layers/symbol_layer_impl.hpp>
#include <mbgl/style/layers/custom_layer.hpp>
#include <mbgl/style/layers/custom_layer_impl.hpp>
#include <mbgl/style/layers/background_layer.hpp>
#include <mbgl/style/layers/background_layer_impl.hpp>
#include <mbgl/style/layers/fill_layer.hpp>
#include <mbgl/style/layers/fill_extrusion_layer.hpp>
#include <mbgl/style/layers/line_layer.hpp>
#include <mbgl/style/layers/circle_layer.hpp>
#include <mbgl/style/layers/raster_layer.hpp>
#include <mbgl/style/layer_impl.hpp>
#include <mbgl/style/parser.hpp>
#include <mbgl/style/transition_options.hpp>
#include <mbgl/style/class_dictionary.hpp>
#include <mbgl/style/update_parameters.hpp>
#include <mbgl/style/cascade_parameters.hpp>
#include <mbgl/style/property_evaluation_parameters.hpp>
#include <mbgl/sprite/sprite_atlas.hpp>
#include <mbgl/text/glyph_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/renderer/render_item.hpp>
#include <mbgl/renderer/render_tile.hpp>
#include <mbgl/renderer/render_background_layer.hpp>
#include <mbgl/renderer/render_circle_layer.hpp>
#include <mbgl/renderer/render_custom_layer.hpp>
#include <mbgl/renderer/render_fill_extrusion_layer.hpp>
#include <mbgl/renderer/render_fill_layer.hpp>
#include <mbgl/renderer/render_line_layer.hpp>
#include <mbgl/renderer/render_raster_layer.hpp>
#include <mbgl/renderer/render_symbol_layer.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/exception.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/math/minmax.hpp>
#include <mbgl/map/query.hpp>

#include <algorithm>

namespace mbgl {
namespace style {

static Observer nullObserver;

Style::Style(Scheduler& scheduler_, FileSource& fileSource_, float pixelRatio)
    : scheduler(scheduler_),
      fileSource(fileSource_),
      glyphAtlas(std::make_unique<GlyphAtlas>(Size{ 2048, 2048 }, fileSource)),
      spriteAtlas(std::make_unique<SpriteAtlas>(Size{ 1024, 1024 }, pixelRatio)),
      lineAtlas(std::make_unique<LineAtlas>(Size{ 256, 512 })),
      light(std::make_unique<Light>()),
      observer(&nullObserver) {
    glyphAtlas->setObserver(this);
    spriteAtlas->setObserver(this);
}

Style::~Style() {
    for (const auto& source : sources) {
        source->baseImpl->setObserver(nullptr);
    }

    for (const auto& layer : layers) {
        if (CustomLayer* customLayer = layer->as<CustomLayer>()) {
            customLayer->impl->deinitialize();
        }
    }

    glyphAtlas->setObserver(nullptr);
    spriteAtlas->setObserver(nullptr);
}

bool Style::addClass(const std::string& className) {
    if (hasClass(className)) return false;
    classes.push_back(className);
    return true;
}

bool Style::hasClass(const std::string& className) const {
    return std::find(classes.begin(), classes.end(), className) != classes.end();
}

bool Style::removeClass(const std::string& className) {
    const auto it = std::find(classes.begin(), classes.end(), className);
    if (it != classes.end()) {
        classes.erase(it);
        return true;
    }
    return false;
}

void Style::setClasses(const std::vector<std::string>& classNames) {
    classes = classNames;
}

std::vector<std::string> Style::getClasses() const {
    return classes;
}

void Style::setTransitionOptions(const TransitionOptions& options) {
    transitionOptions = options;
}

TransitionOptions Style::getTransitionOptions() const {
    return transitionOptions;
}

void Style::setJSON(const std::string& json) {
    sources.clear();
    layers.clear();
    renderLayers.clear();
    classes.clear();
    transitionOptions = {};
    updateBatch = {};

    Parser parser;
    auto error = parser.parse(json);

    if (error) {
        std::string message = "Failed to parse style: " + util::toString(error);
        Log::Error(Event::ParseStyle, message.c_str());
        observer->onStyleError(std::make_exception_ptr(util::StyleParseException(message)));
        observer->onResourceError(error);
        return;
    }

    for (auto& source : parser.sources) {
        addSource(std::move(source));
    }

    for (auto& layer : parser.layers) {
        addLayer(std::move(layer));
    }

    name = parser.name;
    defaultLatLng = parser.latLng;
    defaultZoom = parser.zoom;
    defaultBearing = parser.bearing;
    defaultPitch = parser.pitch;
    light = std::make_unique<Light>(parser.light);

    glyphAtlas->setURL(parser.glyphURL);
    spriteAtlas->load(parser.spriteURL, scheduler, fileSource);

    loaded = true;

    observer->onStyleLoaded();
}

void Style::addSource(std::unique_ptr<Source> source) {
    // Guard against duplicate source ids
    auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& existing) {
        return existing->getID() == source->getID();
    });

    if (it != sources.end()) {
        std::string msg = "Source " + source->getID() + " already exists";
        throw std::runtime_error(msg.c_str());
    }

    source->baseImpl->setObserver(this);
    sources.emplace_back(std::move(source));
}

std::unique_ptr<Source> Style::removeSource(const std::string& id) {
    auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) {
        return source->getID() == id;
    });

    if (it == sources.end()) {
        return nullptr;
    }

    auto source = std::move(*it);
    sources.erase(it);
    updateBatch.sourceIDs.erase(id);

    source->baseImpl->detach();
    return source;
}

std::vector<const Layer*> Style::getLayers() const {
    std::vector<const Layer*> result;
    result.reserve(layers.size());
    for (const auto& layer : layers) {
        result.push_back(layer.get());
    }
    return result;
}

std::vector<Layer*> Style::getLayers() {
    std::vector<Layer*> result;
    result.reserve(layers.size());
    for (auto& layer : layers) {
        result.push_back(layer.get());
    }
    return result;
}

std::vector<std::unique_ptr<Layer>>::const_iterator Style::findLayer(const std::string& id) const {
    return std::find_if(layers.begin(), layers.end(), [&](const auto& layer) {
        return layer->baseImpl->id == id;
    });
}

Layer* Style::getLayer(const std::string& id) const {
    auto it = findLayer(id);
    return it != layers.end() ? it->get() : nullptr;
}

Layer* Style::addLayer(std::unique_ptr<Layer> layer, optional<std::string> before) {
    // TODO: verify source

    // Guard against duplicate layer ids
    auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& existing) {
        return existing->getID() == layer->getID();
    });

    if (it != layers.end()) {
        throw std::runtime_error(std::string{"Layer "} + layer->getID() + " already exists");
    }

    if (CustomLayer* customLayer = layer->as<CustomLayer>()) {
        customLayer->impl->initialize();
    }

    layer->baseImpl->setObserver(this);

    auto added = layers.emplace(before ? findLayer(*before) : layers.end(), std::move(layer))->get();
    renderLayers.emplace(before ? findRenderLayer(*before) : renderLayers.end(), added->baseImpl->createRenderLayer());
    return std::move(added);
}

std::unique_ptr<Layer> Style::removeLayer(const std::string& id) {
    auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& layer) {
        return layer->baseImpl->id == id;
    });

    if (it == layers.end())
        return nullptr;

    auto layer = std::move(*it);

    if (CustomLayer* customLayer = layer->as<CustomLayer>()) {
        customLayer->impl->deinitialize();
    }

    layers.erase(it);
    removeRenderLayer(id);
    return layer;
}

std::vector<const RenderLayer*> Style::getRenderLayers() const {
    std::vector<const RenderLayer*> result;
    result.reserve(renderLayers.size());
    for (const auto& layer : renderLayers) {
        result.push_back(layer.get());
    }
    return result;
}

std::vector<RenderLayer*> Style::getRenderLayers() {
    std::vector<RenderLayer*> result;
    result.reserve(renderLayers.size());
    for (auto& layer : renderLayers) {
        result.push_back(layer.get());
    }
    return result;
}

std::vector<std::unique_ptr<RenderLayer>>::const_iterator Style::findRenderLayer(const std::string& id) const {
    return std::find_if(renderLayers.begin(), renderLayers.end(), [&](const auto& layer) {
        return layer->baseImpl.id == id;
    });
}

RenderLayer* Style::getRenderLayer(const std::string& id) const {
    auto it = findRenderLayer(id);
    return it != renderLayers.end() ? it->get() : nullptr;
}

void Style::removeRenderLayer(const std::string& id) {
    auto it = std::find_if(renderLayers.begin(), renderLayers.end(), [&](const auto& layer) {
        return layer->baseImpl.id == id;
    });

    if (it != renderLayers.end()) {
        renderLayers.erase(it);
    }
}

std::string Style::getName() const {
    return name;
}

LatLng Style::getDefaultLatLng() const {
    return defaultLatLng;
}

double Style::getDefaultZoom() const {
    return defaultZoom;
}

double Style::getDefaultBearing() const {
    return defaultBearing;
}

double Style::getDefaultPitch() const {
    return defaultPitch;
}

void Style::updateTiles(const UpdateParameters& parameters) {
    for (const auto& source : sources) {
        if (source->baseImpl->enabled) {
            source->baseImpl->updateTiles(parameters);
        }
    }
}

void Style::relayout() {
    for (const auto& sourceID : updateBatch.sourceIDs) {
        Source* source = getSource(sourceID);
        if (source && source->baseImpl->enabled) {
            source->baseImpl->reloadTiles();
        } else if (source) {
            source->baseImpl->invalidateTiles();
        }
    }
    updateBatch.sourceIDs.clear();
}

void Style::cascade(const TimePoint& timePoint, MapMode mode) {
    // When in continuous mode, we can either have user- or style-defined
    // transitions. Still mode is always immediate.
    static const TransitionOptions immediateTransition {};

    std::vector<ClassID> classIDs;
    for (const auto& className : classes) {
        classIDs.push_back(ClassDictionary::Get().lookup(className));
    }
    classIDs.push_back(ClassID::Default);

    const CascadeParameters parameters {
        classIDs,
        mode == MapMode::Continuous ? timePoint : Clock::time_point::max(),
        mode == MapMode::Continuous ? transitionOptions : immediateTransition
    };

    for (const auto& layer : renderLayers) {
        layer->cascade(parameters);
    }

    transitioningLight = TransitioningLight(*light, std::move(transitioningLight), parameters);
}

void Style::recalculate(float z, const TimePoint& timePoint, MapMode mode) {
    // Disable all sources first. If we find an enabled layer that uses this source, we will
    // re-enable it later.
    for (const auto& source : sources) {
        source->baseImpl->enabled = false;
    }

    zoomHistory.update(z, timePoint);

    const PropertyEvaluationParameters parameters {
        z,
        mode == MapMode::Continuous ? timePoint : Clock::time_point::max(),
        zoomHistory,
        mode == MapMode::Continuous ? util::DEFAULT_FADE_DURATION : Duration::zero()
    };

    hasPendingTransitions = transitioningLight.hasTransition();
    for (const auto& layer : renderLayers) {
        hasPendingTransitions |= layer->evaluate(parameters);

        // Disable this layer if it doesn't need to be rendered.
        const bool needsRendering = layer->needsRendering(zoomHistory.lastZoom);
        if (!needsRendering) {
            continue;
        }

        // If this layer has a source, make sure that it gets loaded.
        if (Source* source = getSource(layer->baseImpl.source)) {
            source->baseImpl->enabled = true;
            if (!source->baseImpl->loaded) {
                source->baseImpl->loadDescription(fileSource);
            }
        }
    }

    evaluatedLight = EvaluatedLight(transitioningLight, parameters);

    // Remove the existing tiles if we didn't end up re-enabling the source.
    for (const auto& source : sources) {
        if (!source->baseImpl->enabled) {
            source->baseImpl->removeTiles();
        }
    }
}

std::vector<const Source*> Style::getSources() const {
    std::vector<const Source*> result;
    result.reserve(sources.size());
    for (const auto& source : sources) {
        result.push_back(source.get());
    }
    return result;
}

std::vector<Source*> Style::getSources() {
    std::vector<Source*> result;
    result.reserve(sources.size());
    for (auto& source : sources) {
        result.push_back(source.get());
    }
    return result;
}

Source* Style::getSource(const std::string& id) const {
    const auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) {
        return source->getID() == id;
    });

    return it != sources.end() ? it->get() : nullptr;
}

bool Style::hasTransitions() const {
    return hasPendingTransitions;
}

bool Style::isLoaded() const {
    if (!loaded) {
        return false;
    }

    for (const auto& source: sources) {
        if (source->baseImpl->enabled && !source->baseImpl->isLoaded()) {
            return false;
        }
    }

    if (!spriteAtlas->isLoaded()) {
        return false;
    }

    return true;
}

RenderData Style::getRenderData(MapDebugOptions debugOptions, float angle) const {
    RenderData result;

    for (const auto& source : sources) {
        if (source->baseImpl->enabled) {
            result.sources.insert(source.get());
        }
    }

    for (const auto& layer : renderLayers) {
        if (!layer->needsRendering(zoomHistory.lastZoom)) {
            continue;
        }

        if (const RenderBackgroundLayer* background = layer->as<RenderBackgroundLayer>()) {
            if (debugOptions & MapDebugOptions::Overdraw) {
                // We want to skip glClear optimization in overdraw mode.
                result.order.emplace_back(*layer);
                continue;
            }
            const BackgroundPaintProperties::Evaluated& paint = background->evaluated;
            if (layer.get() == renderLayers[0].get() && paint.get<BackgroundPattern>().from.empty()) {
                // This is a solid background. We can use glClear().
                result.backgroundColor = paint.get<BackgroundColor>() * paint.get<BackgroundOpacity>();
            } else {
                // This is a textured background, or not the bottommost layer. We need to render it with a quad.
                result.order.emplace_back(*layer);
            }
            continue;
        }

        if (layer->is<RenderCustomLayer>()) {
            result.order.emplace_back(*layer);
            continue;
        }

        Source* source = getSource(layer->baseImpl.source);
        if (!source) {
            Log::Warning(Event::Render, "can't find source for layer '%s'", layer->baseImpl.id.c_str());
            continue;
        }

        auto& renderTiles = source->baseImpl->getRenderTiles();
        const bool symbolLayer = layer->is<RenderSymbolLayer>();

        // Sort symbol tiles in opposite y position, so tiles with overlapping
        // symbols are drawn on top of each other, with lower symbols being
        // drawn on top of higher symbols.
        std::vector<std::reference_wrapper<RenderTile>> sortedTiles;
        std::transform(renderTiles.begin(), renderTiles.end(), std::back_inserter(sortedTiles),
                [](auto& pair) { return std::ref(pair.second); });
        if (symbolLayer) {
            std::sort(sortedTiles.begin(), sortedTiles.end(),
                      [angle](const RenderTile& a, const RenderTile& b) {
                Point<float> pa(a.id.canonical.x, a.id.canonical.y);
                Point<float> pb(b.id.canonical.x, b.id.canonical.y);

                auto par = util::rotate(pa, angle);
                auto pbr = util::rotate(pb, angle);

                return std::tie(par.y, par.x) < std::tie(pbr.y, pbr.x);
            });
        }

        std::vector<std::reference_wrapper<RenderTile>> sortedTilesForInsertion;
        for (auto tileIt = sortedTiles.begin(); tileIt != sortedTiles.end(); ++tileIt) {
            auto& tile = tileIt->get();
            if (!tile.tile.isRenderable()) {
                continue;
            }

            // We're not clipping symbol layers, so when we have both parents and children of symbol
            // layers, we drop all children in favor of their parent to avoid duplicate labels.
            // See https://github.com/mapbox/mapbox-gl-native/issues/2482
            if (symbolLayer) {
                bool skip = false;
                // Look back through the buckets we decided to render to find out whether there is
                // already a bucket from this layer that is a parent of this tile. Tiles are ordered
                // by zoom level when we obtain them from getTiles().
                for (auto it = sortedTilesForInsertion.rbegin();
                     it != sortedTilesForInsertion.rend(); ++it) {
                    if (tile.tile.id.isChildOf(it->get().tile.id)) {
                        skip = true;
                        break;
                    }
                }
                if (skip) {
                    continue;
                }
            }

            auto bucket = tile.tile.getBucket(*layer);
            if (bucket) {
                sortedTilesForInsertion.emplace_back(tile);
                tile.used = true;
            }
        }

        result.order.emplace_back(*layer, std::move(sortedTilesForInsertion));
    }

    return result;
}

std::vector<Feature> Style::queryRenderedFeatures(const ScreenLineString& geometry,
                                                  const TransformState& transformState,
                                                  const RenderedQueryOptions& options) const {
    std::unordered_set<std::string> sourceFilter;

    if (options.layerIDs) {
        for (const auto& layerID : *options.layerIDs) {
            auto layer = getLayer(layerID);
            if (layer) sourceFilter.emplace(layer->baseImpl->source);
        }
    }

    std::vector<Feature> result;
    std::unordered_map<std::string, std::vector<Feature>> resultsByLayer;

    for (const auto& source : sources) {
        if (!sourceFilter.empty() && sourceFilter.find(source->getID()) == sourceFilter.end()) {
            continue;
        }

        auto sourceResults = source->baseImpl->queryRenderedFeatures(geometry, transformState, options);
        std::move(sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin()));
    }

    if (resultsByLayer.empty()) {
        return result;
    }

    // Combine all results based on the style layer order.
    for (const auto& layer : renderLayers) {
        if (!layer->needsRendering(zoomHistory.lastZoom)) {
            continue;
        }
        auto it = resultsByLayer.find(layer->baseImpl.id);
        if (it != resultsByLayer.end()) {
            std::move(it->second.begin(), it->second.end(), std::back_inserter(result));
        }
    }

    return result;
}

void Style::setSourceTileCacheSize(size_t size) {
    for (const auto& source : sources) {
        source->baseImpl->setCacheSize(size);
    }
}

void Style::onLowMemory() {
    for (const auto& source : sources) {
        source->baseImpl->onLowMemory();
    }
}

void Style::setObserver(style::Observer* observer_) {
    observer = observer_;
}

void Style::onGlyphsLoaded(const FontStack& fontStack, const GlyphRange& glyphRange) {
    observer->onGlyphsLoaded(fontStack, glyphRange);
}

void Style::onGlyphsError(const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load glyph range %d-%d for font stack %s: %s",
               glyphRange.first, glyphRange.second, fontStackToString(fontStack).c_str(), util::toString(error).c_str());
    observer->onGlyphsError(fontStack, glyphRange, error);
    observer->onResourceError(error);
}

void Style::onSourceLoaded(Source& source) {
    observer->onSourceLoaded(source);
    observer->onUpdate(Update::Repaint);
}

void Style::onSourceChanged(Source& source) {
    observer->onSourceChanged(source);
}

void Style::onSourceError(Source& source, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load source %s: %s",
               source.getID().c_str(), util::toString(error).c_str());
    observer->onSourceError(source, error);
    observer->onResourceError(error);
}

void Style::onSourceDescriptionChanged(Source& source) {
    observer->onSourceDescriptionChanged(source);
    if (!source.baseImpl->loaded) {
        source.baseImpl->loadDescription(fileSource);
    }
}

void Style::onTileChanged(Source& source, const OverscaledTileID& tileID) {
    observer->onTileChanged(source, tileID);
    observer->onUpdate(Update::Repaint);
}

void Style::onTileError(Source& source, const OverscaledTileID& tileID, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load tile %s for source %s: %s",
               util::toString(tileID).c_str(), source.getID().c_str(), util::toString(error).c_str());
    observer->onTileError(source, tileID, error);
    observer->onResourceError(error);
}

void Style::onSpriteLoaded() {
    observer->onSpriteLoaded();
    observer->onUpdate(Update::Repaint); // For *-pattern properties.
}

void Style::onSpriteError(std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load sprite: %s", util::toString(error).c_str());
    observer->onSpriteError(error);
    observer->onResourceError(error);
}

struct QueueSourceReloadVisitor {
    UpdateBatch& updateBatch;

    // No need to reload sources for these types; their visibility can change but
    // they don't participate in layout.
    void operator()(CustomLayer&) {}
    void operator()(RasterLayer&) {}
    void operator()(BackgroundLayer&) {}

    template <class VectorLayer>
    void operator()(VectorLayer& layer) {
        updateBatch.sourceIDs.insert(layer.getSourceID());
    }
};

void Style::onLayerFilterChanged(Layer& layer) {
    layer.accept(QueueSourceReloadVisitor { updateBatch });
    observer->onUpdate(Update::Layout);
}

void Style::onLayerVisibilityChanged(Layer& layer) {
    layer.accept(QueueSourceReloadVisitor { updateBatch });
    observer->onUpdate(Update::RecalculateStyle | Update::Layout);
}

void Style::onLayerPaintPropertyChanged(Layer&) {
    observer->onUpdate(Update::RecalculateStyle | Update::Classes);
}

void Style::onLayerDataDrivenPaintPropertyChanged(Layer& layer) {
    layer.accept(QueueSourceReloadVisitor { updateBatch });
    observer->onUpdate(Update::RecalculateStyle | Update::Classes | Update::Layout);
}

void Style::onLayerLayoutPropertyChanged(Layer& layer, const char * property) {
    layer.accept(QueueSourceReloadVisitor { updateBatch });

    auto update = Update::Layout;

    // Recalculate the style for certain properties
    bool needsRecalculation = strcmp(property, "icon-size") == 0 || strcmp(property, "text-size") == 0;
    if (needsRecalculation) {
        update |= Update::RecalculateStyle;
    }
    observer->onUpdate(update);
}

void Style::dumpDebugLogs() const {
    for (const auto& source : sources) {
        source->baseImpl->dumpDebugLogs();
    }

    spriteAtlas->dumpDebugLogs();
}

} // namespace style
} // namespace mbgl