Line data Source code
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 : 34 : namespace PS::Loader 35 : { 36 : /* 37 : 38 : [KEEP IN SYNC WITH WIKI!] 39 : 40 : Overview 41 : -------- 42 : 43 : "Loading" is the act of preparing a game session, including reading all 44 : required data from disk. Ideally, this would be very quick, but for complex 45 : maps and/or low-end machines, a duration of several seconds can be expected. 46 : Having the game freeze that long is unacceptable; instead, we want to display 47 : the current progress and task, which greatly increases user patience. 48 : 49 : 50 : Allowing for Display 51 : -------------------- 52 : 53 : To display progress, we need to periodically 'interrupt' loading. 54 : Threads come to mind, but there is a problem: since OpenGL graphics calls 55 : must come from the main thread, loading would have to happen in a 56 : background thread. Everything would thus need to be made thread-safe, 57 : which is a considerable complication. 58 : 59 : Therefore, 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 61 : being called directly, they are registered with our queue. We are called from 62 : the main loop and process as many tasks as possible within one "timeslice". 63 : 64 : After that, progress is updated: an estimated duration for each task 65 : (derived from timings on one machine) is used to calculate headway. 66 : As long as task lengths only differ by a constant factor between machines, 67 : this timing is exact; even if not, only smoothness of update suffers. 68 : 69 : 70 : Interrupting Lengthy Tasks 71 : -------------------------- 72 : 73 : The 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: 75 : either make them coroutines, i.e. have them return to the main loop and then 76 : resume where they left off, or re-enter a limited version of the main loop. 77 : The former requires persistent state and careful implementation, 78 : but 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 84 : even exit the game immediately. 85 : 86 : We therefore go with the 'coroutine' (more correctly 'generator') approach. 87 : Examples of tasks that take so long and typical implementations may 88 : be seen in MapReader.cpp. 89 : 90 : 91 : Intended Use 92 : ------------ 93 : 94 : PS::Loader::BeginRegistering(); 95 : PS::Loader::Register(..) for each sub-function 96 : PS::Loader::EndRegistering(); 97 : Then 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. 109 : void 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 : */ 125 : class Task 126 : { 127 : public: 128 36 : class promise_type 129 : { 130 : class SuspendIf 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: 147 : bool m_Suspend; 148 : }; 149 : public: 150 36 : Task get_return_object() noexcept 151 : { 152 36 : 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 0 : void unhandled_exception() noexcept 161 : { 162 0 : m_Exception = std::current_exception(); 163 0 : } 164 : 165 : SuspendIf yield_value(const int progress) noexcept 166 : { 167 : m_Progress = progress; 168 : return SuspendIf{m_StepEnd < timer_Time()}; 169 : } 170 : 171 : int m_Progress{0}; 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 66 : Task(Task&& other) noexcept : 180 66 : 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 : 188 102 : ~Task() 189 : { 190 102 : if (m_Handle) 191 69 : m_Handle.destroy(); 192 69 : } 193 : 194 8 : [[nodiscard]] double GetProgress() const noexcept 195 : { 196 8 : return m_Handle.promise().m_Progress; 197 : } 198 : 199 38 : void Step(const double timeBudget) 200 : { 201 38 : m_Handle.promise().m_StepEnd = timeBudget + timer_Time(); 202 38 : m_Handle.resume(); 203 38 : std::exception_ptr exception{std::exchange(m_Handle.promise().m_Exception, {})}; 204 38 : if (exception) 205 0 : std::rethrow_exception(std::move(exception)); 206 38 : } 207 : 208 33 : [[nodiscard]] bool IsDone() const noexcept 209 : { 210 41 : return m_Handle.done(); 211 : } 212 : 213 33 : [[nodiscard]] int Get() const noexcept 214 : { 215 33 : return m_Handle.promise().m_Result; 216 : } 217 : 218 : private: 219 36 : explicit Task(std::coroutine_handle<promise_type> h) noexcept : 220 36 : m_Handle{std::move(h)} 221 : {} 222 : 223 : std::coroutine_handle<promise_type> m_Handle; 224 : }; 225 : 226 : using 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). 235 : void 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. 240 : void 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. 246 : void Cancel(); 247 : 248 21 : struct ProgressiveLoadResult 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 : */ 256 : Status status{0}; 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 : */ 267 : int progressPercent; 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 : */ 273 : ProgressiveLoadResult ProgressiveLoad(double time_budget); 274 : 275 : // immediately process all queued load requests. 276 : // returns 0 on success or a negative error code. 277 : Status NonprogressiveLoad(); 278 : 279 : } // namespace PS::Loader 280 : 281 : #endif // #ifndef INCLUDED_LOADER