summaryrefslogtreecommitdiff
path: root/platform/android/src/android_gl_thread.hpp
blob: 78777aa4750e289cd792523567fc0af2285baf6d (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
#pragma once

#include <mbgl/actor/actor.hpp>
#include <mbgl/actor/mailbox.hpp>
#include <mbgl/actor/scheduler.hpp>
#include <mbgl/renderer/renderer.hpp>

#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <utility>

namespace mbgl {
namespace android {

class AndroidGLThread : public Scheduler {
public:
    using InvalidateCallback = std::function<void ()>;

    template <class... Args>
    AndroidGLThread(InvalidateCallback callback_, Args&&... args)
        : renderer(std::make_unique<Renderer>(std::forward<Args>(args)...))
        , mailbox(std::make_shared<Mailbox>(*this))
        , callback(callback_)
        , rendererRef(*renderer, mailbox) {
    }

    ~AndroidGLThread() override = default;

    ActorRef<Renderer> actor() const {
        return rendererRef;
    }

    void schedule(std::weak_ptr<Mailbox> scheduled) override {
        {
            std::lock_guard<std::mutex> lock(mutex);
            queue.push(scheduled);
        }

        // Invalidate so we get processing time later
        callback();
    }

    // Only safe on the GL Thread
    void process() {
        std::unique_lock<std::mutex> lock(mutex);

        if (queue.empty()) {
            return;
        }

        auto scheduled = queue.front();
        queue.pop();

        lock.unlock();

        Mailbox::maybeReceive(scheduled);
    }

    // Only safe to access on the GL Thread
    std::unique_ptr<Renderer> renderer;

private:
    std::mutex mutex;
    std::queue<std::weak_ptr<Mailbox>> queue;

    std::shared_ptr<Mailbox> mailbox;
    InvalidateCallback callback;
    ActorRef<Renderer> rendererRef;
};

} // namespace android
} // namespace mbgl