-
-
Notifications
You must be signed in to change notification settings - Fork 599
Expand file tree
/
Copy pathgeometry_tile.cpp
More file actions
618 lines (512 loc) · 21.7 KB
/
Copy pathgeometry_tile.cpp
File metadata and controls
618 lines (512 loc) · 21.7 KB
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
#include <mbgl/tile/geometry_tile.hpp>
#include <mbgl/actor/scheduler.hpp>
#include <mbgl/geometry/feature_index.hpp>
#include <mbgl/style/layers/custom_layer.hpp>
#include <mbgl/renderer/layers/render_custom_layer.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/renderer/buckets/symbol_bucket.hpp>
#include <mbgl/renderer/layers/render_background_layer.hpp>
#include <mbgl/renderer/layers/render_symbol_layer.hpp>
#include <mbgl/renderer/query.hpp>
#include <mbgl/renderer/render_source.hpp>
#include <mbgl/renderer/tile_parameters.hpp>
#include <mbgl/renderer/tile_render_data.hpp>
#include <mbgl/style/layer_impl.hpp>
#include <mbgl/style/layers/background_layer.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/tile/geometry_tile_worker.hpp>
#include <mbgl/tile/tile_observer.hpp>
#include <mbgl/util/instrumentation.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/util/thread_pool.hpp>
#include <mbgl/gfx/upload_pass.hpp>
#include <utility>
namespace mbgl {
LayerRenderData* GeometryTile::LayoutResult::getLayerRenderData(const style::Layer::Impl& layerImpl) {
MLN_TRACE_FUNC();
MLN_ZONE_STR(layerImpl.id);
auto it = layerRenderData.find(layerImpl.id);
if (it == layerRenderData.end()) {
return nullptr;
}
LayerRenderData& result = it->second;
if (result.layerProperties->baseImpl->getTypeInfo() != layerImpl.getTypeInfo()) {
// Layer data might be outdated, see issue #12432.
return nullptr;
}
return &result;
}
class ImagePatch {
public:
ImagePatch(Immutable<style::Image::Impl> image_, const Rect<uint16_t>& paddedRect_)
: image(std::move(image_)),
paddedRect(paddedRect_) {}
Immutable<style::Image::Impl> image;
Rect<uint16_t> paddedRect;
};
void populateImagePatches(ImagePositions& imagePositions,
const ImageManager& imageManager,
std::vector<ImagePatch>& /*out*/ patches) {
if (imagePositions.empty()) {
imagePositions.reserve(imageManager.updatedImageVersions.size());
}
for (auto& updatedImageVersion : imageManager.updatedImageVersions) {
const std::string& name = updatedImageVersion.first;
const uint32_t version = updatedImageVersion.second;
const auto it = imagePositions.find(updatedImageVersion.first);
if (it != imagePositions.end()) {
auto& position = it->second;
if (position.version == version) continue;
const auto updatedImage = imageManager.getSharedImage(name);
if (updatedImage == nullptr) continue;
patches.emplace_back(*updatedImage, position.paddedRect);
position.version = version;
}
}
}
class GeometryTileRenderData final : public TileRenderData {
public:
GeometryTileRenderData(std::shared_ptr<GeometryTile::LayoutResult> layoutResult_,
std::shared_ptr<TileAtlasTextures> atlasTextures_)
: TileRenderData(std::move(atlasTextures_)),
layoutResult(std::move(layoutResult_)) {}
private:
// TileRenderData overrides.
std::optional<ImagePosition> getPattern(const std::string&) const override;
const LayerRenderData* getLayerRenderData(const style::Layer::Impl&) const override;
Bucket* getBucket(const style::Layer::Impl&) const override;
void upload(gfx::UploadPass&) override;
void prepare(const SourcePrepareParameters&) override;
std::shared_ptr<GeometryTile::LayoutResult> layoutResult;
std::vector<ImagePatch> imagePatches;
};
using namespace style;
std::optional<ImagePosition> GeometryTileRenderData::getPattern(const std::string& pattern) const {
MLN_TRACE_FUNC();
if (layoutResult) {
const auto& patternPositions = layoutResult->imageAtlas.patternPositions;
auto it = patternPositions.find(pattern);
if (it != patternPositions.end()) {
return it->second;
}
}
return std::nullopt;
}
void GeometryTileRenderData::upload(gfx::UploadPass& uploadPass) {
MLN_TRACE_FUNC();
if (!layoutResult) return;
auto uploadFn = [&](Bucket& bucket) {
if (bucket.needsUpload()) {
bucket.upload(uploadPass);
}
};
for (auto& entry : layoutResult->layerRenderData) {
uploadFn(*entry.second.bucket);
}
assert(atlasTextures);
if (const auto& glyphDynamicTexture = layoutResult->glyphAtlas.dynamicTexture) {
glyphDynamicTexture->uploadDeferredImages();
atlasTextures->glyph = glyphDynamicTexture->getTexture();
}
if (const auto& imageDynamicTexture = layoutResult->imageAtlas.dynamicTexture) {
imageDynamicTexture->uploadDeferredImages();
atlasTextures->icon = imageDynamicTexture->getTexture();
}
if (!imagePatches.empty()) {
for (const auto& imagePatch : imagePatches) { // patch updated images.
atlasTextures->icon->uploadSubRegion(imagePatch.image->image,
imagePatch.paddedRect.x + ImagePosition::padding,
imagePatch.paddedRect.y + ImagePosition::padding);
}
imagePatches.clear();
}
}
void GeometryTileRenderData::prepare(const SourcePrepareParameters& parameters) {
MLN_TRACE_FUNC();
if (!layoutResult) return;
imagePatches.clear();
populateImagePatches(layoutResult->imageAtlas.iconPositions, parameters.imageManager, imagePatches);
populateImagePatches(layoutResult->imageAtlas.patternPositions, parameters.imageManager, imagePatches);
}
Bucket* GeometryTileRenderData::getBucket(const Layer::Impl& layer) const {
const LayerRenderData* data = getLayerRenderData(layer);
return data ? data->bucket.get() : nullptr;
}
const LayerRenderData* GeometryTileRenderData::getLayerRenderData(const style::Layer::Impl& layerImpl) const {
return layoutResult ? layoutResult->getLayerRenderData(layerImpl) : nullptr;
}
GeometryTile::LayoutResult::~LayoutResult() {
if (dynamicTextureAtlas) {
dynamicTextureAtlas->removeTextures(glyphAtlas.textureHandles, glyphAtlas.dynamicTexture);
dynamicTextureAtlas->removeTextures(imageAtlas.textureHandles, imageAtlas.dynamicTexture);
}
}
/*
Correlation between GeometryTile and GeometryTileWorker is safeguarded by two
correlation schemes:
GeometryTile's 'correlationID' is used for ensuring the tile will be flagged
as non-pending only when the placement coming from the last operation (as in
'setData', 'setLayers', 'setShowCollisionBoxes') occurs. This is important
for still mode rendering as we want to render only when all layout and
placement operations are completed.
GeometryTileWorker's 'imageCorrelationID' is used for checking whether an
image request reply coming from `GeometryTile` is valid. Previous image
request replies are ignored as they result in incomplete placement attempts
that could flag the tile as non-pending too early.
*/
GeometryTile::GeometryTile(const OverscaledTileID& id_,
std::string sourceID_,
const TileParameters& parameters,
TileObserver* observer_)
: Tile(Kind::Geometry, id_, std::move(sourceID_), observer_),
ImageRequestor(parameters.imageManager),
threadPool(parameters.threadPool),
mailbox(std::make_shared<Mailbox>(*Scheduler::GetCurrent())),
worker(parameters.isUpdateSynchronous,
parameters.threadPool, // Scheduler reference for the Actor retainer
OptionalActorRef<GeometryTile>(parameters.isUpdateSynchronous, *this, mailbox),
parameters.threadPool,
id_,
sourceID,
obsolete,
parameters.mode,
parameters.pixelRatio,
parameters.debugOptions & MapDebugOptions::Collision,
parameters.dynamicTextureAtlas,
parameters.glyphManager->getFontFaces()),
fileSource(parameters.fileSource),
glyphManager(parameters.glyphManager),
imageManager(parameters.imageManager),
mode(parameters.mode),
showCollisionBoxes(parameters.debugOptions & MapDebugOptions::Collision) {}
GeometryTile::~GeometryTile() {
MLN_TRACE_FUNC();
markObsolete();
glyphManager->removeRequestor(*this);
imageManager->removeRequestor(*this);
if (pending) {
// This tile never finished loading or was abandoned, emit a cancellation event
observer->onTileAction(id, sourceID, TileOperation::Cancelled);
}
if (layoutResult) {
threadPool.runOnRenderThread(
[layoutResult_{std::move(layoutResult)}, atlasTextures_{std::move(atlasTextures)}]() {});
}
}
void GeometryTile::cancel() {
markObsolete();
}
void GeometryTile::markObsolete() {
obsolete = true;
mailbox->abandon();
}
void GeometryTile::setError(std::exception_ptr err) {
loaded = true;
observer->onTileError(*this, std::move(err));
}
void GeometryTile::setData(std::unique_ptr<const GeometryTileData> data_) {
MLN_TRACE_FUNC();
if (obsolete) {
return;
}
if (!pending) {
observer->onTileAction(id, sourceID, TileOperation::StartParse);
}
// Mark the tile as pending again if it was complete before to prevent
// signaling a complete state despite pending parse operations.
pending = true;
++correlationID;
worker.self().invoke(
&GeometryTileWorker::setData, std::move(data_), imageManager->getAvailableImages(), correlationID);
}
void GeometryTile::reset() {
MLN_TRACE_FUNC();
// If there is pending work, indicate that work has been cancelled.
// Clear the pending status.
if (pending) {
observer->onTileAction(id, sourceID, TileOperation::Cancelled);
pending = false;
}
// Reset the tile to an unloaded state to avoid signaling completion
// after clearing the tile's pending status.
loaded = false;
// Reset the worker to the `NeedsParse` state.
++correlationID;
worker.self().invoke(&GeometryTileWorker::reset, correlationID);
}
std::unique_ptr<TileRenderData> GeometryTile::createRenderData() {
MLN_TRACE_FUNC();
return std::make_unique<GeometryTileRenderData>(layoutResult, atlasTextures);
}
void GeometryTile::setLayers(const std::vector<Immutable<LayerProperties>>& layers) {
MLN_TRACE_FUNC();
// Mark the tile as pending again if it was complete before to prevent
// signaling a complete state despite pending parse operations.
if (!pending) {
pending = true;
observer->onTileAction(id, sourceID, TileOperation::StartParse);
}
std::vector<Immutable<LayerProperties>> impls;
impls.reserve(layers.size());
for (const auto& layer : layers) {
MLN_TRACE_ZONE(layer);
MLN_ZONE_STR(layer->baseImpl->id);
// Skip irrelevant layers.
const auto& layerImpl = *layer->baseImpl;
assert(layerImpl.getTypeInfo()->source != LayerTypeInfo::Source::NotRequired);
assert(layerImpl.source == sourceID);
assert(layerImpl.visibility != VisibilityType::None);
if (id.overscaledZ < std::floor(layerImpl.minZoom) || id.overscaledZ >= std::ceil(layerImpl.maxZoom)) {
continue;
}
impls.push_back(layer);
}
++correlationID;
worker.self().invoke(
&GeometryTileWorker::setLayers, std::move(impls), imageManager->getAvailableImages(), correlationID);
}
void GeometryTile::setShowCollisionBoxes(const bool showCollisionBoxes_) {
MLN_TRACE_FUNC();
if (showCollisionBoxes != showCollisionBoxes_) {
showCollisionBoxes = showCollisionBoxes_;
++correlationID;
worker.self().invoke(&GeometryTileWorker::setShowCollisionBoxes, showCollisionBoxes, correlationID);
}
}
void GeometryTile::onLayout(std::shared_ptr<LayoutResult> result,
const uint64_t resultCorrelationID,
bool isPartialResult) {
MLN_TRACE_FUNC();
// Partial progressive updates are optional visual improvements. Ignore stale
// partial callbacks to avoid applying outdated buckets and triggering
// redundant tile updates while a newer parse cycle is already in progress.
if (isPartialResult && resultCorrelationID != correlationID) {
return;
}
loaded = true;
renderable = true;
if (!isPartialResult && resultCorrelationID == correlationID) {
pending = false;
observer->onTileAction(id, sourceID, TileOperation::EndParse);
}
layoutResult = std::move(result);
if (!atlasTextures) {
atlasTextures = std::make_shared<TileAtlasTextures>();
}
if (layoutResult) {
for (const auto& data : layoutResult->layerRenderData) {
if (data.second.bucket) {
data.second.bucket->check(SYM_GUARD_LOC);
}
}
}
observer->onTileChanged(*this);
if (layoutResult) {
for (const auto& data : layoutResult->layerRenderData) {
if (data.second.bucket) {
data.second.bucket->check(SYM_GUARD_LOC);
}
}
}
}
void GeometryTile::onError(std::exception_ptr err, const uint64_t resultCorrelationID) {
loaded = true;
if (resultCorrelationID == correlationID) {
pending = false;
observer->onTileAction(id, sourceID, TileOperation::Error);
}
observer->onTileError(*this, std::move(err));
}
void GeometryTile::onGlyphsAvailable(GlyphMap glyphMap, [[maybe_unused]] HBShapeRequests requests) {
MLN_TRACE_FUNC();
HBShapeResults results;
#ifdef MLN_TEXT_SHAPING_HARFBUZZ
for (auto& fontStackIT : requests) {
auto fontStack = fontStackIT.first;
auto& fontTypes = fontStackIT.second;
for (auto& typesIT : fontTypes) {
auto type = typesIT.first;
auto& strs = typesIT.second;
for (auto& str : strs) {
std::vector<GlyphID> shapedGlyphIDs;
std::shared_ptr<std::vector<HBShapeAdjust>> shapedAdjusts =
std::make_shared<std::vector<HBShapeAdjust>>();
glyphManager->hbShaping(str, fontStack, type, shapedGlyphIDs, *shapedAdjusts);
std::u16string shapedstr;
shapedstr.reserve(shapedGlyphIDs.size());
for (auto& glyphID : shapedGlyphIDs) {
shapedstr += glyphID.complex.code;
auto fontStackHash = FontStackHasher()(fontStack);
bool needShape = true;
if (glyphMap.contains(fontStackHash)) {
auto& glyphs = glyphMap[fontStackHash];
if (glyphs.contains(glyphID)) needShape = false;
}
if (needShape) {
auto glyph = glyphManager->getGlyph(fontStack, glyphID);
glyphMap[fontStackHash].emplace(glyph->id, glyph);
}
}
results[fontStack][type][str] = HBShapeResult{shapedstr,
shapedAdjusts}; //.emplace(str, shapedstr, shapedAdjusts);
}
}
}
#endif // MLN_TEXT_SHAPING_HARFBUZZ
worker.self().invoke(&GeometryTileWorker::onGlyphsAvailable, std::move(glyphMap), std::move(results));
}
void GeometryTile::getGlyphs(GlyphDependencies glyphDependencies) {
MLN_TRACE_FUNC();
if (fileSource) {
glyphManager->getGlyphs(*this, std::move(glyphDependencies), *fileSource);
}
}
void GeometryTile::onImagesAvailable(ImageMap images,
ImageMap patterns,
ImageVersionMap versionMap,
uint64_t imageCorrelationID) {
MLN_TRACE_FUNC();
worker.self().invoke(&GeometryTileWorker::onImagesAvailable,
std::move(images),
std::move(patterns),
std::move(versionMap),
imageCorrelationID);
}
void GeometryTile::getImages(ImageRequestPair pair) {
MLN_TRACE_FUNC();
imageManager->getImages(*this, std::move(pair));
}
std::shared_ptr<FeatureIndex> GeometryTile::getFeatureIndex() const {
return layoutResult ? layoutResult->featureIndex : nullptr;
}
bool GeometryTile::layerPropertiesUpdated(const Immutable<style::LayerProperties>& layerProperties) {
MLN_TRACE_FUNC();
LayerRenderData* renderData = getLayerRenderData(*layerProperties->baseImpl);
if (!renderData) {
return false;
}
if (renderData->layerProperties != layerProperties &&
renderData->layerProperties->constantsMask() == layerProperties->constantsMask()) {
renderData->layerProperties = layerProperties;
}
return true;
}
const GeometryTileData* GeometryTile::getData() const {
if (!layoutResult || !layoutResult->featureIndex) {
return nullptr;
}
return layoutResult->featureIndex->getData();
}
LayerRenderData* GeometryTile::getLayerRenderData(const style::Layer::Impl& layerImpl) {
MLN_TRACE_FUNC();
return layoutResult ? layoutResult->getLayerRenderData(layerImpl) : nullptr;
}
float GeometryTile::getQueryPadding(const std::unordered_map<std::string, const RenderLayer*>& layers) {
MLN_TRACE_FUNC();
float queryPadding = 0;
for (const auto& pair : layers) {
const LayerRenderData* data = getLayerRenderData(*pair.second->baseImpl);
if (data && data->bucket && data->bucket->hasData()) {
queryPadding = std::max(queryPadding, data->bucket->getQueryRadius(*pair.second));
}
}
return queryPadding;
}
void GeometryTile::queryRenderedFeatures(std::unordered_map<std::string, std::vector<Feature>>& result,
const GeometryCoordinates& queryGeometry,
const TransformState& transformState,
const std::unordered_map<std::string, const RenderLayer*>& layers,
const RenderedQueryOptions& options,
const mat4& projMatrix,
const SourceFeatureState& featureState) {
MLN_TRACE_FUNC();
if (!getData()) return;
const float queryPadding = getQueryPadding(layers);
mat4 posMatrix;
transformState.matrixFor(posMatrix, id.toUnwrapped());
matrix::multiply(posMatrix, projMatrix, posMatrix);
layoutResult->featureIndex->query(result,
queryGeometry,
transformState,
posMatrix,
util::tileSize_D * id.overscaleFactor(),
std::pow(2, transformState.getZoom() - id.overscaledZ),
options,
id.toUnwrapped(),
layers,
queryPadding * transformState.maxPitchScaleFactor(),
featureState);
}
void GeometryTile::querySourceFeatures(std::vector<Feature>& result, const SourceQueryOptions& options) {
MLN_TRACE_FUNC();
// Data not yet available, or tile is empty
if (!getData()) {
return;
}
// No source layers, specified, nothing to do
if (!options.sourceLayers) {
Log::Warning(Event::General, "At least one sourceLayer required");
return;
}
for (const auto& sourceLayer : *options.sourceLayers) {
// Go throught all sourceLayers, if any
// to gather all the features
auto layer = getData()->getLayer(sourceLayer);
if (layer) {
auto featureCount = layer->featureCount();
for (std::size_t i = 0; i < featureCount; i++) {
auto feature = layer->getFeature(i);
// Apply filter, if any
if (options.filter && !(*options.filter)(style::expression::EvaluationContext{
static_cast<float>(this->id.overscaledZ), feature.get()})) {
continue;
}
result.emplace_back(convertFeature(*feature, id.canonical));
}
}
}
}
bool GeometryTile::holdForFade() const {
return mode == MapMode::Continuous &&
(fadeState == FadeState::NeedsFirstPlacement || fadeState == FadeState::NeedsSecondPlacement);
}
void GeometryTile::markRenderedIdeal() {
fadeState = FadeState::Loaded;
}
void GeometryTile::markRenderedPreviously() {
if (fadeState == FadeState::Loaded) {
fadeState = FadeState::NeedsFirstPlacement;
}
}
void GeometryTile::performedFadePlacement() {
if (fadeState == FadeState::NeedsFirstPlacement) {
fadeState = FadeState::NeedsSecondPlacement;
} else if (fadeState == FadeState::NeedsSecondPlacement) {
fadeState = FadeState::CanRemove;
}
}
void GeometryTile::setFeatureState(const LayerFeatureStates& states) {
MLN_TRACE_FUNC();
const auto layers = getData();
if ((layers == nullptr) || states.empty() || !layoutResult) {
return;
}
for (auto& layerIdToLayerRenderData = layoutResult->layerRenderData;
auto& [layerID, renderData] : layerIdToLayerRenderData) {
std::string sourceLayerId = renderData.layerProperties->baseImpl->sourceLayer;
if (const auto sourceLayer = layers->getLayer(sourceLayerId)) {
auto entry = states.find(sourceLayerId);
if (entry == states.end()) {
continue;
}
const auto& featureStates = entry->second;
if (featureStates.empty()) {
continue;
}
if (const auto bucket = renderData.bucket; bucket && bucket->hasData()) {
bucket->update(featureStates, *sourceLayer, layerID, layoutResult->imageAtlas.patternPositions);
}
}
}
}
} // namespace mbgl