move to libuv for the rendering loop

This commit is contained in:
Konstantin Käfer
2014-04-30 12:01:26 +02:00
parent ddc359f006
commit 1216a061d3
32 changed files with 1312 additions and 911 deletions

View File

@@ -2,6 +2,7 @@
#define LLMR_MAIN
#include "map/map.hpp"
#include "map/view.hpp"
#include "map/settings.hpp"
#endif

View File

@@ -3,8 +3,9 @@
#include <uv.h>
#include <llmr/map/tile.hpp>
#include <llmr/map/tile_data.hpp>
#include <llmr/map/view.hpp>
// #include <llmr/map/tile.hpp>
// #include <llmr/map/tile_data.hpp>
#include <llmr/map/transform.hpp>
#include <llmr/style/style.hpp>
#include <llmr/geometry/glyph_atlas.hpp>
@@ -18,31 +19,34 @@
namespace llmr {
class Settings;
class Source;
class Map : private util::noncopyable {
public:
explicit Map(Settings& settings);
explicit Map(View &view);
~Map();
// Start/stop the map render thread
void start();
void run();
void stop();
/* setup */
void setup();
void loadStyle(const uint8_t *const data, uint32_t bytes);
void loadSettings();
// Runs the map event loop.
void run();
// Triggers a lazy rerender: only performs a render when the map is not clean.
void rerender();
// Forces a map update: always triggers a rerender.
void update();
// Size
void resize(uint16_t width, uint16_t height, float ratio = 1);
void resize(uint16_t width, uint16_t height, float ratio, uint16_t fb_width, uint16_t fb_height);
/* callback */
void update();
void render();
// Animations
void cancelAnimations();
/* position */
// Position
void moveBy(double dx, double dy, double duration = 0);
void setLonLat(double lon, double lat, double duration = 0);
void getLonLat(double &lon, double &lat) const;
@@ -50,7 +54,7 @@ public:
void stopPanning();
void resetPosition();
/* scale */
// Scale
void scaleBy(double ds, double cx = -1, double cy = -1, double duration = 0);
void setScale(double scale, double cx = -1, double cy = -1, double duration = 0);
double getScale() const;
@@ -62,39 +66,63 @@ public:
void startScaling();
void stopScaling();
/* rotation */
// Rotation
void rotateBy(double sx, double sy, double ex, double ey, double duration = 0);
void setAngle(double angle, double cx = -1, double cy = -1, double duration = 0);
void setAngle(double angle, double cx = -1, double cy = -1);
double getAngle() const;
void resetNorth();
void startRotating();
void stopRotating();
void redraw();
// Toggles
void setDebug(bool value);
void toggleDebug();
bool getDebug() const;
void toggleRaster();
box cornersToBox(uint32_t z) const;
public: // Getters
float getPixelRatio() const;
Style& getStyle();
GlyphAtlas& getGlyphAtlas();
uv_loop_t *getLoop();
public:
inline const TransformState &getState() const { return state; }
inline const Style &getStyle() const { return style; }
inline GlyphAtlas &getGlyphAtlas() { return glyphAtlas; }
inline uv_loop_t *getLoop() { return loop; }
private:
bool updateTiles();
static void eventloop(void *arg);
// uv async callbacks
static void render(uv_async_t *async);
static void terminate(uv_async_t *async);
static void delete_async(uv_handle_t *handle);
// Setup
void setup();
void loadStyle(const uint8_t *const data, uint32_t bytes);
void updateTiles();
// Prepares a map render by updating the tiles we need for the current view, as well as updating
// the stylesheet.
void prepare();
// Unconditionally performs a render with the current map state.
void render();
public:
// If cleared, the next time the render thread attempts to render the map, it will *actually*
// render the map.
std::atomic_flag clean = ATOMIC_FLAG_INIT;
// If this flag is cleared, the current back buffer is ready for being swapped with the front
// buffer (i.e. it has rendered data).
std::atomic_flag swapped = ATOMIC_FLAG_INIT;
// This is cleared once the current front buffer has been presented and the back buffer is
// ready for rendering.
std::atomic_flag rendered = ATOMIC_FLAG_INIT;
private:
Settings& settings;
View &view;
Transform transform;
TransformState state;
Texturepool texturepool;
Style style;
GlyphAtlas glyphAtlas;
@@ -102,10 +130,15 @@ private:
std::map<std::string, const std::unique_ptr<Source>> sources;
bool debug = false;
double animationTime = 0;
private:
bool async = false;
uv_loop_t *loop = nullptr;
uv_thread_t thread;
uv_async_t async_terminate;
uv_async_t *async_terminate = nullptr;
uv_async_t *async_render = nullptr;
};
}

