Repository navigation
Asynchronous rendering #8820
Description
We want to be able to offload rendering onto a separate thread to free up the main thread on some platforms (most notably Android and Qt). The main thread should, as much as possible, be used only for user input and drawing so that a high frame-rate can be maintained.
A lot of work is already delegated to dedicate workers, but in order to offer a smooth experience on somewhat more lightweight hardware we need to eliminate some of the processing currently done on the main thread. Most notably:
- Rendering (OpenGL)
- DDS (evaluation of source functions)
Not all platforms need/should use a separate thread for rendering, so we want to enable a model where either is possible. Also, as an additional hurdle, on some platforms we want to be able to integrate with existing platform specific solutions such as the GLSurfaceView which come with a dedicated render thread that prohibits the use of a run loop as it blocks on a mutex.
In order to support this, we probably need a model where we utilise three threads:
- Main thread for integration with the UI framework / exposes our public API
- Supporting thread for orchestration of the render data preparation and render thread wake-up
- The render thread
Eg. Something like (very high-level):

Preparation
Currently a couple of classes contain data that is needed on both the main thread (to offer our public, synchronous api) and on the would-be render thread. In preparation of supporting a render thread these classes need to be split up accordingly. In the case of Layers and Sources, we've decided to aim for a model where we have a parallel tree of Render items which have a reference to their counterpart's immutable implementation class.
Related:
Currently underway
- Separate Layers in style and rendering parts: Separate rendering part from specification part for layers #8797
- Separate Sources in style and rendering parts: Separate rendering part from specification part for sources #8821
- Split Light: Render light #8889
- Split SpriteAtlas Split-off render sprite atlas #8937
- Investigate
GlyphAtlascallbacks - Make
Layer::ImplandSource::Implsubclasses immutable so they may be shared between style and render layers/sources [core] Immutable style Impls #8929
- Promote
add/remove/getImageand thestyle::Imagemap itself toStyle, and makeStyleresponsible for loading the sprite PNG and JSON, parceling out the individual images, and filling up the map. -
GlyphAtlaswill belong toRenderStyle, which won't be able to propagateonGlyphsLoaded/Errormessages to a parent observer. Investigate whether this is necessary/how to eliminate. (Likely do the same foronSpriteLoaded/Errorfor consistency, even though it could be preserved.) - What's
lastErrorused for? Should it belong toStyleorRenderStyleexclusively, or does it need to be split? -
TileParameterswill have aRenderStylereference rather than aStylereference.GeometryTilewill need to iterate overRenderLayersrather thanLayers, obtain an immutableImplfor each, and pass them to the worker rather than a copy of theLayer. -
SpriteAtlaswill need access to images (by immutable reference). - Replace in-place updates of
renderSourcesandrenderLayers(insetJSONand{add,remove}{Source,Layer}) withupdate-time updates based on diffing immutables. - Eliminate separate annotation SpriteAtlas ([core] Don't use a separate SpriteAtlas for annotation images #9003)
- Implement auto-growing SpriteAtlas texture
- Need shelf-pack-cpp with v2 improvements
- Implement auto-growing SpriteAtlas texture
- Replace inline SpriteAtlas updates with diffing ([core] Replace inline SpriteAtlas updates with diffing #9010)
- Replace
updateBatchmechanism with immutable layer diffing ([core] Omnibus: Split RenderStyle from Style #9119) - Both
StyleandRenderStyleneedisLoadedanddumpDebugLogsmethods. In the places that callStyle::isLoaded, add a call toRenderStyle::isLoaded(); likewise fordumpDebugLogs. ([core] Omnibus: Split RenderStyle from Style #9119) -
GlyphAtlaswill need access to a glyph URL (by immutable reference). ([core] Omnibus: Split RenderStyle from Style #9119) -
updatewill move toRenderStyle. Replace direct access to sources, layers, images, transition options, classes, and light with immutable references passed viaUpdateParameters. ([core] Omnibus: Split RenderStyle from Style #9119) - Rewrite
FileSourceusing actors (Convert DefaultFileSource and dependents to actor model #7678), or otherwise makeDefaultFileSourcethreadsafe - Rewrite
AnnotationManagerto use runtime styling APIs (Reimplement MGLAnnotation atop MGLSource and MGLStyleLayer #6181), or otherwise make it threadsafe Mutex guard annotation manager for cross thread usage #9220 - Ensure that
GeoJSONSource's use of GeoJSONVT and Supercluster is threadsafe
- Define
Renderer/Renderer::Implpair:- SDK code implementing renderer thread will own
std::unique_ptr<Renderer>provided by core Renderer::Implto hide details from public header- Public
Renderermethods:update(const UpdateParameters&)(UpdateParametersforward declared)render(const RenderParameters&)(RenderParametersforward declared)
- Probably merge
PainterandRenderStyleintoRenderer::Impl
- SDK code implementing renderer thread will own
- Define interfaces to be implemented by SDKs to provide background rendering (or not). Methods:
setRenderer(std::unique_ptr<Renderer>)(might be null to "reset" renderer during shutdown)update(std::unique_ptr<UpdateParameters>)render(std::unique_ptr<RenderParameters>)- Latter two are expected to forward to
Renderereither immediately (synchronously) or via sending message to rendering thread (asynchronously) - Also need some way for
Rendererto trigger a re-render when needed (animation) - Also need some way to forward "Low Memory" notifications
- Also need to deal with
RenderStyleObserver/MapObservernotifications - Also need query APIs, w/ potential cross-thread synchronization
Next steps
- Actually implement asynchronicity in the
RenderFrontendfor Android - Handle context loss on Android -- I (@jfirebaugh) vote for just recreating a totally fresh
Rendererif we lose the context. The alternative is to keep a copy of all bucket data in main memory, so that we can recreate the GL buffers from it. This would ~2x the memory usage of maps, just to get somewhat faster reloads when the context comes back -- not worth it IMO. - TODO: can we refactor still rendering logic as an implementation of this new interface?
cc @mapbox/gl

Activity
zugaldia commentedon Apr 26, 2017
Related (follow-up) work on Android to implement
GlSurfaceViewto contain the map view: #5766.jfirebaugh commentedon Apr 26, 2017
Summary of the task of splitting
SpriteAtlas: we want to start treating the set of images specified by the style more similarly to how we treat layers and sources. I.e.Styleshould own astd::vector<std::unique_ptr<Image>>. The rest ofSpriteAtlasis rendering related and will belong to theRenderStyle. We'll bridge access toImages betweenStyleand theSpriteAtlasinRenderStyleusing the same mechanism as forLayers andSources (most likely via sharing references to immutable objects).tmpsantos commentedon Apr 27, 2017
What is not clear from this design is how something like "query rendered features" is going to work synchronously. We need the "evaluated" state for that, right?
ivovandongen commentedon May 2, 2017
@tmpsantos Very good question. ATM I see two options:
We can support both of course, but moving to the later would have my preference.
jfirebaugh commentedon May 4, 2017
I did a rough dry run at splitting
StyleandRenderStylejust to see what will need to change to allow that to happen. Here's my list. Items marked with ℹ️ depend on having infrastructure in place for immutable objects.add/remove/getImageand thestyle::Imagemap itself toStyle, and makeStyleresponsible for loading the sprite PNG and JSON, parceling out the individual images, and filling up the map.GlyphAtlaswill belong toRenderStyle, which won't be able to propagateonGlyphsLoaded/Errormessages to a parent observer. Investigate whether this is necessary/how to eliminate. (Likely do the same foronSpriteLoaded/Errorfor consistency, even though it could be preserved.)lastErrorused for? Should it belong toStyleorRenderStyleexclusively, or does it need to be split?StyleandRenderStyleneedisLoadedanddumpDebugLogsmethods. In the places that callStyle::isLoaded, add a call toRenderStyle::isLoaded(); likewise fordumpDebugLogs.TileParameterswill have aRenderStylereference rather than aStylereference.GeometryTilewill need to iterate overRenderLayersrather thanLayers, obtain an immutableImplfor each, and pass them to the worker rather than a copy of theLayer.GlyphAtlaswill need access to a glyph URL (by immutable reference).SpriteAtlaswill need access to images (by immutable reference).renderSourcesandrenderLayers(insetJSONand{add,remove}{Source,Layer}) withupdate-time updates based on diffing immutables.updateBatchmechanism with immutable layer diffing.updatewill move toRenderStyle. Replace direct access to sources, layers, images, transition options, classes, and light with immutable references passed viaUpdateParameters.I'm continuing to work on prerequisites for the ℹ️ items, but I could use help on the others.
ivovandongen commentedon May 5, 2017
@jfirebaugh
I will take care of that while looking at the
SpriteAtlasDepending on the concurrency model / necessity, we could retain this. I was imagining re-using the actor model for communication between Style/RenderStyle. In this case we can propagate these messages back from RenderStyle to Style.
I'm finishing up the Light changes you requested now and then will start to pick up the items you list one by one.
ivovandongen commentedon May 5, 2017
Looking into cutting up the SpriteAtlas; it seems that we would need a way for the
RenderStyle-to-be to communicate back to theStyleto request images since theGeometryTiles (loaded by RenderStyle) require it. Doesn't seem to be a way around this if we coordinate loading the images on the main thread as we need access to both images added through the api and images loaded through the sprite url for{add/remove/get}Image.We should pass the
RenderStylean interface (likeImageProvider) to use when requesting images, which we could implement differently later on to abstract over the threads Style and RenderStyle live on.jfirebaugh commentedon May 5, 2017
No, communication is one way; there's no communication in
Render⇢Styledirection. All data will be provided in theStyle⇢Renderdirection via immutable references, including for images. This means we probably need to splitstyle::Imageandstyle::Image::Impl, so we can provideImmutable<style::Image::Impl>s to theRenderStyle.Like it's responsible for loading source TileJSON,
Stylewill be responsible for loading the sprite. (In a future revision of the style specification I hope that both sprite images and source TileJSON will be mandatorily inline.)kkaefer commentedon May 9, 2017
I added a write-up of lifetimes and object ownership in
GLSurfaceViewover in #5766 (comment)jfirebaugh commentedon Jun 8, 2017
I've been keeping a list of potential followup changes. These are things that I've noticed when working on this that would be nice to do at some point but so far aren't directly necessary:
rendererdirectoryfoo_bucket.cpp,foo_render_layer.cpp,foo_program.cpp,foo_shaders.cppall in the same directory)Transform/TransformState⇢Camera/Immutable<Camera::Impl>RenderLayer::{transition,evaluate,setImpl}into a singleupdatemethod (likeRenderSource)RenderStyle::updateandRenderStyle::getRenderData?MapMode⇢RenderModeSourceTypeenum tosource_type.hpp(likelayer_type.hpp)getRenderSourceRenderStyle::queryRenderedFeaturesaddImageto update existing images -- should be a separate APILayer/Source/Image(related to Crash when mutating sources and layers that were added to a previously loaded style #8882)Stylea public API, remove runtime styling APIs fromMap(related to Initializers for MGLStyle #6386)