Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderThread.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "RenderThread.hpp"
4
5#ifdef ES_RENDER_THREADS
6#include <cassert>
7#include <cstdlib>
8#include <exception>
9#include <utility>
10#ifdef __EMSCRIPTEN__
11#include <emscripten/emscripten.h>
12#include <emscripten/threading.h>
13#endif
14
15namespace esengine {
16
17thread_local RenderThread* RenderThread::current_ = nullptr;
18
19RenderThread::~RenderThread() { stop(); }
20
21bool RenderThread::start(const char* canvas) {
22 if (started_) return true;
23 stopping_ = false;
24#ifdef __EMSCRIPTEN__
25 if (!emscripten_has_threading_support()) return false;
26 proxy_ = em_proxying_queue_create();
27 if (!proxy_) return false;
28 pthread_attr_t attr;
29 pthread_attr_init(&attr);
30 if (canvas) emscripten_pthread_attr_settransferredcanvases(&attr, canvas);
31 const int error = pthread_create(&worker_, &attr, webEntry, this);
32 pthread_attr_destroy(&attr);
33 if (error) {
34 em_proxying_queue_destroy(proxy_);
35 proxy_ = nullptr;
36 return false;
37 }
38#else
39 (void)canvas;
40 worker_ = std::thread([this] {
41 current_ = this;
42 std::unique_lock lock(mutex_);
43 for (;;) {
44 changed_.wait(lock, [&] { return stopping_ || !pending_.empty(); });
45 if (pending_.empty()) break;
46 auto command = std::move(pending_.front());
47 pending_.pop_front();
48 lock.unlock();
49 run(std::move(command));
50 lock.lock();
51 }
52 current_ = nullptr;
53 });
54#endif
55 started_ = true;
56 return true;
57}
58
59void RenderThread::run(Command command) {
60 command.execute();
61 // Release captures before publishing completion, including resource owners.
62 command.execute = {};
63 {
64 std::lock_guard lock(mutex_);
65 completed_ = command.serial;
66 }
67 changed_.notify_all();
68}
69
70#ifdef __EMSCRIPTEN__
71void* RenderThread::webEntry(void* arg) {
72 current_ = static_cast<RenderThread*>(arg);
73 // Return to the browser between batches so OffscreenCanvas can present and
74 // readback/context events can run, even when the game submits no more work.
75 emscripten_exit_with_live_runtime();
76 return nullptr;
77}
78
79void RenderThread::drainWeb(void* arg) {
80 auto& self = *static_cast<RenderThread*>(arg);
81 std::deque<Command> batch;
82 {
83 std::lock_guard lock(self.mutex_);
84 batch.swap(self.pending_);
85 }
86 for (auto& command : batch) self.run(std::move(command));
87}
88#endif
89
90RenderThread::Fence RenderThread::enqueue(std::function<void()> work) {
91 if (!started_) { work(); return 0; }
92 assert(!isOwner());
93 Fence serial;
94 {
95 std::lock_guard lock(mutex_);
96 serial = ++submitted_;
97#ifdef __EMSCRIPTEN__
98 const bool wake = pending_.empty();
99#endif
100 pending_.push_back({serial, std::move(work)});
101#ifdef __EMSCRIPTEN__
102 if (wake && !emscripten_proxy_async(proxy_, worker_, drainWeb, this)) std::abort();
103#endif
104 }
105 changed_.notify_all();
106 return serial;
107}
108
110 std::lock_guard lock(mutex_);
111 return submitted_;
112}
113
114bool RenderThread::complete(Fence value) const {
115 std::lock_guard lock(mutex_);
116 return completed_ >= value;
117}
118
119void RenderThread::wait(Fence value) {
120 if (!value) return;
121 assert(!isOwner());
122 std::unique_lock lock(mutex_);
123 changed_.wait(lock, [&] { return completed_ >= value; });
124}
125
126void RenderThread::invokeChecked(std::function<void()> work) {
127#ifdef __cpp_exceptions
128 std::exception_ptr error;
129 wait(enqueue([&] {
130 try { work(); }
131 catch (...) { error = std::current_exception(); }
132 }));
133 if (error) std::rethrow_exception(error);
134#else
135 wait(enqueue(std::move(work)));
136#endif
137}
138
139void RenderThread::flush() { if (started_ && !isOwner()) wait(fence()); }
140
141void RenderThread::finishFrame(std::function<void()> end) {
142 wait(frames_[frameSlot_]);
143 frames_[frameSlot_] = enqueue(std::move(end));
144 frameSlot_ ^= 1;
145}
146
147void RenderThread::stop() {
148 if (!started_) return;
149 flush();
150#ifdef __EMSCRIPTEN__
151 if (!emscripten_proxy_async(proxy_, worker_, [](void*) { pthread_exit(nullptr); }, nullptr)) std::abort();
152 pthread_join(worker_, nullptr);
153 em_proxying_queue_destroy(proxy_);
154 proxy_ = nullptr;
155#else
156 {
157 std::lock_guard lock(mutex_);
158 stopping_ = true;
159 }
160 changed_.notify_all();
161 worker_.join();
162#endif
163 started_ = false;
164}
165
166} // namespace esengine
167#endif
bool complete(Fence value) const
Fence enqueue(std::function< void()> fn)
void finishFrame(std::function< void()> fn)
bool start(const char *=nullptr)
std::span< const EsCmd > run(SystemFn fn, std::span< const std::uint32_t > fallback, std::span< const QuerySpec > queries, std::span< void *const > resources, CallArena &arena, WorldStamp world={})
Definition AotHost.hpp:181