Line data Source code
1 : /* Copyright (C) 2026 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 : #include "precompiled.h"
22 :
23 : #include "Loader.h"
24 :
25 : #include "lib/code_annotation.h"
26 : #include "lib/secure_crt.h"
27 : #include "lib/utf8.h"
28 :
29 : #include <deque>
30 : #include <numeric>
31 : #include <optional>
32 : #include <string>
33 : #include <utility>
34 :
35 : #if 0
36 : #define LOADER_LOG(...) debug_printf(__VA_ARGS__)
37 : #else
38 : #define LOADER_LOG(...)
39 : #endif
40 :
41 : namespace PS::Loader
42 : {
43 : namespace
44 : {
45 : // set by PS::Loader::EndRegistering; may be 0 during development when
46 : // estimated task durations haven't yet been set.
47 : double total_estimated_duration;
48 :
49 : // total time spent loading so far, set by PS::Loader::ProgressiveLoad.
50 : // we need a persistent counter so it can be reset after each load.
51 : // this also accumulates less errors than:
52 : // progress += task_estimated / total_estimated.
53 : double estimated_duration_tally;
54 :
55 : // Needed for report of how long each individual task took.
56 : // Only read by LOADER_LOG, which may be compiled out.
57 : [[maybe_unused]] double task_elapsed_time;
58 :
59 : // main purpose is to indicate whether a load is in progress, so that
60 : // PS::Loader::ProgressiveLoad can return 0 iff loading just completed.
61 : // the REGISTERING state allows us to detect 2 simultaneous loads (bogus);
62 : // FIRST_LOAD is used to skip the first timeslice (see PS::Loader::ProgressiveLoad).
63 : enum
64 : {
65 : IDLE,
66 : REGISTERING,
67 : FIRST_LOAD,
68 : LOADING
69 : }
70 : state = IDLE;
71 :
72 :
73 : // holds all state for one load request; stored in queue.
74 : struct LoadRequest
75 : {
76 : // member documentation is in PS::Loader::Register (avoid duplication).
77 :
78 : LoadFunc func;
79 :
80 : // Translatable string shown to the player.
81 : std::wstring description;
82 :
83 : int estimated_duration_ms;
84 :
85 : // PS::Loader::Register gets these as parameters; pack everything together.
86 33 : LoadRequest(LoadFunc func_, std::wstring desc_, int ms_)
87 33 : : func(std::move(func_)), description(std::move(desc_)), estimated_duration_ms(ms_)
88 : {
89 : }
90 : };
91 :
92 : using LoadRequests = std::deque<LoadRequest>;
93 : LoadRequests load_requests;
94 : std::optional<PS::Loader::Task> currentTask;
95 : } // anonymous namespace
96 :
97 : // call before starting to register load requests.
98 : // this routine is provided so we can prevent 2 simultaneous load operations,
99 : // which is bogus. that can happen by clicking the load button quickly,
100 : // or issuing via console while already loading.
101 3 : void BeginRegistering()
102 : {
103 3 : ENSURE(state == IDLE);
104 :
105 3 : state = REGISTERING;
106 3 : load_requests.clear();
107 3 : }
108 :
109 :
110 : // register a task (later processed in FIFO order).
111 : // <func>: function that will perform the actual work; see LoadFunc.
112 : // <param>: (optional) parameter/persistent state.
113 : // <description>: user-visible description of the current task, e.g.
114 : // "Loading Textures".
115 : // <estimated_duration_ms>: used to calculate progress, and when checking
116 : // whether there is enough of the time budget left to process this task
117 : // (reduces timeslice overruns, making the main loop more responsive).
118 33 : void Register(LoadFunc func, std::wstring description, int estimatedDurationMs)
119 : {
120 33 : ENSURE(state == REGISTERING); // must be called between PS::Loader::(Begin|End)Register
121 :
122 99 : load_requests.push_back({std::move(func), std::move(description), estimatedDurationMs});
123 33 : }
124 :
125 :
126 : // call when finished registering tasks; subsequent calls to
127 : // PS::Loader::ProgressiveLoad will then work off the queued entries.
128 3 : void EndRegistering()
129 : {
130 3 : ENSURE(state == REGISTERING);
131 3 : ENSURE(!load_requests.empty());
132 :
133 3 : state = FIRST_LOAD;
134 3 : estimated_duration_tally = 0.0;
135 3 : task_elapsed_time = 0.0;
136 36 : total_estimated_duration = std::accumulate(load_requests.begin(), load_requests.end(), 0.0,
137 33 : [](double partial_result, const LoadRequest& lr) -> double { return partial_result + lr.estimated_duration_ms * 1e-3; });
138 3 : }
139 :
140 :
141 : // immediately cancel this load; no further tasks will be processed.
142 : // used to abort loading upon user request or failure.
143 : // note: no special notification will be returned by PS::Loader::ProgressiveLoad.
144 0 : void Cancel()
145 : {
146 : // the queue doesn't need to be emptied now; that'll happen during the
147 : // next PS::Loader::StartRegistering. for now, it is sufficient to set the
148 : // state, so that PS::Loader::ProgressiveLoad is a no-op.
149 0 : state = IDLE;
150 0 : }
151 :
152 : namespace
153 : {
154 : // helper routine for PS::Loader::ProgressiveLoad.
155 : // tries to prevent starting a long task when at the end of a timeslice.
156 33 : bool HaveTimeForNextTask(double time_left, double time_budget, int estimated_duration_ms)
157 : {
158 : // have already exceeded our time budget
159 33 : if(time_left <= 0.0)
160 : return false;
161 :
162 : // we haven't started a request yet this timeslice. start it even if
163 : // it's longer than time_budget to make sure there is progress.
164 33 : if(time_left == time_budget)
165 : return true;
166 :
167 : // check next task length. we want a lengthy task to happen in its own
168 : // timeslice so that its description is displayed beforehand.
169 30 : const double estimated_duration = estimated_duration_ms*1e-3;
170 30 : if(time_left+estimated_duration > time_budget*1.20)
171 : return false;
172 :
173 : return true;
174 : }
175 : }
176 :
177 6 : ProgressiveLoadResult ProgressiveLoad(double time_budget)
178 : {
179 6 : ProgressiveLoadResult ret;
180 6 : double progress = 0.0; // used to set progress_percent
181 6 : double time_left = time_budget;
182 :
183 : // don't do any work the first time around so that a graphics update
184 : // happens before the first (probably lengthy) timeslice.
185 6 : if(state == FIRST_LOAD)
186 : {
187 3 : state = LOADING;
188 :
189 3 : ret.status = ERR::TIMED_OUT; // make caller think we did something
190 : // progress already set to 0.0; that'll be passed back.
191 3 : goto done;
192 : }
193 :
194 : // we're called unconditionally from the main loop, so this isn't
195 : // an error; there is just nothing to do.
196 3 : if(state != LOADING)
197 0 : return {};
198 :
199 36 : while(!load_requests.empty())
200 : {
201 : // get next task; abort if there's not enough time left for it.
202 33 : const LoadRequest& lr = load_requests.front();
203 33 : const double estimated_duration = lr.estimated_duration_ms*1e-3;
204 33 : if(!HaveTimeForNextTask(time_left, time_budget, lr.estimated_duration_ms))
205 : {
206 0 : ret.status = ERR::TIMED_OUT;
207 0 : goto done;
208 : }
209 :
210 : // call this task's function and bill elapsed time.
211 33 : const double t0 = timer_Time();
212 33 : if (!currentTask.has_value())
213 66 : currentTask.emplace(lr.func());
214 33 : try
215 : {
216 33 : currentTask->Step(time_left);
217 : }
218 0 : catch(...)
219 : {
220 0 : currentTask.reset();
221 0 : throw;
222 0 : }
223 33 : const bool timed_out = !currentTask->IsDone();
224 33 : const double elapsed_time = timer_Time() - t0;
225 33 : time_left -= elapsed_time;
226 33 : task_elapsed_time += elapsed_time;
227 :
228 : // either finished entirely, or failed => remove from queue.
229 33 : if(!timed_out)
230 : {
231 : LOADER_LOG("Loader: completed %s in %g ms; estimate was %g ms\n",
232 : utf8_from_wstring(lr.description).c_str(), task_elapsed_time*1e3,
233 33 : estimated_duration*1e3);
234 33 : task_elapsed_time = 0.0;
235 33 : estimated_duration_tally += estimated_duration;
236 33 : load_requests.pop_front();
237 : }
238 :
239 : // calculate progress (only possible if estimates have been given)
240 33 : if(total_estimated_duration != 0.0)
241 : {
242 33 : double current_estimate = estimated_duration_tally;
243 :
244 : // function interrupted itself; add its estimated progress.
245 : // note: monotonicity is guaranteed since we never add more than
246 : // its estimated_duration_ms.
247 33 : if(timed_out)
248 0 : current_estimate += estimated_duration * currentTask->GetProgress() / 100.0;
249 :
250 33 : progress = current_estimate / total_estimated_duration;
251 : }
252 :
253 : // do we need to continue?
254 : // .. function interrupted itself, i.e. timed out; abort.
255 33 : if(timed_out)
256 : {
257 0 : ret.status = ERR::TIMED_OUT;
258 0 : goto done;
259 : }
260 :
261 66 : const int taskResult{std::exchange(currentTask, std::nullopt)->Get()};
262 : // .. failed; abort. loading will continue when we're called in
263 : // the next iteration of the main loop.
264 : // rationale: bail immediately instead of remembering the first
265 : // error that came up so we can report all errors that happen.
266 33 : if(taskResult < 0)
267 : {
268 0 : ret.status = static_cast<Status>(taskResult);
269 0 : goto done;
270 : }
271 : // .. function called PS::Loader::Cancel; abort. return OK since this is an
272 : // intentional cancellation, not an error.
273 33 : if(state != LOADING)
274 : {
275 0 : ret.status = INFO::OK;
276 0 : goto done;
277 : }
278 : // .. succeeded; continue and process next queued task.
279 : }
280 :
281 : // queue is empty, we just finished.
282 3 : state = IDLE;
283 3 : ret.status = INFO::ALL_COMPLETE;
284 :
285 :
286 : // set output params (there are several return points above)
287 6 : done:
288 6 : ret.progressPercent = static_cast<int>(progress * 100.0);
289 6 : ENSURE(0 <= ret.progressPercent && ret.progressPercent <= 100);
290 :
291 : // we want the next task, instead of what just completed:
292 : // it will be displayed during the next load phase.
293 6 : if(!load_requests.empty())
294 3 : ret.nextDescription = load_requests.front().description;
295 :
296 : LOADER_LOG("Loader: returning; desc=%s progress=%d\n",
297 6 : utf8_from_wstring(ret.nextDescription).c_str(), ret.progressPercent);
298 :
299 6 : return ret;
300 6 : }
301 :
302 :
303 : // immediately process all queued load requests.
304 : // returns 0 on success or a negative error code.
305 3 : Status NonprogressiveLoad()
306 : {
307 3 : const double time_budget = 100.0;
308 : // large enough so that individual functions won't time out
309 : // (that'd waste time).
310 :
311 6 : for(;;)
312 : {
313 6 : const auto [ret, description, progress_percent] = ProgressiveLoad(time_budget);
314 6 : switch(ret)
315 : {
316 0 : case INFO::OK:
317 0 : debug_warn(L"No load in progress");
318 : return INFO::OK;
319 : case INFO::ALL_COMPLETE:
320 : return INFO::OK;
321 : case ERR::TIMED_OUT:
322 : break; // continue loading
323 0 : default:
324 3 : WARN_RETURN_STATUS_IF_ERR(ret); // failed; complain
325 : }
326 6 : }
327 : }
328 : } // namespace PS::Loader
|