View File

@@ -13,7 +13,7 @@
namespace llmr {
class Map;
class Transform;
class TransformState;
class Painter;
class Texturepool;
@@ -25,15 +25,18 @@ public:
};
public:
Source(Map &map, Transform &transform, Painter &painter, Texturepool &texturepool,
Source(Map &map, Painter &painter, Texturepool &texturepool,
const char *url = "", Type type = Type::vector, std::vector<uint32_t> zooms = {0},
uint32_t tile_size = 512, uint32_t min_zoom = 0, uint32_t max_zoom = 14,
bool enabled = true);
bool update();
void prepare_render(bool is_baselayer = false);
void prepare_render(const TransformState &transform, bool is_baselayer = false);
void render(double animationTime);
public:
bool enabled;
@@ -51,7 +54,6 @@ private:
private:
Map& map;
Transform& transform;
Painter& painter;
Texturepool& texturepool;

View File

@@ -59,7 +59,8 @@ public:
~TileData();
void request();
bool parse();
void scheduleParsing();
void parse();
void cancel();
const std::string toString() const;

View File

@@ -1,11 +1,11 @@
#ifndef LLMR_MAP_TRANSFORM
#define LLMR_MAP_TRANSFORM
#include <llmr/util/vec.hpp>
#include <llmr/util/mat4.hpp>
#include <llmr/util/animation.hpp>
#include <llmr/util/noncopyable.hpp>
#include <llmr/map/tile.hpp>
#include <llmr/util/uv.hpp>
#include "transform_state.hpp"
#include <forward_list>
@@ -17,82 +17,72 @@ struct box;
public:
Transform();
// Map view
// Note: width * ratio does not necessarily equal fb_width
bool resize(uint16_t width, uint16_t height, float ratio,
uint16_t fb_width, uint16_t fb_height);
// Position
void moveBy(double dx, double dy, double duration = 0);
void setLonLat(double lon, double lat, double duration = 0);
void setLonLatZoom(double lon, double lat, double zoom, double duration = 0);
void getLonLat(double& lon, double& lat) const;
void getLonLatZoom(double& lon, double& lat, double& zoom) const;
void startPanning();
void stopPanning();
// Zoom
void scaleBy(double ds, double cx = -1, double cy = -1, double duration = 0);
void setScale(double scale, double cx = -1, double cy = -1, double duration = 0);
void setZoom(double zoom, double duration = 0);
double getZoom() const;
double getScale() const;
void startRotating();
void stopRotating();
// Angle
void rotateBy(double sx, double sy, double ex, double ey, double duration = 0);
void setAngle(double angle, double duration = 0);
void setAngle(double angle, double cx, double cy);
double getAngle() const;
void startScaling();
void stopScaling();
// Animations
bool needsAnimation() const;
void updateAnimations(double time);
void cancelAnimations();
// Map view changes.
// Note: width * ratio does not necessarily equal fb_width
void resize(uint16_t width, uint16_t height, float ratio, uint16_t fb_width, uint16_t fb_height);
// Relative changes
void moveBy(double dx, double dy, double duration = 0);
void scaleBy(double ds, double cx = -1, double cy = -1, double duration = 0);
void rotateBy(double sx, double sy, double ex, double ey, double duration = 0);
// Absolute changes
void setScale(double scale, double cx = -1, double cy = -1, double duration = 0);
void setAngle(double angle, double duration = 0);
void setZoom(double zoom, double duration = 0);
void setLonLat(double lon, double lat, double duration = 0);
void setLonLatZoom(double lon, double lat, double zoom, double duration = 0);
// Getters
void matrixFor(mat4& matrix, const Tile::ID& id) const;
float getZoom() const;
float getNormalizedZoom() const;
int32_t getIntegerZoom() const;
double getScale() const;
double getAngle() const;
void getLonLat(double& lon, double& lat) const;
void getLonLatZoom(double& lon, double& lat, double& zoom) const;
// Animations
void startPanning();
void stopPanning();
void startRotating();
void stopRotating();
void startScaling();
void stopScaling();
box cornersToBox(uint32_t z) const;
// More getters
inline uint16_t getWidth() const { return width; }
inline uint16_t getHeight() const { return height; }
inline uint16_t getFramebufferWidth() const { return fb_width; }
inline uint16_t getFramebufferHeight() const { return fb_height; }
inline float getPixelRatio() const { return pixelRatio; }
// Transform state
const TransformState currentState() const;
const TransformState finalState() const;
private:
void setScaleXY(double new_scale, double xn, double yn, double duration = 0);
double pixel_x() const;
double pixel_y() const;
// Functions prefixed with underscores will *not* perform any locks. It is the caller's
// responsibility to lock this object.
void _moveBy(double dx, double dy, double duration = 0);
void _setScale(double scale, double cx, double cy, double duration = 0);
void _setScaleXY(double new_scale, double xn, double yn, double duration = 0);
void _setAngle(double angle, double duration = 0);
void _clearPanning();
void _clearRotating();
void _clearScaling();
private:
// logical dimensions
uint16_t width = 0;
uint16_t height = 0;
mutable uv::rwlock mtx;
// physical (framebuffer) dimensions
uint16_t fb_width = 0;
uint16_t fb_height = 0;
// This reflects the current state of the transform, representing the actual position of the
// map. After calling a transform function with a timer, this will likely remain the same until
// you render a new frame.
TransformState current;
float pixelRatio = 1;
// This reflects the final position of the transform, after all possible animations took place.
TransformState final;
public:
bool rotating = false;
bool scaling = false;
bool panning = false;
private:
double x = 0, y = 0; // pixel values of the map center in the current scale
double angle = 0;
double scale = 1;
double min_scale = pow(2, 0);
double max_scale = pow(2, 20);
// Limit the amount of zooming possible on the map.
// TODO: make these modifiable from outside.
const double min_scale = pow(2, 0);
const double max_scale = pow(2, 20);
// cache values for spherical mercator math
double zc, Bc, Cc;

View File

@@ -0,0 +1,68 @@
#ifndef LLMR_MAP_TRANSFORM_STATE
#define LLMR_MAP_TRANSFORM_STATE
#include <llmr/util/mat4.hpp>
#include <llmr/map/tile.hpp>
#include <cstdint>
namespace llmr {
class Transform;
class TransformState {
friend class Transform;
public:
// Matrix
void matrixFor(mat4& matrix, const Tile::ID& id) const;
box cornersToBox(uint32_t z) const;
// Dimensions
uint16_t getWidth() const;
uint16_t getHeight() const;
uint16_t getFramebufferWidth() const;
uint16_t getFramebufferHeight() const;
const std::array<uint16_t, 2> getFramebufferDimensions() const;
float getPixelRatio() const;
// Zoom
float getNormalizedZoom() const;
int32_t getIntegerZoom() const;
double getZoom() const;
double getScale() const;
// Rotation
float getAngle() const;
// Changing
bool isChanging() const;
private:
double pixel_x() const;
double pixel_y() const;
private:
// logical dimensions
uint16_t width = 0, height = 0;
// physical (framebuffer) dimensions
std::array<uint16_t, 2> framebuffer = {{ 0, 0 }};
// map scale factor
float pixelRatio = 0;
// animation state
bool rotating = false;
bool scaling = false;
bool panning = false;
// map position
double x = 0, y = 0;
double angle = 0;
double scale = 1;
};
}
#endif

19
include/llmr/map/view.hpp Normal file
View File

@@ -0,0 +1,19 @@
#ifndef LLMR_MAP_VIEW
#define LLMR_MAP_VIEW
namespace llmr {
class View {
public:
// Called from the render (=GL) thread. Signals that the context should
// swap the front and the back buffer.
virtual void swap() = 0;
// Called from the render thread. Makes the GL context active in the current
// thread. This is typically just called once at the beginning of the
// renderer setup since the render thread doesn't switch the contexts.
virtual void make_active() = 0;
};
}
#endif

View File

@@ -13,34 +13,27 @@ extern const char *kSpriteURL;
namespace platform {
// Restarts painting. This could for example trigger the event loop of the controlling application.
void restart();
class Request;
struct Response {
Response(std::function<void(Response *)> callback) : callback(callback) {}
int16_t code = -1;
std::string body;
std::string error_message;
std::function<void(Response *)> callback;
};
// Makes an HTTP request of a URL on a background thread, calls a function with the results in
// another thread, then calls the foreground callback in the original main thread.
// Returns a cancellable request.
std::shared_ptr<Request> request_http(const std::string &url,
std::function<void(Response *)> background_function,
std::function<void()> foreground_callback,
std::function<void(Response *)> callback,
uv_loop_t *loop);
// Cancels an HTTP request.
void cancel_request_http(const std::shared_ptr<Request> &req);
// Returns a relative timestamp in seconds. This value must be monotonic.
double elapsed();
// Shows an RGBA image with the specified dimensions in a named window.
void show_debug_image(std::string name, const char *data, size_t width, size_t height);

View File

@@ -4,13 +4,13 @@
#include <string>
#include <functional>
#include <memory>
#include <atomic>
#include <llmr/util/noncopyable.hpp>
// Forward definition.
typedef struct uv_work_s uv_work_t;
typedef struct uv_check_s uv_check_t;
typedef struct uv_loop_s uv_loop_t;
typedef struct uv_async_s uv_async_t;
namespace llmr {
namespace platform {
@@ -20,24 +20,22 @@ struct Response;
class Request : public std::enable_shared_from_this<Request>, private util::noncopyable {
public:
Request(const std::string &url,
std::function<void(Response *)> background_function,
std::function<void()> foreground_callback,
std::function<void(Response *)> callback,
uv_loop_t *loop);
~Request();
public:
static void work_callback(uv_work_t *work);
static void after_work_callback(uv_work_t *work, int status);
void complete();
private:
static void complete(uv_async_t *async);
public:
const std::string url;
const std::function<void(Response *)> background_function;
const std::function<void()> foreground_callback;
std::unique_ptr<Response> res;
bool cancelled = false;
std::atomic<bool> cancelled;
public:
uv_check_t *check = nullptr;
uv_async_t *async = nullptr;
uv_loop_t *loop = nullptr;
};
}

View File

@@ -17,6 +17,8 @@
#include <llmr/shader/raster_shader.hpp>
#include <llmr/shader/text_shader.hpp>
#include <llmr/map/transform_state.hpp>
namespace llmr {
class Transform;
@@ -32,7 +34,8 @@ class RasterBucket;
class Painter : private util::noncopyable {
public:
Painter(Transform& transform, Style& style, GlyphAtlas& glyphAtlas);
Painter(Map &map);
void setup();
void clear();
@@ -72,9 +75,7 @@ public:
mat4 extrudeMatrix;
private:
Transform& transform;
Style& style;
GlyphAtlas& glyphAtlas;
Map& map;
FrameHistory frameHistory;
@@ -83,6 +84,7 @@ private:
uint32_t gl_program = 0;
float gl_lineWidth = 0;
bool gl_depthMask = true;
std::array<uint16_t, 2> gl_viewport = {{ 0, 0 }};
float strata = 0;
const float strata_epsilon = 1.0f / (1 << 16);
enum { Opaque, Translucent } pass = Opaque;

View File

@@ -41,18 +41,22 @@ public:
ImagePosition getPosition(const std::string& name, bool repeating = false);
operator bool() const;
bool isLoaded() const;
public:
const float pixelRatio;
std::shared_ptr<Raster> raster;
private:
void parseJSON(const std::string& data);
void asyncParseJSON();
static void parseJSON(std::shared_ptr<Sprite> &sprite);
static void complete(std::shared_ptr<Sprite> &sprite);
private:
Map &map;
mutable std::mutex mtx;
std::string body;
bool loaded = false;
std::map<std::string, SpritePosition> pos;
};

View File

@@ -0,0 +1,42 @@
#ifndef LLMR_UTIL_TIME
#define LLMR_UTIL_TIME
#include <uv.h>
namespace llmr {
typedef uint64_t time;
namespace util {
// Returns time in nanoseconds since an arbitrary point in the past. This has
// no relation to the current time, but is continuously increasing, so
// comparisons between different timestamps produce meaningful values.
inline time now() {
return uv_hrtime();
}
}
// used for time conversions
constexpr time operator"" _nanoseconds (long double ns) { return ns; }
constexpr time operator"" _nanosecond (long double ns) { return ns; }
constexpr time operator"" _microseconds (long double us) { return us * 1e3; }
constexpr time operator"" _microsecond (long double us) { return us * 1e3; }
constexpr time operator"" _milliseconds (long double ms) { return ms * 1e6; }
constexpr time operator"" _millisecond (long double ms) { return ms * 1e6; }
constexpr time operator"" _seconds (long double s) { return s * 1e9; }
constexpr time operator"" _second (long double s) { return s * 1e9; }
constexpr time operator"" _nanoseconds (unsigned long long ns) { return ns; }
constexpr time operator"" _nanosecond (unsigned long long ns) { return ns; }
constexpr time operator"" _microseconds (unsigned long long us) { return us * 1e3; }
constexpr time operator"" _microsecond (unsigned long long us) { return us * 1e3; }
constexpr time operator"" _milliseconds (unsigned long long ms) { return ms * 1e6; }
constexpr time operator"" _millisecond (unsigned long long ms) { return ms * 1e6; }
constexpr time operator"" _seconds (unsigned long long s) { return s * 1e9; }
constexpr time operator"" _second (unsigned long long s) { return s * 1e9; }
}
#endif

View File

@@ -8,7 +8,6 @@
namespace uv {
typedef void (*callback)();
class mutex {
public:
@@ -16,7 +15,6 @@ public:
inline ~mutex() { uv_mutex_destroy(&mtx); }
inline void lock() { uv_mutex_lock(&mtx); }
inline void unlock() { uv_mutex_unlock(&mtx); }
inline bool trylock() { return uv_mutex_trylock(&mtx); }
private:
uv_mutex_t mtx;
@@ -31,8 +29,40 @@ private:
mutex &mtx;
};
class rwlock {
public:
inline rwlock() { assert(uv_rwlock_init(&mtx) == 0); }
inline ~rwlock() { uv_rwlock_destroy(&mtx); }
inline void rdlock() { uv_rwlock_rdlock(&mtx); }
inline void wrlock() { uv_rwlock_wrlock(&mtx); }
inline void rdunlock() { uv_rwlock_rdunlock(&mtx); }
inline void wrunlock() { uv_rwlock_wrunlock(&mtx); }
private:
uv_rwlock_t mtx;
};
class readlock {
public:
inline readlock(rwlock &mtx) : mtx(mtx) { mtx.rdlock(); }
inline ~readlock() { mtx.rdunlock(); }
private:
rwlock &mtx;
};
class writelock {
public:
inline writelock(rwlock &mtx) : mtx(mtx) { mtx.wrlock(); }
inline ~writelock() { mtx.wrunlock(); }
private:
rwlock &mtx;
};
class once {
public:
typedef void (*callback)();
void operator()(void (*callback)(void)) {
uv_once(&o, callback);
}
@@ -41,6 +71,40 @@ private:
uv_once_t o = UV_ONCE_INIT;
};
template <typename T>
class work {
public:
typedef void (*work_callback)(T &object);
typedef void (*after_work_callback)(T &object);
template<typename... Args>
work(uv_loop_t *loop, work_callback work_cb, after_work_callback after_work_cb, Args&&... args)
: data(std::forward<Args>(args)...),
work_cb(work_cb),
after_work_cb(after_work_cb) {
req.data = this;
uv_queue_work(loop, &req, do_work, after_work);
}
private:
static void do_work(uv_work_t *req) {
work<T> *w = static_cast<work<T> *>(req->data);
w->work_cb(w->data);
}
static void after_work(uv_work_t *req, int) {
work<T> *w = static_cast<work<T> *>(req->data);
w->after_work_cb(w->data);
delete w;
}
private:
uv_work_t req;
T data;
work_callback work_cb;
after_work_callback after_work_cb;
};
}
#endif