Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Loader.h
Go to the documentation of this file.
1/* Copyright (C) 2025 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18// FIFO queue of load 'functors' with time limit; enables displaying
19// load progress without resorting to threads (complicated).
20
21#ifndef INCLUDED_LOADER
22#define INCLUDED_LOADER
23
24#include "lib/debug.h"
25#include "lib/status.h"
26#include "lib/timer.h"
27
28#include <coroutine>
29#include <exception>
30#include <functional>
31#include <string>
32#include <utility>
33
34namespace PS::Loader
35{
36/*
37
38[KEEP IN SYNC WITH WIKI!]
39
40Overview
41--------
42
43"Loading" is the act of preparing a game session, including reading all
44required data from disk. Ideally, this would be very quick, but for complex
45maps and/or low-end machines, a duration of several seconds can be expected.
46Having the game freeze that long is unacceptable; instead, we want to display
47the current progress and task, which greatly increases user patience.
48
49
50Allowing for Display
51--------------------
52
53To display progress, we need to periodically 'interrupt' loading.
54Threads come to mind, but there is a problem: since OpenGL graphics calls
55must come from the main thread, loading would have to happen in a
56background thread. Everything would thus need to be made thread-safe,
57which is a considerable complication.
58
59Therefore, we load from a single thread, and split the operation up into
60"tasks" (as short as possible). These are typically function calls instead of
61being called directly, they are registered with our queue. We are called from
62the main loop and process as many tasks as possible within one "timeslice".
63
64After that, progress is updated: an estimated duration for each task
65(derived from timings on one machine) is used to calculate headway.
66As long as task lengths only differ by a constant factor between machines,
67this timing is exact; even if not, only smoothness of update suffers.
68
69
70Interrupting Lengthy Tasks
71--------------------------
72
73The above is sufficient for basic needs, but breaks down if tasks are long
74(> 500ms). To fix this, we will need to modify the tasks themselves:
75either make them coroutines, i.e. have them return to the main loop and then
76resume where they left off, or re-enter a limited version of the main loop.
77The former requires persistent state and careful implementation,
78but yields significant advantages:
79- progress calculation is easy and smooth,
80- all services of the main loop (especially input*) are available, and
81- complexity due to reentering the main loop is avoided.
82
83* input is important, since we want to be able to abort long loads or
84even exit the game immediately.
85
86We therefore go with the 'coroutine' (more correctly 'generator') approach.
87Examples of tasks that take so long and typical implementations may
88be seen in MapReader.cpp.
89
90
91Intended Use
92------------
93
94 PS::Loader::BeginRegistering();
95 PS::Loader::Register(..) for each sub-function
96 PS::Loader::EndRegistering();
97Then in the main loop, call PS::Loader::ProgressiveLoad().
98
99*/
100
101
102// NOTE: this module is not thread-safe!
103
104
105// call before starting to register tasks.
106// this routine is provided so we can prevent 2 simultaneous load operations,
107// which is bogus. that can happen by clicking the load button quickly,
108// or issuing via console while already loading.
109void BeginRegistering();
110
111/**
112 * Coroutine which performs the actual work.
113 *
114 * `co_yield ...` can be used to yield the current progress. Iff the timeout is
115 * reached, the coroutine suspends.
116 * `co_await std::suspend_always{}` is usefull to force a suspention. e.g. When
117 * no progress can be made such as when the work is done on a different
118 * thread.
119 * `co_return 0` notifies the loader that the task is fineshed without an
120 * error.
121 * `co_return ...` when the returned value is negative the loader interprets
122 * that as a task failure. `PS::Loader::ProgressiveLoad` will abort
123 * immediately and forward the error code.
124 */
125class Task
126{
127public:
129 {
131 {
132 public:
133 explicit SuspendIf(const bool suspend) :
134 m_Suspend{suspend}
135 {}
136
137 bool await_ready() const noexcept
138 {
139 return !m_Suspend;
140 }
141 void await_suspend(std::coroutine_handle<promise_type>) const noexcept
142 {}
143 void await_resume() const noexcept
144 {}
145
146 private:
148 };
149 public:
151 {
152 return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
153 }
154 std::suspend_always initial_suspend() const noexcept { return {}; }
155 std::suspend_always final_suspend() const noexcept { return {}; }
156 void return_value(const int result) noexcept
157 {
158 m_Result = result;
159 }
160 void unhandled_exception() noexcept
161 {
162 m_Exception = std::current_exception();
163 }
164
165 SuspendIf yield_value(const int progress) noexcept
166 {
167 m_Progress = progress;
168 return SuspendIf{m_StepEnd < timer_Time()};
169 }
170
172 double m_StepEnd;
173 int m_Result{0};
174 std::exception_ptr m_Exception;
175 };
176
177 Task(const Task&) = delete;
178 Task& operator =(const Task&) = delete;
179 Task(Task&& other) noexcept :
180 m_Handle{std::exchange(other.m_Handle, {})}
181 {}
182 Task& operator =(Task&& other) noexcept
183 {
184 m_Handle = std::exchange(other.m_Handle, {});
185 return *this;
186 }
187
189 {
190 if (m_Handle)
191 m_Handle.destroy();
192 }
193
194 [[nodiscard]] double GetProgress() const noexcept
195 {
196 return m_Handle.promise().m_Progress;
197 }
198
199 void Step(const double timeBudget)
200 {
201 m_Handle.promise().m_StepEnd = timeBudget + timer_Time();
202 m_Handle.resume();
203 std::exception_ptr exception{std::exchange(m_Handle.promise().m_Exception, {})};
204 if (exception)
205 std::rethrow_exception(std::move(exception));
206 }
207
208 [[nodiscard]] bool IsDone() const noexcept
209 {
210 return m_Handle.done();
211 }
212
213 [[nodiscard]] int Get() const noexcept
214 {
215 return m_Handle.promise().m_Result;
216 }
217
218private:
219 explicit Task(std::coroutine_handle<promise_type> h) noexcept :
220 m_Handle{std::move(h)}
221 {}
222
223 std::coroutine_handle<promise_type> m_Handle;
224};
225
226using LoadFunc = std::function<PS::Loader::Task()>;
227
228// register a task (later processed in FIFO order).
229// <func>: function that will perform the actual work; see LoadFunc.
230// <description>: user-visible description of the current task, e.g.
231// "Loading Textures".
232// <estimated_duration_ms>: used to calculate progress, and when checking
233// whether there is enough of the time budget left to process this task
234// (reduces timeslice overruns, making the main loop more responsive).
235void Register(LoadFunc func, std::wstring description, int estimated_duration_ms);
236
237
238// call when finished registering tasks; subsequent calls to
239// PS::Loader::ProgressiveLoad will then work off the queued entries.
240void EndRegistering();
241
242
243// immediately cancel this load; no further tasks will be processed.
244// used to abort loading upon user request or failure.
245// note: no special notification will be returned by PS::Loader::ProgressiveLoad.
246void Cancel();
247
249{
250 /**
251 * @c INFO::All_COMPLETE if the final load task just completed.
252 * @c ERR::TIMED_OUT if loading is in progress but didn't finish.
253 * @c 0 if not currently loading (no-op).
254 * Otherwise an error code. the request has been de-queued.
255 */
257
258 /**
259 * An empty string when finished.
260 * Otherwise the description of the next task that will be undertaken.
261 */
262 std::wstring nextDescription;
263
264 /**
265 * The current progress value.
266 */
268};
269/**
270 * Process as many of the queued tasks as possible within @c timeBudget [s].
271 * if a task is lengthy, the budget may be exceeded. call from the main loop.
272 */
273ProgressiveLoadResult ProgressiveLoad(double time_budget);
274
275// immediately process all queued load requests.
276// returns 0 on success or a negative error code.
278
279} // namespace PS::Loader
280
281#endif // #ifndef INCLUDED_LOADER
void await_suspend(std::coroutine_handle< promise_type >) const noexcept
Definition: Loader.h:141
bool await_ready() const noexcept
Definition: Loader.h:137
bool m_Suspend
Definition: Loader.h:147
void await_resume() const noexcept
Definition: Loader.h:143
SuspendIf(const bool suspend)
Definition: Loader.h:133
Definition: Loader.h:129
int m_Progress
Definition: Loader.h:171
std::suspend_always final_suspend() const noexcept
Definition: Loader.h:155
SuspendIf yield_value(const int progress) noexcept
Definition: Loader.h:165
int m_Result
Definition: Loader.h:173
std::suspend_always initial_suspend() const noexcept
Definition: Loader.h:154
void unhandled_exception() noexcept
Definition: Loader.h:160
std::exception_ptr m_Exception
Definition: Loader.h:174
Task get_return_object() noexcept
Definition: Loader.h:150
double m_StepEnd
Definition: Loader.h:172
void return_value(const int result) noexcept
Definition: Loader.h:156
Coroutine which performs the actual work.
Definition: Loader.h:126
double GetProgress() const noexcept
Definition: Loader.h:194
bool IsDone() const noexcept
Definition: Loader.h:208
Task & operator=(const Task &)=delete
void Step(const double timeBudget)
Definition: Loader.h:199
~Task()
Definition: Loader.h:188
Task(const Task &)=delete
std::coroutine_handle< promise_type > m_Handle
Definition: Loader.h:223
Task(Task &&other) noexcept
Definition: Loader.h:179
Task(std::coroutine_handle< promise_type > h) noexcept
Definition: Loader.h:219
int Get() const noexcept
Definition: Loader.h:213
Definition: Loader.cpp:42
void EndRegistering()
Definition: Loader.cpp:128
ProgressiveLoadResult ProgressiveLoad(double time_budget)
Process as many of the queued tasks as possible within timeBudget [s].
Definition: Loader.cpp:177
std::function< PS::Loader::Task()> LoadFunc
Definition: Loader.h:226
void Register(LoadFunc func, std::wstring description, int estimatedDurationMs)
Definition: Loader.cpp:118
void BeginRegistering()
Definition: Loader.cpp:101
Status NonprogressiveLoad()
Definition: Loader.cpp:305
void Cancel()
Definition: Loader.cpp:144
std::int64_t Status
Error handling system.
Definition: status.h:174
Definition: Loader.h:249
int progressPercent
The current progress value.
Definition: Loader.h:267
Status status
INFO::All_COMPLETE if the final load task just completed.
Definition: Loader.h:256
std::wstring nextDescription
An empty string when finished.
Definition: Loader.h:262
double timer_Time()
Definition: timer.cpp:132